diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index ee46bdcf7d8bb..dc2a8be5b3cf1 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -1379,7 +1379,9 @@ impl<'a> Visitor<'a> for AstValidator<'a> { this.dcx() .emit_err(errors::ScalableVectorNotTupleStruct { span: item.span }); } - if !self.sess.target.arch.supports_scalable_vectors() { + if !self.sess.target.arch.supports_scalable_vectors() + && !self.sess.opts.actually_rustdoc + { this.dcx().emit_err(errors::ScalableVectorBadArch { span: attr.span }); } } diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index ccc4a1a64c56f..8d000ebe9236c 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -19,6 +19,7 @@ use rustc_session::parse::{ParseSess, feature_err}; use rustc_span::{ErrorGuaranteed, Span, Symbol, sym}; use thin_vec::ThinVec; +use crate::attributes::AttributeSafety; use crate::context::{AcceptContext, ShouldEmit, Stage}; use crate::parser::{ AllowExprMetavar, ArgParser, MetaItemListParser, MetaItemOrLitParser, NameValueParser, @@ -408,6 +409,7 @@ fn parse_cfg_attr_internal<'a>( attribute.style, AttrPath { segments: attribute.path().into_boxed_slice(), span: attribute.span }, Some(attribute.get_normal_item().unsafety), + AttributeSafety::Normal, ParsedDescription::Attribute, pred_span, CRATE_NODE_ID, diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs b/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs index 4ff224006ca89..918fd0a4582b7 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs @@ -12,6 +12,7 @@ use rustc_session::Session; use rustc_session::lint::builtin::UNREACHABLE_CFG_SELECT_PREDICATES; use rustc_span::{ErrorGuaranteed, Span, Symbol, sym}; +use crate::attributes::AttributeSafety; use crate::parser::{AllowExprMetavar, MetaItemOrLitParser}; use crate::{AttributeParser, ParsedDescription, ShouldEmit, errors, parse_cfg_entry}; @@ -105,6 +106,7 @@ pub fn parse_cfg_select( AttrStyle::Inner, AttrPath { segments: vec![sym::cfg_select].into_boxed_slice(), span: cfg_span }, None, + AttributeSafety::Normal, ParsedDescription::Macro, cfg_span, lint_node_id, diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index 93664aff49157..1c49d9808d8ed 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -1,7 +1,9 @@ use rustc_hir::attrs::{CoverageAttrKind, OptimizeAttr, RtsanSetting, SanitizerSet, UsedBy}; use rustc_session::parse::feature_err; +use rustc_span::edition::Edition::Edition2024; use super::prelude::*; +use crate::attributes::AttributeSafety; use crate::session_diagnostics::{ NakedFunctionIncompatibleAttribute, NullOnExport, NullOnObjcClass, NullOnObjcSelector, ObjcClassExpectedStringLiteral, ObjcSelectorExpectedStringLiteral, @@ -121,6 +123,7 @@ pub(crate) struct ExportNameParser; impl SingleAttributeParser for ExportNameParser { const PATH: &[rustc_span::Symbol] = &[sym::export_name]; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; + const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: Some(Edition2024) }; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[ Allow(Target::Static), Allow(Target::Fn), @@ -238,6 +241,7 @@ impl AttributeParser for NakedParser { this.span = Some(cx.attr_span); } })]; + const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None }; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[ Allow(Target::Fn), Allow(Target::Method(MethodKind::Inherent)), @@ -363,6 +367,7 @@ pub(crate) struct NoMangleParser; impl NoArgsAttributeParser for NoMangleParser { const PATH: &[Symbol] = &[sym::no_mangle]; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; + const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: Some(Edition2024) }; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[ Allow(Target::Fn), Allow(Target::Static), @@ -565,6 +570,7 @@ pub(crate) struct ForceTargetFeatureParser; impl CombineAttributeParser for ForceTargetFeatureParser { type Item = (Symbol, Span); const PATH: &[Symbol] = &[sym::force_target_feature]; + const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None }; const CONVERT: ConvertFn = |items, span| AttributeKind::TargetFeature { features: items, attr_span: span, diff --git a/compiler/rustc_attr_parsing/src/attributes/doc.rs b/compiler/rustc_attr_parsing/src/attributes/doc.rs index a569483ea7c39..99f856684abd5 100644 --- a/compiler/rustc_attr_parsing/src/attributes/doc.rs +++ b/compiler/rustc_attr_parsing/src/attributes/doc.rs @@ -665,7 +665,11 @@ impl DocParser { let span = cx.attr_span; cx.emit_lint( rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES, - AttributeLintKind::IllFormedAttributeInput { suggestions, docs: None }, + AttributeLintKind::IllFormedAttributeInput { + suggestions, + docs: None, + help: None, + }, span, ); } diff --git a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs index e1ae2068f9fd3..c70c9a0d7db53 100644 --- a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs @@ -5,11 +5,13 @@ use rustc_hir::attrs::*; use rustc_session::Session; use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT; use rustc_session::parse::feature_err; +use rustc_span::edition::Edition::Edition2024; use rustc_span::kw; use rustc_target::spec::{Arch, BinaryFormat}; use super::prelude::*; use super::util::parse_single_integer; +use crate::attributes::AttributeSafety; use crate::attributes::cfg::parse_cfg_entry; use crate::session_diagnostics::{ AsNeededCompatibility, BundleNeedsStatic, EmptyLinkName, ExportSymbolsNeedsStatic, @@ -468,6 +470,7 @@ pub(crate) struct LinkSectionParser; impl SingleAttributeParser for LinkSectionParser { const PATH: &[Symbol] = &[sym::link_section]; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; + const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: Some(Edition2024) }; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[ Allow(Target::Static), Allow(Target::Fn), @@ -513,6 +516,7 @@ pub(crate) struct FfiConstParser; impl NoArgsAttributeParser for FfiConstParser { const PATH: &[Symbol] = &[sym::ffi_const]; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; + const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None }; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::ForeignFn)]); const CREATE: fn(Span) -> AttributeKind = AttributeKind::FfiConst; } @@ -521,6 +525,7 @@ pub(crate) struct FfiPureParser; impl NoArgsAttributeParser for FfiPureParser { const PATH: &[Symbol] = &[sym::ffi_pure]; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; + const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None }; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::ForeignFn)]); const CREATE: fn(Span) -> AttributeKind = AttributeKind::FfiPure; } diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index 66f452040954b..1e9292f67f7b6 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -18,6 +18,7 @@ use std::marker::PhantomData; use rustc_feature::{AttributeTemplate, template}; use rustc_hir::attrs::AttributeKind; +use rustc_span::edition::Edition; use rustc_span::{Span, Symbol}; use thin_vec::ThinVec; @@ -98,6 +99,7 @@ pub(crate) trait AttributeParser: Default + 'static { /// If an attribute has this symbol, the `accept` function will be called on it. const ATTRIBUTES: AcceptMapping; const ALLOWED_TARGETS: AllowedTargets; + const SAFETY: AttributeSafety = AttributeSafety::Normal; /// The parser has gotten a chance to accept the attributes on an item, /// here it can produce an attribute. @@ -128,6 +130,7 @@ pub(crate) trait SingleAttributeParser: 'static { /// Configures what to do when when the same attribute is /// applied more than once on the same syntax node. const ON_DUPLICATE: OnDuplicate; + const SAFETY: AttributeSafety = AttributeSafety::Normal; const ALLOWED_TARGETS: AllowedTargets; @@ -166,6 +169,7 @@ impl, S: Stage> AttributeParser for Single }, )]; const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS; + const SAFETY: AttributeSafety = T::SAFETY; fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option { Some(self.1?.0) @@ -218,6 +222,18 @@ impl OnDuplicate { } } +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum AttributeSafety { + /// Normal attribute that does not need `#[unsafe(...)]` + Normal, + /// Unsafe attribute that requires safety obligations to be discharged. + /// + /// An error is emitted when `#[unsafe(...)]` is omitted, except when the attribute's edition + /// is less than the one stored in `unsafe_since`. This handles attributes that were safe in + /// earlier editions, but become unsafe in later ones. + Unsafe { unsafe_since: Option }, +} + /// An even simpler version of [`SingleAttributeParser`]: /// now automatically check that there are no arguments provided to the attribute. /// @@ -227,6 +243,7 @@ pub(crate) trait NoArgsAttributeParser: 'static { const PATH: &[Symbol]; const ON_DUPLICATE: OnDuplicate; const ALLOWED_TARGETS: AllowedTargets; + const SAFETY: AttributeSafety = AttributeSafety::Normal; /// Create the [`AttributeKind`] given attribute's [`Span`]. const CREATE: fn(Span) -> AttributeKind; @@ -243,6 +260,7 @@ impl, S: Stage> Default for WithoutArgs { impl, S: Stage> SingleAttributeParser for WithoutArgs { const PATH: &[Symbol] = T::PATH; const ON_DUPLICATE: OnDuplicate = T::ON_DUPLICATE; + const SAFETY: AttributeSafety = T::SAFETY; const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS; const TEMPLATE: AttributeTemplate = template!(Word); @@ -272,6 +290,7 @@ pub(crate) trait CombineAttributeParser: 'static { /// For example, individual representations from `#[repr(...)]` attributes into an `AttributeKind::Repr(x)`, /// where `x` is a vec of these individual reprs. const CONVERT: ConvertFn; + const SAFETY: AttributeSafety = AttributeSafety::Normal; const ALLOWED_TARGETS: AllowedTargets; @@ -313,6 +332,7 @@ impl, S: Stage> AttributeParser for Combine) -> Option { if let Some(first_span) = self.first_span { diff --git a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs index e8d2bedc37802..1f50d84869f49 100644 --- a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs @@ -27,8 +27,15 @@ impl SingleAttributeParser for IgnoreParser { }; Some(str_value) } - ArgParser::List(_) => { - cx.adcx().warn_ill_formed_attribute_input(ILL_FORMED_ATTRIBUTE_INPUT); + ArgParser::List(list) => { + let help = list.single().and_then(|item| item.meta_item()).and_then(|item| { + item.args().no_args().ok()?; + Some(item.path().to_string()) + }); + cx.adcx().warn_ill_formed_attribute_input_with_help( + ILL_FORMED_ATTRIBUTE_INPUT, + help, + ); return None; } }, diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 74eb1222078d0..407a3759b6977 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -59,7 +59,7 @@ use crate::attributes::stability::*; use crate::attributes::test_attrs::*; use crate::attributes::traits::*; use crate::attributes::transparency::*; -use crate::attributes::{AttributeParser as _, Combine, Single, WithoutArgs}; +use crate::attributes::{AttributeParser as _, AttributeSafety, Combine, Single, WithoutArgs}; use crate::parser::{ArgParser, RefPathParser}; use crate::session_diagnostics::{ AttributeParseError, AttributeParseErrorReason, AttributeParseErrorSuggestions, @@ -76,6 +76,7 @@ pub(super) struct GroupTypeInnerAccept { pub(super) template: AttributeTemplate, pub(super) accept_fn: AcceptFn, pub(super) allowed_targets: AllowedTargets, + pub(super) safety: AttributeSafety, pub(super) finalizer: FinalizeFn, } @@ -126,6 +127,7 @@ macro_rules! attribute_parsers { accept_fn(s, cx, args) }) }), + safety: <$names as crate::attributes::AttributeParser<$stage>>::SAFETY, allowed_targets: <$names as crate::attributes::AttributeParser<$stage>>::ALLOWED_TARGETS, finalizer: Box::new(|cx| { let state = STATE_OBJECT.take(); @@ -830,11 +832,18 @@ where } pub(crate) fn warn_ill_formed_attribute_input(&mut self, lint: &'static Lint) { + self.warn_ill_formed_attribute_input_with_help(lint, None) + } + pub(crate) fn warn_ill_formed_attribute_input_with_help( + &mut self, + lint: &'static Lint, + help: Option, + ) { let suggestions = self.suggestions(); let span = self.attr_span; self.emit_lint( lint, - AttributeLintKind::IllFormedAttributeInput { suggestions, docs: None }, + AttributeLintKind::IllFormedAttributeInput { suggestions, docs: None, help }, span, ); } diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index e9d868039380b..a0fae010e0552 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -13,6 +13,7 @@ use rustc_session::Session; use rustc_session::lint::{BuiltinLintDiag, LintId}; use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym}; +use crate::attributes::AttributeSafety; use crate::context::{AcceptContext, FinalizeContext, FinalizeFn, SharedContext, Stage}; use crate::early_parsed::{EARLY_PARSED_ATTRIBUTES, EarlyParsedState}; use crate::parser::{AllowExprMetavar, ArgParser, PathParser, RefPathParser}; @@ -172,6 +173,7 @@ impl<'sess> AttributeParser<'sess, Early> { parse_fn: fn(cx: &mut AcceptContext<'_, '_, Early>, item: &ArgParser) -> Option, template: &AttributeTemplate, allow_expr_metavar: AllowExprMetavar, + expected_safety: AttributeSafety, ) -> Option { let ast::AttrKind::Normal(normal_attr) = &attr.kind else { panic!("parse_single called on a doc attr") @@ -194,6 +196,7 @@ impl<'sess> AttributeParser<'sess, Early> { attr.style, path, Some(normal_attr.item.unsafety), + expected_safety, ParsedDescription::Attribute, target_span, target_node_id, @@ -215,6 +218,7 @@ impl<'sess> AttributeParser<'sess, Early> { attr_style: AttrStyle, attr_path: AttrPath, attr_safety: Option, + expected_safety: AttributeSafety, parsed_description: ParsedDescription, target_span: Span, target_node_id: NodeId, @@ -236,7 +240,13 @@ impl<'sess> AttributeParser<'sess, Early> { ) }; if let Some(safety) = attr_safety { - parser.check_attribute_safety(&attr_path, inner_span, safety, &mut emit_lint) + parser.check_attribute_safety( + &attr_path, + inner_span, + safety, + expected_safety, + &mut emit_lint, + ) } let attr_id = sess.psess.attr_id_generator.mk_attr_id(); let mut cx: AcceptContext<'_, 'sess, Early> = AcceptContext { @@ -353,17 +363,18 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { } }; - self.check_attribute_safety( - &attr_path, - lower_span(n.item.span()), - n.item.unsafety, - &mut emit_lint, - ); - let parts = n.item.path.segments.iter().map(|seg| seg.ident.name).collect::>(); if let Some(accept) = S::parsers().accepters.get(parts.as_slice()) { + self.check_attribute_safety( + &attr_path, + lower_span(n.item.span()), + n.item.unsafety, + accept.safety, + &mut emit_lint, + ); + let Some(args) = ArgParser::from_attr_args( args, &parts, @@ -437,6 +448,14 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { span: attr_span, }; + self.check_attribute_safety( + &attr_path, + lower_span(n.item.span()), + n.item.unsafety, + AttributeSafety::Normal, + &mut emit_lint, + ); + if !matches!(self.stage.should_emit(), ShouldEmit::Nothing) && target == Target::Crate { diff --git a/compiler/rustc_attr_parsing/src/lib.rs b/compiler/rustc_attr_parsing/src/lib.rs index 93eb5a0c3ab73..1b08ed3c49b78 100644 --- a/compiler/rustc_attr_parsing/src/lib.rs +++ b/compiler/rustc_attr_parsing/src/lib.rs @@ -106,6 +106,7 @@ mod session_diagnostics; mod target_checking; pub mod validate_attr; +pub use attributes::AttributeSafety; pub use attributes::cfg::{ CFG_TEMPLATE, EvalConfigResult, eval_config_entry, parse_cfg, parse_cfg_attr, parse_cfg_entry, }; diff --git a/compiler/rustc_attr_parsing/src/safety.rs b/compiler/rustc_attr_parsing/src/safety.rs index 4cc703c5d0cc4..f560598cb80bf 100644 --- a/compiler/rustc_attr_parsing/src/safety.rs +++ b/compiler/rustc_attr_parsing/src/safety.rs @@ -1,11 +1,11 @@ use rustc_ast::Safety; -use rustc_feature::{AttributeSafety, BUILTIN_ATTRIBUTE_MAP}; use rustc_hir::AttrPath; use rustc_hir::lints::AttributeLintKind; use rustc_session::lint::LintId; use rustc_session::lint::builtin::UNSAFE_ATTR_OUTSIDE_UNSAFE; use rustc_span::Span; +use crate::attributes::AttributeSafety; use crate::context::Stage; use crate::{AttributeParser, ShouldEmit}; @@ -15,28 +15,23 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { attr_path: &AttrPath, attr_span: Span, attr_safety: Safety, + expected_safety: AttributeSafety, emit_lint: &mut impl FnMut(LintId, Span, AttributeLintKind), ) { if matches!(self.stage.should_emit(), ShouldEmit::Nothing) { return; } - let name = (attr_path.segments.len() == 1).then_some(attr_path.segments[0]); - - // FIXME: We should retrieve this information from the attribute parsers instead of from `BUILTIN_ATTRIBUTE_MAP` - let builtin_attr_info = name.and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name)); - let builtin_attr_safety = builtin_attr_info.map(|x| x.safety); - - match (builtin_attr_safety, attr_safety) { + match (expected_safety, attr_safety) { // - Unsafe builtin attribute // - User wrote `#[unsafe(..)]`, which is permitted on any edition - (Some(AttributeSafety::Unsafe { .. }), Safety::Unsafe(..)) => { + (AttributeSafety::Unsafe { .. }, Safety::Unsafe(..)) => { // OK } // - Unsafe builtin attribute // - User did not write `#[unsafe(..)]` - (Some(AttributeSafety::Unsafe { unsafe_since }), Safety::Default) => { + (AttributeSafety::Unsafe { unsafe_since }, Safety::Default) => { let path_span = attr_path.span; // If the `attr_item`'s span is not from a macro, then just suggest @@ -95,7 +90,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { // - Normal builtin attribute // - Writing `#[unsafe(..)]` is not permitted on normal builtin attributes - (None | Some(AttributeSafety::Normal), Safety::Unsafe(unsafe_span)) => { + (AttributeSafety::Normal, Safety::Unsafe(unsafe_span)) => { self.stage.emit_err( self.sess, crate::session_diagnostics::InvalidAttrUnsafe { @@ -107,14 +102,11 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { // - Normal builtin attribute // - No explicit `#[unsafe(..)]` written. - (None | Some(AttributeSafety::Normal), Safety::Default) => { + (AttributeSafety::Normal, Safety::Default) => { // OK } - ( - Some(AttributeSafety::Unsafe { .. } | AttributeSafety::Normal) | None, - Safety::Safe(..), - ) => { + (_, Safety::Safe(..)) => { self.sess.dcx().span_delayed_bug( attr_span, "`check_attribute_safety` does not expect `Safety::Safe` on attributes", diff --git a/compiler/rustc_attr_parsing/src/validate_attr.rs b/compiler/rustc_attr_parsing/src/validate_attr.rs index f56e85b110610..f047c19a150b9 100644 --- a/compiler/rustc_attr_parsing/src/validate_attr.rs +++ b/compiler/rustc_attr_parsing/src/validate_attr.rs @@ -1,15 +1,14 @@ //! Meta-syntax validation logic of attributes for post-expansion. use std::convert::identity; -use std::slice; use rustc_ast::token::Delimiter; use rustc_ast::tokenstream::DelimSpan; use rustc_ast::{ self as ast, AttrArgs, Attribute, DelimArgs, MetaItem, MetaItemInner, MetaItemKind, Safety, }; -use rustc_errors::{Applicability, FatalError, PResult}; -use rustc_feature::{AttributeTemplate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute}; +use rustc_errors::{Applicability, PResult}; +use rustc_feature::{AttributeTemplate, BUILTIN_ATTRIBUTE_MAP}; use rustc_hir::AttrPath; use rustc_hir::lints::AttributeLintKind; use rustc_parse::parse_in; @@ -19,43 +18,23 @@ use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT; use rustc_session::parse::ParseSess; use rustc_span::{Span, Symbol, sym}; -use crate::{AttributeParser, Late, session_diagnostics as errors}; +use crate::session_diagnostics as errors; pub fn check_attr(psess: &ParseSess, attr: &Attribute) { - if attr.is_doc_comment() || attr.has_name(sym::cfg_trace) || attr.has_name(sym::cfg_attr_trace) + // Built-in attributes are parsed in their respective attribute parsers, so can be ignored here + if attr.is_doc_comment() + || attr.name().is_some_and(|name| BUILTIN_ATTRIBUTE_MAP.contains_key(&name)) { return; } - let builtin_attr_info = attr.name().and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name)); - - // Check input tokens for built-in and key-value attributes. - match builtin_attr_info { - // `rustc_dummy` doesn't have any restrictions specific to built-in attributes. - Some(BuiltinAttribute { name, template, .. }) => { - if AttributeParser::::is_parsed_attribute(slice::from_ref(&name)) { - return; - } - match parse_meta(psess, attr) { - // Don't check safety again, we just did that - Ok(meta) => { - check_builtin_meta_item(psess, &meta, attr.style, *name, *template, false) - } - Err(err) => { - err.emit(); - } - } - } - _ => { - let attr_item = attr.get_normal_item(); - if let AttrArgs::Eq { .. } = attr_item.args.unparsed_ref().unwrap() { - // All key-value attributes are restricted to meta-item syntax. - match parse_meta(psess, attr) { - Ok(_) => {} - Err(err) => { - err.emit(); - } - } + let attr_item = attr.get_normal_item(); + if let AttrArgs::Eq { .. } = attr_item.args.unparsed_ref().unwrap() { + // All key-value attributes are restricted to meta-item syntax. + match parse_meta(psess, attr) { + Ok(_) => {} + Err(err) => { + err.emit(); } } } @@ -170,7 +149,7 @@ pub fn check_builtin_meta_item( } } -fn emit_malformed_attribute( +pub fn emit_malformed_attribute( psess: &ParseSess, style: ast::AttrStyle, span: Span, @@ -211,6 +190,7 @@ fn emit_malformed_attribute( BuiltinLintDiag::AttributeLint(AttributeLintKind::IllFormedAttributeInput { suggestions: suggestions.clone(), docs: template.docs, + help: None, }), ); } else { @@ -231,15 +211,3 @@ fn emit_malformed_attribute( err.emit(); } } - -pub fn emit_fatal_malformed_builtin_attribute( - psess: &ParseSess, - attr: &Attribute, - name: Symbol, -) -> ! { - let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template; - emit_malformed_attribute(psess, attr.style, attr.span, name, template); - // This is fatal, otherwise it will likely cause a cascade of other errors - // (and an error here is expected to be very rare). - FatalError.raise() -} diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index cddb37c7d816f..94c3a48b1c1e3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -914,12 +914,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { if show_assign_sugg { struct LetVisitor { decl_span: Span, - sugg_span: Option, + sugg: Option<(Span, bool)>, } impl<'v> Visitor<'v> for LetVisitor { fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) { - if self.sugg_span.is_some() { + if self.sugg.is_some() { return; } @@ -927,19 +927,23 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // but we could suggest `todo!()` for all uninitialized bindings in the pattern if let hir::StmtKind::Let(hir::LetStmt { span, ty, init: None, pat, .. }) = &ex.kind - && let hir::PatKind::Binding(..) = pat.kind + && let hir::PatKind::Binding(binding_mode, ..) = pat.kind && span.contains(self.decl_span) { - self.sugg_span = ty.map_or(Some(self.decl_span), |ty| Some(ty.span)); + // Insert after the whole binding pattern so suggestions stay valid for + // bindings with `@` subpatterns like `ref mut x @ v`. + let strip_ref = matches!(binding_mode.0, hir::ByRef::Yes(..)); + self.sugg = + ty.map_or(Some((pat.span, strip_ref)), |ty| Some((ty.span, strip_ref))); } hir::intravisit::walk_stmt(self, ex); } } - let mut visitor = LetVisitor { decl_span, sugg_span: None }; + let mut visitor = LetVisitor { decl_span, sugg: None }; visitor.visit_body(&body); - if let Some(span) = visitor.sugg_span { - self.suggest_assign_value(&mut err, moved_place, span); + if let Some((span, strip_ref)) = visitor.sugg { + self.suggest_assign_value(&mut err, moved_place, span, strip_ref); } } err @@ -950,8 +954,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { err: &mut Diag<'_>, moved_place: PlaceRef<'tcx>, sugg_span: Span, + strip_ref: bool, ) { - let ty = moved_place.ty(self.body, self.infcx.tcx).ty; + let mut ty = moved_place.ty(self.body, self.infcx.tcx).ty; + if strip_ref && let ty::Ref(_, inner, _) = ty.kind() { + ty = *inner; + } debug!("ty: {:?}, kind: {:?}", ty, ty.kind()); let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.infcx.param_env, ty) diff --git a/compiler/rustc_builtin_macros/src/cfg.rs b/compiler/rustc_builtin_macros/src/cfg.rs index c4a458089f2d2..2872cff0fdc7a 100644 --- a/compiler/rustc_builtin_macros/src/cfg.rs +++ b/compiler/rustc_builtin_macros/src/cfg.rs @@ -6,7 +6,8 @@ use rustc_ast::tokenstream::TokenStream; use rustc_ast::{AttrStyle, token}; use rustc_attr_parsing::parser::{AllowExprMetavar, MetaItemOrLitParser}; use rustc_attr_parsing::{ - self as attr, AttributeParser, CFG_TEMPLATE, ParsedDescription, ShouldEmit, parse_cfg_entry, + self as attr, AttributeParser, AttributeSafety, CFG_TEMPLATE, ParsedDescription, ShouldEmit, + parse_cfg_entry, }; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_hir::attrs::CfgEntry; @@ -53,6 +54,7 @@ fn parse_cfg(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream) -> Result, -) -> LtoData { +fn prepare_lto(each_linked_rlib_for_lto: &[PathBuf], dcx: DiagCtxtHandle<'_>) -> LtoData { let tmp_path = match tempdir() { Ok(tmp_path) => tmp_path, Err(error) => { @@ -64,32 +59,30 @@ fn prepare_lto( // We save off all the bytecode and GCC module file path for later processing // with either fat or thin LTO let mut upstream_modules = Vec::new(); - if cgcx.lto != Lto::ThinLocal { - for path in each_linked_rlib_for_lto { - let archive_data = unsafe { - Mmap::map(File::open(path).expect("couldn't open rlib")).expect("couldn't map rlib") - }; - let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib"); - let obj_files = archive - .members() - .filter_map(|child| { - child.ok().and_then(|c| { - std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c)) - }) - }) - .filter(|&(name, _)| looks_like_rust_object_file(name)); - for (name, child) in obj_files { - info!("adding bitcode from {}", name); - let path = tmp_path.path().join(name); - match save_as_file(child.data(&*archive_data).expect("corrupt rlib"), &path) { - Ok(()) => { - let buffer = ModuleBuffer::new(path); - let module = SerializedModule::Local(buffer); - upstream_modules.push((module, CString::new(name).unwrap())); - } - Err(e) => { - dcx.emit_fatal(e); - } + for path in each_linked_rlib_for_lto { + let archive_data = unsafe { + Mmap::map(File::open(path).expect("couldn't open rlib")).expect("couldn't map rlib") + }; + let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib"); + let obj_files = archive + .members() + .filter_map(|child| { + child + .ok() + .and_then(|c| std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))) + }) + .filter(|&(name, _)| looks_like_rust_object_file(name)); + for (name, child) in obj_files { + info!("adding bitcode from {}", name); + let path = tmp_path.path().join(name); + match save_as_file(child.data(&*archive_data).expect("corrupt rlib"), &path) { + Ok(()) => { + let buffer = ModuleBuffer::new(path); + let module = SerializedModule::Local(buffer); + upstream_modules.push((module, CString::new(name).unwrap())); + } + Err(e) => { + dcx.emit_fatal(e); } } } @@ -115,7 +108,7 @@ pub(crate) fn run_fat( ) -> CompiledModule { let dcx = DiagCtxt::new(Box::new(shared_emitter.clone())); let dcx = dcx.handle(); - let lto_data = prepare_lto(cgcx, each_linked_rlib_for_lto, dcx); + let lto_data = prepare_lto(each_linked_rlib_for_lto, dcx); /*let symbols_below_threshold = lto_data.symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::>();*/ fat_lto( diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index bf13f0b2127b7..d50968bad2501 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -81,9 +81,9 @@ use gccjit::{CType, Context, OptimizationLevel}; #[cfg(feature = "master")] use gccjit::{TargetInfo, Version}; use rustc_ast::expand::allocator::AllocatorMethod; -use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule}; +use rustc_codegen_ssa::back::lto::ThinModule; use rustc_codegen_ssa::back::write::{ - CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryFn, + CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryFn, ThinLtoInput, }; use rustc_codegen_ssa::base::codegen_crate; use rustc_codegen_ssa::target_features::cfg_target_feature; @@ -449,8 +449,7 @@ impl WriteBackendMethods for GccCodegenBackend { // FIXME(bjorn3): Limit LTO exports to these symbols _exported_symbols_for_lto: &[String], _each_linked_rlib_for_lto: &[PathBuf], - _modules: Vec<(String, Self::ModuleBuffer)>, - _cached_modules: Vec<(SerializedModule, WorkProduct)>, + _modules: Vec>, ) -> (Vec>, Vec) { unreachable!() } diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index f6cd229cb106d..09863961c9d69 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -9,7 +9,7 @@ use object::read::archive::ArchiveFile; use object::{Object, ObjectSection}; use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared}; use rustc_codegen_ssa::back::write::{ - CodegenContext, FatLtoInput, SharedEmitter, TargetMachineFactoryFn, + CodegenContext, FatLtoInput, SharedEmitter, TargetMachineFactoryFn, ThinLtoInput, }; use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind, looks_like_rust_object_file}; @@ -20,7 +20,7 @@ use rustc_errors::{DiagCtxt, DiagCtxtHandle}; use rustc_hir::attrs::SanitizerSet; use rustc_middle::bug; use rustc_middle::dep_graph::WorkProduct; -use rustc_session::config::{self, Lto}; +use rustc_session::config; use tracing::{debug, info}; use crate::back::write::{ @@ -90,33 +90,31 @@ fn prepare_lto( // We save off all the bytecode and LLVM module ids for later processing // with either fat or thin LTO let mut upstream_modules = Vec::new(); - if cgcx.lto != Lto::ThinLocal { - for path in each_linked_rlib_for_lto { - let archive_data = unsafe { - Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib")) - .expect("couldn't map rlib") - }; - let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib"); - let obj_files = archive - .members() - .filter_map(|child| { - child.ok().and_then(|c| { - std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c)) - }) - }) - .filter(|&(name, _)| looks_like_rust_object_file(name)); - for (name, child) in obj_files { - info!("adding bitcode from {}", name); - match get_bitcode_slice_from_object_data( - child.data(&*archive_data).expect("corrupt rlib"), - cgcx, - ) { - Ok(data) => { - let module = SerializedModule::FromRlib(data.to_vec()); - upstream_modules.push((module, CString::new(name).unwrap())); - } - Err(e) => dcx.emit_fatal(e), + for path in each_linked_rlib_for_lto { + let archive_data = unsafe { + Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib")) + .expect("couldn't map rlib") + }; + let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib"); + let obj_files = archive + .members() + .filter_map(|child| { + child + .ok() + .and_then(|c| std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))) + }) + .filter(|&(name, _)| looks_like_rust_object_file(name)); + for (name, child) in obj_files { + info!("adding bitcode from {}", name); + match get_bitcode_slice_from_object_data( + child.data(&*archive_data).expect("corrupt rlib"), + cgcx, + ) { + Ok(data) => { + let module = SerializedModule::FromRlib(data.to_vec()); + upstream_modules.push((module, CString::new(name).unwrap())); } + Err(e) => dcx.emit_fatal(e), } } } @@ -187,8 +185,7 @@ pub(crate) fn run_thin( dcx: DiagCtxtHandle<'_>, exported_symbols_for_lto: &[String], each_linked_rlib_for_lto: &[PathBuf], - modules: Vec<(String, ModuleBuffer)>, - cached_modules: Vec<(SerializedModule, WorkProduct)>, + modules: Vec>, ) -> (Vec>, Vec) { let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx); @@ -200,7 +197,7 @@ pub(crate) fn run_thin( is deferred to the linker" ); } - thin_lto(cgcx, prof, dcx, modules, upstream_modules, cached_modules, &symbols_below_threshold) + thin_lto(cgcx, prof, dcx, modules, upstream_modules, &symbols_below_threshold) } fn fat_lto( @@ -300,7 +297,7 @@ fn fat_lto( // For all serialized bitcode files we parse them and link them in as we did // above, this is all mostly handled in C++. - let mut linker = Linker::new(llmod); + let linker = unsafe { llvm::LLVMRustLinkerNew(llmod) }; for (bc_decoded, name) in serialized_modules { let _timer = prof .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| { @@ -308,11 +305,19 @@ fn fat_lto( }); info!("linking {:?}", name); let data = bc_decoded.data(); - linker - .add(data) - .unwrap_or_else(|()| write::llvm_err(dcx, LlvmError::LoadBitcode { name })); + + unsafe { + if !llvm::LLVMRustLinkerAdd( + linker, + data.as_ptr() as *const libc::c_char, + data.len(), + ) { + llvm::LLVMRustLinkerFree(linker); + write::llvm_err(dcx, LlvmError::LoadBitcode { name }) + } + } } - drop(linker); + unsafe { llvm::LLVMRustLinkerFree(linker) }; save_temp_bitcode(cgcx, &module, "lto.input"); // Internalize everything below threshold to help strip out more modules and such. @@ -330,36 +335,6 @@ fn fat_lto( module } -pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>); - -impl<'a> Linker<'a> { - pub(crate) fn new(llmod: &'a llvm::Module) -> Self { - unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) } - } - - pub(crate) fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> { - unsafe { - if llvm::LLVMRustLinkerAdd( - self.0, - bytecode.as_ptr() as *const libc::c_char, - bytecode.len(), - ) { - Ok(()) - } else { - Err(()) - } - } - } -} - -impl Drop for Linker<'_> { - fn drop(&mut self) { - unsafe { - llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _)); - } - } -} - /// Prepare "thin" LTO to get run on these modules. /// /// The general structure of ThinLTO is quite different from the structure of @@ -394,24 +369,35 @@ fn thin_lto( cgcx: &CodegenContext, prof: &SelfProfilerRef, dcx: DiagCtxtHandle<'_>, - modules: Vec<(String, ModuleBuffer)>, + modules: Vec>, serialized_modules: Vec<(SerializedModule, CString)>, - cached_modules: Vec<(SerializedModule, WorkProduct)>, symbols_below_threshold: &[*const libc::c_char], ) -> (Vec>, Vec) { let _timer = prof.generic_activity("LLVM_thin_lto_global_analysis"); unsafe { info!("going for that thin, thin LTO"); - let green_modules: FxHashMap<_, _> = - cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect(); + let green_modules: FxHashMap<_, _> = modules + .iter() + .filter_map(|module| { + if let ThinLtoInput::Green { wp, .. } = module { + Some((wp.cgu_name.clone(), wp.clone())) + } else { + None + } + }) + .collect(); - let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len(); + let full_scope_len = modules.len(); let mut thin_buffers = Vec::with_capacity(modules.len()); let mut module_names = Vec::with_capacity(full_scope_len); let mut thin_modules = Vec::with_capacity(full_scope_len); - for (i, (name, buffer)) in modules.into_iter().enumerate() { + for (i, module) in modules.into_iter().enumerate() { + let (name, buffer) = match module { + ThinLtoInput::Red { name, buffer } => (name, buffer), + ThinLtoInput::Green { wp, buffer } => (wp.cgu_name, buffer), + }; info!("local module: {} - {}", i, name); let cname = CString::new(name.as_bytes()).unwrap(); thin_modules.push(llvm::ThinLTOModule { @@ -439,19 +425,15 @@ fn thin_lto( // incremental ThinLTO first where we could actually avoid // looking at upstream modules entirely sometimes (the contents, // we must always unconditionally look at the index). - let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len()); - - let cached_modules = - cached_modules.into_iter().map(|(sm, wp)| (sm, CString::new(wp.cgu_name).unwrap())); - for (module, name) in serialized_modules.into_iter().chain(cached_modules) { - info!("upstream or cached module {:?}", name); + for (module, name) in serialized_modules { + info!("upstream module {:?}", name); thin_modules.push(llvm::ThinLTOModule { identifier: name.as_ptr(), data: module.data().as_ptr(), len: module.data().len(), }); - serialized.push(module); + thin_buffers.push(module); module_names.push(name); } @@ -500,12 +482,7 @@ fn thin_lto( // also put all memory referenced by the C++ data (buffers, ids, etc) // into the arc as well. After this we'll create a thin module // codegen per module in this data. - let shared = Arc::new(ThinShared { - data, - thin_buffers, - serialized_modules: serialized, - module_names, - }); + let shared = Arc::new(ThinShared { data, modules: thin_buffers, module_names }); let mut copy_jobs = vec![]; let mut opt_jobs = vec![]; diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 17b6956ebd533..65c70c754918d 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -25,10 +25,10 @@ use back::write::{create_informational_target_machine, create_target_machine}; use context::SimpleCx; use llvm_util::target_config; use rustc_ast::expand::allocator::AllocatorMethod; -use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule}; +use rustc_codegen_ssa::back::lto::ThinModule; use rustc_codegen_ssa::back::write::{ CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryConfig, - TargetMachineFactoryFn, + TargetMachineFactoryFn, ThinLtoInput, }; use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::{CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, TargetConfig}; @@ -163,8 +163,7 @@ impl WriteBackendMethods for LlvmCodegenBackend { dcx: DiagCtxtHandle<'_>, exported_symbols_for_lto: &[String], each_linked_rlib_for_lto: &[PathBuf], - modules: Vec<(String, Self::ModuleBuffer)>, - cached_modules: Vec<(SerializedModule, WorkProduct)>, + modules: Vec>, ) -> (Vec>, Vec) { back::lto::run_thin( cgcx, @@ -173,7 +172,6 @@ impl WriteBackendMethods for LlvmCodegenBackend { exported_symbols_for_lto, each_linked_rlib_for_lto, modules, - cached_modules, ) } fn optimize( diff --git a/compiler/rustc_codegen_ssa/src/back/lto.rs b/compiler/rustc_codegen_ssa/src/back/lto.rs index a2c951c16d28d..cd380abb75e0e 100644 --- a/compiler/rustc_codegen_ssa/src/back/lto.rs +++ b/compiler/rustc_codegen_ssa/src/back/lto.rs @@ -32,18 +32,13 @@ impl ThinModule { } pub fn data(&self) -> &[u8] { - let a = self.shared.thin_buffers.get(self.idx).map(|b| b.data()); - a.unwrap_or_else(|| { - let len = self.shared.thin_buffers.len(); - self.shared.serialized_modules[self.idx - len].data() - }) + self.shared.modules[self.idx].data() } } pub struct ThinShared { pub data: B::ThinData, - pub thin_buffers: Vec, - pub serialized_modules: Vec>, + pub modules: Vec>, pub module_names: Vec, } @@ -110,11 +105,9 @@ pub(super) fn exported_symbols_for_lto( // If we're performing LTO for the entire crate graph, then for each of our // upstream dependencies, include their exported symbols. - if tcx.sess.lto() != Lto::ThinLocal { - for &cnum in each_linked_rlib_for_lto { - let _timer = tcx.prof.generic_activity("lto_generate_symbols_below_threshold"); - symbols_below_threshold.extend(copy_symbols(cnum)); - } + for &cnum in each_linked_rlib_for_lto { + let _timer = tcx.prof.generic_activity("lto_generate_symbols_below_threshold"); + symbols_below_threshold.extend(copy_symbols(cnum)); } // Mark allocator shim symbols as exported only if they were generated. diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 1770251fcba46..82d7e23602e25 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -359,8 +359,7 @@ fn generate_thin_lto_work( dcx: DiagCtxtHandle<'_>, exported_symbols_for_lto: &[String], each_linked_rlib_for_lto: &[PathBuf], - needs_thin_lto: Vec<(String, B::ModuleBuffer)>, - import_only_modules: Vec<(SerializedModule, WorkProduct)>, + needs_thin_lto: Vec>, ) -> Vec<(ThinLtoWorkItem, u64)> { let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work"); @@ -371,7 +370,6 @@ fn generate_thin_lto_work( exported_symbols_for_lto, each_linked_rlib_for_lto, needs_thin_lto, - import_only_modules, ); lto_modules .into_iter() @@ -398,16 +396,12 @@ enum MaybeLtoModules { exported_symbols_for_lto: Arc>, each_linked_rlib_file_for_lto: Vec, needs_fat_lto: Vec>, - lto_import_only_modules: - Vec<(SerializedModule<::ModuleBuffer>, WorkProduct)>, }, ThinLto { cgcx: CodegenContext, exported_symbols_for_lto: Arc>, each_linked_rlib_file_for_lto: Vec, - needs_thin_lto: Vec<(String, ::ModuleBuffer)>, - lto_import_only_modules: - Vec<(SerializedModule<::ModuleBuffer>, WorkProduct)>, + needs_thin_lto: Vec>, }, } @@ -603,30 +597,28 @@ pub fn produce_final_output_artifacts( // Clean up unwanted temporary files. // We create the following files by default: - // - #crate#.#module-name#.bc - // - #crate#.#module-name#.o - // - #crate#.crate.metadata.bc - // - #crate#.crate.metadata.o - // - #crate#.o (linked from crate.##.o) - // - #crate#.bc (copied from crate.##.bc) + // - #crate#.#module-name#.rcgu.bc + // - #crate#.#module-name#.rcgu.o + // - #crate#.o (linked from crate.##.rcgu.o) + // - #crate#.bc (copied from crate.##.rcgu.bc) // We may create additional files if requested by the user (through // `-C save-temps` or `--emit=` flags). if !sess.opts.cg.save_temps { - // Remove the temporary .#module-name#.o objects. If the user didn't + // Remove the temporary .#module-name#.rcgu.o objects. If the user didn't // explicitly request bitcode (with --emit=bc), and the bitcode is not // needed for building an rlib, then we must remove .#module-name#.bc as // well. - // Specific rules for keeping .#module-name#.bc: + // Specific rules for keeping .#module-name#.rcgu.bc: // - If the user requested bitcode (`user_wants_bitcode`), and // codegen_units > 1, then keep it. // - If the user requested bitcode but codegen_units == 1, then we - // can toss .#module-name#.bc because we copied it to .bc earlier. + // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier. // - If we're not building an rlib and the user didn't request - // bitcode, then delete .#module-name#.bc. + // bitcode, then delete .#module-name#.rcgu.bc. // If you change how this works, also update back::link::link_rlib, - // where .#module-name#.bc files are (maybe) deleted after making an + // where .#module-name#.rcgu.bc files are (maybe) deleted after making an // rlib. let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe); @@ -686,7 +678,6 @@ pub fn produce_final_output_artifacts( // We leave the following files around by default: // - #crate#.o - // - #crate#.crate.metadata.o // - #crate#.bc // These are used in linking steps and will be cleaned up afterward. } @@ -787,6 +778,11 @@ pub enum FatLtoInput { InMemory(ModuleCodegen), } +pub enum ThinLtoInput { + Red { name: String, buffer: SerializedModule }, + Green { wp: WorkProduct, buffer: SerializedModule }, +} + /// Actual LTO type we end up choosing based on multiple factors. pub(crate) enum ComputedLtoType { No, @@ -973,8 +969,7 @@ fn do_fat_lto( tm_factory: TargetMachineFactoryFn, exported_symbols_for_lto: &[String], each_linked_rlib_for_lto: &[PathBuf], - mut needs_fat_lto: Vec>, - import_only_modules: Vec<(SerializedModule, WorkProduct)>, + needs_fat_lto: Vec>, ) -> CompiledModule { let _timer = prof.verbose_generic_activity("LLVM_fatlto"); @@ -983,10 +978,6 @@ fn do_fat_lto( check_lto_allowed(&cgcx, dcx); - for (module, wp) in import_only_modules { - needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module }) - } - B::optimize_and_codegen_fat_lto( cgcx, prof, @@ -1005,11 +996,7 @@ fn do_thin_lto( tm_factory: TargetMachineFactoryFn, exported_symbols_for_lto: Arc>, each_linked_rlib_for_lto: Vec, - needs_thin_lto: Vec<(String, ::ModuleBuffer)>, - lto_import_only_modules: Vec<( - SerializedModule<::ModuleBuffer>, - WorkProduct, - )>, + needs_thin_lto: Vec>, ) -> Vec { let _timer = prof.verbose_generic_activity("LLVM_thinlto"); @@ -1046,7 +1033,6 @@ fn do_thin_lto( &exported_symbols_for_lto, &each_linked_rlib_for_lto, needs_thin_lto, - lto_import_only_modules, ) { let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e); @@ -1264,13 +1250,16 @@ fn start_executing_work( let mut each_linked_rlib_for_lto = Vec::new(); let mut each_linked_rlib_file_for_lto = Vec::new(); - drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| { - if link::ignored_for_lto(sess, crate_info, cnum) { - return; - } - each_linked_rlib_for_lto.push(cnum); - each_linked_rlib_file_for_lto.push(path.to_path_buf()); - })); + if sess.lto() != Lto::No && sess.lto() != Lto::ThinLocal { + drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| { + if link::ignored_for_lto(sess, crate_info, cnum) { + return; + } + + each_linked_rlib_for_lto.push(cnum); + each_linked_rlib_file_for_lto.push(path.to_path_buf()); + })); + } // Compute the set of symbols we need to retain when doing LTO (if we need to) let exported_symbols_for_lto = @@ -1723,7 +1712,10 @@ fn start_executing_work( } Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => { assert!(needs_fat_lto.is_empty()); - needs_thin_lto.push((name, thin_buffer)); + needs_thin_lto.push(ThinLtoInput::Red { + name, + buffer: SerializedModule::Local(thin_buffer), + }); } Err(Some(WorkerFatalError)) => { // Like `CodegenAborted`, wait for remaining work to finish. @@ -1766,17 +1758,24 @@ fn start_executing_work( needs_fat_lto.push(FatLtoInput::InMemory(allocator_module)); } + for (module, wp) in lto_import_only_modules { + needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module }) + } + return Ok(MaybeLtoModules::FatLto { cgcx, exported_symbols_for_lto, each_linked_rlib_file_for_lto, needs_fat_lto, - lto_import_only_modules, }); } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() { assert!(compiled_modules.is_empty()); assert!(needs_fat_lto.is_empty()); + for (buffer, wp) in lto_import_only_modules { + needs_thin_lto.push(ThinLtoInput::Green { wp, buffer }) + } + if cgcx.lto == Lto::ThinLocal { compiled_modules.extend(do_thin_lto::( &cgcx, @@ -1786,12 +1785,14 @@ fn start_executing_work( exported_symbols_for_lto, each_linked_rlib_file_for_lto, needs_thin_lto, - lto_import_only_modules, )); } else { if let Some(allocator_module) = allocator_module.take() { let thin_buffer = B::serialize_module(allocator_module.module_llvm, true); - needs_thin_lto.push((allocator_module.name, thin_buffer)); + needs_thin_lto.push(ThinLtoInput::Red { + name: allocator_module.name, + buffer: SerializedModule::Local(thin_buffer), + }); } return Ok(MaybeLtoModules::ThinLto { @@ -1799,7 +1800,6 @@ fn start_executing_work( exported_symbols_for_lto, each_linked_rlib_file_for_lto, needs_thin_lto, - lto_import_only_modules, }); } } @@ -2173,7 +2173,6 @@ impl OngoingCodegen { exported_symbols_for_lto, each_linked_rlib_file_for_lto, needs_fat_lto, - lto_import_only_modules, } => { let tm_factory = self.backend.target_machine_factory( sess, @@ -2190,7 +2189,6 @@ impl OngoingCodegen { &exported_symbols_for_lto, &each_linked_rlib_file_for_lto, needs_fat_lto, - lto_import_only_modules, )], allocator_module: None, } @@ -2200,7 +2198,6 @@ impl OngoingCodegen { exported_symbols_for_lto, each_linked_rlib_file_for_lto, needs_thin_lto, - lto_import_only_modules, } => { let tm_factory = self.backend.target_machine_factory( sess, @@ -2217,7 +2214,6 @@ impl OngoingCodegen { exported_symbols_for_lto, each_linked_rlib_file_for_lto, needs_thin_lto, - lto_import_only_modules, ), allocator_module: None, } diff --git a/compiler/rustc_codegen_ssa/src/traits/write.rs b/compiler/rustc_codegen_ssa/src/traits/write.rs index 5d2313092fa84..cca6db78e381e 100644 --- a/compiler/rustc_codegen_ssa/src/traits/write.rs +++ b/compiler/rustc_codegen_ssa/src/traits/write.rs @@ -6,9 +6,9 @@ use rustc_errors::DiagCtxtHandle; use rustc_middle::dep_graph::WorkProduct; use rustc_session::{Session, config}; -use crate::back::lto::{SerializedModule, ThinModule}; +use crate::back::lto::ThinModule; use crate::back::write::{ - CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryFn, + CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryFn, ThinLtoInput, }; use crate::{CompiledModule, ModuleCodegen}; @@ -47,8 +47,7 @@ pub trait WriteBackendMethods: Clone + 'static { dcx: DiagCtxtHandle<'_>, exported_symbols_for_lto: &[String], each_linked_rlib_for_lto: &[PathBuf], - modules: Vec<(String, Self::ModuleBuffer)>, - cached_modules: Vec<(SerializedModule, WorkProduct)>, + modules: Vec>, ) -> (Vec>, Vec); fn optimize( cgcx: &CodegenContext, diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index ec5951e50e3a8..ab50b1fbd4cf8 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -12,8 +12,8 @@ use rustc_ast::{ }; use rustc_attr_parsing::parser::AllowExprMetavar; use rustc_attr_parsing::{ - self as attr, AttributeParser, CFG_TEMPLATE, EvalConfigResult, ShouldEmit, eval_config_entry, - parse_cfg, + self as attr, AttributeParser, AttributeSafety, CFG_TEMPLATE, EvalConfigResult, ShouldEmit, + eval_config_entry, parse_cfg, }; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_errors::msg; @@ -404,6 +404,7 @@ impl<'a> StripUnconfigured<'a> { parse_cfg, &CFG_TEMPLATE, AllowExprMetavar::Yes, + AttributeSafety::Normal, ) else { // Cfg attribute was not parsable, give up return EvalConfigResult::True; diff --git a/compiler/rustc_expand/src/errors.rs b/compiler/rustc_expand/src/errors.rs index 6c5732f497f8a..cee333e0a59fd 100644 --- a/compiler/rustc_expand/src/errors.rs +++ b/compiler/rustc_expand/src/errors.rs @@ -603,21 +603,3 @@ pub(crate) struct TrailingMacro { pub is_trailing: bool, pub name: Ident, } - -#[derive(Diagnostic)] -#[diag("unused attribute `{$attr_name}`")] -pub(crate) struct UnusedBuiltinAttribute { - #[note( - "the built-in attribute `{$attr_name}` will be ignored, since it's applied to the macro invocation `{$macro_name}`" - )] - pub invoc_span: Span, - pub attr_name: Symbol, - pub macro_name: String, - #[suggestion( - "remove the attribute", - code = "", - applicability = "machine-applicable", - style = "tool-only" - )] - pub attr_span: Span, -} diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index e3a15f193e581..0ba87d6296b39 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -15,8 +15,8 @@ use rustc_ast::{ use rustc_ast_pretty::pprust; use rustc_attr_parsing::parser::AllowExprMetavar; use rustc_attr_parsing::{ - AttributeParser, CFG_TEMPLATE, Early, EvalConfigResult, ShouldEmit, eval_config_entry, - parse_cfg, validate_attr, + AttributeParser, AttributeSafety, CFG_TEMPLATE, EvalConfigResult, ShouldEmit, + eval_config_entry, parse_cfg, validate_attr, }; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_data_structures::stack::ensure_sufficient_stack; @@ -30,7 +30,7 @@ use rustc_parse::parser::{ RecoverColon, RecoverComma, Recovery, token_descr, }; use rustc_session::Session; -use rustc_session::lint::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS}; +use rustc_session::lint::builtin::UNUSED_DOC_COMMENTS; use rustc_session::parse::feature_err; use rustc_span::hygiene::SyntaxContext; use rustc_span::{ErrorGuaranteed, FileName, Ident, LocalExpnId, Span, Symbol, sym}; @@ -2274,21 +2274,6 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { self.cx.current_expansion.lint_node_id, crate::errors::MacroCallUnusedDocComment { span: attr.span }, ); - } else if rustc_attr_parsing::is_builtin_attr(attr) - && !AttributeParser::::is_parsed_attribute(&attr.path()) - { - let attr_name = attr.name().unwrap(); - self.cx.sess.psess.buffer_lint( - UNUSED_ATTRIBUTES, - attr.span, - self.cx.current_expansion.lint_node_id, - crate::errors::UnusedBuiltinAttribute { - attr_name, - macro_name: pprust::path_to_string(&call.path), - invoc_span: call.path.span, - attr_span: attr.span, - }, - ); } } } @@ -2310,6 +2295,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { parse_cfg, &CFG_TEMPLATE, AllowExprMetavar::Yes, + AttributeSafety::Normal, ) else { // Cfg attribute was not parsable, give up return EvalConfigResult::True; diff --git a/compiler/rustc_expand/src/module.rs b/compiler/rustc_expand/src/module.rs index 79ab3cab22ce2..803803ec3f6cb 100644 --- a/compiler/rustc_expand/src/module.rs +++ b/compiler/rustc_expand/src/module.rs @@ -2,12 +2,14 @@ use std::iter::once; use std::path::{self, Path, PathBuf}; use rustc_ast::{AttrVec, Attribute, Inline, Item, ModSpans}; -use rustc_attr_parsing::validate_attr; +use rustc_attr_parsing::validate_attr::emit_malformed_attribute; use rustc_errors::{Diag, ErrorGuaranteed}; +use rustc_feature::template; use rustc_parse::lexer::StripTokens; use rustc_parse::{exp, new_parser_from_file, unwrap_or_emit_fatal}; use rustc_session::Session; use rustc_session::parse::ParseSess; +use rustc_span::fatal_error::FatalError; use rustc_span::{Ident, Span, sym}; use thin_vec::ThinVec; @@ -184,6 +186,7 @@ pub(crate) fn mod_file_path_from_attr( attrs: &[Attribute], dir_path: &Path, ) -> Option { + // FIXME(154781) use a parsed attribute here // Extract path string from first `#[path = "path_string"]` attribute. let first_path = attrs.iter().find(|at| at.has_name(sym::path))?; let Some(path_sym) = first_path.value_str() else { @@ -195,7 +198,17 @@ pub(crate) fn mod_file_path_from_attr( // Usually bad forms are checked during semantic analysis via // `TyCtxt::check_mod_attrs`), but by the time that runs the macro // is expanded, and it doesn't give an error. - validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, first_path, sym::path); + emit_malformed_attribute( + &sess.psess, + first_path.style, + first_path.span, + sym::path, + template!( + NameValueStr: "file", + "https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute" + ), + ); + FatalError.raise() }; let path_str = path_sym.as_str(); diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index acbcba90fbcc0..a3782a7990b0a 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -2,13 +2,9 @@ use std::sync::LazyLock; -use AttributeDuplicates::*; use AttributeGate::*; -use AttributeType::*; use rustc_data_structures::fx::FxHashMap; use rustc_hir::AttrStyle; -use rustc_hir::attrs::EncodeCrossCrate; -use rustc_span::edition::Edition; use rustc_span::{Symbol, sym}; use crate::Features; @@ -73,29 +69,6 @@ pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg // move that documentation into the relevant place in the other docs, and // remove the chapter on the flag. -#[derive(Copy, Clone, PartialEq, Debug)] -pub enum AttributeType { - /// Normal, builtin attribute that is consumed - /// by the compiler before the unused_attribute check - Normal, - - /// Builtin attribute that is only allowed at the crate level - CrateLevel, -} - -#[derive(Copy, Clone, PartialEq, Debug)] -pub enum AttributeSafety { - /// Normal attribute that does not need `#[unsafe(...)]` - Normal, - - /// Unsafe attribute that requires safety obligations to be discharged. - /// - /// An error is emitted when `#[unsafe(...)]` is omitted, except when the attribute's edition - /// is less than the one stored in `unsafe_since`. This handles attributes that were safe in - /// earlier editions, but become unsafe in later ones. - Unsafe { unsafe_since: Option }, -} - #[derive(Clone, Debug, Copy)] pub enum AttributeGate { /// A gated attribute which requires a feature gate to be enabled. @@ -181,57 +154,6 @@ impl AttributeTemplate { } } -/// How to handle multiple duplicate attributes on the same item. -#[derive(Clone, Copy, Default)] -pub enum AttributeDuplicates { - /// Duplicates of this attribute are allowed. - /// - /// This should only be used with attributes where duplicates have semantic - /// meaning, or some kind of "additive" behavior. For example, `#[warn(..)]` - /// can be specified multiple times, and it combines all the entries. Or use - /// this if there is validation done elsewhere. - #[default] - DuplicatesOk, - /// Duplicates after the first attribute will be an unused_attribute warning. - /// - /// This is usually used for "word" attributes, where they are used as a - /// boolean marker, like `#[used]`. It is not necessarily wrong that there - /// are duplicates, but the others should probably be removed. - WarnFollowing, - /// Same as `WarnFollowing`, but only issues warnings for word-style attributes. - /// - /// This is only for special cases, for example multiple `#[macro_use]` can - /// be warned, but multiple `#[macro_use(...)]` should not because the list - /// form has different meaning from the word form. - WarnFollowingWordOnly, - /// Duplicates after the first attribute will be an error. - /// - /// This should be used where duplicates would be ignored, but carry extra - /// meaning that could cause confusion. For example, `#[stable(since="1.0")] - /// #[stable(since="2.0")]`, which version should be used for `stable`? - ErrorFollowing, - /// Duplicates preceding the last instance of the attribute will be an error. - /// - /// This is the same as `ErrorFollowing`, except the last attribute is the - /// one that is "used". This is typically used in cases like codegen - /// attributes which usually only honor the last attribute. - ErrorPreceding, - /// Duplicates after the first attribute will be an unused_attribute warning - /// with a note that this will be an error in the future. - /// - /// This should be used for attributes that should be `ErrorFollowing`, but - /// because older versions of rustc silently accepted (and ignored) the - /// attributes, this is used to transition. - FutureWarnFollowing, - /// Duplicates preceding the last instance of the attribute will be a - /// warning, with a note that this will be an error in the future. - /// - /// This is the same as `FutureWarnFollowing`, except the last attribute is - /// the one that is "used". Ideally these can eventually migrate to - /// `ErrorPreceding`. - FutureWarnPreceding, -} - /// A convenience macro for constructing attribute templates. /// E.g., `template!(Word, List: "description")` means that the attribute /// supports forms `#[attr]` and `#[attr(description)]`. @@ -268,82 +190,16 @@ macro_rules! template { } macro_rules! ungated { - (unsafe($edition:ident) $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => { - BuiltinAttribute { - name: sym::$attr, - encode_cross_crate: $encode_cross_crate, - type_: $typ, - safety: AttributeSafety::Unsafe { unsafe_since: Some(Edition::$edition) }, - template: $tpl, - gate: Ungated, - duplicates: $duplicates, - } - }; - (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => { - BuiltinAttribute { - name: sym::$attr, - encode_cross_crate: $encode_cross_crate, - type_: $typ, - safety: AttributeSafety::Unsafe { unsafe_since: None }, - template: $tpl, - gate: Ungated, - duplicates: $duplicates, - } - }; - ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => { - BuiltinAttribute { - name: sym::$attr, - encode_cross_crate: $encode_cross_crate, - type_: $typ, - safety: AttributeSafety::Normal, - template: $tpl, - gate: Ungated, - duplicates: $duplicates, - } + ($attr:ident $(,)?) => { + BuiltinAttribute { name: sym::$attr, gate: Ungated } }; } macro_rules! gated { - (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $gate:ident, $message:expr $(,)?) => { - BuiltinAttribute { - name: sym::$attr, - encode_cross_crate: $encode_cross_crate, - type_: $typ, - safety: AttributeSafety::Unsafe { unsafe_since: None }, - template: $tpl, - duplicates: $duplicates, - gate: Gated { - feature: sym::$gate, - message: $message, - check: Features::$gate, - notes: &[], - }, - } - }; - (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $message:expr $(,)?) => { - BuiltinAttribute { - name: sym::$attr, - encode_cross_crate: $encode_cross_crate, - type_: $typ, - safety: AttributeSafety::Unsafe { unsafe_since: None }, - template: $tpl, - duplicates: $duplicates, - gate: Gated { - feature: sym::$attr, - message: $message, - check: Features::$attr, - notes: &[], - }, - } - }; - ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $gate:ident, $message:expr $(,)?) => { + ($attr:ident, $gate:ident, $message:expr $(,)?) => { BuiltinAttribute { name: sym::$attr, - encode_cross_crate: $encode_cross_crate, - type_: $typ, - safety: AttributeSafety::Normal, - template: $tpl, - duplicates: $duplicates, + gate: Gated { feature: sym::$gate, message: $message, @@ -352,14 +208,10 @@ macro_rules! gated { }, } }; - ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $message:expr $(,)?) => { + ($attr:ident, $message:expr $(,)?) => { BuiltinAttribute { name: sym::$attr, - encode_cross_crate: $encode_cross_crate, - type_: $typ, - safety: AttributeSafety::Normal, - template: $tpl, - duplicates: $duplicates, + gate: Gated { feature: sym::$attr, message: $message, @@ -371,13 +223,8 @@ macro_rules! gated { } macro_rules! rustc_attr { - (TEST, $attr:ident, $typ:expr, $tpl:expr, $duplicate:expr, $encode_cross_crate:expr $(,)?) => { - rustc_attr!( - $attr, - $typ, - $tpl, - $duplicate, - $encode_cross_crate, + (TEST, $attr:ident $(,)?) => { + rustc_attr!( $attr, concat!( "the `#[", stringify!($attr), @@ -385,14 +232,9 @@ macro_rules! rustc_attr { ), ) }; - ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $($notes:expr),* $(,)?) => { + ($attr:ident $(, $notes:expr)* $(,)?) => { BuiltinAttribute { name: sym::$attr, - encode_cross_crate: $encode_cross_crate, - type_: $typ, - safety: AttributeSafety::Normal, - template: $tpl, - duplicates: $duplicates, gate: Gated { feature: sym::rustc_attrs, message: "use of an internal attribute", @@ -416,15 +258,6 @@ macro_rules! experimental { pub struct BuiltinAttribute { pub name: Symbol, - /// Whether this attribute is encode cross crate. - /// - /// If so, it is encoded in the crate metadata. - /// Otherwise, it can only be used in the local crate. - pub encode_cross_crate: EncodeCrossCrate, - pub type_: AttributeType, - pub safety: AttributeSafety, - pub template: AttributeTemplate, - pub duplicates: AttributeDuplicates, pub gate: AttributeGate, } @@ -436,379 +269,98 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ // ========================================================================== // Conditional compilation: - ungated!( - cfg, Normal, - template!( - List: &["predicate"], - "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute" - ), - DuplicatesOk, EncodeCrossCrate::No - ), - ungated!( - cfg_attr, Normal, - template!( - List: &["predicate, attr1, attr2, ..."], - "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute" - ), - DuplicatesOk, EncodeCrossCrate::No - ), + ungated!(cfg), + ungated!(cfg_attr), // Testing: - ungated!( - ignore, Normal, - template!( - Word, - NameValueStr: "reason", - "https://doc.rust-lang.org/reference/attributes/testing.html#the-ignore-attribute" - ), - WarnFollowing, EncodeCrossCrate::No, - ), - ungated!( - should_panic, Normal, - template!( - Word, - List: &[r#"expected = "reason""#], - NameValueStr: "reason", - "https://doc.rust-lang.org/reference/attributes/testing.html#the-should_panic-attribute" - ), - FutureWarnFollowing, EncodeCrossCrate::No, - ), + ungated!(ignore), + ungated!(should_panic), // Macros: - ungated!( - automatically_derived, Normal, - template!( - Word, - "https://doc.rust-lang.org/reference/attributes/derive.html#the-automatically_derived-attribute" - ), - WarnFollowing, EncodeCrossCrate::Yes - ), - ungated!( - macro_use, Normal, - template!( - Word, - List: &["name1, name2, ..."], - "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_use-attribute" - ), - WarnFollowingWordOnly, EncodeCrossCrate::No, - ), - ungated!(macro_escape, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No), // Deprecated synonym for `macro_use`. - ungated!( - macro_export, Normal, - template!( - Word, - List: &["local_inner_macros"], - "https://doc.rust-lang.org/reference/macros-by-example.html#path-based-scope" - ), - WarnFollowing, EncodeCrossCrate::Yes - ), - ungated!( - proc_macro, Normal, - template!( - Word, - "https://doc.rust-lang.org/reference/procedural-macros.html#function-like-procedural-macros"), - ErrorFollowing, EncodeCrossCrate::No - ), - ungated!( - proc_macro_derive, Normal, - template!( - List: &["TraitName", "TraitName, attributes(name1, name2, ...)"], - "https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros" - ), - ErrorFollowing, EncodeCrossCrate::No, - ), - ungated!( - proc_macro_attribute, Normal, - template!(Word, "https://doc.rust-lang.org/reference/procedural-macros.html#attribute-macros"), - ErrorFollowing, EncodeCrossCrate::No - ), + ungated!(automatically_derived), + ungated!(macro_use), + ungated!(macro_escape), // Deprecated synonym for `macro_use`. + ungated!(macro_export), + ungated!(proc_macro), + ungated!(proc_macro_derive), + ungated!(proc_macro_attribute), // Lints: - ungated!( - warn, Normal, - template!( - List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#], - "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes" - ), - DuplicatesOk, EncodeCrossCrate::No, - ), - ungated!( - allow, Normal, - template!( - List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#], - "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes" - ), - DuplicatesOk, EncodeCrossCrate::No, - ), - ungated!( - expect, Normal, - template!( - List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#], - "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes" - ), - DuplicatesOk, EncodeCrossCrate::No, - ), - ungated!( - forbid, Normal, - template!( - List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#], - "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes" - ), - DuplicatesOk, EncodeCrossCrate::No - ), - ungated!( - deny, Normal, - template!( - List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#], - "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes" - ), - DuplicatesOk, EncodeCrossCrate::No - ), - ungated!( - must_use, Normal, - template!( - Word, - NameValueStr: "reason", - "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" - ), - FutureWarnFollowing, EncodeCrossCrate::Yes - ), - gated!( - must_not_suspend, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing, - EncodeCrossCrate::Yes, experimental!(must_not_suspend) - ), - ungated!( - deprecated, Normal, - template!( - Word, - List: &[r#"/*opt*/ since = "version", /*opt*/ note = "reason""#], - NameValueStr: "reason", - "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute" - ), - ErrorFollowing, EncodeCrossCrate::Yes - ), + ungated!(warn), + ungated!(allow), + ungated!(expect), + ungated!(forbid), + ungated!(deny), + ungated!(must_use), + gated!(must_not_suspend, experimental!(must_not_suspend)), + ungated!(deprecated), // Crate properties: - ungated!( - crate_name, CrateLevel, - template!( - NameValueStr: "name", - "https://doc.rust-lang.org/reference/crates-and-source-files.html#the-crate_name-attribute" - ), - FutureWarnFollowing, EncodeCrossCrate::No, - ), - ungated!( - crate_type, CrateLevel, - template!( - NameValueStr: ["bin", "lib", "dylib", "cdylib", "rlib", "staticlib", "sdylib", "proc-macro"], - "https://doc.rust-lang.org/reference/linkage.html" - ), - DuplicatesOk, EncodeCrossCrate::No, - ), + ungated!(crate_name), + ungated!(crate_type), // ABI, linking, symbols, and FFI - ungated!( - link, Normal, - template!(List: &[ - r#"name = "...""#, - r#"name = "...", kind = "dylib|static|...""#, - r#"name = "...", wasm_import_module = "...""#, - r#"name = "...", import_name_type = "decorated|noprefix|undecorated""#, - r#"name = "...", kind = "dylib|static|...", wasm_import_module = "...", import_name_type = "decorated|noprefix|undecorated""#, - ], "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link-attribute"), - DuplicatesOk, EncodeCrossCrate::No, - ), - ungated!( - link_name, Normal, - template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link_name-attribute"), - FutureWarnPreceding, EncodeCrossCrate::Yes - ), - ungated!( - no_link, Normal, - template!(Word, "https://doc.rust-lang.org/reference/items/extern-crates.html#the-no_link-attribute"), - WarnFollowing, EncodeCrossCrate::No - ), - ungated!( - repr, Normal, - template!( - List: &["C", "Rust", "transparent", "align(...)", "packed(...)", ""], - "https://doc.rust-lang.org/reference/type-layout.html#representations" - ), - DuplicatesOk, EncodeCrossCrate::No - ), + ungated!(link), + ungated!(link_name), + ungated!(no_link), + ungated!(repr), // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity - gated!(rustc_align, Normal, template!(List: &["alignment"]), DuplicatesOk, EncodeCrossCrate::No, fn_align, experimental!(rustc_align)), - gated!(rustc_align_static, Normal, template!(List: &["alignment"]), DuplicatesOk, EncodeCrossCrate::No, static_align, experimental!(rustc_align_static)), - ungated!( - unsafe(Edition2024) export_name, Normal, - template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute"), - FutureWarnPreceding, EncodeCrossCrate::No - ), - ungated!( - unsafe(Edition2024) link_section, Normal, - template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute"), - FutureWarnPreceding, EncodeCrossCrate::No - ), - ungated!( - unsafe(Edition2024) no_mangle, Normal, - template!(Word, "https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute"), - WarnFollowing, EncodeCrossCrate::No - ), - ungated!( - used, Normal, - template!(Word, List: &["compiler", "linker"], "https://doc.rust-lang.org/reference/abi.html#the-used-attribute"), - WarnFollowing, EncodeCrossCrate::No - ), - ungated!( - link_ordinal, Normal, - template!(List: &["ordinal"], "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link_ordinal-attribute"), - ErrorPreceding, EncodeCrossCrate::Yes - ), - ungated!( - unsafe naked, Normal, - template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-naked-attribute"), - WarnFollowing, EncodeCrossCrate::No - ), + gated!(rustc_align,fn_align, experimental!(rustc_align)), + gated!(rustc_align_static,static_align, experimental!(rustc_align_static)), + ungated!(export_name), + ungated!(link_section), + ungated!(no_mangle), + ungated!(used), + ungated!(link_ordinal), + ungated!(naked), // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details. - rustc_attr!( - rustc_pass_indirectly_in_non_rustic_abis, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::No, - "types marked with `#[rustc_pass_indirectly_in_non_rustic_abis]` are always passed indirectly by non-Rustic ABIs" - ), + rustc_attr!(rustc_pass_indirectly_in_non_rustic_abis, "types marked with `#[rustc_pass_indirectly_in_non_rustic_abis]` are always passed indirectly by non-Rustic ABIs"), // Limits: - ungated!( - recursion_limit, CrateLevel, - template!(NameValueStr: "N", "https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute"), - FutureWarnFollowing, EncodeCrossCrate::No - ), - ungated!( - type_length_limit, CrateLevel, - template!(NameValueStr: "N", "https://doc.rust-lang.org/reference/attributes/limits.html#the-type_length_limit-attribute"), - FutureWarnFollowing, EncodeCrossCrate::No - ), + ungated!(recursion_limit), + ungated!(type_length_limit), gated!( - move_size_limit, CrateLevel, template!(NameValueStr: "N"), ErrorFollowing, - EncodeCrossCrate::No, large_assignments, experimental!(move_size_limit) + move_size_limit, large_assignments, experimental!(move_size_limit) ), // Entry point: - ungated!( - no_main, CrateLevel, - template!(Word, "https://doc.rust-lang.org/reference/crates-and-source-files.html#the-no_main-attribute"), - WarnFollowing, EncodeCrossCrate::No - ), + ungated!(no_main), // Modules, prelude, and resolution: - ungated!( - path, Normal, - template!(NameValueStr: "file", "https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute"), - FutureWarnFollowing, EncodeCrossCrate::No - ), - ungated!( - no_std, CrateLevel, - template!(Word, "https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute"), - WarnFollowing, EncodeCrossCrate::No - ), - ungated!( - no_implicit_prelude, Normal, - template!(Word, "https://doc.rust-lang.org/reference/names/preludes.html#the-no_implicit_prelude-attribute"), - WarnFollowing, EncodeCrossCrate::No - ), - ungated!( - non_exhaustive, Normal, - template!(Word, "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute"), - WarnFollowing, EncodeCrossCrate::Yes - ), + ungated!(path), + ungated!(no_std), + ungated!(no_implicit_prelude), + ungated!(non_exhaustive), // Runtime - ungated!( - windows_subsystem, CrateLevel, - template!(NameValueStr: ["windows", "console"], "https://doc.rust-lang.org/reference/runtime.html#the-windows_subsystem-attribute"), - FutureWarnFollowing, EncodeCrossCrate::No - ), - ungated!( // RFC 2070 - panic_handler, Normal, - template!(Word, "https://doc.rust-lang.org/reference/panic.html#the-panic_handler-attribute"), - WarnFollowing, EncodeCrossCrate::Yes - ), + ungated!(windows_subsystem), + ungated!(// RFC 2070 + panic_handler), // Code generation: - ungated!( - inline, Normal, - template!( - Word, - List: &["always", "never"], - "https://doc.rust-lang.org/reference/attributes/codegen.html#the-inline-attribute" - ), - FutureWarnFollowing, EncodeCrossCrate::No - ), - ungated!( - cold, Normal, - template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-cold-attribute"), - WarnFollowing, EncodeCrossCrate::No - ), - ungated!( - no_builtins, CrateLevel, - template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-no_builtins-attribute"), - WarnFollowing, EncodeCrossCrate::Yes - ), - ungated!( - target_feature, Normal, - template!(List: &[r#"enable = "name""#], "https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute"), - DuplicatesOk, EncodeCrossCrate::No, - ), - ungated!( - track_caller, Normal, - template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-track_caller-attribute"), - WarnFollowing, EncodeCrossCrate::Yes - ), - ungated!( - instruction_set, Normal, - template!(List: &["set"], "https://doc.rust-lang.org/reference/attributes/codegen.html#the-instruction_set-attribute"), - ErrorPreceding, EncodeCrossCrate::No - ), + ungated!(inline), + ungated!(cold), + ungated!(no_builtins), + ungated!(target_feature), + ungated!(track_caller), + ungated!(instruction_set), gated!( - unsafe force_target_feature, Normal, template!(List: &[r#"enable = "name""#]), - DuplicatesOk, EncodeCrossCrate::No, effective_target_features, experimental!(force_target_feature) + force_target_feature, + effective_target_features, experimental!(force_target_feature) ), gated!( - sanitize, Normal, template!(List: &[r#"address = "on|off""#, r#"kernel_address = "on|off""#, r#"cfi = "on|off""#, r#"hwaddress = "on|off""#, r#"kernel_hwaddress = "on|off""#, r#"kcfi = "on|off""#, r#"memory = "on|off""#, r#"memtag = "on|off""#, r#"shadow_call_stack = "on|off""#, r#"thread = "on|off""#]), ErrorPreceding, - EncodeCrossCrate::No, sanitize, experimental!(sanitize), - ), + sanitize, + sanitize, experimental!(sanitize),), gated!( - coverage, Normal, template!(OneOf: &[sym::off, sym::on]), - ErrorPreceding, EncodeCrossCrate::No, + coverage, coverage_attribute, experimental!(coverage) ), - ungated!( - doc, Normal, - template!( - List: &["hidden", "inline"], - NameValueStr: "string", - "https://doc.rust-lang.org/rustdoc/write-documentation/the-doc-attribute.html" - ), - DuplicatesOk, EncodeCrossCrate::Yes - ), + ungated!(doc), // Debugging - ungated!( - debugger_visualizer, Normal, - template!( - List: &[r#"natvis_file = "...", gdb_script_file = "...""#], - "https://doc.rust-lang.org/reference/attributes/debugger.html#the-debugger_visualizer-attribute" - ), - DuplicatesOk, EncodeCrossCrate::No - ), - ungated!( - collapse_debuginfo, Normal, - template!( - List: &["no", "external", "yes"], - "https://doc.rust-lang.org/reference/attributes/debugger.html#the-collapse_debuginfo-attribute" - ), - ErrorFollowing, EncodeCrossCrate::Yes - ), + ungated!(debugger_visualizer), + ungated!(collapse_debuginfo), // ========================================================================== // Unstable attributes: @@ -816,71 +368,61 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ // Linking: gated!( - export_stable, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, experimental!(export_stable) + export_stable, experimental!(export_stable) ), // Testing: gated!( - test_runner, CrateLevel, template!(List: &["path"]), ErrorFollowing, - EncodeCrossCrate::Yes, custom_test_frameworks, - "custom test frameworks are an unstable feature", + test_runner, custom_test_frameworks, + "custom test frameworks are an unstable feature" ), gated!( - reexport_test_harness_main, CrateLevel, template!(NameValueStr: "name"), ErrorFollowing, - EncodeCrossCrate::No, custom_test_frameworks, - "custom test frameworks are an unstable feature", + reexport_test_harness_main, custom_test_frameworks, + "custom test frameworks are an unstable feature" ), // RFC #1268 gated!( - marker, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, - marker_trait_attr, experimental!(marker) + marker,marker_trait_attr, experimental!(marker) ), gated!( - thread_local, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, - "`#[thread_local]` is an experimental feature, and does not currently handle destructors", + thread_local,"`#[thread_local]` is an experimental feature, and does not currently handle destructors" ), gated!( - no_core, CrateLevel, template!(Word), WarnFollowing, - EncodeCrossCrate::No, experimental!(no_core) + no_core, experimental!(no_core) ), // RFC 2412 gated!( - optimize, Normal, template!(List: &["none", "size", "speed"]), ErrorPreceding, - EncodeCrossCrate::No, optimize_attribute, experimental!(optimize) + optimize, + optimize_attribute, experimental!(optimize) ), gated!( - unsafe ffi_pure, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, experimental!(ffi_pure) + ffi_pure, experimental!(ffi_pure) ), gated!( - unsafe ffi_const, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, experimental!(ffi_const) + ffi_const, experimental!(ffi_const) ), gated!( - register_tool, CrateLevel, template!(List: &["tool1, tool2, ..."]), DuplicatesOk, - EncodeCrossCrate::No, experimental!(register_tool), + register_tool, experimental!(register_tool) ), // `#[cfi_encoding = ""]` gated!( - cfi_encoding, Normal, template!(NameValueStr: "encoding"), ErrorPreceding, - EncodeCrossCrate::Yes, experimental!(cfi_encoding) + cfi_encoding, + experimental!(cfi_encoding) ), // `#[coroutine]` attribute to be applied to closures to make them coroutines instead gated!( - coroutine, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::No, coroutines, experimental!(coroutine) + coroutine,coroutines, experimental!(coroutine) ), // RFC 3543 // `#[patchable_function_entry(prefix_nops = m, entry_nops = n)]` gated!( - patchable_function_entry, Normal, template!(List: &["prefix_nops = m, entry_nops = n"]), ErrorPreceding, - EncodeCrossCrate::Yes, experimental!(patchable_function_entry) + patchable_function_entry, + experimental!(patchable_function_entry) ), // The `#[loop_match]` and `#[const_continue]` attributes are part of the @@ -888,12 +430,10 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ // // - https://github.com/rust-lang/rust/issues/132306 gated!( - const_continue, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::No, loop_match, experimental!(const_continue) + const_continue,loop_match, experimental!(const_continue) ), gated!( - loop_match, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::No, loop_match, experimental!(loop_match) + loop_match,loop_match, experimental!(loop_match) ), // The `#[pin_v2]` attribute is part of the `pin_ergonomics` experiment @@ -901,100 +441,52 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ // // - https://github.com/rust-lang/rust/issues/130494 gated!( - pin_v2, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::Yes, pin_ergonomics, experimental!(pin_v2), + pin_v2,pin_ergonomics, experimental!(pin_v2), ), // ========================================================================== // Internal attributes: Stability, deprecation, and unsafe: // ========================================================================== - ungated!( - feature, CrateLevel, - template!(List: &["name1, name2, ..."]), DuplicatesOk, EncodeCrossCrate::No, - ), + ungated!(feature), // DuplicatesOk since it has its own validation - ungated!( - stable, Normal, - template!(List: &[r#"feature = "name", since = "version""#]), DuplicatesOk, EncodeCrossCrate::No, - ), - ungated!( - unstable, Normal, - template!(List: &[r#"feature = "name", reason = "...", issue = "N""#]), DuplicatesOk, - EncodeCrossCrate::Yes - ), - ungated!( - unstable_feature_bound, Normal, template!(Word, List: &["feat1, feat2, ..."]), - DuplicatesOk, EncodeCrossCrate::No, - ), - ungated!( - rustc_const_unstable, Normal, template!(List: &[r#"feature = "name""#]), - DuplicatesOk, EncodeCrossCrate::Yes - ), - ungated!( - rustc_const_stable, Normal, - template!(List: &[r#"feature = "name""#]), DuplicatesOk, EncodeCrossCrate::No, - ), - ungated!( - rustc_default_body_unstable, Normal, - template!(List: &[r#"feature = "name", reason = "...", issue = "N""#]), - DuplicatesOk, EncodeCrossCrate::No - ), - gated!( - allow_internal_unstable, Normal, template!(Word, List: &["feat1, feat2, ..."]), - DuplicatesOk, EncodeCrossCrate::Yes, + ungated!(stable), + ungated!(unstable), + ungated!(unstable_feature_bound), + ungated!(rustc_const_unstable), + ungated!(rustc_const_stable), + ungated!(rustc_default_body_unstable), + gated!( + allow_internal_unstable, "allow_internal_unstable side-steps feature gating and stability checks", ), gated!( - allow_internal_unsafe, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, "allow_internal_unsafe side-steps the unsafe_code lint", + allow_internal_unsafe, "allow_internal_unsafe side-steps the unsafe_code lint", ), gated!( - rustc_eii_foreign_item, Normal, template!(Word), - ErrorFollowing, EncodeCrossCrate::Yes, eii_internals, + rustc_eii_foreign_item, + eii_internals, "used internally to mark types with a `transparent` representation when it is guaranteed by the documentation", ), - rustc_attr!( - rustc_allowed_through_unstable_modules, Normal, template!(NameValueStr: "deprecation message"), - WarnFollowing, EncodeCrossCrate::No, + rustc_attr!(rustc_allowed_through_unstable_modules, "rustc_allowed_through_unstable_modules special cases accidental stabilizations of stable items \ through unstable paths" ), - rustc_attr!( - rustc_deprecated_safe_2024, Normal, template!(List: &[r#"audit_that = "...""#]), - ErrorFollowing, EncodeCrossCrate::Yes, - "`#[rustc_deprecated_safe_2024]` is used to declare functions unsafe across the edition 2024 boundary", - ), - rustc_attr!( - rustc_pub_transparent, Normal, template!(Word), - ErrorFollowing, EncodeCrossCrate::Yes, - "used internally to mark types with a `transparent` representation when it is guaranteed by the documentation", - ), + rustc_attr!(rustc_deprecated_safe_2024, "`#[rustc_deprecated_safe_2024]` is used to declare functions unsafe across the edition 2024 boundary"), + rustc_attr!(rustc_pub_transparent, "used internally to mark types with a `transparent` representation when it is guaranteed by the documentation"), // ========================================================================== // Internal attributes: Type system related: // ========================================================================== - gated!(fundamental, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes, experimental!(fundamental)), + gated!(fundamental, experimental!(fundamental)), gated!( - may_dangle, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, dropck_eyepatch, - "`may_dangle` has unstable semantics and may be removed in the future", + may_dangle, dropck_eyepatch, + "`may_dangle` has unstable semantics and may be removed in the future" ), - rustc_attr!( - rustc_never_type_options, - Normal, - template!(List: &[ - "", - r#"fallback = "unit""#, - r#"fallback = "niko""#, - r#"fallback = "never""#, - r#"fallback = "no""#, - ]), - ErrorFollowing, - EncodeCrossCrate::No, + rustc_attr!(rustc_never_type_options, "`rustc_never_type_options` is used to experiment with never type fallback and work on \ never type stabilization" ), @@ -1003,57 +495,33 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ // Internal attributes: Runtime related: // ========================================================================== - rustc_attr!( - rustc_allocator, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, - ), - rustc_attr!( - rustc_nounwind, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, - ), - rustc_attr!( - rustc_reallocator, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, - ), - rustc_attr!( - rustc_deallocator, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, - ), - rustc_attr!( - rustc_allocator_zeroed, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, - ), - rustc_attr!( - rustc_allocator_zeroed_variant, Normal, template!(NameValueStr: "function"), ErrorPreceding, - EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_allocator), + rustc_attr!(rustc_nounwind), + rustc_attr!(rustc_reallocator), + rustc_attr!(rustc_deallocator), + rustc_attr!(rustc_allocator_zeroed), + rustc_attr!(rustc_allocator_zeroed_variant), gated!( - default_lib_allocator, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, allocator_internals, experimental!(default_lib_allocator), + default_lib_allocator, allocator_internals, experimental!(default_lib_allocator), ), gated!( - needs_allocator, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, allocator_internals, experimental!(needs_allocator), + needs_allocator, allocator_internals, experimental!(needs_allocator), ), gated!( - panic_runtime, CrateLevel, template!(Word), WarnFollowing, - EncodeCrossCrate::No, experimental!(panic_runtime) + panic_runtime, experimental!(panic_runtime) ), gated!( - needs_panic_runtime, CrateLevel, template!(Word), WarnFollowing, - EncodeCrossCrate::No, experimental!(needs_panic_runtime) + needs_panic_runtime, experimental!(needs_panic_runtime) ), gated!( - compiler_builtins, CrateLevel, template!(Word), WarnFollowing, - EncodeCrossCrate::No, + compiler_builtins, "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \ - which contains compiler-rt intrinsics and will never be stable", + which contains compiler-rt intrinsics and will never be stable" ), gated!( - profiler_runtime, CrateLevel, template!(Word), WarnFollowing, - EncodeCrossCrate::No, + profiler_runtime, "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \ - which contains the profiler runtime and will never be stable", + which contains the profiler runtime and will never be stable" ), // ========================================================================== @@ -1061,277 +529,113 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ // ========================================================================== gated!( - linkage, Normal, template!(NameValueStr: [ - "available_externally", - "common", - "extern_weak", - "external", - "internal", - "linkonce", - "linkonce_odr", - "weak", - "weak_odr", - ], "https://doc.rust-lang.org/reference/linkage.html"), - ErrorPreceding, EncodeCrossCrate::No, - "the `linkage` attribute is experimental and not portable across platforms", - ), - rustc_attr!( - rustc_std_internal_symbol, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, - ), - rustc_attr!( - rustc_objc_class, Normal, template!(NameValueStr: "ClassName"), ErrorPreceding, - EncodeCrossCrate::No, - ), - rustc_attr!( - rustc_objc_selector, Normal, template!(NameValueStr: "methodName"), ErrorPreceding, - EncodeCrossCrate::No, + linkage, + "the `linkage` attribute is experimental and not portable across platforms" ), + rustc_attr!(rustc_std_internal_symbol), + rustc_attr!(rustc_objc_class), + rustc_attr!(rustc_objc_selector), // ========================================================================== // Internal attributes, Macro related: // ========================================================================== - rustc_attr!( - rustc_builtin_macro, Normal, - template!(Word, List: &["name", "name, /*opt*/ attributes(name1, name2, ...)"]), ErrorFollowing, - EncodeCrossCrate::Yes, - ), - rustc_attr!( - rustc_proc_macro_decls, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, - ), - rustc_attr!( - rustc_macro_transparency, Normal, - template!(NameValueStr: ["transparent", "semiopaque", "opaque"]), ErrorFollowing, - EncodeCrossCrate::Yes, "used internally for testing macro hygiene", - ), - rustc_attr!( - rustc_autodiff, Normal, - template!(Word, List: &[r#""...""#]), DuplicatesOk, - EncodeCrossCrate::Yes, - ), - rustc_attr!( - rustc_offload_kernel, Normal, - template!(Word), DuplicatesOk, - EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_builtin_macro), + rustc_attr!(rustc_proc_macro_decls), + rustc_attr!(rustc_macro_transparency, "used internally for testing macro hygiene"), + rustc_attr!(rustc_autodiff), + rustc_attr!(rustc_offload_kernel), // Traces that are left when `cfg` and `cfg_attr` attributes are expanded. // The attributes are not gated, to avoid stability errors, but they cannot be used in stable // or unstable code directly because `sym::cfg_(attr_)trace` are not valid identifiers, they // can only be generated by the compiler. - ungated!( - cfg_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk, - EncodeCrossCrate::Yes - ), - ungated!( - cfg_attr_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk, - EncodeCrossCrate::No - ), + ungated!(cfg_trace), + ungated!(cfg_attr_trace), // ========================================================================== // Internal attributes, Diagnostics related: // ========================================================================== - rustc_attr!( - rustc_on_unimplemented, Normal, - template!( - List: &[r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#], - NameValueStr: "message" - ), - ErrorFollowing, EncodeCrossCrate::Yes, - "see `#[diagnostic::on_unimplemented]` for the stable equivalent of this attribute" - ), - rustc_attr!( - rustc_confusables, Normal, - template!(List: &[r#""name1", "name2", ..."#]), - ErrorFollowing, EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_on_unimplemented, "see `#[diagnostic::on_unimplemented]` for the stable equivalent of this attribute"), + rustc_attr!(rustc_confusables), // Enumerates "identity-like" conversion methods to suggest on type mismatch. - rustc_attr!( - rustc_conversion_suggestion, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_conversion_suggestion), // Prevents field reads in the marked trait or method to be considered // during dead code analysis. - rustc_attr!( - rustc_trivial_field_reads, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_trivial_field_reads), // Used by the `rustc::potential_query_instability` lint to warn methods which // might not be stable during incremental compilation. - rustc_attr!( - rustc_lint_query_instability, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_lint_query_instability), // Used by the `rustc::untracked_query_information` lint to warn methods which // might not be stable during incremental compilation. - rustc_attr!( - rustc_lint_untracked_query_information, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_lint_untracked_query_information), // Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions` // types (as well as any others in future). - rustc_attr!( - rustc_lint_opt_ty, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_lint_opt_ty), // Used by the `rustc::bad_opt_access` lint on fields // types (as well as any others in future). - rustc_attr!( - rustc_lint_opt_deny_field_access, Normal, template!(List: &["message"]), - WarnFollowing, EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_lint_opt_deny_field_access), // ========================================================================== // Internal attributes, Const related: // ========================================================================== - rustc_attr!( - rustc_promotable, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, ), - rustc_attr!( - rustc_legacy_const_generics, Normal, template!(List: &["N"]), ErrorFollowing, - EncodeCrossCrate::Yes, - ), + rustc_attr!(rustc_promotable), + rustc_attr!(rustc_legacy_const_generics), // Do not const-check this function's body. It will always get replaced during CTFE via `hook_special_const_fn`. - rustc_attr!( - rustc_do_not_const_check, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::Yes, "`#[rustc_do_not_const_check]` skips const-check for this function's body", - ), - rustc_attr!( - rustc_const_stable_indirect, Normal, - template!(Word), - WarnFollowing, - EncodeCrossCrate::No, - "this is an internal implementation detail", - ), - rustc_attr!( - rustc_intrinsic_const_stable_indirect, Normal, - template!(Word), WarnFollowing, EncodeCrossCrate::No, "this is an internal implementation detail", - ), - rustc_attr!( - rustc_allow_const_fn_unstable, Normal, - template!(Word, List: &["feat1, feat2, ..."]), DuplicatesOk, EncodeCrossCrate::No, - "rustc_allow_const_fn_unstable side-steps feature gating and stability checks" - ), + rustc_attr!(rustc_do_not_const_check, "`#[rustc_do_not_const_check]` skips const-check for this function's body"), + rustc_attr!(rustc_const_stable_indirect, "this is an internal implementation detail"), + rustc_attr!(rustc_intrinsic_const_stable_indirect, "this is an internal implementation detail"), + rustc_attr!(rustc_allow_const_fn_unstable, "rustc_allow_const_fn_unstable side-steps feature gating and stability checks"), // ========================================================================== // Internal attributes, Layout related: // ========================================================================== - rustc_attr!( - rustc_layout_scalar_valid_range_start, Normal, template!(List: &["value"]), ErrorFollowing, - EncodeCrossCrate::Yes, - "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \ - niche optimizations in the standard library", - ), - rustc_attr!( - rustc_layout_scalar_valid_range_end, Normal, template!(List: &["value"]), ErrorFollowing, - EncodeCrossCrate::Yes, - "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \ - niche optimizations in the standard library", - ), - rustc_attr!( - rustc_simd_monomorphize_lane_limit, Normal, template!(NameValueStr: "N"), ErrorFollowing, - EncodeCrossCrate::Yes, - "the `#[rustc_simd_monomorphize_lane_limit]` attribute is just used by std::simd \ - for better error messages", - ), - rustc_attr!( - rustc_nonnull_optimization_guaranteed, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::Yes, + rustc_attr!(rustc_layout_scalar_valid_range_start, "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \ + niche optimizations in the standard library"), + rustc_attr!(rustc_layout_scalar_valid_range_end, "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \ + niche optimizations in the standard library"), + rustc_attr!(rustc_simd_monomorphize_lane_limit, "the `#[rustc_simd_monomorphize_lane_limit]` attribute is just used by std::simd \ + for better error messages"), + rustc_attr!(rustc_nonnull_optimization_guaranteed, "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to document \ guaranteed niche optimizations in the standard library", "the compiler does not even check whether the type indeed is being non-null-optimized; \ - it is your responsibility to ensure that the attribute is only used on types that are optimized", + it is your responsibility to ensure that the attribute is only used on types that are optimized" ), // ========================================================================== // Internal attributes, Misc: // ========================================================================== gated!( - lang, Normal, template!(NameValueStr: "name"), DuplicatesOk, EncodeCrossCrate::No, lang_items, - "lang items are subject to change", - ), - rustc_attr!( - rustc_as_ptr, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::Yes, - "`#[rustc_as_ptr]` is used to mark functions returning pointers to their inner allocations" - ), - rustc_attr!( - rustc_should_not_be_called_on_const_items, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::Yes, - "`#[rustc_should_not_be_called_on_const_items]` is used to mark methods that don't make sense to be called on interior mutable consts" - ), - rustc_attr!( - rustc_pass_by_value, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::Yes, - "`#[rustc_pass_by_value]` is used to mark types that must be passed by value instead of reference" - ), - rustc_attr!( - rustc_never_returns_null_ptr, Normal, template!(Word), ErrorFollowing, - EncodeCrossCrate::Yes, - "`#[rustc_never_returns_null_ptr]` is used to mark functions returning non-null pointers" - ), - rustc_attr!( - rustc_no_implicit_autorefs, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, - "`#[rustc_no_implicit_autorefs]` is used to mark functions for which an autoref to the dereference of a raw pointer should not be used as an argument" - ), - rustc_attr!( - rustc_coherence_is_core, AttributeType::CrateLevel, template!(Word), ErrorFollowing, EncodeCrossCrate::No, - "`#![rustc_coherence_is_core]` allows inherent methods on builtin types, only intended to be used in `core`" - ), - rustc_attr!( - rustc_coinductive, AttributeType::Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, - "`#[rustc_coinductive]` changes a trait to be coinductive, allowing cycles in the trait solver" - ), - rustc_attr!( - rustc_allow_incoherent_impl, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::No, - "`#[rustc_allow_incoherent_impl]` has to be added to all impl items of an incoherent inherent impl" - ), - rustc_attr!( - rustc_preserve_ub_checks, AttributeType::CrateLevel, template!(Word), ErrorFollowing, EncodeCrossCrate::No, - "`#![rustc_preserve_ub_checks]` prevents the designated crate from evaluating whether UB checks are enabled when optimizing MIR", - ), - rustc_attr!( - rustc_deny_explicit_impl, - AttributeType::Normal, - template!(Word), - ErrorFollowing, - EncodeCrossCrate::No, + lang,lang_items, + "lang items are subject to change"), + rustc_attr!(rustc_as_ptr, "`#[rustc_as_ptr]` is used to mark functions returning pointers to their inner allocations"), + rustc_attr!(rustc_should_not_be_called_on_const_items, "`#[rustc_should_not_be_called_on_const_items]` is used to mark methods that don't make sense to be called on interior mutable consts"), + rustc_attr!(rustc_pass_by_value, "`#[rustc_pass_by_value]` is used to mark types that must be passed by value instead of reference"), + rustc_attr!(rustc_never_returns_null_ptr, "`#[rustc_never_returns_null_ptr]` is used to mark functions returning non-null pointers"), + rustc_attr!(rustc_no_implicit_autorefs, "`#[rustc_no_implicit_autorefs]` is used to mark functions for which an autoref to the dereference of a raw pointer should not be used as an argument"), + rustc_attr!(rustc_coherence_is_core, "`#![rustc_coherence_is_core]` allows inherent methods on builtin types, only intended to be used in `core`"), + rustc_attr!(rustc_coinductive, "`#[rustc_coinductive]` changes a trait to be coinductive, allowing cycles in the trait solver"), + rustc_attr!(rustc_allow_incoherent_impl, "`#[rustc_allow_incoherent_impl]` has to be added to all impl items of an incoherent inherent impl"), + rustc_attr!(rustc_preserve_ub_checks, "`#![rustc_preserve_ub_checks]` prevents the designated crate from evaluating whether UB checks are enabled when optimizing MIR"), + rustc_attr!(rustc_deny_explicit_impl, "`#[rustc_deny_explicit_impl]` enforces that a trait can have no user-provided impls" ), - rustc_attr!( - rustc_dyn_incompatible_trait, - AttributeType::Normal, - template!(Word), - ErrorFollowing, - EncodeCrossCrate::No, + rustc_attr!(rustc_dyn_incompatible_trait, "`#[rustc_dyn_incompatible_trait]` marks a trait as dyn-incompatible, \ even if it otherwise satisfies the requirements to be dyn-compatible." ), - rustc_attr!( - rustc_has_incoherent_inherent_impls, AttributeType::Normal, template!(Word), - ErrorFollowing, EncodeCrossCrate::Yes, - "`#[rustc_has_incoherent_inherent_impls]` allows the addition of incoherent inherent impls for \ + rustc_attr!(rustc_has_incoherent_inherent_impls, "`#[rustc_has_incoherent_inherent_impls]` allows the addition of incoherent inherent impls for \ the given type by annotating all impl items with `#[rustc_allow_incoherent_impl]`" ), - rustc_attr!( - rustc_non_const_trait_method, AttributeType::Normal, template!(Word), - ErrorFollowing, EncodeCrossCrate::No, - "`#[rustc_non_const_trait_method]` should only used by the standard library to mark trait methods \ + rustc_attr!(rustc_non_const_trait_method, "`#[rustc_non_const_trait_method]` should only used by the standard library to mark trait methods \ as non-const to allow large traits an easier transition to const" ), BuiltinAttribute { name: sym::rustc_diagnostic_item, - // FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`. - encode_cross_crate: EncodeCrossCrate::Yes, - type_: Normal, - safety: AttributeSafety::Normal, - template: template!(NameValueStr: "name"), - duplicates: ErrorFollowing, gate: Gated { feature: sym::rustc_attrs, message: "use of an internal attribute", @@ -1342,236 +646,98 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ }, gated!( // Used in resolve: - prelude_import, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, "`#[prelude_import]` is for use by rustc only", + prelude_import, "`#[prelude_import]` is for use by rustc only", ), gated!( - rustc_paren_sugar, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, - unboxed_closures, "unboxed_closures are still evolving", + rustc_paren_sugar,unboxed_closures, "unboxed_closures are still evolving", ), rustc_attr!( - rustc_inherit_overflow_checks, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, + rustc_inherit_overflow_checks, "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \ overflow checking behavior of several functions in the standard library that are inlined \ - across crates", + across crates" ), rustc_attr!( - rustc_reservation_impl, Normal, - template!(NameValueStr: "reservation message"), ErrorFollowing, EncodeCrossCrate::Yes, + rustc_reservation_impl, "the `#[rustc_reservation_impl]` attribute is internally used \ for reserving `impl From for T` as part of the effort to stabilize `!`" ), + rustc_attr!(rustc_test_marker, "the `#[rustc_test_marker]` attribute is used internally to track tests"), rustc_attr!( - rustc_test_marker, Normal, template!(NameValueStr: "name"), WarnFollowing, - EncodeCrossCrate::No, "the `#[rustc_test_marker]` attribute is used internally to track tests", - ), - rustc_attr!( - rustc_unsafe_specialization_marker, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No, + rustc_unsafe_specialization_marker, "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations" ), rustc_attr!( - rustc_specialization_trait, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No, + rustc_specialization_trait, "the `#[rustc_specialization_trait]` attribute is used to check specializations" ), rustc_attr!( - rustc_main, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, - "the `#[rustc_main]` attribute is used internally to specify test entry point function", + rustc_main, + "the `#[rustc_main]` attribute is used internally to specify test entry point function" ), rustc_attr!( - rustc_skip_during_method_dispatch, Normal, template!(List: &["array, boxed_slice"]), ErrorFollowing, - EncodeCrossCrate::No, + rustc_skip_during_method_dispatch, "the `#[rustc_skip_during_method_dispatch]` attribute is used to exclude a trait \ from method dispatch when the receiver is of the following type, for compatibility in \ editions < 2021 (array) or editions < 2024 (boxed_slice)" ), - rustc_attr!( - rustc_must_implement_one_of, Normal, template!(List: &["function1, function2, ..."]), - ErrorFollowing, EncodeCrossCrate::No, - "the `#[rustc_must_implement_one_of]` attribute is used to change minimal complete \ + rustc_attr!(rustc_must_implement_one_of, "the `#[rustc_must_implement_one_of]` attribute is used to change minimal complete \ definition of a trait. Its syntax and semantics are highly experimental and will be \ subject to change before stabilization", ), - rustc_attr!( - rustc_doc_primitive, Normal, template!(NameValueStr: "primitive name"), ErrorFollowing, - EncodeCrossCrate::Yes, "the `#[rustc_doc_primitive]` attribute is used by the standard library \ + rustc_attr!(rustc_doc_primitive, "the `#[rustc_doc_primitive]` attribute is used by the standard library \ to provide a way to generate documentation for primitive types", ), gated!( - rustc_intrinsic, Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, intrinsics, - "the `#[rustc_intrinsic]` attribute is used to declare intrinsics as function items", - ), - rustc_attr!( - rustc_no_mir_inline, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes, - "`#[rustc_no_mir_inline]` prevents the MIR inliner from inlining a function while not affecting codegen" - ), - rustc_attr!( - rustc_force_inline, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing, EncodeCrossCrate::Yes, - "`#[rustc_force_inline]` forces a free function to be inlined" - ), - rustc_attr!( - rustc_scalable_vector, Normal, template!(List: &["count"]), WarnFollowing, EncodeCrossCrate::Yes, - "`#[rustc_scalable_vector]` defines a scalable vector type" + rustc_intrinsic,intrinsics, + "the `#[rustc_intrinsic]` attribute is used to declare intrinsics as function items" ), + rustc_attr!(rustc_no_mir_inline, "`#[rustc_no_mir_inline]` prevents the MIR inliner from inlining a function while not affecting codegen"), + rustc_attr!(rustc_force_inline, "`#[rustc_force_inline]` forces a free function to be inlined"), + rustc_attr!(rustc_scalable_vector, "`#[rustc_scalable_vector]` defines a scalable vector type"), // ========================================================================== // Internal attributes, Testing: // ========================================================================== - rustc_attr!(TEST, rustc_effective_visibility, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes), - rustc_attr!( - TEST, rustc_dump_inferred_outlives, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_capture_analysis, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_insignificant_dtor, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::Yes - ), - rustc_attr!( - TEST, rustc_no_implicit_bounds, CrateLevel, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_strict_coherence, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::Yes - ), - rustc_attr!( - TEST, rustc_dump_variances, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_dump_variances_of_opaques, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_hidden_type_of_opaques, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_layout, Normal, template!(List: &["field1, field2, ..."]), - WarnFollowing, EncodeCrossCrate::Yes - ), - rustc_attr!( - TEST, rustc_abi, Normal, template!(List: &["field1, field2, ..."]), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_regions, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_delayed_bug_from_inside_query, Normal, - template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_dump_user_args, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_evaluate_where_clauses, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::Yes - ), - rustc_attr!( - TEST, rustc_if_this_changed, Normal, template!(Word, List: &["DepNode"]), DuplicatesOk, - EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_then_this_would_need, Normal, template!(List: &["DepNode"]), DuplicatesOk, - EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_clean, Normal, - template!(List: &[r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#]), - DuplicatesOk, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_partition_reused, Normal, - template!(List: &[r#"cfg = "...", module = "...""#]), DuplicatesOk, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_partition_codegened, Normal, - template!(List: &[r#"cfg = "...", module = "...""#]), DuplicatesOk, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_expected_cgu_reuse, Normal, - template!(List: &[r#"cfg = "...", module = "...", kind = "...""#]), DuplicatesOk, - EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_symbol_name, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_def_path, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_mir, Normal, template!(List: &["arg1, arg2, ..."]), - DuplicatesOk, EncodeCrossCrate::Yes - ), - gated!( - custom_mir, Normal, template!(List: &[r#"dialect = "...", phase = "...""#]), - ErrorFollowing, EncodeCrossCrate::No, - "the `#[custom_mir]` attribute is just used for the Rust test suite", - ), - rustc_attr!( - TEST, rustc_dump_item_bounds, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_dump_predicates, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_dump_def_parents, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_dump_object_lifetime_defaults, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_dump_vtable, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/), - DuplicatesOk, EncodeCrossCrate::No - ), - rustc_attr!( - TEST, pattern_complexity_limit, CrateLevel, template!(NameValueStr: "N"), - ErrorFollowing, EncodeCrossCrate::No, - ), + rustc_attr!(TEST, rustc_effective_visibility), + rustc_attr!(TEST, rustc_dump_inferred_outlives), + rustc_attr!(TEST, rustc_capture_analysis), + rustc_attr!(TEST, rustc_insignificant_dtor), + rustc_attr!(TEST, rustc_no_implicit_bounds), + rustc_attr!(TEST, rustc_strict_coherence), + rustc_attr!(TEST, rustc_dump_variances), + rustc_attr!(TEST, rustc_dump_variances_of_opaques), + rustc_attr!(TEST, rustc_hidden_type_of_opaques), + rustc_attr!(TEST, rustc_layout), + rustc_attr!(TEST, rustc_abi), + rustc_attr!(TEST, rustc_regions), + rustc_attr!(TEST, rustc_delayed_bug_from_inside_query), + rustc_attr!(TEST, rustc_dump_user_args), + rustc_attr!(TEST, rustc_evaluate_where_clauses), + rustc_attr!(TEST, rustc_if_this_changed), + rustc_attr!(TEST, rustc_then_this_would_need), + rustc_attr!(TEST, rustc_clean), + rustc_attr!(TEST, rustc_partition_reused), + rustc_attr!(TEST, rustc_partition_codegened), + rustc_attr!(TEST, rustc_expected_cgu_reuse), + rustc_attr!(TEST, rustc_symbol_name), + rustc_attr!(TEST, rustc_def_path), + rustc_attr!(TEST, rustc_mir), + gated!(custom_mir, "the `#[custom_mir]` attribute is just used for the Rust test suite"), + rustc_attr!(TEST, rustc_dump_item_bounds), + rustc_attr!(TEST, rustc_dump_predicates), + rustc_attr!(TEST, rustc_dump_def_parents), + rustc_attr!(TEST, rustc_dump_object_lifetime_defaults), + rustc_attr!(TEST, rustc_dump_vtable), + rustc_attr!(TEST, rustc_dummy), + rustc_attr!(TEST, pattern_complexity_limit), ]; pub fn is_builtin_attr_name(name: Symbol) -> bool { BUILTIN_ATTRIBUTE_MAP.get(&name).is_some() } -/// Whether this builtin attribute is encoded cross crate. -/// This means it can be used cross crate. -pub fn encode_cross_crate(name: Symbol) -> bool { - if let Some(attr) = BUILTIN_ATTRIBUTE_MAP.get(&name) { - attr.encode_cross_crate == EncodeCrossCrate::Yes - } else { - true - } -} - -pub fn is_valid_for_get_attr(name: Symbol) -> bool { - BUILTIN_ATTRIBUTE_MAP.get(&name).is_some_and(|attr| match attr.duplicates { - WarnFollowing | ErrorFollowing | ErrorPreceding | FutureWarnFollowing - | FutureWarnPreceding => true, - DuplicatesOk | WarnFollowingWordOnly => false, - }) -} - pub static BUILTIN_ATTRIBUTE_MAP: LazyLock> = LazyLock::new(|| { let mut map = FxHashMap::default(); diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index 9d046bdef1cf3..5a7f33d50bc30 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -129,10 +129,9 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option Diagnostic<'a, ()> for DecorateAttrLint<'_, '_, '_> { &AttributeLintKind::UnusedDuplicate { this, other, warning } => { lints::UnusedDuplicate { this, other, warning }.into_diag(dcx, level) } - AttributeLintKind::IllFormedAttributeInput { suggestions, docs } => { + AttributeLintKind::IllFormedAttributeInput { suggestions, docs, help } => { lints::IllFormedAttributeInput { num_suggestions: suggestions.len(), suggestions: DiagArgValue::StrListSepByAnd( @@ -145,6 +145,7 @@ impl<'a> Diagnostic<'a, ()> for DecorateAttrLint<'_, '_, '_> { ), has_docs: docs.is_some(), docs: docs.unwrap_or(""), + help: help.clone().map(|h| lints::IllFormedAttributeInputHelp { lint: h }), } .into_diag(dcx, level) } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 5819f2bc151f9..ccee479f0ef6a 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -3009,6 +3009,16 @@ pub(crate) struct IllFormedAttributeInput { #[note("for more information, visit <{$docs}>")] pub has_docs: bool, pub docs: &'static str, + #[subdiagnostic] + pub help: Option, +} + +#[derive(Subdiagnostic)] +#[help( + "if you meant to silence a warning, consider using #![allow({$lint})] or #![expect({$lint})]" +)] +pub(crate) struct IllFormedAttributeInputHelp { + pub lint: String, } #[derive(Diagnostic)] diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 7e51029b02bb6..d00cd59ab13dc 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -690,6 +690,7 @@ pub enum AttributeLintKind { IllFormedAttributeInput { suggestions: Vec, docs: Option<&'static str>, + help: Option, }, EmptyAttribute { first_span: Span, diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 8bf919dab8e79..3f8c11a87e85b 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -864,10 +864,6 @@ fn analyze_attr(attr: &hir::Attribute, state: &mut AnalyzeAttrState<'_>) -> bool && p.encode_cross_crate() == EncodeCrossCrate::No { // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates. - } else if let Some(name) = attr.name() - && !rustc_feature::encode_cross_crate(name) - { - // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates. } else if let hir::Attribute::Parsed(AttributeKind::DocComment { .. }) = attr { // We keep all doc comments reachable to rustdoc because they might be "imported" into // downstream crates if they use `#[doc(inline)]` to copy an item's documentation into diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 822bbe079327f..82b081c1ab3a8 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1725,13 +1725,8 @@ impl<'tcx> TyCtxt<'tcx> { #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to call rustc_hir::find_attr! instead."] pub fn get_attr(self, did: impl Into, attr: Symbol) -> Option<&'tcx hir::Attribute> { - if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) { - let did: DefId = did.into(); - bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr); - } else { - #[allow(deprecated)] - self.get_attrs(did, attr).next() - } + #[allow(deprecated)] + self.get_attrs(did, attr).next() } /// Determines whether an item is annotated with an attribute. diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 621ceeffac658..0e0715a8861bc 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1640,6 +1640,9 @@ impl<'tcx> Ty<'tcx> { TyKind::Coroutine(def_id, args) => { Some(args.as_coroutine().variant_range(*def_id, tcx)) } + TyKind::UnsafeBinder(bound_ty) => { + tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).variant_range(tcx) + } _ => None, } } @@ -1661,6 +1664,9 @@ impl<'tcx> Ty<'tcx> { TyKind::Coroutine(def_id, args) => { Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index)) } + TyKind::UnsafeBinder(bound_ty) => tcx + .instantiate_bound_regions_with_erased((*bound_ty).into()) + .discriminant_for_variant(tcx, variant_index), _ => None, } } @@ -1679,6 +1685,9 @@ impl<'tcx> Ty<'tcx> { } ty::Pat(ty, _) => ty.discriminant_ty(tcx), + ty::UnsafeBinder(bound_ty) => { + tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).discriminant_ty(tcx) + } ty::Bool | ty::Char @@ -1700,7 +1709,6 @@ impl<'tcx> Ty<'tcx> { | ty::CoroutineWitness(..) | ty::Never | ty::Tuple(_) - | ty::UnsafeBinder(_) | ty::Error(_) | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8, diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 79b79db6ccc07..e2f0f8fee0d8d 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -192,7 +192,22 @@ impl<'a> Parser<'a> { // At this point, we have failed to parse an item. if !matches!(vis.kind, VisibilityKind::Inherited) { - this.dcx().emit_err(errors::VisibilityNotFollowedByItem { span: vis.span, vis }); + let mut err = this + .dcx() + .create_err(errors::VisibilityNotFollowedByItem { span: vis.span, vis }); + if let Some((ident, _)) = this.token.ident() + && !ident.is_used_keyword() + && let Some((similar_kw, is_incorrect_case)) = ident + .name + .find_similar(&rustc_span::symbol::used_keywords(|| ident.span.edition())) + { + err.subdiagnostic(errors::MisspelledKw { + similar_kw: similar_kw.to_string(), + span: ident.span, + is_incorrect_case, + }); + } + err.emit(); } if let Defaultness::Default(span) = def { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 12b583d8fee15..3e3810b7f1257 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -6,17 +6,15 @@ //! item. use std::cell::Cell; -use std::collections::hash_map::Entry; use std::slice; use rustc_abi::ExternAbi; use rustc_ast::ast; use rustc_attr_parsing::{AttributeParser, Late}; -use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::thin_vec::ThinVec; use rustc_data_structures::unord::UnordMap; use rustc_errors::{DiagCtxtHandle, IntoDiagArg, MultiSpan, msg}; -use rustc_feature::{AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute}; +use rustc_feature::BUILTIN_ATTRIBUTE_MAP; use rustc_hir::attrs::diagnostic::Directive; use rustc_hir::attrs::{ AttributeKind, CrateType, DocAttribute, DocInline, EiiDecl, EiiImpl, EiiImplResolution, @@ -137,7 +135,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { target: Target, item: Option>, ) { - let mut seen = FxHashMap::default(); let attrs = self.tcx.hir_attrs(hir_id); for attr in attrs { match attr { @@ -404,64 +401,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - if hir_id != CRATE_HIR_ID { - match attr { - Attribute::Parsed(_) => { /* Already validated. */ } - Attribute::Unparsed(attr) => { - // FIXME(jdonszelmann): remove once all crate-level attrs are parsed and caught by - // the above - if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) = - attr.path - .segments - .first() - .and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name)) - { - match attr.style { - ast::AttrStyle::Outer => { - let attr_span = attr.span; - let bang_position = self - .tcx - .sess - .source_map() - .span_until_char(attr_span, '[') - .shrink_to_hi(); - - self.tcx.emit_node_span_lint( - UNUSED_ATTRIBUTES, - hir_id, - attr.span, - errors::OuterCrateLevelAttr { - suggestion: errors::OuterCrateLevelAttrSuggestion { - bang_position, - }, - }, - ) - } - ast::AttrStyle::Inner => self.tcx.emit_node_span_lint( - UNUSED_ATTRIBUTES, - hir_id, - attr.span, - errors::InnerCrateLevelAttr, - ), - } - } - } - } - } - - if let Attribute::Unparsed(unparsed_attr) = attr - && let Some(BuiltinAttribute { duplicates, .. }) = - attr.name().and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name)) - { - check_duplicates( - self.tcx, - unparsed_attr.span, - attr, - hir_id, - *duplicates, - &mut seen, - ); - } self.check_unused_attribute(hir_id, attr) } @@ -1994,67 +1933,6 @@ pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { check_mod_attrs, ..*providers }; } -// FIXME(jdonszelmann): remove, check during parsing -fn check_duplicates( - tcx: TyCtxt<'_>, - attr_span: Span, - attr: &Attribute, - hir_id: HirId, - duplicates: AttributeDuplicates, - seen: &mut FxHashMap, -) { - use AttributeDuplicates::*; - if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() { - return; - } - let attr_name = attr.name().unwrap(); - match duplicates { - DuplicatesOk => {} - WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => { - match seen.entry(attr_name) { - Entry::Occupied(mut entry) => { - let (this, other) = if matches!(duplicates, FutureWarnPreceding) { - let to_remove = entry.insert(attr_span); - (to_remove, attr_span) - } else { - (attr_span, *entry.get()) - }; - tcx.emit_node_span_lint( - UNUSED_ATTRIBUTES, - hir_id, - this, - errors::UnusedDuplicate { - this, - other, - warning: matches!( - duplicates, - FutureWarnFollowing | FutureWarnPreceding - ), - }, - ); - } - Entry::Vacant(entry) => { - entry.insert(attr_span); - } - } - } - ErrorFollowing | ErrorPreceding => match seen.entry(attr_name) { - Entry::Occupied(mut entry) => { - let (this, other) = if matches!(duplicates, ErrorPreceding) { - let to_remove = entry.insert(attr_span); - (to_remove, attr_span) - } else { - (attr_span, *entry.get()) - }; - tcx.dcx().emit_err(errors::UnusedMultiple { this, other, name: attr_name }); - } - Entry::Vacant(entry) => { - entry.insert(attr_span); - } - }, - } -} - fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool { matches!(&self_ty.kind, hir::TyKind::Tup([_])) || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind { diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 628d0b0c961a1..46b96ff1da353 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -326,30 +326,6 @@ pub(crate) struct InvalidMayDangle { pub attr_span: Span, } -#[derive(Diagnostic)] -#[diag("unused attribute")] -pub(crate) struct UnusedDuplicate { - #[suggestion("remove this attribute", code = "", applicability = "machine-applicable")] - pub this: Span, - #[note("attribute also specified here")] - pub other: Span, - #[warning( - "this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!" - )] - pub warning: bool, -} - -#[derive(Diagnostic)] -#[diag("multiple `{$name}` attributes")] -pub(crate) struct UnusedMultiple { - #[primary_span] - #[suggestion("remove this attribute", code = "", applicability = "machine-applicable")] - pub this: Span, - #[note("attribute also specified here")] - pub other: Span, - pub name: Symbol, -} - #[derive(Diagnostic)] #[diag("this `#[deprecated]` annotation has no effect")] pub(crate) struct DeprecatedAnnotationHasNoEffect { diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index aff10c4320fe1..344b46f01b756 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -93,6 +93,7 @@ #![feature(async_iterator)] #![feature(bstr)] #![feature(bstr_internals)] +#![feature(case_ignorable)] #![feature(cast_maybe_uninit)] #![feature(cell_get_cloned)] #![feature(char_internals)] diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index 46d48afbf5a14..ce33fd1d8f9df 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -1074,18 +1074,20 @@ impl char { self > '\u{02FF}' && unicode::Grapheme_Extend(self) } - /// Returns `true` if this `char` has the `Case_Ignorable` property. + /// Returns `true` if this `char` has the `Case_Ignorable` property. This narrow-use property + /// is used to implement context-dependent casing for the Greek letter sigma (uppercase Σ), + /// which has two lowercase forms. /// - /// `Case_Ignorable` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and - /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`]. + /// `Case_Ignorable` is [described][D136] in Chapter 3 (Conformance) of the Unicode Core Specification, + /// and specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`]; + /// see those resources for more information. /// - /// [Unicode Standard]: https://www.unicode.org/versions/latest/ + /// [D136]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G63116 /// [ucd]: https://www.unicode.org/reports/tr44/ /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt #[must_use] #[inline] - #[doc(hidden)] - #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] + #[unstable(feature = "case_ignorable", issue = "154848")] pub fn is_case_ignorable(self) -> bool { if self.is_ascii() { matches!(self, '\'' | '.' | ':' | '^' | '`') diff --git a/tests/ui/malformed/ignore-with-lint-name.rs b/tests/ui/malformed/ignore-with-lint-name.rs new file mode 100644 index 0000000000000..eb023ea81d572 --- /dev/null +++ b/tests/ui/malformed/ignore-with-lint-name.rs @@ -0,0 +1,6 @@ +#[ignore(clippy::single_match)] +//~^ ERROR valid forms for the attribute are `#[ignore = "reason"]` and `#[ignore]` +//~| HELP if you meant to silence a warning, consider using #![allow(clippy::single_match)] or #![expect(clippy::single_match)] +//~| WARN this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +fn main() {} diff --git a/tests/ui/malformed/ignore-with-lint-name.stderr b/tests/ui/malformed/ignore-with-lint-name.stderr new file mode 100644 index 0000000000000..a2f251de6fcc3 --- /dev/null +++ b/tests/ui/malformed/ignore-with-lint-name.stderr @@ -0,0 +1,25 @@ +error: valid forms for the attribute are `#[ignore = "reason"]` and `#[ignore]` + --> $DIR/ignore-with-lint-name.rs:1:1 + | +LL | #[ignore(clippy::single_match)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: if you meant to silence a warning, consider using #![allow(clippy::single_match)] or #![expect(clippy::single_match)] + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 + = note: `#[deny(ill_formed_attribute_input)]` (part of `#[deny(future_incompatible)]`) on by default + +error: aborting due to 1 previous error + +Future incompatibility report: Future breakage diagnostic: +error: valid forms for the attribute are `#[ignore = "reason"]` and `#[ignore]` + --> $DIR/ignore-with-lint-name.rs:1:1 + | +LL | #[ignore(clippy::single_match)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: if you meant to silence a warning, consider using #![allow(clippy::single_match)] or #![expect(clippy::single_match)] + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57571 + = note: `#[deny(ill_formed_attribute_input)]` (part of `#[deny(future_incompatible)]`) on by default + diff --git a/tests/ui/moves/assign-value-after-at-pattern-issue-145564.fixed b/tests/ui/moves/assign-value-after-at-pattern-issue-145564.fixed new file mode 100644 index 0000000000000..2a1584d37e70a --- /dev/null +++ b/tests/ui/moves/assign-value-after-at-pattern-issue-145564.fixed @@ -0,0 +1,19 @@ +//@ run-rustfix +#![allow(unused_variables)] + +fn main() { + let ref mut x @ _v = 42; + *x = 1; //~ ERROR used binding `x` isn't initialized + + let a @ _b: i32 = 42; + println!("{}", a); //~ ERROR used binding `a` isn't initialized + + let ref c @ _d: i32 = 42; + println!("{:?}", c); //~ ERROR used binding `c` isn't initialized + + let ref e: i32 = 42; + println!("{:?}", e); //~ ERROR used binding `e` isn't initialized + + let ref mut y = 42; + *y = 1; //~ ERROR used binding `y` isn't initialized +} diff --git a/tests/ui/moves/assign-value-after-at-pattern-issue-145564.rs b/tests/ui/moves/assign-value-after-at-pattern-issue-145564.rs new file mode 100644 index 0000000000000..101a77fac1cec --- /dev/null +++ b/tests/ui/moves/assign-value-after-at-pattern-issue-145564.rs @@ -0,0 +1,19 @@ +//@ run-rustfix +#![allow(unused_variables)] + +fn main() { + let ref mut x @ _v; + *x = 1; //~ ERROR used binding `x` isn't initialized + + let a @ _b: i32; + println!("{}", a); //~ ERROR used binding `a` isn't initialized + + let ref c @ _d: i32; + println!("{:?}", c); //~ ERROR used binding `c` isn't initialized + + let ref e: i32; + println!("{:?}", e); //~ ERROR used binding `e` isn't initialized + + let ref mut y; + *y = 1; //~ ERROR used binding `y` isn't initialized +} diff --git a/tests/ui/moves/assign-value-after-at-pattern-issue-145564.stderr b/tests/ui/moves/assign-value-after-at-pattern-issue-145564.stderr new file mode 100644 index 0000000000000..5bfde08045d74 --- /dev/null +++ b/tests/ui/moves/assign-value-after-at-pattern-issue-145564.stderr @@ -0,0 +1,68 @@ +error[E0381]: used binding `x` isn't initialized + --> $DIR/assign-value-after-at-pattern-issue-145564.rs:6:5 + | +LL | let ref mut x @ _v; + | --------- binding declared here but left uninitialized +LL | *x = 1; + | ^^^^^^ `x` used here but it isn't initialized + | +help: consider assigning a value + | +LL | let ref mut x @ _v = 42; + | ++++ + +error[E0381]: used binding `a` isn't initialized + --> $DIR/assign-value-after-at-pattern-issue-145564.rs:9:20 + | +LL | let a @ _b: i32; + | - binding declared here but left uninitialized +LL | println!("{}", a); + | ^ `a` used here but it isn't initialized + | +help: consider assigning a value + | +LL | let a @ _b: i32 = 42; + | ++++ + +error[E0381]: used binding `c` isn't initialized + --> $DIR/assign-value-after-at-pattern-issue-145564.rs:12:22 + | +LL | let ref c @ _d: i32; + | ----- binding declared here but left uninitialized +LL | println!("{:?}", c); + | ^ `c` used here but it isn't initialized + | +help: consider assigning a value + | +LL | let ref c @ _d: i32 = 42; + | ++++ + +error[E0381]: used binding `e` isn't initialized + --> $DIR/assign-value-after-at-pattern-issue-145564.rs:15:22 + | +LL | let ref e: i32; + | ----- binding declared here but left uninitialized +LL | println!("{:?}", e); + | ^ `e` used here but it isn't initialized + | +help: consider assigning a value + | +LL | let ref e: i32 = 42; + | ++++ + +error[E0381]: used binding `y` isn't initialized + --> $DIR/assign-value-after-at-pattern-issue-145564.rs:18:5 + | +LL | let ref mut y; + | --------- binding declared here but left uninitialized +LL | *y = 1; + | ^^^^^^ `y` used here but it isn't initialized + | +help: consider assigning a value + | +LL | let ref mut y = 42; + | ++++ + +error: aborting due to 5 previous errors + +For more information about this error, try `rustc --explain E0381`. diff --git a/tests/ui/parser/misspelled-keywords/pub-const-fn.rs b/tests/ui/parser/misspelled-keywords/pub-const-fn.rs new file mode 100644 index 0000000000000..1a291cdee32d8 --- /dev/null +++ b/tests/ui/parser/misspelled-keywords/pub-const-fn.rs @@ -0,0 +1,5 @@ +pub cnst fn code() {} +//~^ ERROR visibility `pub` is not followed by an item +//~| ERROR expected item, found `cnst` + +fn main() {} diff --git a/tests/ui/parser/misspelled-keywords/pub-const-fn.stderr b/tests/ui/parser/misspelled-keywords/pub-const-fn.stderr new file mode 100644 index 0000000000000..c9b70a77f5d1f --- /dev/null +++ b/tests/ui/parser/misspelled-keywords/pub-const-fn.stderr @@ -0,0 +1,22 @@ +error: visibility `pub` is not followed by an item + --> $DIR/pub-const-fn.rs:1:1 + | +LL | pub cnst fn code() {} + | ^^^ the visibility + | + = help: you likely meant to define an item, e.g., `pub fn foo() {}` +help: there is a keyword `const` with a similar name + | +LL | pub const fn code() {} + | + + +error: expected item, found `cnst` + --> $DIR/pub-const-fn.rs:1:5 + | +LL | pub cnst fn code() {} + | ^^^^ expected item + | + = note: for a full list of items that can appear in modules, see + +error: aborting due to 2 previous errors + diff --git a/tests/ui/unsafe-binders/discriminant-for-variant.rs b/tests/ui/unsafe-binders/discriminant-for-variant.rs new file mode 100644 index 0000000000000..6a2ef22e92628 --- /dev/null +++ b/tests/ui/unsafe-binders/discriminant-for-variant.rs @@ -0,0 +1,11 @@ +#![feature(unsafe_binders)] + +const None: Option Option>> = None; +//~^ ERROR the trait bound `Box<(dyn Send + 'static)>: Copy` is not satisfied +//~| ERROR the trait bound `Box<(dyn Send + 'static)>: Copy` is not satisfied + +fn main() { + match None { + _ => {} + } +} diff --git a/tests/ui/unsafe-binders/discriminant-for-variant.stderr b/tests/ui/unsafe-binders/discriminant-for-variant.stderr new file mode 100644 index 0000000000000..ed1a38ae14e40 --- /dev/null +++ b/tests/ui/unsafe-binders/discriminant-for-variant.stderr @@ -0,0 +1,19 @@ +error[E0277]: the trait bound `Box<(dyn Send + 'static)>: Copy` is not satisfied + --> $DIR/discriminant-for-variant.rs:3:13 + | +LL | const None: Option Option>> = None; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `Box<(dyn Send + 'static)>` + | + = note: required for `Option>` to implement `Copy` + +error[E0277]: the trait bound `Box<(dyn Send + 'static)>: Copy` is not satisfied + --> $DIR/discriminant-for-variant.rs:3:54 + | +LL | const None: Option Option>> = None; + | ^^^^ the trait `Copy` is not implemented for `Box<(dyn Send + 'static)>` + | + = note: required for `Option>` to implement `Copy` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`.