From 20431706a863f92cb37dc512fef6e48d192aaf2c Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:11:38 +0200 Subject: Merging upstream version 1.66.0+dfsg1. Signed-off-by: Daniel Baumann --- compiler/rustc_passes/src/check_attr.rs | 277 +++--- compiler/rustc_passes/src/check_const.rs | 17 +- compiler/rustc_passes/src/dead.rs | 136 ++- compiler/rustc_passes/src/debugger_visualizer.rs | 15 +- compiler/rustc_passes/src/diagnostic_items.rs | 45 +- compiler/rustc_passes/src/entry.rs | 157 ++-- compiler/rustc_passes/src/errors.rs | 1095 +++++++++++++++++++--- compiler/rustc_passes/src/hir_id_validator.rs | 23 +- compiler/rustc_passes/src/hir_stats.rs | 4 +- compiler/rustc_passes/src/lang_items.rs | 211 ++--- compiler/rustc_passes/src/layout_test.rs | 77 +- compiler/rustc_passes/src/lib.rs | 3 +- compiler/rustc_passes/src/lib_features.rs | 34 +- compiler/rustc_passes/src/liveness.rs | 65 +- compiler/rustc_passes/src/loops.rs | 161 +--- compiler/rustc_passes/src/naked_functions.rs | 88 +- compiler/rustc_passes/src/reachable.rs | 53 +- compiler/rustc_passes/src/stability.rs | 230 ++--- compiler/rustc_passes/src/weak_lang_items.rs | 31 +- 19 files changed, 1659 insertions(+), 1063 deletions(-) (limited to 'compiler/rustc_passes/src') diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index b3f15ba7c..27a57adf9 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -4,16 +4,21 @@ //! conflicts between multiple such attributes attached to the same //! item. -use crate::errors; +use crate::errors::{ + self, AttrApplication, DebugVisualizerUnreadable, InvalidAttrAtCrateLevel, ObjectLifetimeErr, + OnlyHasEffectOn, TransparentIncompatible, UnrecognizedReprHint, +}; use rustc_ast::{ast, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem}; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{fluent, struct_span_err, Applicability, MultiSpan}; +use rustc_errors::{fluent, Applicability, MultiSpan}; use rustc_expand::base::resolve_path; use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; use rustc_hir as hir; -use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID}; +use rustc_hir::{ + self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID, +}; use rustc_hir::{MethodKind, Target}; use rustc_middle::hir::nested_filter; use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault; @@ -35,8 +40,8 @@ pub(crate) fn target_from_impl_item<'tcx>( match impl_item.kind { hir::ImplItemKind::Const(..) => Target::AssocConst, hir::ImplItemKind::Fn(..) => { - let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id()); - let containing_item = tcx.hir().expect_item(parent_hir_id); + let parent_def_id = tcx.hir().get_parent_item(impl_item.hir_id()).def_id; + let containing_item = tcx.hir().expect_item(parent_def_id); let containing_impl_is_for_trait = match &containing_item.kind { hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(), _ => bug!("parent of an ImplItem must be an Impl"), @@ -47,7 +52,7 @@ pub(crate) fn target_from_impl_item<'tcx>( Target::Method(MethodKind::Inherent) } } - hir::ImplItemKind::TyAlias(..) => Target::AssocTy, + hir::ImplItemKind::Type(..) => Target::AssocTy, } } @@ -162,17 +167,17 @@ impl CheckAttrVisitor<'_> { sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target), sym::deprecated => self.check_deprecated(hir_id, attr, span, target), sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target), - sym::path => self.check_generic_attr(hir_id, attr, target, &[Target::Mod]), + sym::path => self.check_generic_attr(hir_id, attr, target, Target::Mod), sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target), sym::macro_export => self.check_macro_export(hir_id, attr, target), sym::ignore | sym::should_panic | sym::proc_macro_derive => { - self.check_generic_attr(hir_id, attr, target, &[Target::Fn]) + self.check_generic_attr(hir_id, attr, target, Target::Fn) } sym::automatically_derived => { - self.check_generic_attr(hir_id, attr, target, &[Target::Impl]) + self.check_generic_attr(hir_id, attr, target, Target::Impl) } sym::no_implicit_prelude => { - self.check_generic_attr(hir_id, attr, target, &[Target::Mod]) + self.check_generic_attr(hir_id, attr, target, Target::Mod) } sym::rustc_object_lifetime_default => self.check_object_lifetime_default(hir_id), _ => {} @@ -263,7 +268,7 @@ impl CheckAttrVisitor<'_> { } // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with // just a lint, because we previously erroneously allowed it and some crates used it - // accidentally, to to be compatible with crates depending on them, we can't throw an + // accidentally, to be compatible with crates depending on them, we can't throw an // error here. Target::AssocConst => { self.tcx.emit_spanned_lint( @@ -349,29 +354,18 @@ impl CheckAttrVisitor<'_> { hir_id: HirId, attr: &Attribute, target: Target, - allowed_targets: &[Target], + allowed_target: Target, ) { - if !allowed_targets.iter().any(|t| t == &target) { - let name = attr.name_or_empty(); - let mut i = allowed_targets.iter(); - // Pluralize - let b = i.next().map_or_else(String::new, |t| t.to_string() + "s"); - let supported_names = i.enumerate().fold(b, |mut b, (i, allowed_target)| { - if allowed_targets.len() > 2 && i == allowed_targets.len() - 2 { - b.push_str(", and "); - } else if allowed_targets.len() == 2 && i == allowed_targets.len() - 2 { - b.push_str(" and "); - } else { - b.push_str(", "); - } - // Pluralize - b.push_str(&(allowed_target.to_string() + "s")); - b - }); - self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { - lint.build(&format!("`#[{name}]` only has an effect on {}", supported_names)) - .emit(); - }); + if target != allowed_target { + self.tcx.emit_spanned_lint( + UNUSED_ATTRIBUTES, + hir_id, + attr.span, + OnlyHasEffectOn { + attr_name: attr.name_or_empty(), + target_name: allowed_target.name().replace(" ", "_"), + }, + ); } } @@ -382,7 +376,7 @@ impl CheckAttrVisitor<'_> { | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[allow_internal_unstable]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked"); @@ -427,7 +421,7 @@ impl CheckAttrVisitor<'_> { ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(), ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(), }; - tcx.sess.span_err(p.span, &repr); + tcx.sess.emit_err(ObjectLifetimeErr { span: p.span, repr }); } } } @@ -462,7 +456,7 @@ impl CheckAttrVisitor<'_> { Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[track_caller]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { for attr in attrs { @@ -491,7 +485,7 @@ impl CheckAttrVisitor<'_> { Target::Struct | Target::Enum | Target::Variant => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[non_exhaustive]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive"); @@ -513,7 +507,7 @@ impl CheckAttrVisitor<'_> { Target::Trait => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[marker]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker"); @@ -572,7 +566,7 @@ impl CheckAttrVisitor<'_> { } // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[target_feature]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature"); @@ -640,8 +634,8 @@ impl CheckAttrVisitor<'_> { let span = meta.span(); if let Some(location) = match target { Target::AssocTy => { - let parent_hir_id = self.tcx.hir().get_parent_item(hir_id); - let containing_item = self.tcx.hir().expect_item(parent_hir_id); + let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id; + let containing_item = self.tcx.hir().expect_item(parent_def_id); if Target::from_item(containing_item) == Target::Impl { Some("type alias in implementation block") } else { @@ -649,8 +643,8 @@ impl CheckAttrVisitor<'_> { } } Target::AssocConst => { - let parent_hir_id = self.tcx.hir().get_parent_item(hir_id); - let containing_item = self.tcx.hir().expect_item(parent_hir_id); + let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id; + let containing_item = self.tcx.hir().expect_item(parent_def_id); // We can't link to trait impl's consts. let err = "associated constant in trait implementation block"; match containing_item.kind { @@ -828,8 +822,8 @@ impl CheckAttrVisitor<'_> { if let Some((prev_inline, prev_span)) = *specified_inline { if do_inline != prev_inline { let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]); - spans.push_span_label(prev_span, fluent::passes::doc_inline_conflict_first); - spans.push_span_label(meta.span(), fluent::passes::doc_inline_conflict_second); + spans.push_span_label(prev_span, fluent::passes_doc_inline_conflict_first); + spans.push_span_label(meta.span(), fluent::passes_doc_inline_conflict_second); self.tcx.sess.emit_err(errors::DocKeywordConflict { spans }); return false; } @@ -875,25 +869,31 @@ impl CheckAttrVisitor<'_> { hir_id: HirId, ) -> bool { if hir_id != CRATE_HIR_ID { - self.tcx.struct_span_lint_hir(INVALID_DOC_ATTRIBUTES, hir_id, meta.span(), |lint| { - let mut err = lint.build(fluent::passes::attr_crate_level); - if attr.style == AttrStyle::Outer - && self.tcx.hir().get_parent_item(hir_id) == CRATE_DEF_ID - { - if let Ok(mut src) = self.tcx.sess.source_map().span_to_snippet(attr.span) { - src.insert(1, '!'); - err.span_suggestion_verbose( - attr.span, - fluent::passes::suggestion, - src, - Applicability::MaybeIncorrect, - ); - } else { - err.span_help(attr.span, fluent::passes::help); + self.tcx.struct_span_lint_hir( + INVALID_DOC_ATTRIBUTES, + hir_id, + meta.span(), + fluent::passes_attr_crate_level, + |err| { + if attr.style == AttrStyle::Outer + && self.tcx.hir().get_parent_item(hir_id) == CRATE_OWNER_ID + { + if let Ok(mut src) = self.tcx.sess.source_map().span_to_snippet(attr.span) { + src.insert(1, '!'); + err.span_suggestion_verbose( + attr.span, + fluent::suggestion, + src, + Applicability::MaybeIncorrect, + ); + } else { + err.span_help(attr.span, fluent::help); + } } - } - err.note(fluent::passes::note).emit(); - }); + err.note(fluent::note); + err + }, + ); return false; } true @@ -934,6 +934,22 @@ impl CheckAttrVisitor<'_> { is_valid } + /// Check that the `#![doc(cfg_hide(...))]` attribute only contains a list of attributes. + /// Returns `true` if valid. + fn check_doc_cfg_hide(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool { + if meta.meta_item_list().is_some() { + true + } else { + self.tcx.emit_spanned_lint( + INVALID_DOC_ATTRIBUTES, + hir_id, + meta.span(), + errors::DocCfgHideTakesList, + ); + false + } + } + /// Runs various checks on `#[doc]` attributes. Returns `true` if valid. /// /// `specified_inline` should be initialized to `None` and kept for the scope @@ -987,6 +1003,13 @@ impl CheckAttrVisitor<'_> { is_valid = false; } + sym::cfg_hide + if !self.check_attr_crate_level(attr, meta, hir_id) + || !self.check_doc_cfg_hide(meta, hir_id) => + { + is_valid = false; + } + sym::inline | sym::no_inline if !self.check_doc_inline( attr, @@ -1205,7 +1228,7 @@ impl CheckAttrVisitor<'_> { Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[cold]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold"); @@ -1247,7 +1270,7 @@ impl CheckAttrVisitor<'_> { Target::ForeignFn | Target::ForeignStatic => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[link_name]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name"); @@ -1281,7 +1304,7 @@ impl CheckAttrVisitor<'_> { Target::ExternCrate => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[no_link]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link"); @@ -1311,7 +1334,7 @@ impl CheckAttrVisitor<'_> { Target::Method(..) if self.is_impl_item(hir_id) => true, // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[export_name]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name"); @@ -1503,7 +1526,7 @@ impl CheckAttrVisitor<'_> { Target::Static | Target::Fn | Target::Method(..) => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[link_section]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section"); @@ -1528,7 +1551,7 @@ impl CheckAttrVisitor<'_> { Target::Method(..) if self.is_impl_item(hir_id) => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[no_mangle]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle"); @@ -1594,12 +1617,17 @@ impl CheckAttrVisitor<'_> { continue; } - let (article, allowed_targets) = match hint.name_or_empty() { + match hint.name_or_empty() { sym::C => { is_c = true; match target { Target::Struct | Target::Union | Target::Enum => continue, - _ => ("a", "struct, enum, or union"), + _ => { + self.tcx.sess.emit_err(AttrApplication::StructEnumUnion { + hint_span: hint.span(), + span, + }); + } } } sym::align => { @@ -1615,12 +1643,20 @@ impl CheckAttrVisitor<'_> { match target { Target::Struct | Target::Union | Target::Enum | Target::Fn => continue, - _ => ("a", "struct, enum, function, or union"), + _ => { + self.tcx.sess.emit_err(AttrApplication::StructEnumFunctionUnion { + hint_span: hint.span(), + span, + }); + } } } sym::packed => { if target != Target::Struct && target != Target::Union { - ("a", "struct or union") + self.tcx.sess.emit_err(AttrApplication::StructUnion { + hint_span: hint.span(), + span, + }); } else { continue; } @@ -1628,7 +1664,9 @@ impl CheckAttrVisitor<'_> { sym::simd => { is_simd = true; if target != Target::Struct { - ("a", "struct") + self.tcx + .sess + .emit_err(AttrApplication::Struct { hint_span: hint.span(), span }); } else { continue; } @@ -1637,7 +1675,12 @@ impl CheckAttrVisitor<'_> { is_transparent = true; match target { Target::Struct | Target::Union | Target::Enum => continue, - _ => ("a", "struct, enum, or union"), + _ => { + self.tcx.sess.emit_err(AttrApplication::StructEnumUnion { + hint_span: hint.span(), + span, + }); + } } } sym::i8 @@ -1654,35 +1697,18 @@ impl CheckAttrVisitor<'_> { | sym::usize => { int_reprs += 1; if target != Target::Enum { - ("an", "enum") + self.tcx + .sess + .emit_err(AttrApplication::Enum { hint_span: hint.span(), span }); } else { continue; } } _ => { - struct_span_err!( - self.tcx.sess, - hint.span(), - E0552, - "unrecognized representation hint" - ) - .help("valid reprs are `C`, `align`, `packed`, `transparent`, `simd`, `i8`, `u8`, \ - `i16`, `u16`, `i32`, `u32`, `i64`, `u64`, `i128`, `u128`, `isize`, `usize`") - .emit(); - + self.tcx.sess.emit_err(UnrecognizedReprHint { span: hint.span() }); continue; } }; - - struct_span_err!( - self.tcx.sess, - hint.span(), - E0517, - "{}", - &format!("attribute should be applied to {article} {allowed_targets}") - ) - .span_label(span, &format!("not {article} {allowed_targets}")) - .emit(); } // Just point at all repr hints if there are any incompatibilities. @@ -1692,14 +1718,9 @@ impl CheckAttrVisitor<'_> { // Error on repr(transparent, ). if is_transparent && hints.len() > 1 { let hint_spans: Vec<_> = hint_spans.clone().collect(); - struct_span_err!( - self.tcx.sess, - hint_spans, - E0692, - "transparent {} cannot have other repr hints", - target - ) - .emit(); + self.tcx + .sess + .emit_err(TransparentIncompatible { hint_spans, target: target.to_string() }); } // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8) if (int_reprs > 1) @@ -1742,7 +1763,7 @@ impl CheckAttrVisitor<'_> { } } Some(_) => { - // This error case is handled in rustc_typeck::collect. + // This error case is handled in rustc_hir_analysis::collect. } None => { // Default case (compiler) when arg isn't defined. @@ -1784,7 +1805,7 @@ impl CheckAttrVisitor<'_> { Target::MacroDef => true, // FIXME(#80564): We permit struct fields and match arms to have an // `#[allow_internal_unstable]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm => { self.inline_attr_str_error_without_macro_def( @@ -1851,14 +1872,12 @@ impl CheckAttrVisitor<'_> { match std::fs::File::open(&file) { Ok(_) => true, - Err(err) => { - self.tcx - .sess - .struct_span_err( - meta_item.span, - &format!("couldn't read {}: {}", file.display(), err), - ) - .emit(); + Err(error) => { + self.tcx.sess.emit_err(DebugVisualizerUnreadable { + span: meta_item.span, + file: &file, + error, + }); false } } @@ -1881,7 +1900,7 @@ impl CheckAttrVisitor<'_> { } // FIXME(#80564): We permit struct fields and match arms to have an // `#[allow_internal_unstable]` attribute with just a lint, because we previously - // erroneously allowed it and some crates used it accidentally, to to be compatible + // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable"); @@ -2043,7 +2062,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { // so this lets us continue to run them while maintaining backwards compatibility. // In the long run, the checks should be harmonized. if let ItemKind::Macro(ref macro_def, _) = item.kind { - let def_id = item.def_id.to_def_id(); + let def_id = item.owner_id.to_def_id(); if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) { check_non_exported_macro_for_invalid_attrs(self.tcx, item); } @@ -2169,25 +2188,11 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) { if attr.style == AttrStyle::Inner { for attr_to_check in ATTRS_TO_CHECK { if attr.has_name(*attr_to_check) { - let mut err = tcx.sess.struct_span_err( - attr.span, - &format!( - "`{}` attribute cannot be used at crate level", - attr_to_check.to_ident_string() - ), - ); - // Only emit an error with a suggestion if we can create a - // string out of the attribute span - if let Ok(src) = tcx.sess.source_map().span_to_snippet(attr.span) { - let replacement = src.replace("#!", "#"); - err.span_suggestion_verbose( - attr.span, - "perhaps you meant to use an outer attribute", - replacement, - rustc_errors::Applicability::MachineApplicable, - ); - } - err.emit(); + tcx.sess.emit_err(InvalidAttrAtCrateLevel { + span: attr.span, + snippet: tcx.sess.source_map().span_to_snippet(attr.span).ok(), + name: *attr_to_check, + }); } } } diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index 70518284c..aa726d6cd 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -8,7 +8,6 @@ //! through, but errors for structured control flow in a `const` should be emitted here. use rustc_attr as attr; -use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; @@ -18,6 +17,8 @@ use rustc_middle::ty::TyCtxt; use rustc_session::parse::feature_err; use rustc_span::{sym, Span, Symbol}; +use crate::errors::ExprNotAllowedInContext; + /// An expression that is not *always* legal in a const context. #[derive(Clone, Copy)] enum NonConstExpr { @@ -133,18 +134,22 @@ impl<'tcx> CheckConstVisitor<'tcx> { let const_kind = const_kind.expect("`const_check_violated` may only be called inside a const context"); - let msg = format!("{} is not allowed in a `{}`", expr.name(), const_kind.keyword_name()); - let required_gates = required_gates.unwrap_or(&[]); let missing_gates: Vec<_> = required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect(); match missing_gates.as_slice() { [] => { - struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit(); + tcx.sess.emit_err(ExprNotAllowedInContext { + span, + expr: expr.name(), + context: const_kind.keyword_name(), + }); } [missing_primary, ref missing_secondary @ ..] => { + let msg = + format!("{} is not allowed in a `{}`", expr.name(), const_kind.keyword_name()); let mut err = feature_err(&tcx.sess.parse_sess, *missing_primary, span, &msg); // If multiple feature gates would be required to enable this expression, include @@ -191,10 +196,6 @@ impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> { self.tcx.hir() } - fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - intravisit::walk_item(self, item); - } - fn visit_anon_const(&mut self, anon: &'tcx hir::AnonConst) { let kind = Some(hir::ConstContext::Const); self.recurse_into(kind, None, |this| intravisit::walk_anon_const(this, anon)); diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index f141d7bee..753d01f46 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -11,13 +11,15 @@ use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{Node, PatKind, TyKind}; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use rustc_middle::middle::privacy; +use rustc_middle::middle::privacy::Level; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, DefIdTree, TyCtxt}; use rustc_session::lint; use rustc_span::symbol::{sym, Symbol}; use std::mem; +use crate::errors::UselessAssignment; + // Any local node that may call something in its body block should be // explored. For example, if it's a live Node::Item that is a // function, then we should explore its block to check for codes that @@ -102,14 +104,8 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { } } Res::Def(_, def_id) => self.check_def_id(def_id), - Res::SelfTy { trait_: t, alias_to: i } => { - if let Some(t) = t { - self.check_def_id(t); - } - if let Some((i, _)) = i { - self.check_def_id(i); - } - } + Res::SelfTyParam { trait_: t } => self.check_def_id(t), + Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i), Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {} } } @@ -186,18 +182,11 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { && !assign.span.from_expansion() { let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..)); - self.tcx.struct_span_lint_hir( + self.tcx.emit_spanned_lint( lint::builtin::DEAD_CODE, assign.hir_id, assign.span, - |lint| { - lint.build(&format!( - "useless assignment of {} of type `{}` to itself", - if is_field_assign { "field" } else { "variable" }, - self.typeck_results().expr_ty(lhs), - )) - .emit(); - }, + UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) } ) } } @@ -291,8 +280,8 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { } fn visit_node(&mut self, node: Node<'tcx>) { - if let Node::ImplItem(hir::ImplItem { def_id, .. }) = node - && self.should_ignore_item(def_id.to_def_id()) + if let Node::ImplItem(hir::ImplItem { owner_id, .. }) = node + && self.should_ignore_item(owner_id.to_def_id()) { return; } @@ -304,7 +293,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { match node { Node::Item(item) => match item.kind { hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { - let def = self.tcx.adt_def(item.def_id); + let def = self.tcx.adt_def(item.owner_id); self.repr_has_repr_c = def.repr().c(); self.repr_has_repr_simd = def.repr().simd(); @@ -317,7 +306,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { intravisit::walk_trait_item(self, trait_item); } Node::ImplItem(impl_item) => { - let item = self.tcx.local_parent(impl_item.def_id); + let item = self.tcx.local_parent(impl_item.owner_id.def_id); if self.tcx.impl_trait_ref(item).is_none() { //// If it's a type whose items are live, then it's live, too. //// This is done to handle the case where, for example, the static @@ -374,7 +363,7 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> { if has_repr_c || (f.is_positional() && has_repr_simd) { return Some(def_id); } - if !tcx.visibility(f.hir_id.owner).is_public() { + if !tcx.visibility(f.hir_id.owner.def_id).is_public() { return None; } if tcx.visibility(def_id).is_public() { Some(def_id) } else { None } @@ -528,10 +517,10 @@ fn check_item<'tcx>( ) { let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.hir_id()); if allow_dead_code { - worklist.push(id.def_id); + worklist.push(id.owner_id.def_id); } - match tcx.def_kind(id.def_id) { + match tcx.def_kind(id.owner_id) { DefKind::Enum => { let item = tcx.hir().item(id); if let hir::ItemKind::Enum(ref enum_def, _) = item.kind { @@ -551,15 +540,15 @@ fn check_item<'tcx>( } } DefKind::Impl => { - let of_trait = tcx.impl_trait_ref(id.def_id); + let of_trait = tcx.impl_trait_ref(id.owner_id); if of_trait.is_some() { - worklist.push(id.def_id); + worklist.push(id.owner_id.def_id); } // get DefIds from another query let local_def_ids = tcx - .associated_item_def_ids(id.def_id) + .associated_item_def_ids(id.owner_id) .iter() .filter_map(|def_id| def_id.as_local()); @@ -577,12 +566,12 @@ fn check_item<'tcx>( if let hir::ItemKind::Struct(ref variant_data, _) = item.kind && let Some(ctor_hir_id) = variant_data.ctor_hir_id() { - struct_constructors.insert(tcx.hir().local_def_id(ctor_hir_id), item.def_id); + struct_constructors.insert(tcx.hir().local_def_id(ctor_hir_id), item.owner_id.def_id); } } DefKind::GlobalAsm => { // global_asm! is always live. - worklist.push(id.def_id); + worklist.push(id.owner_id.def_id); } _ => {} } @@ -590,12 +579,12 @@ fn check_item<'tcx>( fn check_trait_item<'tcx>(tcx: TyCtxt<'tcx>, worklist: &mut Vec, id: hir::TraitItemId) { use hir::TraitItemKind::{Const, Fn}; - if matches!(tcx.def_kind(id.def_id), DefKind::AssocConst | DefKind::AssocFn) { + if matches!(tcx.def_kind(id.owner_id), DefKind::AssocConst | DefKind::AssocFn) { let trait_item = tcx.hir().trait_item(id); if matches!(trait_item.kind, Const(_, Some(_)) | Fn(_, hir::TraitFn::Provided(_))) && has_allow_dead_code_or_lang_attr(tcx, trait_item.hir_id()) { - worklist.push(trait_item.def_id); + worklist.push(trait_item.owner_id.def_id); } } } @@ -605,27 +594,24 @@ fn check_foreign_item<'tcx>( worklist: &mut Vec, id: hir::ForeignItemId, ) { - if matches!(tcx.def_kind(id.def_id), DefKind::Static(_) | DefKind::Fn) + if matches!(tcx.def_kind(id.owner_id), DefKind::Static(_) | DefKind::Fn) && has_allow_dead_code_or_lang_attr(tcx, id.hir_id()) { - worklist.push(id.def_id); + worklist.push(id.owner_id.def_id); } } fn create_and_seed_worklist<'tcx>( tcx: TyCtxt<'tcx>, ) -> (Vec, FxHashMap) { - let access_levels = &tcx.privacy_access_levels(()); + let effective_visibilities = &tcx.effective_visibilities(()); // see `MarkSymbolVisitor::struct_constructors` let mut struct_constructors = Default::default(); - let mut worklist = access_levels - .map + let mut worklist = effective_visibilities .iter() - .filter_map( - |(&id, &level)| { - if level >= privacy::AccessLevel::Reachable { Some(id) } else { None } - }, - ) + .filter_map(|(&id, effective_vis)| { + effective_vis.is_public_at_level(Level::Reachable).then_some(id) + }) // Seed entry point .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local())) .collect::>(); @@ -726,6 +712,26 @@ impl<'tcx> DeadVisitor<'tcx> { }) .collect(); + let descr = tcx.def_kind(first_id).descr(first_id.to_def_id()); + let span_len = dead_codes.len(); + let names = match &names[..] { + _ if span_len > 6 => String::new(), + [name] => format!("`{name}` "), + [names @ .., last] => { + format!( + "{} and `{last}` ", + names.iter().map(|name| format!("`{name}`")).join(", ") + ) + } + [] => unreachable!(), + }; + let msg = format!( + "{these}{descr}{s} {names}{are} never {participle}", + these = if span_len > 6 { "multiple " } else { "" }, + s = pluralize!(span_len), + are = pluralize!("is", span_len), + ); + tcx.struct_span_lint_hir( if is_positional { lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS @@ -734,27 +740,8 @@ impl<'tcx> DeadVisitor<'tcx> { }, tcx.hir().local_def_id_to_hir_id(first_id), MultiSpan::from_spans(spans.clone()), - |lint| { - let descr = tcx.def_kind(first_id).descr(first_id.to_def_id()); - let span_len = dead_codes.len(); - let names = match &names[..] { - _ if span_len > 6 => String::new(), - [name] => format!("`{name}` "), - [names @ .., last] => { - format!( - "{} and `{last}` ", - names.iter().map(|name| format!("`{name}`")).join(", ") - ) - } - [] => unreachable!(), - }; - let mut err = lint.build(&format!( - "{these}{descr}{s} {names}{are} never {participle}", - these = if span_len > 6 { "multiple " } else { "" }, - s = pluralize!(span_len), - are = pluralize!("is", span_len), - )); - + msg, + |err| { if is_positional { err.multipart_suggestion( &format!( @@ -800,7 +787,7 @@ impl<'tcx> DeadVisitor<'tcx> { ); err.note(&msg); } - err.emit(); + err }, ); } @@ -874,19 +861,19 @@ fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) { let module_items = tcx.hir_module_items(module); for item in module_items.items() { - if !live_symbols.contains(&item.def_id) { - let parent = tcx.local_parent(item.def_id); + if !live_symbols.contains(&item.owner_id.def_id) { + let parent = tcx.local_parent(item.owner_id.def_id); if parent != module && !live_symbols.contains(&parent) { // We already have diagnosed something. continue; } - visitor.check_definition(item.def_id); + visitor.check_definition(item.owner_id.def_id); continue; } - let def_kind = tcx.def_kind(item.def_id); + let def_kind = tcx.def_kind(item.owner_id); if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind { - let adt = tcx.adt_def(item.def_id); + let adt = tcx.adt_def(item.owner_id); let mut dead_variants = Vec::new(); for variant in adt.variants() { @@ -929,16 +916,21 @@ fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) { visitor.warn_dead_fields_and_variants(def_id, "read", dead_fields, is_positional) } - visitor.warn_dead_fields_and_variants(item.def_id, "constructed", dead_variants, false); + visitor.warn_dead_fields_and_variants( + item.owner_id.def_id, + "constructed", + dead_variants, + false, + ); } } for impl_item in module_items.impl_items() { - visitor.check_definition(impl_item.def_id); + visitor.check_definition(impl_item.owner_id.def_id); } for foreign_item in module_items.foreign_items() { - visitor.check_definition(foreign_item.def_id); + visitor.check_definition(foreign_item.owner_id.def_id); } // We do not warn trait items. diff --git a/compiler/rustc_passes/src/debugger_visualizer.rs b/compiler/rustc_passes/src/debugger_visualizer.rs index e08683fe2..253b0a88e 100644 --- a/compiler/rustc_passes/src/debugger_visualizer.rs +++ b/compiler/rustc_passes/src/debugger_visualizer.rs @@ -13,6 +13,8 @@ use rustc_span::{sym, DebuggerVisualizerFile, DebuggerVisualizerType}; use std::sync::Arc; +use crate::errors::DebugVisualizerUnreadable; + fn check_for_debugger_visualizer<'tcx>( tcx: TyCtxt<'tcx>, hir_id: HirId, @@ -54,13 +56,12 @@ fn check_for_debugger_visualizer<'tcx>( debugger_visualizers .insert(DebuggerVisualizerFile::new(Arc::from(contents), visualizer_type)); } - Err(err) => { - tcx.sess - .struct_span_err( - meta_item.span, - &format!("couldn't read {}: {}", file.display(), err), - ) - .emit(); + Err(error) => { + tcx.sess.emit_err(DebugVisualizerUnreadable { + span: meta_item.span, + file: &file, + error, + }); } } } diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index e6b69d898..a72056e00 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -14,7 +14,9 @@ use rustc_hir::diagnostic_items::DiagnosticItems; use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{kw::Empty, sym, Symbol}; + +use crate::errors::{DuplicateDiagnosticItem, DuplicateDiagnosticItemInCrate}; fn observe_item<'tcx>( tcx: TyCtxt<'tcx>, @@ -33,25 +35,22 @@ fn collect_item(tcx: TyCtxt<'_>, items: &mut DiagnosticItems, name: Symbol, item items.id_to_name.insert(item_def_id, name); if let Some(original_def_id) = items.name_to_id.insert(name, item_def_id) { if original_def_id != item_def_id { - let mut err = match tcx.hir().span_if_local(item_def_id) { - Some(span) => tcx - .sess - .struct_span_err(span, &format!("duplicate diagnostic item found: `{name}`.")), - None => tcx.sess.struct_err(&format!( - "duplicate diagnostic item in crate `{}`: `{}`.", - tcx.crate_name(item_def_id.krate), - name - )), - }; - if let Some(span) = tcx.hir().span_if_local(original_def_id) { - err.span_note(span, "the diagnostic item is first defined here"); + let orig_span = tcx.hir().span_if_local(original_def_id); + let orig_crate_name = if orig_span.is_some() { + None } else { - err.note(&format!( - "the diagnostic item is first defined in crate `{}`.", - tcx.crate_name(original_def_id.krate) - )); - } - err.emit(); + Some(tcx.crate_name(original_def_id.krate)) + }; + match tcx.hir().span_if_local(item_def_id) { + Some(span) => tcx.sess.emit_err(DuplicateDiagnosticItem { span, name }), + None => tcx.sess.emit_err(DuplicateDiagnosticItemInCrate { + span: orig_span, + orig_crate_name: orig_crate_name.unwrap_or(Empty), + have_orig_crate_name: orig_crate_name.map(|_| ()), + crate_name: tcx.crate_name(item_def_id.krate), + name, + }), + }; } } } @@ -74,19 +73,19 @@ fn diagnostic_items<'tcx>(tcx: TyCtxt<'tcx>, cnum: CrateNum) -> DiagnosticItems let crate_items = tcx.hir_crate_items(()); for id in crate_items.items() { - observe_item(tcx, &mut diagnostic_items, id.def_id); + observe_item(tcx, &mut diagnostic_items, id.owner_id.def_id); } for id in crate_items.trait_items() { - observe_item(tcx, &mut diagnostic_items, id.def_id); + observe_item(tcx, &mut diagnostic_items, id.owner_id.def_id); } for id in crate_items.impl_items() { - observe_item(tcx, &mut diagnostic_items, id.def_id); + observe_item(tcx, &mut diagnostic_items, id.owner_id.def_id); } for id in crate_items.foreign_items() { - observe_item(tcx, &mut diagnostic_items, id.def_id); + observe_item(tcx, &mut diagnostic_items, id.owner_id.def_id); } diagnostic_items diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index cd10170d3..5885f45ae 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -1,5 +1,5 @@ use rustc_ast::entry::EntryPointType; -use rustc_errors::struct_span_err; +use rustc_errors::error_code; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::{ItemId, Node, CRATE_HIR_ID}; @@ -8,7 +8,12 @@ use rustc_middle::ty::{DefIdTree, TyCtxt}; use rustc_session::config::{sigpipe, CrateType, EntryFnType}; use rustc_session::parse::feature_err; use rustc_span::symbol::sym; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::{Span, Symbol}; + +use crate::errors::{ + AttrOnlyInFunctions, AttrOnlyOnMain, AttrOnlyOnRootMain, ExternMain, MultipleRustcMain, + MultipleStartFunctions, NoMainErr, UnixSigpipeValues, +}; struct EntryContext<'tcx> { tcx: TyCtxt<'tcx>, @@ -57,7 +62,7 @@ fn entry_point_type(ctxt: &EntryContext<'_>, id: ItemId, at_root: bool) -> Entry } else if ctxt.tcx.sess.contains_name(attrs, sym::rustc_main) { EntryPointType::RustcMainAttr } else { - if let Some(name) = ctxt.tcx.opt_item_name(id.def_id.to_def_id()) + if let Some(name) = ctxt.tcx.opt_item_name(id.owner_id.to_def_id()) && name == sym::main { if at_root { // This is a top-level function so can be `main`. @@ -71,64 +76,57 @@ fn entry_point_type(ctxt: &EntryContext<'_>, id: ItemId, at_root: bool) -> Entry } } -fn err_if_attr_found(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol, details: &str) { +fn attr_span_by_symbol(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol) -> Option { let attrs = ctxt.tcx.hir().attrs(id.hir_id()); - if let Some(attr) = ctxt.tcx.sess.find_by_name(attrs, sym) { - ctxt.tcx - .sess - .struct_span_err(attr.span, &format!("`{}` attribute {}", sym, details)) - .emit(); - } + ctxt.tcx.sess.find_by_name(attrs, sym).map(|attr| attr.span) } fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) { - let at_root = ctxt.tcx.opt_local_parent(id.def_id) == Some(CRATE_DEF_ID); + let at_root = ctxt.tcx.opt_local_parent(id.owner_id.def_id) == Some(CRATE_DEF_ID); match entry_point_type(ctxt, id, at_root) { EntryPointType::None => { - err_if_attr_found(ctxt, id, sym::unix_sigpipe, "can only be used on `fn main()`"); + if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) { + ctxt.tcx.sess.emit_err(AttrOnlyOnMain { span, attr: sym::unix_sigpipe }); + } } - _ if !matches!(ctxt.tcx.def_kind(id.def_id), DefKind::Fn) => { - err_if_attr_found(ctxt, id, sym::start, "can only be used on functions"); - err_if_attr_found(ctxt, id, sym::rustc_main, "can only be used on functions"); + _ if !matches!(ctxt.tcx.def_kind(id.owner_id), DefKind::Fn) => { + for attr in [sym::start, sym::rustc_main] { + if let Some(span) = attr_span_by_symbol(ctxt, id, attr) { + ctxt.tcx.sess.emit_err(AttrOnlyInFunctions { span, attr }); + } + } } EntryPointType::MainNamed => (), EntryPointType::OtherMain => { - err_if_attr_found(ctxt, id, sym::unix_sigpipe, "can only be used on root `fn main()`"); - ctxt.non_main_fns.push(ctxt.tcx.def_span(id.def_id)); + if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) { + ctxt.tcx.sess.emit_err(AttrOnlyOnRootMain { span, attr: sym::unix_sigpipe }); + } + ctxt.non_main_fns.push(ctxt.tcx.def_span(id.owner_id)); } EntryPointType::RustcMainAttr => { if ctxt.attr_main_fn.is_none() { - ctxt.attr_main_fn = Some((id.def_id, ctxt.tcx.def_span(id.def_id.to_def_id()))); + ctxt.attr_main_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id))); } else { - struct_span_err!( - ctxt.tcx.sess, - ctxt.tcx.def_span(id.def_id.to_def_id()), - E0137, - "multiple functions with a `#[rustc_main]` attribute" - ) - .span_label( - ctxt.tcx.def_span(id.def_id.to_def_id()), - "additional `#[rustc_main]` function", - ) - .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[rustc_main]` function") - .emit(); + ctxt.tcx.sess.emit_err(MultipleRustcMain { + span: ctxt.tcx.def_span(id.owner_id.to_def_id()), + first: ctxt.attr_main_fn.unwrap().1, + additional: ctxt.tcx.def_span(id.owner_id.to_def_id()), + }); } } EntryPointType::Start => { - err_if_attr_found(ctxt, id, sym::unix_sigpipe, "can only be used on `fn main()`"); + if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) { + ctxt.tcx.sess.emit_err(AttrOnlyOnMain { span, attr: sym::unix_sigpipe }); + } if ctxt.start_fn.is_none() { - ctxt.start_fn = Some((id.def_id, ctxt.tcx.def_span(id.def_id.to_def_id()))); + ctxt.start_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id))); } else { - struct_span_err!( - ctxt.tcx.sess, - ctxt.tcx.def_span(id.def_id.to_def_id()), - E0138, - "multiple `start` functions" - ) - .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here") - .span_label(ctxt.tcx.def_span(id.def_id.to_def_id()), "multiple `start` functions") - .emit(); + ctxt.tcx.sess.emit_err(MultipleStartFunctions { + span: ctxt.tcx.def_span(id.owner_id), + labeled: ctxt.tcx.def_span(id.owner_id.to_def_id()), + previous: ctxt.start_fn.unwrap().1, + }); } } } @@ -144,12 +142,7 @@ fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) -> Option<(DefId, if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() { // non-local main imports are handled below if let Some(def_id) = def_id.as_local() && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) { - tcx.sess - .struct_span_err( - tcx.def_span(def_id), - "the `main` function cannot be declared in an `extern` block", - ) - .emit(); + tcx.sess.emit_err(ExternMain { span: tcx.def_span(def_id) }); return None; } @@ -182,12 +175,7 @@ fn sigpipe(tcx: TyCtxt<'_>, def_id: DefId) -> u8 { sigpipe::DEFAULT } _ => { - tcx.sess - .struct_span_err( - attr.span, - "valid values for `#[unix_sigpipe = \"...\"]` are `inherit`, `sig_ign`, or `sig_dfl`", - ) - .emit(); + tcx.sess.emit_err(UnixSigpipeValues { span: attr.span }); sigpipe::DEFAULT } } @@ -206,52 +194,29 @@ fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) { } // There is no main function. - let mut err = struct_span_err!( - tcx.sess, - DUMMY_SP, - E0601, - "`main` function not found in crate `{}`", - tcx.crate_name(LOCAL_CRATE) - ); - let filename = &tcx.sess.local_crate_source_file; - let note = if !visitor.non_main_fns.is_empty() { - for &span in &visitor.non_main_fns { - err.span_note(span, "here is a function named `main`"); - } - err.note("you have one or more functions named `main` not defined at the crate level"); - err.help("consider moving the `main` function definitions"); - // There were some functions named `main` though. Try to give the user a hint. - format!( - "the main function must be defined at the crate level{}", - filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default() - ) - } else if let Some(filename) = filename { - format!("consider adding a `main` function to `{}`", filename.display()) - } else { - String::from("consider adding a `main` function at the crate level") - }; + let mut has_filename = true; + let filename = tcx.sess.local_crate_source_file.clone().unwrap_or_else(|| { + has_filename = false; + Default::default() + }); + let main_def_opt = tcx.resolutions(()).main_def; + let diagnostic_id = error_code!(E0601); + let add_teach_note = tcx.sess.teach(&diagnostic_id); // The file may be empty, which leads to the diagnostic machinery not emitting this // note. This is a relatively simple way to detect that case and emit a span-less // note instead. - if tcx.sess.source_map().lookup_line(sp.hi()).is_ok() { - err.set_span(sp.shrink_to_hi()); - err.span_label(sp.shrink_to_hi(), ¬e); - } else { - err.note(¬e); - } - - if let Some(main_def) = tcx.resolutions(()).main_def && main_def.opt_fn_def_id().is_none(){ - // There is something at `crate::main`, but it is not a function definition. - err.span_label(main_def.span, "non-function item at `crate::main` is found"); - } - - if tcx.sess.teach(&err.get_code().unwrap()) { - err.note( - "If you don't know the basics of Rust, you can go look to the Rust Book \ - to get started: https://doc.rust-lang.org/book/", - ); - } - err.emit(); + let file_empty = !tcx.sess.source_map().lookup_line(sp.hi()).is_ok(); + + tcx.sess.emit_err(NoMainErr { + sp, + crate_name: tcx.crate_name(LOCAL_CRATE), + has_filename, + filename, + file_empty, + non_main_fns: visitor.non_main_fns.clone(), + main_def_opt, + add_teach_note, + }); } pub fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 96cc8ae98..adaaf5392 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1,39 +1,49 @@ -use rustc_errors::{Applicability, MultiSpan}; -use rustc_macros::{LintDiagnostic, SessionDiagnostic, SessionSubdiagnostic}; -use rustc_span::{Span, Symbol}; +use std::{ + io::Error, + path::{Path, PathBuf}, +}; + +use rustc_ast::Label; +use rustc_errors::{error_code, Applicability, ErrorGuaranteed, IntoDiagnostic, MultiSpan}; +use rustc_hir::{self as hir, ExprKind, Target}; +use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; +use rustc_middle::ty::{MainDefinition, Ty}; +use rustc_span::{Span, Symbol, DUMMY_SP}; + +use crate::lang_items::Duplicate; #[derive(LintDiagnostic)] -#[diag(passes::outer_crate_level_attr)] +#[diag(passes_outer_crate_level_attr)] pub struct OuterCrateLevelAttr; #[derive(LintDiagnostic)] -#[diag(passes::inner_crate_level_attr)] +#[diag(passes_inner_crate_level_attr)] pub struct InnerCrateLevelAttr; #[derive(LintDiagnostic)] -#[diag(passes::ignored_attr_with_macro)] +#[diag(passes_ignored_attr_with_macro)] pub struct IgnoredAttrWithMacro<'a> { pub sym: &'a str, } #[derive(LintDiagnostic)] -#[diag(passes::ignored_attr)] +#[diag(passes_ignored_attr)] pub struct IgnoredAttr<'a> { pub sym: &'a str, } #[derive(LintDiagnostic)] -#[diag(passes::inline_ignored_function_prototype)] +#[diag(passes_inline_ignored_function_prototype)] pub struct IgnoredInlineAttrFnProto; #[derive(LintDiagnostic)] -#[diag(passes::inline_ignored_constants)] +#[diag(passes_inline_ignored_constants)] #[warning] #[note] pub struct IgnoredInlineAttrConstants; -#[derive(SessionDiagnostic)] -#[diag(passes::inline_not_fn_or_closure, code = "E0518")] +#[derive(Diagnostic)] +#[diag(passes_inline_not_fn_or_closure, code = "E0518")] pub struct InlineNotFnOrClosure { #[primary_span] pub attr_span: Span, @@ -42,19 +52,19 @@ pub struct InlineNotFnOrClosure { } #[derive(LintDiagnostic)] -#[diag(passes::no_coverage_ignored_function_prototype)] +#[diag(passes_no_coverage_ignored_function_prototype)] pub struct IgnoredNoCoverageFnProto; #[derive(LintDiagnostic)] -#[diag(passes::no_coverage_propagate)] +#[diag(passes_no_coverage_propagate)] pub struct IgnoredNoCoveragePropagate; #[derive(LintDiagnostic)] -#[diag(passes::no_coverage_fn_defn)] +#[diag(passes_no_coverage_fn_defn)] pub struct IgnoredNoCoverageFnDefn; -#[derive(SessionDiagnostic)] -#[diag(passes::no_coverage_not_coverable, code = "E0788")] +#[derive(Diagnostic)] +#[diag(passes_no_coverage_not_coverable, code = "E0788")] pub struct IgnoredNoCoverageNotCoverable { #[primary_span] pub attr_span: Span, @@ -62,8 +72,8 @@ pub struct IgnoredNoCoverageNotCoverable { pub defn_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::should_be_applied_to_fn)] +#[derive(Diagnostic)] +#[diag(passes_should_be_applied_to_fn)] pub struct AttrShouldBeAppliedToFn { #[primary_span] pub attr_span: Span, @@ -71,15 +81,15 @@ pub struct AttrShouldBeAppliedToFn { pub defn_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::naked_tracked_caller, code = "E0736")] +#[derive(Diagnostic)] +#[diag(passes_naked_tracked_caller, code = "E0736")] pub struct NakedTrackedCaller { #[primary_span] pub attr_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::should_be_applied_to_fn, code = "E0739")] +#[derive(Diagnostic)] +#[diag(passes_should_be_applied_to_fn, code = "E0739")] pub struct TrackedCallerWrongLocation { #[primary_span] pub attr_span: Span, @@ -87,8 +97,8 @@ pub struct TrackedCallerWrongLocation { pub defn_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::should_be_applied_to_struct_enum, code = "E0701")] +#[derive(Diagnostic)] +#[diag(passes_should_be_applied_to_struct_enum, code = "E0701")] pub struct NonExhaustiveWrongLocation { #[primary_span] pub attr_span: Span, @@ -96,8 +106,8 @@ pub struct NonExhaustiveWrongLocation { pub defn_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::should_be_applied_to_trait)] +#[derive(Diagnostic)] +#[diag(passes_should_be_applied_to_trait)] pub struct AttrShouldBeAppliedToTrait { #[primary_span] pub attr_span: Span, @@ -106,11 +116,11 @@ pub struct AttrShouldBeAppliedToTrait { } #[derive(LintDiagnostic)] -#[diag(passes::target_feature_on_statement)] +#[diag(passes_target_feature_on_statement)] pub struct TargetFeatureOnStatement; -#[derive(SessionDiagnostic)] -#[diag(passes::should_be_applied_to_static)] +#[derive(Diagnostic)] +#[diag(passes_should_be_applied_to_static)] pub struct AttrShouldBeAppliedToStatic { #[primary_span] pub attr_span: Span, @@ -118,24 +128,24 @@ pub struct AttrShouldBeAppliedToStatic { pub defn_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_expect_str)] +#[derive(Diagnostic)] +#[diag(passes_doc_expect_str)] pub struct DocExpectStr<'a> { #[primary_span] pub attr_span: Span, pub attr_name: &'a str, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_alias_empty)] +#[derive(Diagnostic)] +#[diag(passes_doc_alias_empty)] pub struct DocAliasEmpty<'a> { #[primary_span] pub span: Span, pub attr_str: &'a str, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_alias_bad_char)] +#[derive(Diagnostic)] +#[diag(passes_doc_alias_bad_char)] pub struct DocAliasBadChar<'a> { #[primary_span] pub span: Span, @@ -143,16 +153,16 @@ pub struct DocAliasBadChar<'a> { pub char_: char, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_alias_start_end)] +#[derive(Diagnostic)] +#[diag(passes_doc_alias_start_end)] pub struct DocAliasStartEnd<'a> { #[primary_span] pub span: Span, pub attr_str: &'a str, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_alias_bad_location)] +#[derive(Diagnostic)] +#[diag(passes_doc_alias_bad_location)] pub struct DocAliasBadLocation<'a> { #[primary_span] pub span: Span, @@ -160,8 +170,8 @@ pub struct DocAliasBadLocation<'a> { pub location: &'a str, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_alias_not_an_alias)] +#[derive(Diagnostic)] +#[diag(passes_doc_alias_not_an_alias)] pub struct DocAliasNotAnAlias<'a> { #[primary_span] pub span: Span, @@ -169,64 +179,64 @@ pub struct DocAliasNotAnAlias<'a> { } #[derive(LintDiagnostic)] -#[diag(passes::doc_alias_duplicated)] +#[diag(passes_doc_alias_duplicated)] pub struct DocAliasDuplicated { #[label] pub first_defn: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_alias_not_string_literal)] +#[derive(Diagnostic)] +#[diag(passes_doc_alias_not_string_literal)] pub struct DocAliasNotStringLiteral { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_alias_malformed)] +#[derive(Diagnostic)] +#[diag(passes_doc_alias_malformed)] pub struct DocAliasMalformed { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_keyword_empty_mod)] +#[derive(Diagnostic)] +#[diag(passes_doc_keyword_empty_mod)] pub struct DocKeywordEmptyMod { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_keyword_not_mod)] +#[derive(Diagnostic)] +#[diag(passes_doc_keyword_not_mod)] pub struct DocKeywordNotMod { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_keyword_invalid_ident)] +#[derive(Diagnostic)] +#[diag(passes_doc_keyword_invalid_ident)] pub struct DocKeywordInvalidIdent { #[primary_span] pub span: Span, pub doc_keyword: Symbol, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_fake_variadic_not_valid)] +#[derive(Diagnostic)] +#[diag(passes_doc_fake_variadic_not_valid)] pub struct DocFakeVariadicNotValid { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_keyword_only_impl)] +#[derive(Diagnostic)] +#[diag(passes_doc_keyword_only_impl)] pub struct DocKeywordOnlyImpl { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_inline_conflict)] +#[derive(Diagnostic)] +#[diag(passes_doc_inline_conflict)] #[help] pub struct DocKeywordConflict { #[primary_span] @@ -234,17 +244,17 @@ pub struct DocKeywordConflict { } #[derive(LintDiagnostic)] -#[diag(passes::doc_inline_only_use)] +#[diag(passes_doc_inline_only_use)] #[note] pub struct DocInlineOnlyUse { #[label] pub attr_span: Span, - #[label(passes::not_a_use_item_label)] + #[label(not_a_use_item_label)] pub item_span: Option, } -#[derive(SessionDiagnostic)] -#[diag(passes::doc_attr_not_crate_level)] +#[derive(Diagnostic)] +#[diag(passes_doc_attr_not_crate_level)] pub struct DocAttrNotCrateLevel<'a> { #[primary_span] pub span: Span, @@ -252,29 +262,33 @@ pub struct DocAttrNotCrateLevel<'a> { } #[derive(LintDiagnostic)] -#[diag(passes::doc_test_unknown)] +#[diag(passes_doc_test_unknown)] pub struct DocTestUnknown { pub path: String, } #[derive(LintDiagnostic)] -#[diag(passes::doc_test_takes_list)] +#[diag(passes_doc_test_takes_list)] pub struct DocTestTakesList; #[derive(LintDiagnostic)] -#[diag(passes::doc_primitive)] +#[diag(passes_doc_cfg_hide_takes_list)] +pub struct DocCfgHideTakesList; + +#[derive(LintDiagnostic)] +#[diag(passes_doc_primitive)] pub struct DocPrimitive; #[derive(LintDiagnostic)] -#[diag(passes::doc_test_unknown_any)] +#[diag(passes_doc_test_unknown_any)] pub struct DocTestUnknownAny { pub path: String, } #[derive(LintDiagnostic)] -#[diag(passes::doc_test_unknown_spotlight)] +#[diag(passes_doc_test_unknown_spotlight)] #[note] -#[note(passes::no_op_note)] +#[note(no_op_note)] pub struct DocTestUnknownSpotlight { pub path: String, #[suggestion_short(applicability = "machine-applicable", code = "notable_trait")] @@ -282,7 +296,7 @@ pub struct DocTestUnknownSpotlight { } #[derive(LintDiagnostic)] -#[diag(passes::doc_test_unknown_include)] +#[diag(passes_doc_test_unknown_include)] pub struct DocTestUnknownInclude { pub path: String, pub value: String, @@ -292,11 +306,11 @@ pub struct DocTestUnknownInclude { } #[derive(LintDiagnostic)] -#[diag(passes::doc_invalid)] +#[diag(passes_doc_invalid)] pub struct DocInvalid; -#[derive(SessionDiagnostic)] -#[diag(passes::pass_by_value)] +#[derive(Diagnostic)] +#[diag(passes_pass_by_value)] pub struct PassByValue { #[primary_span] pub attr_span: Span, @@ -304,8 +318,8 @@ pub struct PassByValue { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::allow_incoherent_impl)] +#[derive(Diagnostic)] +#[diag(passes_allow_incoherent_impl)] pub struct AllowIncoherentImpl { #[primary_span] pub attr_span: Span, @@ -313,8 +327,8 @@ pub struct AllowIncoherentImpl { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::has_incoherent_inherent_impl)] +#[derive(Diagnostic)] +#[diag(passes_has_incoherent_inherent_impl)] pub struct HasIncoherentInherentImpl { #[primary_span] pub attr_span: Span, @@ -323,21 +337,21 @@ pub struct HasIncoherentInherentImpl { } #[derive(LintDiagnostic)] -#[diag(passes::must_use_async)] +#[diag(passes_must_use_async)] pub struct MustUseAsync { #[label] pub span: Span, } #[derive(LintDiagnostic)] -#[diag(passes::must_use_no_effect)] +#[diag(passes_must_use_no_effect)] pub struct MustUseNoEffect { pub article: &'static str, pub target: rustc_hir::Target, } -#[derive(SessionDiagnostic)] -#[diag(passes::must_not_suspend)] +#[derive(Diagnostic)] +#[diag(passes_must_not_suspend)] pub struct MustNotSuspend { #[primary_span] pub attr_span: Span, @@ -346,7 +360,7 @@ pub struct MustNotSuspend { } #[derive(LintDiagnostic)] -#[diag(passes::cold)] +#[diag(passes_cold)] #[warning] pub struct Cold { #[label] @@ -354,7 +368,7 @@ pub struct Cold { } #[derive(LintDiagnostic)] -#[diag(passes::link)] +#[diag(passes_link)] #[warning] pub struct Link { #[label] @@ -362,7 +376,7 @@ pub struct Link { } #[derive(LintDiagnostic)] -#[diag(passes::link_name)] +#[diag(passes_link_name)] #[warning] pub struct LinkName<'a> { #[help] @@ -372,8 +386,8 @@ pub struct LinkName<'a> { pub value: &'a str, } -#[derive(SessionDiagnostic)] -#[diag(passes::no_link)] +#[derive(Diagnostic)] +#[diag(passes_no_link)] pub struct NoLink { #[primary_span] pub attr_span: Span, @@ -381,8 +395,8 @@ pub struct NoLink { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::export_name)] +#[derive(Diagnostic)] +#[diag(passes_export_name)] pub struct ExportName { #[primary_span] pub attr_span: Span, @@ -390,8 +404,8 @@ pub struct ExportName { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_layout_scalar_valid_range_not_struct)] +#[derive(Diagnostic)] +#[diag(passes_rustc_layout_scalar_valid_range_not_struct)] pub struct RustcLayoutScalarValidRangeNotStruct { #[primary_span] pub attr_span: Span, @@ -399,15 +413,15 @@ pub struct RustcLayoutScalarValidRangeNotStruct { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_layout_scalar_valid_range_arg)] +#[derive(Diagnostic)] +#[diag(passes_rustc_layout_scalar_valid_range_arg)] pub struct RustcLayoutScalarValidRangeArg { #[primary_span] pub attr_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_legacy_const_generics_only)] +#[derive(Diagnostic)] +#[diag(passes_rustc_legacy_const_generics_only)] pub struct RustcLegacyConstGenericsOnly { #[primary_span] pub attr_span: Span, @@ -415,8 +429,8 @@ pub struct RustcLegacyConstGenericsOnly { pub param_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_legacy_const_generics_index)] +#[derive(Diagnostic)] +#[diag(passes_rustc_legacy_const_generics_index)] pub struct RustcLegacyConstGenericsIndex { #[primary_span] pub attr_span: Span, @@ -424,8 +438,8 @@ pub struct RustcLegacyConstGenericsIndex { pub generics_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_legacy_const_generics_index_exceed)] +#[derive(Diagnostic)] +#[diag(passes_rustc_legacy_const_generics_index_exceed)] pub struct RustcLegacyConstGenericsIndexExceed { #[primary_span] #[label] @@ -433,22 +447,22 @@ pub struct RustcLegacyConstGenericsIndexExceed { pub arg_count: usize, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_legacy_const_generics_index_negative)] +#[derive(Diagnostic)] +#[diag(passes_rustc_legacy_const_generics_index_negative)] pub struct RustcLegacyConstGenericsIndexNegative { #[primary_span] pub invalid_args: Vec, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_dirty_clean)] +#[derive(Diagnostic)] +#[diag(passes_rustc_dirty_clean)] pub struct RustcDirtyClean { #[primary_span] pub span: Span, } #[derive(LintDiagnostic)] -#[diag(passes::link_section)] +#[diag(passes_link_section)] #[warning] pub struct LinkSection { #[label] @@ -456,52 +470,52 @@ pub struct LinkSection { } #[derive(LintDiagnostic)] -#[diag(passes::no_mangle_foreign)] +#[diag(passes_no_mangle_foreign)] #[warning] #[note] pub struct NoMangleForeign { #[label] pub span: Span, - #[suggestion(applicability = "machine-applicable")] + #[suggestion(code = "", applicability = "machine-applicable")] pub attr_span: Span, pub foreign_item_kind: &'static str, } #[derive(LintDiagnostic)] -#[diag(passes::no_mangle)] +#[diag(passes_no_mangle)] #[warning] pub struct NoMangle { #[label] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::repr_ident, code = "E0565")] +#[derive(Diagnostic)] +#[diag(passes_repr_ident, code = "E0565")] pub struct ReprIdent { #[primary_span] pub span: Span, } #[derive(LintDiagnostic)] -#[diag(passes::repr_conflicting, code = "E0566")] +#[diag(passes_repr_conflicting, code = "E0566")] pub struct ReprConflicting; -#[derive(SessionDiagnostic)] -#[diag(passes::used_static)] +#[derive(Diagnostic)] +#[diag(passes_used_static)] pub struct UsedStatic { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::used_compiler_linker)] +#[derive(Diagnostic)] +#[diag(passes_used_compiler_linker)] pub struct UsedCompilerLinker { #[primary_span] pub spans: Vec, } -#[derive(SessionDiagnostic)] -#[diag(passes::allow_internal_unstable)] +#[derive(Diagnostic)] +#[diag(passes_allow_internal_unstable)] pub struct AllowInternalUnstable { #[primary_span] pub attr_span: Span, @@ -509,25 +523,34 @@ pub struct AllowInternalUnstable { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::debug_visualizer_placement)] +#[derive(Diagnostic)] +#[diag(passes_debug_visualizer_placement)] pub struct DebugVisualizerPlacement { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::debug_visualizer_invalid)] -#[note(passes::note_1)] -#[note(passes::note_2)] -#[note(passes::note_3)] +#[derive(Diagnostic)] +#[diag(passes_debug_visualizer_invalid)] +#[note(note_1)] +#[note(note_2)] +#[note(note_3)] pub struct DebugVisualizerInvalid { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_allow_const_fn_unstable)] +#[derive(Diagnostic)] +#[diag(passes_debug_visualizer_unreadable)] +pub struct DebugVisualizerUnreadable<'a> { + #[primary_span] + pub span: Span, + pub file: &'a Path, + pub error: Error, +} + +#[derive(Diagnostic)] +#[diag(passes_rustc_allow_const_fn_unstable)] pub struct RustcAllowConstFnUnstable { #[primary_span] pub attr_span: Span, @@ -535,8 +558,8 @@ pub struct RustcAllowConstFnUnstable { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_std_internal_symbol)] +#[derive(Diagnostic)] +#[diag(passes_rustc_std_internal_symbol)] pub struct RustcStdInternalSymbol { #[primary_span] pub attr_span: Span, @@ -544,66 +567,66 @@ pub struct RustcStdInternalSymbol { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::const_trait)] +#[derive(Diagnostic)] +#[diag(passes_const_trait)] pub struct ConstTrait { #[primary_span] pub attr_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::link_ordinal)] +#[derive(Diagnostic)] +#[diag(passes_link_ordinal)] pub struct LinkOrdinal { #[primary_span] pub attr_span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::stability_promotable)] +#[derive(Diagnostic)] +#[diag(passes_stability_promotable)] pub struct StabilityPromotable { #[primary_span] pub attr_span: Span, } #[derive(LintDiagnostic)] -#[diag(passes::deprecated)] +#[diag(passes_deprecated)] pub struct Deprecated; #[derive(LintDiagnostic)] -#[diag(passes::macro_use)] +#[diag(passes_macro_use)] pub struct MacroUse { pub name: Symbol, } #[derive(LintDiagnostic)] -#[diag(passes::macro_export)] +#[diag(passes_macro_export)] pub struct MacroExport; #[derive(LintDiagnostic)] -#[diag(passes::plugin_registrar)] +#[diag(passes_plugin_registrar)] pub struct PluginRegistrar; -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum UnusedNote { - #[note(passes::unused_empty_lints_note)] + #[note(passes_unused_empty_lints_note)] EmptyList { name: Symbol }, - #[note(passes::unused_no_lints_note)] + #[note(passes_unused_no_lints_note)] NoLints { name: Symbol }, - #[note(passes::unused_default_method_body_const_note)] + #[note(passes_unused_default_method_body_const_note)] DefaultMethodBodyConst, } #[derive(LintDiagnostic)] -#[diag(passes::unused)] +#[diag(passes_unused)] pub struct Unused { - #[suggestion(applicability = "machine-applicable")] + #[suggestion(code = "", applicability = "machine-applicable")] pub attr_span: Span, #[subdiagnostic] pub note: UnusedNote, } -#[derive(SessionDiagnostic)] -#[diag(passes::non_exported_macro_invalid_attrs, code = "E0518")] +#[derive(Diagnostic)] +#[diag(passes_non_exported_macro_invalid_attrs, code = "E0518")] pub struct NonExportedMacroInvalidAttrs { #[primary_span] #[label] @@ -611,7 +634,7 @@ pub struct NonExportedMacroInvalidAttrs { } #[derive(LintDiagnostic)] -#[diag(passes::unused_duplicate)] +#[diag(passes_unused_duplicate)] pub struct UnusedDuplicate { #[suggestion(code = "", applicability = "machine-applicable")] pub this: Span, @@ -621,8 +644,8 @@ pub struct UnusedDuplicate { pub warning: Option<()>, } -#[derive(SessionDiagnostic)] -#[diag(passes::unused_multiple)] +#[derive(Diagnostic)] +#[diag(passes_unused_multiple)] pub struct UnusedMultiple { #[primary_span] #[suggestion(code = "", applicability = "machine-applicable")] @@ -632,8 +655,8 @@ pub struct UnusedMultiple { pub name: Symbol, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_lint_opt_ty)] +#[derive(Diagnostic)] +#[diag(passes_rustc_lint_opt_ty)] pub struct RustcLintOptTy { #[primary_span] pub attr_span: Span, @@ -641,8 +664,8 @@ pub struct RustcLintOptTy { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::rustc_lint_opt_deny_field_access)] +#[derive(Diagnostic)] +#[diag(passes_rustc_lint_opt_deny_field_access)] pub struct RustcLintOptDenyFieldAccess { #[primary_span] pub attr_span: Span, @@ -650,11 +673,779 @@ pub struct RustcLintOptDenyFieldAccess { pub span: Span, } -#[derive(SessionDiagnostic)] -#[diag(passes::collapse_debuginfo)] +#[derive(Diagnostic)] +#[diag(passes_collapse_debuginfo)] pub struct CollapseDebuginfo { #[primary_span] pub attr_span: Span, #[label] pub defn_span: Span, } + +#[derive(LintDiagnostic)] +#[diag(passes_deprecated_annotation_has_no_effect)] +pub struct DeprecatedAnnotationHasNoEffect { + #[suggestion(applicability = "machine-applicable", code = "")] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(passes_unknown_external_lang_item, code = "E0264")] +pub struct UnknownExternLangItem { + #[primary_span] + pub span: Span, + pub lang_item: Symbol, +} + +#[derive(Diagnostic)] +#[diag(passes_missing_panic_handler)] +pub struct MissingPanicHandler; + +#[derive(Diagnostic)] +#[diag(passes_alloc_func_required)] +pub struct AllocFuncRequired; + +#[derive(Diagnostic)] +#[diag(passes_missing_alloc_error_handler)] +pub struct MissingAllocErrorHandler; + +#[derive(Diagnostic)] +#[diag(passes_missing_lang_item)] +#[note] +#[help] +pub struct MissingLangItem { + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(passes_lang_item_on_incorrect_target, code = "E0718")] +pub struct LangItemOnIncorrectTarget { + #[primary_span] + #[label] + pub span: Span, + pub name: Symbol, + pub expected_target: Target, + pub actual_target: Target, +} + +#[derive(Diagnostic)] +#[diag(passes_unknown_lang_item, code = "E0522")] +pub struct UnknownLangItem { + #[primary_span] + #[label] + pub span: Span, + pub name: Symbol, +} + +pub struct InvalidAttrAtCrateLevel { + pub span: Span, + pub snippet: Option, + pub name: Symbol, +} + +impl IntoDiagnostic<'_> for InvalidAttrAtCrateLevel { + fn into_diagnostic( + self, + handler: &'_ rustc_errors::Handler, + ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { + let mut diag = handler.struct_err(rustc_errors::fluent::passes_invalid_attr_at_crate_level); + diag.set_span(self.span); + diag.set_arg("name", self.name); + // Only emit an error with a suggestion if we can create a string out + // of the attribute span + if let Some(src) = self.snippet { + let replacement = src.replace("#!", "#"); + diag.span_suggestion_verbose( + self.span, + rustc_errors::fluent::suggestion, + replacement, + rustc_errors::Applicability::MachineApplicable, + ); + } + diag + } +} + +#[derive(Diagnostic)] +#[diag(passes_duplicate_diagnostic_item)] +pub struct DuplicateDiagnosticItem { + #[primary_span] + pub span: Span, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(passes_duplicate_diagnostic_item_in_crate)] +pub struct DuplicateDiagnosticItemInCrate { + #[note(passes_diagnostic_item_first_defined)] + pub span: Option, + pub orig_crate_name: Symbol, + #[note] + pub have_orig_crate_name: Option<()>, + pub crate_name: Symbol, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(passes_abi)] +pub struct Abi { + #[primary_span] + pub span: Span, + pub abi: String, +} + +#[derive(Diagnostic)] +#[diag(passes_align)] +pub struct Align { + #[primary_span] + pub span: Span, + pub align: String, +} + +#[derive(Diagnostic)] +#[diag(passes_size)] +pub struct Size { + #[primary_span] + pub span: Span, + pub size: String, +} + +#[derive(Diagnostic)] +#[diag(passes_homogeneous_aggregate)] +pub struct HomogeneousAggregate { + #[primary_span] + pub span: Span, + pub homogeneous_aggregate: String, +} + +#[derive(Diagnostic)] +#[diag(passes_layout_of)] +pub struct LayoutOf { + #[primary_span] + pub span: Span, + pub normalized_ty: String, + pub ty_layout: String, +} + +#[derive(Diagnostic)] +#[diag(passes_unrecognized_field)] +pub struct UnrecognizedField { + #[primary_span] + pub span: Span, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(passes_feature_stable_twice, code = "E0711")] +pub struct FeatureStableTwice { + #[primary_span] + pub span: Span, + pub feature: Symbol, + pub since: Symbol, + pub prev_since: Symbol, +} + +#[derive(Diagnostic)] +#[diag(passes_feature_previously_declared, code = "E0711")] +pub struct FeaturePreviouslyDeclared<'a, 'b> { + #[primary_span] + pub span: Span, + pub feature: Symbol, + pub declared: &'a str, + pub prev_declared: &'b str, +} + +#[derive(Diagnostic)] +#[diag(passes_expr_not_allowed_in_context, code = "E0744")] +pub struct ExprNotAllowedInContext<'a> { + #[primary_span] + pub span: Span, + pub expr: String, + pub context: &'a str, +} + +pub struct BreakNonLoop<'a> { + pub span: Span, + pub head: Option, + pub kind: &'a str, + pub suggestion: String, + pub loop_label: Option