diff --git a/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs b/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs index 5610ef6a83dc0..743d3c9b5e76e 100644 --- a/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs +++ b/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs @@ -4,7 +4,7 @@ use rustc_feature::AttributeStability; use super::macro_attrs::check_macro_only; use super::prelude::*; -use crate::session_diagnostics; +use crate::diagnostics; pub(crate) struct AllowInternalUnstableParser; impl CombineAttributeParser for AllowInternalUnstableParser { @@ -92,7 +92,7 @@ fn parse_unstable( let mut res = Vec::new(); let Some(list) = args.as_list() else { - cx.emit_err(session_diagnostics::ExpectsFeatureList { + cx.emit_err(diagnostics::ExpectsFeatureList { span: cx.attr_span, name: symbol.to_ident_string(), }); @@ -104,7 +104,7 @@ fn parse_unstable( if let Some(ident) = param.meta_item_no_args().and_then(|i| i.path().word()) { res.push(ident.name); } else { - cx.emit_err(session_diagnostics::ExpectsFeatures { + cx.emit_err(diagnostics::ExpectsFeatures { span: param_span, name: symbol.to_ident_string(), }); diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index ef37027f07b96..9ac15a5dc87b7 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -19,16 +19,14 @@ use thin_vec::ThinVec; use crate::attributes::AttributeSafety; use crate::context::{AcceptContext, ShouldEmit}; -use crate::parser::{ - AllowExprMetavar, ArgParser, MetaItemListParser, MetaItemOrLitParser, NameValueParser, -}; -use crate::session_diagnostics::{ +use crate::diagnostics::{ AttributeParseError, AttributeParseErrorReason, CfgAttrBadDelim, MetaBadDelimSugg, ParsedDescription, }; -use crate::{ - AttributeParser, AttributeTemplate, check_cfg, parse_version, session_diagnostics, template, +use crate::parser::{ + AllowExprMetavar, ArgParser, MetaItemListParser, MetaItemOrLitParser, NameValueParser, }; +use crate::{AttributeParser, AttributeTemplate, check_cfg, diagnostics, parse_version, template}; pub const CFG_TEMPLATE: AttributeTemplate = template!( List: &["predicate"], @@ -131,25 +129,17 @@ fn parse_cfg_entry_version( ) -> Result { try_gate_cfg(sym::version, meta_span, cx.sess(), cx.features_option()); let Some(version) = list.as_single() else { - return Err( - cx.emit_err(session_diagnostics::ExpectedSingleVersionLiteral { span: list.span }) - ); + return Err(cx.emit_err(diagnostics::ExpectedSingleVersionLiteral { span: list.span })); }; let Some(version_lit) = version.as_lit() else { - return Err( - cx.emit_err(session_diagnostics::ExpectedVersionLiteral { span: version.span() }) - ); + return Err(cx.emit_err(diagnostics::ExpectedVersionLiteral { span: version.span() })); }; let Some(version_str) = version_lit.value_as_str() else { - return Err( - cx.emit_err(session_diagnostics::ExpectedVersionLiteral { span: version_lit.span }) - ); + return Err(cx.emit_err(diagnostics::ExpectedVersionLiteral { span: version_lit.span })); }; let min_version = parse_version(version_str).or_else(|| { - cx.sess() - .dcx() - .emit_warn(session_diagnostics::UnknownVersionLiteral { span: version_lit.span }); + cx.sess().dcx().emit_warn(diagnostics::UnknownVersionLiteral { span: version_lit.span }); None }); @@ -362,7 +352,7 @@ pub fn parse_cfg_attr( path: AttrPath::from_ast(&cfg_attr.get_normal_item().path, identity), description: ParsedDescription::Attribute, reason, - suggestions: session_diagnostics::AttributeParseErrorSuggestions::CreatedByTemplate( + suggestions: diagnostics::AttributeParseErrorSuggestions::CreatedByTemplate( CFG_ATTR_TEMPLATE.suggestions( ParsedDescription::Attribute, cfg_attr.get_normal_item().unsafety, diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index d9ae0aa0b2307..1e56b65c633b1 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -8,7 +8,7 @@ use rustc_span::edition::Edition::Edition2024; use super::prelude::*; use crate::attributes::AttributeSafety; -use crate::session_diagnostics::{ +use crate::diagnostics::{ EmptyExportName, EmptySection, NakedFunctionIncompatibleAttribute, NullOnExport, NullOnObjcClass, NullOnObjcSelector, NullOnSection, ObjcClassExpectedStringLiteral, ObjcSelectorExpectedStringLiteral, SanitizeInvalidStatic, TargetFeatureOnLangItem, diff --git a/compiler/rustc_attr_parsing/src/attributes/confusables.rs b/compiler/rustc_attr_parsing/src/attributes/confusables.rs index 091566012d158..780e7fc1333b6 100644 --- a/compiler/rustc_attr_parsing/src/attributes/confusables.rs +++ b/compiler/rustc_attr_parsing/src/attributes/confusables.rs @@ -1,7 +1,7 @@ use rustc_feature::AttributeStability; use super::prelude::*; -use crate::session_diagnostics::EmptyConfusables; +use crate::diagnostics::EmptyConfusables; #[derive(Default)] pub(crate) struct ConfusablesParser { diff --git a/compiler/rustc_attr_parsing/src/attributes/deprecation.rs b/compiler/rustc_attr_parsing/src/attributes/deprecation.rs index 46f99691b602d..c3fadb9f41489 100644 --- a/compiler/rustc_attr_parsing/src/attributes/deprecation.rs +++ b/compiler/rustc_attr_parsing/src/attributes/deprecation.rs @@ -5,9 +5,7 @@ use rustc_hir::attrs::{DeprecatedSince, Deprecation, RustcVersion}; use super::prelude::*; use super::util::parse_version; -use crate::session_diagnostics::{ - DeprecatedItemSuggestion, InvalidSince, MissingNote, MissingSince, -}; +use crate::diagnostics::{DeprecatedItemSuggestion, InvalidSince, MissingNote, MissingSince}; fn get( cx: &mut AcceptContext<'_, '_>, diff --git a/compiler/rustc_attr_parsing/src/attributes/doc.rs b/compiler/rustc_attr_parsing/src/attributes/doc.rs index cba00f5f068a6..897dea6cd49f9 100644 --- a/compiler/rustc_attr_parsing/src/attributes/doc.rs +++ b/compiler/rustc_attr_parsing/src/attributes/doc.rs @@ -14,20 +14,18 @@ use super::prelude::{ALL_TARGETS, AllowedTargets}; use super::{AcceptMapping, AttributeParser, template}; use crate::context::{AcceptContext, FinalizeContext}; use crate::diagnostics::{ - AttrCrateLevelOnly, DocAliasDuplicated, DocAutoCfgExpectsHideOrShow, + AttrCrateLevelOnly, DocAliasBadChar, DocAliasDuplicated, DocAliasEmpty, DocAliasMalformed, + DocAliasStartEnd, DocAttrNotCrateLevel, DocAttributeNotAttribute, DocAutoCfgExpectsHideOrShow, DocAutoCfgHideShowExpectsList, DocAutoCfgHideShowNoIdentBeforeValues, DocAutoCfgHideShowUnexpectedItem, DocAutoCfgHideShowUnexpectedItemAfterValues, - DocAutoCfgHideShowValuesMix, DocAutoCfgWrongLiteral, DocTestLiteral, DocTestTakesList, - DocTestUnknown, DocUnknownAny, DocUnknownInclude, DocUnknownPasses, DocUnknownPlugins, - DocUnknownSpotlight, ExpectedNameValue, ExpectedNoArgs, IllFormedAttributeInput, MalformedDoc, + DocAutoCfgHideShowValuesMix, DocAutoCfgWrongLiteral, DocKeywordNotKeyword, DocTestLiteral, + DocTestTakesList, DocTestUnknown, DocUnknownAny, DocUnknownInclude, DocUnknownPasses, + DocUnknownPlugins, DocUnknownSpotlight, ExpectedNameValue, ExpectedNoArgs, + IllFormedAttributeInput, MalformedDoc, UnusedDuplicate, }; use crate::parser::{ ArgParser, MetaItemListParser, MetaItemOrLitParser, MetaItemParser, OwnedPathParser, }; -use crate::session_diagnostics::{ - DocAliasBadChar, DocAliasEmpty, DocAliasMalformed, DocAliasStartEnd, DocAttrNotCrateLevel, - DocAttributeNotAttribute, DocKeywordNotKeyword, UnusedDuplicate, -}; fn check_keyword(cx: &mut AcceptContext<'_, '_>, keyword: Symbol, span: Span) -> bool { // FIXME: Once rustdoc can handle URL conflicts on case insensitive file systems, we diff --git a/compiler/rustc_attr_parsing/src/attributes/inline.rs b/compiler/rustc_attr_parsing/src/attributes/inline.rs index 52960ae220a59..c3972b23eb101 100644 --- a/compiler/rustc_attr_parsing/src/attributes/inline.rs +++ b/compiler/rustc_attr_parsing/src/attributes/inline.rs @@ -4,7 +4,7 @@ use rustc_hir::find_attr; use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT; use super::prelude::*; -use crate::session_diagnostics::InlineForceInlineConflict; +use crate::diagnostics::InlineForceInlineConflict; pub(crate) struct InlineParser; diff --git a/compiler/rustc_attr_parsing/src/attributes/instruction_set.rs b/compiler/rustc_attr_parsing/src/attributes/instruction_set.rs index 3a4bb926f759c..afca9845f8cbe 100644 --- a/compiler/rustc_attr_parsing/src/attributes/instruction_set.rs +++ b/compiler/rustc_attr_parsing/src/attributes/instruction_set.rs @@ -2,7 +2,7 @@ use rustc_feature::AttributeStability; use rustc_hir::attrs::InstructionSetAttr; use super::prelude::*; -use crate::session_diagnostics; +use crate::diagnostics; pub(crate) struct InstructionSetParser; @@ -43,7 +43,7 @@ impl SingleAttributeParser for InstructionSetParser { let instruction_set = match architecture.name { sym::arm => { if !cx.sess.target.has_thumb_interworking { - cx.dcx().emit_err(session_diagnostics::UnsupportedInstructionSet { + cx.dcx().emit_err(diagnostics::UnsupportedInstructionSet { span: cx.attr_span, instruction_set: sym::arm, current_target: &cx.sess.opts.target_triple, diff --git a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs index 935265924d7da..ed44cb1d5afc9 100644 --- a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs @@ -13,7 +13,7 @@ use super::prelude::*; use super::util::parse_single_integer; use crate::attributes::AttributeSafety; use crate::attributes::cfg::parse_cfg_entry; -use crate::session_diagnostics::{ +use crate::diagnostics::{ AsNeededCompatibility, BothFfiConstAndPure, BundleNeedsStatic, EmptyLinkName, ExportSymbolsNeedsStatic, ImportNameTypeRaw, ImportNameTypeX86, IncompatibleWasmLink, InvalidLinkModifier, InvalidMachoSection, InvalidMachoSectionReason, LinkFrameworkApple, diff --git a/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs b/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs index 8011beb05546f..719afeb1de0d1 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs @@ -3,7 +3,7 @@ use rustc_hir::attrs::ReprAttr; use rustc_hir::find_attr; use super::prelude::*; -use crate::session_diagnostics::RustcPubTransparent; +use crate::diagnostics::RustcPubTransparent; pub(crate) struct RustcAsPtrParser; impl NoArgsAttributeParser for RustcAsPtrParser { diff --git a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs index 3dec77d3a3550..d382a948bffca 100644 --- a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs @@ -4,7 +4,7 @@ use rustc_hir::find_attr; use rustc_session::lint::builtin::INVALID_MACRO_EXPORT_ARGUMENTS; use super::prelude::*; -use crate::session_diagnostics::MacroOnlyAttribute; +use crate::diagnostics::MacroOnlyAttribute; pub(crate) struct MacroEscapeParser; impl NoArgsAttributeParser for MacroEscapeParser { diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index 1f88d2ab95e9b..09db8dcb84785 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -27,8 +27,8 @@ use rustc_span::{Span, Symbol}; use thin_vec::ThinVec; use crate::context::{AcceptContext, FinalizeCheckContext, FinalizeCheckFn, FinalizeContext}; +use crate::diagnostics::UnusedMultiple; use crate::parser::ArgParser; -use crate::session_diagnostics::UnusedMultiple; use crate::target_checking::AllowedTargets; use crate::{AttributeTemplate, template}; diff --git a/compiler/rustc_attr_parsing/src/attributes/prototype.rs b/compiler/rustc_attr_parsing/src/attributes/prototype.rs index a41010395e7c1..48f65c2434584 100644 --- a/compiler/rustc_attr_parsing/src/attributes/prototype.rs +++ b/compiler/rustc_attr_parsing/src/attributes/prototype.rs @@ -10,7 +10,7 @@ use crate::context::AcceptContext; use crate::parser::{ArgParser, NameValueParser}; use crate::target_checking::AllowedTargets; use crate::target_checking::Policy::Allow; -use crate::{AttributeTemplate, session_diagnostics, template, unstable}; +use crate::{AttributeTemplate, diagnostics, template, unstable}; pub(crate) struct CustomMirParser; @@ -140,10 +140,7 @@ fn check_custom_mir( let Some((dialect, dialect_span)) = dialect else { if let Some((_, phase_span)) = phase { *failed = true; - cx.emit_err(session_diagnostics::CustomMirPhaseRequiresDialect { - attr_span, - phase_span, - }); + cx.emit_err(diagnostics::CustomMirPhaseRequiresDialect { attr_span, phase_span }); } return; }; @@ -152,7 +149,7 @@ fn check_custom_mir( MirDialect::Analysis => { if let Some((MirPhase::Optimized, phase_span)) = phase { *failed = true; - cx.emit_err(session_diagnostics::CustomMirIncompatibleDialectAndPhase { + cx.emit_err(diagnostics::CustomMirIncompatibleDialectAndPhase { dialect, phase: MirPhase::Optimized, attr_span, @@ -165,7 +162,7 @@ fn check_custom_mir( MirDialect::Built => { if let Some((phase, phase_span)) = phase { *failed = true; - cx.emit_err(session_diagnostics::CustomMirIncompatibleDialectAndPhase { + cx.emit_err(diagnostics::CustomMirIncompatibleDialectAndPhase { dialect, phase, attr_span, diff --git a/compiler/rustc_attr_parsing/src/attributes/repr.rs b/compiler/rustc_attr_parsing/src/attributes/repr.rs index bb0da73df015c..d815cf7e5d931 100644 --- a/compiler/rustc_attr_parsing/src/attributes/repr.rs +++ b/compiler/rustc_attr_parsing/src/attributes/repr.rs @@ -6,7 +6,7 @@ use rustc_hir::attrs::ReprAttr; use rustc_session::diagnostics::feature_err; use super::prelude::*; -use crate::session_diagnostics; +use crate::diagnostics; /// Parse #[repr(...)] forms. /// @@ -236,10 +236,7 @@ fn parse_repr_align( AlignKind::Align => ReprAttr::ReprAlign(literal), }), Err(message) => { - cx.emit_err(session_diagnostics::InvalidAlignmentValue { - span: lit.span, - error_part: message, - }); + cx.emit_err(diagnostics::InvalidAlignmentValue { span: lit.span, error_part: message }); None } } @@ -298,7 +295,7 @@ impl RustcAlignParser { match parse_alignment(&lit.kind, cx) { Ok(literal) => self.0 = Ord::max(self.0, Some((literal, cx.attr_span))), Err(message) => { - cx.emit_err(session_diagnostics::InvalidAlignmentValue { + cx.emit_err(diagnostics::InvalidAlignmentValue { span: lit.span, error_part: message, }); diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index b101d378bab98..5b7d305ba0d28 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -14,9 +14,9 @@ use rustc_span::Symbol; use super::prelude::*; use super::util::parse_single_integer; use crate::diagnostics; -use crate::diagnostics::UnknownExternLangItem; -use crate::session_diagnostics::{ - AttributeRequiresOpt, CguFieldsMissing, RustcScalableVectorCountOutOfRange, UnknownLangItem, +use crate::diagnostics::{ + AttributeRequiresOpt, CguFieldsMissing, RustcScalableVectorCountOutOfRange, + UnknownExternLangItem, UnknownLangItem, }; pub(crate) struct RustcMainParser; diff --git a/compiler/rustc_attr_parsing/src/attributes/stability.rs b/compiler/rustc_attr_parsing/src/attributes/stability.rs index 62f16d9719d23..71be778905f26 100644 --- a/compiler/rustc_attr_parsing/src/attributes/stability.rs +++ b/compiler/rustc_attr_parsing/src/attributes/stability.rs @@ -11,7 +11,7 @@ use rustc_hir::{ use super::prelude::*; use super::util::parse_version; -use crate::session_diagnostics; +use crate::diagnostics; const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[ Allow(Target::Fn), @@ -54,7 +54,7 @@ impl StabilityParser { /// Checks, and emits an error when a stability (or unstability) was already set, which would be a duplicate. fn check_duplicate(&self, cx: &AcceptContext<'_, '_>) -> bool { if let Some((_, _)) = self.stability { - cx.emit_err(session_diagnostics::MultipleStabilityLevels { span: cx.attr_span }); + cx.emit_err(diagnostics::MultipleStabilityLevels { span: cx.attr_span }); true } else { false @@ -117,16 +117,15 @@ impl AttributeParser for StabilityParser { { *allowed_through_unstable_modules = Some(atum); } else { - cx.dcx().emit_err(session_diagnostics::RustcAllowedUnstablePairing { - span: cx.target_span, - }); + cx.dcx() + .emit_err(diagnostics::RustcAllowedUnstablePairing { span: cx.target_span }); } } if let Some((Stability { level: StabilityLevel::Stable { .. }, .. }, _)) = self.stability { for other_attr in cx.all_attrs { if other_attr.word_is(sym::unstable_feature_bound) { - cx.emit_err(session_diagnostics::UnstableFeatureBoundIncompatibleStability { + cx.emit_err(diagnostics::UnstableFeatureBoundIncompatibleStability { span: cx.target_span, }); } @@ -152,8 +151,7 @@ impl AttributeParser for BodyStabilityParser { unstable!(staged_api), |this, cx, args| { if this.stability.is_some() { - cx.dcx() - .emit_err(session_diagnostics::MultipleStabilityLevels { span: cx.attr_span }); + cx.dcx().emit_err(diagnostics::MultipleStabilityLevels { span: cx.attr_span }); } else if let Some((feature, level)) = parse_unstability(cx, args) { this.stability = Some((DefaultBodyStability { level, feature }, cx.attr_span)); } @@ -190,7 +188,7 @@ impl ConstStabilityParser { /// Checks, and emits an error when a stability (or unstability) was already set, which would be a duplicate. fn check_duplicate(&self, cx: &AcceptContext<'_, '_>) -> bool { if let Some((_, _)) = self.stability { - cx.emit_err(session_diagnostics::MultipleStabilityLevels { span: cx.attr_span }); + cx.emit_err(diagnostics::MultipleStabilityLevels { span: cx.attr_span }); true } else { false @@ -254,8 +252,7 @@ impl AttributeParser for ConstStabilityParser { if let Some((ref mut stab, _)) = self.stability { stab.promotable = true; } else { - cx.dcx() - .emit_err(session_diagnostics::RustcPromotablePairing { span: cx.target_span }); + cx.dcx().emit_err(diagnostics::RustcPromotablePairing { span: cx.target_span }); } } @@ -323,10 +320,8 @@ pub(crate) fn parse_stability( let feature = match feature { Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature), - Some(_bad_feature) => { - Err(cx.emit_err(session_diagnostics::NonIdentFeature { span: cx.attr_span })) - } - None => Err(cx.emit_err(session_diagnostics::MissingFeature { span: cx.attr_span })), + Some(_bad_feature) => Err(cx.emit_err(diagnostics::NonIdentFeature { span: cx.attr_span })), + None => Err(cx.emit_err(diagnostics::MissingFeature { span: cx.attr_span })), }; let since = if let Some(since) = since { @@ -335,11 +330,11 @@ pub(crate) fn parse_stability( } else if let Some(version) = parse_version(since) { StableSince::Version(version) } else { - let err = cx.emit_err(session_diagnostics::InvalidSince { span: cx.attr_span }); + let err = cx.emit_err(diagnostics::InvalidSince { span: cx.attr_span }); StableSince::Err(err) } } else { - let err = cx.emit_err(session_diagnostics::MissingSince { span: cx.attr_span }); + let err = cx.emit_err(diagnostics::MissingSince { span: cx.attr_span }); StableSince::Err(err) }; @@ -391,15 +386,13 @@ pub(crate) fn parse_unstability( issue_str => match issue_str.parse::>() { Ok(num) => Some(num), Err(err) => { - cx.emit_err( - session_diagnostics::InvalidIssueString { - span: param.span(), - cause: session_diagnostics::InvalidIssueStringCause::from_int_error_kind( - param.args().as_name_value().unwrap().value_span, - err.kind(), - ), - }, - ); + cx.emit_err(diagnostics::InvalidIssueString { + span: param.span(), + cause: diagnostics::InvalidIssueStringCause::from_int_error_kind( + param.args().as_name_value().unwrap().value_span, + err.kind(), + ), + }); return None; } }, @@ -423,21 +416,18 @@ pub(crate) fn parse_unstability( let feature = match feature { Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature), - Some(_bad_feature) => { - Err(cx.emit_err(session_diagnostics::NonIdentFeature { span: cx.attr_span })) - } - None => Err(cx.emit_err(session_diagnostics::MissingFeature { span: cx.attr_span })), + Some(_bad_feature) => Err(cx.emit_err(diagnostics::NonIdentFeature { span: cx.attr_span })), + None => Err(cx.emit_err(diagnostics::MissingFeature { span: cx.attr_span })), }; - let issue = - issue.ok_or_else(|| cx.emit_err(session_diagnostics::MissingIssue { span: cx.attr_span })); + let issue = issue.ok_or_else(|| cx.emit_err(diagnostics::MissingIssue { span: cx.attr_span })); match (feature, issue) { (Ok(feature), Ok(_)) => { // Stable *language* features shouldn't be used as unstable library features. // (Not doing this for stable library features is checked by tidy.) if ACCEPTED_LANG_FEATURES.iter().any(|f| f.name == feature) { - cx.emit_err(session_diagnostics::UnstableAttrForAlreadyStableFeature { + cx.emit_err(diagnostics::UnstableAttrForAlreadyStableFeature { attr_span: cx.attr_span, item_span: cx.target_span, }); @@ -526,7 +516,7 @@ impl CombineAttributeParser for UnstableRemovedParser { }; let Some(version) = parse_version(since) else { - cx.emit_err(session_diagnostics::InvalidSince { span: cx.attr_span }); + cx.emit_err(diagnostics::InvalidSince { span: cx.attr_span }); return None; }; diff --git a/compiler/rustc_attr_parsing/src/attributes/util.rs b/compiler/rustc_attr_parsing/src/attributes/util.rs index 7969d1bb9ce2c..b6cc68ffc04fe 100644 --- a/compiler/rustc_attr_parsing/src/attributes/util.rs +++ b/compiler/rustc_attr_parsing/src/attributes/util.rs @@ -7,8 +7,8 @@ use rustc_hir::attrs::RustcVersion; use rustc_span::Symbol; use crate::context::AcceptContext; +use crate::diagnostics::LimitInvalid; use crate::parser::{ArgParser, NameValueParser}; -use crate::session_diagnostics::LimitInvalid; /// Parse a rustc version number written inside string literal in an attribute, /// like appears in `since = "1.0.0"`. Suffixes like "-dev" and "-nightly" are diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 55732edfbd166..72673214b42d9 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -66,14 +66,14 @@ use crate::attributes::traits::*; use crate::attributes::transparency::*; use crate::attributes::unroll::*; use crate::attributes::{AttributeParser as _, AttributeSafety, Combine, Single, WithoutArgs}; +use crate::diagnostics::{ + AttributeParseError, AttributeParseErrorReason, AttributeParseErrorSuggestions, + ParsedDescription, UnusedDuplicate, +}; use crate::parser::{ ArgParser, MetaItemListParser, MetaItemOrLitParser, MetaItemParser, NameValueParser, RefPathParser, }; -use crate::session_diagnostics::{ - AttributeParseError, AttributeParseErrorReason, AttributeParseErrorSuggestions, - ParsedDescription, UnusedDuplicate, -}; use crate::target_checking::AllowedTargets; use crate::{AttributeParser, AttributeTemplate, EmitAttribute}; diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index 1e76ab44826a9..48128b109194c 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -1,7 +1,18 @@ -use rustc_errors::{Applicability, DiagArgValue, E0264, MultiSpan}; +use std::num::IntErrorKind; + +use rustc_errors::codes::*; +use rustc_errors::{ + Applicability, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, E0264, EmissionGuarantee, Level, + MultiSpan, +}; use rustc_hir::AttrPath; +use rustc_hir::attrs::{MirDialect, MirPhase}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Ident, Span, Symbol}; +use rustc_target::spec::TargetTuple; + +use crate::AttributeTemplate; +use crate::context::Suggestion; #[derive(Diagnostic)] #[diag("`{$name}` attribute cannot be used at crate level")] @@ -73,7 +84,7 @@ pub(crate) struct UnsafeAttrOutsideUnsafeLint { #[label("usage of unsafe attribute")] pub span: Span, #[subdiagnostic] - pub suggestion: Option, + pub suggestion: Option, } #[derive(Diagnostic)] @@ -877,3 +888,1151 @@ pub(crate) struct UnstableDiagnosticAttribute { pub nightly_build: bool, pub feature: Symbol, } + +#[derive(Diagnostic)] +#[diag("`#[rustc_force_inline]` and `#[inline]` cannot be used together")] +pub(crate) struct InlineForceInlineConflict { + #[primary_span] + pub force_inline_span: Span, + #[label("the inline attribute is specified here")] + pub inline_span: Span, +} + +#[derive(Diagnostic)] +#[diag("`#[ffi_const]` function cannot be `#[ffi_pure]`", code = E0757)] +pub(crate) struct BothFfiConstAndPure { + #[primary_span] + pub attr_span: Span, +} + +#[derive(Diagnostic)] +#[diag("attribute should be applied to `#[repr(transparent)]` types")] +pub(crate) struct RustcPubTransparent { + #[primary_span] + pub attr_span: Span, + #[label("not a `#[repr(transparent)]` type")] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("attribute should be applied to a macro")] +pub(crate) struct MacroOnlyAttribute { + #[primary_span] + pub attr_span: Span, + #[label("not a macro")] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("{$attr_str} attribute cannot have empty value")] +pub(crate) struct DocAliasEmpty<'a> { + #[primary_span] + pub span: Span, + pub attr_str: &'a str, +} + +#[derive(Diagnostic)] +#[diag("{$char_} character isn't allowed in {$attr_str}")] +pub(crate) struct DocAliasBadChar<'a> { + #[primary_span] + pub span: Span, + pub attr_str: &'a str, + pub char_: char, +} + +#[derive(Diagnostic)] +#[diag("{$attr_str} cannot start or end with ' '")] +pub(crate) struct DocAliasStartEnd<'a> { + #[primary_span] + pub span: Span, + pub attr_str: &'a str, +} + +#[derive(Diagnostic)] +#[diag("`#[{$name})]` is missing a `{$field}` argument")] +pub(crate) struct CguFieldsMissing<'a> { + #[primary_span] + pub span: Span, + pub name: &'a AttrPath, + pub field: Symbol, +} + +#[derive(Diagnostic)] +#[diag("`#![doc({$attr_name} = \"...\")]` isn't allowed as a crate-level attribute")] +pub(crate) struct DocAttrNotCrateLevel { + #[primary_span] + pub span: Span, + pub attr_name: Symbol, +} + +#[derive(Diagnostic)] +#[diag("nonexistent keyword `{$keyword}` used in `#[doc(keyword = \"...\")]`")] +#[help("only existing keywords are allowed in core/std")] +pub(crate) struct DocKeywordNotKeyword { + #[primary_span] + pub span: Span, + pub keyword: Symbol, +} + +#[derive(Diagnostic)] +#[diag("nonexistent builtin attribute `{$attribute}` used in `#[doc(attribute = \"...\")]`")] +#[help("only existing builtin attributes are allowed in core/std")] +pub(crate) struct DocAttributeNotAttribute { + #[primary_span] + pub span: Span, + pub attribute: Symbol, +} + +#[derive(Diagnostic)] +#[diag( + "`#[target_feature]` cannot be applied to a {$kind -> + [panic_handler] `#[panic_handler]` + *[other] lang item + } function" +)] +pub(crate) struct TargetFeatureOnLangItem { + #[primary_span] + pub attr_span: Span, + pub kind: Symbol, + #[label( + "{$kind -> + [panic_handler] `#[panic_handler]` + *[other] lang item + } function is not allowed to have `#[target_feature]`" + )] + pub item_span: Span, +} + +#[derive(Diagnostic)] +#[diag( + "{$name -> + [panic_impl] `#[panic_handler]` + *[other] `{$name}` lang item +} function is not allowed to have `#[track_caller]`" +)] +pub(crate) struct TrackCallerOnLangItem { + #[primary_span] + pub attr_span: Span, + pub name: Symbol, + #[label( + "{$name -> + [panic_impl] `#[panic_handler]` + *[other] `{$name}` lang item + } function is not allowed to have `#[track_caller]`" + )] + pub sig_span: Span, +} + +#[derive(Diagnostic)] +#[diag("missing 'since'", code = E0542)] +pub(crate) struct MissingSince { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("missing 'note'", code = E0543)] +pub(crate) struct MissingNote { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("multiple stability levels", code = E0544)] +pub(crate) struct MultipleStabilityLevels { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`issue` must be a non-zero numeric string or \"none\"", code = E0545)] +pub(crate) struct InvalidIssueString { + #[primary_span] + pub span: Span, + + #[subdiagnostic] + pub cause: Option, +} + +// The error kinds of `IntErrorKind` are duplicated here in order to allow the messages to be +// translatable. +#[derive(Subdiagnostic)] +pub(crate) enum InvalidIssueStringCause { + #[label("`issue` must not be \"0\", use \"none\" instead")] + MustNotBeZero { + #[primary_span] + span: Span, + }, + + #[label("cannot parse integer from empty string")] + Empty { + #[primary_span] + span: Span, + }, + + #[label("invalid digit found in string")] + InvalidDigit { + #[primary_span] + span: Span, + }, + + #[label("number too large to fit in target type")] + PosOverflow { + #[primary_span] + span: Span, + }, + + #[label("number too small to fit in target type")] + NegOverflow { + #[primary_span] + span: Span, + }, +} + +impl InvalidIssueStringCause { + pub(crate) fn from_int_error_kind(span: Span, kind: &IntErrorKind) -> Option { + match kind { + IntErrorKind::Empty => Some(Self::Empty { span }), + IntErrorKind::InvalidDigit => Some(Self::InvalidDigit { span }), + IntErrorKind::PosOverflow => Some(Self::PosOverflow { span }), + IntErrorKind::NegOverflow => Some(Self::NegOverflow { span }), + IntErrorKind::Zero => Some(Self::MustNotBeZero { span }), + _ => None, + } + } +} + +#[derive(Diagnostic)] +#[diag("missing 'feature'", code = E0546)] +pub(crate) struct MissingFeature { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("'feature' is not an identifier", code = E0546)] +pub(crate) struct NonIdentFeature { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("missing 'issue'", code = E0547)] +pub(crate) struct MissingIssue { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` or a `rustc_const_stable` attribute", code = E0717)] +pub(crate) struct RustcPromotablePairing { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute", code = E0789)] +pub(crate) struct RustcAllowedUnstablePairing { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("suggestions on deprecated items are unstable")] +pub(crate) struct DeprecatedItemSuggestion { + #[primary_span] + pub span: Span, + + #[help("add `#![feature(deprecated_suggestion)]` to the crate root")] + pub is_nightly: bool, + + #[note("see #94785 for more details")] + pub details: (), +} + +#[derive(Diagnostic)] +#[diag("expected single version literal")] +pub(crate) struct ExpectedSingleVersionLiteral { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("expected a version literal")] +pub(crate) struct ExpectedVersionLiteral { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`{$name}` expects a list of feature names")] +pub(crate) struct ExpectsFeatureList { + #[primary_span] + pub span: Span, + + pub name: String, +} + +#[derive(Diagnostic)] +#[diag("`{$name}` expects feature names")] +pub(crate) struct ExpectsFeatures { + #[primary_span] + pub span: Span, + + pub name: String, +} + +#[derive(Diagnostic)] +#[diag("'since' must be a Rust version number, such as \"1.31.0\"")] +pub(crate) struct InvalidSince { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("unknown version literal format, assuming it refers to a future version")] +pub(crate) struct UnknownVersionLiteral { + #[primary_span] + pub span: Span, +} + +// FIXME(jdonszelmann) duplicated from `rustc_passes`, remove once `check_attr` is integrated. +#[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("`export_name` may not be empty")] +pub(crate) struct EmptyExportName { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`section` may not be empty")] +pub(crate) struct EmptySection { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`export_name` may not contain null characters", code = E0648)] +pub(crate) struct NullOnExport { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`link_section` may not contain null characters", code = E0648)] +pub(crate) struct NullOnLinkSection { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("link name may not contain null characters", code = E0648)] +pub(crate) struct NullOnLinkName { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`objc::class!` may not contain null characters")] +pub(crate) struct NullOnObjcClass { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`objc::selector!` may not contain null characters")] +pub(crate) struct NullOnObjcSelector { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`section` may not contain null characters", code = E0648)] +pub(crate) struct NullOnSection { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`objc::class!` expected a string literal")] +pub(crate) struct ObjcClassExpectedStringLiteral { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`objc::selector!` expected a string literal")] +pub(crate) struct ObjcSelectorExpectedStringLiteral { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("expected at least one confusable name")] +pub(crate) struct EmptyConfusables { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[help("the `{$name}{$attribute_args}` attribute can {$only}be applied to {$applied}")] +#[diag("the `{$name}{$attribute_args}` attribute cannot be used on {$target}")] +pub(crate) struct InvalidTarget { + #[primary_span] + pub span: Span, + #[suggestion( + "remove the attribute", + code = "", + applicability = "machine-applicable", + style = "tool-only" + )] + pub attr_span: Span, + pub name: AttrPath, + pub target: &'static str, + pub applied: DiagArgValue, + pub only: &'static str, + pub attribute_args: String, + #[subdiagnostic] + pub help: Option, + #[warning( + "this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!" + )] + pub previously_accepted: bool, + #[note( + "placing this attribute on a macro invocation does nothing even if the macro expands to what would be a valid target for the attribute" + )] + pub on_macro_call: bool, +} + +#[derive(Subdiagnostic)] +pub(crate) enum InvalidTargetHelp { + #[multipart_suggestion( + "did you mean to use `#[export_name]`?", + applicability = "maybe-incorrect" + )] + UseExportName { + #[suggestion_part(code = "unsafe(")] + unsafe_open: Option, + #[suggestion_part(code = "export_name")] + name: Span, + #[suggestion_part(code = ")")] + unsafe_close: Option, + }, + #[help("use `#[rustc_align(...)]` instead")] + UseRustcAlign, + #[help("use `#[rustc_align_static(...)]` instead")] + UseRustcAlignStatic, +} + +#[derive(Diagnostic)] +#[diag("invalid alignment value: {$error_part}", code = E0589)] +pub(crate) struct InvalidAlignmentValue { + #[primary_span] + pub span: Span, + pub error_part: String, +} + +#[derive(Diagnostic)] +#[diag("item annotated with `#[unstable_feature_bound]` should not be stable")] +#[help( + "if this item is meant to be stable, do not use any functions annotated with `#[unstable_feature_bound]`. Otherwise, mark this item as unstable with `#[unstable]`" +)] +pub(crate) struct UnstableFeatureBoundIncompatibleStability { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("attribute incompatible with `#[unsafe(naked)]`", code = E0736)] +pub(crate) struct NakedFunctionIncompatibleAttribute { + #[primary_span] + #[label("the `{$attr}` attribute is incompatible with `#[unsafe(naked)]`")] + pub span: Span, + #[label("function marked with `#[unsafe(naked)]` here")] + pub naked_span: Span, + pub attr: String, +} + +#[derive(Diagnostic)] +#[diag("ordinal value in `link_ordinal` is too large: `{$ordinal}`")] +#[note("the value may not exceed `u16::MAX`")] +pub(crate) struct LinkOrdinalOutOfRange { + #[primary_span] + pub span: Span, + pub ordinal: u128, +} + +#[derive(Diagnostic)] +#[diag("element count in `rustc_scalable_vector` is too large: `{$n}`")] +#[note("the value may not exceed `u16::MAX`")] +pub(crate) struct RustcScalableVectorCountOutOfRange { + #[primary_span] + pub span: Span, + pub n: u128, +} + +#[derive(Diagnostic)] +#[diag("attribute requires {$opt} to be enabled")] +pub(crate) struct AttributeRequiresOpt { + #[primary_span] + pub span: Span, + pub opt: &'static str, +} + +pub(crate) enum AttributeParseErrorReason<'a> { + ExpectedNoArgs, + ExpectedStringLiteral { + byte_string: Option, + }, + ExpectedFilenameLiteral, + ExpectedIntegerLiteral, + ExpectedIntegerLiteralInRange { + lower_bound: isize, + upper_bound: isize, + }, + ExpectedAtLeastOneArgument, + ExpectedArgument, + ExpectedSingleArgument, + ExpectedList, + ExpectedListOrNoArgs, + ExpectedListWithNumArgsOrMore { + args: usize, + }, + ExpectedNameValueOrNoArgs, + ExpectedNonEmptyStringLiteral, + ExpectedNotLiteral, + ExpectedNameValue(Option), + MissingNameValue(Symbol), + DuplicateKey(Symbol), + ExpectedSpecificArgument { + possibilities: &'a [Symbol], + strings: bool, + /// Should we tell the user to write a list when they didn't? + list: bool, + }, + ExpectedIdentifier, +} + +/// A description of a thing that can be parsed using an attribute parser. +#[derive(Copy, Clone)] +pub enum ParsedDescription { + /// Used when parsing attributes. + Attribute, + /// Used when parsing some macros, such as the `cfg!()` macro. + Macro, +} + +pub(crate) struct AttributeParseError<'a> { + pub(crate) span: Span, + pub(crate) inner_span: Span, + pub(crate) template: AttributeTemplate, + pub(crate) path: AttrPath, + pub(crate) description: ParsedDescription, + pub(crate) reason: AttributeParseErrorReason<'a>, + pub(crate) suggestions: AttributeParseErrorSuggestions, +} + +pub(crate) enum AttributeParseErrorSuggestions { + CreatedByTemplate(Vec), + CreatedByParser(Vec), +} + +impl<'a> AttributeParseError<'a> { + fn render_expected_specific_argument( + &self, + diag: &mut Diag<'_, G>, + possibilities: &[Symbol], + strings: bool, + ) where + G: EmissionGuarantee, + { + let quote = if strings { '"' } else { '`' }; + match possibilities { + &[] => {} + &[x] => { + diag.span_label( + self.span, + format!("the only valid argument here is {quote}{x}{quote}"), + ); + } + [first, second] => { + diag.span_label( + self.span, + format!("valid arguments are {quote}{first}{quote} or {quote}{second}{quote}"), + ); + } + [first @ .., second_to_last, last] => { + let mut res = String::new(); + for i in first { + res.push_str(&format!("{quote}{i}{quote}, ")); + } + res.push_str(&format!("{quote}{second_to_last}{quote} or {quote}{last}{quote}")); + + diag.span_label(self.span, format!("valid arguments are {res}")); + } + } + } + + fn render_expected_specific_argument_list( + &self, + diag: &mut Diag<'_, G>, + possibilities: &[Symbol], + strings: bool, + ) where + G: EmissionGuarantee, + { + let description = self.description(); + + let quote = if strings { '"' } else { '`' }; + match possibilities { + &[] => {} + &[x] => { + diag.span_label( + self.span, + format!( + "this {description} is only valid with {quote}{x}{quote} as an argument" + ), + ); + } + [first, second] => { + diag.span_label(self.span, format!("this {description} is only valid with either {quote}{first}{quote} or {quote}{second}{quote} as an argument")); + } + [first @ .., second_to_last, last] => { + let mut res = String::new(); + for i in first { + res.push_str(&format!("{quote}{i}{quote}, ")); + } + res.push_str(&format!("{quote}{second_to_last}{quote} or {quote}{last}{quote}")); + + diag.span_label(self.span, format!("this {description} is only valid with one of the following arguments: {res}")); + } + } + } + + fn render_suggestions(&self, diag: &mut Diag<'_, G>) + where + G: EmissionGuarantee, + { + let description = self.description(); + + match &self.suggestions { + AttributeParseErrorSuggestions::CreatedByTemplate(suggestions) => { + diag.span_suggestions( + self.inner_span, + if suggestions.len() == 1 { + "must be of the form".to_string() + } else { + format!( + "try changing it to one of the following valid forms of the {description}" + ) + }, + suggestions.iter().cloned(), + Applicability::HasPlaceholders, + ); + } + + AttributeParseErrorSuggestions::CreatedByParser(suggestions) => { + for Suggestion { msg, sp, code } in suggestions { + diag.span_suggestion_verbose( + *sp, + msg.clone(), + code.clone(), + Applicability::MaybeIncorrect, + ); + } + } + } + } + + fn description(&self) -> &'static str { + match self.description { + ParsedDescription::Attribute => "attribute", + ParsedDescription::Macro => "macro", + } + } +} + +impl AttributeParseErrorSuggestions { + fn len(&self) -> usize { + match self { + AttributeParseErrorSuggestions::CreatedByTemplate(items) => items.len(), + AttributeParseErrorSuggestions::CreatedByParser(items) => items.len(), + } + } +} + +impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError<'_> { + fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> { + let name = self.path.to_string(); + + let description = self.description(); + + let mut diag = Diag::new(dcx, level, format!("malformed `{name}` {description} input")); + diag.span(self.inner_span); + diag.code(E0539); + match &self.reason { + AttributeParseErrorReason::ExpectedStringLiteral { byte_string } => { + if let Some(start_point_span) = byte_string { + diag.span_suggestion( + *start_point_span, + "consider removing the prefix", + "", + Applicability::MaybeIncorrect, + ); + diag.note("expected a normal string literal, not a byte string literal"); + + // Avoid emitting an "attribute must be of the form" suggestion, as the + // attribute is likely to be well-formed already. + return diag; + } + diag.span_label(self.span, "expected a string literal here"); + } + AttributeParseErrorReason::ExpectedFilenameLiteral => { + diag.span_label(self.span, "expected a filename string literal here"); + } + AttributeParseErrorReason::ExpectedIntegerLiteral => { + diag.span_label(self.span, "expected an integer literal here"); + } + AttributeParseErrorReason::ExpectedIntegerLiteralInRange { + lower_bound, + upper_bound, + } => { + diag.span_label( + self.span, + format!( + "expected an integer literal in the range of {lower_bound}..={upper_bound}" + ), + ); + } + AttributeParseErrorReason::ExpectedSingleArgument => { + diag.span_label(self.span, "expected a single argument here"); + diag.code(E0805); + } + AttributeParseErrorReason::ExpectedArgument => { + diag.span_label(self.span, "expected an argument here"); + diag.code(E0805); + } + AttributeParseErrorReason::ExpectedAtLeastOneArgument => { + diag.span_label(self.span, "expected at least 1 argument here"); + } + AttributeParseErrorReason::ExpectedList => { + diag.span_label(self.span, "expected this to be a list"); + } + AttributeParseErrorReason::ExpectedListOrNoArgs => { + diag.span_label(self.span, "expected a list or no arguments here"); + } + AttributeParseErrorReason::ExpectedListWithNumArgsOrMore { args } => { + diag.span_label(self.span, format!("expected {args} or more items")); + } + AttributeParseErrorReason::ExpectedNameValueOrNoArgs => { + diag.span_label(self.span, "didn't expect a list here"); + } + AttributeParseErrorReason::ExpectedNonEmptyStringLiteral => { + diag.span_label(self.span, "string is not allowed to be empty"); + } + AttributeParseErrorReason::DuplicateKey(key) => { + diag.span_label(self.span, format!("found `{key}` used as a key more than once")); + diag.code(E0538); + } + AttributeParseErrorReason::ExpectedNotLiteral => { + diag.span_label(self.span, "didn't expect a literal here"); + diag.code(E0565); + } + AttributeParseErrorReason::ExpectedNoArgs => { + diag.span_label(self.span, "didn't expect any arguments here"); + diag.code(E0565); + } + AttributeParseErrorReason::ExpectedNameValue(None) => { + // If the span is the entire attribute inner, the suggestion we add below this + // match already contains enough information. + if self.span != self.inner_span { + diag.span_label(self.span, "expected this to be of the form `... = \"...\"`"); + } + } + AttributeParseErrorReason::ExpectedNameValue(Some(name)) => { + diag.span_label( + self.span, + format!("expected this to be of the form `{name} = \"...\"`"), + ); + } + AttributeParseErrorReason::MissingNameValue(name) => { + diag.span_label(self.span, format!("missing argument `{name} = \"...\"`")); + } + AttributeParseErrorReason::ExpectedSpecificArgument { + possibilities, + strings, + list: false, + } => { + self.render_expected_specific_argument(&mut diag, possibilities, *strings); + } + AttributeParseErrorReason::ExpectedSpecificArgument { + possibilities, + strings, + list: true, + } => { + self.render_expected_specific_argument_list(&mut diag, possibilities, *strings); + } + AttributeParseErrorReason::ExpectedIdentifier => { + diag.span_label(self.span, "expected a valid identifier here"); + diag.code(E0565); + } + } + + if let Some(link) = self.template.docs { + diag.note(format!("for more information, visit <{link}>")); + } + + if self.suggestions.len() < 4 { + self.render_suggestions(&mut diag); + } + + diag + } +} + +#[derive(Diagnostic)] +#[diag("`{$name}` is not an unsafe attribute")] +#[note("extraneous unsafe is not allowed in attributes")] +pub(crate) struct InvalidAttrUnsafe { + #[primary_span] + #[label("this is not an unsafe attribute")] + pub span: Span, + pub name: AttrPath, +} + +#[derive(Diagnostic)] +#[diag("unsafe attribute used without unsafe")] +pub(crate) struct UnsafeAttrOutsideUnsafe { + #[primary_span] + #[label("usage of unsafe attribute")] + pub span: Span, + #[subdiagnostic] + pub suggestion: Option, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion("wrap the attribute in `unsafe(...)`", applicability = "machine-applicable")] +pub(crate) struct UnsafeAttrOutsideUnsafeSuggestion { + #[suggestion_part(code = "unsafe(")] + pub left: Span, + #[suggestion_part(code = ")")] + pub right: Span, +} + +#[derive(Diagnostic)] +#[diag("wrong meta list delimiters")] +pub(crate) struct MetaBadDelim { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub sugg: MetaBadDelimSugg, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion( + "the delimiters should be `(` and `)`", + applicability = "machine-applicable" +)] +pub(crate) struct MetaBadDelimSugg { + #[suggestion_part(code = "(")] + pub open: Span, + #[suggestion_part(code = ")")] + pub close: Span, +} + +#[derive(Diagnostic)] +#[diag("expected a literal (`1u8`, `1.0f32`, `\"string\"`, etc.) here, found {$descr}")] +pub(crate) struct InvalidMetaItem { + #[primary_span] + pub span: Span, + pub descr: String, + #[subdiagnostic] + pub quote_ident_sugg: Option, + #[subdiagnostic] + pub remove_neg_sugg: Option, + #[label("{$descr}s are not allowed here")] + pub label: Option, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion( + "surround the identifier with quotation marks to make it into a string literal", + applicability = "machine-applicable" +)] +pub(crate) struct InvalidMetaItemQuoteIdentSugg { + #[suggestion_part(code = "\"")] + pub before: Span, + #[suggestion_part(code = "\"")] + pub after: Span, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion( + "negative numbers are not literals, try removing the `-` sign", + applicability = "machine-applicable" +)] +pub(crate) struct InvalidMetaItemRemoveNegSugg { + #[suggestion_part(code = "")] + pub negative_sign: Span, +} + +#[derive(Diagnostic)] +#[diag("suffixed literals are not allowed in attributes")] +#[help( + "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), use an unsuffixed version (`1`, `1.0`, etc.)" +)] +pub(crate) struct SuffixedLiteralInAttribute { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("link name must not be empty", code = E0454)] +pub(crate) struct EmptyLinkName { + #[primary_span] + #[label("empty link name")] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("link kind `framework` is only supported on Apple targets", code = E0455)] +pub(crate) struct LinkFrameworkApple { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`wasm_import_module` is incompatible with other arguments in `#[link]` attributes")] +pub(crate) struct IncompatibleWasmLink { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`#[link]` attribute requires a `name = \"string\"` argument", code = E0459)] +pub(crate) struct LinkRequiresName { + #[primary_span] + #[label("missing `name` argument")] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("link kind `raw-dylib` is only supported on Windows targets", code = E0455)] +pub(crate) struct RawDylibOnlyWindows { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag( + "invalid linking modifier syntax, expected '+' or '-' prefix before one of: bundle, verbatim, whole-archive, as-needed, export-symbols" +)] +pub(crate) struct InvalidLinkModifier { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("multiple `{$modifier}` modifiers in a single `modifiers` argument")] +pub(crate) struct MultipleModifiers { + #[primary_span] + pub span: Span, + pub modifier: Symbol, +} + +#[derive(Diagnostic)] +#[diag("import name type is only supported on x86")] +pub(crate) struct ImportNameTypeX86 { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("linking modifier `bundle` is only compatible with `static` linking kind")] +pub(crate) struct BundleNeedsStatic { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("linking modifier `export-symbols` is only compatible with `static` linking kind")] +pub(crate) struct ExportSymbolsNeedsStatic { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("linking modifier `whole-archive` is only compatible with `static` linking kind")] +pub(crate) struct WholeArchiveNeedsStatic { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag( + "linking modifier `as-needed` is only compatible with `dylib`, `framework` and `raw-dylib` linking kinds" +)] +pub(crate) struct AsNeededCompatibility { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("import name type can only be used with link kind `raw-dylib`")] +pub(crate) struct ImportNameTypeRaw { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("`limit` must be a non-negative integer")] +pub(crate) struct LimitInvalid<'a> { + #[primary_span] + pub span: Span, + #[label("{$error_str}")] + pub value_span: Span, + pub error_str: &'a str, +} + +#[derive(Diagnostic)] +#[diag("wrong `cfg_attr` delimiters")] +pub(crate) struct CfgAttrBadDelim { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub sugg: MetaBadDelimSugg, +} + +#[derive(Diagnostic)] +#[diag( + "doc alias attribute expects a string `#[doc(alias = \"a\")]` or a list of strings `#[doc(alias(\"a\", \"b\"))]`" +)] +pub(crate) struct DocAliasMalformed { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag("definition of an unknown lang item: `{$name}`", code = E0522)] +pub(crate) struct UnknownLangItem { + #[primary_span] + #[label("definition of unknown lang item `{$name}`")] + pub span: Span, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag("target `{$current_target}` does not support `#[instruction_set({$instruction_set}::*)]`")] +pub(crate) struct UnsupportedInstructionSet<'a> { + #[primary_span] + pub span: Span, + pub instruction_set: Symbol, + pub current_target: &'a TargetTuple, +} + +#[derive(Diagnostic)] +#[diag("`dialect` key required")] +pub(crate) struct CustomMirPhaseRequiresDialect { + #[primary_span] + pub attr_span: Span, + #[label("`phase` argument requires a `dialect` argument")] + pub phase_span: Span, +} + +#[derive(Diagnostic)] +#[diag("the {$dialect} dialect is not compatible with the {$phase} phase")] +pub(crate) struct CustomMirIncompatibleDialectAndPhase { + pub dialect: MirDialect, + pub phase: MirPhase, + #[primary_span] + pub attr_span: Span, + #[label("this dialect...")] + pub dialect_span: Span, + #[label("... is not compatible with this phase")] + pub phase_span: Span, +} + +#[derive(Diagnostic)] +#[diag("can't mark as unstable using an already stable feature")] +pub(crate) struct UnstableAttrForAlreadyStableFeature { + #[primary_span] + #[label("this feature is already stable")] + #[help("consider removing the attribute")] + pub attr_span: Span, + #[label("the stability attribute annotates this item")] + pub item_span: Span, +} + +#[derive(Diagnostic)] +#[diag("invalid Mach-O section specifier")] +pub(crate) struct InvalidMachoSection { + #[primary_span] + #[label("not a valid Mach-O section specifier")] + pub name_span: Span, + #[subdiagnostic] + pub reason: InvalidMachoSectionReason, +} + +#[derive(Subdiagnostic)] +pub(crate) enum InvalidMachoSectionReason { + #[note("a Mach-O section specifier requires a segment and a section, separated by a comma")] + #[help("an example of a valid Mach-O section specifier is `__TEXT,__cstring`")] + MissingSection, + #[note("section name `{$section}` is longer than 16 bytes")] + SectionTooLong { section: String }, +} + +#[derive(Diagnostic)] +#[diag("`#[sanitize({$field} = ...)]` attribute cannot be used on statics")] +#[help("`#[sanitize]` can be used on statics if only the address is sanitized")] +pub(crate) struct SanitizeInvalidStatic { + #[primary_span] + pub span: Span, + pub field: &'static str, +} + +#[derive(Diagnostic)] +#[diag("attribute items not separated with `,`")] +pub(crate) struct ExpectedComma { + #[primary_span] + #[suggestion( + "try adding `,` here", + code = ",", + applicability = "maybe-incorrect", + style = "short" + )] + pub span: Span, + #[subdiagnostic] + pub additional: Vec, +} + +#[derive(Subdiagnostic)] +#[suggestion("try adding `,` here", code = ",", applicability = "maybe-incorrect", style = "short")] +pub(crate) struct AdditionalCommaSuggestion { + #[primary_span] + pub 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, +} diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 73108e42d5ab5..492cf1e268ac6 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -21,8 +21,8 @@ use crate::context::{ ATTRIBUTE_PARSERS, AcceptContext, FinalizeCheckContext, FinalizeCheckFn, FinalizeContext, FinalizeFn, FinalizeOutput, SharedContext, }; +use crate::diagnostics::ParsedDescription; use crate::parser::{AllowExprMetavar, ArgParser, PathParser, RefPathParser}; -use crate::session_diagnostics::ParsedDescription; use crate::synthetic::SyntheticAttrState; use crate::{AttributeTemplate, OmitDoc, ShouldEmit}; diff --git a/compiler/rustc_attr_parsing/src/lib.rs b/compiler/rustc_attr_parsing/src/lib.rs index bcdb401bc08c3..5a1d1b8091da2 100644 --- a/compiler/rustc_attr_parsing/src/lib.rs +++ b/compiler/rustc_attr_parsing/src/lib.rs @@ -104,7 +104,6 @@ mod diagnostics; mod interface; pub mod parser; mod safety; -mod session_diagnostics; mod stability; mod synthetic; mod target_checking; @@ -118,7 +117,7 @@ pub use attributes::cfg::{ pub use attributes::cfg_select::*; pub use attributes::util::{is_builtin_attr, parse_version}; pub use context::{OmitDoc, ShouldEmit}; +pub use diagnostics::ParsedDescription; pub use interface::{AttributeParser, EmitAttribute}; pub use rustc_parse::parser::Recovery; -pub use session_diagnostics::ParsedDescription; pub use template::AttributeTemplate; diff --git a/compiler/rustc_attr_parsing/src/parser.rs b/compiler/rustc_attr_parsing/src/parser.rs index 5f1fc8ba90d5e..a1563d629d474 100644 --- a/compiler/rustc_attr_parsing/src/parser.rs +++ b/compiler/rustc_attr_parsing/src/parser.rs @@ -29,7 +29,7 @@ use rustc_span::{Ident, Span, Symbol, sym}; use thin_vec::ThinVec; use crate::ShouldEmit; -use crate::session_diagnostics::{ +use crate::diagnostics::{ AdditionalCommaSuggestion, ExpectedComma, InvalidMetaItem, InvalidMetaItemQuoteIdentSugg, InvalidMetaItemRemoveNegSugg, MetaBadDelim, MetaBadDelimSugg, SuffixedLiteralInAttribute, }; diff --git a/compiler/rustc_attr_parsing/src/safety.rs b/compiler/rustc_attr_parsing/src/safety.rs index 5b3d52c18aae1..1e0717dfd8e26 100644 --- a/compiler/rustc_attr_parsing/src/safety.rs +++ b/compiler/rustc_attr_parsing/src/safety.rs @@ -66,10 +66,10 @@ impl<'sess> AttributeParser<'sess> { } if emit_error { - self.emit_err(crate::session_diagnostics::UnsafeAttrOutsideUnsafe { + self.emit_err(crate::diagnostics::UnsafeAttrOutsideUnsafe { span: path_span, suggestion: not_from_proc_macro.then(|| { - crate::session_diagnostics::UnsafeAttrOutsideUnsafeSuggestion { + crate::diagnostics::UnsafeAttrOutsideUnsafeSuggestion { left: diag_span.shrink_to_lo(), right: diag_span.shrink_to_hi(), } @@ -85,7 +85,10 @@ impl<'sess> AttributeParser<'sess> { suggestion: not_from_proc_macro .then(|| (diag_span.shrink_to_lo(), diag_span.shrink_to_hi())) .map(|(left, right)| { - crate::session_diagnostics::UnsafeAttrOutsideUnsafeSuggestion { left, right } + crate::diagnostics::UnsafeAttrOutsideUnsafeSuggestion { + left, + right, + } }), } .into_diag(dcx, level) @@ -97,7 +100,7 @@ impl<'sess> AttributeParser<'sess> { // - Normal builtin attribute // - Writing `#[unsafe(..)]` is not permitted on normal builtin attributes (AttributeSafety::Normal, Safety::Unsafe(unsafe_span)) => { - self.emit_err(crate::session_diagnostics::InvalidAttrUnsafe { + self.emit_err(crate::diagnostics::InvalidAttrUnsafe { span: unsafe_span, name: attr_path.clone(), }); diff --git a/compiler/rustc_attr_parsing/src/session_diagnostics.rs b/compiler/rustc_attr_parsing/src/session_diagnostics.rs deleted file mode 100644 index b7c7b39bcb48b..0000000000000 --- a/compiler/rustc_attr_parsing/src/session_diagnostics.rs +++ /dev/null @@ -1,1162 +0,0 @@ -use std::num::IntErrorKind; - -use rustc_errors::codes::*; -use rustc_errors::{ - Applicability, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, -}; -use rustc_hir::AttrPath; -use rustc_hir::attrs::{MirDialect, MirPhase}; -use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::{Span, Symbol}; -use rustc_target::spec::TargetTuple; - -use crate::AttributeTemplate; -use crate::context::Suggestion; - -#[derive(Diagnostic)] -#[diag("`#[rustc_force_inline]` and `#[inline]` cannot be used together")] -pub(crate) struct InlineForceInlineConflict { - #[primary_span] - pub force_inline_span: Span, - #[label("the inline attribute is specified here")] - pub inline_span: Span, -} - -#[derive(Diagnostic)] -#[diag("`#[ffi_const]` function cannot be `#[ffi_pure]`", code = E0757)] -pub(crate) struct BothFfiConstAndPure { - #[primary_span] - pub attr_span: Span, -} - -#[derive(Diagnostic)] -#[diag("attribute should be applied to `#[repr(transparent)]` types")] -pub(crate) struct RustcPubTransparent { - #[primary_span] - pub attr_span: Span, - #[label("not a `#[repr(transparent)]` type")] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("attribute should be applied to a macro")] -pub(crate) struct MacroOnlyAttribute { - #[primary_span] - pub attr_span: Span, - #[label("not a macro")] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("{$attr_str} attribute cannot have empty value")] -pub(crate) struct DocAliasEmpty<'a> { - #[primary_span] - pub span: Span, - pub attr_str: &'a str, -} - -#[derive(Diagnostic)] -#[diag("{$char_} character isn't allowed in {$attr_str}")] -pub(crate) struct DocAliasBadChar<'a> { - #[primary_span] - pub span: Span, - pub attr_str: &'a str, - pub char_: char, -} - -#[derive(Diagnostic)] -#[diag("{$attr_str} cannot start or end with ' '")] -pub(crate) struct DocAliasStartEnd<'a> { - #[primary_span] - pub span: Span, - pub attr_str: &'a str, -} - -#[derive(Diagnostic)] -#[diag("`#[{$name})]` is missing a `{$field}` argument")] -pub(crate) struct CguFieldsMissing<'a> { - #[primary_span] - pub span: Span, - pub name: &'a AttrPath, - pub field: Symbol, -} - -#[derive(Diagnostic)] -#[diag("`#![doc({$attr_name} = \"...\")]` isn't allowed as a crate-level attribute")] -pub(crate) struct DocAttrNotCrateLevel { - #[primary_span] - pub span: Span, - pub attr_name: Symbol, -} - -#[derive(Diagnostic)] -#[diag("nonexistent keyword `{$keyword}` used in `#[doc(keyword = \"...\")]`")] -#[help("only existing keywords are allowed in core/std")] -pub(crate) struct DocKeywordNotKeyword { - #[primary_span] - pub span: Span, - pub keyword: Symbol, -} - -#[derive(Diagnostic)] -#[diag("nonexistent builtin attribute `{$attribute}` used in `#[doc(attribute = \"...\")]`")] -#[help("only existing builtin attributes are allowed in core/std")] -pub(crate) struct DocAttributeNotAttribute { - #[primary_span] - pub span: Span, - pub attribute: Symbol, -} - -#[derive(Diagnostic)] -#[diag( - "`#[target_feature]` cannot be applied to a {$kind -> - [panic_handler] `#[panic_handler]` - *[other] lang item - } function" -)] -pub(crate) struct TargetFeatureOnLangItem { - #[primary_span] - pub attr_span: Span, - pub kind: Symbol, - #[label( - "{$kind -> - [panic_handler] `#[panic_handler]` - *[other] lang item - } function is not allowed to have `#[target_feature]`" - )] - pub item_span: Span, -} - -#[derive(Diagnostic)] -#[diag( - "{$name -> - [panic_impl] `#[panic_handler]` - *[other] `{$name}` lang item -} function is not allowed to have `#[track_caller]`" -)] -pub(crate) struct TrackCallerOnLangItem { - #[primary_span] - pub attr_span: Span, - pub name: Symbol, - #[label( - "{$name -> - [panic_impl] `#[panic_handler]` - *[other] `{$name}` lang item - } function is not allowed to have `#[track_caller]`" - )] - pub sig_span: Span, -} - -#[derive(Diagnostic)] -#[diag("missing 'since'", code = E0542)] -pub(crate) struct MissingSince { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("missing 'note'", code = E0543)] -pub(crate) struct MissingNote { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("multiple stability levels", code = E0544)] -pub(crate) struct MultipleStabilityLevels { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`issue` must be a non-zero numeric string or \"none\"", code = E0545)] -pub(crate) struct InvalidIssueString { - #[primary_span] - pub span: Span, - - #[subdiagnostic] - pub cause: Option, -} - -// The error kinds of `IntErrorKind` are duplicated here in order to allow the messages to be -// translatable. -#[derive(Subdiagnostic)] -pub(crate) enum InvalidIssueStringCause { - #[label("`issue` must not be \"0\", use \"none\" instead")] - MustNotBeZero { - #[primary_span] - span: Span, - }, - - #[label("cannot parse integer from empty string")] - Empty { - #[primary_span] - span: Span, - }, - - #[label("invalid digit found in string")] - InvalidDigit { - #[primary_span] - span: Span, - }, - - #[label("number too large to fit in target type")] - PosOverflow { - #[primary_span] - span: Span, - }, - - #[label("number too small to fit in target type")] - NegOverflow { - #[primary_span] - span: Span, - }, -} - -impl InvalidIssueStringCause { - pub(crate) fn from_int_error_kind(span: Span, kind: &IntErrorKind) -> Option { - match kind { - IntErrorKind::Empty => Some(Self::Empty { span }), - IntErrorKind::InvalidDigit => Some(Self::InvalidDigit { span }), - IntErrorKind::PosOverflow => Some(Self::PosOverflow { span }), - IntErrorKind::NegOverflow => Some(Self::NegOverflow { span }), - IntErrorKind::Zero => Some(Self::MustNotBeZero { span }), - _ => None, - } - } -} - -#[derive(Diagnostic)] -#[diag("missing 'feature'", code = E0546)] -pub(crate) struct MissingFeature { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("'feature' is not an identifier", code = E0546)] -pub(crate) struct NonIdentFeature { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("missing 'issue'", code = E0547)] -pub(crate) struct MissingIssue { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` or a `rustc_const_stable` attribute", code = E0717)] -pub(crate) struct RustcPromotablePairing { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute", code = E0789)] -pub(crate) struct RustcAllowedUnstablePairing { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("suggestions on deprecated items are unstable")] -pub(crate) struct DeprecatedItemSuggestion { - #[primary_span] - pub span: Span, - - #[help("add `#![feature(deprecated_suggestion)]` to the crate root")] - pub is_nightly: bool, - - #[note("see #94785 for more details")] - pub details: (), -} - -#[derive(Diagnostic)] -#[diag("expected single version literal")] -pub(crate) struct ExpectedSingleVersionLiteral { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("expected a version literal")] -pub(crate) struct ExpectedVersionLiteral { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`{$name}` expects a list of feature names")] -pub(crate) struct ExpectsFeatureList { - #[primary_span] - pub span: Span, - - pub name: String, -} - -#[derive(Diagnostic)] -#[diag("`{$name}` expects feature names")] -pub(crate) struct ExpectsFeatures { - #[primary_span] - pub span: Span, - - pub name: String, -} - -#[derive(Diagnostic)] -#[diag("'since' must be a Rust version number, such as \"1.31.0\"")] -pub(crate) struct InvalidSince { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("unknown version literal format, assuming it refers to a future version")] -pub(crate) struct UnknownVersionLiteral { - #[primary_span] - pub span: Span, -} - -// FIXME(jdonszelmann) duplicated from `rustc_passes`, remove once `check_attr` is integrated. -#[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("`export_name` may not be empty")] -pub(crate) struct EmptyExportName { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`section` may not be empty")] -pub(crate) struct EmptySection { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`export_name` may not contain null characters", code = E0648)] -pub(crate) struct NullOnExport { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`link_section` may not contain null characters", code = E0648)] -pub(crate) struct NullOnLinkSection { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("link name may not contain null characters", code = E0648)] -pub(crate) struct NullOnLinkName { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`objc::class!` may not contain null characters")] -pub(crate) struct NullOnObjcClass { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`objc::selector!` may not contain null characters")] -pub(crate) struct NullOnObjcSelector { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`section` may not contain null characters", code = E0648)] -pub(crate) struct NullOnSection { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`objc::class!` expected a string literal")] -pub(crate) struct ObjcClassExpectedStringLiteral { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`objc::selector!` expected a string literal")] -pub(crate) struct ObjcSelectorExpectedStringLiteral { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("expected at least one confusable name")] -pub(crate) struct EmptyConfusables { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[help("the `{$name}{$attribute_args}` attribute can {$only}be applied to {$applied}")] -#[diag("the `{$name}{$attribute_args}` attribute cannot be used on {$target}")] -pub(crate) struct InvalidTarget { - #[primary_span] - pub span: Span, - #[suggestion( - "remove the attribute", - code = "", - applicability = "machine-applicable", - style = "tool-only" - )] - pub attr_span: Span, - pub name: AttrPath, - pub target: &'static str, - pub applied: DiagArgValue, - pub only: &'static str, - pub attribute_args: String, - #[subdiagnostic] - pub help: Option, - #[warning( - "this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!" - )] - pub previously_accepted: bool, - #[note( - "placing this attribute on a macro invocation does nothing even if the macro expands to what would be a valid target for the attribute" - )] - pub on_macro_call: bool, -} - -#[derive(Subdiagnostic)] -pub(crate) enum InvalidTargetHelp { - #[multipart_suggestion( - "did you mean to use `#[export_name]`?", - applicability = "maybe-incorrect" - )] - UseExportName { - #[suggestion_part(code = "unsafe(")] - unsafe_open: Option, - #[suggestion_part(code = "export_name")] - name: Span, - #[suggestion_part(code = ")")] - unsafe_close: Option, - }, - #[help("use `#[rustc_align(...)]` instead")] - UseRustcAlign, - #[help("use `#[rustc_align_static(...)]` instead")] - UseRustcAlignStatic, -} - -#[derive(Diagnostic)] -#[diag("invalid alignment value: {$error_part}", code = E0589)] -pub(crate) struct InvalidAlignmentValue { - #[primary_span] - pub span: Span, - pub error_part: String, -} - -#[derive(Diagnostic)] -#[diag("item annotated with `#[unstable_feature_bound]` should not be stable")] -#[help( - "if this item is meant to be stable, do not use any functions annotated with `#[unstable_feature_bound]`. Otherwise, mark this item as unstable with `#[unstable]`" -)] -pub(crate) struct UnstableFeatureBoundIncompatibleStability { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("attribute incompatible with `#[unsafe(naked)]`", code = E0736)] -pub(crate) struct NakedFunctionIncompatibleAttribute { - #[primary_span] - #[label("the `{$attr}` attribute is incompatible with `#[unsafe(naked)]`")] - pub span: Span, - #[label("function marked with `#[unsafe(naked)]` here")] - pub naked_span: Span, - pub attr: String, -} - -#[derive(Diagnostic)] -#[diag("ordinal value in `link_ordinal` is too large: `{$ordinal}`")] -#[note("the value may not exceed `u16::MAX`")] -pub(crate) struct LinkOrdinalOutOfRange { - #[primary_span] - pub span: Span, - pub ordinal: u128, -} - -#[derive(Diagnostic)] -#[diag("element count in `rustc_scalable_vector` is too large: `{$n}`")] -#[note("the value may not exceed `u16::MAX`")] -pub(crate) struct RustcScalableVectorCountOutOfRange { - #[primary_span] - pub span: Span, - pub n: u128, -} - -#[derive(Diagnostic)] -#[diag("attribute requires {$opt} to be enabled")] -pub(crate) struct AttributeRequiresOpt { - #[primary_span] - pub span: Span, - pub opt: &'static str, -} - -pub(crate) enum AttributeParseErrorReason<'a> { - ExpectedNoArgs, - ExpectedStringLiteral { - byte_string: Option, - }, - ExpectedFilenameLiteral, - ExpectedIntegerLiteral, - ExpectedIntegerLiteralInRange { - lower_bound: isize, - upper_bound: isize, - }, - ExpectedAtLeastOneArgument, - ExpectedArgument, - ExpectedSingleArgument, - ExpectedList, - ExpectedListOrNoArgs, - ExpectedListWithNumArgsOrMore { - args: usize, - }, - ExpectedNameValueOrNoArgs, - ExpectedNonEmptyStringLiteral, - ExpectedNotLiteral, - ExpectedNameValue(Option), - MissingNameValue(Symbol), - DuplicateKey(Symbol), - ExpectedSpecificArgument { - possibilities: &'a [Symbol], - strings: bool, - /// Should we tell the user to write a list when they didn't? - list: bool, - }, - ExpectedIdentifier, -} - -/// A description of a thing that can be parsed using an attribute parser. -#[derive(Copy, Clone)] -pub enum ParsedDescription { - /// Used when parsing attributes. - Attribute, - /// Used when parsing some macros, such as the `cfg!()` macro. - Macro, -} - -pub(crate) struct AttributeParseError<'a> { - pub(crate) span: Span, - pub(crate) inner_span: Span, - pub(crate) template: AttributeTemplate, - pub(crate) path: AttrPath, - pub(crate) description: ParsedDescription, - pub(crate) reason: AttributeParseErrorReason<'a>, - pub(crate) suggestions: AttributeParseErrorSuggestions, -} - -pub(crate) enum AttributeParseErrorSuggestions { - CreatedByTemplate(Vec), - CreatedByParser(Vec), -} - -impl<'a> AttributeParseError<'a> { - fn render_expected_specific_argument( - &self, - diag: &mut Diag<'_, G>, - possibilities: &[Symbol], - strings: bool, - ) where - G: EmissionGuarantee, - { - let quote = if strings { '"' } else { '`' }; - match possibilities { - &[] => {} - &[x] => { - diag.span_label( - self.span, - format!("the only valid argument here is {quote}{x}{quote}"), - ); - } - [first, second] => { - diag.span_label( - self.span, - format!("valid arguments are {quote}{first}{quote} or {quote}{second}{quote}"), - ); - } - [first @ .., second_to_last, last] => { - let mut res = String::new(); - for i in first { - res.push_str(&format!("{quote}{i}{quote}, ")); - } - res.push_str(&format!("{quote}{second_to_last}{quote} or {quote}{last}{quote}")); - - diag.span_label(self.span, format!("valid arguments are {res}")); - } - } - } - - fn render_expected_specific_argument_list( - &self, - diag: &mut Diag<'_, G>, - possibilities: &[Symbol], - strings: bool, - ) where - G: EmissionGuarantee, - { - let description = self.description(); - - let quote = if strings { '"' } else { '`' }; - match possibilities { - &[] => {} - &[x] => { - diag.span_label( - self.span, - format!( - "this {description} is only valid with {quote}{x}{quote} as an argument" - ), - ); - } - [first, second] => { - diag.span_label(self.span, format!("this {description} is only valid with either {quote}{first}{quote} or {quote}{second}{quote} as an argument")); - } - [first @ .., second_to_last, last] => { - let mut res = String::new(); - for i in first { - res.push_str(&format!("{quote}{i}{quote}, ")); - } - res.push_str(&format!("{quote}{second_to_last}{quote} or {quote}{last}{quote}")); - - diag.span_label(self.span, format!("this {description} is only valid with one of the following arguments: {res}")); - } - } - } - - fn render_suggestions(&self, diag: &mut Diag<'_, G>) - where - G: EmissionGuarantee, - { - let description = self.description(); - - match &self.suggestions { - AttributeParseErrorSuggestions::CreatedByTemplate(suggestions) => { - diag.span_suggestions( - self.inner_span, - if suggestions.len() == 1 { - "must be of the form".to_string() - } else { - format!( - "try changing it to one of the following valid forms of the {description}" - ) - }, - suggestions.iter().cloned(), - Applicability::HasPlaceholders, - ); - } - - AttributeParseErrorSuggestions::CreatedByParser(suggestions) => { - for Suggestion { msg, sp, code } in suggestions { - diag.span_suggestion_verbose( - *sp, - msg.clone(), - code.clone(), - Applicability::MaybeIncorrect, - ); - } - } - } - } - - fn description(&self) -> &'static str { - match self.description { - ParsedDescription::Attribute => "attribute", - ParsedDescription::Macro => "macro", - } - } -} - -impl AttributeParseErrorSuggestions { - fn len(&self) -> usize { - match self { - AttributeParseErrorSuggestions::CreatedByTemplate(items) => items.len(), - AttributeParseErrorSuggestions::CreatedByParser(items) => items.len(), - } - } -} - -impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError<'_> { - fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> { - let name = self.path.to_string(); - - let description = self.description(); - - let mut diag = Diag::new(dcx, level, format!("malformed `{name}` {description} input")); - diag.span(self.inner_span); - diag.code(E0539); - match &self.reason { - AttributeParseErrorReason::ExpectedStringLiteral { byte_string } => { - if let Some(start_point_span) = byte_string { - diag.span_suggestion( - *start_point_span, - "consider removing the prefix", - "", - Applicability::MaybeIncorrect, - ); - diag.note("expected a normal string literal, not a byte string literal"); - - // Avoid emitting an "attribute must be of the form" suggestion, as the - // attribute is likely to be well-formed already. - return diag; - } - diag.span_label(self.span, "expected a string literal here"); - } - AttributeParseErrorReason::ExpectedFilenameLiteral => { - diag.span_label(self.span, "expected a filename string literal here"); - } - AttributeParseErrorReason::ExpectedIntegerLiteral => { - diag.span_label(self.span, "expected an integer literal here"); - } - AttributeParseErrorReason::ExpectedIntegerLiteralInRange { - lower_bound, - upper_bound, - } => { - diag.span_label( - self.span, - format!( - "expected an integer literal in the range of {lower_bound}..={upper_bound}" - ), - ); - } - AttributeParseErrorReason::ExpectedSingleArgument => { - diag.span_label(self.span, "expected a single argument here"); - diag.code(E0805); - } - AttributeParseErrorReason::ExpectedArgument => { - diag.span_label(self.span, "expected an argument here"); - diag.code(E0805); - } - AttributeParseErrorReason::ExpectedAtLeastOneArgument => { - diag.span_label(self.span, "expected at least 1 argument here"); - } - AttributeParseErrorReason::ExpectedList => { - diag.span_label(self.span, "expected this to be a list"); - } - AttributeParseErrorReason::ExpectedListOrNoArgs => { - diag.span_label(self.span, "expected a list or no arguments here"); - } - AttributeParseErrorReason::ExpectedListWithNumArgsOrMore { args } => { - diag.span_label(self.span, format!("expected {args} or more items")); - } - AttributeParseErrorReason::ExpectedNameValueOrNoArgs => { - diag.span_label(self.span, "didn't expect a list here"); - } - AttributeParseErrorReason::ExpectedNonEmptyStringLiteral => { - diag.span_label(self.span, "string is not allowed to be empty"); - } - AttributeParseErrorReason::DuplicateKey(key) => { - diag.span_label(self.span, format!("found `{key}` used as a key more than once")); - diag.code(E0538); - } - AttributeParseErrorReason::ExpectedNotLiteral => { - diag.span_label(self.span, "didn't expect a literal here"); - diag.code(E0565); - } - AttributeParseErrorReason::ExpectedNoArgs => { - diag.span_label(self.span, "didn't expect any arguments here"); - diag.code(E0565); - } - AttributeParseErrorReason::ExpectedNameValue(None) => { - // If the span is the entire attribute inner, the suggestion we add below this - // match already contains enough information. - if self.span != self.inner_span { - diag.span_label(self.span, "expected this to be of the form `... = \"...\"`"); - } - } - AttributeParseErrorReason::ExpectedNameValue(Some(name)) => { - diag.span_label( - self.span, - format!("expected this to be of the form `{name} = \"...\"`"), - ); - } - AttributeParseErrorReason::MissingNameValue(name) => { - diag.span_label(self.span, format!("missing argument `{name} = \"...\"`")); - } - AttributeParseErrorReason::ExpectedSpecificArgument { - possibilities, - strings, - list: false, - } => { - self.render_expected_specific_argument(&mut diag, possibilities, *strings); - } - AttributeParseErrorReason::ExpectedSpecificArgument { - possibilities, - strings, - list: true, - } => { - self.render_expected_specific_argument_list(&mut diag, possibilities, *strings); - } - AttributeParseErrorReason::ExpectedIdentifier => { - diag.span_label(self.span, "expected a valid identifier here"); - diag.code(E0565); - } - } - - if let Some(link) = self.template.docs { - diag.note(format!("for more information, visit <{link}>")); - } - - if self.suggestions.len() < 4 { - self.render_suggestions(&mut diag); - } - - diag - } -} - -#[derive(Diagnostic)] -#[diag("`{$name}` is not an unsafe attribute")] -#[note("extraneous unsafe is not allowed in attributes")] -pub(crate) struct InvalidAttrUnsafe { - #[primary_span] - #[label("this is not an unsafe attribute")] - pub span: Span, - pub name: AttrPath, -} - -#[derive(Diagnostic)] -#[diag("unsafe attribute used without unsafe")] -pub(crate) struct UnsafeAttrOutsideUnsafe { - #[primary_span] - #[label("usage of unsafe attribute")] - pub span: Span, - #[subdiagnostic] - pub suggestion: Option, -} - -#[derive(Subdiagnostic)] -#[multipart_suggestion("wrap the attribute in `unsafe(...)`", applicability = "machine-applicable")] -pub(crate) struct UnsafeAttrOutsideUnsafeSuggestion { - #[suggestion_part(code = "unsafe(")] - pub left: Span, - #[suggestion_part(code = ")")] - pub right: Span, -} - -#[derive(Diagnostic)] -#[diag("wrong meta list delimiters")] -pub(crate) struct MetaBadDelim { - #[primary_span] - pub span: Span, - #[subdiagnostic] - pub sugg: MetaBadDelimSugg, -} - -#[derive(Subdiagnostic)] -#[multipart_suggestion( - "the delimiters should be `(` and `)`", - applicability = "machine-applicable" -)] -pub(crate) struct MetaBadDelimSugg { - #[suggestion_part(code = "(")] - pub open: Span, - #[suggestion_part(code = ")")] - pub close: Span, -} - -#[derive(Diagnostic)] -#[diag("expected a literal (`1u8`, `1.0f32`, `\"string\"`, etc.) here, found {$descr}")] -pub(crate) struct InvalidMetaItem { - #[primary_span] - pub span: Span, - pub descr: String, - #[subdiagnostic] - pub quote_ident_sugg: Option, - #[subdiagnostic] - pub remove_neg_sugg: Option, - #[label("{$descr}s are not allowed here")] - pub label: Option, -} - -#[derive(Subdiagnostic)] -#[multipart_suggestion( - "surround the identifier with quotation marks to make it into a string literal", - applicability = "machine-applicable" -)] -pub(crate) struct InvalidMetaItemQuoteIdentSugg { - #[suggestion_part(code = "\"")] - pub before: Span, - #[suggestion_part(code = "\"")] - pub after: Span, -} - -#[derive(Subdiagnostic)] -#[multipart_suggestion( - "negative numbers are not literals, try removing the `-` sign", - applicability = "machine-applicable" -)] -pub(crate) struct InvalidMetaItemRemoveNegSugg { - #[suggestion_part(code = "")] - pub negative_sign: Span, -} - -#[derive(Diagnostic)] -#[diag("suffixed literals are not allowed in attributes")] -#[help( - "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), use an unsuffixed version (`1`, `1.0`, etc.)" -)] -pub(crate) struct SuffixedLiteralInAttribute { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("link name must not be empty", code = E0454)] -pub(crate) struct EmptyLinkName { - #[primary_span] - #[label("empty link name")] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("link kind `framework` is only supported on Apple targets", code = E0455)] -pub(crate) struct LinkFrameworkApple { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`wasm_import_module` is incompatible with other arguments in `#[link]` attributes")] -pub(crate) struct IncompatibleWasmLink { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`#[link]` attribute requires a `name = \"string\"` argument", code = E0459)] -pub(crate) struct LinkRequiresName { - #[primary_span] - #[label("missing `name` argument")] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("link kind `raw-dylib` is only supported on Windows targets", code = E0455)] -pub(crate) struct RawDylibOnlyWindows { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag( - "invalid linking modifier syntax, expected '+' or '-' prefix before one of: bundle, verbatim, whole-archive, as-needed, export-symbols" -)] -pub(crate) struct InvalidLinkModifier { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("multiple `{$modifier}` modifiers in a single `modifiers` argument")] -pub(crate) struct MultipleModifiers { - #[primary_span] - pub span: Span, - pub modifier: Symbol, -} - -#[derive(Diagnostic)] -#[diag("import name type is only supported on x86")] -pub(crate) struct ImportNameTypeX86 { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("linking modifier `bundle` is only compatible with `static` linking kind")] -pub(crate) struct BundleNeedsStatic { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("linking modifier `export-symbols` is only compatible with `static` linking kind")] -pub(crate) struct ExportSymbolsNeedsStatic { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("linking modifier `whole-archive` is only compatible with `static` linking kind")] -pub(crate) struct WholeArchiveNeedsStatic { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag( - "linking modifier `as-needed` is only compatible with `dylib`, `framework` and `raw-dylib` linking kinds" -)] -pub(crate) struct AsNeededCompatibility { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("import name type can only be used with link kind `raw-dylib`")] -pub(crate) struct ImportNameTypeRaw { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("`limit` must be a non-negative integer")] -pub(crate) struct LimitInvalid<'a> { - #[primary_span] - pub span: Span, - #[label("{$error_str}")] - pub value_span: Span, - pub error_str: &'a str, -} - -#[derive(Diagnostic)] -#[diag("wrong `cfg_attr` delimiters")] -pub(crate) struct CfgAttrBadDelim { - #[primary_span] - pub span: Span, - #[subdiagnostic] - pub sugg: MetaBadDelimSugg, -} - -#[derive(Diagnostic)] -#[diag( - "doc alias attribute expects a string `#[doc(alias = \"a\")]` or a list of strings `#[doc(alias(\"a\", \"b\"))]`" -)] -pub(crate) struct DocAliasMalformed { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("definition of an unknown lang item: `{$name}`", code = E0522)] -pub(crate) struct UnknownLangItem { - #[primary_span] - #[label("definition of unknown lang item `{$name}`")] - pub span: Span, - pub name: Symbol, -} - -#[derive(Diagnostic)] -#[diag("target `{$current_target}` does not support `#[instruction_set({$instruction_set}::*)]`")] -pub(crate) struct UnsupportedInstructionSet<'a> { - #[primary_span] - pub span: Span, - pub instruction_set: Symbol, - pub current_target: &'a TargetTuple, -} - -#[derive(Diagnostic)] -#[diag("`dialect` key required")] -pub(crate) struct CustomMirPhaseRequiresDialect { - #[primary_span] - pub attr_span: Span, - #[label("`phase` argument requires a `dialect` argument")] - pub phase_span: Span, -} - -#[derive(Diagnostic)] -#[diag("the {$dialect} dialect is not compatible with the {$phase} phase")] -pub(crate) struct CustomMirIncompatibleDialectAndPhase { - pub dialect: MirDialect, - pub phase: MirPhase, - #[primary_span] - pub attr_span: Span, - #[label("this dialect...")] - pub dialect_span: Span, - #[label("... is not compatible with this phase")] - pub phase_span: Span, -} - -#[derive(Diagnostic)] -#[diag("can't mark as unstable using an already stable feature")] -pub(crate) struct UnstableAttrForAlreadyStableFeature { - #[primary_span] - #[label("this feature is already stable")] - #[help("consider removing the attribute")] - pub attr_span: Span, - #[label("the stability attribute annotates this item")] - pub item_span: Span, -} - -#[derive(Diagnostic)] -#[diag("invalid Mach-O section specifier")] -pub(crate) struct InvalidMachoSection { - #[primary_span] - #[label("not a valid Mach-O section specifier")] - pub name_span: Span, - #[subdiagnostic] - pub reason: InvalidMachoSectionReason, -} - -#[derive(Subdiagnostic)] -pub(crate) enum InvalidMachoSectionReason { - #[note("a Mach-O section specifier requires a segment and a section, separated by a comma")] - #[help("an example of a valid Mach-O section specifier is `__TEXT,__cstring`")] - MissingSection, - #[note("section name `{$section}` is longer than 16 bytes")] - SectionTooLong { section: String }, -} - -#[derive(Diagnostic)] -#[diag("`#[sanitize({$field} = ...)]` attribute cannot be used on statics")] -#[help("`#[sanitize]` can be used on statics if only the address is sanitized")] -pub(crate) struct SanitizeInvalidStatic { - #[primary_span] - pub span: Span, - pub field: &'static str, -} - -#[derive(Diagnostic)] -#[diag("attribute items not separated with `,`")] -pub(crate) struct ExpectedComma { - #[primary_span] - #[suggestion( - "try adding `,` here", - code = ",", - applicability = "maybe-incorrect", - style = "short" - )] - pub span: Span, - #[subdiagnostic] - pub additional: Vec, -} - -#[derive(Subdiagnostic)] -#[suggestion("try adding `,` here", code = ",", applicability = "maybe-incorrect", style = "short")] -pub(crate) struct AdditionalCommaSuggestion { - #[primary_span] - pub 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, -} diff --git a/compiler/rustc_attr_parsing/src/target_checking.rs b/compiler/rustc_attr_parsing/src/target_checking.rs index 6b0d1b094ca0f..fc78279da0c62 100644 --- a/compiler/rustc_attr_parsing/src/target_checking.rs +++ b/compiler/rustc_attr_parsing/src/target_checking.rs @@ -9,9 +9,9 @@ use rustc_span::{BytePos, FileName, RemapPathScopeComponents, Span, Symbol, sym} use crate::context::AcceptContext; use crate::diagnostics::{ - InvalidAttrAtCrateLevel, ItemFollowingInnerAttr, UnsupportedAttributesInWhere, + InvalidAttrAtCrateLevel, InvalidTarget, InvalidTargetHelp, ItemFollowingInnerAttr, + UnsupportedAttributesInWhere, }; -use crate::session_diagnostics::{InvalidTarget, InvalidTargetHelp}; use crate::target_checking::Policy::Allow; use crate::{AttributeParser, ShouldEmit}; diff --git a/compiler/rustc_attr_parsing/src/validate_attr.rs b/compiler/rustc_attr_parsing/src/validate_attr.rs index 08c73352f27eb..53a06e27cc4e8 100644 --- a/compiler/rustc_attr_parsing/src/validate_attr.rs +++ b/compiler/rustc_attr_parsing/src/validate_attr.rs @@ -18,7 +18,7 @@ use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT; use rustc_session::parse::ParseSess; use rustc_span::{Span, Symbol, sym}; -use crate::{AttributeParser, AttributeTemplate, session_diagnostics as errors, template}; +use crate::{AttributeParser, AttributeTemplate, diagnostics as errors, template}; pub fn check_attr(psess: &ParseSess, attr: &Attribute) { use ast::SyntheticAttr::*;