From b38106b6d8478fbfbded5403ee31c056c71cef48 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 17 Aug 2022 14:22:30 +1000 Subject: Replace `rustc_data_structures::thin_vec::ThinVec` with `thin_vec::ThinVec`. `rustc_data_structures::thin_vec::ThinVec` looks like this: ``` pub struct ThinVec(Option>>); ``` It's just a zero word if the vector is empty, but requires two allocations if it is non-empty. So it's only usable in cases where the vector is empty most of the time. This commit removes it in favour of `thin_vec::ThinVec`, which is also word-sized, but stores the length and capacity in the same allocation as the elements. It's good in a wider variety of situation, e.g. in enum variants where the vector is usually/always non-empty. The commit also: - Sorts some `Cargo.toml` dependency lists, to make additions easier. - Sorts some `use` item lists, to make additions easier. - Changes `clean_trait_ref_with_bindings` to take a `ThinVec` rather than a `&[TypeBinding]`, because this avoid some unnecessary allocations. --- compiler/rustc_query_system/Cargo.toml | 7 ++++--- compiler/rustc_query_system/src/query/mod.rs | 3 +-- compiler/rustc_query_system/src/query/plumbing.rs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_query_system/Cargo.toml b/compiler/rustc_query_system/Cargo.toml index b7787aeb8f7..bafc6b0a082 100644 --- a/compiler/rustc_query_system/Cargo.toml +++ b/compiler/rustc_query_system/Cargo.toml @@ -7,9 +7,8 @@ edition = "2021" doctest = false [dependencies] +parking_lot = "0.11" rustc_arena = { path = "../rustc_arena" } -tracing = "0.1" -rustc-rayon-core = { version = "0.4.0", optional = true } rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } @@ -17,12 +16,14 @@ rustc_feature = { path = "../rustc_feature" } rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_macros = { path = "../rustc_macros" } +rustc-rayon-core = { version = "0.4.0", optional = true } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } -parking_lot = "0.11" smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } +thin-vec = "0.2.8" +tracing = "0.1" [features] rustc_use_parallel_compiler = ["rustc-rayon-core"] diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index a1f2b081d43..51b4a2f35e2 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -15,12 +15,11 @@ mod config; pub use self::config::{QueryConfig, QueryDescription, QueryVTable}; use crate::dep_graph::{DepContext, DepNodeIndex, HasDepContext, SerializedDepNodeIndex}; - use rustc_data_structures::sync::Lock; -use rustc_data_structures::thin_vec::ThinVec; use rustc_errors::Diagnostic; use rustc_hir::def::DefKind; use rustc_span::Span; +use thin_vec::ThinVec; /// Description of a frame in the query stack. /// diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 6ae9147ff77..aa10d2d3442 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -14,7 +14,6 @@ use rustc_data_structures::profiling::TimingGuard; #[cfg(parallel_compiler)] use rustc_data_structures::sharded::Sharded; use rustc_data_structures::sync::Lock; -use rustc_data_structures::thin_vec::ThinVec; use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, FatalError}; use rustc_session::Session; use rustc_span::{Span, DUMMY_SP}; @@ -24,6 +23,7 @@ use std::fmt::Debug; use std::hash::Hash; use std::mem; use std::ptr; +use thin_vec::ThinVec; pub struct QueryState { #[cfg(parallel_compiler)] -- cgit 1.4.1-3-g733a5 From b8075e4550a3ec9110930b41e09e77266482e54f Mon Sep 17 00:00:00 2001 From: Yuanheng Li <520dhh@gmail.com> Date: Sun, 21 Aug 2022 21:37:05 +0800 Subject: migrate rustc_query_system to use SessionDiagnostic with manual impl SessionDiagnostic --- .../locales/en-US/query_system.ftl | 21 ++++++++ compiler/rustc_error_messages/src/lib.rs | 1 + compiler/rustc_query_system/src/error.rs | 60 ++++++++++++++++++++++ compiler/rustc_query_system/src/lib.rs | 3 ++ compiler/rustc_query_system/src/query/job.rs | 55 +++++++------------- compiler/rustc_query_system/src/query/plumbing.rs | 14 ++--- 6 files changed, 108 insertions(+), 46 deletions(-) create mode 100644 compiler/rustc_error_messages/locales/en-US/query_system.ftl create mode 100644 compiler/rustc_query_system/src/error.rs (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_error_messages/locales/en-US/query_system.ftl b/compiler/rustc_error_messages/locales/en-US/query_system.ftl new file mode 100644 index 00000000000..2d8c7a65122 --- /dev/null +++ b/compiler/rustc_error_messages/locales/en-US/query_system.ftl @@ -0,0 +1,21 @@ +query_system_reentrant = internal compiler error: re-entrant incremental verify failure, suppressing message + +query_system_increment_compilation = internal compiler error: encountered incremental compilation error with {$dep_node} + .help = This is a known issue with the compiler. Run {$run_cmd} to allow your project to compile + +query_system_increment_compilation_note1 = Please follow the instructions below to create a bug report with the provided information +query_system_increment_compilation_note2 = See for more information + +query_system_cycle = cycle detected when {$stack_bottom} + +query_system_cycle_usage = cycle used when {$usage} + +query_system_cycle_stack_single = ...which immediately requires {$stack_bottom} again + +query_system_cycle_stack_multiple = ...which again requires {$stack_bottom}, completing the cycle + +query_system_cycle_recursive_ty_alias = type aliases cannot be recursive +query_system_cycle_recursive_ty_alias_help1 = consider using a struct, enum, or union instead to break the cycle +query_system_cycle_recursive_ty_alias_help2 = see for more information + +query_system_cycle_recursive_trait_alias = trait aliases cannot be recursive diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index d1ac326a72c..601fa4c72f0 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -52,6 +52,7 @@ fluent_messages! { ty_utils => "../locales/en-US/ty_utils.ftl", typeck => "../locales/en-US/typeck.ftl", mir_dataflow => "../locales/en-US/mir_dataflow.ftl", + query_system => "../locales/en-US/query_system.ftl", } pub use fluent_generated::{self as fluent, DEFAULT_LOCALE_RESOURCES}; diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs new file mode 100644 index 00000000000..2ae6d10b828 --- /dev/null +++ b/compiler/rustc_query_system/src/error.rs @@ -0,0 +1,60 @@ +use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; +use rustc_session::SessionDiagnostic; +use rustc_span::Span; + +pub struct Cycle { + pub span: Span, + pub stack_bottom: String, + pub upper_stack_info: Vec<(Span, String)>, + pub recursive_ty_alias: bool, + pub recursive_trait_alias: bool, + pub cycle_usage: Option<(Span, String)>, +} + +impl SessionDiagnostic<'_> for Cycle { + fn into_diagnostic( + self, + sess: &'_ rustc_session::parse::ParseSess, + ) -> DiagnosticBuilder<'_, ErrorGuaranteed> { + let mut diag = sess.struct_err(rustc_errors::fluent::query_system::cycle); + diag.set_span(self.span); + diag.code(rustc_errors::DiagnosticId::Error("E0391".to_string())); + let upper_stack_len = self.upper_stack_info.len(); + for (span, desc) in self.upper_stack_info.into_iter() { + // FIXME: use fluent translation + diag.span_note(span, &format!("...which requires {}...", desc)); + } + diag.set_arg("stack_bottom", self.stack_bottom); + if upper_stack_len == 0 { + diag.note(rustc_errors::fluent::query_system::cycle_stack_single); + } else { + diag.note(rustc_errors::fluent::query_system::cycle_stack_multiple); + } + if self.recursive_trait_alias { + diag.note(rustc_errors::fluent::query_system::cycle_recursive_trait_alias); + } else if self.recursive_ty_alias { + diag.note(rustc_errors::fluent::query_system::cycle_recursive_ty_alias); + diag.help(rustc_errors::fluent::query_system::cycle_recursive_ty_alias_help1); + diag.help(rustc_errors::fluent::query_system::cycle_recursive_ty_alias_help2); + } + if let Some((span, desc)) = self.cycle_usage { + diag.set_arg("usage", desc); + diag.span_note(span, rustc_errors::fluent::query_system::cycle_usage); + } + diag + } +} + +#[derive(SessionDiagnostic)] +#[diag(query_system::reentrant)] +pub struct Reentrant; + +#[derive(SessionDiagnostic)] +#[diag(query_system::increment_compilation)] +#[help] +#[note(query_system::increment_compilation_note1)] +#[note(query_system::increment_compilation_note2)] +pub struct IncrementCompilation { + pub run_cmd: String, + pub dep_node: String, +} diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index 68284dcaa0b..da775893a2b 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -5,6 +5,8 @@ #![feature(min_specialization)] #![feature(extern_types)] #![allow(rustc::potential_query_instability)] +#![deny(rustc::untranslatable_diagnostic)] +#![deny(rustc::diagnostic_outside_of_impl)] #[macro_use] extern crate tracing; @@ -15,5 +17,6 @@ extern crate rustc_macros; pub mod cache; pub mod dep_graph; +mod error; pub mod ich; pub mod query; diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 6d2aff38172..718ec14db36 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -1,12 +1,10 @@ use crate::query::plumbing::CycleError; use crate::query::{QueryContext, QueryStackFrame}; -use rustc_hir::def::DefKind; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{ - struct_span_err, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, Level, -}; -use rustc_session::Session; +use rustc_errors::{Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, Level}; +use rustc_hir::def::DefKind; +use rustc_session::{Session, SessionDiagnostic}; use rustc_span::Span; use std::hash::Hash; @@ -536,46 +534,29 @@ pub(crate) fn report_cycle<'a>( assert!(!stack.is_empty()); let span = stack[0].query.default_span(stack[1 % stack.len()].span); - let mut err = - struct_span_err!(sess, span, E0391, "cycle detected when {}", stack[0].query.description); + + let mut cycle_diag = crate::error::Cycle { + span, + upper_stack_info: Vec::with_capacity(stack.len() - 1), + stack_bottom: stack[0].query.description.to_owned(), + recursive_ty_alias: false, + recursive_trait_alias: false, + cycle_usage: usage.map(|(span, query)| (query.default_span(span), query.description)), + }; for i in 1..stack.len() { let query = &stack[i].query; let span = query.default_span(stack[(i + 1) % stack.len()].span); - err.span_note(span, &format!("...which requires {}...", query.description)); - } - - if stack.len() == 1 { - err.note(&format!("...which immediately requires {} again", stack[0].query.description)); - } else { - err.note(&format!( - "...which again requires {}, completing the cycle", - stack[0].query.description - )); - } - - if stack.iter().all(|entry| { - entry - .query - .def_kind - .map_or(false, |def_kind| matches!(def_kind, DefKind::TyAlias | DefKind::TraitAlias)) - }) { - if stack.iter().all(|entry| { - entry.query.def_kind.map_or(false, |def_kind| matches!(def_kind, DefKind::TyAlias)) - }) { - err.note("type aliases cannot be recursive"); - err.help("consider using a struct, enum, or union instead to break the cycle"); - err.help("see for more information"); - } else { - err.note("trait aliases cannot be recursive"); - } + cycle_diag.upper_stack_info.push((span, query.description.to_owned())); } - if let Some((span, query)) = usage { - err.span_note(query.default_span(span), &format!("cycle used when {}", query.description)); + if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TyAlias)) { + cycle_diag.recursive_ty_alias = true; + } else if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TraitAlias)) { + cycle_diag.recursive_trait_alias = true; } - err + cycle_diag.into_diagnostic(&sess.parse_sess) } pub fn print_query_stack( diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 6ae9147ff77..e97411b777b 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -618,16 +618,12 @@ fn incremental_verify_ich_cold(sess: &Session, dep_node: DebugArg<'_>, result: D let old_in_panic = INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.replace(true)); if old_in_panic { - sess.struct_err( - "internal compiler error: re-entrant incremental verify failure, suppressing message", - ) - .emit(); + sess.emit_err(crate::error::Reentrant); } else { - sess.struct_err(&format!("internal compiler error: encountered incremental compilation error with {:?}", dep_node)) - .help(&format!("This is a known issue with the compiler. Run {} to allow your project to compile", run_cmd)) - .note("Please follow the instructions below to create a bug report with the provided information") - .note("See for more information") - .emit(); + sess.emit_err(crate::error::IncrementCompilation { + run_cmd, + dep_node: format!("{:?}", dep_node), + }); panic!("Found unstable fingerprints for {:?}: {:?}", dep_node, result); } -- cgit 1.4.1-3-g733a5 From d7e07c0b6b08e898a0720bf9c2fd2a22404bdfec Mon Sep 17 00:00:00 2001 From: Li Yuanheng <520dhh@gmail.com> Date: Tue, 23 Aug 2022 07:23:36 +0800 Subject: link related issue to FIXME Co-authored-by: David Wood --- compiler/rustc_query_system/src/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 2ae6d10b828..515a022e9d9 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -21,7 +21,7 @@ impl SessionDiagnostic<'_> for Cycle { diag.code(rustc_errors::DiagnosticId::Error("E0391".to_string())); let upper_stack_len = self.upper_stack_info.len(); for (span, desc) in self.upper_stack_info.into_iter() { - // FIXME: use fluent translation + // FIXME(#100717): use fluent translation diag.span_note(span, &format!("...which requires {}...", desc)); } diag.set_arg("stack_bottom", self.stack_bottom); -- cgit 1.4.1-3-g733a5 From ac638c1f5fca36484506415319ab254ad522a692 Mon Sep 17 00:00:00 2001 From: Yuanheng Li <520dhh@gmail.com> Date: Tue, 23 Aug 2022 11:19:38 +0800 Subject: use derive proc macro to impl SessionDiagnostic fixes `SessionSubdiagnostic` to accept multiple attributes emitting list of fluent message remains unresolved --- .../locales/en-US/query_system.ftl | 2 + .../rustc_macros/src/diagnostics/subdiagnostic.rs | 694 ++++++++------------- compiler/rustc_query_system/src/error.rs | 87 +-- compiler/rustc_query_system/src/lib.rs | 2 +- compiler/rustc_query_system/src/query/job.rs | 43 +- .../session-diagnostic/subdiagnostic-derive.rs | 164 +---- .../session-diagnostic/subdiagnostic-derive.stderr | 234 ++----- 7 files changed, 415 insertions(+), 811 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_error_messages/locales/en-US/query_system.ftl b/compiler/rustc_error_messages/locales/en-US/query_system.ftl index 2d8c7a65122..7fdecf4f381 100644 --- a/compiler/rustc_error_messages/locales/en-US/query_system.ftl +++ b/compiler/rustc_error_messages/locales/en-US/query_system.ftl @@ -19,3 +19,5 @@ query_system_cycle_recursive_ty_alias_help1 = consider using a struct, enum, or query_system_cycle_recursive_ty_alias_help2 = see for more information query_system_cycle_recursive_trait_alias = trait aliases cannot be recursive + +query_system_cycle_which_requires = ...which requires {$desc}... diff --git a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs index 8b40e295bd8..c1b82abc1e0 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -12,7 +12,7 @@ use quote::{format_ident, quote}; use std::collections::HashMap; use std::fmt; use std::str::FromStr; -use syn::{spanned::Spanned, Attribute, Meta, MetaList, MetaNameValue, NestedMeta, Path}; +use syn::{spanned::Spanned, Meta, MetaList, MetaNameValue, NestedMeta, Path}; use synstructure::{BindingInfo, Structure, VariantInfo}; /// Which kind of suggestion is being created? @@ -28,41 +28,8 @@ enum SubdiagnosticSuggestionKind { Verbose, } -impl FromStr for SubdiagnosticSuggestionKind { - type Err = (); - - fn from_str(s: &str) -> Result { - match s { - "" => Ok(SubdiagnosticSuggestionKind::Normal), - "_short" => Ok(SubdiagnosticSuggestionKind::Short), - "_hidden" => Ok(SubdiagnosticSuggestionKind::Hidden), - "_verbose" => Ok(SubdiagnosticSuggestionKind::Verbose), - _ => Err(()), - } - } -} - -impl SubdiagnosticSuggestionKind { - pub fn to_suggestion_style(&self) -> TokenStream { - match self { - SubdiagnosticSuggestionKind::Normal => { - quote! { rustc_errors::SuggestionStyle::ShowCode } - } - SubdiagnosticSuggestionKind::Short => { - quote! { rustc_errors::SuggestionStyle::HideCodeInline } - } - SubdiagnosticSuggestionKind::Hidden => { - quote! { rustc_errors::SuggestionStyle::HideCodeAlways } - } - SubdiagnosticSuggestionKind::Verbose => { - quote! { rustc_errors::SuggestionStyle::ShowAlways } - } - } - } -} - /// Which kind of subdiagnostic is being created from a variant? -#[derive(Clone)] +#[derive(Clone, Copy)] enum SubdiagnosticKind { /// `#[label(...)]` Label, @@ -73,9 +40,31 @@ enum SubdiagnosticKind { /// `#[warning(...)]` Warn, /// `#[suggestion{,_short,_hidden,_verbose}]` - Suggestion { suggestion_kind: SubdiagnosticSuggestionKind, code: TokenStream }, - /// `#[multipart_suggestion{,_short,_hidden,_verbose}]` - MultipartSuggestion { suggestion_kind: SubdiagnosticSuggestionKind }, + Suggestion(SubdiagnosticSuggestionKind), +} + +impl FromStr for SubdiagnosticKind { + type Err = (); + + fn from_str(s: &str) -> Result { + match s { + "label" => Ok(SubdiagnosticKind::Label), + "note" => Ok(SubdiagnosticKind::Note), + "help" => Ok(SubdiagnosticKind::Help), + "warning" => Ok(SubdiagnosticKind::Warn), + "suggestion" => Ok(SubdiagnosticKind::Suggestion(SubdiagnosticSuggestionKind::Normal)), + "suggestion_short" => { + Ok(SubdiagnosticKind::Suggestion(SubdiagnosticSuggestionKind::Short)) + } + "suggestion_hidden" => { + Ok(SubdiagnosticKind::Suggestion(SubdiagnosticSuggestionKind::Hidden)) + } + "suggestion_verbose" => { + Ok(SubdiagnosticKind::Suggestion(SubdiagnosticSuggestionKind::Verbose)) + } + _ => Err(()), + } + } } impl quote::IdentFragment for SubdiagnosticKind { @@ -85,9 +74,17 @@ impl quote::IdentFragment for SubdiagnosticKind { SubdiagnosticKind::Note => write!(f, "note"), SubdiagnosticKind::Help => write!(f, "help"), SubdiagnosticKind::Warn => write!(f, "warn"), - SubdiagnosticKind::Suggestion { .. } => write!(f, "suggestion_with_style"), - SubdiagnosticKind::MultipartSuggestion { .. } => { - write!(f, "multipart_suggestion_with_style") + SubdiagnosticKind::Suggestion(SubdiagnosticSuggestionKind::Normal) => { + write!(f, "suggestion") + } + SubdiagnosticKind::Suggestion(SubdiagnosticSuggestionKind::Short) => { + write!(f, "suggestion_short") + } + SubdiagnosticKind::Suggestion(SubdiagnosticSuggestionKind::Hidden) => { + write!(f, "suggestion_hidden") + } + SubdiagnosticKind::Suggestion(SubdiagnosticSuggestionKind::Verbose) => { + write!(f, "suggestion_verbose") } } } @@ -151,9 +148,11 @@ impl<'a> SessionSubdiagnosticDerive<'a> { variant, span, fields: fields_map, + kinds: Vec::new(), + slugs: Vec::new(), + code: None, span_field: None, applicability: None, - has_suggestion_parts: false, }; builder.into_tokens().unwrap_or_else(|v| v.to_compile_error()) }); @@ -194,15 +193,21 @@ struct SessionSubdiagnosticDeriveBuilder<'a> { /// derive builder. fields: HashMap, + /// Subdiagnostic kind of the type/variant. + kinds: Vec<(SubdiagnosticKind, proc_macro::Span)>, + + /// Slugs of the subdiagnostic - corresponds to the Fluent identifier for the message - from the + /// `#[kind(slug)]` attribute on the type or variant. + slugs: Vec<(Path, proc_macro::Span)>, + /// If a suggestion, the code to suggest as a replacement - from the `#[kind(code = "...")]` + /// attribute on the type or variant. + code: Option<(TokenStream, proc_macro::Span)>, + /// Identifier for the binding to the `#[primary_span]` field. span_field: Option<(proc_macro2::Ident, proc_macro::Span)>, /// If a suggestion, the identifier for the binding to the `#[applicability]` field or a /// `rustc_errors::Applicability::*` variant directly. applicability: Option<(TokenStream, proc_macro::Span)>, - - /// Set to true when a `#[suggestion_part]` field is encountered, used to generate an error - /// during finalization if still `false`. - has_suggestion_parts: bool, } impl<'a> HasFieldMap for SessionSubdiagnosticDeriveBuilder<'a> { @@ -212,133 +217,124 @@ impl<'a> HasFieldMap for SessionSubdiagnosticDeriveBuilder<'a> { } impl<'a> SessionSubdiagnosticDeriveBuilder<'a> { - fn identify_kind( - &mut self, - ) -> Result, DiagnosticDeriveError> { - let mut kind_slug = None; - - for attr in self.variant.ast().attrs { + fn identify_kind(&mut self) -> Result<(), DiagnosticDeriveError> { + for (i, attr) in self.variant.ast().attrs.iter().enumerate() { let span = attr.span().unwrap(); let name = attr.path.segments.last().unwrap().ident.to_string(); let name = name.as_str(); let meta = attr.parse_meta()?; - let Meta::List(MetaList { ref nested, .. }) = meta else { - throw_invalid_attr!(attr, &meta); - }; - - let mut kind = match name { - "label" => SubdiagnosticKind::Label, - "note" => SubdiagnosticKind::Note, - "help" => SubdiagnosticKind::Help, - "warning" => SubdiagnosticKind::Warn, - _ => { - if let Some(suggestion_kind) = - name.strip_prefix("suggestion").and_then(|s| s.parse().ok()) - { - SubdiagnosticKind::Suggestion { suggestion_kind, code: TokenStream::new() } - } else if let Some(suggestion_kind) = - name.strip_prefix("multipart_suggestion").and_then(|s| s.parse().ok()) - { - SubdiagnosticKind::MultipartSuggestion { suggestion_kind } - } else { - throw_invalid_attr!(attr, &meta); + let kind = match meta { + Meta::List(MetaList { ref nested, .. }) => { + let mut nested_iter = nested.into_iter(); + if let Some(nested_attr) = nested_iter.next() { + match nested_attr { + NestedMeta::Meta(Meta::Path(path)) => { + self.slugs.push((path.clone(), span)); + } + NestedMeta::Meta(meta @ Meta::NameValue(_)) + if matches!( + meta.path().segments.last().unwrap().ident.to_string().as_str(), + "code" | "applicability" + ) => + { + // don't error for valid follow-up attributes + } + nested_attr => { + throw_invalid_nested_attr!(attr, &nested_attr, |diag| { + diag.help( + "first argument of the attribute should be the diagnostic \ + slug", + ) + }) + } + }; } - } - }; - let mut slug = None; - let mut code = None; - - let mut nested_iter = nested.into_iter(); - if let Some(nested_attr) = nested_iter.next() { - match nested_attr { - NestedMeta::Meta(Meta::Path(path)) => { - slug.set_once((path.clone(), span)); - } - NestedMeta::Meta(meta @ Meta::NameValue(_)) - if matches!( - meta.path().segments.last().unwrap().ident.to_string().as_str(), - "code" | "applicability" - ) => - { - // Don't error for valid follow-up attributes. - } - nested_attr => { - throw_invalid_nested_attr!(attr, &nested_attr, |diag| { - diag.help( - "first argument of the attribute should be the diagnostic \ - slug", - ) - }) + for nested_attr in nested_iter { + let meta = match nested_attr { + NestedMeta::Meta(ref meta) => meta, + _ => throw_invalid_nested_attr!(attr, &nested_attr), + }; + + let span = meta.span().unwrap(); + let nested_name = meta.path().segments.last().unwrap().ident.to_string(); + let nested_name = nested_name.as_str(); + + match meta { + Meta::NameValue(MetaNameValue { lit: syn::Lit::Str(s), .. }) => { + match nested_name { + "code" => { + let formatted_str = self.build_format(&s.value(), s.span()); + self.code.set_once((formatted_str, span)); + } + "applicability" => { + let value = match Applicability::from_str(&s.value()) { + Ok(v) => v, + Err(()) => { + span_err(span, "invalid applicability").emit(); + Applicability::Unspecified + } + }; + self.applicability.set_once((quote! { #value }, span)); + } + _ => throw_invalid_nested_attr!(attr, &nested_attr, |diag| { + diag.help( + "only `code` and `applicability` are valid nested \ + attributes", + ) + }), + } + } + _ => throw_invalid_nested_attr!(attr, &nested_attr, |diag| { + if matches!(meta, Meta::Path(_)) { + diag.help( + "a diagnostic slug must be the first argument to the \ + attribute", + ) + } else { + diag + } + }), + } } - }; - } - for nested_attr in nested_iter { - let meta = match nested_attr { - NestedMeta::Meta(ref meta) => meta, - _ => throw_invalid_nested_attr!(attr, &nested_attr), - }; + let Ok(kind) = SubdiagnosticKind::from_str(name) else { + throw_invalid_attr!(attr, &meta) + }; - let span = meta.span().unwrap(); - let nested_name = meta.path().segments.last().unwrap().ident.to_string(); - let nested_name = nested_name.as_str(); + kind + } + _ => throw_invalid_attr!(attr, &meta), + }; - let value = match meta { - Meta::NameValue(MetaNameValue { lit: syn::Lit::Str(value), .. }) => value, - Meta::Path(_) => throw_invalid_nested_attr!(attr, &nested_attr, |diag| { - diag.help("a diagnostic slug must be the first argument to the attribute") - }), - _ => throw_invalid_nested_attr!(attr, &nested_attr), - }; + if matches!( + kind, + SubdiagnosticKind::Label | SubdiagnosticKind::Help | SubdiagnosticKind::Note + ) && self.code.is_some() + { + throw_span_err!( + span, + &format!("`code` is not a valid nested attribute of a `{}` attribute", name) + ); + } - match nested_name { - "code" => { - if matches!(kind, SubdiagnosticKind::Suggestion { .. }) { - let formatted_str = self.build_format(&value.value(), value.span()); - code.set_once((formatted_str, span)); - } else { - span_err( - span, - &format!( - "`code` is not a valid nested attribute of a `{}` attribute", - name - ), - ) - .emit(); - } - } - "applicability" => { - if matches!( - kind, - SubdiagnosticKind::Suggestion { .. } - | SubdiagnosticKind::MultipartSuggestion { .. } - ) { - let value = - Applicability::from_str(&value.value()).unwrap_or_else(|()| { - span_err(span, "invalid applicability").emit(); - Applicability::Unspecified - }); - self.applicability.set_once((quote! { #value }, span)); - } else { - span_err( - span, - &format!( - "`applicability` is not a valid nested attribute of a `{}` attribute", - name - ) - ).emit(); - } - } - _ => throw_invalid_nested_attr!(attr, &nested_attr, |diag| { - diag.help("only `code` and `applicability` are valid nested attributes") - }), - } + if matches!( + kind, + SubdiagnosticKind::Label | SubdiagnosticKind::Help | SubdiagnosticKind::Note + ) && self.applicability.is_some() + { + throw_span_err!( + span, + &format!( + "`applicability` is not a valid nested attribute of a `{}` attribute", + name + ) + ); } - let Some((slug, _)) = slug else { + if self.slugs.len() != i + 1 { throw_span_err!( span, &format!( @@ -346,338 +342,146 @@ impl<'a> SessionSubdiagnosticDeriveBuilder<'a> { name ) ); - }; - - match kind { - SubdiagnosticKind::Suggestion { code: ref mut code_field, .. } => { - let Some((code, _)) = code else { - throw_span_err!(span, "suggestion without `code = \"...\"`"); - }; - *code_field = code; - } - SubdiagnosticKind::Label - | SubdiagnosticKind::Note - | SubdiagnosticKind::Help - | SubdiagnosticKind::Warn - | SubdiagnosticKind::MultipartSuggestion { .. } => {} } - kind_slug.set_once(((kind, slug), span)) + self.kinds.push((kind, span)); } - Ok(kind_slug.map(|(kind_slug, _)| kind_slug)) - } - - /// Generates the code for a field with no attributes. - fn generate_field_set_arg(&mut self, binding: &BindingInfo<'_>) -> TokenStream { - let ast = binding.ast(); - assert_eq!(ast.attrs.len(), 0, "field with attribute used as diagnostic arg"); - - let diag = &self.diag; - let ident = ast.ident.as_ref().unwrap(); - quote! { - #diag.set_arg( - stringify!(#ident), - #binding - ); - } + Ok(()) } - /// Generates the necessary code for all attributes on a field. - fn generate_field_attr_code( + fn generate_field_code( &mut self, binding: &BindingInfo<'_>, - kind: &SubdiagnosticKind, - ) -> TokenStream { + have_suggestion: bool, + ) -> Result { let ast = binding.ast(); - assert!(ast.attrs.len() > 0, "field without attributes generating attr code"); - // Abstract over `Vec` and `Option` fields using `FieldInnerTy`, which will - // apply the generated code on each element in the `Vec` or `Option`. let inner_ty = FieldInnerTy::from_type(&ast.ty); - ast.attrs - .iter() - .map(|attr| { - let info = FieldInfo { - binding, - ty: inner_ty.inner_type().unwrap_or(&ast.ty), - span: &ast.span(), - }; - - let generated = self - .generate_field_code_inner(kind, attr, info) - .unwrap_or_else(|v| v.to_compile_error()); - - inner_ty.with(binding, generated) - }) - .collect() - } - - fn generate_field_code_inner( - &mut self, - kind: &SubdiagnosticKind, - attr: &Attribute, - info: FieldInfo<'_>, - ) -> Result { - let meta = attr.parse_meta()?; - match meta { - Meta::Path(path) => self.generate_field_code_inner_path(kind, attr, info, path), - Meta::List(list @ MetaList { .. }) => { - self.generate_field_code_inner_list(kind, attr, info, list) - } - _ => throw_invalid_attr!(attr, &meta), - } - } - - /// Generates the code for a `[Meta::Path]`-like attribute on a field (e.g. `#[primary_span]`). - fn generate_field_code_inner_path( - &mut self, - kind: &SubdiagnosticKind, - attr: &Attribute, - info: FieldInfo<'_>, - path: Path, - ) -> Result { - let span = attr.span().unwrap(); - let ident = &path.segments.last().unwrap().ident; - let name = ident.to_string(); - let name = name.as_str(); - - match name { - "skip_arg" => Ok(quote! {}), - "primary_span" => { - if matches!(kind, SubdiagnosticKind::MultipartSuggestion { .. }) { - throw_invalid_attr!(attr, &Meta::Path(path), |diag| { - diag.help( - "multipart suggestions use one or more `#[suggestion_part]`s rather \ - than one `#[primary_span]`", - ) - }) - } - - report_error_if_not_applied_to_span(attr, &info)?; + let info = FieldInfo { + binding: binding, + ty: inner_ty.inner_type().unwrap_or(&ast.ty), + span: &ast.span(), + }; - let binding = info.binding.binding.clone(); - self.span_field.set_once((binding, span)); + for attr in &ast.attrs { + let name = attr.path.segments.last().unwrap().ident.to_string(); + let name = name.as_str(); + let span = attr.span().unwrap(); - Ok(quote! {}) - } - "suggestion_part" => { - self.has_suggestion_parts = true; - - match kind { - SubdiagnosticKind::MultipartSuggestion { .. } => { - span_err( - span, - "`#[suggestion_part(...)]` attribute without `code = \"...\"`", - ) - .emit(); - Ok(quote! {}) + let meta = attr.parse_meta()?; + match meta { + Meta::Path(_) => match name { + "primary_span" => { + report_error_if_not_applied_to_span(attr, &info)?; + self.span_field.set_once((binding.binding.clone(), span)); + return Ok(quote! {}); } - SubdiagnosticKind::Label - | SubdiagnosticKind::Note - | SubdiagnosticKind::Help - | SubdiagnosticKind::Warn - | SubdiagnosticKind::Suggestion { .. } => { - throw_invalid_attr!(attr, &Meta::Path(path), |diag| { - diag.help( - "`#[suggestion_part(...)]` is only valid in multipart suggestions, use `#[primary_span]` instead", - ) - }); + "applicability" if have_suggestion => { + report_error_if_not_applied_to_applicability(attr, &info)?; + let binding = binding.binding.clone(); + self.applicability.set_once((quote! { #binding }, span)); + return Ok(quote! {}); } - } - } - "applicability" => { - if let SubdiagnosticKind::Suggestion { .. } - | SubdiagnosticKind::MultipartSuggestion { .. } = kind - { - report_error_if_not_applied_to_applicability(attr, &info)?; - - let binding = info.binding.binding.clone(); - self.applicability.set_once((quote! { #binding }, span)); - } else { - span_err(span, "`#[applicability]` is only valid on suggestions").emit(); - } - - Ok(quote! {}) - } - _ => throw_invalid_attr!(attr, &Meta::Path(path), |diag| { - let span_attr = if let SubdiagnosticKind::MultipartSuggestion { .. } = kind { - "suggestion_part" - } else { - "primary_span" - }; - diag.help(format!( - "only `{span_attr}`, `applicability` and `skip_arg` are valid field attributes", - )) - }), - } - } - - /// Generates the code for a `[Meta::List]`-like attribute on a field (e.g. - /// `#[suggestion_part(code = "...")]`). - fn generate_field_code_inner_list( - &mut self, - kind: &SubdiagnosticKind, - attr: &Attribute, - info: FieldInfo<'_>, - list: MetaList, - ) -> Result { - let span = attr.span().unwrap(); - let ident = &list.path.segments.last().unwrap().ident; - let name = ident.to_string(); - let name = name.as_str(); - - match name { - "suggestion_part" => { - if !matches!(kind, SubdiagnosticKind::MultipartSuggestion { .. }) { - throw_invalid_attr!(attr, &Meta::List(list), |diag| { + "applicability" => { + span_err(span, "`#[applicability]` is only valid on suggestions").emit(); + return Ok(quote! {}); + } + "skip_arg" => { + return Ok(quote! {}); + } + _ => throw_invalid_attr!(attr, &meta, |diag| { diag.help( - "`#[suggestion_part(...)]` is only valid in multipart suggestions", + "only `primary_span`, `applicability` and `skip_arg` are valid field \ + attributes", ) - }) - } - - self.has_suggestion_parts = true; - - report_error_if_not_applied_to_span(attr, &info)?; - - let mut code = None; - for nested_attr in list.nested.iter() { - let NestedMeta::Meta(ref meta) = nested_attr else { - throw_invalid_nested_attr!(attr, &nested_attr); - }; - - let span = meta.span().unwrap(); - let nested_name = meta.path().segments.last().unwrap().ident.to_string(); - let nested_name = nested_name.as_str(); - - let Meta::NameValue(MetaNameValue { lit: syn::Lit::Str(value), .. }) = meta else { - throw_invalid_nested_attr!(attr, &nested_attr); - }; + }), + }, + _ => throw_invalid_attr!(attr, &meta), + } + } - match nested_name { - "code" => { - let formatted_str = self.build_format(&value.value(), value.span()); - code.set_once((formatted_str, span)); - } - _ => throw_invalid_nested_attr!(attr, &nested_attr, |diag| { - diag.help("`code` is the only valid nested attribute") - }), - } - } + let ident = ast.ident.as_ref().unwrap(); - let Some((code, _)) = code else { - span_err(span, "`#[suggestion_part(...)]` attribute without `code = \"...\"`") - .emit(); - return Ok(quote! {}); - }; - let binding = info.binding; + let diag = &self.diag; + let generated = quote! { + #diag.set_arg( + stringify!(#ident), + #binding + ); + }; - Ok(quote! { suggestions.push((#binding, #code)); }) - } - _ => throw_invalid_attr!(attr, &Meta::List(list), |diag| { - let span_attr = if let SubdiagnosticKind::MultipartSuggestion { .. } = kind { - "suggestion_part" - } else { - "primary_span" - }; - diag.help(format!( - "only `{span_attr}`, `applicability` and `skip_arg` are valid field attributes", - )) - }), - } + Ok(inner_ty.with(binding, generated)) } - pub fn into_tokens(&mut self) -> Result { - let Some((kind, slug)) = self.identify_kind()? else { + fn into_tokens(&mut self) -> Result { + self.identify_kind()?; + if self.kinds.is_empty() { throw_span_err!( self.variant.ast().ident.span().unwrap(), "subdiagnostic kind not specified" ); }; + let have_suggestion = + self.kinds.iter().any(|(k, _)| matches!(k, SubdiagnosticKind::Suggestion(_))); + let mut args = TokenStream::new(); + for binding in self.variant.bindings() { + let arg = self + .generate_field_code(binding, have_suggestion) + .unwrap_or_else(|v| v.to_compile_error()); + args.extend(arg); + } + let mut tokens = TokenStream::new(); + for ((kind, _), (slug, _)) in self.kinds.iter().zip(&self.slugs) { + let code = match self.code.as_ref() { + Some((code, _)) => Some(quote! { #code }), + None if have_suggestion => { + span_err(self.span, "suggestion without `code = \"...\"`").emit(); + Some(quote! { /* macro error */ "..." }) + } + None => None, + }; - let init = match &kind { - SubdiagnosticKind::Label - | SubdiagnosticKind::Note - | SubdiagnosticKind::Help - | SubdiagnosticKind::Warn - | SubdiagnosticKind::Suggestion { .. } => quote! {}, - SubdiagnosticKind::MultipartSuggestion { .. } => { - quote! { let mut suggestions = Vec::new(); } - } - }; - - let attr_args: TokenStream = self - .variant - .bindings() - .iter() - .filter(|binding| !binding.ast().attrs.is_empty()) - .map(|binding| self.generate_field_attr_code(binding, &kind)) - .collect(); - - let span_field = self.span_field.as_ref().map(|(span, _)| span); - let applicability = self.applicability.take().map_or_else( - || quote! { rustc_errors::Applicability::Unspecified }, - |(applicability, _)| applicability, - ); + let span_field = self.span_field.as_ref().map(|(span, _)| span); + let applicability = match self.applicability.clone() { + Some((applicability, _)) => Some(applicability), + None if have_suggestion => { + span_err(self.span, "suggestion without `applicability`").emit(); + Some(quote! { rustc_errors::Applicability::Unspecified }) + } + None => None, + }; - let diag = &self.diag; - let name = format_ident!("{}{}", if span_field.is_some() { "span_" } else { "" }, kind); - let message = quote! { rustc_errors::fluent::#slug }; - let call = match kind { - SubdiagnosticKind::Suggestion { suggestion_kind, code } => { + let diag = &self.diag; + let name = format_ident!("{}{}", if span_field.is_some() { "span_" } else { "" }, kind); + let message = quote! { rustc_errors::fluent::#slug }; + let call = if matches!(kind, SubdiagnosticKind::Suggestion(..)) { if let Some(span) = span_field { - let style = suggestion_kind.to_suggestion_style(); - - quote! { #diag.#name(#span, #message, #code, #applicability, #style); } + quote! { #diag.#name(#span, #message, #code, #applicability); } } else { span_err(self.span, "suggestion without `#[primary_span]` field").emit(); quote! { unreachable!(); } } - } - SubdiagnosticKind::MultipartSuggestion { suggestion_kind } => { - if !self.has_suggestion_parts { - span_err( - self.span, - "multipart suggestion without any `#[suggestion_part(...)]` fields", - ) - .emit(); - } - - let style = suggestion_kind.to_suggestion_style(); - - quote! { #diag.#name(#message, suggestions, #applicability, #style); } - } - SubdiagnosticKind::Label => { + } else if matches!(kind, SubdiagnosticKind::Label) { if let Some(span) = span_field { quote! { #diag.#name(#span, #message); } } else { span_err(self.span, "label without `#[primary_span]` field").emit(); quote! { unreachable!(); } } - } - _ => { + } else { if let Some(span) = span_field { quote! { #diag.#name(#span, #message); } } else { quote! { #diag.#name(#message); } } - } - }; + }; + tokens.extend(quote! { + #call + #args + }); + } - let plain_args: TokenStream = self - .variant - .bindings() - .iter() - .filter(|binding| binding.ast().attrs.is_empty()) - .map(|binding| self.generate_field_set_arg(binding)) - .collect(); - - Ok(quote! { - #init - #attr_args - #call - #plain_args - }) + Ok(tokens) } } diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 515a022e9d9..9b808afeef6 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -1,50 +1,59 @@ -use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; -use rustc_session::SessionDiagnostic; +use rustc_errors::AddSubdiagnostic; use rustc_span::Span; -pub struct Cycle { +pub struct CycleStack { pub span: Span, - pub stack_bottom: String, - pub upper_stack_info: Vec<(Span, String)>, - pub recursive_ty_alias: bool, - pub recursive_trait_alias: bool, - pub cycle_usage: Option<(Span, String)>, + pub desc: String, } -impl SessionDiagnostic<'_> for Cycle { - fn into_diagnostic( - self, - sess: &'_ rustc_session::parse::ParseSess, - ) -> DiagnosticBuilder<'_, ErrorGuaranteed> { - let mut diag = sess.struct_err(rustc_errors::fluent::query_system::cycle); - diag.set_span(self.span); - diag.code(rustc_errors::DiagnosticId::Error("E0391".to_string())); - let upper_stack_len = self.upper_stack_info.len(); - for (span, desc) in self.upper_stack_info.into_iter() { - // FIXME(#100717): use fluent translation - diag.span_note(span, &format!("...which requires {}...", desc)); - } - diag.set_arg("stack_bottom", self.stack_bottom); - if upper_stack_len == 0 { - diag.note(rustc_errors::fluent::query_system::cycle_stack_single); - } else { - diag.note(rustc_errors::fluent::query_system::cycle_stack_multiple); - } - if self.recursive_trait_alias { - diag.note(rustc_errors::fluent::query_system::cycle_recursive_trait_alias); - } else if self.recursive_ty_alias { - diag.note(rustc_errors::fluent::query_system::cycle_recursive_ty_alias); - diag.help(rustc_errors::fluent::query_system::cycle_recursive_ty_alias_help1); - diag.help(rustc_errors::fluent::query_system::cycle_recursive_ty_alias_help2); - } - if let Some((span, desc)) = self.cycle_usage { - diag.set_arg("usage", desc); - diag.span_note(span, rustc_errors::fluent::query_system::cycle_usage); - } - diag +impl AddSubdiagnostic for CycleStack { + fn add_to_diagnostic(self, diag: &mut rustc_errors::Diagnostic) { + diag.span_note(self.span, &format!("...which requires {}...", self.desc)); } } +#[derive(SessionSubdiagnostic)] +pub enum StackCount { + #[note(query_system::cycle_stack_single)] + Single, + #[note(query_system::cycle_stack_multiple)] + Multiple, +} + +#[derive(SessionSubdiagnostic)] +pub enum Alias { + #[note(query_system::cycle_recursive_ty_alias)] + #[help(query_system::cycle_recursive_ty_alias_help1)] + #[help(query_system::cycle_recursive_ty_alias_help2)] + Ty, + #[note(query_system::cycle_recursive_trait_alias)] + Trait, +} + +#[derive(SessionSubdiagnostic)] +#[note(query_system::cycle_usage)] +pub struct CycleUsage { + #[primary_span] + pub span: Span, + pub usage: String, +} + +#[derive(SessionDiagnostic)] +#[diag(query_system::cycle, code = "E0391")] +pub struct Cycle { + #[primary_span] + pub span: Span, + pub stack_bottom: String, + #[subdiagnostic] + pub cycle_stack: Vec, + #[subdiagnostic] + pub stack_count: StackCount, + #[subdiagnostic] + pub alias: Option, + #[subdiagnostic] + pub cycle_usage: Option, +} + #[derive(SessionDiagnostic)] #[diag(query_system::reentrant)] pub struct Reentrant; diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index da775893a2b..7067bc5f09c 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -5,7 +5,7 @@ #![feature(min_specialization)] #![feature(extern_types)] #![allow(rustc::potential_query_instability)] -#![deny(rustc::untranslatable_diagnostic)] +// #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] #[macro_use] diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 718ec14db36..af1741bad6c 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -1,3 +1,4 @@ +use crate::error::CycleStack; use crate::query::plumbing::CycleError; use crate::query::{QueryContext, QueryStackFrame}; @@ -535,26 +536,42 @@ pub(crate) fn report_cycle<'a>( let span = stack[0].query.default_span(stack[1 % stack.len()].span); - let mut cycle_diag = crate::error::Cycle { - span, - upper_stack_info: Vec::with_capacity(stack.len() - 1), - stack_bottom: stack[0].query.description.to_owned(), - recursive_ty_alias: false, - recursive_trait_alias: false, - cycle_usage: usage.map(|(span, query)| (query.default_span(span), query.description)), - }; + let mut cycle_stack = Vec::new(); + + use crate::error::StackCount; + let stack_count = if stack.len() == 1 { StackCount::Single } else { StackCount::Multiple }; for i in 1..stack.len() { let query = &stack[i].query; let span = query.default_span(stack[(i + 1) % stack.len()].span); - cycle_diag.upper_stack_info.push((span, query.description.to_owned())); + cycle_stack.push(CycleStack { span, desc: query.description.to_owned() }); } - if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TyAlias)) { - cycle_diag.recursive_ty_alias = true; - } else if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TraitAlias)) { - cycle_diag.recursive_trait_alias = true; + let mut cycle_usage = None; + if let Some((span, query)) = usage { + cycle_usage = Some(crate::error::CycleUsage { + span: query.default_span(span), + usage: query.description, + }); } + // let cycle_usage = usage.map(|(span, query)| query.default_span(span)) + + let alias = if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TyAlias)) { + Some(crate::error::Alias::Ty) + } else if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TraitAlias)) { + Some(crate::error::Alias::Trait) + } else { + None + }; + + let cycle_diag = crate::error::Cycle { + span, + cycle_stack, + stack_bottom: stack[0].query.description.to_owned(), + alias, + cycle_usage: cycle_usage, + stack_count, + }; cycle_diag.into_diagnostic(&sess.parse_sess) } diff --git a/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs b/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs index 89eaec78c6f..f0843c60543 100644 --- a/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs +++ b/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs @@ -167,8 +167,8 @@ enum P { #[derive(SessionSubdiagnostic)] enum Q { #[bar] - //~^ ERROR `#[bar]` is not a valid attribute - //~^^ ERROR cannot find attribute `bar` in this scope +//~^ ERROR `#[bar]` is not a valid attribute +//~^^ ERROR cannot find attribute `bar` in this scope A { #[primary_span] span: Span, @@ -179,8 +179,8 @@ enum Q { #[derive(SessionSubdiagnostic)] enum R { #[bar = "..."] - //~^ ERROR `#[bar = ...]` is not a valid attribute - //~^^ ERROR cannot find attribute `bar` in this scope +//~^ ERROR `#[bar = ...]` is not a valid attribute +//~^^ ERROR cannot find attribute `bar` in this scope A { #[primary_span] span: Span, @@ -191,8 +191,8 @@ enum R { #[derive(SessionSubdiagnostic)] enum S { #[bar = 4] - //~^ ERROR `#[bar = ...]` is not a valid attribute - //~^^ ERROR cannot find attribute `bar` in this scope +//~^ ERROR `#[bar = ...]` is not a valid attribute +//~^^ ERROR cannot find attribute `bar` in this scope A { #[primary_span] span: Span, @@ -203,8 +203,8 @@ enum S { #[derive(SessionSubdiagnostic)] enum T { #[bar("...")] - //~^ ERROR `#[bar(...)]` is not a valid attribute - //~^^ ERROR cannot find attribute `bar` in this scope +//~^ ERROR `#[bar("...")]` is not a valid attribute +//~^^ ERROR cannot find attribute `bar` in this scope A { #[primary_span] span: Span, @@ -215,7 +215,7 @@ enum T { #[derive(SessionSubdiagnostic)] enum U { #[label(code = "...")] - //~^ ERROR diagnostic slug must be first argument of a `#[label(...)]` attribute +//~^ ERROR diagnostic slug must be first argument of a `#[label(...)]` attribute A { #[primary_span] span: Span, @@ -232,7 +232,7 @@ enum V { var: String, }, B { - //~^ ERROR subdiagnostic kind not specified +//~^ ERROR subdiagnostic kind not specified #[primary_span] span: Span, var: String, @@ -307,16 +307,6 @@ union AC { b: u64 } -#[derive(SessionSubdiagnostic)] -#[label(parser::add_paren)] -//~^ NOTE previously specified here -#[label(parser::add_paren)] -//~^ ERROR specified multiple times -struct AD { - #[primary_span] - span: Span, -} - #[derive(SessionSubdiagnostic)] #[label(parser::add_paren, parser::add_paren)] //~^ ERROR `#[label(parser::add_paren)]` is not a valid attribute @@ -329,16 +319,16 @@ struct AE { #[label(parser::add_paren)] struct AF { #[primary_span] - //~^ NOTE previously specified here +//~^ NOTE previously specified here span_a: Span, #[primary_span] - //~^ ERROR specified multiple times +//~^ ERROR specified multiple times span_b: Span, } #[derive(SessionSubdiagnostic)] struct AG { - //~^ ERROR subdiagnostic kind not specified +//~^ ERROR subdiagnostic kind not specified #[primary_span] span: Span, } @@ -390,25 +380,27 @@ struct AK { #[primary_span] span: Span, #[applicability] - //~^ NOTE previously specified here +//~^ NOTE previously specified here applicability_a: Applicability, #[applicability] - //~^ ERROR specified multiple times +//~^ ERROR specified multiple times applicability_b: Applicability, } #[derive(SessionSubdiagnostic)] #[suggestion(parser::add_paren, code = "...")] +//~^ ERROR suggestion without `applicability` struct AL { #[primary_span] span: Span, #[applicability] - //~^ ERROR the `#[applicability]` attribute can only be applied to fields of type `Applicability` +//~^ ERROR the `#[applicability]` attribute can only be applied to fields of type `Applicability` applicability: Span, } #[derive(SessionSubdiagnostic)] #[suggestion(parser::add_paren, code = "...")] +//~^ ERROR suggestion without `applicability` struct AM { #[primary_span] span: Span, @@ -444,7 +436,8 @@ struct AQ; #[derive(SessionSubdiagnostic)] #[suggestion(parser::add_paren, code = "...")] -//~^ ERROR suggestion without `#[primary_span]` field +//~^ ERROR suggestion without `applicability` +//~^^ ERROR suggestion without `#[primary_span]` field struct AR { var: String, } @@ -514,120 +507,3 @@ struct AZ { #[primary_span] span: Span, } - -#[derive(SessionSubdiagnostic)] -#[suggestion(parser::add_paren, code = "...")] -//~^ ERROR suggestion without `#[primary_span]` field -struct BA { - #[suggestion_part] - //~^ ERROR `#[suggestion_part]` is not a valid attribute - span: Span, - #[suggestion_part(code = "...")] - //~^ ERROR `#[suggestion_part(...)]` is not a valid attribute - span2: Span, - #[applicability] - applicability: Applicability, - var: String, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren, code = "...", applicability = "machine-applicable")] -//~^ ERROR multipart suggestion without any `#[suggestion_part(...)]` fields -//~| ERROR `code` is not a valid nested attribute of a `multipart_suggestion` attribute -struct BBa { - var: String, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] -struct BBb { - #[suggestion_part] - //~^ ERROR `#[suggestion_part(...)]` attribute without `code = "..."` - span1: Span, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] -struct BBc { - #[suggestion_part()] - //~^ ERROR `#[suggestion_part(...)]` attribute without `code = "..."` - span1: Span, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren)] -//~^ ERROR multipart suggestion without any `#[suggestion_part(...)]` fields -struct BC { - #[primary_span] - //~^ ERROR `#[primary_span]` is not a valid attribute - span: Span, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren)] -struct BD { - #[suggestion_part] - //~^ ERROR `#[suggestion_part(...)]` attribute without `code = "..."` - span1: Span, - #[suggestion_part()] - //~^ ERROR `#[suggestion_part(...)]` attribute without `code = "..."` - span2: Span, - #[suggestion_part(foo = "bar")] - //~^ ERROR `#[suggestion_part(foo = ...)]` is not a valid attribute - span4: Span, - #[suggestion_part(code = "...")] - //~^ ERROR the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` - s1: String, - #[suggestion_part()] - //~^ ERROR the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` - s2: String, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] -struct BE { - #[suggestion_part(code = "...", code = ",,,")] - //~^ ERROR specified multiple times - //~| NOTE previously specified here - span: Span, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] -struct BF { - #[suggestion_part(code = "(")] - first: Span, - #[suggestion_part(code = ")")] - second: Span, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren)] -struct BG { - #[applicability] - appl: Applicability, - #[suggestion_part(code = "(")] - first: Span, - #[suggestion_part(code = ")")] - second: Span, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] -//~^ NOTE previously specified here -struct BH { - #[applicability] - //~^ ERROR specified multiple times - appl: Applicability, - #[suggestion_part(code = "(")] - first: Span, - #[suggestion_part(code = ")")] - second: Span, -} - -#[derive(SessionSubdiagnostic)] -#[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] -struct BI { - #[suggestion_part(code = "")] - spans: Vec, -} diff --git a/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr b/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr index 75a34f44bbe..6bd9144dbf6 100644 --- a/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr +++ b/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr @@ -65,16 +65,16 @@ LL | #[label()] | ^^^^^^^^^^ error: `code` is not a valid nested attribute of a `label` attribute - --> $DIR/subdiagnostic-derive.rs:137:28 + --> $DIR/subdiagnostic-derive.rs:137:1 | LL | #[label(parser::add_paren, code = "...")] - | ^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `applicability` is not a valid nested attribute of a `label` attribute - --> $DIR/subdiagnostic-derive.rs:146:28 + --> $DIR/subdiagnostic-derive.rs:146:1 | LL | #[label(parser::add_paren, applicability = "machine-applicable")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: unsupported type attribute for subdiagnostic enum --> $DIR/subdiagnostic-derive.rs:155:1 @@ -100,11 +100,13 @@ error: `#[bar = ...]` is not a valid attribute LL | #[bar = 4] | ^^^^^^^^^^ -error: `#[bar(...)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:205:5 +error: `#[bar("...")]` is not a valid attribute + --> $DIR/subdiagnostic-derive.rs:205:11 | LL | #[bar("...")] - | ^^^^^^^^^^^^^ + | ^^^^^ + | + = help: first argument of the attribute should be the diagnostic slug error: diagnostic slug must be first argument of a `#[label(...)]` attribute --> $DIR/subdiagnostic-derive.rs:217:5 @@ -161,8 +163,6 @@ error: `#[bar(...)]` is not a valid attribute | LL | #[bar("...")] | ^^^^^^^^^^^^^ - | - = help: only `primary_span`, `applicability` and `skip_arg` are valid field attributes error: unexpected unsupported untagged union --> $DIR/subdiagnostic-derive.rs:304:1 @@ -174,20 +174,8 @@ LL | | b: u64 LL | | } | |_^ -error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:313:1 - | -LL | #[label(parser::add_paren)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -note: previously specified here - --> $DIR/subdiagnostic-derive.rs:311:1 - | -LL | #[label(parser::add_paren)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - error: `#[label(parser::add_paren)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:321:28 + --> $DIR/subdiagnostic-derive.rs:311:28 | LL | #[label(parser::add_paren, parser::add_paren)] | ^^^^^^^^^^^^^^^^^ @@ -195,225 +183,133 @@ LL | #[label(parser::add_paren, parser::add_paren)] = help: a diagnostic slug must be the first argument to the attribute error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:334:5 + --> $DIR/subdiagnostic-derive.rs:324:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ | note: previously specified here - --> $DIR/subdiagnostic-derive.rs:331:5 + --> $DIR/subdiagnostic-derive.rs:321:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ error: subdiagnostic kind not specified - --> $DIR/subdiagnostic-derive.rs:340:8 + --> $DIR/subdiagnostic-derive.rs:330:8 | LL | struct AG { | ^^ error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:377:47 + --> $DIR/subdiagnostic-derive.rs:367:47 | LL | #[suggestion(parser::add_paren, code = "...", code = "...")] | ^^^^^^^^^^^^ | note: previously specified here - --> $DIR/subdiagnostic-derive.rs:377:33 + --> $DIR/subdiagnostic-derive.rs:367:33 | LL | #[suggestion(parser::add_paren, code = "...", code = "...")] | ^^^^^^^^^^^^ error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:395:5 + --> $DIR/subdiagnostic-derive.rs:385:5 | LL | #[applicability] | ^^^^^^^^^^^^^^^^ | note: previously specified here - --> $DIR/subdiagnostic-derive.rs:392:5 + --> $DIR/subdiagnostic-derive.rs:382:5 | LL | #[applicability] | ^^^^^^^^^^^^^^^^ error: the `#[applicability]` attribute can only be applied to fields of type `Applicability` - --> $DIR/subdiagnostic-derive.rs:405:5 + --> $DIR/subdiagnostic-derive.rs:396:5 | LL | #[applicability] | ^^^^^^^^^^^^^^^^ -error: suggestion without `code = "..."` - --> $DIR/subdiagnostic-derive.rs:418:1 - | -LL | #[suggestion(parser::add_paren)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: invalid applicability - --> $DIR/subdiagnostic-derive.rs:428:46 - | -LL | #[suggestion(parser::add_paren, code ="...", applicability = "foo")] - | ^^^^^^^^^^^^^^^^^^^^^ - -error: suggestion without `#[primary_span]` field - --> $DIR/subdiagnostic-derive.rs:446:1 +error: suggestion without `applicability` + --> $DIR/subdiagnostic-derive.rs:391:1 | LL | / #[suggestion(parser::add_paren, code = "...")] LL | | -LL | | struct AR { -LL | | var: String, +LL | | struct AL { +LL | | #[primary_span] +... | +LL | | applicability: Span, LL | | } | |_^ -error: unsupported type attribute for subdiagnostic enum - --> $DIR/subdiagnostic-derive.rs:460:1 - | -LL | #[label] - | ^^^^^^^^ - -error: `var` doesn't refer to a field on this type - --> $DIR/subdiagnostic-derive.rs:480:39 - | -LL | #[suggestion(parser::add_paren, code ="{var}", applicability = "machine-applicable")] - | ^^^^^^^ - -error: `var` doesn't refer to a field on this type - --> $DIR/subdiagnostic-derive.rs:499:43 - | -LL | #[suggestion(parser::add_paren, code ="{var}", applicability = "machine-applicable")] - | ^^^^^^^ - -error: `#[suggestion_part]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:522:5 - | -LL | #[suggestion_part] - | ^^^^^^^^^^^^^^^^^^ - | - = help: `#[suggestion_part(...)]` is only valid in multipart suggestions, use `#[primary_span]` instead - -error: `#[suggestion_part(...)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:525:5 +error: suggestion without `applicability` + --> $DIR/subdiagnostic-derive.rs:402:1 | -LL | #[suggestion_part(code = "...")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = help: `#[suggestion_part(...)]` is only valid in multipart suggestions +LL | / #[suggestion(parser::add_paren, code = "...")] +LL | | +LL | | struct AM { +LL | | #[primary_span] +LL | | span: Span, +LL | | } + | |_^ -error: suggestion without `#[primary_span]` field - --> $DIR/subdiagnostic-derive.rs:519:1 +error: suggestion without `code = "..."` + --> $DIR/subdiagnostic-derive.rs:410:1 | -LL | / #[suggestion(parser::add_paren, code = "...")] +LL | / #[suggestion(parser::add_paren)] LL | | -LL | | struct BA { -LL | | #[suggestion_part] +LL | | struct AN { +LL | | #[primary_span] ... | -LL | | var: String, +LL | | applicability: Applicability, LL | | } | |_^ -error: `code` is not a valid nested attribute of a `multipart_suggestion` attribute - --> $DIR/subdiagnostic-derive.rs:534:43 +error: invalid applicability + --> $DIR/subdiagnostic-derive.rs:420:46 | -LL | #[multipart_suggestion(parser::add_paren, code = "...", applicability = "machine-applicable")] - | ^^^^^^^^^^^^ +LL | #[suggestion(parser::add_paren, code ="...", applicability = "foo")] + | ^^^^^^^^^^^^^^^^^^^^^ -error: multipart suggestion without any `#[suggestion_part(...)]` fields - --> $DIR/subdiagnostic-derive.rs:534:1 +error: suggestion without `applicability` + --> $DIR/subdiagnostic-derive.rs:438:1 | -LL | / #[multipart_suggestion(parser::add_paren, code = "...", applicability = "machine-applicable")] +LL | / #[suggestion(parser::add_paren, code = "...")] LL | | LL | | -LL | | struct BBa { +LL | | struct AR { LL | | var: String, LL | | } | |_^ -error: `#[suggestion_part(...)]` attribute without `code = "..."` - --> $DIR/subdiagnostic-derive.rs:544:5 - | -LL | #[suggestion_part] - | ^^^^^^^^^^^^^^^^^^ - -error: `#[suggestion_part(...)]` attribute without `code = "..."` - --> $DIR/subdiagnostic-derive.rs:552:5 - | -LL | #[suggestion_part()] - | ^^^^^^^^^^^^^^^^^^^^ - -error: `#[primary_span]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:561:5 - | -LL | #[primary_span] - | ^^^^^^^^^^^^^^^ - | - = help: multipart suggestions use one or more `#[suggestion_part]`s rather than one `#[primary_span]` - -error: multipart suggestion without any `#[suggestion_part(...)]` fields - --> $DIR/subdiagnostic-derive.rs:558:1 +error: suggestion without `#[primary_span]` field + --> $DIR/subdiagnostic-derive.rs:438:1 | -LL | / #[multipart_suggestion(parser::add_paren)] +LL | / #[suggestion(parser::add_paren, code = "...")] LL | | -LL | | struct BC { -LL | | #[primary_span] LL | | -LL | | span: Span, +LL | | struct AR { +LL | | var: String, LL | | } | |_^ -error: `#[suggestion_part(...)]` attribute without `code = "..."` - --> $DIR/subdiagnostic-derive.rs:569:5 - | -LL | #[suggestion_part] - | ^^^^^^^^^^^^^^^^^^ - -error: `#[suggestion_part(...)]` attribute without `code = "..."` - --> $DIR/subdiagnostic-derive.rs:572:5 - | -LL | #[suggestion_part()] - | ^^^^^^^^^^^^^^^^^^^^ - -error: `#[suggestion_part(foo = ...)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:575:23 - | -LL | #[suggestion_part(foo = "bar")] - | ^^^^^^^^^^^ - | - = help: `code` is the only valid nested attribute - -error: the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` - --> $DIR/subdiagnostic-derive.rs:578:5 - | -LL | #[suggestion_part(code = "...")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` - --> $DIR/subdiagnostic-derive.rs:581:5 +error: unsupported type attribute for subdiagnostic enum + --> $DIR/subdiagnostic-derive.rs:453:1 | -LL | #[suggestion_part()] - | ^^^^^^^^^^^^^^^^^^^^ +LL | #[label] + | ^^^^^^^^ -error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:589:37 - | -LL | #[suggestion_part(code = "...", code = ",,,")] - | ^^^^^^^^^^^^ - | -note: previously specified here - --> $DIR/subdiagnostic-derive.rs:589:23 +error: `var` doesn't refer to a field on this type + --> $DIR/subdiagnostic-derive.rs:473:39 | -LL | #[suggestion_part(code = "...", code = ",,,")] - | ^^^^^^^^^^^^ +LL | #[suggestion(parser::add_paren, code ="{var}", applicability = "machine-applicable")] + | ^^^^^^^ -error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:619:5 - | -LL | #[applicability] - | ^^^^^^^^^^^^^^^^ - | -note: previously specified here - --> $DIR/subdiagnostic-derive.rs:616:43 +error: `var` doesn't refer to a field on this type + --> $DIR/subdiagnostic-derive.rs:492:43 | -LL | #[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[suggestion(parser::add_paren, code ="{var}", applicability = "machine-applicable")] + | ^^^^^^^ error: cannot find attribute `foo` in this scope --> $DIR/subdiagnostic-derive.rs:63:3 @@ -475,6 +371,6 @@ error[E0425]: cannot find value `slug` in module `rustc_errors::fluent` LL | #[label(slug)] | ^^^^ not found in `rustc_errors::fluent` -error: aborting due to 64 previous errors +error: aborting due to 50 previous errors For more information about this error, try `rustc --explain E0425`. -- cgit 1.4.1-3-g733a5 From 166aef90fb7936892af5f0f88335e732d207c731 Mon Sep 17 00:00:00 2001 From: Li Yuanheng <520dhh@gmail.com> Date: Thu, 25 Aug 2022 23:32:28 +0800 Subject: delete leftover comment --- compiler/rustc_query_system/src/query/job.rs | 1 - 1 file changed, 1 deletion(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index af1741bad6c..ddb5cd06344 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -554,7 +554,6 @@ pub(crate) fn report_cycle<'a>( usage: query.description, }); } - // let cycle_usage = usage.map(|(span, query)| query.default_span(span)) let alias = if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TyAlias)) { Some(crate::error::Alias::Ty) -- cgit 1.4.1-3-g733a5 From 7ce59ebf496590c8b2ba3693c13e981d369add4b Mon Sep 17 00:00:00 2001 From: Li Yuanheng <520dhh@gmail.com> Date: Sat, 27 Aug 2022 11:55:38 +0800 Subject: SessionDiagnostic for QueryOverflow error --- compiler/rustc_error_messages/locales/en-US/query_system.ftl | 2 ++ compiler/rustc_error_messages/src/lib.rs | 2 +- compiler/rustc_query_system/src/error.rs | 4 ++++ compiler/rustc_query_system/src/query/mod.rs | 2 +- 4 files changed, 8 insertions(+), 2 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_error_messages/locales/en-US/query_system.ftl b/compiler/rustc_error_messages/locales/en-US/query_system.ftl index 7fdecf4f381..167704e46c0 100644 --- a/compiler/rustc_error_messages/locales/en-US/query_system.ftl +++ b/compiler/rustc_error_messages/locales/en-US/query_system.ftl @@ -21,3 +21,5 @@ query_system_cycle_recursive_ty_alias_help2 = see "../locales/en-US/passes.ftl", plugin_impl => "../locales/en-US/plugin_impl.ftl", privacy => "../locales/en-US/privacy.ftl", + query_system => "../locales/en-US/query_system.ftl", save_analysis => "../locales/en-US/save_analysis.ftl", ty_utils => "../locales/en-US/ty_utils.ftl", typeck => "../locales/en-US/typeck.ftl", mir_dataflow => "../locales/en-US/mir_dataflow.ftl", - query_system => "../locales/en-US/query_system.ftl", } pub use fluent_generated::{self as fluent, DEFAULT_LOCALE_RESOURCES}; diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 9b808afeef6..5f992ec9e21 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -67,3 +67,7 @@ pub struct IncrementCompilation { pub run_cmd: String, pub dep_node: String, } + +#[derive(SessionDiagnostic)] +#[diag(query_system::query_overflow)] +pub struct QueryOverflow; diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index a1f2b081d43..c6197b9fedb 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -125,6 +125,6 @@ pub trait QueryContext: HasDepContext { ) -> R; fn depth_limit_error(&self) { - self.dep_context().sess().fatal("queries overflow the depth limit!"); + self.dep_context().sess().emit_fatal(crate::error::QueryOverflow); } } -- cgit 1.4.1-3-g733a5 From 4e09a13bb848a64acf6bb20359f582e813e74764 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Mon, 29 Aug 2022 10:20:14 -0500 Subject: Don't create two new closures for each query - Parameterize DepKindStruct over `'tcx` This allows passing in an invariant function pointer in `query_callback`, rather than having to try and make it work for any lifetime. - Add a new `execute_query` function to `QueryDescription` so we can call `tcx.$name` without needing to be in a macro context --- compiler/rustc_middle/src/arena.rs | 2 +- compiler/rustc_middle/src/dep_graph/dep_node.rs | 6 +-- compiler/rustc_middle/src/ty/context.rs | 6 +-- compiler/rustc_query_impl/src/plumbing.rs | 51 ++++++++++--------------- compiler/rustc_query_system/src/query/config.rs | 3 ++ 5 files changed, 31 insertions(+), 37 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index b94de537dc8..65d5f755f72 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -100,7 +100,7 @@ macro_rules! arena_types { [decode] is_late_bound_map: rustc_data_structures::fx::FxIndexSet, [decode] impl_source: rustc_middle::traits::ImplSource<'tcx, ()>, - [] dep_kind: rustc_middle::dep_graph::DepKindStruct, + [] dep_kind: rustc_middle::dep_graph::DepKindStruct<'tcx>, ]); ) } diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 65fc8a2e9cf..7718906ac4e 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -74,7 +74,7 @@ pub use rustc_query_system::dep_graph::{DepContext, DepNodeParams}; /// Information is retrieved by indexing the `DEP_KINDS` array using the integer value /// of the `DepKind`. Overall, this allows to implement `DepContext` using this manual /// jump table instead of large matches. -pub struct DepKindStruct { +pub struct DepKindStruct<'tcx> { /// Anonymous queries cannot be replayed from one compiler invocation to the next. /// When their result is needed, it is recomputed. They are useful for fine-grained /// dependency tracking, and caching within one compiler invocation. @@ -124,10 +124,10 @@ pub struct DepKindStruct { /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode` /// is actually a `DefPathHash`, and can therefore just look up the corresponding /// `DefId` in `tcx.def_path_hash_to_def_id`. - pub force_from_dep_node: Option, dep_node: DepNode) -> bool>, + pub force_from_dep_node: Option, dep_node: DepNode) -> bool>, /// Invoke a query to put the on-disk cached value in memory. - pub try_load_from_on_disk_cache: Option, DepNode)>, + pub try_load_from_on_disk_cache: Option, DepNode)>, } impl DepKind { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 052bb1263c9..7a990773ab8 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1089,7 +1089,7 @@ pub struct GlobalCtxt<'tcx> { pub queries: &'tcx dyn query::QueryEngine<'tcx>, pub query_caches: query::QueryCaches<'tcx>, - query_kinds: &'tcx [DepKindStruct], + query_kinds: &'tcx [DepKindStruct<'tcx>], // Internal caches for metadata decoding. No need to track deps on this. pub ty_rcache: Lock>>, @@ -1246,7 +1246,7 @@ impl<'tcx> TyCtxt<'tcx> { dep_graph: DepGraph, on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, queries: &'tcx dyn query::QueryEngine<'tcx>, - query_kinds: &'tcx [DepKindStruct], + query_kinds: &'tcx [DepKindStruct<'tcx>], crate_name: &str, output_filenames: OutputFilenames, ) -> GlobalCtxt<'tcx> { @@ -1296,7 +1296,7 @@ impl<'tcx> TyCtxt<'tcx> { } } - pub(crate) fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct { + pub(crate) fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct<'tcx> { &self.query_kinds[k as usize] } diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index cc7e0765171..274df5b5e5e 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -301,11 +301,8 @@ pub(crate) fn create_query_frame< QueryStackFrame::new(name, description, span, def_kind, hash) } -pub(crate) fn try_load_from_on_disk_cache<'tcx, Q, V>( - tcx: TyCtxt<'tcx>, - dep_node: DepNode, - cache_query_deps: fn(TyCtxt<'tcx>, Q::Key) -> V, -) where +fn try_load_from_on_disk_cache<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode) +where Q: QueryDescription>, Q::Key: DepNodeParams>, { @@ -315,11 +312,11 @@ pub(crate) fn try_load_from_on_disk_cache<'tcx, Q, V>( panic!("Failed to recover key for {:?} with hash {}", dep_node, dep_node.hash) }); if Q::cache_on_disk(tcx, &key) { - let _ = cache_query_deps(tcx, key); + let _ = Q::execute_query(tcx, key); } } -pub(crate) fn force_from_dep_node<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> bool +fn force_from_dep_node<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> bool where Q: QueryDescription>, Q::Key: DepNodeParams>, @@ -336,13 +333,9 @@ where } pub(crate) fn query_callback<'tcx, Q: QueryConfig>( - // NOTE: we can't remove these function pointers, because `recover` is invariant -> `try_load_from_on_disk_cache` takes a concrete lifetime, not a universal lifetime. - // Instead, we infer the correct lifetime at the callsite, so we can pass in a HRTB function pointer to the DepKindStruct. - try_load_from_on_disk_cache: fn(TyCtxt<'_>, DepNode), - force_from_dep_node: fn(TyCtxt<'_>, DepNode) -> bool, is_anon: bool, is_eval_always: bool, -) -> DepKindStruct +) -> DepKindStruct<'tcx> where Q: QueryDescription>, Q::Key: DepNodeParams>, @@ -363,8 +356,8 @@ where is_anon, is_eval_always, fingerprint_style, - force_from_dep_node: Some(force_from_dep_node), - try_load_from_on_disk_cache: Some(try_load_from_on_disk_cache), + force_from_dep_node: Some(force_from_dep_node::), + try_load_from_on_disk_cache: Some(try_load_from_on_disk_cache::), } } @@ -431,6 +424,10 @@ macro_rules! define_queries { try_load_from_disk: Self::TRY_LOAD_FROM_DISK, } } + + fn execute_query(tcx: TyCtxt<'tcx>, k: Self::Key) -> Self::Stored { + tcx.$name(k) + } })* #[allow(nonstandard_style)] @@ -439,7 +436,7 @@ macro_rules! define_queries { use rustc_query_system::dep_graph::FingerprintStyle; // We use this for most things when incr. comp. is turned off. - pub fn Null() -> DepKindStruct { + pub fn Null<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: false, is_eval_always: false, @@ -450,7 +447,7 @@ macro_rules! define_queries { } // We use this for the forever-red node. - pub fn Red() -> DepKindStruct { + pub fn Red<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: false, is_eval_always: false, @@ -460,7 +457,7 @@ macro_rules! define_queries { } } - pub fn TraitSelect() -> DepKindStruct { + pub fn TraitSelect<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: true, is_eval_always: false, @@ -470,7 +467,7 @@ macro_rules! define_queries { } } - pub fn CompileCodegenUnit() -> DepKindStruct { + pub fn CompileCodegenUnit<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: false, is_eval_always: false, @@ -480,7 +477,7 @@ macro_rules! define_queries { } } - pub fn CompileMonoItem() -> DepKindStruct { + pub fn CompileMonoItem<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: false, is_eval_always: false, @@ -490,21 +487,15 @@ macro_rules! define_queries { } } - $(pub(crate) fn $name()-> DepKindStruct { - let is_anon = is_anon!([$($modifiers)*]); - let is_eval_always = is_eval_always!([$($modifiers)*]); - type Q<'tcx> = queries::$name<'tcx>; - - $crate::plumbing::query_callback::>( - |tcx, key| $crate::plumbing::try_load_from_on_disk_cache::, _>(tcx, key, TyCtxt::$name), - |tcx, key| $crate::plumbing::force_from_dep_node::>(tcx, key), - is_anon, - is_eval_always + $(pub(crate) fn $name<'tcx>()-> DepKindStruct<'tcx> { + $crate::plumbing::query_callback::>( + is_anon!([$($modifiers)*]), + is_eval_always!([$($modifiers)*]), ) })* } - pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct] { + pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct<'tcx>] { arena.alloc_from_iter(make_dep_kind_array!(query_callbacks)) } } diff --git a/compiler/rustc_query_system/src/query/config.rs b/compiler/rustc_query_system/src/query/config.rs index bd0fd7ac350..ea38df836cb 100644 --- a/compiler/rustc_query_system/src/query/config.rs +++ b/compiler/rustc_query_system/src/query/config.rs @@ -73,4 +73,7 @@ pub trait QueryDescription: QueryConfig { fn make_vtable(tcx: CTX, key: &Self::Key) -> QueryVTable; fn cache_on_disk(tcx: CTX::DepContext, key: &Self::Key) -> bool; + + // Don't use this method to compute query results, instead use the methods on TyCtxt + fn execute_query(tcx: CTX::DepContext, k: Self::Key) -> Self::Stored; } -- cgit 1.4.1-3-g733a5 From 321e60bf3429d32c5ab1d03f22e3e4654bc0c388 Mon Sep 17 00:00:00 2001 From: Jhonny Bill Mena Date: Mon, 5 Sep 2022 00:15:50 -0400 Subject: UPDATE - into_diagnostic to take a Handler instead of a ParseSess Suggested by the team in this Zulip Topic https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20SessionDiagnostic.20on.20Handler Handler already has almost all the capabilities of ParseSess when it comes to diagnostic emission, in this migration we only needed to add the ability to access source_map from the emitter in order to get a Snippet and the start_point. Not sure if this is the best way to address this gap --- compiler/rustc_attr/src/session_diagnostics.rs | 18 +++++++++++------- compiler/rustc_errors/src/lib.rs | 22 ++++++++++++++++++++++ .../src/infer/error_reporting/need_type_info.rs | 14 +++++++------- compiler/rustc_lint/src/errors.rs | 8 ++++---- .../rustc_macros/src/diagnostics/diagnostic.rs | 2 +- compiler/rustc_metadata/src/errors.rs | 12 ++++++------ compiler/rustc_monomorphize/src/errors.rs | 5 +++-- compiler/rustc_parse/src/parser/expr.rs | 5 +++-- compiler/rustc_query_system/src/query/job.rs | 2 +- compiler/rustc_session/src/parse.rs | 6 +++--- compiler/rustc_session/src/session.rs | 6 +++--- compiler/rustc_trait_selection/src/errors.rs | 8 ++++---- compiler/rustc_typeck/src/errors.rs | 12 ++++++------ src/test/ui-fulldeps/internal-lints/diagnostics.rs | 22 +++++++++++----------- 14 files changed, 85 insertions(+), 57 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 25cd960dbf1..f74540e9655 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -1,9 +1,11 @@ use std::num::IntErrorKind; use rustc_ast as ast; -use rustc_errors::{error_code, fluent, Applicability, DiagnosticBuilder, ErrorGuaranteed}; +use rustc_errors::{ + error_code, fluent, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler, +}; use rustc_macros::SessionDiagnostic; -use rustc_session::{parse::ParseSess, SessionDiagnostic}; +use rustc_session::SessionDiagnostic; use rustc_span::{Span, Symbol}; use crate::UnsupportedLiteralReason; @@ -49,9 +51,9 @@ pub(crate) struct UnknownMetaItem<'a> { // Manual implementation to be able to format `expected` items correctly. impl<'a> SessionDiagnostic<'a> for UnknownMetaItem<'_> { - fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, ErrorGuaranteed> { + fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { let expected = self.expected.iter().map(|name| format!("`{}`", name)).collect::>(); - let mut diag = sess.span_diagnostic.struct_span_err_with_code( + let mut diag = handler.struct_span_err_with_code( self.span, fluent::attr::unknown_meta_item, error_code!(E0541), @@ -207,8 +209,8 @@ pub(crate) struct UnsupportedLiteral { } impl<'a> SessionDiagnostic<'a> for UnsupportedLiteral { - fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, ErrorGuaranteed> { - let mut diag = sess.span_diagnostic.struct_span_err_with_code( + fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { + let mut diag = handler.struct_span_err_with_code( self.span, match self.reason { UnsupportedLiteralReason::Generic => fluent::attr::unsupported_literal_generic, @@ -223,8 +225,10 @@ impl<'a> SessionDiagnostic<'a> for UnsupportedLiteral { error_code!(E0565), ); if self.is_bytestr { + let start_point = handler.span_start_point_from_emitter(self.span).unwrap_or(self.span); + diag.span_suggestion( - sess.source_map().start_point(self.span), + start_point, fluent::attr::unsupported_literal_suggestion, "", Applicability::MaybeIncorrect, diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 68abdd0bad1..af554db3013 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -1098,6 +1098,28 @@ impl Handler { ); std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations) } + + pub fn span_to_snippet_from_emitter( + &self, + span: rustc_span::Span, + ) -> Option> { + self.inner + .borrow() + .emitter + .source_map() + .map_or_else(|| Option::None, |sm| Some(sm.span_to_snippet(span))) + } + + pub fn span_start_point_from_emitter( + &self, + span: rustc_span::Span, + ) -> Option { + self.inner + .borrow() + .emitter + .source_map() + .map_or_else(|| Option::None, |sm| Some(sm.start_point(span))) + } } impl HandlerInner { diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index 91a05367eee..44c8084d732 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -341,7 +341,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { multi_suggestions, bad_label, } - .into_diagnostic(&self.tcx.sess.parse_sess), + .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic), TypeAnnotationNeeded::E0283 => AmbigousImpl { span, source_kind, @@ -351,7 +351,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { multi_suggestions, bad_label, } - .into_diagnostic(&self.tcx.sess.parse_sess), + .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic), TypeAnnotationNeeded::E0284 => AmbigousReturn { span, source_kind, @@ -361,7 +361,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { multi_suggestions, bad_label, } - .into_diagnostic(&self.tcx.sess.parse_sess), + .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic), } } @@ -537,7 +537,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { multi_suggestions, bad_label: None, } - .into_diagnostic(&self.tcx.sess.parse_sess), + .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic), TypeAnnotationNeeded::E0283 => AmbigousImpl { span, source_kind, @@ -547,7 +547,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { multi_suggestions, bad_label: None, } - .into_diagnostic(&self.tcx.sess.parse_sess), + .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic), TypeAnnotationNeeded::E0284 => AmbigousReturn { span, source_kind, @@ -557,7 +557,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { multi_suggestions, bad_label: None, } - .into_diagnostic(&self.tcx.sess.parse_sess), + .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic), } } @@ -575,7 +575,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { span, generator_kind: GeneratorKindAsDiagArg(kind), } - .into_diagnostic(&self.tcx.sess.parse_sess) + .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic) } } diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index 606d8bda8aa..5c183d4091e 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -1,6 +1,6 @@ -use rustc_errors::{fluent, AddSubdiagnostic, ErrorGuaranteed}; +use rustc_errors::{fluent, AddSubdiagnostic, ErrorGuaranteed, Handler}; use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; -use rustc_session::{lint::Level, parse::ParseSess, SessionDiagnostic}; +use rustc_session::{lint::Level, SessionDiagnostic}; use rustc_span::{Span, Symbol}; #[derive(SessionDiagnostic)] @@ -122,9 +122,9 @@ pub struct CheckNameUnknown { impl SessionDiagnostic<'_> for CheckNameUnknown { fn into_diagnostic( self, - sess: &ParseSess, + handler: &Handler, ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { - let mut diag = sess.struct_err(fluent::lint::check_name_unknown); + let mut diag = handler.struct_err(fluent::lint::check_name_unknown); diag.code(rustc_errors::error_code!(E0602)); if let Some(suggestion) = self.suggestion { diag.help(fluent::lint::help); diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic.rs b/compiler/rustc_macros/src/diagnostics/diagnostic.rs index 244edec2841..cf1c5945529 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -88,7 +88,7 @@ impl<'a> SessionDiagnosticDerive<'a> { { fn into_diagnostic( self, - #sess: &'__session_diagnostic_sess rustc_session::parse::ParseSess + #sess: &'__session_diagnostic_sess rustc_errors::Handler ) -> rustc_errors::DiagnosticBuilder<'__session_diagnostic_sess, G> { use rustc_errors::IntoDiagnosticArg; #implementation diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 18d0248333a..8378d2b791d 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -424,9 +424,9 @@ pub(crate) struct MultipleCandidates { impl SessionDiagnostic<'_> for MultipleCandidates { fn into_diagnostic( self, - sess: &'_ rustc_session::parse::ParseSess, + handler: &'_ rustc_errors::Handler, ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { - let mut diag = sess.struct_err(rustc_errors::fluent::metadata::multiple_candidates); + let mut diag = handler.struct_err(rustc_errors::fluent::metadata::multiple_candidates); diag.set_arg("crate_name", self.crate_name); diag.set_arg("flavor", self.flavor); diag.code(error_code!(E0465)); @@ -540,9 +540,9 @@ pub struct InvalidMetadataFiles { impl SessionDiagnostic<'_> for InvalidMetadataFiles { fn into_diagnostic( self, - sess: &'_ rustc_session::parse::ParseSess, + handler: &'_ rustc_errors::Handler, ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { - let mut diag = sess.struct_err(rustc_errors::fluent::metadata::invalid_meta_files); + let mut diag = handler.struct_err(rustc_errors::fluent::metadata::invalid_meta_files); diag.set_arg("crate_name", self.crate_name); diag.set_arg("add_info", self.add_info); diag.code(error_code!(E0786)); @@ -568,9 +568,9 @@ pub struct CannotFindCrate { impl SessionDiagnostic<'_> for CannotFindCrate { fn into_diagnostic( self, - sess: &'_ rustc_session::parse::ParseSess, + handler: &'_ rustc_errors::Handler, ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { - let mut diag = sess.struct_err(rustc_errors::fluent::metadata::cannot_find_crate); + let mut diag = handler.struct_err(rustc_errors::fluent::metadata::cannot_find_crate); diag.set_arg("crate_name", self.crate_name); diag.set_arg("add_info", self.add_info); diag.set_arg("locator_triple", self.locator_triple.triple()); diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index 77b6cfa1f69..d5f05e790d3 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -47,9 +47,10 @@ pub struct UnusedGenericParams { impl SessionDiagnostic<'_> for UnusedGenericParams { fn into_diagnostic( self, - sess: &'_ rustc_session::parse::ParseSess, + handler: &'_ rustc_errors::Handler, ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { - let mut diag = sess.struct_err(rustc_errors::fluent::monomorphize::unused_generic_params); + let mut diag = + handler.struct_err(rustc_errors::fluent::monomorphize::unused_generic_params); diag.set_span(self.span); for (span, name) in self.param_spans.into_iter().zip(self.param_names) { // FIXME: I can figure out how to do a label with a fluent string with a fixed message, diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index d4828a20120..7addf519872 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1997,7 +1997,7 @@ impl<'a> Parser<'a> { return Err(MissingSemicolonBeforeArray { open_delim: open_delim_span, semicolon: prev_span.shrink_to_hi(), - }.into_diagnostic(self.sess)); + }.into_diagnostic(&self.sess.span_diagnostic)); } Ok(_) => (), Err(err) => err.cancel(), @@ -2745,7 +2745,8 @@ impl<'a> Parser<'a> { fn parse_try_block(&mut self, span_lo: Span) -> PResult<'a, P> { let (attrs, body) = self.parse_inner_attrs_and_block()?; if self.eat_keyword(kw::Catch) { - Err(CatchAfterTry { span: self.prev_token.span }.into_diagnostic(self.sess)) + Err(CatchAfterTry { span: self.prev_token.span } + .into_diagnostic(&self.sess.span_diagnostic)) } else { let span = span_lo.to(body.span); self.sess.gated_spans.gate(sym::try_blocks, span); diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index ddb5cd06344..45b4079fb54 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -572,7 +572,7 @@ pub(crate) fn report_cycle<'a>( stack_count, }; - cycle_diag.into_diagnostic(&sess.parse_sess) + cycle_diag.into_diagnostic(&sess.parse_sess.span_diagnostic) } pub fn print_query_stack( diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 5b95d73bd4d..9bc7fbfbe14 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -343,7 +343,7 @@ impl ParseSess { &'a self, err: impl SessionDiagnostic<'a>, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { - err.into_diagnostic(self) + err.into_diagnostic(&self.span_diagnostic) } pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed { @@ -354,7 +354,7 @@ impl ParseSess { &'a self, warning: impl SessionDiagnostic<'a, ()>, ) -> DiagnosticBuilder<'a, ()> { - warning.into_diagnostic(self) + warning.into_diagnostic(&self.span_diagnostic) } pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) { @@ -365,7 +365,7 @@ impl ParseSess { &'a self, fatal: impl SessionDiagnostic<'a, !>, ) -> DiagnosticBuilder<'a, !> { - fatal.into_diagnostic(self) + fatal.into_diagnostic(&self.span_diagnostic) } pub fn emit_fatal<'a>(&'a self, fatal: impl SessionDiagnostic<'a, !>) -> ! { diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index a49af23be23..557edad548c 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -21,7 +21,7 @@ use rustc_errors::json::JsonEmitter; use rustc_errors::registry::Registry; use rustc_errors::{ error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, - EmissionGuarantee, ErrorGuaranteed, FluentBundle, LazyFallbackBundle, MultiSpan, + EmissionGuarantee, ErrorGuaranteed, FluentBundle, Handler, LazyFallbackBundle, MultiSpan, }; use rustc_macros::HashStable_Generic; pub use rustc_span::def_id::StableCrateId; @@ -220,9 +220,9 @@ pub struct PerfStats { /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic]. #[rustc_diagnostic_item = "SessionDiagnostic"] pub trait SessionDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> { - /// Write out as a diagnostic out of `sess`. + /// Write out as a diagnostic out of `Handler`. #[must_use] - fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, T>; + fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, T>; } impl Session { diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index 81977f25ca2..ab0afc54514 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -1,7 +1,7 @@ -use rustc_errors::{fluent, ErrorGuaranteed}; +use rustc_errors::{fluent, ErrorGuaranteed, Handler}; use rustc_macros::SessionDiagnostic; use rustc_middle::ty::{PolyTraitRef, Ty, Unevaluated}; -use rustc_session::{parse::ParseSess, Limit, SessionDiagnostic}; +use rustc_session::{Limit, SessionDiagnostic}; use rustc_span::{Span, Symbol}; #[derive(SessionDiagnostic)] @@ -69,9 +69,9 @@ pub struct NegativePositiveConflict<'a> { impl SessionDiagnostic<'_> for NegativePositiveConflict<'_> { fn into_diagnostic( self, - sess: &ParseSess, + handler: &Handler, ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { - let mut diag = sess.struct_err(fluent::trait_selection::negative_positive_conflict); + let mut diag = handler.struct_err(fluent::trait_selection::negative_positive_conflict); diag.set_arg("trait_desc", self.trait_desc); diag.set_arg( "self_desc", diff --git a/compiler/rustc_typeck/src/errors.rs b/compiler/rustc_typeck/src/errors.rs index 14c0558cdde..bfe03d62575 100644 --- a/compiler/rustc_typeck/src/errors.rs +++ b/compiler/rustc_typeck/src/errors.rs @@ -1,8 +1,8 @@ //! Errors emitted by typeck. -use rustc_errors::{error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed}; +use rustc_errors::{error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler}; use rustc_macros::{LintDiagnostic, SessionDiagnostic, SessionSubdiagnostic}; use rustc_middle::ty::Ty; -use rustc_session::{parse::ParseSess, SessionDiagnostic}; +use rustc_session::SessionDiagnostic; use rustc_span::{symbol::Ident, Span, Symbol}; #[derive(SessionDiagnostic)] @@ -250,8 +250,8 @@ pub struct MissingTypeParams { // Manual implementation of `SessionDiagnostic` to be able to call `span_to_snippet`. impl<'a> SessionDiagnostic<'a> for MissingTypeParams { - fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, ErrorGuaranteed> { - let mut err = sess.span_diagnostic.struct_span_err_with_code( + fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { + let mut err = handler.struct_span_err_with_code( self.span, rustc_errors::fluent::typeck::missing_type_params, error_code!(E0393), @@ -269,8 +269,8 @@ impl<'a> SessionDiagnostic<'a> for MissingTypeParams { err.span_label(self.def_span, rustc_errors::fluent::typeck::label); let mut suggested = false; - if let (Ok(snippet), true) = ( - sess.source_map().span_to_snippet(self.span), + if let (Some(Ok(snippet)), true) = ( + handler.span_to_snippet_from_emitter(self.span), // Don't suggest setting the type params if there are some already: the order is // tricky to get right and the user will already know what the syntax is. self.empty_generic_args, diff --git a/src/test/ui-fulldeps/internal-lints/diagnostics.rs b/src/test/ui-fulldeps/internal-lints/diagnostics.rs index 0e449256153..89997585db2 100644 --- a/src/test/ui-fulldeps/internal-lints/diagnostics.rs +++ b/src/test/ui-fulldeps/internal-lints/diagnostics.rs @@ -11,9 +11,9 @@ extern crate rustc_macros; extern crate rustc_session; extern crate rustc_span; -use rustc_errors::{AddSubdiagnostic, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, fluent}; +use rustc_errors::{AddSubdiagnostic, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, fluent}; use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; -use rustc_session::{parse::ParseSess, SessionDiagnostic}; +use rustc_session::SessionDiagnostic; use rustc_span::Span; #[derive(SessionDiagnostic)] @@ -33,8 +33,8 @@ struct Note { pub struct UntranslatableInSessionDiagnostic; impl<'a> SessionDiagnostic<'a, ErrorGuaranteed> for UntranslatableInSessionDiagnostic { - fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, ErrorGuaranteed> { - sess.struct_err("untranslatable diagnostic") + fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { + handler.struct_err("untranslatable diagnostic") //~^ ERROR diagnostics should be created using translatable messages } } @@ -42,8 +42,8 @@ impl<'a> SessionDiagnostic<'a, ErrorGuaranteed> for UntranslatableInSessionDiagn pub struct TranslatableInSessionDiagnostic; impl<'a> SessionDiagnostic<'a, ErrorGuaranteed> for TranslatableInSessionDiagnostic { - fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, ErrorGuaranteed> { - sess.struct_err(fluent::parser::expect_path) + fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { + handler.struct_err(fluent::parser::expect_path) } } @@ -64,11 +64,11 @@ impl AddSubdiagnostic for TranslatableInAddSubdiagnostic { } } -pub fn make_diagnostics<'a>(sess: &'a ParseSess) { - let _diag = sess.struct_err(fluent::parser::expect_path); +pub fn make_diagnostics<'a>(handler: &'a Handler) { + let _diag = handler.struct_err(fluent::parser::expect_path); //~^ ERROR diagnostics should only be created in `SessionDiagnostic`/`AddSubdiagnostic` impls - let _diag = sess.struct_err("untranslatable diagnostic"); + let _diag = handler.struct_err("untranslatable diagnostic"); //~^ ERROR diagnostics should only be created in `SessionDiagnostic`/`AddSubdiagnostic` impls //~^^ ERROR diagnostics should be created using translatable messages } @@ -76,6 +76,6 @@ pub fn make_diagnostics<'a>(sess: &'a ParseSess) { // Check that `rustc_lint_diagnostics`-annotated functions aren't themselves linted. #[rustc_lint_diagnostics] -pub fn skipped_because_of_annotation<'a>(sess: &'a ParseSess) { - let _diag = sess.struct_err("untranslatable diagnostic"); // okay! +pub fn skipped_because_of_annotation<'a>(handler: &'a Handler) { + let _diag = handler.struct_err("untranslatable diagnostic"); // okay! } -- cgit 1.4.1-3-g733a5 From 4856affd90df68b0b56dee73c431e9d9cdfc977a Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Thu, 1 Sep 2022 20:43:12 -0500 Subject: Make `HandleCycleError` an enum instead of a macro-generated closure - Add a `HandleCycleError` enum to rustc_query_system, along with a `handle_cycle_error` function - Move `Value` to rustc_query_system, so `handle_cycle_error` can use it - Move the `Value` impls from rustc_query_impl to rustc_middle. This is necessary due to orphan rules. --- compiler/rustc_middle/src/lib.rs | 1 + compiler/rustc_middle/src/values.rs | 54 +++++++++++++++++++ compiler/rustc_query_impl/src/lib.rs | 3 -- compiler/rustc_query_impl/src/plumbing.rs | 24 ++++----- compiler/rustc_query_impl/src/values.rs | 65 ----------------------- compiler/rustc_query_system/src/error.rs | 7 +++ compiler/rustc_query_system/src/lib.rs | 4 ++ compiler/rustc_query_system/src/query/config.rs | 5 +- compiler/rustc_query_system/src/query/plumbing.rs | 38 +++++++++++-- compiler/rustc_query_system/src/values.rs | 14 +++++ 10 files changed, 129 insertions(+), 86 deletions(-) create mode 100644 compiler/rustc_middle/src/values.rs delete mode 100644 compiler/rustc_query_impl/src/values.rs create mode 100644 compiler/rustc_query_system/src/values.rs (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index be9e5865e54..7edc9a16cc1 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -95,6 +95,7 @@ pub mod mir; pub mod thir; pub mod traits; pub mod ty; +mod values; pub mod util { pub mod bug; diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/values.rs new file mode 100644 index 00000000000..7fbe9ae2a84 --- /dev/null +++ b/compiler/rustc_middle/src/values.rs @@ -0,0 +1,54 @@ +use rustc_middle::ty::{self, AdtSizedConstraint, Ty, TyCtxt}; +use rustc_query_system::Value; + +impl<'tcx> Value> for Ty<'_> { + fn from_cycle_error(tcx: TyCtxt<'tcx>) -> Self { + // SAFETY: This is never called when `Self` is not `Ty<'tcx>`. + // FIXME: Represent the above fact in the trait system somehow. + unsafe { std::mem::transmute::, Ty<'_>>(tcx.ty_error()) } + } +} + +impl<'tcx> Value> for ty::SymbolName<'_> { + fn from_cycle_error(tcx: TyCtxt<'tcx>) -> Self { + // SAFETY: This is never called when `Self` is not `SymbolName<'tcx>`. + // FIXME: Represent the above fact in the trait system somehow. + unsafe { + std::mem::transmute::, ty::SymbolName<'_>>(ty::SymbolName::new( + tcx, "", + )) + } + } +} + +impl<'tcx> Value> for AdtSizedConstraint<'_> { + fn from_cycle_error(tcx: TyCtxt<'tcx>) -> Self { + // SAFETY: This is never called when `Self` is not `AdtSizedConstraint<'tcx>`. + // FIXME: Represent the above fact in the trait system somehow. + unsafe { + std::mem::transmute::, AdtSizedConstraint<'_>>( + AdtSizedConstraint(tcx.intern_type_list(&[tcx.ty_error()])), + ) + } + } +} + +impl<'tcx> Value> for ty::Binder<'_, ty::FnSig<'_>> { + fn from_cycle_error(tcx: TyCtxt<'tcx>) -> Self { + let err = tcx.ty_error(); + // FIXME(compiler-errors): It would be nice if we could get the + // query key, so we could at least generate a fn signature that + // has the right arity. + let fn_sig = ty::Binder::dummy(tcx.mk_fn_sig( + [].into_iter(), + err, + false, + rustc_hir::Unsafety::Normal, + rustc_target::spec::abi::Abi::Rust, + )); + + // SAFETY: This is never called when `Self` is not `ty::Binder<'tcx, ty::FnSig<'tcx>>`. + // FIXME: Represent the above fact in the trait system somehow. + unsafe { std::mem::transmute::, ty::Binder<'_, ty::FnSig<'_>>>(fn_sig) } + } +} diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index 8ea09880694..26d397f70e0 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -34,9 +34,6 @@ pub use rustc_query_system::query::{deadlock, QueryContext}; mod keys; use keys::Key; -mod values; -use self::values::Value; - pub use rustc_query_system::query::QueryConfig; pub(crate) use rustc_query_system::query::{QueryDescription, QueryVTable}; diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 274df5b5e5e..1e375deb20d 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -18,6 +18,7 @@ use rustc_query_system::query::{ force_query, QueryConfig, QueryContext, QueryDescription, QueryJobId, QueryMap, QuerySideEffects, QueryStackFrame, }; +use rustc_query_system::Value; use std::any::Any; use std::num::NonZeroU64; use thin_vec::ThinVec; @@ -174,21 +175,17 @@ impl<'tcx> QueryCtxt<'tcx> { } macro_rules! handle_cycle_error { - ([][$tcx: expr, $error:expr]) => {{ - $error.emit(); - Value::from_cycle_error($tcx) + ([]) => {{ + rustc_query_system::HandleCycleError::Error }}; - ([(fatal_cycle) $($rest:tt)*][$tcx:expr, $error:expr]) => {{ - $error.emit(); - $tcx.sess.abort_if_errors(); - unreachable!() + ([(fatal_cycle) $($rest:tt)*]) => {{ + rustc_query_system::HandleCycleError::Fatal }}; - ([(cycle_delay_bug) $($rest:tt)*][$tcx:expr, $error:expr]) => {{ - $error.delay_as_bug(); - Value::from_cycle_error($tcx) + ([(cycle_delay_bug) $($rest:tt)*]) => {{ + rustc_query_system::HandleCycleError::DelayBug }}; - ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => { - handle_cycle_error!([$($modifiers)*][$($args)*]) + ([$other:tt $($modifiers:tt)*]) => { + handle_cycle_error!([$($modifiers)*]) }; } @@ -320,6 +317,7 @@ fn force_from_dep_node<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> bool where Q: QueryDescription>, Q::Key: DepNodeParams>, + Q::Value: Value>, { if let Some(key) = Q::Key::recover(tcx, &dep_node) { #[cfg(debug_assertions)] @@ -418,7 +416,7 @@ macro_rules! define_queries { depth_limit: depth_limit!([$($modifiers)*]), dep_kind: dep_graph::DepKind::$name, hash_result: hash_result!([$($modifiers)*]), - handle_cycle_error: |tcx, mut error| handle_cycle_error!([$($modifiers)*][tcx, error]), + handle_cycle_error: handle_cycle_error!([$($modifiers)*]), compute, cache_on_disk, try_load_from_disk: Self::TRY_LOAD_FROM_DISK, diff --git a/compiler/rustc_query_impl/src/values.rs b/compiler/rustc_query_impl/src/values.rs deleted file mode 100644 index 0ed48f8d4a0..00000000000 --- a/compiler/rustc_query_impl/src/values.rs +++ /dev/null @@ -1,65 +0,0 @@ -use super::QueryCtxt; -use rustc_middle::ty::{self, AdtSizedConstraint, Ty}; - -pub(super) trait Value<'tcx>: Sized { - fn from_cycle_error(tcx: QueryCtxt<'tcx>) -> Self; -} - -impl<'tcx, T> Value<'tcx> for T { - default fn from_cycle_error(tcx: QueryCtxt<'tcx>) -> T { - tcx.sess.abort_if_errors(); - bug!("Value::from_cycle_error called without errors"); - } -} - -impl<'tcx> Value<'tcx> for Ty<'_> { - fn from_cycle_error(tcx: QueryCtxt<'tcx>) -> Self { - // SAFETY: This is never called when `Self` is not `Ty<'tcx>`. - // FIXME: Represent the above fact in the trait system somehow. - unsafe { std::mem::transmute::, Ty<'_>>(tcx.ty_error()) } - } -} - -impl<'tcx> Value<'tcx> for ty::SymbolName<'_> { - fn from_cycle_error(tcx: QueryCtxt<'tcx>) -> Self { - // SAFETY: This is never called when `Self` is not `SymbolName<'tcx>`. - // FIXME: Represent the above fact in the trait system somehow. - unsafe { - std::mem::transmute::, ty::SymbolName<'_>>(ty::SymbolName::new( - *tcx, "", - )) - } - } -} - -impl<'tcx> Value<'tcx> for AdtSizedConstraint<'_> { - fn from_cycle_error(tcx: QueryCtxt<'tcx>) -> Self { - // SAFETY: This is never called when `Self` is not `AdtSizedConstraint<'tcx>`. - // FIXME: Represent the above fact in the trait system somehow. - unsafe { - std::mem::transmute::, AdtSizedConstraint<'_>>( - AdtSizedConstraint(tcx.intern_type_list(&[tcx.ty_error()])), - ) - } - } -} - -impl<'tcx> Value<'tcx> for ty::Binder<'_, ty::FnSig<'_>> { - fn from_cycle_error(tcx: QueryCtxt<'tcx>) -> Self { - let err = tcx.ty_error(); - // FIXME(compiler-errors): It would be nice if we could get the - // query key, so we could at least generate a fn signature that - // has the right arity. - let fn_sig = ty::Binder::dummy(tcx.mk_fn_sig( - [].into_iter(), - err, - false, - rustc_hir::Unsafety::Normal, - rustc_target::spec::abi::Abi::Rust, - )); - - // SAFETY: This is never called when `Self` is not `ty::Binder<'tcx, ty::FnSig<'tcx>>`. - // FIXME: Represent the above fact in the trait system somehow. - unsafe { std::mem::transmute::, ty::Binder<'_, ty::FnSig<'_>>>(fn_sig) } - } -} diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 5f992ec9e21..3fb06cbedbd 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -12,6 +12,13 @@ impl AddSubdiagnostic for CycleStack { } } +#[derive(Copy, Clone)] +pub enum HandleCycleError { + Error, + Fatal, + DelayBug, +} + #[derive(SessionSubdiagnostic)] pub enum StackCount { #[note(query_system::cycle_stack_single)] diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index 7067bc5f09c..8a88b5c3340 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -20,3 +20,7 @@ pub mod dep_graph; mod error; pub mod ich; pub mod query; +mod values; + +pub use error::HandleCycleError; +pub use values::Value; diff --git a/compiler/rustc_query_system/src/query/config.rs b/compiler/rustc_query_system/src/query/config.rs index ea38df836cb..c63e110a62e 100644 --- a/compiler/rustc_query_system/src/query/config.rs +++ b/compiler/rustc_query_system/src/query/config.rs @@ -2,12 +2,12 @@ use crate::dep_graph::DepNode; use crate::dep_graph::SerializedDepNodeIndex; +use crate::error::HandleCycleError; use crate::ich::StableHashingContext; use crate::query::caches::QueryCache; use crate::query::{QueryContext, QueryState}; use rustc_data_structures::fingerprint::Fingerprint; -use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; use std::fmt::Debug; use std::hash::Hash; @@ -19,6 +19,7 @@ pub trait QueryConfig { type Stored: Clone; } +#[derive(Copy, Clone)] pub struct QueryVTable { pub anon: bool, pub dep_kind: CTX::DepKind, @@ -28,7 +29,7 @@ pub struct QueryVTable { pub compute: fn(CTX::DepContext, K) -> V, pub hash_result: Option, &V) -> Fingerprint>, - pub handle_cycle_error: fn(CTX, DiagnosticBuilder<'_, ErrorGuaranteed>) -> V, + pub handle_cycle_error: HandleCycleError, pub try_load_from_disk: Option Option>, } diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 7bbc22e8293..e39e39860cb 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -7,6 +7,8 @@ use crate::query::caches::QueryCache; use crate::query::config::{QueryDescription, QueryVTable}; use crate::query::job::{report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo}; use crate::query::{QueryContext, QueryMap, QuerySideEffects, QueryStackFrame}; +use crate::values::Value; +use crate::HandleCycleError; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; #[cfg(parallel_compiler)] @@ -118,19 +120,46 @@ where fn mk_cycle( tcx: CTX, error: CycleError, - handle_cycle_error: fn(CTX, DiagnosticBuilder<'_, ErrorGuaranteed>) -> V, + handler: HandleCycleError, cache: &dyn crate::query::QueryStorage, ) -> R where CTX: QueryContext, - V: std::fmt::Debug, + V: std::fmt::Debug + Value, R: Clone, { let error = report_cycle(tcx.dep_context().sess(), error); - let value = handle_cycle_error(tcx, error); + let value = handle_cycle_error(*tcx.dep_context(), error, handler); cache.store_nocache(value) } +fn handle_cycle_error( + tcx: CTX, + mut error: DiagnosticBuilder<'_, ErrorGuaranteed>, + handler: HandleCycleError, +) -> V +where + CTX: DepContext, + V: Value, +{ + use HandleCycleError::*; + match handler { + Error => { + error.emit(); + Value::from_cycle_error(tcx) + } + Fatal => { + error.emit(); + tcx.sess().abort_if_errors(); + unreachable!() + } + DelayBug => { + error.delay_as_bug(); + Value::from_cycle_error(tcx) + } + } +} + impl<'tcx, K> JobOwner<'tcx, K> where K: Eq + Hash + Clone, @@ -336,6 +365,7 @@ fn try_execute_query( where C: QueryCache, C::Key: Clone + DepNodeParams, + C::Value: Value, CTX: QueryContext, { match JobOwner::<'_, C::Key>::try_start(&tcx, state, span, key.clone()) { @@ -686,6 +716,7 @@ pub fn get_query(tcx: CTX, span: Span, key: Q::Key, mode: QueryMode) -> where Q: QueryDescription, Q::Key: DepNodeParams, + Q::Value: Value, CTX: QueryContext, { let query = Q::make_vtable(tcx, &key); @@ -718,6 +749,7 @@ pub fn force_query(tcx: CTX, key: Q::Key, dep_node: DepNode, Q::Key: DepNodeParams, + Q::Value: Value, CTX: QueryContext, { // We may be concurrently trying both execute and force a query. diff --git a/compiler/rustc_query_system/src/values.rs b/compiler/rustc_query_system/src/values.rs new file mode 100644 index 00000000000..aeef66f86da --- /dev/null +++ b/compiler/rustc_query_system/src/values.rs @@ -0,0 +1,14 @@ +use crate::dep_graph::DepContext; + +pub trait Value: Sized { + fn from_cycle_error(tcx: CTX) -> Self; +} + +impl Value for T { + default fn from_cycle_error(tcx: CTX) -> T { + tcx.sess().abort_if_errors(); + // Ideally we would use `bug!` here. But bug! is only defined in rustc_middle, and it's + // non-trivial to define it earlier. + panic!("Value::from_cycle_error called without errors"); + } +} -- cgit 1.4.1-3-g733a5 From 578fc49fc1bbc5498138c84eecad68ee3de54173 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Wed, 7 Sep 2022 14:46:04 -0700 Subject: Use HashStable_Generic in rustc_type_ir A lot of the types in this crate implemented HashStable directly to avoid circular dependencies. One way around that is to use HashStable_Generic. We adopt that here to avoid a lot of boilerplate. This doesn't update all the types, because some would require `I: Interner + HashStable`. --- Cargo.lock | 1 + compiler/rustc_query_system/Cargo.toml | 1 + .../rustc_query_system/src/ich/impls_syntax.rs | 2 + compiler/rustc_type_ir/src/lib.rs | 49 ++++------------------ compiler/rustc_type_ir/src/sty.rs | 6 +-- 5 files changed, 16 insertions(+), 43 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/Cargo.lock b/Cargo.lock index 68ea8b51c55..90bcc2e4be4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3958,6 +3958,7 @@ dependencies = [ "rustc_session", "rustc_span", "rustc_target", + "rustc_type_ir", "smallvec", "thin-vec", "tracing", diff --git a/compiler/rustc_query_system/Cargo.toml b/compiler/rustc_query_system/Cargo.toml index bafc6b0a082..d7599a56c0b 100644 --- a/compiler/rustc_query_system/Cargo.toml +++ b/compiler/rustc_query_system/Cargo.toml @@ -21,6 +21,7 @@ rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } +rustc_type_ir = { path = "../rustc_type_ir" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } thin-vec = "0.2.8" tracing = "0.1" diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index d7732cb1825..0bc811eb044 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -148,3 +148,5 @@ impl<'tcx> HashStable> for rustc_feature::Features { }); } } + +impl<'ctx> rustc_type_ir::HashStableContext for StableHashingContext<'ctx> {} diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 5488bca8f47..da30344ef7e 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -23,6 +23,9 @@ pub mod sty; pub use codec::*; pub use sty::*; +/// Needed so we can use #[derive(HashStable_Generic)] +pub trait HashStableContext {} + pub trait Interner { type AdtDef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; type SubstsRef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; @@ -295,6 +298,7 @@ rustc_index::newtype_index! { /// is the outer fn. /// /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index + #[derive(HashStable_Generic)] pub struct DebruijnIndex { DEBUG_FORMAT = "DebruijnIndex({})", const INNERMOST = 0, @@ -366,7 +370,7 @@ impl DebruijnIndex { } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[derive(Encodable, Decodable)] +#[derive(Encodable, Decodable, HashStable_Generic)] pub enum IntTy { Isize, I8, @@ -413,7 +417,7 @@ impl IntTy { } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)] -#[derive(Encodable, Decodable)] +#[derive(Encodable, Decodable, HashStable_Generic)] pub enum UintTy { Usize, U8, @@ -460,7 +464,7 @@ impl UintTy { } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[derive(Encodable, Decodable)] +#[derive(Encodable, Decodable, HashStable_Generic)] pub enum FloatTy { F32, F64, @@ -597,7 +601,7 @@ impl UnifyKey for FloatVid { } } -#[derive(Copy, Clone, PartialEq, Decodable, Encodable, Hash)] +#[derive(Copy, Clone, PartialEq, Decodable, Encodable, Hash, HashStable_Generic)] #[rustc_pass_by_value] pub enum Variance { Covariant, // T <: T iff A <: B -- e.g., function return type @@ -666,30 +670,6 @@ impl Variance { } } -impl HashStable for DebruijnIndex { - fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { - self.as_u32().hash_stable(ctx, hasher); - } -} - -impl HashStable for IntTy { - fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { - discriminant(self).hash_stable(ctx, hasher); - } -} - -impl HashStable for UintTy { - fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { - discriminant(self).hash_stable(ctx, hasher); - } -} - -impl HashStable for FloatTy { - fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { - discriminant(self).hash_stable(ctx, hasher); - } -} - impl HashStable for InferTy { fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { use InferTy::*; @@ -703,12 +683,6 @@ impl HashStable for InferTy { } } -impl HashStable for Variance { - fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { - discriminant(self).hash_stable(ctx, hasher); - } -} - impl fmt::Debug for IntVarValue { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { @@ -811,6 +785,7 @@ rustc_index::newtype_index! { /// declared, but a type name in a non-zero universe is a placeholder /// type -- an idealized representative of "types in general" that we /// use for checking generic functions. + #[derive(HashStable_Generic)] pub struct UniverseIndex { DEBUG_FORMAT = "U{}", } @@ -850,9 +825,3 @@ impl UniverseIndex { self.private < other.private } } - -impl HashStable for UniverseIndex { - fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { - self.private.hash_stable(ctx, hasher); - } -} diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index 74737e30bb4..26e48d2d214 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -3,7 +3,6 @@ use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use std::{fmt, hash}; -use crate::DebruijnIndex; use crate::FloatTy; use crate::IntTy; use crate::Interner; @@ -11,6 +10,7 @@ use crate::TyDecoder; use crate::TyEncoder; use crate::UintTy; use crate::UniverseIndex; +use crate::{DebruijnIndex, HashStableContext}; use self::RegionKind::*; use self::TyKind::*; @@ -774,7 +774,7 @@ where // This is not a derived impl because a derive would require `I: HashStable` #[allow(rustc::usage_of_ty_tykind)] -impl HashStable for TyKind +impl HashStable for TyKind where I::AdtDef: HashStable, I::DefId: HashStable, @@ -1286,7 +1286,7 @@ where } // This is not a derived impl because a derive would require `I: HashStable` -impl HashStable for RegionKind +impl HashStable for RegionKind where I::EarlyBoundRegion: HashStable, I::BoundRegion: HashStable, -- cgit 1.4.1-3-g733a5 From 7208bdee33460b9915e6b389b236d231d2ca3ffc Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Thu, 1 Sep 2022 22:26:03 -0500 Subject: Remove `cache_on_disk` from `QueryVTable` This is not only simpler, but removes a generic function and unwrap. I have hope it will see compile time and bootstrap time improvements. --- compiler/rustc_query_impl/src/plumbing.rs | 3 +-- compiler/rustc_query_system/src/query/config.rs | 10 ++-------- compiler/rustc_query_system/src/query/plumbing.rs | 6 +++--- 3 files changed, 6 insertions(+), 13 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 48539d580c7..4ff3917e113 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -442,8 +442,7 @@ macro_rules! define_queries { hash_result: hash_result!([$($modifiers)*]), handle_cycle_error: handle_cycle_error!([$($modifiers)*]), compute, - cache_on_disk, - try_load_from_disk: Self::TRY_LOAD_FROM_DISK, + try_load_from_disk: if cache_on_disk { Self::TRY_LOAD_FROM_DISK } else { None }, } } diff --git a/compiler/rustc_query_system/src/query/config.rs b/compiler/rustc_query_system/src/query/config.rs index c63e110a62e..340deb88915 100644 --- a/compiler/rustc_query_system/src/query/config.rs +++ b/compiler/rustc_query_system/src/query/config.rs @@ -25,11 +25,12 @@ pub struct QueryVTable { pub dep_kind: CTX::DepKind, pub eval_always: bool, pub depth_limit: bool, - pub cache_on_disk: bool, pub compute: fn(CTX::DepContext, K) -> V, pub hash_result: Option, &V) -> Fingerprint>, pub handle_cycle_error: HandleCycleError, + // NOTE: this is not quite the same as `Q::TRY_LOAD_FROM_DISK`; it can also be `None` if + // `cache_on_disk` returned false for this key. pub try_load_from_disk: Option Option>, } @@ -44,13 +45,6 @@ impl QueryVTable { pub(crate) fn compute(&self, tcx: CTX::DepContext, key: K) -> V { (self.compute)(tcx, key) } - - pub(crate) fn try_load_from_disk(&self, tcx: CTX, index: SerializedDepNodeIndex) -> Option { - self.try_load_from_disk - .expect("QueryDescription::load_from_disk() called for an unsupported query.")( - tcx, index, - ) - } } pub trait QueryDescription: QueryConfig { diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index e39e39860cb..8179a674afa 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -488,14 +488,14 @@ where // First we try to load the result from the on-disk cache. // Some things are never cached on disk. - if query.cache_on_disk { + if let Some(try_load_from_disk) = query.try_load_from_disk { let prof_timer = tcx.dep_context().profiler().incr_cache_loading(); // The call to `with_query_deserialization` enforces that no new `DepNodes` // are created during deserialization. See the docs of that method for more // details. - let result = dep_graph - .with_query_deserialization(|| query.try_load_from_disk(tcx, prev_dep_node_index)); + let result = + dep_graph.with_query_deserialization(|| try_load_from_disk(tcx, prev_dep_node_index)); prof_timer.finish_with_query_invocation_id(dep_node_index.into()); -- cgit 1.4.1-3-g733a5 From 0a9d7dbca23bb05fab13c1dc75a87cdb2bf69ff5 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Tue, 6 Sep 2022 19:09:32 -0500 Subject: Remove unnecessary `TRY_LOAD_FROM_DISK` constant --- compiler/rustc_query_impl/src/lib.rs | 1 - compiler/rustc_query_impl/src/plumbing.rs | 5 +---- compiler/rustc_query_system/src/query/config.rs | 5 +---- 3 files changed, 2 insertions(+), 9 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index 8148f8e017c..c87d26b3950 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -34,7 +34,6 @@ pub use rustc_query_system::query::{deadlock, QueryContext}; mod keys; use keys::Key; -use rustc_query_system::dep_graph::SerializedDepNodeIndex; pub use rustc_query_system::query::QueryConfig; pub(crate) use rustc_query_system::query::{QueryDescription, QueryVTable}; diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index e38de2a0e40..6e0649cc471 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -412,9 +412,6 @@ macro_rules! define_queries { impl<'tcx> QueryDescription> for queries::$name<'tcx> { rustc_query_description! { $name } - const TRY_LOAD_FROM_DISK: Option, SerializedDepNodeIndex) -> Option> - = should_ever_cache_on_disk!([$($modifiers)*]); - type Cache = query_storage::$name<'tcx>; #[inline(always)] @@ -445,7 +442,7 @@ macro_rules! define_queries { hash_result: hash_result!([$($modifiers)*]), handle_cycle_error: handle_cycle_error!([$($modifiers)*]), compute, - try_load_from_disk: if cache_on_disk { Self::TRY_LOAD_FROM_DISK } else { None }, + try_load_from_disk: if cache_on_disk { should_ever_cache_on_disk!([$($modifiers)*]) } else { None }, } } diff --git a/compiler/rustc_query_system/src/query/config.rs b/compiler/rustc_query_system/src/query/config.rs index 340deb88915..c4549cc9eb4 100644 --- a/compiler/rustc_query_system/src/query/config.rs +++ b/compiler/rustc_query_system/src/query/config.rs @@ -29,8 +29,7 @@ pub struct QueryVTable { pub compute: fn(CTX::DepContext, K) -> V, pub hash_result: Option, &V) -> Fingerprint>, pub handle_cycle_error: HandleCycleError, - // NOTE: this is not quite the same as `Q::TRY_LOAD_FROM_DISK`; it can also be `None` if - // `cache_on_disk` returned false for this key. + // NOTE: this is also `None` if `cache_on_disk()` returns false, not just if it's unsupported by the query pub try_load_from_disk: Option Option>, } @@ -48,8 +47,6 @@ impl QueryVTable { } pub trait QueryDescription: QueryConfig { - const TRY_LOAD_FROM_DISK: Option Option>; - type Cache: QueryCache; fn describe(tcx: CTX, key: Self::Key) -> String; -- cgit 1.4.1-3-g733a5 From bd45139cb014d51adaff46b9797504bc6eac2564 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 9 Sep 2022 12:05:01 +0200 Subject: Allow query system to recover a HirId. --- compiler/rustc_middle/src/dep_graph/dep_node.rs | 38 ++++++++++++++++++++---- compiler/rustc_query_system/src/dep_graph/mod.rs | 6 +++- 2 files changed, 37 insertions(+), 7 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 7718906ac4e..aae12705e3d 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -62,7 +62,7 @@ use crate::ty::TyCtxt; use rustc_data_structures::fingerprint::Fingerprint; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_hir::definitions::DefPathHash; -use rustc_hir::HirId; +use rustc_hir::{HirId, ItemLocalId}; use rustc_query_system::dep_graph::FingerprintStyle; use rustc_span::symbol::Symbol; use std::hash::Hash; @@ -289,7 +289,7 @@ impl DepNodeExt for DepNode { let kind = dep_kind_from_label_string(label)?; match kind.fingerprint_style(tcx) { - FingerprintStyle::Opaque => Err(()), + FingerprintStyle::Opaque | FingerprintStyle::HirId => Err(()), FingerprintStyle::Unit => Ok(DepNode::new_no_params(tcx, kind)), FingerprintStyle::DefPathHash => { Ok(DepNode::from_def_path_hash(tcx, def_path_hash, kind)) @@ -417,7 +417,7 @@ impl<'tcx> DepNodeParams> for (DefId, DefId) { impl<'tcx> DepNodeParams> for HirId { #[inline(always)] fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::Opaque + FingerprintStyle::HirId } // We actually would not need to specialize the implementation of this @@ -426,10 +426,36 @@ impl<'tcx> DepNodeParams> for HirId { #[inline(always)] fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { let HirId { owner, local_id } = *self; - let def_path_hash = tcx.def_path_hash(owner.to_def_id()); - let local_id = Fingerprint::from_smaller_hash(local_id.as_u32().into()); + Fingerprint::new( + // `owner` is local, so is completely defined by the local hash + def_path_hash.local_hash(), + local_id.as_u32().into(), + ) + } - def_path_hash.0.combine(local_id) + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + let HirId { owner, local_id } = *self; + format!("{}.{}", tcx.def_path_str(owner.to_def_id()), local_id.as_u32()) + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + if dep_node.kind.fingerprint_style(tcx) == FingerprintStyle::HirId { + let (local_hash, local_id) = Fingerprint::from(dep_node.hash).as_value(); + let def_path_hash = DefPathHash::new(tcx.sess.local_stable_crate_id(), local_hash); + let owner = tcx + .def_path_hash_to_def_id(def_path_hash, &mut || { + panic!("Failed to extract HirId: {:?} {}", dep_node.kind, dep_node.hash) + }) + .expect_local(); + let local_id = local_id + .try_into() + .unwrap_or_else(|_| panic!("local id should be u32, found {:?}", local_id)); + Some(HirId { owner, local_id: ItemLocalId::from_u32(local_id) }) + } else { + None + } } } diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index 342d95ca490..6f3bd776216 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -67,6 +67,8 @@ impl HasDepContext for T { pub enum FingerprintStyle { /// The fingerprint is actually a DefPathHash. DefPathHash, + /// The fingerprint is actually a HirId. + HirId, /// Query key was `()` or equivalent, so fingerprint is just zero. Unit, /// Some opaque hash. @@ -77,7 +79,9 @@ impl FingerprintStyle { #[inline] pub fn reconstructible(self) -> bool { match self { - FingerprintStyle::DefPathHash | FingerprintStyle::Unit => true, + FingerprintStyle::DefPathHash | FingerprintStyle::Unit | FingerprintStyle::HirId => { + true + } FingerprintStyle::Opaque => false, } } -- cgit 1.4.1-3-g733a5 From 44506f38e079caec1b6c14e05a9b86e19544757f Mon Sep 17 00:00:00 2001 From: SparrowLii Date: Wed, 14 Sep 2022 21:00:00 +0800 Subject: add note for `layout_of` when query depth overflows --- .../locales/en-US/query_system.ftl | 2 ++ compiler/rustc_query_impl/src/plumbing.rs | 2 +- compiler/rustc_query_system/src/error.rs | 14 ++++++++++++- compiler/rustc_query_system/src/query/job.rs | 24 +++++++++++++++++++++- compiler/rustc_query_system/src/query/mod.rs | 15 ++++++++++++-- 5 files changed, 52 insertions(+), 5 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_error_messages/locales/en-US/query_system.ftl b/compiler/rustc_error_messages/locales/en-US/query_system.ftl index 167704e46c0..050a41fc7f9 100644 --- a/compiler/rustc_error_messages/locales/en-US/query_system.ftl +++ b/compiler/rustc_error_messages/locales/en-US/query_system.ftl @@ -23,3 +23,5 @@ query_system_cycle_recursive_trait_alias = trait aliases cannot be recursive query_system_cycle_which_requires = ...which requires {$desc}... query_system_query_overflow = queries overflow the depth limit! + +query_system_layout_of_depth = Query depth increased by {$depth} when {$desc}! diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 6fb3c69b1f4..3ca657cbca1 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -109,7 +109,7 @@ impl QueryContext for QueryCtxt<'_> { // when accessing the `ImplicitCtxt`. tls::with_related_context(**self, move |current_icx| { if depth_limit && !self.recursion_limit().value_within_limit(current_icx.query_depth) { - self.depth_limit_error(); + self.depth_limit_error(token); } // Update the `ImplicitCtxt` to point to our new query job. diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 3fb06cbedbd..5f57a1510aa 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -77,4 +77,16 @@ pub struct IncrementCompilation { #[derive(SessionDiagnostic)] #[diag(query_system::query_overflow)] -pub struct QueryOverflow; +pub struct QueryOverflow { + #[subdiagnostic] + pub layout_of_depth: Option, +} + +#[derive(SessionSubdiagnostic)] +#[note(query_system::layout_of_depth)] +pub struct LayoutOfDepth { + #[primary_span] + pub span: Span, + pub desc: String, + pub depth: usize, +} diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 45b4079fb54..a5ea3a098a6 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -59,6 +59,7 @@ impl QueryJobId { } } +#[derive(Clone)] pub struct QueryJobInfo { pub query: QueryStackFrame, pub job: QueryJob, @@ -116,10 +117,10 @@ impl QueryJob { } } -#[cfg(not(parallel_compiler))] impl QueryJobId { #[cold] #[inline(never)] + #[cfg(not(parallel_compiler))] pub(super) fn find_cycle_in_stack( &self, query_map: QueryMap, @@ -156,6 +157,27 @@ impl QueryJobId { panic!("did not find a cycle") } + + #[cold] + #[inline(never)] + pub(super) fn try_find_layout_root( + &self, + query_map: QueryMap, + ) -> Option<(QueryJobInfo, usize)> { + let mut last_layout = None; + let mut current_id = Some(*self); + let mut depth = 0; + + while let Some(id) = current_id { + let info = query_map.get(&id).unwrap(); + if info.query.name == "layout_of" { + depth += 1; + last_layout = Some((info.clone(), depth)); + } + current_id = info.job.parent; + } + last_layout + } } #[cfg(parallel_compiler)] diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index 0b07bb64b6a..e29e8815331 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -123,7 +123,18 @@ pub trait QueryContext: HasDepContext { compute: impl FnOnce() -> R, ) -> R; - fn depth_limit_error(&self) { - self.dep_context().sess().emit_fatal(crate::error::QueryOverflow); + fn depth_limit_error(&self, job: QueryJobId) { + let sess = self.dep_context().sess(); + let mut layout_of_depth = None; + if let Some(map) = self.try_collect_active_jobs() { + if let Some((info, depth)) = job.try_find_layout_root(map) { + layout_of_depth = Some(crate::error::LayoutOfDepth { + span: info.job.span, + desc: info.query.description, + depth, + }); + } + } + sess.emit_fatal(crate::error::QueryOverflow { layout_of_depth }); } } -- cgit 1.4.1-3-g733a5 From 89fd6ae458c96f7c3be00d93861ed3f0aa53d95b Mon Sep 17 00:00:00 2001 From: SparrowLii Date: Thu, 15 Sep 2022 15:45:17 +0800 Subject: correct span, add help message and add UI test when query depth overflows --- .../locales/en-US/query_system.ftl | 3 ++- compiler/rustc_query_impl/src/plumbing.rs | 27 ++++++++++++++++++- compiler/rustc_query_system/src/error.rs | 10 ++++--- compiler/rustc_query_system/src/lib.rs | 2 ++ compiler/rustc_query_system/src/query/job.rs | 5 +--- compiler/rustc_query_system/src/query/mod.rs | 17 ++---------- src/test/ui/query-system/query_depth.rs | 31 ++++++++++++++++++++++ src/test/ui/query-system/query_depth.stderr | 11 ++++++++ 8 files changed, 82 insertions(+), 24 deletions(-) create mode 100644 src/test/ui/query-system/query_depth.rs create mode 100644 src/test/ui/query-system/query_depth.stderr (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_error_messages/locales/en-US/query_system.ftl b/compiler/rustc_error_messages/locales/en-US/query_system.ftl index 050a41fc7f9..b914ba52a73 100644 --- a/compiler/rustc_error_messages/locales/en-US/query_system.ftl +++ b/compiler/rustc_error_messages/locales/en-US/query_system.ftl @@ -23,5 +23,6 @@ query_system_cycle_recursive_trait_alias = trait aliases cannot be recursive query_system_cycle_which_requires = ...which requires {$desc}... query_system_query_overflow = queries overflow the depth limit! + .help = consider increasing the recursion limit by adding a `#![recursion_limit = "{$suggested_limit}"]` attribute to your crate (`{$crate_name}`) -query_system_layout_of_depth = Query depth increased by {$depth} when {$desc}! +query_system_layout_of_depth = query depth increased by {$depth} when {$desc} diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 3ca657cbca1..b9edb757b56 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -19,8 +19,10 @@ use rustc_query_system::query::{ force_query, QueryConfig, QueryContext, QueryDescription, QueryJobId, QueryMap, QuerySideEffects, QueryStackFrame, }; -use rustc_query_system::Value; +use rustc_query_system::{LayoutOfDepth, QueryOverflow, Value}; use rustc_serialize::Decodable; +use rustc_session::Limit; +use rustc_span::def_id::LOCAL_CRATE; use std::any::Any; use std::num::NonZeroU64; use thin_vec::ThinVec; @@ -127,6 +129,29 @@ impl QueryContext for QueryCtxt<'_> { }) }) } + + fn depth_limit_error(&self, job: QueryJobId) { + let mut span = None; + let mut layout_of_depth = None; + if let Some(map) = self.try_collect_active_jobs() { + if let Some((info, depth)) = job.try_find_layout_root(map) { + span = Some(info.job.span); + layout_of_depth = Some(LayoutOfDepth { desc: info.query.description, depth }); + } + } + + let suggested_limit = match self.recursion_limit() { + Limit(0) => Limit(2), + limit => limit * 2, + }; + + self.sess.emit_fatal(QueryOverflow { + span, + layout_of_depth, + suggested_limit, + crate_name: self.crate_name(LOCAL_CRATE), + }); + } } impl<'tcx> QueryCtxt<'tcx> { diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 5f57a1510aa..bececca7585 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -1,5 +1,6 @@ use rustc_errors::AddSubdiagnostic; -use rustc_span::Span; +use rustc_session::Limit; +use rustc_span::{Span, Symbol}; pub struct CycleStack { pub span: Span, @@ -76,17 +77,20 @@ pub struct IncrementCompilation { } #[derive(SessionDiagnostic)] +#[help] #[diag(query_system::query_overflow)] pub struct QueryOverflow { + #[primary_span] + pub span: Option, #[subdiagnostic] pub layout_of_depth: Option, + pub suggested_limit: Limit, + pub crate_name: Symbol, } #[derive(SessionSubdiagnostic)] #[note(query_system::layout_of_depth)] pub struct LayoutOfDepth { - #[primary_span] - pub span: Span, pub desc: String, pub depth: usize, } diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index 8a88b5c3340..78b06f520a8 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -23,4 +23,6 @@ pub mod query; mod values; pub use error::HandleCycleError; +pub use error::LayoutOfDepth; +pub use error::QueryOverflow; pub use values::Value; diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index a5ea3a098a6..95305eabd0d 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -160,10 +160,7 @@ impl QueryJobId { #[cold] #[inline(never)] - pub(super) fn try_find_layout_root( - &self, - query_map: QueryMap, - ) -> Option<(QueryJobInfo, usize)> { + pub fn try_find_layout_root(&self, query_map: QueryMap) -> Option<(QueryJobInfo, usize)> { let mut last_layout = None; let mut current_id = Some(*self); let mut depth = 0; diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index e29e8815331..7a96c53b604 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -14,7 +14,7 @@ pub use self::caches::{ mod config; pub use self::config::{QueryConfig, QueryDescription, QueryVTable}; -use crate::dep_graph::{DepContext, DepNodeIndex, HasDepContext, SerializedDepNodeIndex}; +use crate::dep_graph::{DepNodeIndex, HasDepContext, SerializedDepNodeIndex}; use rustc_data_structures::sync::Lock; use rustc_errors::Diagnostic; use rustc_hir::def::DefKind; @@ -123,18 +123,5 @@ pub trait QueryContext: HasDepContext { compute: impl FnOnce() -> R, ) -> R; - fn depth_limit_error(&self, job: QueryJobId) { - let sess = self.dep_context().sess(); - let mut layout_of_depth = None; - if let Some(map) = self.try_collect_active_jobs() { - if let Some((info, depth)) = job.try_find_layout_root(map) { - layout_of_depth = Some(crate::error::LayoutOfDepth { - span: info.job.span, - desc: info.query.description, - depth, - }); - } - } - sess.emit_fatal(crate::error::QueryOverflow { layout_of_depth }); - } + fn depth_limit_error(&self, job: QueryJobId); } diff --git a/src/test/ui/query-system/query_depth.rs b/src/test/ui/query-system/query_depth.rs new file mode 100644 index 00000000000..e600c1c08e5 --- /dev/null +++ b/src/test/ui/query-system/query_depth.rs @@ -0,0 +1,31 @@ +// build-fail + +#![recursion_limit = "64"] +type Byte = Option + >>>> >>>> + >>>> >>>> + >>>> >>>> + >>>> >>>> + >>>> >>>> + >>>> >>>> + >>>> >>>> + >>>> >>>> + >>>> >>>> + >>>> >>>> +>>>> >>>>; + +fn main() { +//~^ ERROR: queries overflow the depth limit! + println!("{}", std::mem::size_of::()); +} diff --git a/src/test/ui/query-system/query_depth.stderr b/src/test/ui/query-system/query_depth.stderr new file mode 100644 index 00000000000..43a18b4e074 --- /dev/null +++ b/src/test/ui/query-system/query_depth.stderr @@ -0,0 +1,11 @@ +error: queries overflow the depth limit! + --> $DIR/query_depth.rs:28:1 + | +LL | fn main() { + | ^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "128"]` attribute to your crate (`query_depth`) + = note: query depth increased by 66 when computing layout of `core::option::Option>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>` + +error: aborting due to previous error + -- cgit 1.4.1-3-g733a5 From 173eb6f407438dff732b1636b5134ff220da3f5b Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 27 Feb 2022 07:07:36 +0100 Subject: Only enable the let_else feature on bootstrap On later stages, the feature is already stable. Result of running: rg -l "feature.let_else" compiler/ src/librustdoc/ library/ | xargs sed -s -i "s#\\[feature.let_else#\\[cfg_attr\\(bootstrap, feature\\(let_else\\)#" --- compiler/rustc_ast/src/lib.rs | 2 +- compiler/rustc_ast_lowering/src/lib.rs | 2 +- compiler/rustc_ast_passes/src/lib.rs | 2 +- compiler/rustc_attr/src/lib.rs | 2 +- compiler/rustc_borrowck/src/lib.rs | 2 +- compiler/rustc_builtin_macros/src/lib.rs | 2 +- compiler/rustc_codegen_llvm/src/lib.rs | 2 +- compiler/rustc_codegen_ssa/src/lib.rs | 2 +- compiler/rustc_const_eval/src/lib.rs | 2 +- compiler/rustc_data_structures/src/lib.rs | 2 +- compiler/rustc_driver/src/lib.rs | 2 +- compiler/rustc_errors/src/lib.rs | 2 +- compiler/rustc_expand/src/lib.rs | 2 +- compiler/rustc_hir/src/lib.rs | 2 +- compiler/rustc_incremental/src/lib.rs | 2 +- compiler/rustc_index/src/lib.rs | 2 +- compiler/rustc_infer/src/lib.rs | 2 +- compiler/rustc_interface/src/lib.rs | 2 +- compiler/rustc_lint/src/lib.rs | 2 +- compiler/rustc_macros/src/lib.rs | 2 +- compiler/rustc_metadata/src/lib.rs | 2 +- compiler/rustc_middle/src/lib.rs | 2 +- compiler/rustc_mir_build/src/lib.rs | 2 +- compiler/rustc_mir_dataflow/src/lib.rs | 2 +- compiler/rustc_mir_transform/src/lib.rs | 2 +- compiler/rustc_monomorphize/src/lib.rs | 2 +- compiler/rustc_parse/src/lib.rs | 2 +- compiler/rustc_passes/src/lib.rs | 2 +- compiler/rustc_privacy/src/lib.rs | 2 +- compiler/rustc_query_system/src/lib.rs | 2 +- compiler/rustc_resolve/src/lib.rs | 2 +- compiler/rustc_save_analysis/src/lib.rs | 2 +- compiler/rustc_serialize/src/lib.rs | 2 +- compiler/rustc_session/src/lib.rs | 2 +- compiler/rustc_span/src/lib.rs | 2 +- compiler/rustc_target/src/lib.rs | 2 +- compiler/rustc_trait_selection/src/lib.rs | 2 +- compiler/rustc_traits/src/lib.rs | 2 +- compiler/rustc_ty_utils/src/lib.rs | 2 +- compiler/rustc_typeck/src/lib.rs | 2 +- library/alloc/src/lib.rs | 2 +- library/std/src/lib.rs | 2 +- src/librustdoc/lib.rs | 2 +- 43 files changed, 43 insertions(+), 43 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index 4d3620ee8b0..bd7a85b07a0 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -15,7 +15,7 @@ #![feature(if_let_guard)] #![cfg_attr(bootstrap, feature(label_break_value))] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(negative_impls)] #![feature(slice_internals)] diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 409ee55268c..9ac09b5c8b3 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -32,7 +32,7 @@ #![feature(box_patterns)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_ast_passes/src/lib.rs b/compiler/rustc_ast_passes/src/lib.rs index af25982e288..8aa9d57f046 100644 --- a/compiler/rustc_ast_passes/src/lib.rs +++ b/compiler/rustc_ast_passes/src/lib.rs @@ -9,7 +9,7 @@ #![feature(if_let_guard)] #![feature(iter_is_partitioned)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #[macro_use] diff --git a/compiler/rustc_attr/src/lib.rs b/compiler/rustc_attr/src/lib.rs index 053f848aacb..52e65a9c774 100644 --- a/compiler/rustc_attr/src/lib.rs +++ b/compiler/rustc_attr/src/lib.rs @@ -5,7 +5,7 @@ //! to this crate. #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index ec652f85217..86da87d0603 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -3,7 +3,7 @@ #![allow(rustc::potential_query_instability)] #![feature(box_patterns)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(rustc_attrs)] diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs index 280fa704511..8aeb3b82a9c 100644 --- a/compiler/rustc_builtin_macros/src/lib.rs +++ b/compiler/rustc_builtin_macros/src/lib.rs @@ -9,7 +9,7 @@ #![feature(if_let_guard)] #![feature(is_sorted)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(proc_macro_internals)] #![feature(proc_macro_quote)] #![recursion_limit = "256"] diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 334425ae55b..42c65e04e3b 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -7,7 +7,7 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(hash_raw_entry)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(extern_types)] #![feature(once_cell)] #![feature(iter_intersperse)] diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs index 4ea75dba471..e736b2aba9c 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -1,7 +1,7 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(box_patterns)] #![feature(try_blocks)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(associated_type_bounds)] #![feature(strict_provenance)] diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index 72ac6af685d..9f47d302a0c 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -10,7 +10,7 @@ Rust MIR: a lowered representation of Rust. #![feature(decl_macro)] #![feature(exact_size_is_empty)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(map_try_insert)] #![feature(min_specialization)] #![feature(slice_ptr_get)] diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index a7429ed008f..56f7823efe0 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -13,7 +13,7 @@ #![feature(cell_leak)] #![feature(control_flow_enum)] #![feature(extend_one)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(hash_raw_entry)] #![feature(hasher_prefixfree_extras)] #![feature(maybe_uninit_uninit_array)] diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index d6f51d7eee1..8fb9508194b 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -5,7 +5,7 @@ //! This API is completely unstable and subject to change. #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 1b24f07e689..c3e78209612 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -7,7 +7,7 @@ #![feature(if_let_guard)] #![feature(adt_const_params)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![feature(result_option_inspect)] #![feature(rustc_attrs)] diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index ac0e200b1b7..ffc9abe64d2 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -3,7 +3,7 @@ #![feature(associated_type_defaults)] #![feature(if_let_guard)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(macro_metavar_expr)] #![feature(proc_macro_diagnostic)] #![feature(proc_macro_internals)] diff --git a/compiler/rustc_hir/src/lib.rs b/compiler/rustc_hir/src/lib.rs index 1b33cb9c2da..946da9265ba 100644 --- a/compiler/rustc_hir/src/lib.rs +++ b/compiler/rustc_hir/src/lib.rs @@ -5,7 +5,7 @@ #![feature(associated_type_defaults)] #![feature(closure_track_caller)] #![feature(const_btree_new)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(min_specialization)] #![feature(never_type)] diff --git a/compiler/rustc_incremental/src/lib.rs b/compiler/rustc_incremental/src/lib.rs index 1e88e8091c3..2c9e21f769f 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -2,7 +2,7 @@ #![deny(missing_docs)] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_index/src/lib.rs b/compiler/rustc_index/src/lib.rs index aa34673de81..a00d7bd6801 100644 --- a/compiler/rustc_index/src/lib.rs +++ b/compiler/rustc_index/src/lib.rs @@ -3,7 +3,7 @@ #![feature(allow_internal_unstable)] #![feature(bench_black_box)] #![feature(extend_one)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(new_uninit)] #![feature(step_trait)] diff --git a/compiler/rustc_infer/src/lib.rs b/compiler/rustc_infer/src/lib.rs index 931ebca7d01..ef60d2c9188 100644 --- a/compiler/rustc_infer/src/lib.rs +++ b/compiler/rustc_infer/src/lib.rs @@ -19,7 +19,7 @@ #![feature(extend_one)] #![cfg_attr(bootstrap, feature(label_break_value))] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(try_blocks)] diff --git a/compiler/rustc_interface/src/lib.rs b/compiler/rustc_interface/src/lib.rs index 1a8d619fafb..41cd7b0e9b1 100644 --- a/compiler/rustc_interface/src/lib.rs +++ b/compiler/rustc_interface/src/lib.rs @@ -1,5 +1,5 @@ #![feature(box_patterns)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(internal_output_capture)] #![feature(thread_spawn_unchecked)] #![feature(once_cell)] diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 2a22a6e5be1..c760e435699 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -34,7 +34,7 @@ #![feature(iter_intersperse)] #![feature(iter_order_by)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![recursion_limit = "256"] diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 20ee5dfc727..2c027d754da 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -1,5 +1,5 @@ #![feature(allow_internal_unstable)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![feature(proc_macro_diagnostic)] #![feature(proc_macro_span)] diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs index ba6f1e4a3a5..6f5604b7e11 100644 --- a/compiler/rustc_metadata/src/lib.rs +++ b/compiler/rustc_metadata/src/lib.rs @@ -5,7 +5,7 @@ #![cfg_attr(bootstrap, feature(generic_associated_types))] #![feature(iter_from_generator)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(proc_macro_internals)] #![feature(macro_metavar_expr)] diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index ea08879cb53..01b9277b983 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -40,7 +40,7 @@ #![feature(new_uninit)] #![feature(once_cell)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(trusted_len)] #![feature(type_alias_impl_trait)] diff --git a/compiler/rustc_mir_build/src/lib.rs b/compiler/rustc_mir_build/src/lib.rs index 11cd2a9aa4d..0c0a2fe9c9e 100644 --- a/compiler/rustc_mir_build/src/lib.rs +++ b/compiler/rustc_mir_build/src/lib.rs @@ -6,7 +6,7 @@ #![feature(control_flow_enum)] #![feature(if_let_guard)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(once_cell)] #![recursion_limit = "256"] diff --git a/compiler/rustc_mir_dataflow/src/lib.rs b/compiler/rustc_mir_dataflow/src/lib.rs index 62b712f7b8d..b45c32ee986 100644 --- a/compiler/rustc_mir_dataflow/src/lib.rs +++ b/compiler/rustc_mir_dataflow/src/lib.rs @@ -1,7 +1,7 @@ #![feature(associated_type_defaults)] #![feature(box_patterns)] #![feature(exact_size_is_empty)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(once_cell)] #![feature(stmt_expr_attributes)] diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 162f7d969b1..e6fc8559571 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -1,7 +1,7 @@ #![allow(rustc::potential_query_instability)] #![feature(box_patterns)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(map_try_insert)] #![feature(min_specialization)] #![feature(never_type)] diff --git a/compiler/rustc_monomorphize/src/lib.rs b/compiler/rustc_monomorphize/src/lib.rs index 3afff7bcabf..ba6ce9fd40f 100644 --- a/compiler/rustc_monomorphize/src/lib.rs +++ b/compiler/rustc_monomorphize/src/lib.rs @@ -1,6 +1,6 @@ #![feature(array_windows)] #![feature(control_flow_enum)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] #![deny(rustc::untranslatable_diagnostic)] diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 3c88e1ef377..a37327f4294 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -4,7 +4,7 @@ #![feature(box_patterns)] #![feature(if_let_guard)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![feature(rustc_attrs)] #![recursion_limit = "256"] diff --git a/compiler/rustc_passes/src/lib.rs b/compiler/rustc_passes/src/lib.rs index 7b2f83958af..39ebb8db21c 100644 --- a/compiler/rustc_passes/src/lib.rs +++ b/compiler/rustc_passes/src/lib.rs @@ -8,7 +8,7 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(iter_intersperse)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(map_try_insert)] #![feature(min_specialization)] #![feature(try_blocks)] diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 92ef61fe64c..48ab31ab92d 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1,7 +1,7 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(associated_type_defaults)] #![feature(control_flow_enum)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(rustc_private)] #![feature(try_blocks)] #![recursion_limit = "256"] diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index 8a88b5c3340..f92c3831f26 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -1,7 +1,7 @@ #![feature(assert_matches)] #![feature(core_intrinsics)] #![feature(hash_raw_entry)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(extern_types)] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 749a78a7552..54a7f416ce6 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -12,7 +12,7 @@ #![feature(if_let_guard)] #![feature(iter_intersperse)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![recursion_limit = "256"] #![allow(rustdoc::private_intra_doc_links)] diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs index ebe44a56449..ce03c2a8ad0 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -1,6 +1,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(if_let_guard)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] #![feature(never_type)] diff --git a/compiler/rustc_serialize/src/lib.rs b/compiler/rustc_serialize/src/lib.rs index 91f4cfaf5ac..fa9c7bd54c3 100644 --- a/compiler/rustc_serialize/src/lib.rs +++ b/compiler/rustc_serialize/src/lib.rs @@ -14,7 +14,7 @@ Core encoding and decoding interfaces. #![feature(min_specialization)] #![feature(core_intrinsics)] #![feature(maybe_uninit_slice)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(new_uninit)] #![feature(allocator_api)] #![cfg_attr(test, feature(test))] diff --git a/compiler/rustc_session/src/lib.rs b/compiler/rustc_session/src/lib.rs index b9b243f6f08..f6bab775e76 100644 --- a/compiler/rustc_session/src/lib.rs +++ b/compiler/rustc_session/src/lib.rs @@ -1,6 +1,6 @@ #![feature(if_let_guard)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(once_cell)] diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 26b4ebeab1b..ada3bae6150 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -15,7 +15,7 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(array_windows)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(if_let_guard)] #![feature(negative_impls)] #![feature(min_specialization)] diff --git a/compiler/rustc_target/src/lib.rs b/compiler/rustc_target/src/lib.rs index 9c9e297849e..a7deab9d2ef 100644 --- a/compiler/rustc_target/src/lib.rs +++ b/compiler/rustc_target/src/lib.rs @@ -11,7 +11,7 @@ #![feature(assert_matches)] #![feature(associated_type_bounds)] #![feature(exhaustive_patterns)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(rustc_attrs)] diff --git a/compiler/rustc_trait_selection/src/lib.rs b/compiler/rustc_trait_selection/src/lib.rs index f039b1fca18..d35f74974fd 100644 --- a/compiler/rustc_trait_selection/src/lib.rs +++ b/compiler/rustc_trait_selection/src/lib.rs @@ -18,7 +18,7 @@ #![feature(hash_drain_filter)] #![cfg_attr(bootstrap, feature(label_break_value))] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(if_let_guard)] #![feature(never_type)] #![feature(type_alias_impl_trait)] diff --git a/compiler/rustc_traits/src/lib.rs b/compiler/rustc_traits/src/lib.rs index 318e76c79f1..2d39e973ed9 100644 --- a/compiler/rustc_traits/src/lib.rs +++ b/compiler/rustc_traits/src/lib.rs @@ -3,7 +3,7 @@ #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #[macro_use] diff --git a/compiler/rustc_ty_utils/src/lib.rs b/compiler/rustc_ty_utils/src/lib.rs index 6931b15b1ba..8524e57cb58 100644 --- a/compiler/rustc_ty_utils/src/lib.rs +++ b/compiler/rustc_ty_utils/src/lib.rs @@ -6,7 +6,7 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(control_flow_enum)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![feature(box_patterns)] #![recursion_limit = "256"] diff --git a/compiler/rustc_typeck/src/lib.rs b/compiler/rustc_typeck/src/lib.rs index ac66819d283..b1ce972e1d6 100644 --- a/compiler/rustc_typeck/src/lib.rs +++ b/compiler/rustc_typeck/src/lib.rs @@ -66,7 +66,7 @@ This API is completely unstable and subject to change. #![feature(iter_intersperse)] #![cfg_attr(bootstrap, feature(label_break_value))] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(once_cell)] diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index e5cf9033c86..8619467c2d9 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -169,7 +169,7 @@ #![cfg_attr(not(test), feature(generator_trait))] #![feature(hashmap_internals)] #![feature(lang_items)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(negative_impls)] #![feature(never_type)] diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index f13500de014..bc4f1b27c2a 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -255,7 +255,7 @@ #![cfg_attr(bootstrap, feature(label_break_value))] #![feature(lang_items)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(linkage)] #![feature(link_cfg)] #![feature(min_specialization)] diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index f6c648140b8..14d695582b0 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -9,7 +9,7 @@ #![feature(control_flow_enum)] #![feature(drain_filter)] #![feature(let_chains)] -#![feature(let_else)] +#![cfg_attr(bootstrap, feature(let_else))] #![feature(test)] #![feature(never_type)] #![feature(once_cell)] -- cgit 1.4.1-3-g733a5 From 5b8152807cae152d5c7cfb40615e5a817a6cf750 Mon Sep 17 00:00:00 2001 From: Jhonny Bill Mena Date: Wed, 7 Sep 2022 09:36:08 -0400 Subject: UPDATE - move SessionDiagnostic from rustc_session to rustc_errors --- compiler/rustc_attr/src/session_diagnostics.rs | 2 +- compiler/rustc_errors/src/diagnostic_builder.rs | 9 +++++++++ compiler/rustc_errors/src/lib.rs | 1 + compiler/rustc_expand/src/base.rs | 6 ++++-- .../rustc_infer/src/infer/error_reporting/need_type_info.rs | 2 +- compiler/rustc_lint/src/errors.rs | 4 ++-- compiler/rustc_macros/src/diagnostics/diagnostic.rs | 2 +- compiler/rustc_metadata/src/errors.rs | 4 ++-- compiler/rustc_monomorphize/src/errors.rs | 2 +- compiler/rustc_parse/src/parser/expr.rs | 2 +- compiler/rustc_query_system/src/query/job.rs | 6 ++++-- compiler/rustc_session/src/parse.rs | 3 +-- compiler/rustc_session/src/session.rs | 11 +---------- compiler/rustc_trait_selection/src/errors.rs | 4 ++-- compiler/rustc_typeck/src/errors.rs | 2 +- src/test/ui-fulldeps/internal-lints/diagnostics.rs | 3 +-- 16 files changed, 33 insertions(+), 30 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 085175d4bed..ed8400391c2 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -1,11 +1,11 @@ use std::num::IntErrorKind; use rustc_ast as ast; +use rustc_errors::SessionDiagnostic; use rustc_errors::{ error_code, fluent, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler, }; use rustc_macros::SessionDiagnostic; -use rustc_session::SessionDiagnostic; use rustc_span::{Span, Symbol}; use crate::UnsupportedLiteralReason; diff --git a/compiler/rustc_errors/src/diagnostic_builder.rs b/compiler/rustc_errors/src/diagnostic_builder.rs index 7e29dc207ac..71e21373d0d 100644 --- a/compiler/rustc_errors/src/diagnostic_builder.rs +++ b/compiler/rustc_errors/src/diagnostic_builder.rs @@ -13,6 +13,15 @@ use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::thread::panicking; +/// Trait implemented by error types. This should not be implemented manually. Instead, use +/// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic]. +#[rustc_diagnostic_item = "SessionDiagnostic"] +pub trait SessionDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> { + /// Write out as a diagnostic out of `Handler`. + #[must_use] + fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, T>; +} + /// Used for emitting structured error messages and other diagnostic information. /// /// If there is some state in a downstream crate you would like to diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 6f969bfcc53..3549d3c4999 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -60,6 +60,7 @@ mod snippet; mod styled_buffer; pub mod translation; +pub use diagnostic_builder::SessionDiagnostic; pub use snippet::Style; pub type PResult<'a, T> = Result>; diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index e1da3ecdec7..11598ea0fff 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -10,11 +10,13 @@ use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind use rustc_attr::{self as attr, Deprecation, Stability}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::sync::{self, Lrc}; -use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, PResult}; +use rustc_errors::{ + Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, PResult, SessionDiagnostic, +}; use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT; use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics}; use rustc_parse::{self, parser, MACRO_ARGUMENTS}; -use rustc_session::{parse::ParseSess, Limit, Session, SessionDiagnostic}; +use rustc_session::{parse::ParseSess, Limit, Session}; use rustc_span::def_id::{CrateNum, DefId, LocalDefId}; use rustc_span::edition::Edition; use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId}; diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index 89a448edc9b..dccd3f3a1cc 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -4,6 +4,7 @@ use crate::errors::{ }; use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use crate::infer::InferCtxt; +use rustc_errors::SessionDiagnostic; use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, IntoDiagnosticArg}; use rustc_hir as hir; use rustc_hir::def::Res; @@ -18,7 +19,6 @@ use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Print, Printer}; use rustc_middle::ty::{self, DefIdTree, InferConst}; use rustc_middle::ty::{GenericArg, GenericArgKind, SubstsRef}; use rustc_middle::ty::{IsSuggestable, Ty, TyCtxt, TypeckResults}; -use rustc_session::SessionDiagnostic; use rustc_span::symbol::{kw, Ident}; use rustc_span::{BytePos, Span}; use std::borrow::Cow; diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index 5c183d4091e..ac98948189b 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -1,6 +1,6 @@ -use rustc_errors::{fluent, AddSubdiagnostic, ErrorGuaranteed, Handler}; +use rustc_errors::{fluent, AddSubdiagnostic, ErrorGuaranteed, Handler, SessionDiagnostic}; use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; -use rustc_session::{lint::Level, SessionDiagnostic}; +use rustc_session::lint::Level; use rustc_span::{Span, Symbol}; #[derive(SessionDiagnostic)] diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic.rs b/compiler/rustc_macros/src/diagnostics/diagnostic.rs index cf1c5945529..891b6a118de 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -82,7 +82,7 @@ impl<'a> SessionDiagnosticDerive<'a> { structure.gen_impl(quote! { gen impl<'__session_diagnostic_sess, G> - rustc_session::SessionDiagnostic<'__session_diagnostic_sess, G> + rustc_errors::SessionDiagnostic<'__session_diagnostic_sess, G> for @Self where G: rustc_errors::EmissionGuarantee { diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 7d63fad3240..8cbcadb625a 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -3,9 +3,9 @@ use std::{ path::{Path, PathBuf}, }; -use rustc_errors::{error_code, ErrorGuaranteed}; +use rustc_errors::{error_code, ErrorGuaranteed, SessionDiagnostic}; use rustc_macros::SessionDiagnostic; -use rustc_session::{config, SessionDiagnostic}; +use rustc_session::config; use rustc_span::{sym, Span, Symbol}; use rustc_target::spec::{PanicStrategy, TargetTriple}; diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index d5f05e790d3..883380dca08 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -1,8 +1,8 @@ use std::path::PathBuf; use rustc_errors::ErrorGuaranteed; +use rustc_errors::SessionDiagnostic; use rustc_macros::{LintDiagnostic, SessionDiagnostic}; -use rustc_session::SessionDiagnostic; use rustc_span::Span; #[derive(SessionDiagnostic)] diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index f4f75f71e72..bb93f1cc260 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -36,10 +36,10 @@ use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits}; use rustc_ast::{ClosureBinder, StmtKind}; use rustc_ast_pretty::pprust; +use rustc_errors::SessionDiagnostic; use rustc_errors::{Applicability, Diagnostic, PResult}; use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP; use rustc_session::lint::BuiltinLintDiagnostics; -use rustc_session::SessionDiagnostic; use rustc_span::source_map::{self, Span, Spanned}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{BytePos, Pos}; diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 95305eabd0d..705305ff806 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -3,9 +3,11 @@ use crate::query::plumbing::CycleError; use crate::query::{QueryContext, QueryStackFrame}; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, Level}; +use rustc_errors::{ + Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, Level, SessionDiagnostic, +}; use rustc_hir::def::DefKind; -use rustc_session::{Session, SessionDiagnostic}; +use rustc_session::Session; use rustc_span::Span; use std::hash::Hash; diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 0389b2a06a3..564629a6703 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -6,14 +6,13 @@ use crate::errors::{FeatureDiagnosticForIssue, FeatureDiagnosticHelp, FeatureGat use crate::lint::{ builtin::UNSTABLE_SYNTAX_PRE_EXPANSION, BufferedEarlyLint, BuiltinLintDiagnostics, Lint, LintId, }; -use crate::SessionDiagnostic; use rustc_ast::node_id::NodeId; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::sync::{Lock, Lrc}; use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler}; use rustc_errors::{ fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId, - DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, MultiSpan, StashKey, + DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, MultiSpan, SessionDiagnostic, StashKey, }; use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures}; use rustc_span::edition::Edition; diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index a001f87db00..6a5a89747df 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -28,7 +28,7 @@ use rustc_errors::json::JsonEmitter; use rustc_errors::registry::Registry; use rustc_errors::{ error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, - EmissionGuarantee, ErrorGuaranteed, FluentBundle, Handler, LazyFallbackBundle, MultiSpan, + ErrorGuaranteed, FluentBundle, LazyFallbackBundle, MultiSpan, SessionDiagnostic, }; use rustc_macros::HashStable_Generic; pub use rustc_span::def_id::StableCrateId; @@ -223,15 +223,6 @@ pub struct PerfStats { pub normalize_projection_ty: AtomicUsize, } -/// Trait implemented by error types. This should not be implemented manually. Instead, use -/// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic]. -#[rustc_diagnostic_item = "SessionDiagnostic"] -pub trait SessionDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> { - /// Write out as a diagnostic out of `Handler`. - #[must_use] - fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, T>; -} - impl Session { pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option) { self.miri_unleashed_features.lock().push((span, feature_gate)); diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index ab0afc54514..dc7078d9ada 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -1,7 +1,7 @@ -use rustc_errors::{fluent, ErrorGuaranteed, Handler}; +use rustc_errors::{fluent, ErrorGuaranteed, Handler, SessionDiagnostic}; use rustc_macros::SessionDiagnostic; use rustc_middle::ty::{PolyTraitRef, Ty, Unevaluated}; -use rustc_session::{Limit, SessionDiagnostic}; +use rustc_session::Limit; use rustc_span::{Span, Symbol}; #[derive(SessionDiagnostic)] diff --git a/compiler/rustc_typeck/src/errors.rs b/compiler/rustc_typeck/src/errors.rs index 0d2e6674585..ed4c4f688bf 100644 --- a/compiler/rustc_typeck/src/errors.rs +++ b/compiler/rustc_typeck/src/errors.rs @@ -1,8 +1,8 @@ //! Errors emitted by typeck. +use rustc_errors::SessionDiagnostic; use rustc_errors::{error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler}; use rustc_macros::{LintDiagnostic, SessionDiagnostic, SessionSubdiagnostic}; use rustc_middle::ty::Ty; -use rustc_session::SessionDiagnostic; use rustc_span::{symbol::Ident, Span, Symbol}; #[derive(SessionDiagnostic)] diff --git a/src/test/ui-fulldeps/internal-lints/diagnostics.rs b/src/test/ui-fulldeps/internal-lints/diagnostics.rs index e9e809fa416..3b31a290449 100644 --- a/src/test/ui-fulldeps/internal-lints/diagnostics.rs +++ b/src/test/ui-fulldeps/internal-lints/diagnostics.rs @@ -12,10 +12,9 @@ extern crate rustc_session; extern crate rustc_span; use rustc_errors::{ - AddSubdiagnostic, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, fluent + AddSubdiagnostic, SessionDiagnostic, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, fluent }; use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; -use rustc_session::SessionDiagnostic; use rustc_span::Span; #[derive(SessionDiagnostic)] -- cgit 1.4.1-3-g733a5 From 19b348fed44342d8addbbb5e8f67cda5dc8d9b95 Mon Sep 17 00:00:00 2001 From: Jhonny Bill Mena Date: Sun, 18 Sep 2022 11:45:41 -0400 Subject: UPDATE - rename DiagnosticHandler trait to IntoDiagnostic --- compiler/rustc_ast_lowering/src/errors.rs | 66 ++++----- compiler/rustc_ast_passes/src/errors.rs | 54 +++---- compiler/rustc_attr/src/session_diagnostics.rs | 68 ++++----- compiler/rustc_borrowck/src/session_diagnostics.rs | 16 +-- compiler/rustc_builtin_macros/src/cfg.rs | 6 +- compiler/rustc_const_eval/src/errors.rs | 44 +++--- compiler/rustc_driver/src/session_diagnostics.rs | 16 +-- .../rustc_error_messages/locales/en-US/lint.ftl | 2 +- compiler/rustc_errors/src/diagnostic.rs | 2 +- compiler/rustc_errors/src/diagnostic_builder.rs | 7 +- compiler/rustc_errors/src/lib.rs | 75 +++++++++- compiler/rustc_expand/src/base.rs | 6 +- compiler/rustc_expand/src/errors.rs | 14 +- .../src/infer/error_reporting/need_type_info.rs | 2 +- compiler/rustc_interface/src/errors.rs | 30 ++-- compiler/rustc_lint/src/errors.rs | 22 +-- compiler/rustc_lint/src/internal.rs | 4 +- .../rustc_macros/src/diagnostics/diagnostic.rs | 22 +-- .../src/diagnostics/diagnostic_builder.rs | 6 +- compiler/rustc_macros/src/diagnostics/mod.rs | 8 +- compiler/rustc_macros/src/lib.rs | 2 +- compiler/rustc_metadata/src/errors.rs | 158 ++++++++++----------- compiler/rustc_middle/src/error.rs | 8 +- compiler/rustc_mir_dataflow/src/errors.rs | 22 +-- compiler/rustc_monomorphize/src/errors.rs | 16 +-- compiler/rustc_parse/src/parser/diagnostics.rs | 84 +++++------ compiler/rustc_parse/src/parser/expr.rs | 2 +- compiler/rustc_passes/src/errors.rs | 104 +++++++------- compiler/rustc_plugin_impl/src/errors.rs | 6 +- compiler/rustc_privacy/src/errors.rs | 14 +- compiler/rustc_query_system/src/error.rs | 14 +- compiler/rustc_query_system/src/query/job.rs | 2 +- compiler/rustc_save_analysis/src/errors.rs | 4 +- compiler/rustc_session/src/errors.rs | 24 ++-- compiler/rustc_session/src/parse.rs | 16 +-- compiler/rustc_session/src/session.rs | 18 +-- compiler/rustc_span/src/symbol.rs | 2 +- compiler/rustc_symbol_mangling/src/errors.rs | 4 +- compiler/rustc_trait_selection/src/errors.rs | 18 +-- compiler/rustc_ty_utils/src/errors.rs | 6 +- compiler/rustc_typeck/src/check/expr.rs | 2 +- compiler/rustc_typeck/src/errors.rs | 58 ++++---- src/test/ui-fulldeps/internal-lints/diagnostics.rs | 15 +- .../ui-fulldeps/internal-lints/diagnostics.stderr | 4 +- .../session-diagnostic/diagnostic-derive.rs | 154 ++++++++++---------- .../session-diagnostic/diagnostic-derive.stderr | 16 +-- 46 files changed, 659 insertions(+), 584 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index c87d0ca9657..3f3024eb2b8 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -1,8 +1,8 @@ use rustc_errors::{fluent, AddSubdiagnostic, Applicability, Diagnostic, DiagnosticArgFromDisplay}; -use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; use rustc_span::{symbol::Ident, Span, Symbol}; -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::generic_type_with_parentheses, code = "E0214")] pub struct GenericTypeWithParentheses { #[primary_span] @@ -28,7 +28,7 @@ impl AddSubdiagnostic for UseAngleBrackets { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[help] #[diag(ast_lowering::invalid_abi, code = "E0703")] pub struct InvalidAbi { @@ -39,7 +39,7 @@ pub struct InvalidAbi { pub valid_abis: String, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::assoc_ty_parentheses)] pub struct AssocTyParentheses { #[primary_span] @@ -71,7 +71,7 @@ impl AddSubdiagnostic for AssocTyParenthesesSub { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(ast_lowering::misplaced_impl_trait, code = "E0562")] pub struct MisplacedImplTrait<'a> { #[primary_span] @@ -79,14 +79,14 @@ pub struct MisplacedImplTrait<'a> { pub position: DiagnosticArgFromDisplay<'a>, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::rustc_box_attribute_error)] pub struct RustcBoxAttributeError { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::underscore_expr_lhs_assign)] pub struct UnderscoreExprLhsAssign { #[primary_span] @@ -94,7 +94,7 @@ pub struct UnderscoreExprLhsAssign { pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::base_expression_double_dot)] pub struct BaseExpressionDoubleDot { #[primary_span] @@ -102,7 +102,7 @@ pub struct BaseExpressionDoubleDot { pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::await_only_in_async_fn_and_blocks, code = "E0728")] pub struct AwaitOnlyInAsyncFnAndBlocks { #[primary_span] @@ -112,21 +112,21 @@ pub struct AwaitOnlyInAsyncFnAndBlocks { pub item_span: Option, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::generator_too_many_parameters, code = "E0628")] pub struct GeneratorTooManyParameters { #[primary_span] pub fn_decl_span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::closure_cannot_be_static, code = "E0697")] pub struct ClosureCannotBeStatic { #[primary_span] pub fn_decl_span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[help] #[diag(ast_lowering::async_non_move_closure_not_supported, code = "E0708")] pub struct AsyncNonMoveClosureNotSupported { @@ -134,7 +134,7 @@ pub struct AsyncNonMoveClosureNotSupported { pub fn_decl_span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::functional_record_update_destructuring_assignment)] pub struct FunctionalRecordUpdateDestructuringAssignemnt { #[primary_span] @@ -142,28 +142,28 @@ pub struct FunctionalRecordUpdateDestructuringAssignemnt { pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::async_generators_not_supported, code = "E0727")] pub struct AsyncGeneratorsNotSupported { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::inline_asm_unsupported_target, code = "E0472")] pub struct InlineAsmUnsupportedTarget { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::att_syntax_only_x86)] pub struct AttSyntaxOnlyX86 { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::abi_specified_multiple_times)] pub struct AbiSpecifiedMultipleTimes { #[primary_span] @@ -175,14 +175,14 @@ pub struct AbiSpecifiedMultipleTimes { pub equivalent: Option<()>, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::clobber_abi_not_supported)] pub struct ClobberAbiNotSupported { #[primary_span] pub abi_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[note] #[diag(ast_lowering::invalid_abi_clobber_abi)] pub struct InvalidAbiClobberAbi { @@ -191,7 +191,7 @@ pub struct InvalidAbiClobberAbi { pub supported_abis: String, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::invalid_register)] pub struct InvalidRegister<'a> { #[primary_span] @@ -200,7 +200,7 @@ pub struct InvalidRegister<'a> { pub error: &'a str, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::invalid_register_class)] pub struct InvalidRegisterClass<'a> { #[primary_span] @@ -209,7 +209,7 @@ pub struct InvalidRegisterClass<'a> { pub error: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(ast_lowering::invalid_asm_template_modifier_reg_class)] pub struct InvalidAsmTemplateModifierRegClass { #[primary_span] @@ -229,7 +229,7 @@ pub enum InvalidAsmTemplateModifierRegClassSub { DoesNotSupportModifier { class_name: Symbol }, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::invalid_asm_template_modifier_const)] pub struct InvalidAsmTemplateModifierConst { #[primary_span] @@ -239,7 +239,7 @@ pub struct InvalidAsmTemplateModifierConst { pub op_span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::invalid_asm_template_modifier_sym)] pub struct InvalidAsmTemplateModifierSym { #[primary_span] @@ -249,7 +249,7 @@ pub struct InvalidAsmTemplateModifierSym { pub op_span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::register_class_only_clobber)] pub struct RegisterClassOnlyClobber { #[primary_span] @@ -257,7 +257,7 @@ pub struct RegisterClassOnlyClobber { pub reg_class_name: Symbol, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::register_conflict)] pub struct RegisterConflict<'a> { #[primary_span] @@ -271,7 +271,7 @@ pub struct RegisterConflict<'a> { pub in_out: Option, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[help] #[diag(ast_lowering::sub_tuple_binding)] pub struct SubTupleBinding<'a> { @@ -288,7 +288,7 @@ pub struct SubTupleBinding<'a> { pub ctx: &'a str, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::extra_double_dot)] pub struct ExtraDoubleDot<'a> { #[primary_span] @@ -299,7 +299,7 @@ pub struct ExtraDoubleDot<'a> { pub ctx: &'a str, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[note] #[diag(ast_lowering::misplaced_double_dot)] pub struct MisplacedDoubleDot { @@ -307,28 +307,28 @@ pub struct MisplacedDoubleDot { pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::misplaced_relax_trait_bound)] pub struct MisplacedRelaxTraitBound { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::not_supported_for_lifetime_binder_async_closure)] pub struct NotSupportedForLifetimeBinderAsyncClosure { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::arbitrary_expression_in_pattern)] pub struct ArbitraryExpressionInPattern { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(DiagnosticHandler, Clone, Copy)] #[diag(ast_lowering::inclusive_range_with_no_end)] pub struct InclusiveRangeWithNoEnd { #[primary_span] diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 4f3b09c5871..20e2209acbe 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -1,12 +1,12 @@ //! Errors emitted by ast_passes. -use rustc_errors::{fluent, AddSubdiagnostic, Applicability, Diagnostic}; -use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; +use rustc_errors::{fluent, AddToDiagnostic, Applicability, Diagnostic}; +use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; use crate::ast_validation::ForbiddenLetReason; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::forbidden_let)] #[note] pub struct ForbiddenLet { @@ -16,7 +16,7 @@ pub struct ForbiddenLet { pub(crate) reason: ForbiddenLetReason, } -impl AddSubdiagnostic for ForbiddenLetReason { +impl AddToDiagnostic for ForbiddenLetReason { fn add_to_diagnostic(self, diag: &mut Diagnostic) { match self { Self::GenericForbidden => {} @@ -30,7 +30,7 @@ impl AddSubdiagnostic for ForbiddenLetReason { } } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::forbidden_let_stable)] #[note] pub struct ForbiddenLetStable { @@ -38,21 +38,21 @@ pub struct ForbiddenLetStable { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::forbidden_assoc_constraint)] pub struct ForbiddenAssocConstraint { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::keyword_lifetime)] pub struct KeywordLifetime { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::invalid_label)] pub struct InvalidLabel { #[primary_span] @@ -60,7 +60,7 @@ pub struct InvalidLabel { pub name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::invalid_visibility, code = "E0449")] pub struct InvalidVisibility { #[primary_span] @@ -79,7 +79,7 @@ pub enum InvalidVisibilityNote { IndividualForeignItems, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::trait_fn_const, code = "E0379")] pub struct TraitFnConst { #[primary_span] @@ -87,21 +87,21 @@ pub struct TraitFnConst { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::forbidden_lifetime_bound)] pub struct ForbiddenLifetimeBound { #[primary_span] pub spans: Vec, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::forbidden_non_lifetime_param)] pub struct ForbiddenNonLifetimeParam { #[primary_span] pub spans: Vec, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::fn_param_too_many)] pub struct FnParamTooMany { #[primary_span] @@ -109,21 +109,21 @@ pub struct FnParamTooMany { pub max_num_args: usize, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::fn_param_c_var_args_only)] pub struct FnParamCVarArgsOnly { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::fn_param_c_var_args_not_last)] pub struct FnParamCVarArgsNotLast { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::fn_param_doc_comment)] pub struct FnParamDocComment { #[primary_span] @@ -131,14 +131,14 @@ pub struct FnParamDocComment { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::fn_param_forbidden_attr)] pub struct FnParamForbiddenAttr { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::fn_param_forbidden_self)] #[note] pub struct FnParamForbiddenSelf { @@ -147,7 +147,7 @@ pub struct FnParamForbiddenSelf { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::forbidden_default)] pub struct ForbiddenDefault { #[primary_span] @@ -156,7 +156,7 @@ pub struct ForbiddenDefault { pub def_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::assoc_const_without_body)] pub struct AssocConstWithoutBody { #[primary_span] @@ -165,7 +165,7 @@ pub struct AssocConstWithoutBody { pub replace_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::assoc_fn_without_body)] pub struct AssocFnWithoutBody { #[primary_span] @@ -174,7 +174,7 @@ pub struct AssocFnWithoutBody { pub replace_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::assoc_type_without_body)] pub struct AssocTypeWithoutBody { #[primary_span] @@ -183,7 +183,7 @@ pub struct AssocTypeWithoutBody { pub replace_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::const_without_body)] pub struct ConstWithoutBody { #[primary_span] @@ -192,7 +192,7 @@ pub struct ConstWithoutBody { pub replace_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::static_without_body)] pub struct StaticWithoutBody { #[primary_span] @@ -201,7 +201,7 @@ pub struct StaticWithoutBody { pub replace_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::ty_alias_without_body)] pub struct TyAliasWithoutBody { #[primary_span] @@ -210,7 +210,7 @@ pub struct TyAliasWithoutBody { pub replace_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(ast_passes::fn_without_body)] pub struct FnWithoutBody { #[primary_span] @@ -227,7 +227,7 @@ pub struct ExternBlockSuggestion { pub abi: Option, } -impl AddSubdiagnostic for ExternBlockSuggestion { +impl AddToDiagnostic for ExternBlockSuggestion { fn add_to_diagnostic(self, diag: &mut Diagnostic) { let start_suggestion = if let Some(abi) = self.abi { format!("extern \"{}\" {{", abi) diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index ed8400391c2..8362b51af40 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -1,23 +1,23 @@ use std::num::IntErrorKind; use rustc_ast as ast; -use rustc_errors::SessionDiagnostic; use rustc_errors::{ - error_code, fluent, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler, + error_code, fluent, Applicability, DiagnosticBuilder, IntoDiagnostic, ErrorGuaranteed, + Handler, }; -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use rustc_span::{Span, Symbol}; use crate::UnsupportedLiteralReason; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::expected_one_cfg_pattern, code = "E0536")] pub(crate) struct ExpectedOneCfgPattern { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::invalid_predicate, code = "E0537")] pub(crate) struct InvalidPredicate { #[primary_span] @@ -26,7 +26,7 @@ pub(crate) struct InvalidPredicate { pub predicate: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::multiple_item, code = "E0538")] pub(crate) struct MultipleItem { #[primary_span] @@ -35,7 +35,7 @@ pub(crate) struct MultipleItem { pub item: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::incorrect_meta_item, code = "E0539")] pub(crate) struct IncorrectMetaItem { #[primary_span] @@ -50,7 +50,7 @@ pub(crate) struct UnknownMetaItem<'a> { } // Manual implementation to be able to format `expected` items correctly. -impl<'a> SessionDiagnostic<'a> for UnknownMetaItem<'_> { +impl<'a> IntoDiagnostic<'a> for UnknownMetaItem<'_> { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { let expected = self.expected.iter().map(|name| format!("`{}`", name)).collect::>(); let mut diag = handler.struct_span_err_with_code( @@ -65,28 +65,28 @@ impl<'a> SessionDiagnostic<'a> for UnknownMetaItem<'_> { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::missing_since, code = "E0542")] pub(crate) struct MissingSince { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::missing_note, code = "E0543")] pub(crate) struct MissingNote { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::multiple_stability_levels, code = "E0544")] pub(crate) struct MultipleStabilityLevels { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::invalid_issue_string, code = "E0545")] pub(crate) struct InvalidIssueString { #[primary_span] @@ -144,21 +144,21 @@ impl InvalidIssueStringCause { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::missing_feature, code = "E0546")] pub(crate) struct MissingFeature { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::non_ident_feature, code = "E0546")] pub(crate) struct NonIdentFeature { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::missing_issue, code = "E0547")] pub(crate) struct MissingIssue { #[primary_span] @@ -167,7 +167,7 @@ pub(crate) struct MissingIssue { // FIXME: This diagnostic is identical to `IncorrectMetaItem`, barring the error code. Consider // changing this to `IncorrectMetaItem`. See #51489. -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::incorrect_meta_item, code = "E0551")] pub(crate) struct IncorrectMetaItem2 { #[primary_span] @@ -176,14 +176,14 @@ pub(crate) struct IncorrectMetaItem2 { // FIXME: Why is this the same error code as `InvalidReprHintNoParen` and `InvalidReprHintNoValue`? // It is more similar to `IncorrectReprFormatGeneric`. -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::incorrect_repr_format_packed_one_or_zero_arg, code = "E0552")] pub(crate) struct IncorrectReprFormatPackedOneOrZeroArg { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::invalid_repr_hint_no_paren, code = "E0552")] pub(crate) struct InvalidReprHintNoParen { #[primary_span] @@ -192,7 +192,7 @@ pub(crate) struct InvalidReprHintNoParen { pub name: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::invalid_repr_hint_no_value, code = "E0552")] pub(crate) struct InvalidReprHintNoValue { #[primary_span] @@ -209,7 +209,7 @@ pub(crate) struct UnsupportedLiteral { pub start_point_span: Span, } -impl<'a> SessionDiagnostic<'a> for UnsupportedLiteral { +impl<'a> IntoDiagnostic<'a> for UnsupportedLiteral { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { let mut diag = handler.struct_span_err_with_code( self.span, @@ -237,7 +237,7 @@ impl<'a> SessionDiagnostic<'a> for UnsupportedLiteral { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::invalid_repr_align_need_arg, code = "E0589")] pub(crate) struct InvalidReprAlignNeedArg { #[primary_span] @@ -245,7 +245,7 @@ pub(crate) struct InvalidReprAlignNeedArg { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::invalid_repr_generic, code = "E0589")] pub(crate) struct InvalidReprGeneric<'a> { #[primary_span] @@ -255,14 +255,14 @@ pub(crate) struct InvalidReprGeneric<'a> { pub error_part: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::incorrect_repr_format_align_one_arg, code = "E0693")] pub(crate) struct IncorrectReprFormatAlignOneArg { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::incorrect_repr_format_generic, code = "E0693")] pub(crate) struct IncorrectReprFormatGeneric<'a> { #[primary_span] @@ -317,28 +317,28 @@ impl<'a> IncorrectReprFormatGenericCause<'a> { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::rustc_promotable_pairing, code = "E0717")] pub(crate) struct RustcPromotablePairing { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::rustc_allowed_unstable_pairing, code = "E0789")] pub(crate) struct RustcAllowedUnstablePairing { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::cfg_predicate_identifier)] pub(crate) struct CfgPredicateIdentifier { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::deprecated_item_suggestion)] pub(crate) struct DeprecatedItemSuggestion { #[primary_span] @@ -351,21 +351,21 @@ pub(crate) struct DeprecatedItemSuggestion { pub details: (), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::expected_single_version_literal)] pub(crate) struct ExpectedSingleVersionLiteral { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::expected_version_literal)] pub(crate) struct ExpectedVersionLiteral { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::expects_feature_list)] pub(crate) struct ExpectsFeatureList { #[primary_span] @@ -374,7 +374,7 @@ pub(crate) struct ExpectsFeatureList { pub name: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::expects_features)] pub(crate) struct ExpectsFeatures { #[primary_span] @@ -383,14 +383,14 @@ pub(crate) struct ExpectsFeatures { pub name: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::soft_no_args)] pub(crate) struct SoftNoArgs { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(attr::unknown_version_literal)] pub(crate) struct UnknownVersionLiteral { #[primary_span] diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index 5d750c6ca8c..1014a92cc39 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -1,11 +1,11 @@ use rustc_errors::{IntoDiagnosticArg, MultiSpan}; -use rustc_macros::{LintDiagnostic, SessionDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::Span; use crate::diagnostics::RegionName; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(borrowck::move_unsized, code = "E0161")] pub(crate) struct MoveUnsized<'tcx> { pub ty: Ty<'tcx>, @@ -14,7 +14,7 @@ pub(crate) struct MoveUnsized<'tcx> { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(borrowck::higher_ranked_lifetime_error)] pub(crate) struct HigherRankedLifetimeError { #[subdiagnostic] @@ -31,14 +31,14 @@ pub(crate) enum HigherRankedErrorCause { CouldNotNormalize { value: String }, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(borrowck::higher_ranked_subtype_error)] pub(crate) struct HigherRankedSubtypeError { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(borrowck::generic_does_not_live_long_enough)] pub(crate) struct GenericDoesNotLiveLongEnough { pub kind: String, @@ -53,7 +53,7 @@ pub(crate) struct VarNeedNotMut { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(borrowck::const_not_used_in_type_alias)] pub(crate) struct ConstNotUsedTraitAlias { pub ct: String, @@ -61,7 +61,7 @@ pub(crate) struct ConstNotUsedTraitAlias { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(borrowck::var_cannot_escape_closure)] #[note] #[note(borrowck::cannot_escape)] @@ -110,7 +110,7 @@ pub(crate) enum FnMutReturnTypeErr { }, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(borrowck::lifetime_constraints_error)] pub(crate) struct LifetimeOutliveErr { #[primary_span] diff --git a/compiler/rustc_builtin_macros/src/cfg.rs b/compiler/rustc_builtin_macros/src/cfg.rs index 9046bf13059..55b54fede93 100644 --- a/compiler/rustc_builtin_macros/src/cfg.rs +++ b/compiler/rustc_builtin_macros/src/cfg.rs @@ -8,7 +8,7 @@ use rustc_ast::tokenstream::TokenStream; use rustc_attr as attr; use rustc_errors::PResult; use rustc_expand::base::{self, *}; -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use rustc_span::Span; pub fn expand_cfg( @@ -35,7 +35,7 @@ pub fn expand_cfg( } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(builtin_macros::requires_cfg_pattern)] struct RequiresCfgPattern { #[primary_span] @@ -43,7 +43,7 @@ struct RequiresCfgPattern { span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(builtin_macros::expected_one_cfg_pattern)] struct OneCfgPattern { #[primary_span] diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index c3547cb3abd..d0b94e91abf 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -1,8 +1,8 @@ use rustc_hir::ConstContext; -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use rustc_span::Span; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::unstable_in_stable)] pub(crate) struct UnstableInStable { pub gate: String, @@ -21,14 +21,14 @@ pub(crate) struct UnstableInStable { pub attr_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::thread_local_access, code = "E0625")] pub(crate) struct NonConstOpErr { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::static_access, code = "E0013")] #[help] pub(crate) struct StaticAccessErr { @@ -40,7 +40,7 @@ pub(crate) struct StaticAccessErr { pub teach: Option<()>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::raw_ptr_to_int)] #[note] #[note(const_eval::note2)] @@ -49,7 +49,7 @@ pub(crate) struct RawPtrToIntErr { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::raw_ptr_comparison)] #[note] pub(crate) struct RawPtrComparisonErr { @@ -57,14 +57,14 @@ pub(crate) struct RawPtrComparisonErr { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::panic_non_str)] pub(crate) struct PanicNonStrErr { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::mut_deref, code = "E0658")] pub(crate) struct MutDerefErr { #[primary_span] @@ -72,7 +72,7 @@ pub(crate) struct MutDerefErr { pub kind: ConstContext, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::transient_mut_borrow, code = "E0658")] pub(crate) struct TransientMutBorrowErr { #[primary_span] @@ -80,7 +80,7 @@ pub(crate) struct TransientMutBorrowErr { pub kind: ConstContext, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::transient_mut_borrow_raw, code = "E0658")] pub(crate) struct TransientMutBorrowErrRaw { #[primary_span] @@ -88,7 +88,7 @@ pub(crate) struct TransientMutBorrowErrRaw { pub kind: ConstContext, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::max_num_nodes_in_const)] pub(crate) struct MaxNumNodesInConstErr { #[primary_span] @@ -96,7 +96,7 @@ pub(crate) struct MaxNumNodesInConstErr { pub global_const_id: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::unallowed_fn_pointer_call)] pub(crate) struct UnallowedFnPointerCall { #[primary_span] @@ -104,7 +104,7 @@ pub(crate) struct UnallowedFnPointerCall { pub kind: ConstContext, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::unstable_const_fn)] pub(crate) struct UnstableConstFn { #[primary_span] @@ -112,7 +112,7 @@ pub(crate) struct UnstableConstFn { pub def_path: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::unallowed_mutable_refs, code = "E0764")] pub(crate) struct UnallowedMutableRefs { #[primary_span] @@ -122,7 +122,7 @@ pub(crate) struct UnallowedMutableRefs { pub teach: Option<()>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::unallowed_mutable_refs_raw, code = "E0764")] pub(crate) struct UnallowedMutableRefsRaw { #[primary_span] @@ -131,7 +131,7 @@ pub(crate) struct UnallowedMutableRefsRaw { #[note(const_eval::teach_note)] pub teach: Option<()>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::non_const_fmt_macro_call, code = "E0015")] pub(crate) struct NonConstFmtMacroCall { #[primary_span] @@ -139,7 +139,7 @@ pub(crate) struct NonConstFmtMacroCall { pub kind: ConstContext, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::non_const_fn_call, code = "E0015")] pub(crate) struct NonConstFnCall { #[primary_span] @@ -148,7 +148,7 @@ pub(crate) struct NonConstFnCall { pub kind: ConstContext, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::unallowed_op_in_const_context)] pub(crate) struct UnallowedOpInConstContext { #[primary_span] @@ -156,7 +156,7 @@ pub(crate) struct UnallowedOpInConstContext { pub msg: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::unallowed_heap_allocations, code = "E0010")] pub(crate) struct UnallowedHeapAllocations { #[primary_span] @@ -167,7 +167,7 @@ pub(crate) struct UnallowedHeapAllocations { pub teach: Option<()>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::unallowed_inline_asm, code = "E0015")] pub(crate) struct UnallowedInlineAsm { #[primary_span] @@ -175,7 +175,7 @@ pub(crate) struct UnallowedInlineAsm { pub kind: ConstContext, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::interior_mutable_data_refer, code = "E0492")] pub(crate) struct InteriorMutableDataRefer { #[primary_span] @@ -188,7 +188,7 @@ pub(crate) struct InteriorMutableDataRefer { pub teach: Option<()>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(const_eval::interior_mutability_borrow)] pub(crate) struct InteriorMutabilityBorrow { #[primary_span] diff --git a/compiler/rustc_driver/src/session_diagnostics.rs b/compiler/rustc_driver/src/session_diagnostics.rs index e9696792d05..704d3c7fd2a 100644 --- a/compiler/rustc_driver/src/session_diagnostics.rs +++ b/compiler/rustc_driver/src/session_diagnostics.rs @@ -1,38 +1,38 @@ -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(driver::rlink_unable_to_read)] pub(crate) struct RlinkUnableToRead { pub err: std::io::Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(driver::rlink_wrong_file_type)] pub(crate) struct RLinkWrongFileType; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(driver::rlink_empty_version_number)] pub(crate) struct RLinkEmptyVersionNumber; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(driver::rlink_encoding_version_mismatch)] pub(crate) struct RLinkEncodingVersionMismatch { pub version_array: String, pub rlink_version: u32, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(driver::rlink_rustc_version_mismatch)] pub(crate) struct RLinkRustcVersionMismatch<'a> { pub rustc_version: String, pub current_version: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(driver::rlink_no_a_file)] pub(crate) struct RlinkNotAFile; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(driver::unpretty_dump_fail)] pub(crate) struct UnprettyDumpFail { pub path: String, diff --git a/compiler/rustc_error_messages/locales/en-US/lint.ftl b/compiler/rustc_error_messages/locales/en-US/lint.ftl index 7f9918e4f12..6cc0cb49e1f 100644 --- a/compiler/rustc_error_messages/locales/en-US/lint.ftl +++ b/compiler/rustc_error_messages/locales/en-US/lint.ftl @@ -51,7 +51,7 @@ lint_non_existant_doc_keyword = found non-existing keyword `{$keyword}` used in .help = only existing keywords are allowed in core/std lint_diag_out_of_impl = - diagnostics should only be created in `SessionDiagnostic`/`AddSubdiagnostic` impls + diagnostics should only be created in `IntoDiagnostic`/`AddSubdiagnostic` impls lint_untranslatable_diag = diagnostics should be created using translatable messages diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index 6dfb6b11b16..8a56068fcc7 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -35,7 +35,7 @@ pub enum DiagnosticArgValue<'source> { Number(usize), } -/// Converts a value of a type into a `DiagnosticArg` (typically a field of a `SessionDiagnostic` +/// Converts a value of a type into a `DiagnosticArg` (typically a field of an `IntoDiagnostic` /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*` /// crates to implement this. diff --git a/compiler/rustc_errors/src/diagnostic_builder.rs b/compiler/rustc_errors/src/diagnostic_builder.rs index 71e21373d0d..b646dd662cb 100644 --- a/compiler/rustc_errors/src/diagnostic_builder.rs +++ b/compiler/rustc_errors/src/diagnostic_builder.rs @@ -14,9 +14,10 @@ use std::ops::{Deref, DerefMut}; use std::thread::panicking; /// Trait implemented by error types. This should not be implemented manually. Instead, use -/// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic]. -#[rustc_diagnostic_item = "SessionDiagnostic"] -pub trait SessionDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> { +/// `#[derive(DiagnosticHandler)]` -- see [rustc_macros::DiagnosticHandler]. +#[cfg_attr(bootstrap, rustc_diagnostic_item = "SessionDiagnostic")] +#[cfg_attr(not(bootstrap), rustc_diagnostic_item = "DiagnosticHandler")] +pub trait IntoDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> { /// Write out as a diagnostic out of `Handler`. #[must_use] fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, T>; diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 3549d3c4999..aed52bce9aa 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -60,7 +60,7 @@ mod snippet; mod styled_buffer; pub mod translation; -pub use diagnostic_builder::SessionDiagnostic; +pub use diagnostic_builder::IntoDiagnostic; pub use snippet::Style; pub type PResult<'a, T> = Result>; @@ -647,6 +647,8 @@ impl Handler { /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_diagnostic( &self, msg: impl Into, @@ -660,6 +662,8 @@ impl Handler { /// * `can_emit_warnings` is `true` /// * `is_force_warn` was set in `DiagnosticId::Lint` #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_warn( &self, span: impl Into, @@ -676,6 +680,8 @@ impl Handler { /// Attempting to `.emit()` the builder will only emit if either: /// * `can_emit_warnings` is `true` /// * `is_force_warn` was set in `DiagnosticId::Lint` + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_warn_with_expectation( &self, span: impl Into, @@ -689,6 +695,8 @@ impl Handler { /// Construct a builder at the `Allow` level at the given `span` and with the `msg`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_allow( &self, span: impl Into, @@ -702,6 +710,8 @@ impl Handler { /// Construct a builder at the `Warning` level at the given `span` and with the `msg`. /// Also include a code. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_warn_with_code( &self, span: impl Into, @@ -719,6 +729,8 @@ impl Handler { /// * `can_emit_warnings` is `true` /// * `is_force_warn` was set in `DiagnosticId::Lint` #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_warn(&self, msg: impl Into) -> DiagnosticBuilder<'_, ()> { DiagnosticBuilder::new(self, Level::Warning(None), msg) } @@ -729,6 +741,8 @@ impl Handler { /// Attempting to `.emit()` the builder will only emit if either: /// * `can_emit_warnings` is `true` /// * `is_force_warn` was set in `DiagnosticId::Lint` + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_warn_with_expectation( &self, msg: impl Into, @@ -739,12 +753,16 @@ impl Handler { /// Construct a builder at the `Allow` level with the `msg`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_allow(&self, msg: impl Into) -> DiagnosticBuilder<'_, ()> { DiagnosticBuilder::new(self, Level::Allow, msg) } /// Construct a builder at the `Expect` level with the `msg`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_expect( &self, msg: impl Into, @@ -755,6 +773,8 @@ impl Handler { /// Construct a builder at the `Error` level at the given `span` and with the `msg`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_err( &self, span: impl Into, @@ -767,6 +787,8 @@ impl Handler { /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_err_with_code( &self, span: impl Into, @@ -781,6 +803,8 @@ impl Handler { /// Construct a builder at the `Error` level with the `msg`. // FIXME: This method should be removed (every error should have an associated error code). #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_err( &self, msg: impl Into, @@ -790,12 +814,16 @@ impl Handler { /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors. #[doc(hidden)] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_err_lint(&self, msg: impl Into) -> DiagnosticBuilder<'_, ()> { DiagnosticBuilder::new(self, Level::Error { lint: true }, msg) } /// Construct a builder at the `Error` level with the `msg` and the `code`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_err_with_code( &self, msg: impl Into, @@ -808,6 +836,8 @@ impl Handler { /// Construct a builder at the `Warn` level with the `msg` and the `code`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_warn_with_code( &self, msg: impl Into, @@ -820,6 +850,8 @@ impl Handler { /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_fatal( &self, span: impl Into, @@ -832,6 +864,8 @@ impl Handler { /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_fatal_with_code( &self, span: impl Into, @@ -845,18 +879,24 @@ impl Handler { /// Construct a builder at the `Error` level with the `msg`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_fatal(&self, msg: impl Into) -> DiagnosticBuilder<'_, !> { DiagnosticBuilder::new_fatal(self, msg) } /// Construct a builder at the `Help` level with the `msg`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_help(&self, msg: impl Into) -> DiagnosticBuilder<'_, ()> { DiagnosticBuilder::new(self, Level::Help, msg) } /// Construct a builder at the `Note` level with the `msg`. #[rustc_lint_diagnostics] + #[allow(rustc::diagnostic_outside_of_impl)] + #[allow(rustc::untranslatable_diagnostic)] pub fn struct_note_without_error( &self, msg: impl Into, @@ -1029,6 +1069,39 @@ impl Handler { self.inner.borrow_mut().emit_diagnostic(diagnostic) } + pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed { + self.create_err(err).emit() + } + + pub fn create_err<'a>( + &'a self, + err: impl IntoDiagnostic<'a>, + ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { + err.into_diagnostic(self) + } + + pub fn create_warning<'a>( + &'a self, + warning: impl IntoDiagnostic<'a, ()>, + ) -> DiagnosticBuilder<'a, ()> { + warning.into_diagnostic(self) + } + + pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) { + self.create_warning(warning).emit() + } + + pub fn create_fatal<'a>( + &'a self, + fatal: impl IntoDiagnostic<'a, !>, + ) -> DiagnosticBuilder<'a, !> { + fatal.into_diagnostic(self) + } + + pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! { + self.create_fatal(fatal).emit() + } + fn emit_diag_at_span( &self, mut diag: Diagnostic, diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 11598ea0fff..ca429b6adc1 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -11,7 +11,7 @@ use rustc_attr::{self as attr, Deprecation, Stability}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::sync::{self, Lrc}; use rustc_errors::{ - Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, PResult, SessionDiagnostic, + Applicability, DiagnosticBuilder, IntoDiagnostic, ErrorGuaranteed, MultiSpan, PResult, }; use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT; use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics}; @@ -1111,12 +1111,12 @@ impl<'a> ExtCtxt<'a> { pub fn create_err( &self, - err: impl SessionDiagnostic<'a>, + err: impl IntoDiagnostic<'a>, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { self.sess.create_err(err) } - pub fn emit_err(&self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed { + pub fn emit_err(&self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed { self.sess.emit_err(err) } diff --git a/compiler/rustc_expand/src/errors.rs b/compiler/rustc_expand/src/errors.rs index 0feae0debd2..7cbdad3cd95 100644 --- a/compiler/rustc_expand/src/errors.rs +++ b/compiler/rustc_expand/src/errors.rs @@ -1,29 +1,29 @@ -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use rustc_span::symbol::MacroRulesNormalizedIdent; use rustc_span::Span; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(expand::expr_repeat_no_syntax_vars)] pub(crate) struct NoSyntaxVarsExprRepeat { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(expand::must_repeat_once)] pub(crate) struct MustRepeatOnce { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(expand::count_repetition_misplaced)] pub(crate) struct CountRepetitionMisplaced { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(expand::meta_var_expr_unrecognized_var)] pub(crate) struct MetaVarExprUnrecognizedVar { #[primary_span] @@ -31,7 +31,7 @@ pub(crate) struct MetaVarExprUnrecognizedVar { pub key: MacroRulesNormalizedIdent, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(expand::var_still_repeating)] pub(crate) struct VarStillRepeating { #[primary_span] @@ -39,7 +39,7 @@ pub(crate) struct VarStillRepeating { pub ident: MacroRulesNormalizedIdent, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(expand::meta_var_dif_seq_matchers)] pub(crate) struct MetaVarsDifSeqMatchers { #[primary_span] diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index dccd3f3a1cc..baa97d72a4b 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -4,7 +4,7 @@ use crate::errors::{ }; use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use crate::infer::InferCtxt; -use rustc_errors::SessionDiagnostic; +use rustc_errors::IntoDiagnostic; use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, IntoDiagnosticArg}; use rustc_hir as hir; use rustc_hir::def::Res; diff --git a/compiler/rustc_interface/src/errors.rs b/compiler/rustc_interface/src/errors.rs index 6a497aed4ab..dc975099fc7 100644 --- a/compiler/rustc_interface/src/errors.rs +++ b/compiler/rustc_interface/src/errors.rs @@ -1,10 +1,10 @@ -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use rustc_span::{Span, Symbol}; use std::io; use std::path::Path; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::ferris_identifier)] pub struct FerrisIdentifier { #[primary_span] @@ -13,7 +13,7 @@ pub struct FerrisIdentifier { pub first_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::emoji_identifier)] pub struct EmojiIdentifier { #[primary_span] @@ -21,67 +21,67 @@ pub struct EmojiIdentifier { pub ident: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::mixed_bin_crate)] pub struct MixedBinCrate; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::mixed_proc_macro_crate)] pub struct MixedProcMacroCrate; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::proc_macro_doc_without_arg)] pub struct ProcMacroDocWithoutArg; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::error_writing_dependencies)] pub struct ErrorWritingDependencies<'a> { pub path: &'a Path, pub error: io::Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::input_file_would_be_overwritten)] pub struct InputFileWouldBeOverWritten<'a> { pub path: &'a Path, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::generated_file_conflicts_with_directory)] pub struct GeneratedFileConflictsWithDirectory<'a> { pub input_path: &'a Path, pub dir_path: &'a Path, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::temps_dir_error)] pub struct TempsDirError; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::out_dir_error)] pub struct OutDirError; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::cant_emit_mir)] pub struct CantEmitMIR { pub error: io::Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::rustc_error_fatal)] pub struct RustcErrorFatal { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::rustc_error_unexpected_annotation)] pub struct RustcErrorUnexpectedAnnotation { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(interface::failed_writing_file)] pub struct FailedWritingFile<'a> { pub path: &'a Path, diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index ac98948189b..261570acb7b 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -1,9 +1,9 @@ -use rustc_errors::{fluent, AddSubdiagnostic, ErrorGuaranteed, Handler, SessionDiagnostic}; -use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; +use rustc_errors::{fluent, AddSubdiagnostic, IntoDiagnostic, ErrorGuaranteed, Handler}; +use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; use rustc_session::lint::Level; use rustc_span::{Span, Symbol}; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(lint::overruled_attribute, code = "E0453")] pub struct OverruledAttribute { #[primary_span] @@ -42,7 +42,7 @@ impl AddSubdiagnostic for OverruledAttributeSub { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(lint::malformed_attribute, code = "E0452")] pub struct MalformedAttribute { #[primary_span] @@ -61,7 +61,7 @@ pub enum MalformedAttributeSub { ReasonMustComeLast(#[primary_span] Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(lint::unknown_tool_in_scoped_lint, code = "E0710")] pub struct UnknownToolInScopedLint { #[primary_span] @@ -72,7 +72,7 @@ pub struct UnknownToolInScopedLint { pub is_nightly_build: Option<()>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(lint::builtin_ellipsis_inclusive_range_patterns, code = "E0783")] pub struct BuiltinEllpisisInclusiveRangePatterns { #[primary_span] @@ -107,7 +107,7 @@ impl AddSubdiagnostic for RequestedLevel { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(lint::unsupported_group, code = "E0602")] pub struct UnsupportedGroup { pub lint_group: String, @@ -119,7 +119,7 @@ pub struct CheckNameUnknown { pub sub: RequestedLevel, } -impl SessionDiagnostic<'_> for CheckNameUnknown { +impl IntoDiagnostic<'_> for CheckNameUnknown { fn into_diagnostic( self, handler: &Handler, @@ -136,7 +136,7 @@ impl SessionDiagnostic<'_> for CheckNameUnknown { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(lint::check_name_unknown_tool, code = "E0602")] pub struct CheckNameUnknownTool { pub tool_name: Symbol, @@ -144,7 +144,7 @@ pub struct CheckNameUnknownTool { pub sub: RequestedLevel, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(lint::check_name_warning)] pub struct CheckNameWarning { pub msg: String, @@ -152,7 +152,7 @@ pub struct CheckNameWarning { pub sub: RequestedLevel, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(lint::check_name_deprecated)] pub struct CheckNameDeprecated { pub lint_name: String, diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index dd1fc5916db..dec75c9d380 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -372,7 +372,7 @@ declare_tool_lint! { declare_tool_lint! { pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL, Allow, - "prevent creation of diagnostics outside of `SessionDiagnostic`/`AddSubdiagnostic` impls", + "prevent creation of diagnostics outside of `DiagnosticHandler`/`AddSubdiagnostic` impls", report_in_external_macro: true } @@ -404,7 +404,7 @@ impl LateLintPass<'_> for Diagnostics { let Impl { of_trait: Some(of_trait), .. } = impl_ && let Some(def_id) = of_trait.trait_def_id() && let Some(name) = cx.tcx.get_diagnostic_name(def_id) && - matches!(name, sym::SessionDiagnostic | sym::AddSubdiagnostic | sym::DecorateLint) + matches!(name, sym::DiagnosticHandler | sym::AddSubdiagnostic | sym::DecorateLint) { found_impl = true; break; diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic.rs b/compiler/rustc_macros/src/diagnostics/diagnostic.rs index 891b6a118de..c5b5edab816 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -11,27 +11,27 @@ use synstructure::Structure; /// The central struct for constructing the `into_diagnostic` method from an annotated struct. pub(crate) struct SessionDiagnosticDerive<'a> { structure: Structure<'a>, - sess: syn::Ident, + handler: syn::Ident, builder: DiagnosticDeriveBuilder, } impl<'a> SessionDiagnosticDerive<'a> { - pub(crate) fn new(diag: syn::Ident, sess: syn::Ident, structure: Structure<'a>) -> Self { + pub(crate) fn new(diag: syn::Ident, handler: syn::Ident, structure: Structure<'a>) -> Self { Self { builder: DiagnosticDeriveBuilder { diag, fields: build_field_mapping(&structure), - kind: DiagnosticDeriveKind::SessionDiagnostic, + kind: DiagnosticDeriveKind::DiagnosticHandler, code: None, slug: None, }, - sess, + handler, structure, } } pub(crate) fn into_tokens(self) -> TokenStream { - let SessionDiagnosticDerive { mut structure, sess, mut builder } = self; + let SessionDiagnosticDerive { mut structure, handler, mut builder } = self; let ast = structure.ast(); let implementation = { @@ -53,7 +53,7 @@ impl<'a> SessionDiagnosticDerive<'a> { } Some(slug) => { quote! { - let mut #diag = #sess.struct_diagnostic(rustc_errors::fluent::#slug); + let mut #diag = #handler.struct_diagnostic(rustc_errors::fluent::#slug); } } }; @@ -72,7 +72,7 @@ impl<'a> SessionDiagnosticDerive<'a> { } else { span_err( ast.span().unwrap(), - "`#[derive(SessionDiagnostic)]` can only be used on structs", + "`#[derive(DiagnosticHandler)]` can only be used on structs", ) .emit(); @@ -81,15 +81,15 @@ impl<'a> SessionDiagnosticDerive<'a> { }; structure.gen_impl(quote! { - gen impl<'__session_diagnostic_sess, G> - rustc_errors::SessionDiagnostic<'__session_diagnostic_sess, G> + gen impl<'__diagnostic_handler_sess, G> + rustc_errors::IntoDiagnostic<'__diagnostic_handler_sess, G> for @Self where G: rustc_errors::EmissionGuarantee { fn into_diagnostic( self, - #sess: &'__session_diagnostic_sess rustc_errors::Handler - ) -> rustc_errors::DiagnosticBuilder<'__session_diagnostic_sess, G> { + #handler: &'__diagnostic_handler_sess rustc_errors::Handler + ) -> rustc_errors::DiagnosticBuilder<'__diagnostic_handler_sess, G> { use rustc_errors::IntoDiagnosticArg; #implementation } diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index 2a4fe48a8ac..4af3fd23624 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -21,12 +21,12 @@ use synstructure::{BindingInfo, Structure}; /// What kind of diagnostic is being derived - a fatal/error/warning or a lint? #[derive(Copy, Clone, PartialEq, Eq)] pub(crate) enum DiagnosticDeriveKind { - SessionDiagnostic, + DiagnosticHandler, LintDiagnostic, } /// Tracks persistent information required for building up individual calls to diagnostic methods -/// for generated diagnostic derives - both `SessionDiagnostic` for fatal/errors/warnings and +/// for generated diagnostic derives - both `DiagnosticHandler` for fatal/errors/warnings and /// `LintDiagnostic` for lints. pub(crate) struct DiagnosticDeriveBuilder { /// The identifier to use for the generated `DiagnosticBuilder` instance. @@ -333,7 +333,7 @@ impl DiagnosticDeriveBuilder { } "primary_span" => { match self.kind { - DiagnosticDeriveKind::SessionDiagnostic => { + DiagnosticDeriveKind::DiagnosticHandler => { report_error_if_not_applied_to_span(attr, &info)?; Ok(quote! { diff --git a/compiler/rustc_macros/src/diagnostics/mod.rs b/compiler/rustc_macros/src/diagnostics/mod.rs index 2ff21e18ff8..162089c881e 100644 --- a/compiler/rustc_macros/src/diagnostics/mod.rs +++ b/compiler/rustc_macros/src/diagnostics/mod.rs @@ -12,7 +12,7 @@ use quote::format_ident; use subdiagnostic::SessionSubdiagnosticDerive; use synstructure::Structure; -/// Implements `#[derive(SessionDiagnostic)]`, which allows for errors to be specified as a struct, +/// Implements `#[derive(DiagnosticHandler)]`, which allows for errors to be specified as a struct, /// independent from the actual diagnostics emitting code. /// /// ```ignore (rust) @@ -22,7 +22,7 @@ use synstructure::Structure; /// # use rustc_span::{symbol::Ident, Span}; /// # extern crate rust_middle; /// # use rustc_middle::ty::Ty; -/// #[derive(SessionDiagnostic)] +/// #[derive(DiagnosticHandler)] /// #[diag(borrowck::move_out_of_borrow, code = "E0505")] /// pub struct MoveOutOfBorrowError<'tcx> { /// pub name: Ident, @@ -56,10 +56,10 @@ use synstructure::Structure; /// }); /// ``` /// -/// See rustc dev guide for more examples on using the `#[derive(SessionDiagnostic)]`: +/// See rustc dev guide for more examples on using the `#[derive(DiagnosticHandler)]`: /// pub fn session_diagnostic_derive(s: Structure<'_>) -> TokenStream { - SessionDiagnosticDerive::new(format_ident!("diag"), format_ident!("sess"), s).into_tokens() + SessionDiagnosticDerive::new(format_ident!("diag"), format_ident!("handler"), s).into_tokens() } /// Implements `#[derive(LintDiagnostic)]`, which allows for lints to be specified as a struct, diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 2c027d754da..13305782ff1 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -127,7 +127,7 @@ decl_derive!([TypeFoldable, attributes(type_foldable)] => type_foldable::type_fo decl_derive!([TypeVisitable, attributes(type_visitable)] => type_visitable::type_visitable_derive); decl_derive!([Lift, attributes(lift)] => lift::lift_derive); decl_derive!( - [SessionDiagnostic, attributes( + [DiagnosticHandler, attributes( // struct attributes diag, help, diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 8cbcadb625a..0a5973ca1aa 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -3,49 +3,49 @@ use std::{ path::{Path, PathBuf}, }; -use rustc_errors::{error_code, ErrorGuaranteed, SessionDiagnostic}; -use rustc_macros::SessionDiagnostic; +use rustc_errors::{error_code, IntoDiagnostic, ErrorGuaranteed}; +use rustc_macros::DiagnosticHandler; use rustc_session::config; use rustc_span::{sym, Span, Symbol}; use rustc_target::spec::{PanicStrategy, TargetTriple}; use crate::locator::CrateFlavor; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::rlib_required)] pub struct RlibRequired { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::lib_required)] pub struct LibRequired<'a> { pub crate_name: Symbol, pub kind: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::crate_dep_multiple)] #[help] pub struct CrateDepMultiple { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::two_panic_runtimes)] pub struct TwoPanicRuntimes { pub prev_name: Symbol, pub cur_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::bad_panic_strategy)] pub struct BadPanicStrategy { pub runtime: Symbol, pub strategy: PanicStrategy, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::required_panic_strategy)] pub struct RequiredPanicStrategy { pub crate_name: Symbol, @@ -53,7 +53,7 @@ pub struct RequiredPanicStrategy { pub desired_strategy: PanicStrategy, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::incompatible_panic_in_drop_strategy)] pub struct IncompatiblePanicInDropStrategy { pub crate_name: Symbol, @@ -61,56 +61,56 @@ pub struct IncompatiblePanicInDropStrategy { pub desired_strategy: PanicStrategy, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_names_in_link)] pub struct MultipleNamesInLink { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_kinds_in_link)] pub struct MultipleKindsInLink { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::link_name_form)] pub struct LinkNameForm { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::link_kind_form)] pub struct LinkKindForm { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::link_modifiers_form)] pub struct LinkModifiersForm { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::link_cfg_form)] pub struct LinkCfgForm { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::wasm_import_form)] pub struct WasmImportForm { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::empty_link_name, code = "E0454")] pub struct EmptyLinkName { #[primary_span] @@ -118,21 +118,21 @@ pub struct EmptyLinkName { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::link_framework_apple, code = "E0455")] pub struct LinkFrameworkApple { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::framework_only_windows, code = "E0455")] pub struct FrameworkOnlyWindows { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::unknown_link_kind, code = "E0458")] pub struct UnknownLinkKind<'a> { #[primary_span] @@ -141,49 +141,49 @@ pub struct UnknownLinkKind<'a> { pub kind: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_link_modifiers)] pub struct MultipleLinkModifiers { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_cfgs)] pub struct MultipleCfgs { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::link_cfg_single_predicate)] pub struct LinkCfgSinglePredicate { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_wasm_import)] pub struct MultipleWasmImport { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::unexpected_link_arg)] pub struct UnexpectedLinkArg { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::invalid_link_modifier)] pub struct InvalidLinkModifier { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_modifiers)] pub struct MultipleModifiers<'a> { #[primary_span] @@ -191,28 +191,28 @@ pub struct MultipleModifiers<'a> { pub modifier: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::bundle_needs_static)] pub struct BundleNeedsStatic { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::whole_archive_needs_static)] pub struct WholeArchiveNeedsStatic { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::as_needed_compatibility)] pub struct AsNeededCompatibility { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::unknown_link_modifier)] pub struct UnknownLinkModifier<'a> { #[primary_span] @@ -220,14 +220,14 @@ pub struct UnknownLinkModifier<'a> { pub modifier: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::incompatible_wasm_link)] pub struct IncompatibleWasmLink { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::link_requires_name, code = "E0459")] pub struct LinkRequiresName { #[primary_span] @@ -235,105 +235,105 @@ pub struct LinkRequiresName { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::raw_dylib_no_nul)] pub struct RawDylibNoNul { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::link_ordinal_raw_dylib)] pub struct LinkOrdinalRawDylib { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::lib_framework_apple)] pub struct LibFrameworkApple; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::empty_renaming_target)] pub struct EmptyRenamingTarget<'a> { pub lib_name: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::renaming_no_link)] pub struct RenamingNoLink<'a> { pub lib_name: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_renamings)] pub struct MultipleRenamings<'a> { pub lib_name: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::no_link_mod_override)] pub struct NoLinkModOverride { #[primary_span] pub span: Option, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::unsupported_abi_i686)] pub struct UnsupportedAbiI686 { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::unsupported_abi)] pub struct UnsupportedAbi { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::fail_create_file_encoder)] pub struct FailCreateFileEncoder { pub err: Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::fail_seek_file)] pub struct FailSeekFile { pub err: Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::fail_write_file)] pub struct FailWriteFile { pub err: Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::crate_not_panic_runtime)] pub struct CrateNotPanicRuntime { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::no_panic_strategy)] pub struct NoPanicStrategy { pub crate_name: Symbol, pub strategy: PanicStrategy, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::profiler_builtins_needs_core)] pub struct ProfilerBuiltinsNeedsCore; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::not_profiler_runtime)] pub struct NotProfilerRuntime { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::no_multiple_global_alloc)] pub struct NoMultipleGlobalAlloc { #[primary_span] @@ -343,18 +343,18 @@ pub struct NoMultipleGlobalAlloc { pub span1: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::conflicting_global_alloc)] pub struct ConflictingGlobalAlloc { pub crate_name: Symbol, pub other_crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::global_alloc_required)] pub struct GlobalAllocRequired; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::no_transitive_needs_dep)] pub struct NoTransitiveNeedsDep<'a> { pub crate_name: Symbol, @@ -362,7 +362,7 @@ pub struct NoTransitiveNeedsDep<'a> { pub deps_crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::failed_write_error)] pub struct FailedWriteError { pub filename: PathBuf, @@ -381,20 +381,20 @@ pub struct FailedCreateTempdir { pub err: Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::failed_create_file)] pub struct FailedCreateFile<'a> { pub filename: &'a Path, pub err: Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::failed_create_encoded_metadata)] pub struct FailedCreateEncodedMetadata { pub err: Error, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::non_ascii_name)] pub struct NonAsciiName { #[primary_span] @@ -402,7 +402,7 @@ pub struct NonAsciiName { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::extern_location_not_exist)] pub struct ExternLocationNotExist<'a> { #[primary_span] @@ -411,7 +411,7 @@ pub struct ExternLocationNotExist<'a> { pub location: &'a Path, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::extern_location_not_file)] pub struct ExternLocationNotFile<'a> { #[primary_span] @@ -427,7 +427,7 @@ pub(crate) struct MultipleCandidates { pub candidates: Vec, } -impl SessionDiagnostic<'_> for MultipleCandidates { +impl IntoDiagnostic<'_> for MultipleCandidates { fn into_diagnostic( self, handler: &'_ rustc_errors::Handler, @@ -444,7 +444,7 @@ impl SessionDiagnostic<'_> for MultipleCandidates { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_matching_crates, code = "E0464")] #[note] pub struct MultipleMatchingCrates { @@ -454,7 +454,7 @@ pub struct MultipleMatchingCrates { pub candidates: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::symbol_conflicts_current, code = "E0519")] pub struct SymbolConflictsCurrent { #[primary_span] @@ -462,7 +462,7 @@ pub struct SymbolConflictsCurrent { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::symbol_conflicts_others, code = "E0523")] pub struct SymbolConflictsOthers { #[primary_span] @@ -470,7 +470,7 @@ pub struct SymbolConflictsOthers { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::stable_crate_id_collision)] pub struct StableCrateIdCollision { #[primary_span] @@ -479,7 +479,7 @@ pub struct StableCrateIdCollision { pub crate_name1: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::dl_error)] pub struct DlError { #[primary_span] @@ -487,7 +487,7 @@ pub struct DlError { pub err: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::newer_crate_version, code = "E0460")] #[note] #[note(metadata::found_crate_versions)] @@ -499,7 +499,7 @@ pub struct NewerCrateVersion { pub found_crates: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::no_crate_with_triple, code = "E0461")] #[note(metadata::found_crate_versions)] pub struct NoCrateWithTriple<'a> { @@ -511,7 +511,7 @@ pub struct NoCrateWithTriple<'a> { pub found_crates: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::found_staticlib, code = "E0462")] #[note(metadata::found_crate_versions)] #[help] @@ -523,7 +523,7 @@ pub struct FoundStaticlib { pub found_crates: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::incompatible_rustc, code = "E0514")] #[note(metadata::found_crate_versions)] #[help] @@ -543,7 +543,7 @@ pub struct InvalidMetadataFiles { pub crate_rejections: Vec, } -impl SessionDiagnostic<'_> for InvalidMetadataFiles { +impl IntoDiagnostic<'_> for InvalidMetadataFiles { fn into_diagnostic( self, handler: &'_ rustc_errors::Handler, @@ -571,7 +571,7 @@ pub struct CannotFindCrate { pub locator_triple: TargetTriple, } -impl SessionDiagnostic<'_> for CannotFindCrate { +impl IntoDiagnostic<'_> for CannotFindCrate { fn into_diagnostic( self, handler: &'_ rustc_errors::Handler, @@ -617,7 +617,7 @@ impl SessionDiagnostic<'_> for CannotFindCrate { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::no_dylib_plugin, code = "E0457")] pub struct NoDylibPlugin { #[primary_span] @@ -625,7 +625,7 @@ pub struct NoDylibPlugin { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::crate_location_unknown_type)] pub struct CrateLocationUnknownType<'a> { #[primary_span] @@ -633,7 +633,7 @@ pub struct CrateLocationUnknownType<'a> { pub path: &'a Path, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::lib_filename_form)] pub struct LibFilenameForm<'a> { #[primary_span] @@ -642,28 +642,28 @@ pub struct LibFilenameForm<'a> { pub dll_suffix: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::multiple_import_name_type)] pub struct MultipleImportNameType { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::import_name_type_form)] pub struct ImportNameTypeForm { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::import_name_type_x86)] pub struct ImportNameTypeX86 { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::unknown_import_name_type)] pub struct UnknownImportNameType<'a> { #[primary_span] @@ -671,7 +671,7 @@ pub struct UnknownImportNameType<'a> { pub import_name_type: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(metadata::import_name_type_raw)] pub struct ImportNameTypeRaw { #[primary_span] diff --git a/compiler/rustc_middle/src/error.rs b/compiler/rustc_middle/src/error.rs index 18b31a75bcc..effda9c0557 100644 --- a/compiler/rustc_middle/src/error.rs +++ b/compiler/rustc_middle/src/error.rs @@ -1,9 +1,9 @@ -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use rustc_span::Span; use crate::ty::Ty; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(middle::drop_check_overflow, code = "E0320")] #[note] pub struct DropCheckOverflow<'tcx> { @@ -13,7 +13,7 @@ pub struct DropCheckOverflow<'tcx> { pub overflow_ty: Ty<'tcx>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(middle::opaque_hidden_type_mismatch)] pub struct OpaqueHiddenTypeMismatch<'tcx> { pub self_ty: Ty<'tcx>, @@ -39,7 +39,7 @@ pub enum TypeMismatchReason { }, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(middle::limit_invalid)] pub struct LimitInvalid<'a> { #[primary_span] diff --git a/compiler/rustc_mir_dataflow/src/errors.rs b/compiler/rustc_mir_dataflow/src/errors.rs index cc14257876c..0d36abed2c0 100644 --- a/compiler/rustc_mir_dataflow/src/errors.rs +++ b/compiler/rustc_mir_dataflow/src/errors.rs @@ -1,21 +1,21 @@ -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use rustc_span::{Span, Symbol}; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::path_must_end_in_filename)] pub(crate) struct PathMustEndInFilename { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::unknown_formatter)] pub(crate) struct UnknownFormatter { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::duplicate_values_for)] pub(crate) struct DuplicateValuesFor { #[primary_span] @@ -23,7 +23,7 @@ pub(crate) struct DuplicateValuesFor { pub name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::requires_an_argument)] pub(crate) struct RequiresAnArgument { #[primary_span] @@ -31,39 +31,39 @@ pub(crate) struct RequiresAnArgument { pub name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::stop_after_dataflow_ended_compilation)] pub(crate) struct StopAfterDataFlowEndedCompilation; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::peek_must_be_place_or_ref_place)] pub(crate) struct PeekMustBePlaceOrRefPlace { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::peek_must_be_not_temporary)] pub(crate) struct PeekMustBeNotTemporary { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::peek_bit_not_set)] pub(crate) struct PeekBitNotSet { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::peek_argument_not_a_local)] pub(crate) struct PeekArgumentNotALocal { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(mir_dataflow::peek_argument_untracked)] pub(crate) struct PeekArgumentUntracked { #[primary_span] diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index 883380dca08..150a702dc24 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -1,11 +1,11 @@ use std::path::PathBuf; +use rustc_errors::IntoDiagnostic; use rustc_errors::ErrorGuaranteed; -use rustc_errors::SessionDiagnostic; -use rustc_macros::{LintDiagnostic, SessionDiagnostic}; +use rustc_macros::{DiagnosticHandler, LintDiagnostic}; use rustc_span::Span; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(monomorphize::recursion_limit)] pub struct RecursionLimit { #[primary_span] @@ -19,7 +19,7 @@ pub struct RecursionLimit { pub path: PathBuf, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(monomorphize::type_length_limit)] #[help(monomorphize::consider_type_length_limit)] pub struct TypeLengthLimit { @@ -32,7 +32,7 @@ pub struct TypeLengthLimit { pub type_length: usize, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(monomorphize::requires_lang_item)] pub struct RequiresLangItem { pub lang_item: String, @@ -44,7 +44,7 @@ pub struct UnusedGenericParams { pub param_names: Vec, } -impl SessionDiagnostic<'_> for UnusedGenericParams { +impl IntoDiagnostic<'_> for UnusedGenericParams { fn into_diagnostic( self, handler: &'_ rustc_errors::Handler, @@ -72,11 +72,11 @@ pub struct LargeAssignmentsLint { pub limit: u64, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(monomorphize::unknown_partition_strategy)] pub struct UnknownPartitionStrategy; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(monomorphize::symbol_already_defined)] pub struct SymbolAlreadyDefined { #[primary_span] diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index a65f523a0f4..02148193cf0 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -20,7 +20,7 @@ use rustc_errors::{ fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult, }; use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed}; -use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{Span, SpanSnippetError, DUMMY_SP}; @@ -242,7 +242,7 @@ impl MultiSugg { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::maybe_report_ambiguous_plus)] struct AmbiguousPlus { pub sum_ty: String, @@ -251,7 +251,7 @@ struct AmbiguousPlus { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::maybe_recover_from_bad_type_plus, code = "E0178")] struct BadTypePlus { pub ty: String, @@ -285,7 +285,7 @@ pub enum BadTypePlusSub { }, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::maybe_recover_from_bad_qpath_stage_2)] struct BadQPathStage2 { #[primary_span] @@ -294,7 +294,7 @@ struct BadQPathStage2 { ty: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::incorrect_semicolon)] struct IncorrectSemicolon<'a> { #[primary_span] @@ -305,7 +305,7 @@ struct IncorrectSemicolon<'a> { name: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::incorrect_use_of_await)] struct IncorrectUseOfAwait { #[primary_span] @@ -313,7 +313,7 @@ struct IncorrectUseOfAwait { span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::incorrect_use_of_await)] struct IncorrectAwait { #[primary_span] @@ -324,7 +324,7 @@ struct IncorrectAwait { question_mark: &'static str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::in_in_typo)] struct InInTypo { #[primary_span] @@ -333,7 +333,7 @@ struct InInTypo { sugg_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_variable_declaration)] pub struct InvalidVariableDeclaration { #[primary_span] @@ -362,7 +362,7 @@ pub enum InvalidVariableDeclarationSub { UseLetNotVar(#[primary_span] Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_comparison_operator)] pub(crate) struct InvalidComparisonOperator { #[primary_span] @@ -389,7 +389,7 @@ pub(crate) enum InvalidComparisonOperatorSub { Spaceship(#[primary_span] Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_logical_operator)] #[note] pub(crate) struct InvalidLogicalOperator { @@ -416,7 +416,7 @@ pub(crate) enum InvalidLogicalOperatorSub { Disjunction(#[primary_span] Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::tilde_is_not_unary_operator)] pub(crate) struct TildeAsUnaryOperator( #[primary_span] @@ -424,7 +424,7 @@ pub(crate) struct TildeAsUnaryOperator( pub Span, ); -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::unexpected_token_after_not)] pub(crate) struct NotAsNegationOperator { #[primary_span] @@ -458,7 +458,7 @@ pub enum NotAsNegationOperatorSub { SuggestNotLogical(#[primary_span] Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::malformed_loop_label)] pub(crate) struct MalformedLoopLabel { #[primary_span] @@ -467,7 +467,7 @@ pub(crate) struct MalformedLoopLabel { pub correct_label: Ident, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::lifetime_in_borrow_expression)] pub(crate) struct LifetimeInBorrowExpression { #[primary_span] @@ -477,15 +477,15 @@ pub(crate) struct LifetimeInBorrowExpression { pub lifetime_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::field_expression_with_generic)] pub(crate) struct FieldExpressionWithGeneric(#[primary_span] pub Span); -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::macro_invocation_with_qualified_path)] pub(crate) struct MacroInvocationWithQualifiedPath(#[primary_span] pub Span); -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::unexpected_token_after_label)] pub(crate) struct UnexpectedTokenAfterLabel( #[primary_span] @@ -493,7 +493,7 @@ pub(crate) struct UnexpectedTokenAfterLabel( pub Span, ); -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::require_colon_after_labeled_expression)] #[note] pub(crate) struct RequireColonAfterLabeledExpression { @@ -505,7 +505,7 @@ pub(crate) struct RequireColonAfterLabeledExpression { pub label_end: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::do_catch_syntax_removed)] #[note] pub(crate) struct DoCatchSyntaxRemoved { @@ -514,7 +514,7 @@ pub(crate) struct DoCatchSyntaxRemoved { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::float_literal_requires_integer_part)] pub(crate) struct FloatLiteralRequiresIntegerPart { #[primary_span] @@ -523,7 +523,7 @@ pub(crate) struct FloatLiteralRequiresIntegerPart { pub correct: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_int_literal_width)] #[help] pub(crate) struct InvalidIntLiteralWidth { @@ -532,7 +532,7 @@ pub(crate) struct InvalidIntLiteralWidth { pub width: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_num_literal_base_prefix)] #[note] pub(crate) struct InvalidNumLiteralBasePrefix { @@ -542,7 +542,7 @@ pub(crate) struct InvalidNumLiteralBasePrefix { pub fixed: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_num_literal_suffix)] #[help] pub(crate) struct InvalidNumLiteralSuffix { @@ -552,7 +552,7 @@ pub(crate) struct InvalidNumLiteralSuffix { pub suffix: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_float_literal_width)] #[help] pub(crate) struct InvalidFloatLiteralWidth { @@ -561,7 +561,7 @@ pub(crate) struct InvalidFloatLiteralWidth { pub width: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_float_literal_suffix)] #[help] pub(crate) struct InvalidFloatLiteralSuffix { @@ -571,14 +571,14 @@ pub(crate) struct InvalidFloatLiteralSuffix { pub suffix: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::int_literal_too_large)] pub(crate) struct IntLiteralTooLarge { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::missing_semicolon_before_array)] pub(crate) struct MissingSemicolonBeforeArray { #[primary_span] @@ -587,7 +587,7 @@ pub(crate) struct MissingSemicolonBeforeArray { pub semicolon: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::invalid_block_macro_segment)] pub(crate) struct InvalidBlockMacroSegment { #[primary_span] @@ -596,7 +596,7 @@ pub(crate) struct InvalidBlockMacroSegment { pub context: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::if_expression_missing_then_block)] pub(crate) struct IfExpressionMissingThenBlock { #[primary_span] @@ -613,7 +613,7 @@ pub(crate) enum IfExpressionMissingThenBlockSub { AddThenBlock(#[primary_span] Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::if_expression_missing_condition)] pub(crate) struct IfExpressionMissingCondition { #[primary_span] @@ -623,14 +623,14 @@ pub(crate) struct IfExpressionMissingCondition { pub block_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::expected_expression_found_let)] pub(crate) struct ExpectedExpressionFoundLet { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::expected_else_block)] pub(crate) struct ExpectedElseBlock { #[primary_span] @@ -642,7 +642,7 @@ pub(crate) struct ExpectedElseBlock { pub condition_start: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::outer_attribute_not_allowed_on_if_else)] pub(crate) struct OuterAttributeNotAllowedOnIfElse { #[primary_span] @@ -659,7 +659,7 @@ pub(crate) struct OuterAttributeNotAllowedOnIfElse { pub attributes: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::missing_in_in_for_loop)] pub(crate) struct MissingInInForLoop { #[primary_span] @@ -677,7 +677,7 @@ pub(crate) enum MissingInInForLoopSub { AddIn(#[primary_span] Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::missing_comma_after_match_arm)] pub(crate) struct MissingCommaAfterMatchArm { #[primary_span] @@ -685,7 +685,7 @@ pub(crate) struct MissingCommaAfterMatchArm { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::catch_after_try)] #[help] pub(crate) struct CatchAfterTry { @@ -693,7 +693,7 @@ pub(crate) struct CatchAfterTry { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::comma_after_base_struct)] #[note] pub(crate) struct CommaAfterBaseStruct { @@ -703,7 +703,7 @@ pub(crate) struct CommaAfterBaseStruct { pub comma: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::eq_field_init)] pub(crate) struct EqFieldInit { #[primary_span] @@ -712,7 +712,7 @@ pub(crate) struct EqFieldInit { pub eq: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::dotdotdot)] pub(crate) struct DotDotDot { #[primary_span] @@ -721,7 +721,7 @@ pub(crate) struct DotDotDot { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::left_arrow_operator)] pub(crate) struct LeftArrowOperator { #[primary_span] @@ -729,7 +729,7 @@ pub(crate) struct LeftArrowOperator { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::remove_let)] pub(crate) struct RemoveLet { #[primary_span] diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index bb93f1cc260..ae77961b7bc 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -36,7 +36,7 @@ use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits}; use rustc_ast::{ClosureBinder, StmtKind}; use rustc_ast_pretty::pprust; -use rustc_errors::SessionDiagnostic; +use rustc_errors::IntoDiagnostic; use rustc_errors::{Applicability, Diagnostic, PResult}; use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP; use rustc_session::lint::BuiltinLintDiagnostics; diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 96cc8ae988c..ade5927be8e 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1,5 +1,5 @@ use rustc_errors::{Applicability, MultiSpan}; -use rustc_macros::{LintDiagnostic, SessionDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; use rustc_span::{Span, Symbol}; #[derive(LintDiagnostic)] @@ -32,7 +32,7 @@ pub struct IgnoredInlineAttrFnProto; #[note] pub struct IgnoredInlineAttrConstants; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::inline_not_fn_or_closure, code = "E0518")] pub struct InlineNotFnOrClosure { #[primary_span] @@ -53,7 +53,7 @@ pub struct IgnoredNoCoveragePropagate; #[diag(passes::no_coverage_fn_defn)] pub struct IgnoredNoCoverageFnDefn; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::no_coverage_not_coverable, code = "E0788")] pub struct IgnoredNoCoverageNotCoverable { #[primary_span] @@ -62,7 +62,7 @@ pub struct IgnoredNoCoverageNotCoverable { pub defn_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::should_be_applied_to_fn)] pub struct AttrShouldBeAppliedToFn { #[primary_span] @@ -71,14 +71,14 @@ pub struct AttrShouldBeAppliedToFn { pub defn_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::naked_tracked_caller, code = "E0736")] pub struct NakedTrackedCaller { #[primary_span] pub attr_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::should_be_applied_to_fn, code = "E0739")] pub struct TrackedCallerWrongLocation { #[primary_span] @@ -87,7 +87,7 @@ pub struct TrackedCallerWrongLocation { pub defn_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::should_be_applied_to_struct_enum, code = "E0701")] pub struct NonExhaustiveWrongLocation { #[primary_span] @@ -96,7 +96,7 @@ pub struct NonExhaustiveWrongLocation { pub defn_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::should_be_applied_to_trait)] pub struct AttrShouldBeAppliedToTrait { #[primary_span] @@ -109,7 +109,7 @@ pub struct AttrShouldBeAppliedToTrait { #[diag(passes::target_feature_on_statement)] pub struct TargetFeatureOnStatement; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::should_be_applied_to_static)] pub struct AttrShouldBeAppliedToStatic { #[primary_span] @@ -118,7 +118,7 @@ pub struct AttrShouldBeAppliedToStatic { pub defn_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_expect_str)] pub struct DocExpectStr<'a> { #[primary_span] @@ -126,7 +126,7 @@ pub struct DocExpectStr<'a> { pub attr_name: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_alias_empty)] pub struct DocAliasEmpty<'a> { #[primary_span] @@ -134,7 +134,7 @@ pub struct DocAliasEmpty<'a> { pub attr_str: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_alias_bad_char)] pub struct DocAliasBadChar<'a> { #[primary_span] @@ -143,7 +143,7 @@ pub struct DocAliasBadChar<'a> { pub char_: char, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_alias_start_end)] pub struct DocAliasStartEnd<'a> { #[primary_span] @@ -151,7 +151,7 @@ pub struct DocAliasStartEnd<'a> { pub attr_str: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_alias_bad_location)] pub struct DocAliasBadLocation<'a> { #[primary_span] @@ -160,7 +160,7 @@ pub struct DocAliasBadLocation<'a> { pub location: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_alias_not_an_alias)] pub struct DocAliasNotAnAlias<'a> { #[primary_span] @@ -175,35 +175,35 @@ pub struct DocAliasDuplicated { pub first_defn: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_alias_not_string_literal)] pub struct DocAliasNotStringLiteral { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_alias_malformed)] pub struct DocAliasMalformed { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_keyword_empty_mod)] pub struct DocKeywordEmptyMod { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_keyword_not_mod)] pub struct DocKeywordNotMod { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_keyword_invalid_ident)] pub struct DocKeywordInvalidIdent { #[primary_span] @@ -211,21 +211,21 @@ pub struct DocKeywordInvalidIdent { pub doc_keyword: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_fake_variadic_not_valid)] pub struct DocFakeVariadicNotValid { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_keyword_only_impl)] pub struct DocKeywordOnlyImpl { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_inline_conflict)] #[help] pub struct DocKeywordConflict { @@ -243,7 +243,7 @@ pub struct DocInlineOnlyUse { pub item_span: Option, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::doc_attr_not_crate_level)] pub struct DocAttrNotCrateLevel<'a> { #[primary_span] @@ -295,7 +295,7 @@ pub struct DocTestUnknownInclude { #[diag(passes::doc_invalid)] pub struct DocInvalid; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::pass_by_value)] pub struct PassByValue { #[primary_span] @@ -304,7 +304,7 @@ pub struct PassByValue { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::allow_incoherent_impl)] pub struct AllowIncoherentImpl { #[primary_span] @@ -313,7 +313,7 @@ pub struct AllowIncoherentImpl { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::has_incoherent_inherent_impl)] pub struct HasIncoherentInherentImpl { #[primary_span] @@ -336,7 +336,7 @@ pub struct MustUseNoEffect { pub target: rustc_hir::Target, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::must_not_suspend)] pub struct MustNotSuspend { #[primary_span] @@ -372,7 +372,7 @@ pub struct LinkName<'a> { pub value: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::no_link)] pub struct NoLink { #[primary_span] @@ -381,7 +381,7 @@ pub struct NoLink { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::export_name)] pub struct ExportName { #[primary_span] @@ -390,7 +390,7 @@ pub struct ExportName { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_layout_scalar_valid_range_not_struct)] pub struct RustcLayoutScalarValidRangeNotStruct { #[primary_span] @@ -399,14 +399,14 @@ pub struct RustcLayoutScalarValidRangeNotStruct { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_layout_scalar_valid_range_arg)] pub struct RustcLayoutScalarValidRangeArg { #[primary_span] pub attr_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_legacy_const_generics_only)] pub struct RustcLegacyConstGenericsOnly { #[primary_span] @@ -415,7 +415,7 @@ pub struct RustcLegacyConstGenericsOnly { pub param_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_legacy_const_generics_index)] pub struct RustcLegacyConstGenericsIndex { #[primary_span] @@ -424,7 +424,7 @@ pub struct RustcLegacyConstGenericsIndex { pub generics_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_legacy_const_generics_index_exceed)] pub struct RustcLegacyConstGenericsIndexExceed { #[primary_span] @@ -433,14 +433,14 @@ pub struct RustcLegacyConstGenericsIndexExceed { pub arg_count: usize, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_legacy_const_generics_index_negative)] pub struct RustcLegacyConstGenericsIndexNegative { #[primary_span] pub invalid_args: Vec, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_dirty_clean)] pub struct RustcDirtyClean { #[primary_span] @@ -475,7 +475,7 @@ pub struct NoMangle { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::repr_ident, code = "E0565")] pub struct ReprIdent { #[primary_span] @@ -486,21 +486,21 @@ pub struct ReprIdent { #[diag(passes::repr_conflicting, code = "E0566")] pub struct ReprConflicting; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::used_static)] pub struct UsedStatic { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::used_compiler_linker)] pub struct UsedCompilerLinker { #[primary_span] pub spans: Vec, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::allow_internal_unstable)] pub struct AllowInternalUnstable { #[primary_span] @@ -509,14 +509,14 @@ pub struct AllowInternalUnstable { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::debug_visualizer_placement)] pub struct DebugVisualizerPlacement { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::debug_visualizer_invalid)] #[note(passes::note_1)] #[note(passes::note_2)] @@ -526,7 +526,7 @@ pub struct DebugVisualizerInvalid { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_allow_const_fn_unstable)] pub struct RustcAllowConstFnUnstable { #[primary_span] @@ -535,7 +535,7 @@ pub struct RustcAllowConstFnUnstable { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_std_internal_symbol)] pub struct RustcStdInternalSymbol { #[primary_span] @@ -544,21 +544,21 @@ pub struct RustcStdInternalSymbol { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::const_trait)] pub struct ConstTrait { #[primary_span] pub attr_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::link_ordinal)] pub struct LinkOrdinal { #[primary_span] pub attr_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::stability_promotable)] pub struct StabilityPromotable { #[primary_span] @@ -602,7 +602,7 @@ pub struct Unused { pub note: UnusedNote, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::non_exported_macro_invalid_attrs, code = "E0518")] pub struct NonExportedMacroInvalidAttrs { #[primary_span] @@ -621,7 +621,7 @@ pub struct UnusedDuplicate { pub warning: Option<()>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::unused_multiple)] pub struct UnusedMultiple { #[primary_span] @@ -632,7 +632,7 @@ pub struct UnusedMultiple { pub name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_lint_opt_ty)] pub struct RustcLintOptTy { #[primary_span] @@ -641,7 +641,7 @@ pub struct RustcLintOptTy { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(passes::rustc_lint_opt_deny_field_access)] pub struct RustcLintOptDenyFieldAccess { #[primary_span] diff --git a/compiler/rustc_plugin_impl/src/errors.rs b/compiler/rustc_plugin_impl/src/errors.rs index 2bdb6e4feca..0b2c09f9e1d 100644 --- a/compiler/rustc_plugin_impl/src/errors.rs +++ b/compiler/rustc_plugin_impl/src/errors.rs @@ -1,9 +1,9 @@ //! Errors emitted by plugin_impl -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use rustc_span::Span; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(plugin_impl::load_plugin_error)] pub struct LoadPluginError { #[primary_span] @@ -11,7 +11,7 @@ pub struct LoadPluginError { pub msg: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(plugin_impl::malformed_plugin_attribute, code = "E0498")] pub struct MalformedPluginAttribute { #[primary_span] diff --git a/compiler/rustc_privacy/src/errors.rs b/compiler/rustc_privacy/src/errors.rs index 705ad567aa7..56a2cb059b5 100644 --- a/compiler/rustc_privacy/src/errors.rs +++ b/compiler/rustc_privacy/src/errors.rs @@ -1,8 +1,8 @@ use rustc_errors::DiagnosticArgFromDisplay; -use rustc_macros::{LintDiagnostic, SessionDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; use rustc_span::{Span, Symbol}; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(privacy::field_is_private, code = "E0451")] pub struct FieldIsPrivate { #[primary_span] @@ -29,7 +29,7 @@ pub enum FieldIsPrivateLabel { }, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(privacy::item_is_private)] pub struct ItemIsPrivate<'a> { #[primary_span] @@ -39,7 +39,7 @@ pub struct ItemIsPrivate<'a> { pub descr: DiagnosticArgFromDisplay<'a>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(privacy::unnamed_item_is_private)] pub struct UnnamedItemIsPrivate { #[primary_span] @@ -48,7 +48,7 @@ pub struct UnnamedItemIsPrivate { } // Duplicate of `InPublicInterface` but with a different error code, shares the same slug. -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(privacy::in_public_interface, code = "E0445")] pub struct InPublicInterfaceTraits<'a> { #[primary_span] @@ -62,7 +62,7 @@ pub struct InPublicInterfaceTraits<'a> { } // Duplicate of `InPublicInterfaceTraits` but with a different error code, shares the same slug. -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(privacy::in_public_interface, code = "E0446")] pub struct InPublicInterface<'a> { #[primary_span] @@ -75,7 +75,7 @@ pub struct InPublicInterface<'a> { pub vis_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(privacy::report_effective_visibility)] pub struct ReportEffectiveVisibility { #[primary_span] diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index bececca7585..97a74517f68 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -1,4 +1,4 @@ -use rustc_errors::AddSubdiagnostic; +use rustc_errors::AddToDiagnostic; use rustc_session::Limit; use rustc_span::{Span, Symbol}; @@ -7,7 +7,7 @@ pub struct CycleStack { pub desc: String, } -impl AddSubdiagnostic for CycleStack { +impl AddToDiagnostic for CycleStack { fn add_to_diagnostic(self, diag: &mut rustc_errors::Diagnostic) { diag.span_note(self.span, &format!("...which requires {}...", self.desc)); } @@ -46,7 +46,7 @@ pub struct CycleUsage { pub usage: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(query_system::cycle, code = "E0391")] pub struct Cycle { #[primary_span] @@ -62,11 +62,11 @@ pub struct Cycle { pub cycle_usage: Option, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(query_system::reentrant)] pub struct Reentrant; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(query_system::increment_compilation)] #[help] #[note(query_system::increment_compilation_note1)] @@ -76,7 +76,7 @@ pub struct IncrementCompilation { pub dep_node: String, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[help] #[diag(query_system::query_overflow)] pub struct QueryOverflow { @@ -88,7 +88,7 @@ pub struct QueryOverflow { pub crate_name: Symbol, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[note(query_system::layout_of_depth)] pub struct LayoutOfDepth { pub desc: String, diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 705305ff806..6d26c8f47f3 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -4,7 +4,7 @@ use crate::query::{QueryContext, QueryStackFrame}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{ - Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, Level, SessionDiagnostic, + Diagnostic, DiagnosticBuilder, IntoDiagnostic, ErrorGuaranteed, Handler, Level, }; use rustc_hir::def::DefKind; use rustc_session::Session; diff --git a/compiler/rustc_save_analysis/src/errors.rs b/compiler/rustc_save_analysis/src/errors.rs index f0ce41d02a6..0983ec2f6f7 100644 --- a/compiler/rustc_save_analysis/src/errors.rs +++ b/compiler/rustc_save_analysis/src/errors.rs @@ -1,8 +1,8 @@ -use rustc_macros::SessionDiagnostic; +use rustc_macros::DiagnosticHandler; use std::path::Path; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(save_analysis::could_not_open)] pub(crate) struct CouldNotOpen<'a> { pub file_name: &'a Path, diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index c6596ff2498..4cf46109895 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -8,7 +8,7 @@ use rustc_span::{Span, Symbol}; use rustc_target::abi::TargetDataLayoutErrors; use rustc_target::spec::{SplitDebuginfo, StackProtector, TargetTriple}; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(session::incorrect_cgu_reuse_type)] pub struct IncorrectCguReuseType<'a> { #[primary_span] @@ -19,14 +19,14 @@ pub struct IncorrectCguReuseType<'a> { pub at_least: u8, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(session::cgu_not_recorded)] pub struct CguNotRecorded<'a> { pub cgu_user_name: &'a str, pub cgu_name: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(session::feature_gate_error, code = "E0658")] pub struct FeatureGateError<'a> { #[primary_span] @@ -46,19 +46,19 @@ pub struct FeatureDiagnosticHelp { pub feature: Symbol, } -impl SessionDiagnostic<'_, !> for TargetDataLayoutErrors<'_> { - fn into_diagnostic(self, sess: &Handler) -> DiagnosticBuilder<'_, !> { +impl DiagnosticHandler<'_, !> for TargetDataLayoutErrors<'_> { + fn into_diagnostic(self, handler: &Handler) -> DiagnosticBuilder<'_, !> { let mut diag; match self { TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => { - diag = sess.struct_fatal(fluent::session::target_invalid_address_space); + diag = handler.struct_fatal(fluent::session::target_invalid_address_space); diag.set_arg("addr_space", addr_space); diag.set_arg("cause", cause); diag.set_arg("err", err); diag } TargetDataLayoutErrors::InvalidBits { kind, bit, cause, err } => { - diag = sess.struct_fatal(fluent::session::target_invalid_bits); + diag = handler.struct_fatal(fluent::session::target_invalid_bits); diag.set_arg("kind", kind); diag.set_arg("bit", bit); diag.set_arg("cause", cause); @@ -66,30 +66,30 @@ impl SessionDiagnostic<'_, !> for TargetDataLayoutErrors<'_> { diag } TargetDataLayoutErrors::MissingAlignment { cause } => { - diag = sess.struct_fatal(fluent::session::target_missing_alignment); + diag = handler.struct_fatal(fluent::session::target_missing_alignment); diag.set_arg("cause", cause); diag } TargetDataLayoutErrors::InvalidAlignment { cause, err } => { - diag = sess.struct_fatal(fluent::session::target_invalid_alignment); + diag = handler.struct_fatal(fluent::session::target_invalid_alignment); diag.set_arg("cause", cause); diag.set_arg("err", err); diag } TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => { - diag = sess.struct_fatal(fluent::session::target_inconsistent_architecture); + diag = handler.struct_fatal(fluent::session::target_inconsistent_architecture); diag.set_arg("dl", dl); diag.set_arg("target", target); diag } TargetDataLayoutErrors::InconsistentTargetPointerWidth { pointer_size, target } => { - diag = sess.struct_fatal(fluent::session::target_inconsistent_pointer_width); + diag = handler.struct_fatal(fluent::session::target_inconsistent_pointer_width); diag.set_arg("pointer_size", pointer_size); diag.set_arg("target", target); diag } TargetDataLayoutErrors::InvalidBitsSize { err } => { - diag = sess.struct_fatal(fluent::session::target_invalid_bits_size); + diag = handler.struct_fatal(fluent::session::target_invalid_bits_size); diag.set_arg("err", err); diag } diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 564629a6703..3189dcb08ad 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -11,8 +11,8 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::sync::{Lock, Lrc}; use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler}; use rustc_errors::{ - fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId, - DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, MultiSpan, SessionDiagnostic, StashKey, + fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder, IntoDiagnostic, + DiagnosticId, DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, MultiSpan, StashKey, }; use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures}; use rustc_span::edition::Edition; @@ -344,34 +344,34 @@ impl ParseSess { pub fn create_err<'a>( &'a self, - err: impl SessionDiagnostic<'a>, + err: impl IntoDiagnostic<'a>, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { err.into_diagnostic(&self.span_diagnostic) } - pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed { + pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed { self.create_err(err).emit() } pub fn create_warning<'a>( &'a self, - warning: impl SessionDiagnostic<'a, ()>, + warning: impl IntoDiagnostic<'a, ()>, ) -> DiagnosticBuilder<'a, ()> { warning.into_diagnostic(&self.span_diagnostic) } - pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) { + pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) { self.create_warning(warning).emit() } pub fn create_fatal<'a>( &'a self, - fatal: impl SessionDiagnostic<'a, !>, + fatal: impl IntoDiagnostic<'a, !>, ) -> DiagnosticBuilder<'a, !> { fatal.into_diagnostic(&self.span_diagnostic) } - pub fn emit_fatal<'a>(&'a self, fatal: impl SessionDiagnostic<'a, !>) -> ! { + pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! { self.create_fatal(fatal).emit() } diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 6a5a89747df..e660b739928 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -27,8 +27,8 @@ use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType}; use rustc_errors::json::JsonEmitter; use rustc_errors::registry::Registry; use rustc_errors::{ - error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, - ErrorGuaranteed, FluentBundle, LazyFallbackBundle, MultiSpan, SessionDiagnostic, + error_code, fallback_fluent_bundle, DiagnosticBuilder, IntoDiagnostic, DiagnosticId, + DiagnosticMessage, ErrorGuaranteed, FluentBundle, LazyFallbackBundle, MultiSpan, }; use rustc_macros::HashStable_Generic; pub use rustc_span::def_id::StableCrateId; @@ -505,13 +505,13 @@ impl Session { } pub fn create_err<'a>( &'a self, - err: impl SessionDiagnostic<'a>, + err: impl IntoDiagnostic<'a>, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { self.parse_sess.create_err(err) } pub fn create_feature_err<'a>( &'a self, - err: impl SessionDiagnostic<'a>, + err: impl IntoDiagnostic<'a>, feature: Symbol, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { let mut err = self.parse_sess.create_err(err); @@ -521,25 +521,25 @@ impl Session { add_feature_diagnostics(&mut err, &self.parse_sess, feature); err } - pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed { + pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed { self.parse_sess.emit_err(err) } pub fn create_warning<'a>( &'a self, - err: impl SessionDiagnostic<'a, ()>, + err: impl IntoDiagnostic<'a, ()>, ) -> DiagnosticBuilder<'a, ()> { self.parse_sess.create_warning(err) } - pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) { + pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) { self.parse_sess.emit_warning(warning) } pub fn create_fatal<'a>( &'a self, - fatal: impl SessionDiagnostic<'a, !>, + fatal: impl IntoDiagnostic<'a, !>, ) -> DiagnosticBuilder<'a, !> { self.parse_sess.create_fatal(fatal) } - pub fn emit_fatal<'a>(&'a self, fatal: impl SessionDiagnostic<'a, !>) -> ! { + pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! { self.parse_sess.emit_fatal(fatal) } #[inline] diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 562360130e9..98ff9694808 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -177,6 +177,7 @@ symbols! { DecorateLint, Default, Deref, + DiagnosticHandler, DiagnosticMessage, DirBuilder, Display, @@ -277,7 +278,6 @@ symbols! { RwLockWriteGuard, Send, SeqCst, - SessionDiagnostic, SliceIndex, Some, String, diff --git a/compiler/rustc_symbol_mangling/src/errors.rs b/compiler/rustc_symbol_mangling/src/errors.rs index 664d2543f1f..eb487a03c93 100644 --- a/compiler/rustc_symbol_mangling/src/errors.rs +++ b/compiler/rustc_symbol_mangling/src/errors.rs @@ -1,10 +1,10 @@ //! Errors emitted by symbol_mangling. use rustc_errors::{DiagnosticArgValue, IntoDiagnosticArg}; -use rustc_macros::SessionDiagnostic; +use rustc_macros::Diagnostic; use rustc_span::Span; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(symbol_mangling::test_output)] pub struct TestOutput { #[primary_span] diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index dc7078d9ada..f62bdb00ee0 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -1,10 +1,10 @@ -use rustc_errors::{fluent, ErrorGuaranteed, Handler, SessionDiagnostic}; -use rustc_macros::SessionDiagnostic; +use rustc_errors::{fluent, IntoDiagnostic, ErrorGuaranteed, Handler}; +use rustc_macros::DiagnosticHandler; use rustc_middle::ty::{PolyTraitRef, Ty, Unevaluated}; use rustc_session::Limit; use rustc_span::{Span, Symbol}; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(trait_selection::dump_vtable_entries)] pub struct DumpVTableEntries<'a> { #[primary_span] @@ -13,7 +13,7 @@ pub struct DumpVTableEntries<'a> { pub entries: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(trait_selection::unable_to_construct_constant_value)] pub struct UnableToConstructConstantValue<'a> { #[primary_span] @@ -21,7 +21,7 @@ pub struct UnableToConstructConstantValue<'a> { pub unevaluated: Unevaluated<'a>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[help] #[diag(trait_selection::auto_deref_reached_recursion_limit, code = "E0055")] pub struct AutoDerefReachedRecursionLimit<'a> { @@ -33,7 +33,7 @@ pub struct AutoDerefReachedRecursionLimit<'a> { pub crate_name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(trait_selection::empty_on_clause_in_rustc_on_unimplemented, code = "E0232")] pub struct EmptyOnClauseInOnUnimplemented { #[primary_span] @@ -41,7 +41,7 @@ pub struct EmptyOnClauseInOnUnimplemented { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(trait_selection::invalid_on_clause_in_rustc_on_unimplemented, code = "E0232")] pub struct InvalidOnClauseInOnUnimplemented { #[primary_span] @@ -49,7 +49,7 @@ pub struct InvalidOnClauseInOnUnimplemented { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(trait_selection::no_value_in_rustc_on_unimplemented, code = "E0232")] #[note] pub struct NoValueInOnUnimplemented { @@ -66,7 +66,7 @@ pub struct NegativePositiveConflict<'a> { pub positive_impl_span: Result, } -impl SessionDiagnostic<'_> for NegativePositiveConflict<'_> { +impl IntoDiagnostic<'_> for NegativePositiveConflict<'_> { fn into_diagnostic( self, handler: &Handler, diff --git a/compiler/rustc_ty_utils/src/errors.rs b/compiler/rustc_ty_utils/src/errors.rs index 3a8ef96c991..995e87bcd3b 100644 --- a/compiler/rustc_ty_utils/src/errors.rs +++ b/compiler/rustc_ty_utils/src/errors.rs @@ -1,16 +1,16 @@ //! Errors emitted by ty_utils -use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::Span; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(ty_utils::needs_drop_overflow)] pub struct NeedsDropOverflow<'tcx> { pub query_ty: Ty<'tcx>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(ty_utils::generic_constant_too_complex)] #[help] pub struct GenericConstantTooComplex { diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 93b00850069..11661b8ef6c 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -881,7 +881,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } - // FIXME: Make this use SessionDiagnostic once error codes can be dynamically set. + // FIXME: Make this use DiagnosticHandler once error codes can be dynamically set. let mut err = self.tcx.sess.struct_span_err_with_code( op_span, "invalid left-hand side of assignment", diff --git a/compiler/rustc_typeck/src/errors.rs b/compiler/rustc_typeck/src/errors.rs index ed4c4f688bf..50d400e2921 100644 --- a/compiler/rustc_typeck/src/errors.rs +++ b/compiler/rustc_typeck/src/errors.rs @@ -1,11 +1,11 @@ //! Errors emitted by typeck. -use rustc_errors::SessionDiagnostic; +use rustc_errors::IntoDiagnostic; use rustc_errors::{error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler}; -use rustc_macros::{LintDiagnostic, SessionDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::{symbol::Ident, Span, Symbol}; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::field_multiply_specified_in_initializer, code = "E0062")] pub struct FieldMultiplySpecifiedInInitializer { #[primary_span] @@ -16,7 +16,7 @@ pub struct FieldMultiplySpecifiedInInitializer { pub ident: Ident, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::unrecognized_atomic_operation, code = "E0092")] pub struct UnrecognizedAtomicOperation<'a> { #[primary_span] @@ -25,7 +25,7 @@ pub struct UnrecognizedAtomicOperation<'a> { pub op: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::wrong_number_of_generic_arguments_to_intrinsic, code = "E0094")] pub struct WrongNumberOfGenericArgumentsToIntrinsic<'a> { #[primary_span] @@ -36,7 +36,7 @@ pub struct WrongNumberOfGenericArgumentsToIntrinsic<'a> { pub descr: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::unrecognized_intrinsic_function, code = "E0093")] pub struct UnrecognizedIntrinsicFunction { #[primary_span] @@ -45,7 +45,7 @@ pub struct UnrecognizedIntrinsicFunction { pub name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::lifetimes_or_bounds_mismatch_on_trait, code = "E0195")] pub struct LifetimesOrBoundsMismatchOnTrait { #[primary_span] @@ -57,7 +57,7 @@ pub struct LifetimesOrBoundsMismatchOnTrait { pub ident: Ident, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::drop_impl_on_wrong_item, code = "E0120")] pub struct DropImplOnWrongItem { #[primary_span] @@ -65,7 +65,7 @@ pub struct DropImplOnWrongItem { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::field_already_declared, code = "E0124")] pub struct FieldAlreadyDeclared { pub field_name: Ident, @@ -76,7 +76,7 @@ pub struct FieldAlreadyDeclared { pub prev_span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::copy_impl_on_type_with_dtor, code = "E0184")] pub struct CopyImplOnTypeWithDtor { #[primary_span] @@ -84,14 +84,14 @@ pub struct CopyImplOnTypeWithDtor { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::multiple_relaxed_default_bounds, code = "E0203")] pub struct MultipleRelaxedDefaultBounds { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::copy_impl_on_non_adt, code = "E0206")] pub struct CopyImplOnNonAdt { #[primary_span] @@ -99,7 +99,7 @@ pub struct CopyImplOnNonAdt { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::trait_object_declared_with_no_traits, code = "E0224")] pub struct TraitObjectDeclaredWithNoTraits { #[primary_span] @@ -108,14 +108,14 @@ pub struct TraitObjectDeclaredWithNoTraits { pub trait_alias_span: Option, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0227")] pub struct AmbiguousLifetimeBound { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::assoc_type_binding_not_allowed, code = "E0229")] pub struct AssocTypeBindingNotAllowed { #[primary_span] @@ -123,14 +123,14 @@ pub struct AssocTypeBindingNotAllowed { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::functional_record_update_on_non_struct, code = "E0436")] pub struct FunctionalRecordUpdateOnNonStruct { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::typeof_reserved_keyword_used, code = "E0516")] pub struct TypeofReservedKeywordUsed<'tcx> { pub ty: Ty<'tcx>, @@ -141,7 +141,7 @@ pub struct TypeofReservedKeywordUsed<'tcx> { pub opt_sugg: Option<(Span, Applicability)>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::return_stmt_outside_of_fn_body, code = "E0572")] pub struct ReturnStmtOutsideOfFnBody { #[primary_span] @@ -152,14 +152,14 @@ pub struct ReturnStmtOutsideOfFnBody { pub encl_fn_span: Option, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::yield_expr_outside_of_generator, code = "E0627")] pub struct YieldExprOutsideOfGenerator { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::struct_expr_non_exhaustive, code = "E0639")] pub struct StructExprNonExhaustive { #[primary_span] @@ -167,14 +167,14 @@ pub struct StructExprNonExhaustive { pub what: &'static str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::method_call_on_unknown_type, code = "E0699")] pub struct MethodCallOnUnknownType { #[primary_span] pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::value_of_associated_struct_already_specified, code = "E0719")] pub struct ValueOfAssociatedStructAlreadySpecified { #[primary_span] @@ -186,7 +186,7 @@ pub struct ValueOfAssociatedStructAlreadySpecified { pub def_path: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::address_of_temporary_taken, code = "E0745")] pub struct AddressOfTemporaryTaken { #[primary_span] @@ -232,7 +232,7 @@ pub enum ExpectedReturnTypeLabel<'tcx> { }, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::unconstrained_opaque_type)] #[note] pub struct UnconstrainedOpaqueType { @@ -249,8 +249,8 @@ pub struct MissingTypeParams { pub empty_generic_args: bool, } -// Manual implementation of `SessionDiagnostic` to be able to call `span_to_snippet`. -impl<'a> SessionDiagnostic<'a> for MissingTypeParams { +// Manual implementation of `DiagnosticHandler` to be able to call `span_to_snippet`. +impl<'a> IntoDiagnostic<'a> for MissingTypeParams { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { let mut err = handler.struct_span_err_with_code( self.span, @@ -306,7 +306,7 @@ impl<'a> SessionDiagnostic<'a> for MissingTypeParams { } } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::manual_implementation, code = "E0183")] #[help] pub struct ManualImplementation { @@ -316,7 +316,7 @@ pub struct ManualImplementation { pub trait_name: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::substs_on_overridden_impl)] pub struct SubstsOnOverriddenImpl { #[primary_span] @@ -339,7 +339,7 @@ pub struct ExternCrateNotIdiomatic { pub suggestion_code: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::expected_used_symbol)] pub struct ExpectedUsedSymbol { #[primary_span] diff --git a/src/test/ui-fulldeps/internal-lints/diagnostics.rs b/src/test/ui-fulldeps/internal-lints/diagnostics.rs index 3b31a290449..1ead987ec41 100644 --- a/src/test/ui-fulldeps/internal-lints/diagnostics.rs +++ b/src/test/ui-fulldeps/internal-lints/diagnostics.rs @@ -12,12 +12,13 @@ extern crate rustc_session; extern crate rustc_span; use rustc_errors::{ - AddSubdiagnostic, SessionDiagnostic, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, fluent + AddSubdiagnostic, IntoDiagnostic, Diagnostic, DiagnosticBuilder, + ErrorGuaranteed, Handler, fluent }; -use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; use rustc_span::Span; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(parser::expect_path)] struct DeriveSessionDiagnostic { #[primary_span] @@ -33,7 +34,7 @@ struct Note { pub struct UntranslatableInSessionDiagnostic; -impl<'a> SessionDiagnostic<'a, ErrorGuaranteed> for UntranslatableInSessionDiagnostic { +impl<'a> IntoDiagnostic<'a, ErrorGuaranteed> for UntranslatableInSessionDiagnostic { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { handler.struct_err("untranslatable diagnostic") //~^ ERROR diagnostics should be created using translatable messages @@ -42,7 +43,7 @@ impl<'a> SessionDiagnostic<'a, ErrorGuaranteed> for UntranslatableInSessionDiagn pub struct TranslatableInSessionDiagnostic; -impl<'a> SessionDiagnostic<'a, ErrorGuaranteed> for TranslatableInSessionDiagnostic { +impl<'a> IntoDiagnostic<'a, ErrorGuaranteed> for TranslatableInSessionDiagnostic { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { handler.struct_err(fluent::parser::expect_path) } @@ -67,10 +68,10 @@ impl AddSubdiagnostic for TranslatableInAddSubdiagnostic { pub fn make_diagnostics<'a>(handler: &'a Handler) { let _diag = handler.struct_err(fluent::parser::expect_path); - //~^ ERROR diagnostics should only be created in `SessionDiagnostic`/`AddSubdiagnostic` impls + //~^ ERROR diagnostics should only be created in `IntoDiagnostic`/`AddSubdiagnostic` impls let _diag = handler.struct_err("untranslatable diagnostic"); - //~^ ERROR diagnostics should only be created in `SessionDiagnostic`/`AddSubdiagnostic` impls + //~^ ERROR diagnostics should only be created in `IntoDiagnostic`/`AddSubdiagnostic` impls //~^^ ERROR diagnostics should be created using translatable messages } diff --git a/src/test/ui-fulldeps/internal-lints/diagnostics.stderr b/src/test/ui-fulldeps/internal-lints/diagnostics.stderr index e5c5bc2e998..d5833cf3970 100644 --- a/src/test/ui-fulldeps/internal-lints/diagnostics.stderr +++ b/src/test/ui-fulldeps/internal-lints/diagnostics.stderr @@ -16,7 +16,7 @@ error: diagnostics should be created using translatable messages LL | diag.note("untranslatable diagnostic"); | ^^^^ -error: diagnostics should only be created in `SessionDiagnostic`/`AddSubdiagnostic` impls +error: diagnostics should only be created in `IntoDiagnostic`/`AddSubdiagnostic` impls --> $DIR/diagnostics.rs:70:25 | LL | let _diag = handler.struct_err(fluent::parser::expect_path); @@ -28,7 +28,7 @@ note: the lint level is defined here LL | #![deny(rustc::diagnostic_outside_of_impl)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: diagnostics should only be created in `SessionDiagnostic`/`AddSubdiagnostic` impls +error: diagnostics should only be created in `IntoDiagnostic`/`AddSubdiagnostic` impls --> $DIR/diagnostics.rs:73:25 | LL | let _diag = handler.struct_err("untranslatable diagnostic"); diff --git a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs index c1c109ac1ea..32ba5be8963 100644 --- a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs +++ b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs @@ -1,10 +1,10 @@ // check-fail -// Tests error conditions for specifying diagnostics using #[derive(SessionDiagnostic)] +// Tests error conditions for specifying diagnostics using #[derive(DiagnosticHandler)] // normalize-stderr-test "the following other types implement trait `IntoDiagnosticArg`:(?:.*\n){0,9}\s+and \d+ others" -> "normalized in stderr" // normalize-stderr-test "diagnostic_builder\.rs:[0-9]+:[0-9]+" -> "diagnostic_builder.rs:LL:CC" // The proc_macro2 crate handles spans differently when on beta/stable release rather than nightly, -// changing the output of this test. Since SessionDiagnostic is strictly internal to the compiler +// changing the output of this test. Since DiagnosticHandler is strictly internal to the compiler // the test is just ignored on stable and beta: // ignore-beta // ignore-stable @@ -17,7 +17,7 @@ use rustc_span::symbol::Ident; use rustc_span::Span; extern crate rustc_macros; -use rustc_macros::{SessionDiagnostic, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; extern crate rustc_middle; use rustc_middle::ty::Ty; @@ -27,70 +27,70 @@ use rustc_errors::{Applicability, MultiSpan}; extern crate rustc_session; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct Hello {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct HelloWarn {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] -//~^ ERROR `#[derive(SessionDiagnostic)]` can only be used on structs -enum SessionDiagnosticOnEnum { +//~^ ERROR `#[derive(DiagnosticHandler)]` can only be used on structs +enum DiagnosticHandlerOnEnum { Foo, Bar, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[diag = "E0123"] //~^ ERROR `#[diag = ...]` is not a valid attribute struct WrongStructAttrStyle {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[nonsense(typeck::ambiguous_lifetime_bound, code = "E0123")] //~^ ERROR `#[nonsense(...)]` is not a valid attribute //~^^ ERROR diagnostic slug not specified //~^^^ ERROR cannot find attribute `nonsense` in this scope struct InvalidStructAttr {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag("E0123")] //~^ ERROR `#[diag("...")]` is not a valid attribute //~^^ ERROR diagnostic slug not specified struct InvalidLitNestedAttr {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(nonsense, code = "E0123")] //~^ ERROR cannot find value `nonsense` in module `rustc_errors::fluent` struct InvalidNestedStructAttr {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(nonsense("foo"), code = "E0123", slug = "foo")] //~^ ERROR `#[diag(nonsense(...))]` is not a valid attribute //~^^ ERROR diagnostic slug not specified struct InvalidNestedStructAttr1 {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(nonsense = "...", code = "E0123", slug = "foo")] //~^ ERROR `#[diag(nonsense = ...)]` is not a valid attribute //~^^ ERROR diagnostic slug not specified struct InvalidNestedStructAttr2 {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(nonsense = 4, code = "E0123", slug = "foo")] //~^ ERROR `#[diag(nonsense = ...)]` is not a valid attribute //~^^ ERROR diagnostic slug not specified struct InvalidNestedStructAttr3 {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123", slug = "foo")] //~^ ERROR `#[diag(slug = ...)]` is not a valid attribute struct InvalidNestedStructAttr4 {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct WrongPlaceField { #[suggestion = "bar"] @@ -98,36 +98,36 @@ struct WrongPlaceField { sp: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[diag(typeck::ambiguous_lifetime_bound, code = "E0456")] //~^ ERROR specified multiple times //~^^ ERROR specified multiple times struct DiagSpecifiedTwice {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0456", code = "E0457")] //~^ ERROR specified multiple times struct CodeSpecifiedTwice {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, typeck::ambiguous_lifetime_bound, code = "E0456")] //~^ ERROR `#[diag(typeck::ambiguous_lifetime_bound)]` is not a valid attribute struct SlugSpecifiedTwice {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] struct KindNotProvided {} //~ ERROR diagnostic slug not specified -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(code = "E0456")] //~^ ERROR diagnostic slug not specified struct SlugNotProvided {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound)] struct CodeNotProvided {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct MessageWrongType { #[primary_span] @@ -135,7 +135,7 @@ struct MessageWrongType { foo: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct InvalidPathFieldAttr { #[nonsense] @@ -144,7 +144,7 @@ struct InvalidPathFieldAttr { foo: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithField { name: String, @@ -152,7 +152,7 @@ struct ErrorWithField { span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithMessageAppliedToField { #[label(typeck::label)] @@ -160,7 +160,7 @@ struct ErrorWithMessageAppliedToField { name: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithNonexistentField { #[suggestion(typeck::suggestion, code = "{name}")] @@ -168,7 +168,7 @@ struct ErrorWithNonexistentField { suggestion: (Span, Applicability), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] //~^ ERROR invalid format string: expected `'}'` #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorMissingClosingBrace { @@ -178,7 +178,7 @@ struct ErrorMissingClosingBrace { val: usize, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] //~^ ERROR invalid format string: unmatched `}` #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorMissingOpeningBrace { @@ -188,14 +188,14 @@ struct ErrorMissingOpeningBrace { val: usize, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelOnSpan { #[label(typeck::label)] sp: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelOnNonSpan { #[label(typeck::label)] @@ -203,7 +203,7 @@ struct LabelOnNonSpan { id: u32, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct Suggest { #[suggestion(typeck::suggestion, code = "This is the suggested code")] @@ -213,14 +213,14 @@ struct Suggest { suggestion: (Span, Applicability), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithoutCode { #[suggestion(typeck::suggestion)] suggestion: (Span, Applicability), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithBadKey { #[suggestion(nonsense = "bar")] @@ -228,7 +228,7 @@ struct SuggestWithBadKey { suggestion: (Span, Applicability), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithShorthandMsg { #[suggestion(msg = "bar")] @@ -236,21 +236,21 @@ struct SuggestWithShorthandMsg { suggestion: (Span, Applicability), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithoutMsg { #[suggestion(code = "bar")] suggestion: (Span, Applicability), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithTypesSwapped { #[suggestion(typeck::suggestion, code = "This is suggested code")] suggestion: (Applicability, Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithWrongTypeApplicabilityOnly { #[suggestion(typeck::suggestion, code = "This is suggested code")] @@ -258,14 +258,14 @@ struct SuggestWithWrongTypeApplicabilityOnly { suggestion: Applicability, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithSpanOnly { #[suggestion(typeck::suggestion, code = "This is suggested code")] suggestion: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithDuplicateSpanAndApplicability { #[suggestion(typeck::suggestion, code = "This is suggested code")] @@ -273,7 +273,7 @@ struct SuggestWithDuplicateSpanAndApplicability { suggestion: (Span, Span, Applicability), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithDuplicateApplicabilityAndSpan { #[suggestion(typeck::suggestion, code = "This is suggested code")] @@ -281,7 +281,7 @@ struct SuggestWithDuplicateApplicabilityAndSpan { suggestion: (Applicability, Applicability, Span), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct WrongKindOfAnnotation { #[label = "bar"] @@ -289,7 +289,7 @@ struct WrongKindOfAnnotation { z: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct OptionsInErrors { #[label(typeck::label)] @@ -298,7 +298,7 @@ struct OptionsInErrors { opt_sugg: Option<(Span, Applicability)>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0456")] struct MoveOutOfBorrowError<'tcx> { name: Ident, @@ -312,7 +312,7 @@ struct MoveOutOfBorrowError<'tcx> { opt_sugg: Option<(Span, Applicability)>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithLifetime<'a> { #[label(typeck::label)] @@ -320,7 +320,7 @@ struct ErrorWithLifetime<'a> { name: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithDefaultLabelAttr<'a> { #[label] @@ -328,7 +328,7 @@ struct ErrorWithDefaultLabelAttr<'a> { name: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] //~^ ERROR the trait bound `Hello: IntoDiagnosticArg` is not satisfied #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ArgFieldWithoutSkip { @@ -337,7 +337,7 @@ struct ArgFieldWithoutSkip { other: Hello, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ArgFieldWithSkip { #[primary_span] @@ -348,91 +348,91 @@ struct ArgFieldWithSkip { other: Hello, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithSpannedNote { #[note] span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithSpannedNoteCustom { #[note(typeck::note)] span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[note] struct ErrorWithNote { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[note(typeck::note)] struct ErrorWithNoteCustom { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithSpannedHelp { #[help] span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithSpannedHelpCustom { #[help(typeck::help)] span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[help] struct ErrorWithHelp { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[help(typeck::help)] struct ErrorWithHelpCustom { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[help] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithHelpWrongOrder { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[help(typeck::help)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithHelpCustomWrongOrder { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[note] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithNoteWrongOrder { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[note(typeck::note)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithNoteCustomWrongOrder { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ApplicabilityInBoth { #[suggestion(typeck::suggestion, code = "...", applicability = "maybe-incorrect")] @@ -440,7 +440,7 @@ struct ApplicabilityInBoth { suggestion: (Span, Applicability), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct InvalidApplicability { #[suggestion(typeck::suggestion, code = "...", applicability = "batman")] @@ -448,14 +448,14 @@ struct InvalidApplicability { suggestion: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ValidApplicability { #[suggestion(typeck::suggestion, code = "...", applicability = "maybe-incorrect")] suggestion: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct NoApplicability { #[suggestion(typeck::suggestion, code = "...")] @@ -466,14 +466,14 @@ struct NoApplicability { #[note(parser::add_paren)] struct Note; -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound)] struct Subdiagnostic { #[subdiagnostic] note: Note, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct VecField { #[primary_span] @@ -481,7 +481,7 @@ struct VecField { spans: Vec, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct UnitField { #[primary_span] @@ -492,7 +492,7 @@ struct UnitField { bar: (), } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct OptUnitField { #[primary_span] @@ -503,7 +503,7 @@ struct OptUnitField { bar: Option<()>, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelWithTrailingPath { #[label(typeck::label, foo)] @@ -511,7 +511,7 @@ struct LabelWithTrailingPath { span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelWithTrailingNameValue { #[label(typeck::label, foo = "...")] @@ -519,7 +519,7 @@ struct LabelWithTrailingNameValue { span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelWithTrailingList { #[label(typeck::label, foo("..."))] @@ -540,35 +540,35 @@ struct PrimarySpanOnLint { span: Span, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithMultiSpan { #[primary_span] span: MultiSpan, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[warning] struct ErrorWithWarn { val: String, } -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[error(typeck::ambiguous_lifetime_bound, code = "E0123")] //~^ ERROR `#[error(...)]` is not a valid attribute //~| ERROR diagnostic slug not specified //~| ERROR cannot find attribute `error` in this scope struct ErrorAttribute {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[warn_(typeck::ambiguous_lifetime_bound, code = "E0123")] //~^ ERROR `#[warn_(...)]` is not a valid attribute //~| ERROR diagnostic slug not specified //~| ERROR cannot find attribute `warn_` in this scope struct WarnAttribute {} -#[derive(SessionDiagnostic)] +#[derive(DiagnosticHandler)] #[lint(typeck::ambiguous_lifetime_bound, code = "E0123")] //~^ ERROR `#[lint(...)]` is not a valid attribute //~| ERROR diagnostic slug not specified diff --git a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr index ab5c28fe473..d9198d4ef80 100644 --- a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr +++ b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr @@ -1,9 +1,9 @@ -error: `#[derive(SessionDiagnostic)]` can only be used on structs +error: `#[derive(DiagnosticHandler)]` can only be used on structs --> $DIR/diagnostic-derive.rs:39:1 | LL | / #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] LL | | -LL | | enum SessionDiagnosticOnEnum { +LL | | enum DiagnosticHandlerOnEnum { LL | | Foo, LL | | Bar, LL | | } @@ -214,22 +214,22 @@ LL | #[suggestion(typeck::suggestion, code = "{name}")] error: invalid format string: expected `'}'` but string was terminated --> $DIR/diagnostic-derive.rs:171:16 | -LL | #[derive(SessionDiagnostic)] +LL | #[derive(DiagnosticHandler)] | - ^ expected `'}'` in format string | | | because of this opening brace | = note: if you intended to print `{`, you can escape it using `{{` - = note: this error originates in the derive macro `SessionDiagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the derive macro `DiagnosticHandler` (in Nightly builds, run with -Z macro-backtrace for more info) error: invalid format string: unmatched `}` found --> $DIR/diagnostic-derive.rs:181:15 | -LL | #[derive(SessionDiagnostic)] +LL | #[derive(DiagnosticHandler)] | ^ unmatched `}` in format string | = note: if you intended to print `}`, you can escape it using `}}` - = note: this error originates in the derive macro `SessionDiagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the derive macro `DiagnosticHandler` (in Nightly builds, run with -Z macro-backtrace for more info) error: the `#[label(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` --> $DIR/diagnostic-derive.rs:201:5 @@ -448,7 +448,7 @@ LL | #[diag(nonsense, code = "E0123")] error[E0277]: the trait bound `Hello: IntoDiagnosticArg` is not satisfied --> $DIR/diagnostic-derive.rs:331:10 | -LL | #[derive(SessionDiagnostic)] +LL | #[derive(DiagnosticHandler)] | ^^^^^^^^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `Hello` | = help: normalized in stderr @@ -457,7 +457,7 @@ note: required by a bound in `DiagnosticBuilder::<'a, G>::set_arg` | LL | arg: impl IntoDiagnosticArg, | ^^^^^^^^^^^^^^^^^ required by this bound in `DiagnosticBuilder::<'a, G>::set_arg` - = note: this error originates in the derive macro `SessionDiagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the derive macro `DiagnosticHandler` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 55 previous errors -- cgit 1.4.1-3-g733a5 From a3396b207093c01065b63b0c58f1e6654629166d Mon Sep 17 00:00:00 2001 From: Jhonny Bill Mena Date: Sun, 18 Sep 2022 11:46:56 -0400 Subject: UPDATE - rename DiagnosticHandler macro to Diagnostic --- compiler/rustc_ast_lowering/src/errors.rs | 66 ++++----- compiler/rustc_attr/src/session_diagnostics.rs | 60 ++++---- compiler/rustc_borrowck/src/session_diagnostics.rs | 16 +-- compiler/rustc_builtin_macros/src/cfg.rs | 6 +- compiler/rustc_const_eval/src/errors.rs | 44 +++--- compiler/rustc_driver/src/session_diagnostics.rs | 16 +-- compiler/rustc_errors/src/diagnostic_builder.rs | 4 +- compiler/rustc_expand/src/errors.rs | 14 +- compiler/rustc_interface/src/errors.rs | 30 ++-- compiler/rustc_lint/src/errors.rs | 18 +-- compiler/rustc_lint/src/internal.rs | 4 +- .../rustc_macros/src/diagnostics/diagnostic.rs | 4 +- .../src/diagnostics/diagnostic_builder.rs | 6 +- compiler/rustc_macros/src/diagnostics/mod.rs | 6 +- compiler/rustc_macros/src/lib.rs | 2 +- compiler/rustc_metadata/src/errors.rs | 154 ++++++++++----------- compiler/rustc_middle/src/error.rs | 8 +- compiler/rustc_mir_dataflow/src/errors.rs | 22 +-- compiler/rustc_monomorphize/src/errors.rs | 12 +- compiler/rustc_parse/src/parser/diagnostics.rs | 84 +++++------ compiler/rustc_passes/src/errors.rs | 104 +++++++------- compiler/rustc_plugin_impl/src/errors.rs | 6 +- compiler/rustc_privacy/src/errors.rs | 12 +- compiler/rustc_query_system/src/error.rs | 6 +- compiler/rustc_save_analysis/src/errors.rs | 4 +- compiler/rustc_session/src/errors.rs | 8 +- compiler/rustc_span/src/symbol.rs | 2 +- compiler/rustc_trait_selection/src/errors.rs | 14 +- compiler/rustc_ty_utils/src/errors.rs | 6 +- compiler/rustc_typeck/src/check/expr.rs | 2 +- compiler/rustc_typeck/src/errors.rs | 54 ++++---- src/test/ui-fulldeps/internal-lints/diagnostics.rs | 4 +- .../session-diagnostic/diagnostic-derive.rs | 154 ++++++++++----------- .../session-diagnostic/diagnostic-derive.stderr | 16 +-- 34 files changed, 484 insertions(+), 484 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index 75f20b07277..6dbb2582a37 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -1,8 +1,8 @@ use rustc_errors::{fluent, AddToDiagnostic, Applicability, Diagnostic, DiagnosticArgFromDisplay}; -use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, SessionSubdiagnostic}; use rustc_span::{symbol::Ident, Span, Symbol}; -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::generic_type_with_parentheses, code = "E0214")] pub struct GenericTypeWithParentheses { #[primary_span] @@ -28,7 +28,7 @@ impl AddToDiagnostic for UseAngleBrackets { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[help] #[diag(ast_lowering::invalid_abi, code = "E0703")] pub struct InvalidAbi { @@ -39,7 +39,7 @@ pub struct InvalidAbi { pub valid_abis: String, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::assoc_ty_parentheses)] pub struct AssocTyParentheses { #[primary_span] @@ -71,7 +71,7 @@ impl AddToDiagnostic for AssocTyParenthesesSub { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(ast_lowering::misplaced_impl_trait, code = "E0562")] pub struct MisplacedImplTrait<'a> { #[primary_span] @@ -79,14 +79,14 @@ pub struct MisplacedImplTrait<'a> { pub position: DiagnosticArgFromDisplay<'a>, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::rustc_box_attribute_error)] pub struct RustcBoxAttributeError { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::underscore_expr_lhs_assign)] pub struct UnderscoreExprLhsAssign { #[primary_span] @@ -94,7 +94,7 @@ pub struct UnderscoreExprLhsAssign { pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::base_expression_double_dot)] pub struct BaseExpressionDoubleDot { #[primary_span] @@ -102,7 +102,7 @@ pub struct BaseExpressionDoubleDot { pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::await_only_in_async_fn_and_blocks, code = "E0728")] pub struct AwaitOnlyInAsyncFnAndBlocks { #[primary_span] @@ -112,21 +112,21 @@ pub struct AwaitOnlyInAsyncFnAndBlocks { pub item_span: Option, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::generator_too_many_parameters, code = "E0628")] pub struct GeneratorTooManyParameters { #[primary_span] pub fn_decl_span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::closure_cannot_be_static, code = "E0697")] pub struct ClosureCannotBeStatic { #[primary_span] pub fn_decl_span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[help] #[diag(ast_lowering::async_non_move_closure_not_supported, code = "E0708")] pub struct AsyncNonMoveClosureNotSupported { @@ -134,7 +134,7 @@ pub struct AsyncNonMoveClosureNotSupported { pub fn_decl_span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::functional_record_update_destructuring_assignment)] pub struct FunctionalRecordUpdateDestructuringAssignemnt { #[primary_span] @@ -142,28 +142,28 @@ pub struct FunctionalRecordUpdateDestructuringAssignemnt { pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::async_generators_not_supported, code = "E0727")] pub struct AsyncGeneratorsNotSupported { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::inline_asm_unsupported_target, code = "E0472")] pub struct InlineAsmUnsupportedTarget { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::att_syntax_only_x86)] pub struct AttSyntaxOnlyX86 { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::abi_specified_multiple_times)] pub struct AbiSpecifiedMultipleTimes { #[primary_span] @@ -175,14 +175,14 @@ pub struct AbiSpecifiedMultipleTimes { pub equivalent: Option<()>, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::clobber_abi_not_supported)] pub struct ClobberAbiNotSupported { #[primary_span] pub abi_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[note] #[diag(ast_lowering::invalid_abi_clobber_abi)] pub struct InvalidAbiClobberAbi { @@ -191,7 +191,7 @@ pub struct InvalidAbiClobberAbi { pub supported_abis: String, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::invalid_register)] pub struct InvalidRegister<'a> { #[primary_span] @@ -200,7 +200,7 @@ pub struct InvalidRegister<'a> { pub error: &'a str, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::invalid_register_class)] pub struct InvalidRegisterClass<'a> { #[primary_span] @@ -209,7 +209,7 @@ pub struct InvalidRegisterClass<'a> { pub error: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(ast_lowering::invalid_asm_template_modifier_reg_class)] pub struct InvalidAsmTemplateModifierRegClass { #[primary_span] @@ -229,7 +229,7 @@ pub enum InvalidAsmTemplateModifierRegClassSub { DoesNotSupportModifier { class_name: Symbol }, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::invalid_asm_template_modifier_const)] pub struct InvalidAsmTemplateModifierConst { #[primary_span] @@ -239,7 +239,7 @@ pub struct InvalidAsmTemplateModifierConst { pub op_span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::invalid_asm_template_modifier_sym)] pub struct InvalidAsmTemplateModifierSym { #[primary_span] @@ -249,7 +249,7 @@ pub struct InvalidAsmTemplateModifierSym { pub op_span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::register_class_only_clobber)] pub struct RegisterClassOnlyClobber { #[primary_span] @@ -257,7 +257,7 @@ pub struct RegisterClassOnlyClobber { pub reg_class_name: Symbol, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::register_conflict)] pub struct RegisterConflict<'a> { #[primary_span] @@ -271,7 +271,7 @@ pub struct RegisterConflict<'a> { pub in_out: Option, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[help] #[diag(ast_lowering::sub_tuple_binding)] pub struct SubTupleBinding<'a> { @@ -288,7 +288,7 @@ pub struct SubTupleBinding<'a> { pub ctx: &'a str, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::extra_double_dot)] pub struct ExtraDoubleDot<'a> { #[primary_span] @@ -299,7 +299,7 @@ pub struct ExtraDoubleDot<'a> { pub ctx: &'a str, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[note] #[diag(ast_lowering::misplaced_double_dot)] pub struct MisplacedDoubleDot { @@ -307,28 +307,28 @@ pub struct MisplacedDoubleDot { pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::misplaced_relax_trait_bound)] pub struct MisplacedRelaxTraitBound { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::not_supported_for_lifetime_binder_async_closure)] pub struct NotSupportedForLifetimeBinderAsyncClosure { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::arbitrary_expression_in_pattern)] pub struct ArbitraryExpressionInPattern { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::inclusive_range_with_no_end)] pub struct InclusiveRangeWithNoEnd { #[primary_span] diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 8362b51af40..5e8f9b79850 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -5,19 +5,19 @@ use rustc_errors::{ error_code, fluent, Applicability, DiagnosticBuilder, IntoDiagnostic, ErrorGuaranteed, Handler, }; -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_span::{Span, Symbol}; use crate::UnsupportedLiteralReason; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::expected_one_cfg_pattern, code = "E0536")] pub(crate) struct ExpectedOneCfgPattern { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::invalid_predicate, code = "E0537")] pub(crate) struct InvalidPredicate { #[primary_span] @@ -26,7 +26,7 @@ pub(crate) struct InvalidPredicate { pub predicate: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::multiple_item, code = "E0538")] pub(crate) struct MultipleItem { #[primary_span] @@ -35,7 +35,7 @@ pub(crate) struct MultipleItem { pub item: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::incorrect_meta_item, code = "E0539")] pub(crate) struct IncorrectMetaItem { #[primary_span] @@ -65,28 +65,28 @@ impl<'a> IntoDiagnostic<'a> for UnknownMetaItem<'_> { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::missing_since, code = "E0542")] pub(crate) struct MissingSince { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::missing_note, code = "E0543")] pub(crate) struct MissingNote { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::multiple_stability_levels, code = "E0544")] pub(crate) struct MultipleStabilityLevels { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::invalid_issue_string, code = "E0545")] pub(crate) struct InvalidIssueString { #[primary_span] @@ -144,21 +144,21 @@ impl InvalidIssueStringCause { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::missing_feature, code = "E0546")] pub(crate) struct MissingFeature { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::non_ident_feature, code = "E0546")] pub(crate) struct NonIdentFeature { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::missing_issue, code = "E0547")] pub(crate) struct MissingIssue { #[primary_span] @@ -167,7 +167,7 @@ pub(crate) struct MissingIssue { // FIXME: This diagnostic is identical to `IncorrectMetaItem`, barring the error code. Consider // changing this to `IncorrectMetaItem`. See #51489. -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::incorrect_meta_item, code = "E0551")] pub(crate) struct IncorrectMetaItem2 { #[primary_span] @@ -176,14 +176,14 @@ pub(crate) struct IncorrectMetaItem2 { // FIXME: Why is this the same error code as `InvalidReprHintNoParen` and `InvalidReprHintNoValue`? // It is more similar to `IncorrectReprFormatGeneric`. -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::incorrect_repr_format_packed_one_or_zero_arg, code = "E0552")] pub(crate) struct IncorrectReprFormatPackedOneOrZeroArg { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::invalid_repr_hint_no_paren, code = "E0552")] pub(crate) struct InvalidReprHintNoParen { #[primary_span] @@ -192,7 +192,7 @@ pub(crate) struct InvalidReprHintNoParen { pub name: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::invalid_repr_hint_no_value, code = "E0552")] pub(crate) struct InvalidReprHintNoValue { #[primary_span] @@ -237,7 +237,7 @@ impl<'a> IntoDiagnostic<'a> for UnsupportedLiteral { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::invalid_repr_align_need_arg, code = "E0589")] pub(crate) struct InvalidReprAlignNeedArg { #[primary_span] @@ -245,7 +245,7 @@ pub(crate) struct InvalidReprAlignNeedArg { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::invalid_repr_generic, code = "E0589")] pub(crate) struct InvalidReprGeneric<'a> { #[primary_span] @@ -255,14 +255,14 @@ pub(crate) struct InvalidReprGeneric<'a> { pub error_part: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::incorrect_repr_format_align_one_arg, code = "E0693")] pub(crate) struct IncorrectReprFormatAlignOneArg { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::incorrect_repr_format_generic, code = "E0693")] pub(crate) struct IncorrectReprFormatGeneric<'a> { #[primary_span] @@ -317,28 +317,28 @@ impl<'a> IncorrectReprFormatGenericCause<'a> { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::rustc_promotable_pairing, code = "E0717")] pub(crate) struct RustcPromotablePairing { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::rustc_allowed_unstable_pairing, code = "E0789")] pub(crate) struct RustcAllowedUnstablePairing { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::cfg_predicate_identifier)] pub(crate) struct CfgPredicateIdentifier { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::deprecated_item_suggestion)] pub(crate) struct DeprecatedItemSuggestion { #[primary_span] @@ -351,21 +351,21 @@ pub(crate) struct DeprecatedItemSuggestion { pub details: (), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::expected_single_version_literal)] pub(crate) struct ExpectedSingleVersionLiteral { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::expected_version_literal)] pub(crate) struct ExpectedVersionLiteral { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::expects_feature_list)] pub(crate) struct ExpectsFeatureList { #[primary_span] @@ -374,7 +374,7 @@ pub(crate) struct ExpectsFeatureList { pub name: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::expects_features)] pub(crate) struct ExpectsFeatures { #[primary_span] @@ -383,14 +383,14 @@ pub(crate) struct ExpectsFeatures { pub name: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::soft_no_args)] pub(crate) struct SoftNoArgs { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(attr::unknown_version_literal)] pub(crate) struct UnknownVersionLiteral { #[primary_span] diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index 1014a92cc39..aa8f26eece5 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -1,11 +1,11 @@ use rustc_errors::{IntoDiagnosticArg, MultiSpan}; -use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::Span; use crate::diagnostics::RegionName; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(borrowck::move_unsized, code = "E0161")] pub(crate) struct MoveUnsized<'tcx> { pub ty: Ty<'tcx>, @@ -14,7 +14,7 @@ pub(crate) struct MoveUnsized<'tcx> { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(borrowck::higher_ranked_lifetime_error)] pub(crate) struct HigherRankedLifetimeError { #[subdiagnostic] @@ -31,14 +31,14 @@ pub(crate) enum HigherRankedErrorCause { CouldNotNormalize { value: String }, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(borrowck::higher_ranked_subtype_error)] pub(crate) struct HigherRankedSubtypeError { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(borrowck::generic_does_not_live_long_enough)] pub(crate) struct GenericDoesNotLiveLongEnough { pub kind: String, @@ -53,7 +53,7 @@ pub(crate) struct VarNeedNotMut { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(borrowck::const_not_used_in_type_alias)] pub(crate) struct ConstNotUsedTraitAlias { pub ct: String, @@ -61,7 +61,7 @@ pub(crate) struct ConstNotUsedTraitAlias { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(borrowck::var_cannot_escape_closure)] #[note] #[note(borrowck::cannot_escape)] @@ -110,7 +110,7 @@ pub(crate) enum FnMutReturnTypeErr { }, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(borrowck::lifetime_constraints_error)] pub(crate) struct LifetimeOutliveErr { #[primary_span] diff --git a/compiler/rustc_builtin_macros/src/cfg.rs b/compiler/rustc_builtin_macros/src/cfg.rs index 55b54fede93..46b54eae384 100644 --- a/compiler/rustc_builtin_macros/src/cfg.rs +++ b/compiler/rustc_builtin_macros/src/cfg.rs @@ -8,7 +8,7 @@ use rustc_ast::tokenstream::TokenStream; use rustc_attr as attr; use rustc_errors::PResult; use rustc_expand::base::{self, *}; -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_span::Span; pub fn expand_cfg( @@ -35,7 +35,7 @@ pub fn expand_cfg( } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(builtin_macros::requires_cfg_pattern)] struct RequiresCfgPattern { #[primary_span] @@ -43,7 +43,7 @@ struct RequiresCfgPattern { span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(builtin_macros::expected_one_cfg_pattern)] struct OneCfgPattern { #[primary_span] diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index d0b94e91abf..c6cb7a8b961 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -1,8 +1,8 @@ use rustc_hir::ConstContext; -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_span::Span; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::unstable_in_stable)] pub(crate) struct UnstableInStable { pub gate: String, @@ -21,14 +21,14 @@ pub(crate) struct UnstableInStable { pub attr_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::thread_local_access, code = "E0625")] pub(crate) struct NonConstOpErr { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::static_access, code = "E0013")] #[help] pub(crate) struct StaticAccessErr { @@ -40,7 +40,7 @@ pub(crate) struct StaticAccessErr { pub teach: Option<()>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::raw_ptr_to_int)] #[note] #[note(const_eval::note2)] @@ -49,7 +49,7 @@ pub(crate) struct RawPtrToIntErr { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::raw_ptr_comparison)] #[note] pub(crate) struct RawPtrComparisonErr { @@ -57,14 +57,14 @@ pub(crate) struct RawPtrComparisonErr { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::panic_non_str)] pub(crate) struct PanicNonStrErr { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::mut_deref, code = "E0658")] pub(crate) struct MutDerefErr { #[primary_span] @@ -72,7 +72,7 @@ pub(crate) struct MutDerefErr { pub kind: ConstContext, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::transient_mut_borrow, code = "E0658")] pub(crate) struct TransientMutBorrowErr { #[primary_span] @@ -80,7 +80,7 @@ pub(crate) struct TransientMutBorrowErr { pub kind: ConstContext, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::transient_mut_borrow_raw, code = "E0658")] pub(crate) struct TransientMutBorrowErrRaw { #[primary_span] @@ -88,7 +88,7 @@ pub(crate) struct TransientMutBorrowErrRaw { pub kind: ConstContext, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::max_num_nodes_in_const)] pub(crate) struct MaxNumNodesInConstErr { #[primary_span] @@ -96,7 +96,7 @@ pub(crate) struct MaxNumNodesInConstErr { pub global_const_id: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::unallowed_fn_pointer_call)] pub(crate) struct UnallowedFnPointerCall { #[primary_span] @@ -104,7 +104,7 @@ pub(crate) struct UnallowedFnPointerCall { pub kind: ConstContext, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::unstable_const_fn)] pub(crate) struct UnstableConstFn { #[primary_span] @@ -112,7 +112,7 @@ pub(crate) struct UnstableConstFn { pub def_path: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::unallowed_mutable_refs, code = "E0764")] pub(crate) struct UnallowedMutableRefs { #[primary_span] @@ -122,7 +122,7 @@ pub(crate) struct UnallowedMutableRefs { pub teach: Option<()>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::unallowed_mutable_refs_raw, code = "E0764")] pub(crate) struct UnallowedMutableRefsRaw { #[primary_span] @@ -131,7 +131,7 @@ pub(crate) struct UnallowedMutableRefsRaw { #[note(const_eval::teach_note)] pub teach: Option<()>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::non_const_fmt_macro_call, code = "E0015")] pub(crate) struct NonConstFmtMacroCall { #[primary_span] @@ -139,7 +139,7 @@ pub(crate) struct NonConstFmtMacroCall { pub kind: ConstContext, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::non_const_fn_call, code = "E0015")] pub(crate) struct NonConstFnCall { #[primary_span] @@ -148,7 +148,7 @@ pub(crate) struct NonConstFnCall { pub kind: ConstContext, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::unallowed_op_in_const_context)] pub(crate) struct UnallowedOpInConstContext { #[primary_span] @@ -156,7 +156,7 @@ pub(crate) struct UnallowedOpInConstContext { pub msg: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::unallowed_heap_allocations, code = "E0010")] pub(crate) struct UnallowedHeapAllocations { #[primary_span] @@ -167,7 +167,7 @@ pub(crate) struct UnallowedHeapAllocations { pub teach: Option<()>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::unallowed_inline_asm, code = "E0015")] pub(crate) struct UnallowedInlineAsm { #[primary_span] @@ -175,7 +175,7 @@ pub(crate) struct UnallowedInlineAsm { pub kind: ConstContext, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::interior_mutable_data_refer, code = "E0492")] pub(crate) struct InteriorMutableDataRefer { #[primary_span] @@ -188,7 +188,7 @@ pub(crate) struct InteriorMutableDataRefer { pub teach: Option<()>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(const_eval::interior_mutability_borrow)] pub(crate) struct InteriorMutabilityBorrow { #[primary_span] diff --git a/compiler/rustc_driver/src/session_diagnostics.rs b/compiler/rustc_driver/src/session_diagnostics.rs index 704d3c7fd2a..289baf17773 100644 --- a/compiler/rustc_driver/src/session_diagnostics.rs +++ b/compiler/rustc_driver/src/session_diagnostics.rs @@ -1,38 +1,38 @@ -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(driver::rlink_unable_to_read)] pub(crate) struct RlinkUnableToRead { pub err: std::io::Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(driver::rlink_wrong_file_type)] pub(crate) struct RLinkWrongFileType; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(driver::rlink_empty_version_number)] pub(crate) struct RLinkEmptyVersionNumber; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(driver::rlink_encoding_version_mismatch)] pub(crate) struct RLinkEncodingVersionMismatch { pub version_array: String, pub rlink_version: u32, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(driver::rlink_rustc_version_mismatch)] pub(crate) struct RLinkRustcVersionMismatch<'a> { pub rustc_version: String, pub current_version: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(driver::rlink_no_a_file)] pub(crate) struct RlinkNotAFile; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(driver::unpretty_dump_fail)] pub(crate) struct UnprettyDumpFail { pub path: String, diff --git a/compiler/rustc_errors/src/diagnostic_builder.rs b/compiler/rustc_errors/src/diagnostic_builder.rs index 209a50fd306..f9b46053486 100644 --- a/compiler/rustc_errors/src/diagnostic_builder.rs +++ b/compiler/rustc_errors/src/diagnostic_builder.rs @@ -14,9 +14,9 @@ use std::ops::{Deref, DerefMut}; use std::thread::panicking; /// Trait implemented by error types. This should not be implemented manually. Instead, use -/// `#[derive(DiagnosticHandler)]` -- see [rustc_macros::DiagnosticHandler]. +/// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic]. #[cfg_attr(bootstrap, rustc_diagnostic_item = "SessionDiagnostic")] -#[cfg_attr(not(bootstrap), rustc_diagnostic_item = "DiagnosticHandler")] +#[cfg_attr(not(bootstrap), rustc_diagnostic_item = "Diagnostic")] pub trait IntoDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> { /// Write out as a diagnostic out of `Handler`. #[must_use] diff --git a/compiler/rustc_expand/src/errors.rs b/compiler/rustc_expand/src/errors.rs index 7cbdad3cd95..bd93f0717f5 100644 --- a/compiler/rustc_expand/src/errors.rs +++ b/compiler/rustc_expand/src/errors.rs @@ -1,29 +1,29 @@ -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_span::symbol::MacroRulesNormalizedIdent; use rustc_span::Span; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(expand::expr_repeat_no_syntax_vars)] pub(crate) struct NoSyntaxVarsExprRepeat { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(expand::must_repeat_once)] pub(crate) struct MustRepeatOnce { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(expand::count_repetition_misplaced)] pub(crate) struct CountRepetitionMisplaced { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(expand::meta_var_expr_unrecognized_var)] pub(crate) struct MetaVarExprUnrecognizedVar { #[primary_span] @@ -31,7 +31,7 @@ pub(crate) struct MetaVarExprUnrecognizedVar { pub key: MacroRulesNormalizedIdent, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(expand::var_still_repeating)] pub(crate) struct VarStillRepeating { #[primary_span] @@ -39,7 +39,7 @@ pub(crate) struct VarStillRepeating { pub ident: MacroRulesNormalizedIdent, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(expand::meta_var_dif_seq_matchers)] pub(crate) struct MetaVarsDifSeqMatchers { #[primary_span] diff --git a/compiler/rustc_interface/src/errors.rs b/compiler/rustc_interface/src/errors.rs index dc975099fc7..097640f26c1 100644 --- a/compiler/rustc_interface/src/errors.rs +++ b/compiler/rustc_interface/src/errors.rs @@ -1,10 +1,10 @@ -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_span::{Span, Symbol}; use std::io; use std::path::Path; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::ferris_identifier)] pub struct FerrisIdentifier { #[primary_span] @@ -13,7 +13,7 @@ pub struct FerrisIdentifier { pub first_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::emoji_identifier)] pub struct EmojiIdentifier { #[primary_span] @@ -21,67 +21,67 @@ pub struct EmojiIdentifier { pub ident: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::mixed_bin_crate)] pub struct MixedBinCrate; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::mixed_proc_macro_crate)] pub struct MixedProcMacroCrate; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::proc_macro_doc_without_arg)] pub struct ProcMacroDocWithoutArg; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::error_writing_dependencies)] pub struct ErrorWritingDependencies<'a> { pub path: &'a Path, pub error: io::Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::input_file_would_be_overwritten)] pub struct InputFileWouldBeOverWritten<'a> { pub path: &'a Path, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::generated_file_conflicts_with_directory)] pub struct GeneratedFileConflictsWithDirectory<'a> { pub input_path: &'a Path, pub dir_path: &'a Path, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::temps_dir_error)] pub struct TempsDirError; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::out_dir_error)] pub struct OutDirError; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::cant_emit_mir)] pub struct CantEmitMIR { pub error: io::Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::rustc_error_fatal)] pub struct RustcErrorFatal { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::rustc_error_unexpected_annotation)] pub struct RustcErrorUnexpectedAnnotation { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(interface::failed_writing_file)] pub struct FailedWritingFile<'a> { pub path: &'a Path, diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index e5670833898..0c66ce475c4 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -1,9 +1,9 @@ use rustc_errors::{fluent, AddToDiagnostic, IntoDiagnostic, ErrorGuaranteed, Handler}; -use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, SessionSubdiagnostic}; use rustc_session::lint::Level; use rustc_span::{Span, Symbol}; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(lint::overruled_attribute, code = "E0453")] pub struct OverruledAttribute { #[primary_span] @@ -42,7 +42,7 @@ impl AddToDiagnostic for OverruledAttributeSub { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(lint::malformed_attribute, code = "E0452")] pub struct MalformedAttribute { #[primary_span] @@ -61,7 +61,7 @@ pub enum MalformedAttributeSub { ReasonMustComeLast(#[primary_span] Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(lint::unknown_tool_in_scoped_lint, code = "E0710")] pub struct UnknownToolInScopedLint { #[primary_span] @@ -72,7 +72,7 @@ pub struct UnknownToolInScopedLint { pub is_nightly_build: Option<()>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(lint::builtin_ellipsis_inclusive_range_patterns, code = "E0783")] pub struct BuiltinEllpisisInclusiveRangePatterns { #[primary_span] @@ -107,7 +107,7 @@ impl AddToDiagnostic for RequestedLevel { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(lint::unsupported_group, code = "E0602")] pub struct UnsupportedGroup { pub lint_group: String, @@ -136,7 +136,7 @@ impl IntoDiagnostic<'_> for CheckNameUnknown { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(lint::check_name_unknown_tool, code = "E0602")] pub struct CheckNameUnknownTool { pub tool_name: Symbol, @@ -144,7 +144,7 @@ pub struct CheckNameUnknownTool { pub sub: RequestedLevel, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(lint::check_name_warning)] pub struct CheckNameWarning { pub msg: String, @@ -152,7 +152,7 @@ pub struct CheckNameWarning { pub sub: RequestedLevel, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(lint::check_name_deprecated)] pub struct CheckNameDeprecated { pub lint_name: String, diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 47da8ec5da1..36d8ade22ae 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -372,7 +372,7 @@ declare_tool_lint! { declare_tool_lint! { pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL, Allow, - "prevent creation of diagnostics outside of `DiagnosticHandler`/`AddToDiagnostic` impls", + "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls", report_in_external_macro: true } @@ -404,7 +404,7 @@ impl LateLintPass<'_> for Diagnostics { let Impl { of_trait: Some(of_trait), .. } = impl_ && let Some(def_id) = of_trait.trait_def_id() && let Some(name) = cx.tcx.get_diagnostic_name(def_id) && - matches!(name, sym::DiagnosticHandler | sym::AddSubdiagnostic | sym::DecorateLint) + matches!(name, sym::Diagnostic | sym::AddSubdiagnostic | sym::DecorateLint) { found_impl = true; break; diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic.rs b/compiler/rustc_macros/src/diagnostics/diagnostic.rs index c5b5edab816..c1aae04fcee 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -21,7 +21,7 @@ impl<'a> SessionDiagnosticDerive<'a> { builder: DiagnosticDeriveBuilder { diag, fields: build_field_mapping(&structure), - kind: DiagnosticDeriveKind::DiagnosticHandler, + kind: DiagnosticDeriveKind::Diagnostic, code: None, slug: None, }, @@ -72,7 +72,7 @@ impl<'a> SessionDiagnosticDerive<'a> { } else { span_err( ast.span().unwrap(), - "`#[derive(DiagnosticHandler)]` can only be used on structs", + "`#[derive(Diagnostic)]` can only be used on structs", ) .emit(); diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index 4af3fd23624..32d6ba62a0d 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -21,12 +21,12 @@ use synstructure::{BindingInfo, Structure}; /// What kind of diagnostic is being derived - a fatal/error/warning or a lint? #[derive(Copy, Clone, PartialEq, Eq)] pub(crate) enum DiagnosticDeriveKind { - DiagnosticHandler, + Diagnostic, LintDiagnostic, } /// Tracks persistent information required for building up individual calls to diagnostic methods -/// for generated diagnostic derives - both `DiagnosticHandler` for fatal/errors/warnings and +/// for generated diagnostic derives - both `Diagnostic` for fatal/errors/warnings and /// `LintDiagnostic` for lints. pub(crate) struct DiagnosticDeriveBuilder { /// The identifier to use for the generated `DiagnosticBuilder` instance. @@ -333,7 +333,7 @@ impl DiagnosticDeriveBuilder { } "primary_span" => { match self.kind { - DiagnosticDeriveKind::DiagnosticHandler => { + DiagnosticDeriveKind::Diagnostic => { report_error_if_not_applied_to_span(attr, &info)?; Ok(quote! { diff --git a/compiler/rustc_macros/src/diagnostics/mod.rs b/compiler/rustc_macros/src/diagnostics/mod.rs index 162089c881e..1d5b32c2556 100644 --- a/compiler/rustc_macros/src/diagnostics/mod.rs +++ b/compiler/rustc_macros/src/diagnostics/mod.rs @@ -12,7 +12,7 @@ use quote::format_ident; use subdiagnostic::SessionSubdiagnosticDerive; use synstructure::Structure; -/// Implements `#[derive(DiagnosticHandler)]`, which allows for errors to be specified as a struct, +/// Implements `#[derive(Diagnostic)]`, which allows for errors to be specified as a struct, /// independent from the actual diagnostics emitting code. /// /// ```ignore (rust) @@ -22,7 +22,7 @@ use synstructure::Structure; /// # use rustc_span::{symbol::Ident, Span}; /// # extern crate rust_middle; /// # use rustc_middle::ty::Ty; -/// #[derive(DiagnosticHandler)] +/// #[derive(Diagnostic)] /// #[diag(borrowck::move_out_of_borrow, code = "E0505")] /// pub struct MoveOutOfBorrowError<'tcx> { /// pub name: Ident, @@ -56,7 +56,7 @@ use synstructure::Structure; /// }); /// ``` /// -/// See rustc dev guide for more examples on using the `#[derive(DiagnosticHandler)]`: +/// See rustc dev guide for more examples on using the `#[derive(Diagnostic)]`: /// pub fn session_diagnostic_derive(s: Structure<'_>) -> TokenStream { SessionDiagnosticDerive::new(format_ident!("diag"), format_ident!("handler"), s).into_tokens() diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 13305782ff1..9dd7ccad8bb 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -127,7 +127,7 @@ decl_derive!([TypeFoldable, attributes(type_foldable)] => type_foldable::type_fo decl_derive!([TypeVisitable, attributes(type_visitable)] => type_visitable::type_visitable_derive); decl_derive!([Lift, attributes(lift)] => lift::lift_derive); decl_derive!( - [DiagnosticHandler, attributes( + [Diagnostic, attributes( // struct attributes diag, help, diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 0a5973ca1aa..8ff4eb5fdbc 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -4,48 +4,48 @@ use std::{ }; use rustc_errors::{error_code, IntoDiagnostic, ErrorGuaranteed}; -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_session::config; use rustc_span::{sym, Span, Symbol}; use rustc_target::spec::{PanicStrategy, TargetTriple}; use crate::locator::CrateFlavor; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::rlib_required)] pub struct RlibRequired { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::lib_required)] pub struct LibRequired<'a> { pub crate_name: Symbol, pub kind: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::crate_dep_multiple)] #[help] pub struct CrateDepMultiple { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::two_panic_runtimes)] pub struct TwoPanicRuntimes { pub prev_name: Symbol, pub cur_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::bad_panic_strategy)] pub struct BadPanicStrategy { pub runtime: Symbol, pub strategy: PanicStrategy, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::required_panic_strategy)] pub struct RequiredPanicStrategy { pub crate_name: Symbol, @@ -53,7 +53,7 @@ pub struct RequiredPanicStrategy { pub desired_strategy: PanicStrategy, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::incompatible_panic_in_drop_strategy)] pub struct IncompatiblePanicInDropStrategy { pub crate_name: Symbol, @@ -61,56 +61,56 @@ pub struct IncompatiblePanicInDropStrategy { pub desired_strategy: PanicStrategy, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_names_in_link)] pub struct MultipleNamesInLink { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_kinds_in_link)] pub struct MultipleKindsInLink { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::link_name_form)] pub struct LinkNameForm { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::link_kind_form)] pub struct LinkKindForm { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::link_modifiers_form)] pub struct LinkModifiersForm { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::link_cfg_form)] pub struct LinkCfgForm { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::wasm_import_form)] pub struct WasmImportForm { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::empty_link_name, code = "E0454")] pub struct EmptyLinkName { #[primary_span] @@ -118,21 +118,21 @@ pub struct EmptyLinkName { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::link_framework_apple, code = "E0455")] pub struct LinkFrameworkApple { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::framework_only_windows, code = "E0455")] pub struct FrameworkOnlyWindows { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::unknown_link_kind, code = "E0458")] pub struct UnknownLinkKind<'a> { #[primary_span] @@ -141,49 +141,49 @@ pub struct UnknownLinkKind<'a> { pub kind: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_link_modifiers)] pub struct MultipleLinkModifiers { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_cfgs)] pub struct MultipleCfgs { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::link_cfg_single_predicate)] pub struct LinkCfgSinglePredicate { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_wasm_import)] pub struct MultipleWasmImport { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::unexpected_link_arg)] pub struct UnexpectedLinkArg { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::invalid_link_modifier)] pub struct InvalidLinkModifier { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_modifiers)] pub struct MultipleModifiers<'a> { #[primary_span] @@ -191,28 +191,28 @@ pub struct MultipleModifiers<'a> { pub modifier: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::bundle_needs_static)] pub struct BundleNeedsStatic { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::whole_archive_needs_static)] pub struct WholeArchiveNeedsStatic { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::as_needed_compatibility)] pub struct AsNeededCompatibility { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::unknown_link_modifier)] pub struct UnknownLinkModifier<'a> { #[primary_span] @@ -220,14 +220,14 @@ pub struct UnknownLinkModifier<'a> { pub modifier: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::incompatible_wasm_link)] pub struct IncompatibleWasmLink { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::link_requires_name, code = "E0459")] pub struct LinkRequiresName { #[primary_span] @@ -235,105 +235,105 @@ pub struct LinkRequiresName { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::raw_dylib_no_nul)] pub struct RawDylibNoNul { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::link_ordinal_raw_dylib)] pub struct LinkOrdinalRawDylib { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::lib_framework_apple)] pub struct LibFrameworkApple; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::empty_renaming_target)] pub struct EmptyRenamingTarget<'a> { pub lib_name: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::renaming_no_link)] pub struct RenamingNoLink<'a> { pub lib_name: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_renamings)] pub struct MultipleRenamings<'a> { pub lib_name: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::no_link_mod_override)] pub struct NoLinkModOverride { #[primary_span] pub span: Option, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::unsupported_abi_i686)] pub struct UnsupportedAbiI686 { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::unsupported_abi)] pub struct UnsupportedAbi { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::fail_create_file_encoder)] pub struct FailCreateFileEncoder { pub err: Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::fail_seek_file)] pub struct FailSeekFile { pub err: Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::fail_write_file)] pub struct FailWriteFile { pub err: Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::crate_not_panic_runtime)] pub struct CrateNotPanicRuntime { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::no_panic_strategy)] pub struct NoPanicStrategy { pub crate_name: Symbol, pub strategy: PanicStrategy, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::profiler_builtins_needs_core)] pub struct ProfilerBuiltinsNeedsCore; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::not_profiler_runtime)] pub struct NotProfilerRuntime { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::no_multiple_global_alloc)] pub struct NoMultipleGlobalAlloc { #[primary_span] @@ -343,18 +343,18 @@ pub struct NoMultipleGlobalAlloc { pub span1: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::conflicting_global_alloc)] pub struct ConflictingGlobalAlloc { pub crate_name: Symbol, pub other_crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::global_alloc_required)] pub struct GlobalAllocRequired; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::no_transitive_needs_dep)] pub struct NoTransitiveNeedsDep<'a> { pub crate_name: Symbol, @@ -362,39 +362,39 @@ pub struct NoTransitiveNeedsDep<'a> { pub deps_crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::failed_write_error)] pub struct FailedWriteError { pub filename: PathBuf, pub err: Error, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(metadata::missing_native_library)] pub struct MissingNativeLibrary<'a> { pub libname: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(metadata::failed_create_tempdir)] pub struct FailedCreateTempdir { pub err: Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::failed_create_file)] pub struct FailedCreateFile<'a> { pub filename: &'a Path, pub err: Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::failed_create_encoded_metadata)] pub struct FailedCreateEncodedMetadata { pub err: Error, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::non_ascii_name)] pub struct NonAsciiName { #[primary_span] @@ -402,7 +402,7 @@ pub struct NonAsciiName { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::extern_location_not_exist)] pub struct ExternLocationNotExist<'a> { #[primary_span] @@ -411,7 +411,7 @@ pub struct ExternLocationNotExist<'a> { pub location: &'a Path, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::extern_location_not_file)] pub struct ExternLocationNotFile<'a> { #[primary_span] @@ -444,7 +444,7 @@ impl IntoDiagnostic<'_> for MultipleCandidates { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_matching_crates, code = "E0464")] #[note] pub struct MultipleMatchingCrates { @@ -454,7 +454,7 @@ pub struct MultipleMatchingCrates { pub candidates: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::symbol_conflicts_current, code = "E0519")] pub struct SymbolConflictsCurrent { #[primary_span] @@ -462,7 +462,7 @@ pub struct SymbolConflictsCurrent { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::symbol_conflicts_others, code = "E0523")] pub struct SymbolConflictsOthers { #[primary_span] @@ -470,7 +470,7 @@ pub struct SymbolConflictsOthers { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::stable_crate_id_collision)] pub struct StableCrateIdCollision { #[primary_span] @@ -479,7 +479,7 @@ pub struct StableCrateIdCollision { pub crate_name1: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::dl_error)] pub struct DlError { #[primary_span] @@ -487,7 +487,7 @@ pub struct DlError { pub err: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::newer_crate_version, code = "E0460")] #[note] #[note(metadata::found_crate_versions)] @@ -499,7 +499,7 @@ pub struct NewerCrateVersion { pub found_crates: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::no_crate_with_triple, code = "E0461")] #[note(metadata::found_crate_versions)] pub struct NoCrateWithTriple<'a> { @@ -511,7 +511,7 @@ pub struct NoCrateWithTriple<'a> { pub found_crates: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::found_staticlib, code = "E0462")] #[note(metadata::found_crate_versions)] #[help] @@ -523,7 +523,7 @@ pub struct FoundStaticlib { pub found_crates: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::incompatible_rustc, code = "E0514")] #[note(metadata::found_crate_versions)] #[help] @@ -617,7 +617,7 @@ impl IntoDiagnostic<'_> for CannotFindCrate { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::no_dylib_plugin, code = "E0457")] pub struct NoDylibPlugin { #[primary_span] @@ -625,7 +625,7 @@ pub struct NoDylibPlugin { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::crate_location_unknown_type)] pub struct CrateLocationUnknownType<'a> { #[primary_span] @@ -633,7 +633,7 @@ pub struct CrateLocationUnknownType<'a> { pub path: &'a Path, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::lib_filename_form)] pub struct LibFilenameForm<'a> { #[primary_span] @@ -642,28 +642,28 @@ pub struct LibFilenameForm<'a> { pub dll_suffix: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::multiple_import_name_type)] pub struct MultipleImportNameType { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::import_name_type_form)] pub struct ImportNameTypeForm { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::import_name_type_x86)] pub struct ImportNameTypeX86 { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::unknown_import_name_type)] pub struct UnknownImportNameType<'a> { #[primary_span] @@ -671,7 +671,7 @@ pub struct UnknownImportNameType<'a> { pub import_name_type: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(metadata::import_name_type_raw)] pub struct ImportNameTypeRaw { #[primary_span] diff --git a/compiler/rustc_middle/src/error.rs b/compiler/rustc_middle/src/error.rs index effda9c0557..6d15feb888a 100644 --- a/compiler/rustc_middle/src/error.rs +++ b/compiler/rustc_middle/src/error.rs @@ -1,9 +1,9 @@ -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_span::Span; use crate::ty::Ty; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(middle::drop_check_overflow, code = "E0320")] #[note] pub struct DropCheckOverflow<'tcx> { @@ -13,7 +13,7 @@ pub struct DropCheckOverflow<'tcx> { pub overflow_ty: Ty<'tcx>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(middle::opaque_hidden_type_mismatch)] pub struct OpaqueHiddenTypeMismatch<'tcx> { pub self_ty: Ty<'tcx>, @@ -39,7 +39,7 @@ pub enum TypeMismatchReason { }, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(middle::limit_invalid)] pub struct LimitInvalid<'a> { #[primary_span] diff --git a/compiler/rustc_mir_dataflow/src/errors.rs b/compiler/rustc_mir_dataflow/src/errors.rs index 0d36abed2c0..5b1a88cb284 100644 --- a/compiler/rustc_mir_dataflow/src/errors.rs +++ b/compiler/rustc_mir_dataflow/src/errors.rs @@ -1,21 +1,21 @@ -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_span::{Span, Symbol}; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::path_must_end_in_filename)] pub(crate) struct PathMustEndInFilename { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::unknown_formatter)] pub(crate) struct UnknownFormatter { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::duplicate_values_for)] pub(crate) struct DuplicateValuesFor { #[primary_span] @@ -23,7 +23,7 @@ pub(crate) struct DuplicateValuesFor { pub name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::requires_an_argument)] pub(crate) struct RequiresAnArgument { #[primary_span] @@ -31,39 +31,39 @@ pub(crate) struct RequiresAnArgument { pub name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::stop_after_dataflow_ended_compilation)] pub(crate) struct StopAfterDataFlowEndedCompilation; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::peek_must_be_place_or_ref_place)] pub(crate) struct PeekMustBePlaceOrRefPlace { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::peek_must_be_not_temporary)] pub(crate) struct PeekMustBeNotTemporary { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::peek_bit_not_set)] pub(crate) struct PeekBitNotSet { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::peek_argument_not_a_local)] pub(crate) struct PeekArgumentNotALocal { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(mir_dataflow::peek_argument_untracked)] pub(crate) struct PeekArgumentUntracked { #[primary_span] diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index 150a702dc24..cdc2c74ac8f 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -2,10 +2,10 @@ use std::path::PathBuf; use rustc_errors::IntoDiagnostic; use rustc_errors::ErrorGuaranteed; -use rustc_macros::{DiagnosticHandler, LintDiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic}; use rustc_span::Span; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(monomorphize::recursion_limit)] pub struct RecursionLimit { #[primary_span] @@ -19,7 +19,7 @@ pub struct RecursionLimit { pub path: PathBuf, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(monomorphize::type_length_limit)] #[help(monomorphize::consider_type_length_limit)] pub struct TypeLengthLimit { @@ -32,7 +32,7 @@ pub struct TypeLengthLimit { pub type_length: usize, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(monomorphize::requires_lang_item)] pub struct RequiresLangItem { pub lang_item: String, @@ -72,11 +72,11 @@ pub struct LargeAssignmentsLint { pub limit: u64, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(monomorphize::unknown_partition_strategy)] pub struct UnknownPartitionStrategy; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(monomorphize::symbol_already_defined)] pub struct SymbolAlreadyDefined { #[primary_span] diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 02148193cf0..9989ebb7cdf 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -20,7 +20,7 @@ use rustc_errors::{ fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult, }; use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed}; -use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, SessionSubdiagnostic}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{Span, SpanSnippetError, DUMMY_SP}; @@ -242,7 +242,7 @@ impl MultiSugg { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::maybe_report_ambiguous_plus)] struct AmbiguousPlus { pub sum_ty: String, @@ -251,7 +251,7 @@ struct AmbiguousPlus { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::maybe_recover_from_bad_type_plus, code = "E0178")] struct BadTypePlus { pub ty: String, @@ -285,7 +285,7 @@ pub enum BadTypePlusSub { }, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::maybe_recover_from_bad_qpath_stage_2)] struct BadQPathStage2 { #[primary_span] @@ -294,7 +294,7 @@ struct BadQPathStage2 { ty: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::incorrect_semicolon)] struct IncorrectSemicolon<'a> { #[primary_span] @@ -305,7 +305,7 @@ struct IncorrectSemicolon<'a> { name: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::incorrect_use_of_await)] struct IncorrectUseOfAwait { #[primary_span] @@ -313,7 +313,7 @@ struct IncorrectUseOfAwait { span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::incorrect_use_of_await)] struct IncorrectAwait { #[primary_span] @@ -324,7 +324,7 @@ struct IncorrectAwait { question_mark: &'static str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::in_in_typo)] struct InInTypo { #[primary_span] @@ -333,7 +333,7 @@ struct InInTypo { sugg_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_variable_declaration)] pub struct InvalidVariableDeclaration { #[primary_span] @@ -362,7 +362,7 @@ pub enum InvalidVariableDeclarationSub { UseLetNotVar(#[primary_span] Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_comparison_operator)] pub(crate) struct InvalidComparisonOperator { #[primary_span] @@ -389,7 +389,7 @@ pub(crate) enum InvalidComparisonOperatorSub { Spaceship(#[primary_span] Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_logical_operator)] #[note] pub(crate) struct InvalidLogicalOperator { @@ -416,7 +416,7 @@ pub(crate) enum InvalidLogicalOperatorSub { Disjunction(#[primary_span] Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::tilde_is_not_unary_operator)] pub(crate) struct TildeAsUnaryOperator( #[primary_span] @@ -424,7 +424,7 @@ pub(crate) struct TildeAsUnaryOperator( pub Span, ); -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::unexpected_token_after_not)] pub(crate) struct NotAsNegationOperator { #[primary_span] @@ -458,7 +458,7 @@ pub enum NotAsNegationOperatorSub { SuggestNotLogical(#[primary_span] Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::malformed_loop_label)] pub(crate) struct MalformedLoopLabel { #[primary_span] @@ -467,7 +467,7 @@ pub(crate) struct MalformedLoopLabel { pub correct_label: Ident, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::lifetime_in_borrow_expression)] pub(crate) struct LifetimeInBorrowExpression { #[primary_span] @@ -477,15 +477,15 @@ pub(crate) struct LifetimeInBorrowExpression { pub lifetime_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::field_expression_with_generic)] pub(crate) struct FieldExpressionWithGeneric(#[primary_span] pub Span); -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::macro_invocation_with_qualified_path)] pub(crate) struct MacroInvocationWithQualifiedPath(#[primary_span] pub Span); -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::unexpected_token_after_label)] pub(crate) struct UnexpectedTokenAfterLabel( #[primary_span] @@ -493,7 +493,7 @@ pub(crate) struct UnexpectedTokenAfterLabel( pub Span, ); -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::require_colon_after_labeled_expression)] #[note] pub(crate) struct RequireColonAfterLabeledExpression { @@ -505,7 +505,7 @@ pub(crate) struct RequireColonAfterLabeledExpression { pub label_end: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::do_catch_syntax_removed)] #[note] pub(crate) struct DoCatchSyntaxRemoved { @@ -514,7 +514,7 @@ pub(crate) struct DoCatchSyntaxRemoved { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::float_literal_requires_integer_part)] pub(crate) struct FloatLiteralRequiresIntegerPart { #[primary_span] @@ -523,7 +523,7 @@ pub(crate) struct FloatLiteralRequiresIntegerPart { pub correct: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_int_literal_width)] #[help] pub(crate) struct InvalidIntLiteralWidth { @@ -532,7 +532,7 @@ pub(crate) struct InvalidIntLiteralWidth { pub width: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_num_literal_base_prefix)] #[note] pub(crate) struct InvalidNumLiteralBasePrefix { @@ -542,7 +542,7 @@ pub(crate) struct InvalidNumLiteralBasePrefix { pub fixed: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_num_literal_suffix)] #[help] pub(crate) struct InvalidNumLiteralSuffix { @@ -552,7 +552,7 @@ pub(crate) struct InvalidNumLiteralSuffix { pub suffix: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_float_literal_width)] #[help] pub(crate) struct InvalidFloatLiteralWidth { @@ -561,7 +561,7 @@ pub(crate) struct InvalidFloatLiteralWidth { pub width: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_float_literal_suffix)] #[help] pub(crate) struct InvalidFloatLiteralSuffix { @@ -571,14 +571,14 @@ pub(crate) struct InvalidFloatLiteralSuffix { pub suffix: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::int_literal_too_large)] pub(crate) struct IntLiteralTooLarge { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::missing_semicolon_before_array)] pub(crate) struct MissingSemicolonBeforeArray { #[primary_span] @@ -587,7 +587,7 @@ pub(crate) struct MissingSemicolonBeforeArray { pub semicolon: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::invalid_block_macro_segment)] pub(crate) struct InvalidBlockMacroSegment { #[primary_span] @@ -596,7 +596,7 @@ pub(crate) struct InvalidBlockMacroSegment { pub context: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::if_expression_missing_then_block)] pub(crate) struct IfExpressionMissingThenBlock { #[primary_span] @@ -613,7 +613,7 @@ pub(crate) enum IfExpressionMissingThenBlockSub { AddThenBlock(#[primary_span] Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::if_expression_missing_condition)] pub(crate) struct IfExpressionMissingCondition { #[primary_span] @@ -623,14 +623,14 @@ pub(crate) struct IfExpressionMissingCondition { pub block_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::expected_expression_found_let)] pub(crate) struct ExpectedExpressionFoundLet { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::expected_else_block)] pub(crate) struct ExpectedElseBlock { #[primary_span] @@ -642,7 +642,7 @@ pub(crate) struct ExpectedElseBlock { pub condition_start: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::outer_attribute_not_allowed_on_if_else)] pub(crate) struct OuterAttributeNotAllowedOnIfElse { #[primary_span] @@ -659,7 +659,7 @@ pub(crate) struct OuterAttributeNotAllowedOnIfElse { pub attributes: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::missing_in_in_for_loop)] pub(crate) struct MissingInInForLoop { #[primary_span] @@ -677,7 +677,7 @@ pub(crate) enum MissingInInForLoopSub { AddIn(#[primary_span] Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::missing_comma_after_match_arm)] pub(crate) struct MissingCommaAfterMatchArm { #[primary_span] @@ -685,7 +685,7 @@ pub(crate) struct MissingCommaAfterMatchArm { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::catch_after_try)] #[help] pub(crate) struct CatchAfterTry { @@ -693,7 +693,7 @@ pub(crate) struct CatchAfterTry { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::comma_after_base_struct)] #[note] pub(crate) struct CommaAfterBaseStruct { @@ -703,7 +703,7 @@ pub(crate) struct CommaAfterBaseStruct { pub comma: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::eq_field_init)] pub(crate) struct EqFieldInit { #[primary_span] @@ -712,7 +712,7 @@ pub(crate) struct EqFieldInit { pub eq: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::dotdotdot)] pub(crate) struct DotDotDot { #[primary_span] @@ -721,7 +721,7 @@ pub(crate) struct DotDotDot { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::left_arrow_operator)] pub(crate) struct LeftArrowOperator { #[primary_span] @@ -729,7 +729,7 @@ pub(crate) struct LeftArrowOperator { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::remove_let)] pub(crate) struct RemoveLet { #[primary_span] diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index ade5927be8e..bff2978bd13 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1,5 +1,5 @@ use rustc_errors::{Applicability, MultiSpan}; -use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; use rustc_span::{Span, Symbol}; #[derive(LintDiagnostic)] @@ -32,7 +32,7 @@ pub struct IgnoredInlineAttrFnProto; #[note] pub struct IgnoredInlineAttrConstants; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::inline_not_fn_or_closure, code = "E0518")] pub struct InlineNotFnOrClosure { #[primary_span] @@ -53,7 +53,7 @@ pub struct IgnoredNoCoveragePropagate; #[diag(passes::no_coverage_fn_defn)] pub struct IgnoredNoCoverageFnDefn; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::no_coverage_not_coverable, code = "E0788")] pub struct IgnoredNoCoverageNotCoverable { #[primary_span] @@ -62,7 +62,7 @@ pub struct IgnoredNoCoverageNotCoverable { pub defn_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::should_be_applied_to_fn)] pub struct AttrShouldBeAppliedToFn { #[primary_span] @@ -71,14 +71,14 @@ pub struct AttrShouldBeAppliedToFn { pub defn_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::naked_tracked_caller, code = "E0736")] pub struct NakedTrackedCaller { #[primary_span] pub attr_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::should_be_applied_to_fn, code = "E0739")] pub struct TrackedCallerWrongLocation { #[primary_span] @@ -87,7 +87,7 @@ pub struct TrackedCallerWrongLocation { pub defn_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::should_be_applied_to_struct_enum, code = "E0701")] pub struct NonExhaustiveWrongLocation { #[primary_span] @@ -96,7 +96,7 @@ pub struct NonExhaustiveWrongLocation { pub defn_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::should_be_applied_to_trait)] pub struct AttrShouldBeAppliedToTrait { #[primary_span] @@ -109,7 +109,7 @@ pub struct AttrShouldBeAppliedToTrait { #[diag(passes::target_feature_on_statement)] pub struct TargetFeatureOnStatement; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::should_be_applied_to_static)] pub struct AttrShouldBeAppliedToStatic { #[primary_span] @@ -118,7 +118,7 @@ pub struct AttrShouldBeAppliedToStatic { pub defn_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_expect_str)] pub struct DocExpectStr<'a> { #[primary_span] @@ -126,7 +126,7 @@ pub struct DocExpectStr<'a> { pub attr_name: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_alias_empty)] pub struct DocAliasEmpty<'a> { #[primary_span] @@ -134,7 +134,7 @@ pub struct DocAliasEmpty<'a> { pub attr_str: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_alias_bad_char)] pub struct DocAliasBadChar<'a> { #[primary_span] @@ -143,7 +143,7 @@ pub struct DocAliasBadChar<'a> { pub char_: char, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_alias_start_end)] pub struct DocAliasStartEnd<'a> { #[primary_span] @@ -151,7 +151,7 @@ pub struct DocAliasStartEnd<'a> { pub attr_str: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_alias_bad_location)] pub struct DocAliasBadLocation<'a> { #[primary_span] @@ -160,7 +160,7 @@ pub struct DocAliasBadLocation<'a> { pub location: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_alias_not_an_alias)] pub struct DocAliasNotAnAlias<'a> { #[primary_span] @@ -175,35 +175,35 @@ pub struct DocAliasDuplicated { pub first_defn: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_alias_not_string_literal)] pub struct DocAliasNotStringLiteral { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_alias_malformed)] pub struct DocAliasMalformed { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_keyword_empty_mod)] pub struct DocKeywordEmptyMod { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_keyword_not_mod)] pub struct DocKeywordNotMod { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_keyword_invalid_ident)] pub struct DocKeywordInvalidIdent { #[primary_span] @@ -211,21 +211,21 @@ pub struct DocKeywordInvalidIdent { pub doc_keyword: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_fake_variadic_not_valid)] pub struct DocFakeVariadicNotValid { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_keyword_only_impl)] pub struct DocKeywordOnlyImpl { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_inline_conflict)] #[help] pub struct DocKeywordConflict { @@ -243,7 +243,7 @@ pub struct DocInlineOnlyUse { pub item_span: Option, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::doc_attr_not_crate_level)] pub struct DocAttrNotCrateLevel<'a> { #[primary_span] @@ -295,7 +295,7 @@ pub struct DocTestUnknownInclude { #[diag(passes::doc_invalid)] pub struct DocInvalid; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::pass_by_value)] pub struct PassByValue { #[primary_span] @@ -304,7 +304,7 @@ pub struct PassByValue { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::allow_incoherent_impl)] pub struct AllowIncoherentImpl { #[primary_span] @@ -313,7 +313,7 @@ pub struct AllowIncoherentImpl { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::has_incoherent_inherent_impl)] pub struct HasIncoherentInherentImpl { #[primary_span] @@ -336,7 +336,7 @@ pub struct MustUseNoEffect { pub target: rustc_hir::Target, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::must_not_suspend)] pub struct MustNotSuspend { #[primary_span] @@ -372,7 +372,7 @@ pub struct LinkName<'a> { pub value: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::no_link)] pub struct NoLink { #[primary_span] @@ -381,7 +381,7 @@ pub struct NoLink { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::export_name)] pub struct ExportName { #[primary_span] @@ -390,7 +390,7 @@ pub struct ExportName { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_layout_scalar_valid_range_not_struct)] pub struct RustcLayoutScalarValidRangeNotStruct { #[primary_span] @@ -399,14 +399,14 @@ pub struct RustcLayoutScalarValidRangeNotStruct { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_layout_scalar_valid_range_arg)] pub struct RustcLayoutScalarValidRangeArg { #[primary_span] pub attr_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_legacy_const_generics_only)] pub struct RustcLegacyConstGenericsOnly { #[primary_span] @@ -415,7 +415,7 @@ pub struct RustcLegacyConstGenericsOnly { pub param_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_legacy_const_generics_index)] pub struct RustcLegacyConstGenericsIndex { #[primary_span] @@ -424,7 +424,7 @@ pub struct RustcLegacyConstGenericsIndex { pub generics_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_legacy_const_generics_index_exceed)] pub struct RustcLegacyConstGenericsIndexExceed { #[primary_span] @@ -433,14 +433,14 @@ pub struct RustcLegacyConstGenericsIndexExceed { pub arg_count: usize, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_legacy_const_generics_index_negative)] pub struct RustcLegacyConstGenericsIndexNegative { #[primary_span] pub invalid_args: Vec, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_dirty_clean)] pub struct RustcDirtyClean { #[primary_span] @@ -475,7 +475,7 @@ pub struct NoMangle { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::repr_ident, code = "E0565")] pub struct ReprIdent { #[primary_span] @@ -486,21 +486,21 @@ pub struct ReprIdent { #[diag(passes::repr_conflicting, code = "E0566")] pub struct ReprConflicting; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::used_static)] pub struct UsedStatic { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::used_compiler_linker)] pub struct UsedCompilerLinker { #[primary_span] pub spans: Vec, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::allow_internal_unstable)] pub struct AllowInternalUnstable { #[primary_span] @@ -509,14 +509,14 @@ pub struct AllowInternalUnstable { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::debug_visualizer_placement)] pub struct DebugVisualizerPlacement { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::debug_visualizer_invalid)] #[note(passes::note_1)] #[note(passes::note_2)] @@ -526,7 +526,7 @@ pub struct DebugVisualizerInvalid { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_allow_const_fn_unstable)] pub struct RustcAllowConstFnUnstable { #[primary_span] @@ -535,7 +535,7 @@ pub struct RustcAllowConstFnUnstable { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_std_internal_symbol)] pub struct RustcStdInternalSymbol { #[primary_span] @@ -544,21 +544,21 @@ pub struct RustcStdInternalSymbol { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::const_trait)] pub struct ConstTrait { #[primary_span] pub attr_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::link_ordinal)] pub struct LinkOrdinal { #[primary_span] pub attr_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::stability_promotable)] pub struct StabilityPromotable { #[primary_span] @@ -602,7 +602,7 @@ pub struct Unused { pub note: UnusedNote, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::non_exported_macro_invalid_attrs, code = "E0518")] pub struct NonExportedMacroInvalidAttrs { #[primary_span] @@ -621,7 +621,7 @@ pub struct UnusedDuplicate { pub warning: Option<()>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::unused_multiple)] pub struct UnusedMultiple { #[primary_span] @@ -632,7 +632,7 @@ pub struct UnusedMultiple { pub name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_lint_opt_ty)] pub struct RustcLintOptTy { #[primary_span] @@ -641,7 +641,7 @@ pub struct RustcLintOptTy { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(passes::rustc_lint_opt_deny_field_access)] pub struct RustcLintOptDenyFieldAccess { #[primary_span] diff --git a/compiler/rustc_plugin_impl/src/errors.rs b/compiler/rustc_plugin_impl/src/errors.rs index 0b2c09f9e1d..07ce92a9b26 100644 --- a/compiler/rustc_plugin_impl/src/errors.rs +++ b/compiler/rustc_plugin_impl/src/errors.rs @@ -1,9 +1,9 @@ //! Errors emitted by plugin_impl -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_span::Span; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(plugin_impl::load_plugin_error)] pub struct LoadPluginError { #[primary_span] @@ -11,7 +11,7 @@ pub struct LoadPluginError { pub msg: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(plugin_impl::malformed_plugin_attribute, code = "E0498")] pub struct MalformedPluginAttribute { #[primary_span] diff --git a/compiler/rustc_privacy/src/errors.rs b/compiler/rustc_privacy/src/errors.rs index 56a2cb059b5..71552119482 100644 --- a/compiler/rustc_privacy/src/errors.rs +++ b/compiler/rustc_privacy/src/errors.rs @@ -1,8 +1,8 @@ use rustc_errors::DiagnosticArgFromDisplay; -use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; use rustc_span::{Span, Symbol}; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(privacy::field_is_private, code = "E0451")] pub struct FieldIsPrivate { #[primary_span] @@ -29,7 +29,7 @@ pub enum FieldIsPrivateLabel { }, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(privacy::item_is_private)] pub struct ItemIsPrivate<'a> { #[primary_span] @@ -39,7 +39,7 @@ pub struct ItemIsPrivate<'a> { pub descr: DiagnosticArgFromDisplay<'a>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(privacy::unnamed_item_is_private)] pub struct UnnamedItemIsPrivate { #[primary_span] @@ -48,7 +48,7 @@ pub struct UnnamedItemIsPrivate { } // Duplicate of `InPublicInterface` but with a different error code, shares the same slug. -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(privacy::in_public_interface, code = "E0445")] pub struct InPublicInterfaceTraits<'a> { #[primary_span] @@ -62,7 +62,7 @@ pub struct InPublicInterfaceTraits<'a> { } // Duplicate of `InPublicInterfaceTraits` but with a different error code, shares the same slug. -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(privacy::in_public_interface, code = "E0446")] pub struct InPublicInterface<'a> { #[primary_span] diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 97a74517f68..4c770152f12 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -46,7 +46,7 @@ pub struct CycleUsage { pub usage: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(query_system::cycle, code = "E0391")] pub struct Cycle { #[primary_span] @@ -62,11 +62,11 @@ pub struct Cycle { pub cycle_usage: Option, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(query_system::reentrant)] pub struct Reentrant; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(query_system::increment_compilation)] #[help] #[note(query_system::increment_compilation_note1)] diff --git a/compiler/rustc_save_analysis/src/errors.rs b/compiler/rustc_save_analysis/src/errors.rs index 0983ec2f6f7..8a15ba63661 100644 --- a/compiler/rustc_save_analysis/src/errors.rs +++ b/compiler/rustc_save_analysis/src/errors.rs @@ -1,8 +1,8 @@ -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use std::path::Path; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(save_analysis::could_not_open)] pub(crate) struct CouldNotOpen<'a> { pub file_name: &'a Path, diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index 4cf46109895..7ffe757463f 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -8,7 +8,7 @@ use rustc_span::{Span, Symbol}; use rustc_target::abi::TargetDataLayoutErrors; use rustc_target::spec::{SplitDebuginfo, StackProtector, TargetTriple}; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(session::incorrect_cgu_reuse_type)] pub struct IncorrectCguReuseType<'a> { #[primary_span] @@ -19,14 +19,14 @@ pub struct IncorrectCguReuseType<'a> { pub at_least: u8, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(session::cgu_not_recorded)] pub struct CguNotRecorded<'a> { pub cgu_user_name: &'a str, pub cgu_name: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(session::feature_gate_error, code = "E0658")] pub struct FeatureGateError<'a> { #[primary_span] @@ -46,7 +46,7 @@ pub struct FeatureDiagnosticHelp { pub feature: Symbol, } -impl DiagnosticHandler<'_, !> for TargetDataLayoutErrors<'_> { +impl IntoDiagnostic<'_, !> for TargetDataLayoutErrors<'_> { fn into_diagnostic(self, handler: &Handler) -> DiagnosticBuilder<'_, !> { let mut diag; match self { diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 98ff9694808..ea69334616b 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -177,7 +177,7 @@ symbols! { DecorateLint, Default, Deref, - DiagnosticHandler, + Diagnostic, DiagnosticMessage, DirBuilder, Display, diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index f62bdb00ee0..b02ee593cbe 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -1,10 +1,10 @@ use rustc_errors::{fluent, IntoDiagnostic, ErrorGuaranteed, Handler}; -use rustc_macros::DiagnosticHandler; +use rustc_macros::Diagnostic; use rustc_middle::ty::{PolyTraitRef, Ty, Unevaluated}; use rustc_session::Limit; use rustc_span::{Span, Symbol}; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(trait_selection::dump_vtable_entries)] pub struct DumpVTableEntries<'a> { #[primary_span] @@ -13,7 +13,7 @@ pub struct DumpVTableEntries<'a> { pub entries: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(trait_selection::unable_to_construct_constant_value)] pub struct UnableToConstructConstantValue<'a> { #[primary_span] @@ -21,7 +21,7 @@ pub struct UnableToConstructConstantValue<'a> { pub unevaluated: Unevaluated<'a>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[help] #[diag(trait_selection::auto_deref_reached_recursion_limit, code = "E0055")] pub struct AutoDerefReachedRecursionLimit<'a> { @@ -33,7 +33,7 @@ pub struct AutoDerefReachedRecursionLimit<'a> { pub crate_name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(trait_selection::empty_on_clause_in_rustc_on_unimplemented, code = "E0232")] pub struct EmptyOnClauseInOnUnimplemented { #[primary_span] @@ -41,7 +41,7 @@ pub struct EmptyOnClauseInOnUnimplemented { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(trait_selection::invalid_on_clause_in_rustc_on_unimplemented, code = "E0232")] pub struct InvalidOnClauseInOnUnimplemented { #[primary_span] @@ -49,7 +49,7 @@ pub struct InvalidOnClauseInOnUnimplemented { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(trait_selection::no_value_in_rustc_on_unimplemented, code = "E0232")] #[note] pub struct NoValueInOnUnimplemented { diff --git a/compiler/rustc_ty_utils/src/errors.rs b/compiler/rustc_ty_utils/src/errors.rs index 995e87bcd3b..85165187310 100644 --- a/compiler/rustc_ty_utils/src/errors.rs +++ b/compiler/rustc_ty_utils/src/errors.rs @@ -1,16 +1,16 @@ //! Errors emitted by ty_utils -use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, SessionSubdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::Span; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(ty_utils::needs_drop_overflow)] pub struct NeedsDropOverflow<'tcx> { pub query_ty: Ty<'tcx>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(ty_utils::generic_constant_too_complex)] #[help] pub struct GenericConstantTooComplex { diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 11661b8ef6c..23fadff3248 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -881,7 +881,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } - // FIXME: Make this use DiagnosticHandler once error codes can be dynamically set. + // FIXME: Make this use Diagnostic once error codes can be dynamically set. let mut err = self.tcx.sess.struct_span_err_with_code( op_span, "invalid left-hand side of assignment", diff --git a/compiler/rustc_typeck/src/errors.rs b/compiler/rustc_typeck/src/errors.rs index 50d400e2921..6f00591d54e 100644 --- a/compiler/rustc_typeck/src/errors.rs +++ b/compiler/rustc_typeck/src/errors.rs @@ -1,11 +1,11 @@ //! Errors emitted by typeck. use rustc_errors::IntoDiagnostic; use rustc_errors::{error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler}; -use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::{symbol::Ident, Span, Symbol}; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::field_multiply_specified_in_initializer, code = "E0062")] pub struct FieldMultiplySpecifiedInInitializer { #[primary_span] @@ -16,7 +16,7 @@ pub struct FieldMultiplySpecifiedInInitializer { pub ident: Ident, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::unrecognized_atomic_operation, code = "E0092")] pub struct UnrecognizedAtomicOperation<'a> { #[primary_span] @@ -25,7 +25,7 @@ pub struct UnrecognizedAtomicOperation<'a> { pub op: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::wrong_number_of_generic_arguments_to_intrinsic, code = "E0094")] pub struct WrongNumberOfGenericArgumentsToIntrinsic<'a> { #[primary_span] @@ -36,7 +36,7 @@ pub struct WrongNumberOfGenericArgumentsToIntrinsic<'a> { pub descr: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::unrecognized_intrinsic_function, code = "E0093")] pub struct UnrecognizedIntrinsicFunction { #[primary_span] @@ -45,7 +45,7 @@ pub struct UnrecognizedIntrinsicFunction { pub name: Symbol, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::lifetimes_or_bounds_mismatch_on_trait, code = "E0195")] pub struct LifetimesOrBoundsMismatchOnTrait { #[primary_span] @@ -57,7 +57,7 @@ pub struct LifetimesOrBoundsMismatchOnTrait { pub ident: Ident, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::drop_impl_on_wrong_item, code = "E0120")] pub struct DropImplOnWrongItem { #[primary_span] @@ -65,7 +65,7 @@ pub struct DropImplOnWrongItem { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::field_already_declared, code = "E0124")] pub struct FieldAlreadyDeclared { pub field_name: Ident, @@ -76,7 +76,7 @@ pub struct FieldAlreadyDeclared { pub prev_span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::copy_impl_on_type_with_dtor, code = "E0184")] pub struct CopyImplOnTypeWithDtor { #[primary_span] @@ -84,14 +84,14 @@ pub struct CopyImplOnTypeWithDtor { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::multiple_relaxed_default_bounds, code = "E0203")] pub struct MultipleRelaxedDefaultBounds { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::copy_impl_on_non_adt, code = "E0206")] pub struct CopyImplOnNonAdt { #[primary_span] @@ -99,7 +99,7 @@ pub struct CopyImplOnNonAdt { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::trait_object_declared_with_no_traits, code = "E0224")] pub struct TraitObjectDeclaredWithNoTraits { #[primary_span] @@ -108,14 +108,14 @@ pub struct TraitObjectDeclaredWithNoTraits { pub trait_alias_span: Option, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0227")] pub struct AmbiguousLifetimeBound { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::assoc_type_binding_not_allowed, code = "E0229")] pub struct AssocTypeBindingNotAllowed { #[primary_span] @@ -123,14 +123,14 @@ pub struct AssocTypeBindingNotAllowed { pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::functional_record_update_on_non_struct, code = "E0436")] pub struct FunctionalRecordUpdateOnNonStruct { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::typeof_reserved_keyword_used, code = "E0516")] pub struct TypeofReservedKeywordUsed<'tcx> { pub ty: Ty<'tcx>, @@ -141,7 +141,7 @@ pub struct TypeofReservedKeywordUsed<'tcx> { pub opt_sugg: Option<(Span, Applicability)>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::return_stmt_outside_of_fn_body, code = "E0572")] pub struct ReturnStmtOutsideOfFnBody { #[primary_span] @@ -152,14 +152,14 @@ pub struct ReturnStmtOutsideOfFnBody { pub encl_fn_span: Option, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::yield_expr_outside_of_generator, code = "E0627")] pub struct YieldExprOutsideOfGenerator { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::struct_expr_non_exhaustive, code = "E0639")] pub struct StructExprNonExhaustive { #[primary_span] @@ -167,14 +167,14 @@ pub struct StructExprNonExhaustive { pub what: &'static str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::method_call_on_unknown_type, code = "E0699")] pub struct MethodCallOnUnknownType { #[primary_span] pub span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::value_of_associated_struct_already_specified, code = "E0719")] pub struct ValueOfAssociatedStructAlreadySpecified { #[primary_span] @@ -186,7 +186,7 @@ pub struct ValueOfAssociatedStructAlreadySpecified { pub def_path: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::address_of_temporary_taken, code = "E0745")] pub struct AddressOfTemporaryTaken { #[primary_span] @@ -232,7 +232,7 @@ pub enum ExpectedReturnTypeLabel<'tcx> { }, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::unconstrained_opaque_type)] #[note] pub struct UnconstrainedOpaqueType { @@ -249,7 +249,7 @@ pub struct MissingTypeParams { pub empty_generic_args: bool, } -// Manual implementation of `DiagnosticHandler` to be able to call `span_to_snippet`. +// Manual implementation of `IntoDiagnostic` to be able to call `span_to_snippet`. impl<'a> IntoDiagnostic<'a> for MissingTypeParams { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { let mut err = handler.struct_span_err_with_code( @@ -306,7 +306,7 @@ impl<'a> IntoDiagnostic<'a> for MissingTypeParams { } } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::manual_implementation, code = "E0183")] #[help] pub struct ManualImplementation { @@ -316,7 +316,7 @@ pub struct ManualImplementation { pub trait_name: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::substs_on_overridden_impl)] pub struct SubstsOnOverriddenImpl { #[primary_span] @@ -339,7 +339,7 @@ pub struct ExternCrateNotIdiomatic { pub suggestion_code: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::expected_used_symbol)] pub struct ExpectedUsedSymbol { #[primary_span] diff --git a/src/test/ui-fulldeps/internal-lints/diagnostics.rs b/src/test/ui-fulldeps/internal-lints/diagnostics.rs index e95ab048db3..93766de9a91 100644 --- a/src/test/ui-fulldeps/internal-lints/diagnostics.rs +++ b/src/test/ui-fulldeps/internal-lints/diagnostics.rs @@ -15,10 +15,10 @@ use rustc_errors::{ AddToDiagnostic, IntoDiagnostic, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, fluent }; -use rustc_macros::{DiagnosticHandler, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, SessionSubdiagnostic}; use rustc_span::Span; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(parser::expect_path)] struct DeriveSessionDiagnostic { #[primary_span] diff --git a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs index 32ba5be8963..fd8128c31f8 100644 --- a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs +++ b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs @@ -1,10 +1,10 @@ // check-fail -// Tests error conditions for specifying diagnostics using #[derive(DiagnosticHandler)] +// Tests error conditions for specifying diagnostics using #[derive(Diagnostic)] // normalize-stderr-test "the following other types implement trait `IntoDiagnosticArg`:(?:.*\n){0,9}\s+and \d+ others" -> "normalized in stderr" // normalize-stderr-test "diagnostic_builder\.rs:[0-9]+:[0-9]+" -> "diagnostic_builder.rs:LL:CC" // The proc_macro2 crate handles spans differently when on beta/stable release rather than nightly, -// changing the output of this test. Since DiagnosticHandler is strictly internal to the compiler +// changing the output of this test. Since Diagnostic is strictly internal to the compiler // the test is just ignored on stable and beta: // ignore-beta // ignore-stable @@ -17,7 +17,7 @@ use rustc_span::symbol::Ident; use rustc_span::Span; extern crate rustc_macros; -use rustc_macros::{DiagnosticHandler, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; extern crate rustc_middle; use rustc_middle::ty::Ty; @@ -27,70 +27,70 @@ use rustc_errors::{Applicability, MultiSpan}; extern crate rustc_session; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct Hello {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct HelloWarn {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] -//~^ ERROR `#[derive(DiagnosticHandler)]` can only be used on structs -enum DiagnosticHandlerOnEnum { +//~^ ERROR `#[derive(Diagnostic)]` can only be used on structs +enum DiagnosticOnEnum { Foo, Bar, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[diag = "E0123"] //~^ ERROR `#[diag = ...]` is not a valid attribute struct WrongStructAttrStyle {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[nonsense(typeck::ambiguous_lifetime_bound, code = "E0123")] //~^ ERROR `#[nonsense(...)]` is not a valid attribute //~^^ ERROR diagnostic slug not specified //~^^^ ERROR cannot find attribute `nonsense` in this scope struct InvalidStructAttr {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag("E0123")] //~^ ERROR `#[diag("...")]` is not a valid attribute //~^^ ERROR diagnostic slug not specified struct InvalidLitNestedAttr {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(nonsense, code = "E0123")] //~^ ERROR cannot find value `nonsense` in module `rustc_errors::fluent` struct InvalidNestedStructAttr {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(nonsense("foo"), code = "E0123", slug = "foo")] //~^ ERROR `#[diag(nonsense(...))]` is not a valid attribute //~^^ ERROR diagnostic slug not specified struct InvalidNestedStructAttr1 {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(nonsense = "...", code = "E0123", slug = "foo")] //~^ ERROR `#[diag(nonsense = ...)]` is not a valid attribute //~^^ ERROR diagnostic slug not specified struct InvalidNestedStructAttr2 {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(nonsense = 4, code = "E0123", slug = "foo")] //~^ ERROR `#[diag(nonsense = ...)]` is not a valid attribute //~^^ ERROR diagnostic slug not specified struct InvalidNestedStructAttr3 {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123", slug = "foo")] //~^ ERROR `#[diag(slug = ...)]` is not a valid attribute struct InvalidNestedStructAttr4 {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct WrongPlaceField { #[suggestion = "bar"] @@ -98,36 +98,36 @@ struct WrongPlaceField { sp: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[diag(typeck::ambiguous_lifetime_bound, code = "E0456")] //~^ ERROR specified multiple times //~^^ ERROR specified multiple times struct DiagSpecifiedTwice {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0456", code = "E0457")] //~^ ERROR specified multiple times struct CodeSpecifiedTwice {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, typeck::ambiguous_lifetime_bound, code = "E0456")] //~^ ERROR `#[diag(typeck::ambiguous_lifetime_bound)]` is not a valid attribute struct SlugSpecifiedTwice {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] struct KindNotProvided {} //~ ERROR diagnostic slug not specified -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(code = "E0456")] //~^ ERROR diagnostic slug not specified struct SlugNotProvided {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound)] struct CodeNotProvided {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct MessageWrongType { #[primary_span] @@ -135,7 +135,7 @@ struct MessageWrongType { foo: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct InvalidPathFieldAttr { #[nonsense] @@ -144,7 +144,7 @@ struct InvalidPathFieldAttr { foo: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithField { name: String, @@ -152,7 +152,7 @@ struct ErrorWithField { span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithMessageAppliedToField { #[label(typeck::label)] @@ -160,7 +160,7 @@ struct ErrorWithMessageAppliedToField { name: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithNonexistentField { #[suggestion(typeck::suggestion, code = "{name}")] @@ -168,7 +168,7 @@ struct ErrorWithNonexistentField { suggestion: (Span, Applicability), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] //~^ ERROR invalid format string: expected `'}'` #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorMissingClosingBrace { @@ -178,7 +178,7 @@ struct ErrorMissingClosingBrace { val: usize, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] //~^ ERROR invalid format string: unmatched `}` #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorMissingOpeningBrace { @@ -188,14 +188,14 @@ struct ErrorMissingOpeningBrace { val: usize, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelOnSpan { #[label(typeck::label)] sp: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelOnNonSpan { #[label(typeck::label)] @@ -203,7 +203,7 @@ struct LabelOnNonSpan { id: u32, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct Suggest { #[suggestion(typeck::suggestion, code = "This is the suggested code")] @@ -213,14 +213,14 @@ struct Suggest { suggestion: (Span, Applicability), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithoutCode { #[suggestion(typeck::suggestion)] suggestion: (Span, Applicability), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithBadKey { #[suggestion(nonsense = "bar")] @@ -228,7 +228,7 @@ struct SuggestWithBadKey { suggestion: (Span, Applicability), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithShorthandMsg { #[suggestion(msg = "bar")] @@ -236,21 +236,21 @@ struct SuggestWithShorthandMsg { suggestion: (Span, Applicability), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithoutMsg { #[suggestion(code = "bar")] suggestion: (Span, Applicability), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithTypesSwapped { #[suggestion(typeck::suggestion, code = "This is suggested code")] suggestion: (Applicability, Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithWrongTypeApplicabilityOnly { #[suggestion(typeck::suggestion, code = "This is suggested code")] @@ -258,14 +258,14 @@ struct SuggestWithWrongTypeApplicabilityOnly { suggestion: Applicability, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithSpanOnly { #[suggestion(typeck::suggestion, code = "This is suggested code")] suggestion: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithDuplicateSpanAndApplicability { #[suggestion(typeck::suggestion, code = "This is suggested code")] @@ -273,7 +273,7 @@ struct SuggestWithDuplicateSpanAndApplicability { suggestion: (Span, Span, Applicability), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct SuggestWithDuplicateApplicabilityAndSpan { #[suggestion(typeck::suggestion, code = "This is suggested code")] @@ -281,7 +281,7 @@ struct SuggestWithDuplicateApplicabilityAndSpan { suggestion: (Applicability, Applicability, Span), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct WrongKindOfAnnotation { #[label = "bar"] @@ -289,7 +289,7 @@ struct WrongKindOfAnnotation { z: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct OptionsInErrors { #[label(typeck::label)] @@ -298,7 +298,7 @@ struct OptionsInErrors { opt_sugg: Option<(Span, Applicability)>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0456")] struct MoveOutOfBorrowError<'tcx> { name: Ident, @@ -312,7 +312,7 @@ struct MoveOutOfBorrowError<'tcx> { opt_sugg: Option<(Span, Applicability)>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithLifetime<'a> { #[label(typeck::label)] @@ -320,7 +320,7 @@ struct ErrorWithLifetime<'a> { name: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithDefaultLabelAttr<'a> { #[label] @@ -328,7 +328,7 @@ struct ErrorWithDefaultLabelAttr<'a> { name: &'a str, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] //~^ ERROR the trait bound `Hello: IntoDiagnosticArg` is not satisfied #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ArgFieldWithoutSkip { @@ -337,7 +337,7 @@ struct ArgFieldWithoutSkip { other: Hello, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ArgFieldWithSkip { #[primary_span] @@ -348,91 +348,91 @@ struct ArgFieldWithSkip { other: Hello, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithSpannedNote { #[note] span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithSpannedNoteCustom { #[note(typeck::note)] span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[note] struct ErrorWithNote { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[note(typeck::note)] struct ErrorWithNoteCustom { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithSpannedHelp { #[help] span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithSpannedHelpCustom { #[help(typeck::help)] span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[help] struct ErrorWithHelp { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[help(typeck::help)] struct ErrorWithHelpCustom { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[help] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithHelpWrongOrder { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[help(typeck::help)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithHelpCustomWrongOrder { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[note] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithNoteWrongOrder { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[note(typeck::note)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithNoteCustomWrongOrder { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ApplicabilityInBoth { #[suggestion(typeck::suggestion, code = "...", applicability = "maybe-incorrect")] @@ -440,7 +440,7 @@ struct ApplicabilityInBoth { suggestion: (Span, Applicability), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct InvalidApplicability { #[suggestion(typeck::suggestion, code = "...", applicability = "batman")] @@ -448,14 +448,14 @@ struct InvalidApplicability { suggestion: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ValidApplicability { #[suggestion(typeck::suggestion, code = "...", applicability = "maybe-incorrect")] suggestion: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct NoApplicability { #[suggestion(typeck::suggestion, code = "...")] @@ -466,14 +466,14 @@ struct NoApplicability { #[note(parser::add_paren)] struct Note; -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound)] struct Subdiagnostic { #[subdiagnostic] note: Note, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct VecField { #[primary_span] @@ -481,7 +481,7 @@ struct VecField { spans: Vec, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct UnitField { #[primary_span] @@ -492,7 +492,7 @@ struct UnitField { bar: (), } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct OptUnitField { #[primary_span] @@ -503,7 +503,7 @@ struct OptUnitField { bar: Option<()>, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelWithTrailingPath { #[label(typeck::label, foo)] @@ -511,7 +511,7 @@ struct LabelWithTrailingPath { span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelWithTrailingNameValue { #[label(typeck::label, foo = "...")] @@ -519,7 +519,7 @@ struct LabelWithTrailingNameValue { span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct LabelWithTrailingList { #[label(typeck::label, foo("..."))] @@ -540,35 +540,35 @@ struct PrimarySpanOnLint { span: Span, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] struct ErrorWithMultiSpan { #[primary_span] span: MultiSpan, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] #[warning] struct ErrorWithWarn { val: String, } -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[error(typeck::ambiguous_lifetime_bound, code = "E0123")] //~^ ERROR `#[error(...)]` is not a valid attribute //~| ERROR diagnostic slug not specified //~| ERROR cannot find attribute `error` in this scope struct ErrorAttribute {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[warn_(typeck::ambiguous_lifetime_bound, code = "E0123")] //~^ ERROR `#[warn_(...)]` is not a valid attribute //~| ERROR diagnostic slug not specified //~| ERROR cannot find attribute `warn_` in this scope struct WarnAttribute {} -#[derive(DiagnosticHandler)] +#[derive(Diagnostic)] #[lint(typeck::ambiguous_lifetime_bound, code = "E0123")] //~^ ERROR `#[lint(...)]` is not a valid attribute //~| ERROR diagnostic slug not specified diff --git a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr index d9198d4ef80..b07b35f2723 100644 --- a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr +++ b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr @@ -1,9 +1,9 @@ -error: `#[derive(DiagnosticHandler)]` can only be used on structs +error: `#[derive(Diagnostic)]` can only be used on structs --> $DIR/diagnostic-derive.rs:39:1 | LL | / #[diag(typeck::ambiguous_lifetime_bound, code = "E0123")] LL | | -LL | | enum DiagnosticHandlerOnEnum { +LL | | enum DiagnosticOnEnum { LL | | Foo, LL | | Bar, LL | | } @@ -214,22 +214,22 @@ LL | #[suggestion(typeck::suggestion, code = "{name}")] error: invalid format string: expected `'}'` but string was terminated --> $DIR/diagnostic-derive.rs:171:16 | -LL | #[derive(DiagnosticHandler)] +LL | #[derive(Diagnostic)] | - ^ expected `'}'` in format string | | | because of this opening brace | = note: if you intended to print `{`, you can escape it using `{{` - = note: this error originates in the derive macro `DiagnosticHandler` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the derive macro `Diagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) error: invalid format string: unmatched `}` found --> $DIR/diagnostic-derive.rs:181:15 | -LL | #[derive(DiagnosticHandler)] +LL | #[derive(Diagnostic)] | ^ unmatched `}` in format string | = note: if you intended to print `}`, you can escape it using `}}` - = note: this error originates in the derive macro `DiagnosticHandler` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the derive macro `Diagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) error: the `#[label(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` --> $DIR/diagnostic-derive.rs:201:5 @@ -448,7 +448,7 @@ LL | #[diag(nonsense, code = "E0123")] error[E0277]: the trait bound `Hello: IntoDiagnosticArg` is not satisfied --> $DIR/diagnostic-derive.rs:331:10 | -LL | #[derive(DiagnosticHandler)] +LL | #[derive(Diagnostic)] | ^^^^^^^^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `Hello` | = help: normalized in stderr @@ -457,7 +457,7 @@ note: required by a bound in `DiagnosticBuilder::<'a, G>::set_arg` | LL | arg: impl IntoDiagnosticArg, | ^^^^^^^^^^^^^^^^^ required by this bound in `DiagnosticBuilder::<'a, G>::set_arg` - = note: this error originates in the derive macro `DiagnosticHandler` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the derive macro `Diagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 55 previous errors -- cgit 1.4.1-3-g733a5 From 5f91719f75a1012f4b59391fd89a20bb989b2801 Mon Sep 17 00:00:00 2001 From: Jhonny Bill Mena Date: Sun, 18 Sep 2022 11:47:31 -0400 Subject: UPDATE - rename SessionSubdiagnostic macro to Subdiagnostic Also renames: - sym::AddSubdiagnostic to sym:: Subdiagnostic - rustc_diagnostic_item = "AddSubdiagnostic" to rustc_diagnostic_item = "Subdiagnostic" --- compiler/rustc_ast_lowering/src/errors.rs | 4 +- compiler/rustc_ast_passes/src/errors.rs | 2 +- compiler/rustc_attr/src/session_diagnostics.rs | 4 +- compiler/rustc_borrowck/src/session_diagnostics.rs | 12 +- compiler/rustc_error_messages/src/lib.rs | 4 +- compiler/rustc_errors/src/diagnostic.rs | 9 +- compiler/rustc_expand/src/mbe/macro_rules.rs | 2 +- compiler/rustc_lint/src/errors.rs | 4 +- compiler/rustc_lint/src/internal.rs | 2 +- compiler/rustc_macros/src/diagnostics/mod.rs | 10 +- .../rustc_macros/src/diagnostics/subdiagnostic.rs | 18 +-- compiler/rustc_macros/src/lib.rs | 2 +- compiler/rustc_middle/src/error.rs | 2 +- compiler/rustc_parse/src/parser/diagnostics.rs | 14 +-- compiler/rustc_passes/src/errors.rs | 4 +- compiler/rustc_privacy/src/errors.rs | 4 +- compiler/rustc_query_system/src/error.rs | 7 +- compiler/rustc_session/src/errors.rs | 4 +- compiler/rustc_span/src/symbol.rs | 2 +- compiler/rustc_ty_utils/src/errors.rs | 4 +- compiler/rustc_typeck/src/errors.rs | 6 +- src/test/ui-fulldeps/internal-lints/diagnostics.rs | 4 +- .../session-diagnostic/diagnostic-derive.rs | 4 +- .../session-diagnostic/subdiagnostic-derive.rs | 130 ++++++++++----------- 24 files changed, 130 insertions(+), 128 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index 6dbb2582a37..052979d6d45 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -1,5 +1,5 @@ use rustc_errors::{fluent, AddToDiagnostic, Applicability, Diagnostic, DiagnosticArgFromDisplay}; -use rustc_macros::{Diagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{symbol::Ident, Span, Symbol}; #[derive(Diagnostic, Clone, Copy)] @@ -221,7 +221,7 @@ pub struct InvalidAsmTemplateModifierRegClass { pub sub: InvalidAsmTemplateModifierRegClassSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum InvalidAsmTemplateModifierRegClassSub { #[note(ast_lowering::support_modifiers)] SupportModifier { class_name: Symbol, modifiers: String }, diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 20e2209acbe..035f0ce1cbc 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -71,7 +71,7 @@ pub struct InvalidVisibility { pub note: Option, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum InvalidVisibilityNote { #[note(ast_passes::individual_impl_items)] IndividualImplItems, diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 5e8f9b79850..940a48ed915 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -98,7 +98,7 @@ pub(crate) struct InvalidIssueString { // The error kinds of `IntErrorKind` are duplicated here in order to allow the messages to be // translatable. -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum InvalidIssueStringCause { #[label(attr::must_not_be_zero)] MustNotBeZero { @@ -274,7 +274,7 @@ pub(crate) struct IncorrectReprFormatGeneric<'a> { pub cause: Option>, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum IncorrectReprFormatGenericCause<'a> { #[suggestion(attr::suggestion, code = "{name}({int})", applicability = "machine-applicable")] Int { diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index aa8f26eece5..9f19453a1a6 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -1,5 +1,5 @@ use rustc_errors::{IntoDiagnosticArg, MultiSpan}; -use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::Span; @@ -23,7 +23,7 @@ pub(crate) struct HigherRankedLifetimeError { pub span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum HigherRankedErrorCause { #[note(borrowck::could_not_prove)] CouldNotProve { predicate: String }, @@ -72,7 +72,7 @@ pub(crate) struct FnMutError { pub ty_err: FnMutReturnTypeErr, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum VarHereDenote { #[label(borrowck::var_here_captured)] Captured { @@ -91,7 +91,7 @@ pub(crate) enum VarHereDenote { }, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum FnMutReturnTypeErr { #[label(borrowck::returned_closure_escaped)] ReturnClosure { @@ -117,7 +117,7 @@ pub(crate) struct LifetimeOutliveErr { pub span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum LifetimeReturnCategoryErr<'a> { #[label(borrowck::returned_lifetime_wrong)] WrongReturn { @@ -149,7 +149,7 @@ impl IntoDiagnosticArg for RegionName { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum RequireStaticErr { #[note(borrowck::used_impl_require_static)] UsedImpl { diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index b6e0f3faa73..ff33ae7e8f2 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -268,14 +268,14 @@ type FluentId = Cow<'static, str>; /// Translatable messages for subdiagnostics are typically attributes attached to a larger Fluent /// message so messages of this type must be combined with a `DiagnosticMessage` (using /// `DiagnosticMessage::with_subdiagnostic_message`) before rendering. However, subdiagnostics from -/// the `SessionSubdiagnostic` derive refer to Fluent identifiers directly. +/// the `Subdiagnostic` derive refer to Fluent identifiers directly. #[rustc_diagnostic_item = "SubdiagnosticMessage"] pub enum SubdiagnosticMessage { /// Non-translatable diagnostic message. // FIXME(davidtwco): can a `Cow<'static, str>` be used here? Str(String), /// Identifier of a Fluent message. Instances of this variant are generated by the - /// `SessionSubdiagnostic` derive. + /// `Subdiagnostic` derive. FluentIdentifier(FluentId), /// Attribute of a Fluent message. Needs to be combined with a Fluent identifier to produce an /// actual translated message. Instances of this variant are generated by the `fluent_messages` diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index d3a263ac56d..c66889189ad 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -176,8 +176,9 @@ impl IntoDiagnosticArg for hir::ConstContext { } /// Trait implemented by error types. This should not be implemented manually. Instead, use -/// `#[derive(SessionSubdiagnostic)]` -- see [rustc_macros::SessionSubdiagnostic]. -#[rustc_diagnostic_item = "AddSubdiagnostic"] +/// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic]. +#[cfg_attr(bootstrap, rustc_diagnostic_item = "AddSubdiagnostic")] +#[cfg_attr(not(bootstrap), rustc_diagnostic_item = "Subdiagnostic")] pub trait AddToDiagnostic { /// Add a subdiagnostic to an existing diagnostic. fn add_to_diagnostic(self, diag: &mut Diagnostic); @@ -891,8 +892,8 @@ impl Diagnostic { self } - /// Add a subdiagnostic from a type that implements `SessionSubdiagnostic` - see - /// [rustc_macros::SessionSubdiagnostic]. + /// Add a subdiagnostic from a type that implements `Subdiagnostic` - see + /// [rustc_macros::Subdiagnostic]. pub fn subdiagnostic(&mut self, subdiagnostic: impl AddToDiagnostic) -> &mut Self { subdiagnostic.add_to_diagnostic(self); self diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 7764ffd246e..6d2c7aac6af 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -593,7 +593,7 @@ pub fn compile_declarative_macro( (mk_syn_ext(expander), rule_spans) } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum ExplainDocComment { #[label(expand::explain_doc_comment_inner)] Inner { diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index 0c66ce475c4..3a89d90c88a 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -1,5 +1,5 @@ use rustc_errors::{fluent, AddToDiagnostic, IntoDiagnostic, ErrorGuaranteed, Handler}; -use rustc_macros::{Diagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_session::lint::Level; use rustc_span::{Span, Symbol}; @@ -51,7 +51,7 @@ pub struct MalformedAttribute { pub sub: MalformedAttributeSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum MalformedAttributeSub { #[label(lint::bad_attribute_argument)] BadAttributeArgument(#[primary_span] Span), diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 36d8ade22ae..942475d31fe 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -404,7 +404,7 @@ impl LateLintPass<'_> for Diagnostics { let Impl { of_trait: Some(of_trait), .. } = impl_ && let Some(def_id) = of_trait.trait_def_id() && let Some(name) = cx.tcx.get_diagnostic_name(def_id) && - matches!(name, sym::Diagnostic | sym::AddSubdiagnostic | sym::DecorateLint) + matches!(name, sym::Diagnostic | sym::Subdiagnostic | sym::DecorateLint) { found_impl = true; break; diff --git a/compiler/rustc_macros/src/diagnostics/mod.rs b/compiler/rustc_macros/src/diagnostics/mod.rs index 1d5b32c2556..8eaa8b87c0f 100644 --- a/compiler/rustc_macros/src/diagnostics/mod.rs +++ b/compiler/rustc_macros/src/diagnostics/mod.rs @@ -9,7 +9,7 @@ use diagnostic::{LintDiagnosticDerive, SessionDiagnosticDerive}; pub(crate) use fluent::fluent_messages; use proc_macro2::TokenStream; use quote::format_ident; -use subdiagnostic::SessionSubdiagnosticDerive; +use subdiagnostic::SubdiagnosticDerive; use synstructure::Structure; /// Implements `#[derive(Diagnostic)]`, which allows for errors to be specified as a struct, @@ -108,12 +108,12 @@ pub fn lint_diagnostic_derive(s: Structure<'_>) -> TokenStream { LintDiagnosticDerive::new(format_ident!("diag"), s).into_tokens() } -/// Implements `#[derive(SessionSubdiagnostic)]`, which allows for labels, notes, helps and +/// Implements `#[derive(Subdiagnostic)]`, which allows for labels, notes, helps and /// suggestions to be specified as a structs or enums, independent from the actual diagnostics /// emitting code or diagnostic derives. /// /// ```ignore (rust) -/// #[derive(SessionSubdiagnostic)] +/// #[derive(Subdiagnostic)] /// pub enum ExpectedIdentifierLabel<'tcx> { /// #[label(parser::expected_identifier)] /// WithoutFound { @@ -128,7 +128,7 @@ pub fn lint_diagnostic_derive(s: Structure<'_>) -> TokenStream { /// } /// } /// -/// #[derive(SessionSubdiagnostic)] +/// #[derive(Subdiagnostic)] /// #[suggestion_verbose(parser::raw_identifier)] /// pub struct RawIdentifierSuggestion<'tcx> { /// #[primary_span] @@ -155,5 +155,5 @@ pub fn lint_diagnostic_derive(s: Structure<'_>) -> TokenStream { /// diag.subdiagnostic(RawIdentifierSuggestion { span, applicability, ident }); /// ``` pub fn session_subdiagnostic_derive(s: Structure<'_>) -> TokenStream { - SessionSubdiagnosticDerive::new(s).into_tokens() + SubdiagnosticDerive::new(s).into_tokens() } diff --git a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs index f1bb7feb062..bdeca3420bc 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -98,19 +98,19 @@ impl quote::IdentFragment for SubdiagnosticKind { } /// The central struct for constructing the `add_to_diagnostic` method from an annotated struct. -pub(crate) struct SessionSubdiagnosticDerive<'a> { +pub(crate) struct SubdiagnosticDerive<'a> { structure: Structure<'a>, diag: syn::Ident, } -impl<'a> SessionSubdiagnosticDerive<'a> { +impl<'a> SubdiagnosticDerive<'a> { pub(crate) fn new(structure: Structure<'a>) -> Self { let diag = format_ident!("diag"); Self { structure, diag } } pub(crate) fn into_tokens(self) -> TokenStream { - let SessionSubdiagnosticDerive { mut structure, diag } = self; + let SubdiagnosticDerive { mut structure, diag } = self; let implementation = { let ast = structure.ast(); let span = ast.span().unwrap(); @@ -119,7 +119,7 @@ impl<'a> SessionSubdiagnosticDerive<'a> { syn::Data::Union(..) => { span_err( span, - "`#[derive(SessionSubdiagnostic)]` can only be used on structs and enums", + "`#[derive(Subdiagnostic)]` can only be used on structs and enums", ); } } @@ -146,7 +146,7 @@ impl<'a> SessionSubdiagnosticDerive<'a> { } } - let mut builder = SessionSubdiagnosticDeriveBuilder { + let mut builder = SubdiagnosticDeriveBuilder { diag: &diag, variant, span, @@ -178,10 +178,10 @@ impl<'a> SessionSubdiagnosticDerive<'a> { } /// Tracks persistent information required for building up the call to add to the diagnostic -/// for the final generated method. This is a separate struct to `SessionSubdiagnosticDerive` +/// for the final generated method. This is a separate struct to `SubdiagnosticDerive` /// only to be able to destructure and split `self.builder` and the `self.structure` up to avoid a /// double mut borrow later on. -struct SessionSubdiagnosticDeriveBuilder<'a> { +struct SubdiagnosticDeriveBuilder<'a> { /// The identifier to use for the generated `DiagnosticBuilder` instance. diag: &'a syn::Ident, @@ -205,7 +205,7 @@ struct SessionSubdiagnosticDeriveBuilder<'a> { has_suggestion_parts: bool, } -impl<'a> HasFieldMap for SessionSubdiagnosticDeriveBuilder<'a> { +impl<'a> HasFieldMap for SubdiagnosticDeriveBuilder<'a> { fn get_field_binding(&self, field: &String) -> Option<&TokenStream> { self.fields.get(field) } @@ -241,7 +241,7 @@ impl<'a> FromIterator<&'a SubdiagnosticKind> for KindsStatistics { } } -impl<'a> SessionSubdiagnosticDeriveBuilder<'a> { +impl<'a> SubdiagnosticDeriveBuilder<'a> { fn identify_kind(&mut self) -> Result, DiagnosticDeriveError> { let mut kind_slugs = vec![]; diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 9dd7ccad8bb..8fd23ee5ced 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -161,7 +161,7 @@ decl_derive!( suggestion_verbose)] => diagnostics::lint_diagnostic_derive ); decl_derive!( - [SessionSubdiagnostic, attributes( + [Subdiagnostic, attributes( // struct/variant attributes label, help, diff --git a/compiler/rustc_middle/src/error.rs b/compiler/rustc_middle/src/error.rs index 6d15feb888a..a4ceb494569 100644 --- a/compiler/rustc_middle/src/error.rs +++ b/compiler/rustc_middle/src/error.rs @@ -25,7 +25,7 @@ pub struct OpaqueHiddenTypeMismatch<'tcx> { pub sub: TypeMismatchReason, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum TypeMismatchReason { #[label(middle::conflict_types)] ConflictType { diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 9989ebb7cdf..78bc29fc375 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -20,7 +20,7 @@ use rustc_errors::{ fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult, }; use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed}; -use rustc_macros::{Diagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{Span, SpanSnippetError, DUMMY_SP}; @@ -261,7 +261,7 @@ struct BadTypePlus { pub sub: BadTypePlusSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum BadTypePlusSub { #[suggestion( parser::add_paren, @@ -342,7 +342,7 @@ pub struct InvalidVariableDeclaration { pub sub: InvalidVariableDeclarationSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum InvalidVariableDeclarationSub { #[suggestion( parser::switch_mut_let_order, @@ -372,7 +372,7 @@ pub(crate) struct InvalidComparisonOperator { pub sub: InvalidComparisonOperatorSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum InvalidComparisonOperatorSub { #[suggestion_short( parser::use_instead, @@ -400,7 +400,7 @@ pub(crate) struct InvalidLogicalOperator { pub sub: InvalidLogicalOperatorSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum InvalidLogicalOperatorSub { #[suggestion_short( parser::use_amp_amp_for_conjunction, @@ -605,7 +605,7 @@ pub(crate) struct IfExpressionMissingThenBlock { pub sub: IfExpressionMissingThenBlockSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum IfExpressionMissingThenBlockSub { #[help(parser::condition_possibly_unfinished)] UnfinishedCondition(#[primary_span] Span), @@ -668,7 +668,7 @@ pub(crate) struct MissingInInForLoop { pub sub: MissingInInForLoopSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub(crate) enum MissingInInForLoopSub { // Has been misleading, at least in the past (closed Issue #48492), thus maybe-incorrect #[suggestion_short(parser::use_in_not_of, applicability = "maybe-incorrect", code = "in")] diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index bff2978bd13..52aea9bba43 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1,5 +1,5 @@ use rustc_errors::{Applicability, MultiSpan}; -use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; #[derive(LintDiagnostic)] @@ -583,7 +583,7 @@ pub struct MacroExport; #[diag(passes::plugin_registrar)] pub struct PluginRegistrar; -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum UnusedNote { #[note(passes::unused_empty_lints_note)] EmptyList { name: Symbol }, diff --git a/compiler/rustc_privacy/src/errors.rs b/compiler/rustc_privacy/src/errors.rs index 71552119482..f3a617c2f0f 100644 --- a/compiler/rustc_privacy/src/errors.rs +++ b/compiler/rustc_privacy/src/errors.rs @@ -1,5 +1,5 @@ use rustc_errors::DiagnosticArgFromDisplay; -use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; #[derive(Diagnostic)] @@ -14,7 +14,7 @@ pub struct FieldIsPrivate { pub label: FieldIsPrivateLabel, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum FieldIsPrivateLabel { #[label(privacy::field_is_private_is_update_syntax_label)] IsUpdateSyntax { diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 4c770152f12..ceec75fce28 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -1,6 +1,7 @@ use rustc_errors::AddToDiagnostic; use rustc_session::Limit; use rustc_span::{Span, Symbol}; +use rustc_macros::{Diagnostic, Subdiagnostic}; pub struct CycleStack { pub span: Span, @@ -20,7 +21,7 @@ pub enum HandleCycleError { DelayBug, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum StackCount { #[note(query_system::cycle_stack_single)] Single, @@ -28,7 +29,7 @@ pub enum StackCount { Multiple, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum Alias { #[note(query_system::cycle_recursive_ty_alias)] #[help(query_system::cycle_recursive_ty_alias_help1)] @@ -38,7 +39,7 @@ pub enum Alias { Trait, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[note(query_system::cycle_usage)] pub struct CycleUsage { #[primary_span] diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index 7ffe757463f..997a45272bc 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -34,13 +34,13 @@ pub struct FeatureGateError<'a> { pub explain: &'a str, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[note(session::feature_diagnostic_for_issue)] pub struct FeatureDiagnosticForIssue { pub n: NonZeroU32, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[help(session::feature_diagnostic_help)] pub struct FeatureDiagnosticHelp { pub feature: Symbol, diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index ea69334616b..1baad6a9fd7 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -125,7 +125,6 @@ symbols! { Symbols { AcqRel, Acquire, - AddSubdiagnostic, Alignment, Any, Arc, @@ -283,6 +282,7 @@ symbols! { String, StructuralEq, StructuralPartialEq, + Subdiagnostic, SubdiagnosticMessage, Sync, T, diff --git a/compiler/rustc_ty_utils/src/errors.rs b/compiler/rustc_ty_utils/src/errors.rs index 85165187310..753c474a34b 100644 --- a/compiler/rustc_ty_utils/src/errors.rs +++ b/compiler/rustc_ty_utils/src/errors.rs @@ -1,6 +1,6 @@ //! Errors emitted by ty_utils -use rustc_macros::{Diagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::Span; @@ -22,7 +22,7 @@ pub struct GenericConstantTooComplex { pub sub: GenericConstantTooComplexSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum GenericConstantTooComplexSub { #[label(ty_utils::borrow_not_supported)] BorrowNotSupported(#[primary_span] Span), diff --git a/compiler/rustc_typeck/src/errors.rs b/compiler/rustc_typeck/src/errors.rs index 6f00591d54e..44df47e2fa0 100644 --- a/compiler/rustc_typeck/src/errors.rs +++ b/compiler/rustc_typeck/src/errors.rs @@ -1,7 +1,7 @@ //! Errors emitted by typeck. use rustc_errors::IntoDiagnostic; use rustc_errors::{error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler}; -use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::{symbol::Ident, Span, Symbol}; @@ -194,7 +194,7 @@ pub struct AddressOfTemporaryTaken { pub span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum AddReturnTypeSuggestion { #[suggestion( typeck::add_return_type_add, @@ -217,7 +217,7 @@ pub enum AddReturnTypeSuggestion { }, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum ExpectedReturnTypeLabel<'tcx> { #[label(typeck::expected_default_return_type)] Unit { diff --git a/src/test/ui-fulldeps/internal-lints/diagnostics.rs b/src/test/ui-fulldeps/internal-lints/diagnostics.rs index 93766de9a91..4c2c28dc336 100644 --- a/src/test/ui-fulldeps/internal-lints/diagnostics.rs +++ b/src/test/ui-fulldeps/internal-lints/diagnostics.rs @@ -15,7 +15,7 @@ use rustc_errors::{ AddToDiagnostic, IntoDiagnostic, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, fluent }; -use rustc_macros::{Diagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::Span; #[derive(Diagnostic)] @@ -25,7 +25,7 @@ struct DeriveSessionDiagnostic { span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[note(parser::add_paren)] struct Note { #[primary_span] diff --git a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs index fd8128c31f8..80ea9082881 100644 --- a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs +++ b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.rs @@ -17,7 +17,7 @@ use rustc_span::symbol::Ident; use rustc_span::Span; extern crate rustc_macros; -use rustc_macros::{Diagnostic, LintDiagnostic, SessionSubdiagnostic}; +use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; extern crate rustc_middle; use rustc_middle::ty::Ty; @@ -462,7 +462,7 @@ struct NoApplicability { suggestion: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[note(parser::add_paren)] struct Note; diff --git a/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs b/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs index 812ca0c72bd..9fbe7b1f4c8 100644 --- a/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs +++ b/src/test/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs @@ -1,8 +1,8 @@ // check-fail -// Tests error conditions for specifying subdiagnostics using #[derive(SessionSubdiagnostic)] +// Tests error conditions for specifying subdiagnostics using #[derive(Subdiagnostic)] // The proc_macro2 crate handles spans differently when on beta/stable release rather than nightly, -// changing the output of this test. Since SessionSubdiagnostic is strictly internal to the compiler +// changing the output of this test. Since Subdiagnostic is strictly internal to the compiler // the test is just ignored on stable and beta: // ignore-beta // ignore-stable @@ -17,9 +17,9 @@ extern crate rustc_macros; use rustc_errors::Applicability; use rustc_span::Span; -use rustc_macros::SessionSubdiagnostic; +use rustc_macros::Subdiagnostic; -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] struct A { #[primary_span] @@ -27,7 +27,7 @@ struct A { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum B { #[label(parser::add_paren)] A { @@ -43,14 +43,14 @@ enum B { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] //~^ ERROR label without `#[primary_span]` field struct C { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label] //~^ ERROR `#[label]` is not a valid attribute struct D { @@ -59,7 +59,7 @@ struct D { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[foo] //~^ ERROR `#[foo]` is not a valid attribute //~^^ ERROR cannot find attribute `foo` in this scope @@ -69,7 +69,7 @@ struct E { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label = "..."] //~^ ERROR `#[label = ...]` is not a valid attribute struct F { @@ -78,7 +78,7 @@ struct F { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(bug = "...")] //~^ ERROR `#[label(bug = ...)]` is not a valid attribute struct G { @@ -87,7 +87,7 @@ struct G { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label("...")] //~^ ERROR `#[label("...")]` is not a valid attribute struct H { @@ -96,7 +96,7 @@ struct H { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(slug = 4)] //~^ ERROR `#[label(slug = ...)]` is not a valid attribute struct J { @@ -105,7 +105,7 @@ struct J { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(slug("..."))] //~^ ERROR `#[label(slug(...))]` is not a valid attribute struct K { @@ -114,7 +114,7 @@ struct K { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(slug)] //~^ ERROR cannot find value `slug` in module `rustc_errors::fluent` //~^^ NOTE not found in `rustc_errors::fluent` @@ -124,7 +124,7 @@ struct L { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label()] //~^ ERROR diagnostic slug must be first argument of a `#[label(...)]` attribute struct M { @@ -133,7 +133,7 @@ struct M { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren, code = "...")] //~^ ERROR `code` is not a valid nested attribute of a `label` attribute struct N { @@ -142,7 +142,7 @@ struct N { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren, applicability = "machine-applicable")] //~^ ERROR `applicability` is not a valid nested attribute of a `label` attribute struct O { @@ -151,7 +151,7 @@ struct O { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[foo] //~^ ERROR cannot find attribute `foo` in this scope //~^^ ERROR unsupported type attribute for subdiagnostic enum @@ -164,7 +164,7 @@ enum P { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum Q { #[bar] //~^ ERROR `#[bar]` is not a valid attribute @@ -176,7 +176,7 @@ enum Q { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum R { #[bar = "..."] //~^ ERROR `#[bar = ...]` is not a valid attribute @@ -188,7 +188,7 @@ enum R { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum S { #[bar = 4] //~^ ERROR `#[bar = ...]` is not a valid attribute @@ -200,7 +200,7 @@ enum S { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum T { #[bar("...")] //~^ ERROR `#[bar(...)]` is not a valid attribute @@ -212,7 +212,7 @@ enum T { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum U { #[label(code = "...")] //~^ ERROR diagnostic slug must be first argument of a `#[label(...)]` attribute @@ -223,7 +223,7 @@ enum U { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum V { #[label(parser::add_paren)] A { @@ -239,7 +239,7 @@ enum V { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] //~^ ERROR label without `#[primary_span]` field struct W { @@ -248,7 +248,7 @@ struct W { span: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] struct X { #[primary_span] @@ -258,7 +258,7 @@ struct X { applicability: Applicability, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] struct Y { #[primary_span] @@ -269,7 +269,7 @@ struct Y { bar: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] struct Z { #[primary_span] @@ -280,7 +280,7 @@ struct Z { bar: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] struct AA { #[primary_span] @@ -291,7 +291,7 @@ struct AA { bar: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] struct AB { #[primary_span] @@ -300,14 +300,14 @@ struct AB { z: Z } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] union AC { //~^ ERROR unexpected unsupported untagged union span: u32, b: u64 } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] #[label(parser::add_paren)] struct AD { @@ -315,7 +315,7 @@ struct AD { span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren, parser::add_paren)] //~^ ERROR `#[label(parser::add_paren)]` is not a valid attribute struct AE { @@ -323,7 +323,7 @@ struct AE { span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(parser::add_paren)] struct AF { #[primary_span] @@ -334,14 +334,14 @@ struct AF { span_b: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] struct AG { //~^ ERROR subdiagnostic kind not specified #[primary_span] span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code = "...")] struct AH { #[primary_span] @@ -351,7 +351,7 @@ struct AH { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum AI { #[suggestion(parser::add_paren, code = "...")] A { @@ -371,7 +371,7 @@ enum AI { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code = "...", code = "...")] //~^ ERROR specified multiple times //~^^ NOTE previously specified here @@ -382,7 +382,7 @@ struct AJ { applicability: Applicability, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code = "...")] struct AK { #[primary_span] @@ -395,7 +395,7 @@ struct AK { applicability_b: Applicability, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code = "...")] struct AL { #[primary_span] @@ -405,14 +405,14 @@ struct AL { applicability: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code = "...")] struct AM { #[primary_span] span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren)] //~^ ERROR suggestion without `code = "..."` struct AN { @@ -422,7 +422,7 @@ struct AN { applicability: Applicability, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code ="...", applicability = "foo")] //~^ ERROR invalid applicability struct AO { @@ -430,31 +430,31 @@ struct AO { span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[help(parser::add_paren)] struct AP { var: String } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[note(parser::add_paren)] struct AQ; -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code = "...")] //~^ ERROR suggestion without `#[primary_span]` field struct AR { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code ="...", applicability = "machine-applicable")] struct AS { #[primary_span] span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label] //~^ ERROR unsupported type attribute for subdiagnostic enum enum AT { @@ -466,7 +466,7 @@ enum AT { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code ="{var}", applicability = "machine-applicable")] struct AU { #[primary_span] @@ -474,7 +474,7 @@ struct AU { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code ="{var}", applicability = "machine-applicable")] //~^ ERROR `var` doesn't refer to a field on this type struct AV { @@ -482,7 +482,7 @@ struct AV { span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum AW { #[suggestion(parser::add_paren, code ="{var}", applicability = "machine-applicable")] A { @@ -492,7 +492,7 @@ enum AW { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] enum AX { #[suggestion(parser::add_paren, code ="{var}", applicability = "machine-applicable")] //~^ ERROR `var` doesn't refer to a field on this type @@ -502,18 +502,18 @@ enum AX { } } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[warning(parser::add_paren)] struct AY {} -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[warning(parser::add_paren)] struct AZ { #[primary_span] span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[suggestion(parser::add_paren, code = "...")] //~^ ERROR suggestion without `#[primary_span]` field struct BA { @@ -528,7 +528,7 @@ struct BA { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren, code = "...", applicability = "machine-applicable")] //~^ ERROR multipart suggestion without any `#[suggestion_part(...)]` fields //~| ERROR `code` is not a valid nested attribute of a `multipart_suggestion` attribute @@ -536,7 +536,7 @@ struct BBa { var: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] struct BBb { #[suggestion_part] @@ -544,7 +544,7 @@ struct BBb { span1: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] struct BBc { #[suggestion_part()] @@ -552,7 +552,7 @@ struct BBc { span1: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren)] //~^ ERROR multipart suggestion without any `#[suggestion_part(...)]` fields struct BC { @@ -561,7 +561,7 @@ struct BC { span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren)] struct BD { #[suggestion_part] @@ -581,7 +581,7 @@ struct BD { s2: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] struct BE { #[suggestion_part(code = "...", code = ",,,")] @@ -590,7 +590,7 @@ struct BE { span: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] struct BF { #[suggestion_part(code = "(")] @@ -599,7 +599,7 @@ struct BF { second: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren)] struct BG { #[applicability] @@ -610,7 +610,7 @@ struct BG { second: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] //~^ NOTE previously specified here struct BH { @@ -623,7 +623,7 @@ struct BH { second: Span, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[multipart_suggestion(parser::add_paren, applicability = "machine-applicable")] struct BI { #[suggestion_part(code = "")] -- cgit 1.4.1-3-g733a5 From e52e2344dc574922ce4f8ddfd508f8bfdec3f404 Mon Sep 17 00:00:00 2001 From: Jhonny Bill Mena Date: Thu, 15 Sep 2022 00:01:44 -0400 Subject: FIX - adopt new Diagnostic naming in newly migrated modules FIX - ambiguous Diagnostic link in docs UPDATE - rename diagnostic_items to IntoDiagnostic and AddToDiagnostic [Gardening] FIX - formatting via `x fmt` FIX - rebase conflicts. NOTE: Confirm wheather or not we want to handle TargetDataLayoutErrorsWrapper this way DELETE - unneeded allow attributes in Handler method FIX - broken test FIX - Rebase conflict UPDATE - rename residual _SessionDiagnostic and fix LintDiag link --- compiler/rustc_ast_lowering/src/errors.rs | 2 +- compiler/rustc_attr/src/session_diagnostics.rs | 3 +- compiler/rustc_errors/src/diagnostic.rs | 2 +- compiler/rustc_errors/src/diagnostic_builder.rs | 2 +- compiler/rustc_errors/src/lib.rs | 44 +---------------- compiler/rustc_expand/src/base.rs | 2 +- compiler/rustc_infer/src/errors/mod.rs | 36 +++++++------- .../rustc_infer/src/errors/note_and_explain.rs | 4 +- .../nice_region_error/different_lifetimes.rs | 2 +- compiler/rustc_lint/src/errors.rs | 2 +- compiler/rustc_lint/src/internal.rs | 2 +- .../rustc_macros/src/diagnostics/diagnostic.rs | 6 +-- compiler/rustc_macros/src/diagnostics/mod.rs | 6 +-- compiler/rustc_metadata/src/errors.rs | 2 +- compiler/rustc_middle/src/ty/context.rs | 3 +- compiler/rustc_monomorphize/src/errors.rs | 2 +- compiler/rustc_parse/src/parser/diagnostics.rs | 4 +- compiler/rustc_passes/src/errors.rs | 2 +- compiler/rustc_query_system/src/error.rs | 2 +- compiler/rustc_query_system/src/query/job.rs | 2 +- compiler/rustc_session/src/config.rs | 3 +- compiler/rustc_session/src/errors.rs | 56 +++++++++++----------- compiler/rustc_session/src/parse.rs | 4 +- compiler/rustc_session/src/session.rs | 4 +- compiler/rustc_span/src/symbol.rs | 4 +- compiler/rustc_trait_selection/src/errors.rs | 2 +- src/test/ui-fulldeps/internal-lints/diagnostics.rs | 10 ++-- .../session-diagnostic/diagnostic-derive.stderr | 2 +- 28 files changed, 88 insertions(+), 127 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index 052979d6d45..1ad5fa21d85 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -335,7 +335,7 @@ pub struct InclusiveRangeWithNoEnd { pub span: Span, } -#[derive(SessionDiagnostic, Clone, Copy)] +#[derive(Diagnostic, Clone, Copy)] #[diag(ast_lowering::trait_fn_async, code = "E0706")] #[note] #[note(ast_lowering::note2)] diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 940a48ed915..d3e9a16a9a8 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -2,8 +2,7 @@ use std::num::IntErrorKind; use rustc_ast as ast; use rustc_errors::{ - error_code, fluent, Applicability, DiagnosticBuilder, IntoDiagnostic, ErrorGuaranteed, - Handler, + error_code, fluent, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler, IntoDiagnostic, }; use rustc_macros::Diagnostic; use rustc_span::{Span, Symbol}; diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index c66889189ad..a52e95e92d5 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -178,7 +178,7 @@ impl IntoDiagnosticArg for hir::ConstContext { /// Trait implemented by error types. This should not be implemented manually. Instead, use /// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic]. #[cfg_attr(bootstrap, rustc_diagnostic_item = "AddSubdiagnostic")] -#[cfg_attr(not(bootstrap), rustc_diagnostic_item = "Subdiagnostic")] +#[cfg_attr(not(bootstrap), rustc_diagnostic_item = "AddToDiagnostic")] pub trait AddToDiagnostic { /// Add a subdiagnostic to an existing diagnostic. fn add_to_diagnostic(self, diag: &mut Diagnostic); diff --git a/compiler/rustc_errors/src/diagnostic_builder.rs b/compiler/rustc_errors/src/diagnostic_builder.rs index f9b46053486..b4ba65ca96d 100644 --- a/compiler/rustc_errors/src/diagnostic_builder.rs +++ b/compiler/rustc_errors/src/diagnostic_builder.rs @@ -16,7 +16,7 @@ use std::thread::panicking; /// Trait implemented by error types. This should not be implemented manually. Instead, use /// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic]. #[cfg_attr(bootstrap, rustc_diagnostic_item = "SessionDiagnostic")] -#[cfg_attr(not(bootstrap), rustc_diagnostic_item = "Diagnostic")] +#[cfg_attr(not(bootstrap), rustc_diagnostic_item = "IntoDiagnostic")] pub trait IntoDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> { /// Write out as a diagnostic out of `Handler`. #[must_use] diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 19cae2c9077..68971cebc35 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -437,11 +437,11 @@ struct HandlerInner { /// have been converted. check_unstable_expect_diagnostics: bool, - /// Expected [`Diagnostic`]s store a [`LintExpectationId`] as part of + /// Expected [`Diagnostic`][diagnostic::Diagnostic]s store a [`LintExpectationId`] as part of /// the lint level. [`LintExpectationId`]s created early during the compilation /// (before `HirId`s have been defined) are not stable and can therefore not be /// stored on disk. This buffer stores these diagnostics until the ID has been - /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`]s are the + /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`][diagnostic::Diagnostic]s are the /// submitted for storage and added to the list of fulfilled expectations. unstable_expect_diagnostics: Vec, @@ -647,8 +647,6 @@ impl Handler { /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_diagnostic( &self, msg: impl Into, @@ -662,8 +660,6 @@ impl Handler { /// * `can_emit_warnings` is `true` /// * `is_force_warn` was set in `DiagnosticId::Lint` #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_warn( &self, span: impl Into, @@ -680,8 +676,6 @@ impl Handler { /// Attempting to `.emit()` the builder will only emit if either: /// * `can_emit_warnings` is `true` /// * `is_force_warn` was set in `DiagnosticId::Lint` - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_warn_with_expectation( &self, span: impl Into, @@ -695,8 +689,6 @@ impl Handler { /// Construct a builder at the `Allow` level at the given `span` and with the `msg`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_allow( &self, span: impl Into, @@ -710,8 +702,6 @@ impl Handler { /// Construct a builder at the `Warning` level at the given `span` and with the `msg`. /// Also include a code. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_warn_with_code( &self, span: impl Into, @@ -729,8 +719,6 @@ impl Handler { /// * `can_emit_warnings` is `true` /// * `is_force_warn` was set in `DiagnosticId::Lint` #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_warn(&self, msg: impl Into) -> DiagnosticBuilder<'_, ()> { DiagnosticBuilder::new(self, Level::Warning(None), msg) } @@ -741,8 +729,6 @@ impl Handler { /// Attempting to `.emit()` the builder will only emit if either: /// * `can_emit_warnings` is `true` /// * `is_force_warn` was set in `DiagnosticId::Lint` - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_warn_with_expectation( &self, msg: impl Into, @@ -753,16 +739,12 @@ impl Handler { /// Construct a builder at the `Allow` level with the `msg`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_allow(&self, msg: impl Into) -> DiagnosticBuilder<'_, ()> { DiagnosticBuilder::new(self, Level::Allow, msg) } /// Construct a builder at the `Expect` level with the `msg`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_expect( &self, msg: impl Into, @@ -773,8 +755,6 @@ impl Handler { /// Construct a builder at the `Error` level at the given `span` and with the `msg`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_err( &self, span: impl Into, @@ -787,8 +767,6 @@ impl Handler { /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_err_with_code( &self, span: impl Into, @@ -803,8 +781,6 @@ impl Handler { /// Construct a builder at the `Error` level with the `msg`. // FIXME: This method should be removed (every error should have an associated error code). #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_err( &self, msg: impl Into, @@ -814,16 +790,12 @@ impl Handler { /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors. #[doc(hidden)] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_err_lint(&self, msg: impl Into) -> DiagnosticBuilder<'_, ()> { DiagnosticBuilder::new(self, Level::Error { lint: true }, msg) } /// Construct a builder at the `Error` level with the `msg` and the `code`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_err_with_code( &self, msg: impl Into, @@ -836,8 +808,6 @@ impl Handler { /// Construct a builder at the `Warn` level with the `msg` and the `code`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_warn_with_code( &self, msg: impl Into, @@ -850,8 +820,6 @@ impl Handler { /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_fatal( &self, span: impl Into, @@ -864,8 +832,6 @@ impl Handler { /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_span_fatal_with_code( &self, span: impl Into, @@ -879,24 +845,18 @@ impl Handler { /// Construct a builder at the `Error` level with the `msg`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_fatal(&self, msg: impl Into) -> DiagnosticBuilder<'_, !> { DiagnosticBuilder::new_fatal(self, msg) } /// Construct a builder at the `Help` level with the `msg`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_help(&self, msg: impl Into) -> DiagnosticBuilder<'_, ()> { DiagnosticBuilder::new(self, Level::Help, msg) } /// Construct a builder at the `Note` level with the `msg`. #[rustc_lint_diagnostics] - #[allow(rustc::diagnostic_outside_of_impl)] - #[allow(rustc::untranslatable_diagnostic)] pub fn struct_note_without_error( &self, msg: impl Into, diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index ca429b6adc1..cd8a525e062 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -11,7 +11,7 @@ use rustc_attr::{self as attr, Deprecation, Stability}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::sync::{self, Lrc}; use rustc_errors::{ - Applicability, DiagnosticBuilder, IntoDiagnostic, ErrorGuaranteed, MultiSpan, PResult, + Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult, }; use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT; use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics}; diff --git a/compiler/rustc_infer/src/errors/mod.rs b/compiler/rustc_infer/src/errors/mod.rs index d232a186462..85b877652c6 100644 --- a/compiler/rustc_infer/src/errors/mod.rs +++ b/compiler/rustc_infer/src/errors/mod.rs @@ -1,10 +1,10 @@ use hir::GenericParamKind; use rustc_errors::{ - fluent, AddSubdiagnostic, Applicability, DiagnosticMessage, DiagnosticStyledString, MultiSpan, + fluent, AddToDiagnostic, Applicability, DiagnosticMessage, DiagnosticStyledString, MultiSpan, }; use rustc_hir as hir; use rustc_hir::{FnRetTy, Ty}; -use rustc_macros::SessionDiagnostic; +use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_middle::ty::{Region, TyCtxt}; use rustc_span::symbol::kw; use rustc_span::{symbol::Ident, BytePos, Span}; @@ -16,7 +16,7 @@ use crate::infer::error_reporting::{ pub mod note_and_explain; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(infer::opaque_hidden_type)] pub struct OpaqueHiddenTypeDiag { #[primary_span] @@ -28,7 +28,7 @@ pub struct OpaqueHiddenTypeDiag { pub hidden_type: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(infer::type_annotations_needed, code = "E0282")] pub struct AnnotationRequired<'a> { #[primary_span] @@ -46,7 +46,7 @@ pub struct AnnotationRequired<'a> { } // Copy of `AnnotationRequired` for E0283 -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(infer::type_annotations_needed, code = "E0283")] pub struct AmbigousImpl<'a> { #[primary_span] @@ -64,7 +64,7 @@ pub struct AmbigousImpl<'a> { } // Copy of `AnnotationRequired` for E0284 -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(infer::type_annotations_needed, code = "E0284")] pub struct AmbigousReturn<'a> { #[primary_span] @@ -81,7 +81,7 @@ pub struct AmbigousReturn<'a> { pub multi_suggestions: Vec>, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(infer::need_type_info_in_generator, code = "E0698")] pub struct NeedTypeInfoInGenerator<'a> { #[primary_span] @@ -92,7 +92,7 @@ pub struct NeedTypeInfoInGenerator<'a> { } // Used when a better one isn't available -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] #[label(infer::label_bad)] pub struct InferenceBadError<'a> { #[primary_span] @@ -106,7 +106,7 @@ pub struct InferenceBadError<'a> { pub name: String, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum SourceKindSubdiag<'a> { #[suggestion_verbose( infer::source_kind_subdiag_let, @@ -147,7 +147,7 @@ pub enum SourceKindSubdiag<'a> { }, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum SourceKindMultiSuggestion<'a> { #[multipart_suggestion_verbose( infer::source_kind_fully_qualified, @@ -228,7 +228,7 @@ pub enum RegionOriginNote<'a> { }, } -impl AddSubdiagnostic for RegionOriginNote<'_> { +impl AddToDiagnostic for RegionOriginNote<'_> { fn add_to_diagnostic(self, diag: &mut rustc_errors::Diagnostic) { let mut label_or_note = |span, msg: DiagnosticMessage| { let sub_count = diag.children.iter().filter(|d| d.span.is_dummy()).count(); @@ -289,7 +289,7 @@ pub enum LifetimeMismatchLabels { }, } -impl AddSubdiagnostic for LifetimeMismatchLabels { +impl AddToDiagnostic for LifetimeMismatchLabels { fn add_to_diagnostic(self, diag: &mut rustc_errors::Diagnostic) { match self { LifetimeMismatchLabels::InRet { param_span, ret_span, span, label_var1 } => { @@ -339,7 +339,7 @@ pub struct AddLifetimeParamsSuggestion<'a> { pub add_note: bool, } -impl AddSubdiagnostic for AddLifetimeParamsSuggestion<'_> { +impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> { fn add_to_diagnostic(self, diag: &mut rustc_errors::Diagnostic) { let mut mk_suggestion = || { let ( @@ -422,7 +422,7 @@ impl AddSubdiagnostic for AddLifetimeParamsSuggestion<'_> { } } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(infer::lifetime_mismatch, code = "E0623")] pub struct LifetimeMismatch<'a> { #[primary_span] @@ -438,7 +438,7 @@ pub struct IntroducesStaticBecauseUnmetLifetimeReq { pub binding_span: Span, } -impl AddSubdiagnostic for IntroducesStaticBecauseUnmetLifetimeReq { +impl AddToDiagnostic for IntroducesStaticBecauseUnmetLifetimeReq { fn add_to_diagnostic(mut self, diag: &mut rustc_errors::Diagnostic) { self.unmet_requirements .push_span_label(self.binding_span, fluent::infer::msl_introduces_static); @@ -450,7 +450,7 @@ pub struct ImplNote { pub impl_span: Option, } -impl AddSubdiagnostic for ImplNote { +impl AddToDiagnostic for ImplNote { fn add_to_diagnostic(self, diag: &mut rustc_errors::Diagnostic) { match self.impl_span { Some(span) => diag.span_note(span, fluent::infer::msl_impl_note), @@ -465,7 +465,7 @@ pub enum TraitSubdiag { } // FIXME(#100717) used in `Vec` so requires eager translation/list support -impl AddSubdiagnostic for TraitSubdiag { +impl AddToDiagnostic for TraitSubdiag { fn add_to_diagnostic(self, diag: &mut rustc_errors::Diagnostic) { match self { TraitSubdiag::Note { span } => { @@ -483,7 +483,7 @@ impl AddSubdiagnostic for TraitSubdiag { } } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(infer::mismatched_static_lifetime)] pub struct MismatchedStaticLifetime<'a> { #[primary_span] diff --git a/compiler/rustc_infer/src/errors/note_and_explain.rs b/compiler/rustc_infer/src/errors/note_and_explain.rs index 7e051835b4b..7f54918f736 100644 --- a/compiler/rustc_infer/src/errors/note_and_explain.rs +++ b/compiler/rustc_infer/src/errors/note_and_explain.rs @@ -1,5 +1,5 @@ use crate::infer::error_reporting::nice_region_error::find_anon_type; -use rustc_errors::{self, fluent, AddSubdiagnostic, IntoDiagnosticArg}; +use rustc_errors::{self, fluent, AddToDiagnostic, IntoDiagnosticArg}; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::{symbol::kw, Span}; @@ -158,7 +158,7 @@ impl RegionExplanation<'_> { } } -impl AddSubdiagnostic for RegionExplanation<'_> { +impl AddToDiagnostic for RegionExplanation<'_> { fn add_to_diagnostic(self, diag: &mut rustc_errors::Diagnostic) { if let Some(span) = self.desc.span { diag.span_note(span, fluent::infer::region_explanation); diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs index 3a4320a9a8f..da0271a345e 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/different_lifetimes.rs @@ -11,7 +11,7 @@ use crate::infer::lexical_region_resolve::RegionResolutionError; use crate::infer::SubregionOrigin; use crate::infer::TyCtxt; -use rustc_errors::AddSubdiagnostic; +use rustc_errors::AddToDiagnostic; use rustc_errors::{Diagnostic, ErrorGuaranteed}; use rustc_hir::Ty; use rustc_middle::ty::Region; diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index 3a89d90c88a..880f3fbd00e 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -1,4 +1,4 @@ -use rustc_errors::{fluent, AddToDiagnostic, IntoDiagnostic, ErrorGuaranteed, Handler}; +use rustc_errors::{fluent, AddToDiagnostic, ErrorGuaranteed, Handler, IntoDiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_session::lint::Level; use rustc_span::{Span, Symbol}; diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 942475d31fe..d8a03024d13 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -404,7 +404,7 @@ impl LateLintPass<'_> for Diagnostics { let Impl { of_trait: Some(of_trait), .. } = impl_ && let Some(def_id) = of_trait.trait_def_id() && let Some(name) = cx.tcx.get_diagnostic_name(def_id) && - matches!(name, sym::Diagnostic | sym::Subdiagnostic | sym::DecorateLint) + matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint) { found_impl = true; break; diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic.rs b/compiler/rustc_macros/src/diagnostics/diagnostic.rs index c1aae04fcee..3b8d9594eb9 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -9,13 +9,13 @@ use syn::spanned::Spanned; use synstructure::Structure; /// The central struct for constructing the `into_diagnostic` method from an annotated struct. -pub(crate) struct SessionDiagnosticDerive<'a> { +pub(crate) struct DiagnosticDerive<'a> { structure: Structure<'a>, handler: syn::Ident, builder: DiagnosticDeriveBuilder, } -impl<'a> SessionDiagnosticDerive<'a> { +impl<'a> DiagnosticDerive<'a> { pub(crate) fn new(diag: syn::Ident, handler: syn::Ident, structure: Structure<'a>) -> Self { Self { builder: DiagnosticDeriveBuilder { @@ -31,7 +31,7 @@ impl<'a> SessionDiagnosticDerive<'a> { } pub(crate) fn into_tokens(self) -> TokenStream { - let SessionDiagnosticDerive { mut structure, handler, mut builder } = self; + let DiagnosticDerive { mut structure, handler, mut builder } = self; let ast = structure.ast(); let implementation = { diff --git a/compiler/rustc_macros/src/diagnostics/mod.rs b/compiler/rustc_macros/src/diagnostics/mod.rs index 8eaa8b87c0f..4166816b5e3 100644 --- a/compiler/rustc_macros/src/diagnostics/mod.rs +++ b/compiler/rustc_macros/src/diagnostics/mod.rs @@ -5,7 +5,7 @@ mod fluent; mod subdiagnostic; mod utils; -use diagnostic::{LintDiagnosticDerive, SessionDiagnosticDerive}; +use diagnostic::{DiagnosticDerive, LintDiagnosticDerive}; pub(crate) use fluent::fluent_messages; use proc_macro2::TokenStream; use quote::format_ident; @@ -59,7 +59,7 @@ use synstructure::Structure; /// See rustc dev guide for more examples on using the `#[derive(Diagnostic)]`: /// pub fn session_diagnostic_derive(s: Structure<'_>) -> TokenStream { - SessionDiagnosticDerive::new(format_ident!("diag"), format_ident!("handler"), s).into_tokens() + DiagnosticDerive::new(format_ident!("diag"), format_ident!("handler"), s).into_tokens() } /// Implements `#[derive(LintDiagnostic)]`, which allows for lints to be specified as a struct, @@ -103,7 +103,7 @@ pub fn session_diagnostic_derive(s: Structure<'_>) -> TokenStream { /// ``` /// /// See rustc dev guide for more examples on using the `#[derive(LintDiagnostic)]`: -/// +/// pub fn lint_diagnostic_derive(s: Structure<'_>) -> TokenStream { LintDiagnosticDerive::new(format_ident!("diag"), s).into_tokens() } diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 8ff4eb5fdbc..1cd550644bf 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -3,7 +3,7 @@ use std::{ path::{Path, PathBuf}, }; -use rustc_errors::{error_code, IntoDiagnostic, ErrorGuaranteed}; +use rustc_errors::{error_code, ErrorGuaranteed, IntoDiagnostic}; use rustc_macros::Diagnostic; use rustc_session::config; use rustc_span::{sym, Span, Symbol}; diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 10c5933574f..2b5b4017a5a 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -53,6 +53,7 @@ use rustc_query_system::ich::StableHashingContext; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_session::config::{CrateType, OutputFilenames}; use rustc_session::cstore::CrateStoreDyn; +use rustc_session::errors::TargetDataLayoutErrorsWrapper; use rustc_session::lint::Lint; use rustc_session::Limit; use rustc_session::Session; @@ -1245,7 +1246,7 @@ impl<'tcx> TyCtxt<'tcx> { output_filenames: OutputFilenames, ) -> GlobalCtxt<'tcx> { let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| { - s.emit_fatal(err); + s.emit_fatal(TargetDataLayoutErrorsWrapper(err)); }); let interners = CtxtInterners::new(arena); let common_types = CommonTypes::new( diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index cdc2c74ac8f..cf6e18c013b 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; -use rustc_errors::IntoDiagnostic; use rustc_errors::ErrorGuaranteed; +use rustc_errors::IntoDiagnostic; use rustc_macros::{Diagnostic, LintDiagnostic}; use rustc_span::Span; diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 78bc29fc375..dcea11eadcb 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -434,7 +434,7 @@ pub(crate) struct NotAsNegationOperator { pub sub: NotAsNegationOperatorSub, } -#[derive(SessionSubdiagnostic)] +#[derive(Subdiagnostic)] pub enum NotAsNegationOperatorSub { #[suggestion_short( parser::unexpected_token_after_not_default, @@ -737,7 +737,7 @@ pub(crate) struct RemoveLet { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(parser::use_eq_instead)] pub(crate) struct UseEqInstead { #[primary_span] diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 52aea9bba43..be67c9e3b82 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -650,7 +650,7 @@ pub struct RustcLintOptDenyFieldAccess { pub span: Span, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(passes::collapse_debuginfo)] pub struct CollapseDebuginfo { #[primary_span] diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index ceec75fce28..8602a4cf5ae 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -1,7 +1,7 @@ use rustc_errors::AddToDiagnostic; +use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_session::Limit; use rustc_span::{Span, Symbol}; -use rustc_macros::{Diagnostic, Subdiagnostic}; pub struct CycleStack { pub span: Span, diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 6d26c8f47f3..64aba4703ca 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -4,7 +4,7 @@ use crate::query::{QueryContext, QueryStackFrame}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{ - Diagnostic, DiagnosticBuilder, IntoDiagnostic, ErrorGuaranteed, Handler, Level, + Diagnostic, DiagnosticBuilder, ErrorGuaranteed, Handler, IntoDiagnostic, Level, }; use rustc_hir::def::DefKind; use rustc_session::Session; diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 8bb3878fbbb..57c9a3f4822 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -3,6 +3,7 @@ pub use crate::options::*; +use crate::errors::TargetDataLayoutErrorsWrapper; use crate::search_paths::SearchPath; use crate::utils::{CanonicalizedPath, NativeLib, NativeLibKind}; use crate::{early_error, early_warn, Session}; @@ -898,7 +899,7 @@ fn default_configuration(sess: &Session) -> CrateConfig { let max_atomic_width = sess.target.max_atomic_width(); let atomic_cas = sess.target.atomic_cas; let layout = TargetDataLayout::parse(&sess.target).unwrap_or_else(|err| { - sess.emit_fatal(err); + sess.emit_fatal(TargetDataLayoutErrorsWrapper(err)); }); let mut ret = CrateConfig::default(); diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index 997a45272bc..e01dafe2102 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -1,9 +1,10 @@ use std::num::NonZeroU32; use crate::cgu_reuse_tracker::CguReuse; -use crate::{self as rustc_session, SessionDiagnostic}; -use rustc_errors::{fluent, DiagnosticBuilder, ErrorGuaranteed, Handler, MultiSpan}; -use rustc_macros::SessionDiagnostic; +use rustc_errors::{ + fluent, DiagnosticBuilder, ErrorGuaranteed, Handler, IntoDiagnostic, MultiSpan, +}; +use rustc_macros::Diagnostic; use rustc_span::{Span, Symbol}; use rustc_target::abi::TargetDataLayoutErrors; use rustc_target::spec::{SplitDebuginfo, StackProtector, TargetTriple}; @@ -46,10 +47,12 @@ pub struct FeatureDiagnosticHelp { pub feature: Symbol, } -impl IntoDiagnostic<'_, !> for TargetDataLayoutErrors<'_> { +pub struct TargetDataLayoutErrorsWrapper<'a>(pub TargetDataLayoutErrors<'a>); + +impl IntoDiagnostic<'_, !> for TargetDataLayoutErrorsWrapper<'_> { fn into_diagnostic(self, handler: &Handler) -> DiagnosticBuilder<'_, !> { let mut diag; - match self { + match self.0 { TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => { diag = handler.struct_fatal(fluent::session::target_invalid_address_space); diag.set_arg("addr_space", addr_space); @@ -97,87 +100,87 @@ impl IntoDiagnostic<'_, !> for TargetDataLayoutErrors<'_> { } } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::not_circumvent_feature)] pub struct NotCircumventFeature; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::linker_plugin_lto_windows_not_supported)] pub struct LinkerPluginToWindowsNotSupported; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::profile_use_file_does_not_exist)] pub struct ProfileUseFileDoesNotExist<'a> { pub path: &'a std::path::Path, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::profile_sample_use_file_does_not_exist)] pub struct ProfileSampleUseFileDoesNotExist<'a> { pub path: &'a std::path::Path, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::target_requires_unwind_tables)] pub struct TargetRequiresUnwindTables; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::sanitizer_not_supported)] pub struct SanitizerNotSupported { pub us: String, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::sanitizers_not_supported)] pub struct SanitizersNotSupported { pub us: String, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::cannot_mix_and_match_sanitizers)] pub struct CannotMixAndMatchSanitizers { pub first: String, pub second: String, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::cannot_enable_crt_static_linux)] pub struct CannotEnableCrtStaticLinux; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::sanitizer_cfi_enabled)] pub struct SanitizerCfiEnabled; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::unstable_virtual_function_elimination)] pub struct UnstableVirtualFunctionElimination; -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::unsupported_dwarf_version)] pub struct UnsupportedDwarfVersion { pub dwarf_version: u32, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::target_stack_protector_not_supported)] pub struct StackProtectorNotSupportedForTarget<'a> { pub stack_protector: StackProtector, pub target_triple: &'a TargetTriple, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::split_debuginfo_unstable_platform)] pub struct SplitDebugInfoUnstablePlatform { pub debuginfo: SplitDebuginfo, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::file_is_not_writeable)] pub struct FileIsNotWriteable<'a> { pub file: &'a std::path::Path, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::crate_name_does_not_match)] pub struct CrateNameDoesNotMatch<'a> { #[primary_span] @@ -186,13 +189,13 @@ pub struct CrateNameDoesNotMatch<'a> { pub name: Symbol, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::crate_name_invalid)] pub struct CrateNameInvalid<'a> { pub s: &'a str, } -#[derive(SessionDiagnostic)] +#[derive(Diagnostic)] #[diag(session::crate_name_empty)] pub struct CrateNameEmpty { #[primary_span] @@ -205,11 +208,8 @@ pub struct InvalidCharacterInCrateName<'a> { pub crate_name: &'a str, } -impl crate::SessionDiagnostic<'_> for InvalidCharacterInCrateName<'_> { - fn into_diagnostic( - self, - sess: &Handler, - ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { +impl IntoDiagnostic<'_> for InvalidCharacterInCrateName<'_> { + fn into_diagnostic(self, sess: &Handler) -> DiagnosticBuilder<'_, ErrorGuaranteed> { let mut diag = sess.struct_err(fluent::session::invalid_character_in_create_name); if let Some(sp) = self.span { diag.set_span(sp); diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 3189dcb08ad..b9202af2a67 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -11,8 +11,8 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::sync::{Lock, Lrc}; use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler}; use rustc_errors::{ - fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder, IntoDiagnostic, - DiagnosticId, DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, MultiSpan, StashKey, + fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId, + DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, IntoDiagnostic, MultiSpan, StashKey, }; use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures}; use rustc_span::edition::Edition; diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index e660b739928..0142e981766 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -27,8 +27,8 @@ use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType}; use rustc_errors::json::JsonEmitter; use rustc_errors::registry::Registry; use rustc_errors::{ - error_code, fallback_fluent_bundle, DiagnosticBuilder, IntoDiagnostic, DiagnosticId, - DiagnosticMessage, ErrorGuaranteed, FluentBundle, LazyFallbackBundle, MultiSpan, + error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, + ErrorGuaranteed, FluentBundle, IntoDiagnostic, LazyFallbackBundle, MultiSpan, }; use rustc_macros::HashStable_Generic; pub use rustc_span::def_id::StableCrateId; diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 1baad6a9fd7..7785d29c15f 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -125,6 +125,7 @@ symbols! { Symbols { AcqRel, Acquire, + AddToDiagnostic, Alignment, Any, Arc, @@ -176,7 +177,6 @@ symbols! { DecorateLint, Default, Deref, - Diagnostic, DiagnosticMessage, DirBuilder, Display, @@ -210,6 +210,7 @@ symbols! { Implied, Input, Into, + IntoDiagnostic, IntoFuture, IntoIterator, IoRead, @@ -282,7 +283,6 @@ symbols! { String, StructuralEq, StructuralPartialEq, - Subdiagnostic, SubdiagnosticMessage, Sync, T, diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index b02ee593cbe..5e1b80eae39 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -1,4 +1,4 @@ -use rustc_errors::{fluent, IntoDiagnostic, ErrorGuaranteed, Handler}; +use rustc_errors::{fluent, ErrorGuaranteed, Handler, IntoDiagnostic}; use rustc_macros::Diagnostic; use rustc_middle::ty::{PolyTraitRef, Ty, Unevaluated}; use rustc_session::Limit; diff --git a/src/test/ui-fulldeps/internal-lints/diagnostics.rs b/src/test/ui-fulldeps/internal-lints/diagnostics.rs index 4c2c28dc336..18e39108eca 100644 --- a/src/test/ui-fulldeps/internal-lints/diagnostics.rs +++ b/src/test/ui-fulldeps/internal-lints/diagnostics.rs @@ -20,7 +20,7 @@ use rustc_span::Span; #[derive(Diagnostic)] #[diag(parser::expect_path)] -struct DeriveSessionDiagnostic { +struct DeriveDiagnostic { #[primary_span] span: Span, } @@ -32,18 +32,18 @@ struct Note { span: Span, } -pub struct UntranslatableInSessionDiagnostic; +pub struct UntranslatableInIntoDiagnostic; -impl<'a> IntoDiagnostic<'a, ErrorGuaranteed> for UntranslatableInSessionDiagnostic { +impl<'a> IntoDiagnostic<'a, ErrorGuaranteed> for UntranslatableInIntoDiagnostic { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { handler.struct_err("untranslatable diagnostic") //~^ ERROR diagnostics should be created using translatable messages } } -pub struct TranslatableInSessionDiagnostic; +pub struct TranslatableInIntoDiagnostic; -impl<'a> IntoDiagnostic<'a, ErrorGuaranteed> for TranslatableInSessionDiagnostic { +impl<'a> IntoDiagnostic<'a, ErrorGuaranteed> for TranslatableInIntoDiagnostic { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { handler.struct_err(fluent::parser::expect_path) } diff --git a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr index b07b35f2723..c3972beb512 100644 --- a/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr +++ b/src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr @@ -449,7 +449,7 @@ error[E0277]: the trait bound `Hello: IntoDiagnosticArg` is not satisfied --> $DIR/diagnostic-derive.rs:331:10 | LL | #[derive(Diagnostic)] - | ^^^^^^^^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `Hello` + | ^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `Hello` | = help: normalized in stderr note: required by a bound in `DiagnosticBuilder::<'a, G>::set_arg` -- cgit 1.4.1-3-g733a5 From fc43df0333d5862a219f16d294ae38b14b9191d3 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Tue, 20 Sep 2022 20:04:35 +0200 Subject: Revert "Auto merge of #101620 - cjgillot:compute_lint_levels_by_def, r=oli-obk" This reverts commit 2cb9a65684dba47c52de8fa938febf97a73e70a9, reversing changes made to 750bd1a7ff3e010611b97ee75d30b7cbf5f3a03c. --- compiler/rustc_errors/src/diagnostic.rs | 5 +- compiler/rustc_errors/src/lib.rs | 2 +- compiler/rustc_lint/src/context.rs | 2 +- compiler/rustc_lint/src/early.rs | 1 - compiler/rustc_lint/src/expect.rs | 4 +- compiler/rustc_lint/src/levels.rs | 680 +++++++++------------ compiler/rustc_lint/src/lib.rs | 1 - compiler/rustc_lint_defs/src/lib.rs | 31 +- compiler/rustc_middle/src/dep_graph/dep_node.rs | 38 +- compiler/rustc_middle/src/lint.rs | 222 ++++--- compiler/rustc_middle/src/query/mod.rs | 10 +- compiler/rustc_middle/src/ty/context.rs | 42 +- compiler/rustc_middle/src/ty/query.rs | 4 +- compiler/rustc_query_impl/src/keys.rs | 17 - compiler/rustc_query_system/src/dep_graph/mod.rs | 6 +- ...re-gate-non_exhaustive_omitted_patterns_lint.rs | 5 - ...ate-non_exhaustive_omitted_patterns_lint.stderr | 72 +-- .../force_warn_expected_lints_fulfilled.stderr | 16 +- 18 files changed, 488 insertions(+), 670 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index a52e95e92d5..1c440a0a07e 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -339,10 +339,9 @@ impl Diagnostic { // The lint index inside the attribute is manually transferred here. let lint_index = expectation_id.get_lint_index(); expectation_id.set_lint_index(None); - let mut stable_id = unstable_to_stable + let mut stable_id = *unstable_to_stable .get(&expectation_id) - .expect("each unstable `LintExpectationId` must have a matching stable id") - .normalize(); + .expect("each unstable `LintExpectationId` must have a matching stable id"); stable_id.set_lint_index(lint_index); *expectation_id = stable_id; diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 68971cebc35..b44cf352233 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -1205,7 +1205,7 @@ impl HandlerInner { if let Some(expectation_id) = diagnostic.level.get_expectation_id() { self.suppressed_expected_diag = true; - self.fulfilled_expectations.insert(expectation_id.normalize()); + self.fulfilled_expectations.insert(expectation_id); } if matches!(diagnostic.level, Warning(_)) diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 34506c84cb8..7ca6ec5d962 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -560,7 +560,7 @@ pub struct LateContext<'tcx> { /// Context for lint checking of the AST, after expansion, before lowering to HIR. pub struct EarlyContext<'a> { - pub builder: LintLevelsBuilder<'a, crate::levels::TopDown>, + pub builder: LintLevelsBuilder<'a>, pub buffered: LintBuffer, } diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index 45f54cfed2d..96ecd79a69c 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -59,7 +59,6 @@ impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> { F: FnOnce(&mut Self), { let is_crate_node = id == ast::CRATE_NODE_ID; - debug!(?id); let push = self.context.builder.push(attrs, is_crate_node, None); self.check_id(id); diff --git a/compiler/rustc_lint/src/expect.rs b/compiler/rustc_lint/src/expect.rs index b9a3d52ca9b..699e8154318 100644 --- a/compiler/rustc_lint/src/expect.rs +++ b/compiler/rustc_lint/src/expect.rs @@ -16,10 +16,8 @@ fn check_expectations(tcx: TyCtxt<'_>, tool_filter: Option) { return; } - let lint_expectations = tcx.lint_expectations(()); let fulfilled_expectations = tcx.sess.diagnostic().steal_fulfilled_expectation_ids(); - - tracing::debug!(?lint_expectations, ?fulfilled_expectations); + let lint_expectations = &tcx.lint_levels(()).lint_expectations; for (id, expectation) in lint_expectations { // This check will always be true, since `lint_expectations` only diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index a9ba2ad1d10..1e16ac51e9e 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -6,11 +6,10 @@ use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Applicability, Diagnostic, LintDiagnosticBuilder, MultiSpan}; use rustc_hir as hir; use rustc_hir::{intravisit, HirId}; -use rustc_index::vec::IndexVec; use rustc_middle::hir::nested_filter; use rustc_middle::lint::{ - reveal_actual_level, struct_lint_level, LevelAndSource, LintExpectation, LintLevelSource, - ShallowLintLevelMap, + struct_lint_level, LevelAndSource, LintExpectation, LintLevelMap, LintLevelSets, + LintLevelSource, LintSet, LintStackIndex, COMMAND_LINE, }; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{RegisteredTools, TyCtxt}; @@ -28,292 +27,47 @@ use crate::errors::{ UnknownToolInScopedLint, }; -/// Collection of lint levels for the whole crate. -/// This is used by AST-based lints, which do not -/// wait until we have built HIR to be emitted. -#[derive(Debug)] -struct LintLevelSets { - /// Linked list of specifications. - list: IndexVec, -} - -rustc_index::newtype_index! { - struct LintStackIndex { - ENCODABLE = custom, // we don't need encoding - const COMMAND_LINE = 0, - } -} - -/// Specifications found at this position in the stack. This map only represents the lints -/// found for one set of attributes (like `shallow_lint_levels_on` does). -/// -/// We store the level specifications as a linked list. -/// Each `LintSet` represents a set of attributes on the same AST node. -/// The `parent` forms a linked list that matches the AST tree. -/// This way, walking the linked list is equivalent to walking the AST bottom-up -/// to find the specifications for a given lint. -#[derive(Debug)] -struct LintSet { - // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which - // flag. - specs: FxHashMap, - parent: LintStackIndex, -} - -impl LintLevelSets { - fn new() -> Self { - LintLevelSets { list: IndexVec::new() } - } - - fn get_lint_level( - &self, - lint: &'static Lint, - idx: LintStackIndex, - aux: Option<&FxHashMap>, - sess: &Session, - ) -> LevelAndSource { - let lint = LintId::of(lint); - let (level, mut src) = self.raw_lint_id_level(lint, idx, aux); - let level = reveal_actual_level(level, &mut src, sess, lint, |id| { - self.raw_lint_id_level(id, idx, aux) - }); - (level, src) - } - - fn raw_lint_id_level( - &self, - id: LintId, - mut idx: LintStackIndex, - aux: Option<&FxHashMap>, - ) -> (Option, LintLevelSource) { - if let Some(specs) = aux { - if let Some(&(level, src)) = specs.get(&id) { - return (Some(level), src); - } - } - loop { - let LintSet { ref specs, parent } = self.list[idx]; - if let Some(&(level, src)) = specs.get(&id) { - return (Some(level), src); - } - if idx == COMMAND_LINE { - return (None, LintLevelSource::Default); - } - idx = parent; - } - } -} - -fn lint_expectations(tcx: TyCtxt<'_>, (): ()) -> Vec<(LintExpectationId, LintExpectation)> { +fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap { let store = unerased_lint_store(tcx); + let levels = + LintLevelsBuilder::new(tcx.sess, false, &store, &tcx.resolutions(()).registered_tools); + let mut builder = LintLevelMapBuilder { levels, tcx }; + let krate = tcx.hir().krate(); - let mut builder = LintLevelsBuilder { - sess: tcx.sess, - provider: QueryMapExpectationsWrapper { - tcx, - cur: hir::CRATE_HIR_ID, - specs: ShallowLintLevelMap::default(), - expectations: Vec::new(), - unstable_to_stable_ids: FxHashMap::default(), - }, - warn_about_weird_lints: false, - store, - registered_tools: &tcx.resolutions(()).registered_tools, - }; - - builder.add_command_line(); - builder.add_id(hir::CRATE_HIR_ID); - tcx.hir().walk_toplevel_module(&mut builder); - - tcx.sess.diagnostic().update_unstable_expectation_id(&builder.provider.unstable_to_stable_ids); + builder.levels.id_to_set.reserve(krate.owners.len() + 1); - builder.provider.expectations -} + let push = + builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), true, Some(hir::CRATE_HIR_ID)); -fn shallow_lint_levels_on(tcx: TyCtxt<'_>, hir_id: HirId) -> ShallowLintLevelMap { - let store = unerased_lint_store(tcx); - - let mut levels = LintLevelsBuilder { - sess: tcx.sess, - provider: LintLevelQueryMap { tcx, cur: hir_id, specs: ShallowLintLevelMap::default() }, - warn_about_weird_lints: false, - store, - registered_tools: &tcx.resolutions(()).registered_tools, - }; - - let is_crate = hir::CRATE_HIR_ID == hir_id; - if is_crate { - levels.add_command_line(); - } - debug!(?hir_id); - levels.add(tcx.hir().attrs(hir_id), is_crate, Some(hir_id)); + builder.levels.register_id(hir::CRATE_HIR_ID); + tcx.hir().walk_toplevel_module(&mut builder); + builder.levels.pop(push); - levels.provider.specs + builder.levels.update_unstable_expectation_ids(); + builder.levels.build_map() } -pub struct TopDown { +pub struct LintLevelsBuilder<'s> { + sess: &'s Session, + lint_expectations: Vec<(LintExpectationId, LintExpectation)>, + /// Each expectation has a stable and an unstable identifier. This map + /// is used to map from unstable to stable [`LintExpectationId`]s. + expectation_id_map: FxHashMap, sets: LintLevelSets, + id_to_set: FxHashMap, cur: LintStackIndex, -} - -pub trait LintLevelsProvider { - fn current_specs(&self) -> &FxHashMap; - fn current_specs_mut(&mut self) -> &mut FxHashMap; - fn get_lint_level(&self, lint: &'static Lint, sess: &Session) -> LevelAndSource; - fn push_expectation(&mut self, _id: LintExpectationId, _expectation: LintExpectation) {} -} - -impl LintLevelsProvider for TopDown { - fn current_specs(&self) -> &FxHashMap { - &self.sets.list[self.cur].specs - } - - fn current_specs_mut(&mut self) -> &mut FxHashMap { - &mut self.sets.list[self.cur].specs - } - - fn get_lint_level(&self, lint: &'static Lint, sess: &Session) -> LevelAndSource { - self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), sess) - } -} - -struct LintLevelQueryMap<'tcx> { - tcx: TyCtxt<'tcx>, - cur: HirId, - specs: ShallowLintLevelMap, -} - -impl LintLevelsProvider for LintLevelQueryMap<'_> { - fn current_specs(&self) -> &FxHashMap { - &self.specs.specs - } - fn current_specs_mut(&mut self) -> &mut FxHashMap { - &mut self.specs.specs - } - fn get_lint_level(&self, lint: &'static Lint, _: &Session) -> LevelAndSource { - self.specs.lint_level_id_at_node(self.tcx, LintId::of(lint), self.cur) - } -} - -struct QueryMapExpectationsWrapper<'tcx> { - tcx: TyCtxt<'tcx>, - cur: HirId, - specs: ShallowLintLevelMap, - expectations: Vec<(LintExpectationId, LintExpectation)>, - unstable_to_stable_ids: FxHashMap, -} - -impl LintLevelsProvider for QueryMapExpectationsWrapper<'_> { - fn current_specs(&self) -> &FxHashMap { - &self.specs.specs - } - fn current_specs_mut(&mut self) -> &mut FxHashMap { - self.specs.specs.clear(); - &mut self.specs.specs - } - fn get_lint_level(&self, lint: &'static Lint, _: &Session) -> LevelAndSource { - self.specs.lint_level_id_at_node(self.tcx, LintId::of(lint), self.cur) - } - fn push_expectation(&mut self, id: LintExpectationId, expectation: LintExpectation) { - let LintExpectationId::Stable { attr_id: Some(attr_id), hir_id, attr_index, .. } = id else { bug!("unstable expectation id should already be mapped") }; - let key = LintExpectationId::Unstable { attr_id, lint_index: None }; - - if !self.unstable_to_stable_ids.contains_key(&key) { - self.unstable_to_stable_ids.insert( - key, - LintExpectationId::Stable { hir_id, attr_index, lint_index: None, attr_id: None }, - ); - } - - self.expectations.push((id.normalize(), expectation)); - } -} - -impl<'tcx> LintLevelsBuilder<'_, QueryMapExpectationsWrapper<'tcx>> { - fn add_id(&mut self, hir_id: HirId) { - self.add(self.provider.tcx.hir().attrs(hir_id), hir_id == hir::CRATE_HIR_ID, Some(hir_id)); - } -} - -impl<'tcx> intravisit::Visitor<'tcx> for LintLevelsBuilder<'_, QueryMapExpectationsWrapper<'tcx>> { - type NestedFilter = nested_filter::All; - - fn nested_visit_map(&mut self) -> Self::Map { - self.provider.tcx.hir() - } - - fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { - self.add_id(param.hir_id); - intravisit::walk_param(self, param); - } - - fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { - self.add_id(it.hir_id()); - intravisit::walk_item(self, it); - } - - fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { - self.add_id(it.hir_id()); - intravisit::walk_foreign_item(self, it); - } - - fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) { - // We will call `add_id` when we walk - // the `StmtKind`. The outer statement itself doesn't - // define the lint levels. - intravisit::walk_stmt(self, e); - } - - fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { - self.add_id(e.hir_id); - intravisit::walk_expr(self, e); - } - - fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { - self.add_id(s.hir_id); - intravisit::walk_field_def(self, s); - } - - fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) { - self.add_id(v.id); - intravisit::walk_variant(self, v); - } - - fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { - self.add_id(l.hir_id); - intravisit::walk_local(self, l); - } - - fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { - self.add_id(a.hir_id); - intravisit::walk_arm(self, a); - } - - fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { - self.add_id(trait_item.hir_id()); - intravisit::walk_trait_item(self, trait_item); - } - - fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { - self.add_id(impl_item.hir_id()); - intravisit::walk_impl_item(self, impl_item); - } -} - -pub struct LintLevelsBuilder<'s, P> { - sess: &'s Session, - provider: P, warn_about_weird_lints: bool, store: &'s LintStore, registered_tools: &'s RegisteredTools, } -pub(crate) struct BuilderPush { +pub struct BuilderPush { prev: LintStackIndex, + pub changed: bool, } -impl<'s> LintLevelsBuilder<'s, TopDown> { - pub(crate) fn new( +impl<'s> LintLevelsBuilder<'s> { + pub fn new( sess: &'s Session, warn_about_weird_lints: bool, store: &'s LintStore, @@ -321,66 +75,20 @@ impl<'s> LintLevelsBuilder<'s, TopDown> { ) -> Self { let mut builder = LintLevelsBuilder { sess, - provider: TopDown { sets: LintLevelSets::new(), cur: COMMAND_LINE }, + lint_expectations: Default::default(), + expectation_id_map: Default::default(), + sets: LintLevelSets::new(), + cur: COMMAND_LINE, + id_to_set: Default::default(), warn_about_weird_lints, store, registered_tools, }; - builder.process_command_line(); - assert_eq!(builder.provider.sets.list.len(), 1); + builder.process_command_line(sess, store); + assert_eq!(builder.sets.list.len(), 1); builder } - fn process_command_line(&mut self) { - self.provider.cur = self - .provider - .sets - .list - .push(LintSet { specs: FxHashMap::default(), parent: COMMAND_LINE }); - self.add_command_line(); - } - - /// Pushes a list of AST lint attributes onto this context. - /// - /// This function will return a `BuilderPush` object which should be passed - /// to `pop` when this scope for the attributes provided is exited. - /// - /// This function will perform a number of tasks: - /// - /// * It'll validate all lint-related attributes in `attrs` - /// * It'll mark all lint-related attributes as used - /// * Lint levels will be updated based on the attributes provided - /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to - /// `#[allow]` - /// - /// Don't forget to call `pop`! - pub(crate) fn push( - &mut self, - attrs: &[ast::Attribute], - is_crate_node: bool, - source_hir_id: Option, - ) -> BuilderPush { - let prev = self.provider.cur; - self.provider.cur = - self.provider.sets.list.push(LintSet { specs: FxHashMap::default(), parent: prev }); - - self.add(attrs, is_crate_node, source_hir_id); - - if self.provider.current_specs().is_empty() { - self.provider.sets.list.pop(); - self.provider.cur = prev; - } - - BuilderPush { prev } - } - - /// Called after `push` when the scope of a set of attributes are exited. - pub(crate) fn pop(&mut self, push: BuilderPush) { - self.provider.cur = push.prev; - } -} - -impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { pub(crate) fn sess(&self) -> &Session { self.sess } @@ -390,20 +98,24 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { } fn current_specs(&self) -> &FxHashMap { - self.provider.current_specs() + &self.sets.list[self.cur].specs } fn current_specs_mut(&mut self) -> &mut FxHashMap { - self.provider.current_specs_mut() + &mut self.sets.list[self.cur].specs } - fn add_command_line(&mut self) { - for &(ref lint_name, level) in &self.sess.opts.lint_opts { - self.store.check_lint_name_cmdline(self.sess, &lint_name, level, self.registered_tools); + fn process_command_line(&mut self, sess: &Session, store: &LintStore) { + self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid); + + self.cur = + self.sets.list.push(LintSet { specs: FxHashMap::default(), parent: COMMAND_LINE }); + for &(ref lint_name, level) in &sess.opts.lint_opts { + store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools); let orig_level = level; let lint_flag_val = Symbol::intern(lint_name); - let Ok(ids) = self.store.find_lints(&lint_name) else { + let Ok(ids) = store.find_lints(&lint_name) else { // errors handled in check_lint_name_cmdline above continue }; @@ -426,11 +138,9 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful /// (e.g. if a forbid was already inserted on the same scope), then emits a /// diagnostic with no change to `specs`. - fn insert_spec(&mut self, id: LintId, (mut level, src): LevelAndSource) { - let (old_level, old_src) = self.provider.get_lint_level(id.lint, &self.sess); - if let Level::Expect(id) = &mut level && let LintExpectationId::Stable { .. } = id { - *id = id.normalize(); - } + fn insert_spec(&mut self, id: LintId, (level, src): LevelAndSource) { + let (old_level, old_src) = + self.sets.get_lint_level(id.lint, self.cur, Some(self.current_specs()), &self.sess); // Setting to a non-forbid level is an error if the lint previously had // a forbid level. Note that this is not necessarily true even with a // `#[forbid(..)]` attribute present, as that is overridden by `--cap-lints`. @@ -448,7 +158,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { let id_name = id.lint.name_lower(); let fcw_warning = match old_src { LintLevelSource::Default => false, - LintLevelSource::Node { name, .. } => self.store.is_lint_group(name), + LintLevelSource::Node(symbol, _, _) => self.store.is_lint_group(symbol), LintLevelSource::CommandLine(symbol, _) => self.store.is_lint_group(symbol), }; debug!( @@ -468,8 +178,8 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { id.to_string() )); } - LintLevelSource::Node { span, reason, .. } => { - diag.span_label(span, "`forbid` level set here"); + LintLevelSource::Node(_, forbid_source_span, reason) => { + diag.span_label(forbid_source_span, "`forbid` level set here"); if let Some(rationale) = reason { diag.note(rationale.as_str()); } @@ -489,8 +199,11 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { LintLevelSource::Default => { OverruledAttributeSub::DefaultSource { id: id.to_string() } } - LintLevelSource::Node { span, reason, .. } => { - OverruledAttributeSub::NodeSource { span, reason } + LintLevelSource::Node(_, forbid_source_span, reason) => { + OverruledAttributeSub::NodeSource { + span: forbid_source_span, + reason, + } } LintLevelSource::CommandLine(_, _) => { OverruledAttributeSub::CommandLineSource @@ -543,7 +256,29 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { }; } - fn add(&mut self, attrs: &[ast::Attribute], is_crate_node: bool, source_hir_id: Option) { + /// Pushes a list of AST lint attributes onto this context. + /// + /// This function will return a `BuilderPush` object which should be passed + /// to `pop` when this scope for the attributes provided is exited. + /// + /// This function will perform a number of tasks: + /// + /// * It'll validate all lint-related attributes in `attrs` + /// * It'll mark all lint-related attributes as used + /// * Lint levels will be updated based on the attributes provided + /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to + /// `#[allow]` + /// + /// Don't forget to call `pop`! + pub(crate) fn push( + &mut self, + attrs: &[ast::Attribute], + is_crate_node: bool, + source_hir_id: Option, + ) -> BuilderPush { + let prev = self.cur; + self.cur = self.sets.list.push(LintSet { specs: FxHashMap::default(), parent: prev }); + let sess = self.sess; for (attr_index, attr) in attrs.iter().enumerate() { if attr.has_name(sym::automatically_derived) { @@ -558,17 +293,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { None => continue, // This is the only lint level with a `LintExpectationId` that can be created from an attribute Some(Level::Expect(unstable_id)) if let Some(hir_id) = source_hir_id => { - let LintExpectationId::Unstable { attr_id, lint_index } = unstable_id - else { bug!("stable id Level::from_attr") }; - - let stable_id = LintExpectationId::Stable { - hir_id, - attr_index: attr_index.try_into().unwrap(), - lint_index, - // we pass the previous unstable attr_id such that we can trace the ast id when building a map - // to go from unstable to stable id. - attr_id: Some(attr_id), - }; + let stable_id = self.create_stable_id(unstable_id, hir_id, attr_index); Level::Expect(stable_id) } @@ -683,7 +408,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { [lint] => *lint == LintId::of(UNFULFILLED_LINT_EXPECTATIONS), _ => false, }; - self.provider.push_expectation( + self.lint_expectations.push(( expect_id, LintExpectation::new( reason, @@ -691,19 +416,13 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { is_unfulfilled_lint_expectations, tool_name, ), - ); + )); } - let src = LintLevelSource::Node { - name: meta_item - .path - .segments - .last() - .expect("empty lint name") - .ident - .name, - span: sp, + let src = LintLevelSource::Node( + meta_item.path.segments.last().expect("empty lint name").ident.name, + sp, reason, - }; + ); for &id in *ids { if self.check_gated_lint(id, attr.span) { self.insert_spec(id, (level, src)); @@ -716,26 +435,31 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { Ok(ids) => { let complete_name = &format!("{}::{}", tool_ident.unwrap().name, name); - let src = LintLevelSource::Node { - name: Symbol::intern(complete_name), - span: sp, + let src = LintLevelSource::Node( + Symbol::intern(complete_name), + sp, reason, - }; + ); for &id in ids { if self.check_gated_lint(id, attr.span) { self.insert_spec(id, (level, src)); } } if let Level::Expect(expect_id) = level { - self.provider.push_expectation( + self.lint_expectations.push(( expect_id, LintExpectation::new(reason, sp, false, tool_name), - ); + )); } } Err((Some(ids), ref new_lint_name)) => { let lint = builtin::RENAMED_AND_REMOVED_LINTS; - let (lvl, src) = self.provider.get_lint_level(lint, &sess); + let (lvl, src) = self.sets.get_lint_level( + lint, + self.cur, + Some(self.current_specs()), + &sess, + ); struct_lint_level( self.sess, lint, @@ -759,19 +483,19 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { }, ); - let src = LintLevelSource::Node { - name: Symbol::intern(&new_lint_name), - span: sp, + let src = LintLevelSource::Node( + Symbol::intern(&new_lint_name), + sp, reason, - }; + ); for id in ids { self.insert_spec(*id, (level, src)); } if let Level::Expect(expect_id) = level { - self.provider.push_expectation( + self.lint_expectations.push(( expect_id, LintExpectation::new(reason, sp, false, tool_name), - ); + )); } } Err((None, _)) => { @@ -797,7 +521,12 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { CheckLintNameResult::Warning(msg, renamed) => { let lint = builtin::RENAMED_AND_REMOVED_LINTS; - let (renamed_lint_level, src) = self.provider.get_lint_level(lint, &sess); + let (renamed_lint_level, src) = self.sets.get_lint_level( + lint, + self.cur, + Some(self.current_specs()), + &sess, + ); struct_lint_level( self.sess, lint, @@ -820,7 +549,12 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { } CheckLintNameResult::NoLint(suggestion) => { let lint = builtin::UNKNOWN_LINTS; - let (level, src) = self.provider.get_lint_level(lint, self.sess); + let (level, src) = self.sets.get_lint_level( + lint, + self.cur, + Some(self.current_specs()), + self.sess, + ); struct_lint_level(self.sess, lint, level, src, Some(sp.into()), |lint| { let name = if let Some(tool_ident) = tool_ident { format!("{}::{}", tool_ident.name, name) @@ -849,21 +583,17 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { if let CheckLintNameResult::Ok(ids) = self.store.check_lint_name(&new_name, None, self.registered_tools) { - let src = LintLevelSource::Node { - name: Symbol::intern(&new_name), - span: sp, - reason, - }; + let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason); for &id in ids { if self.check_gated_lint(id, attr.span) { self.insert_spec(id, (level, src)); } } if let Level::Expect(expect_id) = level { - self.provider.push_expectation( + self.lint_expectations.push(( expect_id, LintExpectation::new(reason, sp, false, tool_name), - ); + )); } } else { panic!("renamed lint does not exist: {}", new_name); @@ -878,12 +608,13 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { continue; } - let LintLevelSource::Node { name: lint_attr_name, span: lint_attr_span, .. } = *src else { + let LintLevelSource::Node(lint_attr_name, lint_attr_span, _) = *src else { continue }; let lint = builtin::UNUSED_ATTRIBUTES; - let (lint_level, lint_src) = self.provider.get_lint_level(lint, &self.sess); + let (lint_level, lint_src) = + self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), self.sess); struct_lint_level( self.sess, lint, @@ -903,13 +634,32 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { break; } } + + if self.current_specs().is_empty() { + self.sets.list.pop(); + self.cur = prev; + } + + BuilderPush { prev, changed: prev != self.cur } + } + + fn create_stable_id( + &mut self, + unstable_id: LintExpectationId, + hir_id: HirId, + attr_index: usize, + ) -> LintExpectationId { + let stable_id = + LintExpectationId::Stable { hir_id, attr_index: attr_index as u16, lint_index: None }; + + self.expectation_id_map.insert(unstable_id, stable_id); + + stable_id } /// Checks if the lint is gated on a feature that is not enabled. /// /// Returns `true` if the lint's feature is enabled. - // FIXME only emit this once for each attribute, instead of repeating it 4 times for - // pre-expansion lints, post-expansion lints, `shallow_lint_levels_on` and `lint_expectations`. fn check_gated_lint(&self, lint_id: LintId, span: Span) -> bool { if let Some(feature) = lint_id.lint.feature_gate { if !self.sess.features_untracked().enabled(feature) { @@ -928,14 +678,19 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { true } + /// Called after `push` when the scope of a set of attributes are exited. + pub fn pop(&mut self, push: BuilderPush) { + self.cur = push.prev; + } + /// Find the lint level for a lint. - pub fn lint_level(&self, lint: &'static Lint) -> LevelAndSource { - self.provider.get_lint_level(lint, self.sess) + pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) { + self.sets.get_lint_level(lint, self.cur, None, self.sess) } /// Used to emit a lint-related diagnostic based on the current state of /// this lint context. - pub(crate) fn struct_lint( + pub fn struct_lint( &self, lint: &'static Lint, span: Option, @@ -944,8 +699,141 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { let (level, src) = self.lint_level(lint); struct_lint_level(self.sess, lint, level, src, span, decorate) } + + /// Registers the ID provided with the current set of lints stored in + /// this context. + pub fn register_id(&mut self, id: HirId) { + self.id_to_set.insert(id, self.cur); + } + + fn update_unstable_expectation_ids(&self) { + self.sess.diagnostic().update_unstable_expectation_id(&self.expectation_id_map); + } + + pub fn build_map(self) -> LintLevelMap { + LintLevelMap { + sets: self.sets, + id_to_set: self.id_to_set, + lint_expectations: self.lint_expectations, + } + } +} + +struct LintLevelMapBuilder<'tcx> { + levels: LintLevelsBuilder<'tcx>, + tcx: TyCtxt<'tcx>, +} + +impl LintLevelMapBuilder<'_> { + fn with_lint_attrs(&mut self, id: hir::HirId, f: F) + where + F: FnOnce(&mut Self), + { + let is_crate_hir = id == hir::CRATE_HIR_ID; + let attrs = self.tcx.hir().attrs(id); + let push = self.levels.push(attrs, is_crate_hir, Some(id)); + + if push.changed { + self.levels.register_id(id); + } + f(self); + self.levels.pop(push); + } +} + +impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'tcx> { + type NestedFilter = nested_filter::All; + + fn nested_visit_map(&mut self) -> Self::Map { + self.tcx.hir() + } + + fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { + self.with_lint_attrs(param.hir_id, |builder| { + intravisit::walk_param(builder, param); + }); + } + + fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { + self.with_lint_attrs(it.hir_id(), |builder| { + intravisit::walk_item(builder, it); + }); + } + + fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { + self.with_lint_attrs(it.hir_id(), |builder| { + intravisit::walk_foreign_item(builder, it); + }) + } + + fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) { + // We will call `with_lint_attrs` when we walk + // the `StmtKind`. The outer statement itself doesn't + // define the lint levels. + intravisit::walk_stmt(self, e); + } + + fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { + self.with_lint_attrs(e.hir_id, |builder| { + intravisit::walk_expr(builder, e); + }) + } + + fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) { + self.with_lint_attrs(field.hir_id, |builder| { + intravisit::walk_expr_field(builder, field); + }) + } + + fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { + self.with_lint_attrs(s.hir_id, |builder| { + intravisit::walk_field_def(builder, s); + }) + } + + fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) { + self.with_lint_attrs(v.id, |builder| { + intravisit::walk_variant(builder, v); + }) + } + + fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { + self.with_lint_attrs(l.hir_id, |builder| { + intravisit::walk_local(builder, l); + }) + } + + fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { + self.with_lint_attrs(a.hir_id, |builder| { + intravisit::walk_arm(builder, a); + }) + } + + fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { + self.with_lint_attrs(trait_item.hir_id(), |builder| { + intravisit::walk_trait_item(builder, trait_item); + }); + } + + fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { + self.with_lint_attrs(impl_item.hir_id(), |builder| { + intravisit::walk_impl_item(builder, impl_item); + }); + } + + fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) { + self.with_lint_attrs(field.hir_id, |builder| { + intravisit::walk_pat_field(builder, field); + }) + } + + fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) { + self.with_lint_attrs(p.hir_id, |builder| { + intravisit::walk_generic_param(builder, p); + }); + } } -pub(crate) fn provide(providers: &mut Providers) { - *providers = Providers { shallow_lint_levels_on, lint_expectations, ..*providers }; +pub fn provide(providers: &mut Providers) { + providers.lint_levels = lint_levels; } diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index c760e435699..752a751f6bc 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -35,7 +35,6 @@ #![feature(iter_order_by)] #![feature(let_chains)] #![cfg_attr(bootstrap, feature(let_else))] -#![feature(min_specialization)] #![feature(never_type)] #![recursion_limit = "256"] diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index cbe7afc8e55..11b2d057a07 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -92,7 +92,7 @@ pub enum LintExpectationId { /// stable and can be cached. The additional index ensures that nodes with /// several expectations can correctly match diagnostics to the individual /// expectation. - Stable { hir_id: HirId, attr_index: u16, lint_index: Option, attr_id: Option }, + Stable { hir_id: HirId, attr_index: u16, lint_index: Option }, } impl LintExpectationId { @@ -116,31 +116,13 @@ impl LintExpectationId { *lint_index = new_lint_index } - - /// Prepares the id for hashing. Removes references to the ast. - /// Should only be called when the id is stable. - pub fn normalize(self) -> Self { - match self { - Self::Stable { hir_id, attr_index, lint_index, .. } => { - Self::Stable { hir_id, attr_index, lint_index, attr_id: None } - } - Self::Unstable { .. } => { - unreachable!("`normalize` called when `ExpectationId` is unstable") - } - } - } } impl HashStable for LintExpectationId { #[inline] fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) { match self { - LintExpectationId::Stable { - hir_id, - attr_index, - lint_index: Some(lint_index), - attr_id: _, - } => { + LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => { hir_id.hash_stable(hcx, hasher); attr_index.hash_stable(hcx, hasher); lint_index.hash_stable(hcx, hasher); @@ -160,12 +142,9 @@ impl ToStableHashKey for LintExpectation #[inline] fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType { match self { - LintExpectationId::Stable { - hir_id, - attr_index, - lint_index: Some(lint_index), - attr_id: _, - } => (*hir_id, *attr_index, *lint_index), + LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => { + (*hir_id, *attr_index, *lint_index) + } _ => { unreachable!("HashStable should only be called for a filled `LintExpectationId`") } diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index eded3b3eedc..1fa0c6babab 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -62,7 +62,7 @@ use crate::ty::TyCtxt; use rustc_data_structures::fingerprint::Fingerprint; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_hir::definitions::DefPathHash; -use rustc_hir::{HirId, ItemLocalId}; +use rustc_hir::HirId; use rustc_query_system::dep_graph::FingerprintStyle; use rustc_span::symbol::Symbol; use std::hash::Hash; @@ -280,7 +280,7 @@ impl DepNodeExt for DepNode { let kind = dep_kind_from_label_string(label)?; match kind.fingerprint_style(tcx) { - FingerprintStyle::Opaque | FingerprintStyle::HirId => Err(()), + FingerprintStyle::Opaque => Err(()), FingerprintStyle::Unit => Ok(DepNode::new_no_params(tcx, kind)), FingerprintStyle::DefPathHash => { Ok(DepNode::from_def_path_hash(tcx, def_path_hash, kind)) @@ -408,7 +408,7 @@ impl<'tcx> DepNodeParams> for (DefId, DefId) { impl<'tcx> DepNodeParams> for HirId { #[inline(always)] fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::HirId + FingerprintStyle::Opaque } // We actually would not need to specialize the implementation of this @@ -417,36 +417,10 @@ impl<'tcx> DepNodeParams> for HirId { #[inline(always)] fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { let HirId { owner, local_id } = *self; - let def_path_hash = tcx.def_path_hash(owner.to_def_id()); - Fingerprint::new( - // `owner` is local, so is completely defined by the local hash - def_path_hash.local_hash(), - local_id.as_u32().into(), - ) - } - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - let HirId { owner, local_id } = *self; - format!("{}.{}", tcx.def_path_str(owner.to_def_id()), local_id.as_u32()) - } + let def_path_hash = tcx.def_path_hash(owner.to_def_id()); + let local_id = Fingerprint::from_smaller_hash(local_id.as_u32().into()); - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { - if dep_node.kind.fingerprint_style(tcx) == FingerprintStyle::HirId { - let (local_hash, local_id) = Fingerprint::from(dep_node.hash).as_value(); - let def_path_hash = DefPathHash::new(tcx.sess.local_stable_crate_id(), local_hash); - let owner = tcx - .def_path_hash_to_def_id(def_path_hash, &mut || { - panic!("Failed to extract HirId: {:?} {}", dep_node.kind, dep_node.hash) - }) - .expect_local(); - let local_id = local_id - .try_into() - .unwrap_or_else(|_| panic!("local id should be u32, found {:?}", local_id)); - Some(HirId { owner, local_id: ItemLocalId::from_u32(local_id) }) - } else { - None - } + def_path_hash.0.combine(local_id) } } diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 4cb5ef79177..2f45222de47 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -1,19 +1,20 @@ use std::cmp; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_errors::{Diagnostic, DiagnosticId, LintDiagnosticBuilder, MultiSpan}; use rustc_hir::HirId; +use rustc_index::vec::IndexVec; +use rustc_query_system::ich::StableHashingContext; use rustc_session::lint::{ builtin::{self, FORBIDDEN_LINT_GROUPS}, - FutureIncompatibilityReason, Level, Lint, LintId, + FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId, }; use rustc_session::Session; use rustc_span::hygiene::MacroKind; use rustc_span::source_map::{DesugaringKind, ExpnKind}; use rustc_span::{symbol, Span, Symbol, DUMMY_SP}; -use crate::ty::TyCtxt; - /// How a lint level was set. #[derive(Clone, Copy, PartialEq, Eq, HashStable, Debug)] pub enum LintLevelSource { @@ -22,12 +23,7 @@ pub enum LintLevelSource { Default, /// Lint level was set by an attribute. - Node { - name: Symbol, - span: Span, - /// RFC 2383 reason - reason: Option, - }, + Node(Symbol, Span, Option /* RFC 2383 reason */), /// Lint level was set by a command-line flag. /// The provided `Level` is the level specified on the command line. @@ -39,7 +35,7 @@ impl LintLevelSource { pub fn name(&self) -> Symbol { match *self { LintLevelSource::Default => symbol::kw::Default, - LintLevelSource::Node { name, .. } => name, + LintLevelSource::Node(name, _, _) => name, LintLevelSource::CommandLine(name, _) => name, } } @@ -47,7 +43,7 @@ impl LintLevelSource { pub fn span(&self) -> Span { match *self { LintLevelSource::Default => DUMMY_SP, - LintLevelSource::Node { span, .. } => span, + LintLevelSource::Node(_, span, _) => span, LintLevelSource::CommandLine(_, _) => DUMMY_SP, } } @@ -56,115 +52,145 @@ impl LintLevelSource { /// A tuple of a lint level and its source. pub type LevelAndSource = (Level, LintLevelSource); -/// Return type for the `shallow_lint_levels_on` query. -/// -/// This map represents the set of allowed lints and allowance levels given -/// by the attributes for *a single HirId*. -#[derive(Default, Debug, HashStable)] -pub struct ShallowLintLevelMap { +#[derive(Debug, HashStable)] +pub struct LintLevelSets { + pub list: IndexVec, + pub lint_cap: Level, +} + +rustc_index::newtype_index! { + #[derive(HashStable)] + pub struct LintStackIndex { + const COMMAND_LINE = 0, + } +} + +#[derive(Debug, HashStable)] +pub struct LintSet { + // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which + // flag. pub specs: FxHashMap, + + pub parent: LintStackIndex, } -/// From an initial level and source, verify the effect of special annotations: -/// `warnings` lint level and lint caps. -/// -/// The return of this function is suitable for diagnostics. -pub fn reveal_actual_level( - level: Option, - src: &mut LintLevelSource, - sess: &Session, - lint: LintId, - probe_for_lint_level: impl FnOnce(LintId) -> (Option, LintLevelSource), -) -> Level { - // If `level` is none then we actually assume the default level for this lint. - let mut level = level.unwrap_or_else(|| lint.lint.default_level(sess.edition())); - - // If we're about to issue a warning, check at the last minute for any - // directives against the warnings "lint". If, for example, there's an - // `allow(warnings)` in scope then we want to respect that instead. - // - // We exempt `FORBIDDEN_LINT_GROUPS` from this because it specifically - // triggers in cases (like #80988) where you have `forbid(warnings)`, - // and so if we turned that into an error, it'd defeat the purpose of the - // future compatibility warning. - if level == Level::Warn && lint != LintId::of(FORBIDDEN_LINT_GROUPS) { - let (warnings_level, warnings_src) = probe_for_lint_level(LintId::of(builtin::WARNINGS)); - if let Some(configured_warning_level) = warnings_level { - if configured_warning_level != Level::Warn { - level = configured_warning_level; - *src = warnings_src; +impl LintLevelSets { + pub fn new() -> Self { + LintLevelSets { list: IndexVec::new(), lint_cap: Level::Forbid } + } + + pub fn get_lint_level( + &self, + lint: &'static Lint, + idx: LintStackIndex, + aux: Option<&FxHashMap>, + sess: &Session, + ) -> LevelAndSource { + let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux); + + // If `level` is none then we actually assume the default level for this + // lint. + let mut level = level.unwrap_or_else(|| lint.default_level(sess.edition())); + + // If we're about to issue a warning, check at the last minute for any + // directives against the warnings "lint". If, for example, there's an + // `allow(warnings)` in scope then we want to respect that instead. + // + // We exempt `FORBIDDEN_LINT_GROUPS` from this because it specifically + // triggers in cases (like #80988) where you have `forbid(warnings)`, + // and so if we turned that into an error, it'd defeat the purpose of the + // future compatibility warning. + if level == Level::Warn && LintId::of(lint) != LintId::of(FORBIDDEN_LINT_GROUPS) { + let (warnings_level, warnings_src) = + self.get_lint_id_level(LintId::of(builtin::WARNINGS), idx, aux); + if let Some(configured_warning_level) = warnings_level { + if configured_warning_level != Level::Warn { + level = configured_warning_level; + src = warnings_src; + } } } - } - // Ensure that we never exceed the `--cap-lints` argument unless the source is a --force-warn - level = if let LintLevelSource::CommandLine(_, Level::ForceWarn(_)) = src { - level - } else { - cmp::min(level, sess.opts.lint_cap.unwrap_or(Level::Forbid)) - }; + // Ensure that we never exceed the `--cap-lints` argument + // unless the source is a --force-warn + level = if let LintLevelSource::CommandLine(_, Level::ForceWarn(_)) = src { + level + } else { + cmp::min(level, self.lint_cap) + }; + + if let Some(driver_level) = sess.driver_lint_caps.get(&LintId::of(lint)) { + // Ensure that we never exceed driver level. + level = cmp::min(*driver_level, level); + } - if let Some(driver_level) = sess.driver_lint_caps.get(&lint) { - // Ensure that we never exceed driver level. - level = cmp::min(*driver_level, level); + (level, src) } - level -} - -impl ShallowLintLevelMap { - /// Perform a deep probe in the HIR tree looking for the actual level for the lint. - /// This lint level is not usable for diagnostics, it needs to be corrected by - /// `reveal_actual_level` beforehand. - fn probe_for_lint_level( + pub fn get_lint_id_level( &self, - tcx: TyCtxt<'_>, id: LintId, - start: HirId, + mut idx: LintStackIndex, + aux: Option<&FxHashMap>, ) -> (Option, LintLevelSource) { - if let Some(&(level, src)) = self.specs.get(&id) { - return (Some(level), src); + if let Some(specs) = aux { + if let Some(&(level, src)) = specs.get(&id) { + return (Some(level), src); + } } - - for (parent, _) in tcx.hir().parent_iter(start) { - let specs = tcx.shallow_lint_levels_on(parent); - if let Some(&(level, src)) = specs.specs.get(&id) { + loop { + let LintSet { ref specs, parent } = self.list[idx]; + if let Some(&(level, src)) = specs.get(&id) { return (Some(level), src); } + if idx == COMMAND_LINE { + return (None, LintLevelSource::Default); + } + idx = parent; } - (None, LintLevelSource::Default) } +} + +#[derive(Debug)] +pub struct LintLevelMap { + /// This is a collection of lint expectations as described in RFC 2383, that + /// can be fulfilled during this compilation session. This means that at least + /// one expected lint is currently registered in the lint store. + /// + /// The [`LintExpectationId`] is stored as a part of the [`Expect`](Level::Expect) + /// lint level. + pub lint_expectations: Vec<(LintExpectationId, LintExpectation)>, + pub sets: LintLevelSets, + pub id_to_set: FxHashMap, +} - /// Fetch and return the user-visible lint level for the given lint at the given HirId. - pub fn lint_level_id_at_node( +impl LintLevelMap { + /// If the `id` was previously registered with `register_id` when building + /// this `LintLevelMap` this returns the corresponding lint level and source + /// of the lint level for the lint provided. + /// + /// If the `id` was not previously registered, returns `None`. If `None` is + /// returned then the parent of `id` should be acquired and this function + /// should be called again. + pub fn level_and_source( &self, - tcx: TyCtxt<'_>, - lint: LintId, + lint: &'static Lint, id: HirId, - ) -> (Level, LintLevelSource) { - let (level, mut src) = self.probe_for_lint_level(tcx, lint, id); - let level = reveal_actual_level(level, &mut src, tcx.sess, lint, |lint| { - self.probe_for_lint_level(tcx, lint, id) - }); - debug!(?id, ?level, ?src); - (level, src) + session: &Session, + ) -> Option { + self.id_to_set.get(&id).map(|idx| self.sets.get_lint_level(lint, *idx, None, session)) } } -impl TyCtxt<'_> { - /// Fetch and return the user-visible lint level for the given lint at the given HirId. - pub fn lint_level_at_node(self, lint: &'static Lint, id: HirId) -> (Level, LintLevelSource) { - self.shallow_lint_levels_on(id).lint_level_id_at_node(self, LintId::of(lint), id) - } +impl<'a> HashStable> for LintLevelMap { + #[inline] + fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { + let LintLevelMap { ref sets, ref id_to_set, ref lint_expectations } = *self; - /// Walks upwards from `id` to find a node which might change lint levels with attributes. - /// It stops at `bound` and just returns it if reached. - pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { - let hir = self.hir(); - while id != bound && self.shallow_lint_levels_on(id).specs.is_empty() { - id = hir.get_parent_node(id) - } - id + id_to_set.hash_stable(hcx, hasher); + lint_expectations.hash_stable(hcx, hasher); + + hcx.while_hashing_spans(true, |hcx| sets.hash_stable(hcx, hasher)) } } @@ -235,11 +261,11 @@ pub fn explain_lint_level_source( )); } } - LintLevelSource::Node { name: lint_attr_name, span, reason, .. } => { + LintLevelSource::Node(lint_attr_name, src, reason) => { if let Some(rationale) = reason { err.note(rationale.as_str()); } - err.span_note_once(span, "the lint level is defined here"); + err.span_note_once(src, "the lint level is defined here"); if lint_attr_name.as_str() != name { let level_str = level.as_str(); err.note_once(&format!( diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 1afea4864b8..7ea8c9ed3d3 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -274,14 +274,10 @@ rustc_queries! { separate_provide_extern } - query shallow_lint_levels_on(key: HirId) -> rustc_middle::lint::ShallowLintLevelMap { + query lint_levels(_: ()) -> LintLevelMap { arena_cache - desc { |tcx| "looking up lint levels for `{}`", key } - } - - query lint_expectations(_: ()) -> Vec<(LintExpectationId, LintExpectation)> { - arena_cache - desc { "computing `#[expect]`ed lints in this crate" } + eval_always + desc { "computing the lint levels for items in this crate" } } query parent_module_from_def_id(key: LocalDefId) -> LocalDefId { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 2b5b4017a5a..8c44f4a98df 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -4,7 +4,7 @@ use crate::arena::Arena; use crate::dep_graph::{DepGraph, DepKind, DepKindStruct}; use crate::hir::place::Place as HirPlace; use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos}; -use crate::lint::struct_lint_level; +use crate::lint::{struct_lint_level, LintLevelSource}; use crate::middle::codegen_fn_attrs::CodegenFnAttrs; use crate::middle::resolve_lifetime; use crate::middle::stability; @@ -54,7 +54,7 @@ use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_session::config::{CrateType, OutputFilenames}; use rustc_session::cstore::CrateStoreDyn; use rustc_session::errors::TargetDataLayoutErrorsWrapper; -use rustc_session::lint::Lint; +use rustc_session::lint::{Level, Lint}; use rustc_session::Limit; use rustc_session::Session; use rustc_span::def_id::{DefPathHash, StableCrateId}; @@ -2813,6 +2813,44 @@ impl<'tcx> TyCtxt<'tcx> { iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) } + /// Walks upwards from `id` to find a node which might change lint levels with attributes. + /// It stops at `bound` and just returns it if reached. + pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { + let hir = self.hir(); + loop { + if id == bound { + return bound; + } + + if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) { + return id; + } + let next = hir.get_parent_node(id); + if next == id { + bug!("lint traversal reached the root of the crate"); + } + id = next; + } + } + + pub fn lint_level_at_node( + self, + lint: &'static Lint, + mut id: hir::HirId, + ) -> (Level, LintLevelSource) { + let sets = self.lint_levels(()); + loop { + if let Some(pair) = sets.level_and_source(lint, id, self.sess) { + return pair; + } + let next = self.hir().get_parent_node(id); + if next == id { + bug!("lint traversal reached the root of the crate"); + } + id = next; + } + } + /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`, /// typically generated by `#[derive(LintDiagnostic)]`). pub fn emit_spanned_lint( diff --git a/compiler/rustc_middle/src/ty/query.rs b/compiler/rustc_middle/src/ty/query.rs index be208a9fc70..00da260b1dc 100644 --- a/compiler/rustc_middle/src/ty/query.rs +++ b/compiler/rustc_middle/src/ty/query.rs @@ -1,6 +1,6 @@ use crate::dep_graph; use crate::infer::canonical::{self, Canonical}; -use crate::lint::LintExpectation; +use crate::lint::LintLevelMap; use crate::metadata::ModChild; use crate::middle::codegen_fn_attrs::CodegenFnAttrs; use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; @@ -44,14 +44,12 @@ use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId}; -use rustc_hir::hir_id::HirId; use rustc_hir::lang_items::{LangItem, LanguageItems}; use rustc_hir::{Crate, ItemLocalId, TraitCandidate}; use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec}; use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion}; use rustc_session::cstore::{CrateDepKind, CrateSource}; use rustc_session::cstore::{ExternCrate, ForeignModule, LinkagePreference, NativeLib}; -use rustc_session::lint::LintExpectationId; use rustc_session::utils::NativeLibKind; use rustc_session::Limits; use rustc_span::symbol::Symbol; diff --git a/compiler/rustc_query_impl/src/keys.rs b/compiler/rustc_query_impl/src/keys.rs index 31de83ee141..49175e97f41 100644 --- a/compiler/rustc_query_impl/src/keys.rs +++ b/compiler/rustc_query_impl/src/keys.rs @@ -1,7 +1,6 @@ //! Defines the set of legal keys that can be used in queries. use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; -use rustc_hir::hir_id::HirId; use rustc_middle::infer::canonical::Canonical; use rustc_middle::mir; use rustc_middle::traits; @@ -544,19 +543,3 @@ impl<'tcx> Key for (Ty<'tcx>, ty::ValTree<'tcx>) { DUMMY_SP } } - -impl Key for HirId { - #[inline(always)] - fn query_crate_is_local(&self) -> bool { - true - } - - fn default_span(&self, tcx: TyCtxt<'_>) -> Span { - tcx.hir().span(*self) - } - - #[inline(always)] - fn key_as_def_id(&self) -> Option { - None - } -} diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index 6f3bd776216..342d95ca490 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -67,8 +67,6 @@ impl HasDepContext for T { pub enum FingerprintStyle { /// The fingerprint is actually a DefPathHash. DefPathHash, - /// The fingerprint is actually a HirId. - HirId, /// Query key was `()` or equivalent, so fingerprint is just zero. Unit, /// Some opaque hash. @@ -79,9 +77,7 @@ impl FingerprintStyle { #[inline] pub fn reconstructible(self) -> bool { match self { - FingerprintStyle::DefPathHash | FingerprintStyle::Unit | FingerprintStyle::HirId => { - true - } + FingerprintStyle::DefPathHash | FingerprintStyle::Unit => true, FingerprintStyle::Opaque => false, } } diff --git a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.rs b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.rs index 23457b8e062..9b646060adf 100644 --- a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.rs +++ b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.rs @@ -3,11 +3,9 @@ #![deny(non_exhaustive_omitted_patterns)] //~^ WARNING unknown lint: `non_exhaustive_omitted_patterns` //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` -//~| WARNING unknown lint: `non_exhaustive_omitted_patterns` #![allow(non_exhaustive_omitted_patterns)] //~^ WARNING unknown lint: `non_exhaustive_omitted_patterns` //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` -//~| WARNING unknown lint: `non_exhaustive_omitted_patterns` fn main() { enum Foo { @@ -19,8 +17,6 @@ fn main() { //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` - //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` - //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` match Foo::A { Foo::A => {} Foo::B => {} @@ -35,5 +31,4 @@ fn main() { } //~^^^ WARNING unknown lint: `non_exhaustive_omitted_patterns` //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` - //~| WARNING unknown lint: `non_exhaustive_omitted_patterns` } diff --git a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr index 29023858e4f..3de08e215da 100644 --- a/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr +++ b/src/test/ui/feature-gates/feature-gate-non_exhaustive_omitted_patterns_lint.stderr @@ -10,7 +10,7 @@ LL | #![deny(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:7:1 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:6:1 | LL | #![allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -20,7 +20,7 @@ LL | #![allow(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:17:5 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:15:5 | LL | #[allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -30,7 +30,7 @@ LL | #[allow(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:17:5 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:15:5 | LL | #[allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -40,7 +40,7 @@ LL | #[allow(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:33:9 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:29:9 | LL | #[warn(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -60,7 +60,7 @@ LL | #![deny(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:7:1 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:6:1 | LL | #![allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -70,7 +70,7 @@ LL | #![allow(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:17:5 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:15:5 | LL | #[allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -80,7 +80,7 @@ LL | #[allow(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:17:5 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:15:5 | LL | #[allow(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -90,7 +90,7 @@ LL | #[allow(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:33:9 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:29:9 | LL | #[warn(non_exhaustive_omitted_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -100,13 +100,13 @@ LL | #[warn(non_exhaustive_omitted_patterns)] = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable error[E0004]: non-exhaustive patterns: `Foo::C` not covered - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:24:11 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:20:11 | LL | match Foo::A { | ^^^^^^ pattern `Foo::C` not covered | note: `Foo` defined here - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:14:15 + --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:12:15 | LL | enum Foo { | --- @@ -119,56 +119,6 @@ LL ~ Foo::B => {} LL + Foo::C => todo!() | -warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:3:1 - | -LL | #![deny(non_exhaustive_omitted_patterns)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: the `non_exhaustive_omitted_patterns` lint is unstable - = note: see issue #89554 for more information - = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable - -warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:7:1 - | -LL | #![allow(non_exhaustive_omitted_patterns)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: the `non_exhaustive_omitted_patterns` lint is unstable - = note: see issue #89554 for more information - = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable - -warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:17:5 - | -LL | #[allow(non_exhaustive_omitted_patterns)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: the `non_exhaustive_omitted_patterns` lint is unstable - = note: see issue #89554 for more information - = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable - -warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:17:5 - | -LL | #[allow(non_exhaustive_omitted_patterns)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: the `non_exhaustive_omitted_patterns` lint is unstable - = note: see issue #89554 for more information - = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable - -warning: unknown lint: `non_exhaustive_omitted_patterns` - --> $DIR/feature-gate-non_exhaustive_omitted_patterns_lint.rs:33:9 - | -LL | #[warn(non_exhaustive_omitted_patterns)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: the `non_exhaustive_omitted_patterns` lint is unstable - = note: see issue #89554 for more information - = help: add `#![feature(non_exhaustive_omitted_patterns_lint)]` to the crate attributes to enable - -error: aborting due to previous error; 15 warnings emitted +error: aborting due to previous error; 10 warnings emitted For more information about this error, try `rustc --explain E0004`. diff --git a/src/test/ui/lint/rfc-2383-lint-reason/force_warn_expected_lints_fulfilled.stderr b/src/test/ui/lint/rfc-2383-lint-reason/force_warn_expected_lints_fulfilled.stderr index 5942fa8aeb4..06befcbb511 100644 --- a/src/test/ui/lint/rfc-2383-lint-reason/force_warn_expected_lints_fulfilled.stderr +++ b/src/test/ui/lint/rfc-2383-lint-reason/force_warn_expected_lints_fulfilled.stderr @@ -1,3 +1,11 @@ +warning: denote infinite loops with `loop { ... }` + --> $DIR/force_warn_expected_lints_fulfilled.rs:10:5 + | +LL | while true { + | ^^^^^^^^^^ help: use `loop` + | + = note: requested on the command line with `--force-warn while-true` + warning: unused variable: `x` --> $DIR/force_warn_expected_lints_fulfilled.rs:20:9 | @@ -28,13 +36,5 @@ LL | let mut what_does_the_fox_say = "*ding* *deng* *dung*"; | = note: requested on the command line with `--force-warn unused-mut` -warning: denote infinite loops with `loop { ... }` - --> $DIR/force_warn_expected_lints_fulfilled.rs:10:5 - | -LL | while true { - | ^^^^^^^^^^ help: use `loop` - | - = note: requested on the command line with `--force-warn while-true` - warning: 5 warnings emitted -- cgit 1.4.1-3-g733a5 From 8fe936099a3a2ea236d40212a340fc4a326eb506 Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Tue, 20 Sep 2022 14:11:23 +0900 Subject: separate definitions and `HIR` owners fix a ui test use `into` fix clippy ui test fix a run-make-fulldeps test implement `IntoQueryParam` for `OwnerId` use `OwnerId` for more queries change the type of `ParentOwnerIterator::Item` to `(OwnerId, OwnerNode)` --- compiler/rustc_ast_lowering/src/asm.rs | 2 +- compiler/rustc_ast_lowering/src/expr.rs | 2 +- compiler/rustc_ast_lowering/src/index.rs | 14 +-- compiler/rustc_ast_lowering/src/item.rs | 23 ++-- compiler/rustc_ast_lowering/src/lib.rs | 33 ++++-- .../src/diagnostics/mutability_errors.rs | 4 +- .../src/diagnostics/region_errors.rs | 5 +- .../rustc_borrowck/src/diagnostics/region_name.rs | 3 +- compiler/rustc_borrowck/src/lib.rs | 2 +- compiler/rustc_driver/src/pretty.rs | 2 +- compiler/rustc_hir/src/hir.rs | 36 +++---- compiler/rustc_hir/src/hir_id.rs | 60 +++++++++-- compiler/rustc_hir/src/stable_hash_impls.rs | 10 +- .../rustc_incremental/src/persist/dirty_clean.rs | 8 +- .../rustc_infer/src/infer/error_reporting/mod.rs | 2 +- .../nice_region_error/static_impl_trait.rs | 8 +- compiler/rustc_infer/src/infer/mod.rs | 5 +- compiler/rustc_infer/src/infer/opaque_types.rs | 2 +- compiler/rustc_interface/src/proc_macro_decls.rs | 5 +- compiler/rustc_lint/src/builtin.rs | 28 ++--- compiler/rustc_lint/src/context.rs | 2 +- compiler/rustc_metadata/src/native_libs.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 10 +- compiler/rustc_middle/src/dep_graph/dep_node.rs | 24 ++++- compiler/rustc_middle/src/hir/map/mod.rs | 59 ++++++----- compiler/rustc_middle/src/hir/mod.rs | 36 ++++--- .../rustc_middle/src/middle/resolve_lifetime.rs | 8 +- compiler/rustc_middle/src/mir/mono.rs | 4 +- compiler/rustc_middle/src/query/mod.rs | 16 +-- compiler/rustc_middle/src/ty/context.rs | 17 +-- compiler/rustc_middle/src/ty/error.rs | 2 +- compiler/rustc_middle/src/ty/query.rs | 10 +- compiler/rustc_monomorphize/src/collector.rs | 4 +- compiler/rustc_passes/src/check_attr.rs | 14 +-- compiler/rustc_passes/src/dead.rs | 33 +++--- compiler/rustc_passes/src/diagnostic_items.rs | 8 +- compiler/rustc_passes/src/entry.rs | 8 +- compiler/rustc_passes/src/hir_id_validator.rs | 15 ++- compiler/rustc_passes/src/layout_test.rs | 2 +- compiler/rustc_passes/src/reachable.rs | 14 +-- compiler/rustc_passes/src/stability.rs | 24 ++--- compiler/rustc_privacy/src/lib.rs | 117 +++++++++++---------- compiler/rustc_query_impl/src/keys.rs | 14 +++ compiler/rustc_query_system/src/ich/hcx.rs | 7 +- compiler/rustc_resolve/src/late/lifetimes.rs | 32 +++--- compiler/rustc_save_analysis/src/dump_visitor.rs | 46 ++++---- compiler/rustc_save_analysis/src/lib.rs | 4 +- compiler/rustc_symbol_mangling/src/test.rs | 8 +- .../src/traits/error_reporting/mod.rs | 4 +- .../src/traits/error_reporting/suggestions.rs | 4 +- compiler/rustc_ty_utils/src/assoc.rs | 2 +- compiler/rustc_typeck/src/astconv/mod.rs | 2 +- compiler/rustc_typeck/src/check/_match.rs | 4 +- compiler/rustc_typeck/src/check/check.rs | 20 ++-- compiler/rustc_typeck/src/check/coercion.rs | 6 +- compiler/rustc_typeck/src/check/demand.rs | 2 +- compiler/rustc_typeck/src/check/expr.rs | 6 +- compiler/rustc_typeck/src/check/fn_ctxt/checks.rs | 4 +- compiler/rustc_typeck/src/check/method/suggest.rs | 2 +- compiler/rustc_typeck/src/check/mod.rs | 2 +- compiler/rustc_typeck/src/check/wfcheck.rs | 61 ++++++----- .../rustc_typeck/src/coherence/inherent_impls.rs | 6 +- compiler/rustc_typeck/src/coherence/orphan.rs | 2 +- compiler/rustc_typeck/src/collect.rs | 33 +++--- compiler/rustc_typeck/src/collect/type_of.rs | 20 ++-- compiler/rustc_typeck/src/impl_wf_check.rs | 6 +- src/librustdoc/clean/mod.rs | 8 +- src/librustdoc/passes/propagate_doc_cfg.rs | 2 +- src/librustdoc/scrape_examples.rs | 11 +- .../ui-fulldeps/auxiliary/issue-40001-plugin.rs | 2 +- src/test/ui/thir-tree.stdout | 4 +- src/tools/clippy/clippy_lints/src/dereference.rs | 2 +- src/tools/clippy/clippy_lints/src/doc.rs | 10 +- src/tools/clippy/clippy_lints/src/enum_variants.rs | 2 +- src/tools/clippy/clippy_lints/src/escape.rs | 2 +- .../clippy/clippy_lints/src/exhaustive_items.rs | 2 +- src/tools/clippy/clippy_lints/src/exit.rs | 2 +- .../clippy/clippy_lints/src/fallible_impl_from.rs | 2 +- .../clippy/clippy_lints/src/functions/must_use.rs | 20 ++-- .../src/functions/not_unsafe_ptr_arg_deref.rs | 2 +- .../clippy/clippy_lints/src/functions/result.rs | 14 +-- .../clippy/clippy_lints/src/implicit_hasher.rs | 2 +- .../clippy/clippy_lints/src/inherent_to_string.rs | 2 +- .../src/iter_not_returning_iterator.rs | 4 +- src/tools/clippy/clippy_lints/src/len_zero.rs | 4 +- src/tools/clippy/clippy_lints/src/lifetimes.rs | 4 +- .../clippy_lints/src/loops/mut_range_bound.rs | 2 +- .../clippy_lints/src/manual_non_exhaustive.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/mod.rs | 8 +- .../clippy_lints/src/missing_const_for_fn.rs | 2 +- src/tools/clippy/clippy_lints/src/missing_doc.rs | 2 +- .../clippy/clippy_lints/src/missing_inline.rs | 6 +- src/tools/clippy/clippy_lints/src/mut_key.rs | 2 +- .../clippy/clippy_lints/src/new_without_default.rs | 4 +- .../clippy/clippy_lints/src/non_copy_const.rs | 2 +- .../clippy_lints/src/only_used_in_recursion.rs | 2 +- .../src/operators/assign_op_pattern.rs | 2 +- .../clippy_lints/src/pass_by_ref_or_value.rs | 2 +- .../clippy/clippy_lints/src/redundant_pub_crate.rs | 6 +- .../clippy_lints/src/return_self_not_must_use.rs | 2 +- .../clippy_lints/src/self_named_constructors.rs | 2 +- .../clippy_lints/src/suspicious_trait_impl.rs | 4 +- .../clippy/clippy_lints/src/transmute/utils.rs | 2 +- .../clippy/clippy_lints/src/types/borrowed_box.rs | 2 +- src/tools/clippy/clippy_lints/src/types/mod.rs | 8 +- src/tools/clippy/clippy_lints/src/unused_self.rs | 4 +- .../clippy/clippy_lints/src/unwrap_in_result.rs | 2 +- .../clippy/clippy_lints/src/upper_case_acronyms.rs | 2 +- src/tools/clippy/clippy_lints/src/use_self.rs | 2 +- src/tools/clippy/clippy_lints/src/utils/author.rs | 2 +- .../clippy/clippy_lints/src/wildcard_imports.rs | 6 +- .../clippy_lints/src/zero_sized_map_values.rs | 2 +- src/tools/clippy/clippy_utils/src/lib.rs | 12 +-- src/tools/clippy/clippy_utils/src/usage.rs | 2 +- 114 files changed, 659 insertions(+), 518 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index 24672efc63c..85306d7184d 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -237,7 +237,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Wrap the expression in an AnonConst. let parent_def_id = self.current_hir_id_owner; let node_id = self.next_node_id(); - self.create_def(parent_def_id, node_id, DefPathData::AnonConst); + self.create_def(parent_def_id.def_id, node_id, DefPathData::AnonConst); let anon_const = AnonConst { id: node_id, value: P(expr) }; hir::InlineAsmOperand::SymFn { anon_const: self.lower_anon_const(&anon_const), diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 6c09269352c..94137391568 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -359,7 +359,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let node_id = self.next_node_id(); // Add a definition for the in-band const def. - self.create_def(parent_def_id, node_id, DefPathData::AnonConst); + self.create_def(parent_def_id.def_id, node_id, DefPathData::AnonConst); let anon_const = AnonConst { id: node_id, value: arg }; generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const))); diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index 85846b56762..6d716796343 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -24,7 +24,7 @@ pub(super) struct NodeCollector<'a, 'hir> { /// The parent of this node parent_node: hir::ItemLocalId, - owner: LocalDefId, + owner: OwnerId, definitions: &'a definitions::Definitions, } @@ -81,9 +81,9 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})", self.source_map.span_to_diagnostic_string(span), node, - self.definitions.def_path(self.owner).to_string_no_crate_verbose(), + self.definitions.def_path(self.owner.def_id).to_string_no_crate_verbose(), self.owner, - self.definitions.def_path(hir_id.owner).to_string_no_crate_verbose(), + self.definitions.def_path(hir_id.owner.def_id).to_string_no_crate_verbose(), hir_id.owner, ) } @@ -112,19 +112,19 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_nested_item(&mut self, item: ItemId) { debug!("visit_nested_item: {:?}", item); - self.insert_nested(item.def_id); + self.insert_nested(item.def_id.def_id); } fn visit_nested_trait_item(&mut self, item_id: TraitItemId) { - self.insert_nested(item_id.def_id); + self.insert_nested(item_id.def_id.def_id); } fn visit_nested_impl_item(&mut self, item_id: ImplItemId) { - self.insert_nested(item_id.def_id); + self.insert_nested(item_id.def_id.def_id); } fn visit_nested_foreign_item(&mut self, foreign_id: ForeignItemId) { - self.insert_nested(foreign_id.def_id); + self.insert_nested(foreign_id.def_id.def_id); } fn visit_nested_body(&mut self, id: BodyId) { diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index dfd04fe2974..1251702c1ff 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -68,7 +68,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { bodies: Vec::new(), attrs: SortedMap::default(), children: FxHashMap::default(), - current_hir_id_owner: CRATE_DEF_ID, + current_hir_id_owner: hir::CRATE_OWNER_ID, item_local_id_counter: hir::ItemLocalId::new(0), node_id_to_local_id: Default::default(), local_id_to_def_id: SortedMap::new(), @@ -177,7 +177,8 @@ impl<'hir> LoweringContext<'_, 'hir> { } pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> { - let mut node_ids = smallvec![hir::ItemId { def_id: self.local_def_id(i.id) }]; + let mut node_ids = + smallvec![hir::ItemId { def_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }]; if let ItemKind::Use(ref use_tree) = &i.kind { self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids); } @@ -193,7 +194,9 @@ impl<'hir> LoweringContext<'_, 'hir> { match tree.kind { UseTreeKind::Nested(ref nested_vec) => { for &(ref nested, id) in nested_vec { - vec.push(hir::ItemId { def_id: self.local_def_id(id) }); + vec.push(hir::ItemId { + def_id: hir::OwnerId { def_id: self.local_def_id(id) }, + }); self.lower_item_id_use_tree(nested, id, vec); } } @@ -202,7 +205,9 @@ impl<'hir> LoweringContext<'_, 'hir> { for (_, &id) in iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2]) { - vec.push(hir::ItemId { def_id: self.local_def_id(id) }); + vec.push(hir::ItemId { + def_id: hir::OwnerId { def_id: self.local_def_id(id) }, + }); } } } @@ -553,7 +558,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } let item = hir::Item { - def_id: new_id, + def_id: hir::OwnerId { def_id: new_id }, ident: this.lower_ident(ident), kind, vis_span, @@ -627,7 +632,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } let item = hir::Item { - def_id: new_hir_id, + def_id: hir::OwnerId { def_id: new_hir_id }, ident: this.lower_ident(ident), kind, vis_span, @@ -689,7 +694,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef { hir::ForeignItemRef { - id: hir::ForeignItemId { def_id: self.local_def_id(i.id) }, + id: hir::ForeignItemId { def_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }, ident: self.lower_ident(i.ident), span: self.lower_span(i.span), } @@ -851,7 +856,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } AssocItemKind::MacCall(..) => unimplemented!(), }; - let id = hir::TraitItemId { def_id: self.local_def_id(i.id) }; + let id = hir::TraitItemId { def_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }; hir::TraitItemRef { id, ident: self.lower_ident(i.ident), @@ -931,7 +936,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef { hir::ImplItemRef { - id: hir::ImplItemId { def_id: self.local_def_id(i.id) }, + id: hir::ImplItemId { def_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }, ident: self.lower_ident(i.ident), span: self.lower_span(i.span), kind: match &i.kind { diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index a11721ba021..186c10065f3 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -126,7 +126,7 @@ struct LoweringContext<'a, 'hir> { is_in_trait_impl: bool, is_in_dyn_type: bool, - current_hir_id_owner: LocalDefId, + current_hir_id_owner: hir::OwnerId, item_local_id_counter: hir::ItemLocalId, local_id_to_def_id: SortedMap, trait_map: FxHashMap>, @@ -572,7 +572,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let current_node_ids = std::mem::take(&mut self.node_id_to_local_id); let current_id_to_def_id = std::mem::take(&mut self.local_id_to_def_id); let current_trait_map = std::mem::take(&mut self.trait_map); - let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id); + let current_owner = + std::mem::replace(&mut self.current_hir_id_owner, hir::OwnerId { def_id }); let current_local_counter = std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1)); let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs); @@ -587,7 +588,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug_assert_eq!(_old, None); let item = f(self); - debug_assert_eq!(def_id, item.def_id()); + debug_assert_eq!(def_id, item.def_id().def_id); // `f` should have consumed all the elements in these vectors when constructing `item`. debug_assert!(self.impl_trait_defs.is_empty()); debug_assert!(self.impl_trait_bounds.is_empty()); @@ -786,7 +787,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// Mark a span as relative to the current owning item. fn lower_span(&self, span: Span) -> Span { if self.tcx.sess.opts.unstable_opts.incremental_relative_spans { - span.with_parent(Some(self.current_hir_id_owner)) + span.with_parent(Some(self.current_hir_id_owner.def_id)) } else { // Do not make spans relative when not using incremental compilation. span @@ -812,7 +813,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { LifetimeRes::Fresh { param, .. } => { // Late resolution delegates to us the creation of the `LocalDefId`. let _def_id = self.create_def( - self.current_hir_id_owner, + self.current_hir_id_owner.def_id, param, DefPathData::LifetimeNs(kw::UnderscoreLifetime), ); @@ -1062,7 +1063,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let parent_def_id = self.current_hir_id_owner; let impl_trait_node_id = self.next_node_id(); - self.create_def(parent_def_id, impl_trait_node_id, DefPathData::ImplTrait); + self.create_def( + parent_def_id.def_id, + impl_trait_node_id, + DefPathData::ImplTrait, + ); self.with_dyn_type_scope(false, |this| { let node_id = this.next_node_id(); @@ -1154,7 +1159,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let node_id = self.next_node_id(); // Add a definition for the in-band const def. - self.create_def(parent_def_id, node_id, DefPathData::AnonConst); + self.create_def( + parent_def_id.def_id, + node_id, + DefPathData::AnonConst, + ); let span = self.lower_span(ty.span); let path_expr = Expr { @@ -1551,7 +1560,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug!(?lifetimes); // `impl Trait` now just becomes `Foo<'a, 'b, ..>`. - hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes, in_trait) + hir::TyKind::OpaqueDef( + hir::ItemId { def_id: hir::OwnerId { def_id: opaque_ty_def_id } }, + lifetimes, + in_trait, + ) } /// Registers a new opaque type with the proper `NodeId`s and @@ -1567,7 +1580,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Generate an `type Foo = impl Trait;` declaration. trace!("registering opaque type with id {:#?}", opaque_ty_id); let opaque_ty_item = hir::Item { - def_id: opaque_ty_id, + def_id: hir::OwnerId { def_id: opaque_ty_id }, ident: Ident::empty(), kind: opaque_ty_item_kind, vis_span: self.lower_span(span.shrink_to_lo()), @@ -2018,7 +2031,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // async fn, so the *type parameters* are inherited. It's // only the lifetime parameters that we must supply. let opaque_ty_ref = hir::TyKind::OpaqueDef( - hir::ItemId { def_id: opaque_ty_def_id }, + hir::ItemId { def_id: hir::OwnerId { def_id: opaque_ty_def_id } }, generic_args, in_trait, ); diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 202729b4744..8ad40c0aa0a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -932,7 +932,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let opt_suggestions = self .infcx .tcx - .typeck(path_segment.hir_id.owner) + .typeck(path_segment.hir_id.owner.def_id) .type_dependent_def_id(*hir_id) .and_then(|def_id| self.infcx.tcx.impl_of_method(def_id)) .map(|def_id| self.infcx.tcx.associated_items(def_id)) @@ -1032,7 +1032,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { if look_at_return && hir.get_return_block(closure_id).is_some() { // ...otherwise we are probably in the tail expression of the function, point at the // return type. - match hir.get_by_def_id(hir.get_parent_item(fn_call_id)) { + match hir.get_by_def_id(hir.get_parent_item(fn_call_id).def_id) { hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(sig, ..), .. }) | hir::Node::TraitItem(hir::TraitItem { ident, diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 34be2874fcb..43d67bfa729 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -281,7 +281,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let tcx = self.infcx.tcx; match tcx.hir().get_if_local(def_id) { Some(Node::ImplItem(impl_item)) => { - match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id())) { + match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id()).def_id) + { Some(Node::Item(Item { kind: ItemKind::Impl(hir::Impl { self_ty, .. }), .. @@ -291,7 +292,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } Some(Node::TraitItem(trait_item)) => { let trait_did = tcx.hir().get_parent_item(trait_item.hir_id()); - match tcx.hir().find_by_def_id(trait_did) { + match tcx.hir().find_by_def_id(trait_did.def_id) { Some(Node::Item(Item { kind: ItemKind::Trait(..), .. })) => { // The method being called is defined in the `trait`, but the `'static` // obligation comes from the `impl`. Find that `impl` so that we can point diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 6c1eaa809c9..419e6c81791 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -707,7 +707,8 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { hir::AsyncGeneratorKind::Block => " of async block", hir::AsyncGeneratorKind::Closure => " of async closure", hir::AsyncGeneratorKind::Fn => { - let parent_item = hir.get_by_def_id(hir.get_parent_item(mir_hir_id)); + let parent_item = + hir.get_by_def_id(hir.get_parent_item(mir_hir_id).def_id); let output = &parent_item .fn_decl() .expect("generator lowered from async fn should be in fn") diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index cb16bec57ee..6b90f2daeea 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -134,7 +134,7 @@ fn mir_borrowck<'tcx>( let opt_closure_req = tcx .infer_ctxt() - .with_opaque_type_inference(DefiningAnchor::Bind(hir_owner)) + .with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)) .enter(|infcx| { let input_body: &Body<'_> = &input_body.borrow(); let promoted: &IndexVec<_, _> = &promoted.borrow(); diff --git a/compiler/rustc_driver/src/pretty.rs b/compiler/rustc_driver/src/pretty.rs index 2874fa0caff..e97da4322fa 100644 --- a/compiler/rustc_driver/src/pretty.rs +++ b/compiler/rustc_driver/src/pretty.rs @@ -329,7 +329,7 @@ impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> { let typeck_results = self.maybe_typeck_results.get().or_else(|| { self.tcx .hir() - .maybe_body_owned_by(expr.hir_id.owner) + .maybe_body_owned_by(expr.hir_id.owner.def_id) .map(|body_id| self.tcx.typeck_body(body_id)) }); diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index a8436ea64f8..018b7cc5d9d 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1,6 +1,6 @@ use crate::def::{CtorKind, DefKind, Res}; use crate::def_id::DefId; -pub(crate) use crate::hir_id::{HirId, ItemLocalId}; +pub(crate) use crate::hir_id::{HirId, ItemLocalId, OwnerId}; use crate::intravisit::FnKind; use crate::LangItem; @@ -2206,14 +2206,14 @@ pub struct FnSig<'hir> { // so it can fetched later. #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)] pub struct TraitItemId { - pub def_id: LocalDefId, + pub def_id: OwnerId, } impl TraitItemId { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. - HirId::make_owner(self.def_id) + HirId::make_owner(self.def_id.def_id) } } @@ -2224,7 +2224,7 @@ impl TraitItemId { #[derive(Debug, HashStable_Generic)] pub struct TraitItem<'hir> { pub ident: Ident, - pub def_id: LocalDefId, + pub def_id: OwnerId, pub generics: &'hir Generics<'hir>, pub kind: TraitItemKind<'hir>, pub span: Span, @@ -2235,7 +2235,7 @@ impl TraitItem<'_> { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. - HirId::make_owner(self.def_id) + HirId::make_owner(self.def_id.def_id) } pub fn trait_item_id(&self) -> TraitItemId { @@ -2270,14 +2270,14 @@ pub enum TraitItemKind<'hir> { // so it can fetched later. #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)] pub struct ImplItemId { - pub def_id: LocalDefId, + pub def_id: OwnerId, } impl ImplItemId { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. - HirId::make_owner(self.def_id) + HirId::make_owner(self.def_id.def_id) } } @@ -2285,7 +2285,7 @@ impl ImplItemId { #[derive(Debug, HashStable_Generic)] pub struct ImplItem<'hir> { pub ident: Ident, - pub def_id: LocalDefId, + pub def_id: OwnerId, pub generics: &'hir Generics<'hir>, pub kind: ImplItemKind<'hir>, pub defaultness: Defaultness, @@ -2297,7 +2297,7 @@ impl ImplItem<'_> { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. - HirId::make_owner(self.def_id) + HirId::make_owner(self.def_id.def_id) } pub fn impl_item_id(&self) -> ImplItemId { @@ -2888,14 +2888,14 @@ impl<'hir> VariantData<'hir> { // so it can fetched later. #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, Hash, HashStable_Generic)] pub struct ItemId { - pub def_id: LocalDefId, + pub def_id: OwnerId, } impl ItemId { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. - HirId::make_owner(self.def_id) + HirId::make_owner(self.def_id.def_id) } } @@ -2905,7 +2905,7 @@ impl ItemId { #[derive(Debug, HashStable_Generic)] pub struct Item<'hir> { pub ident: Ident, - pub def_id: LocalDefId, + pub def_id: OwnerId, pub kind: ItemKind<'hir>, pub span: Span, pub vis_span: Span, @@ -2915,7 +2915,7 @@ impl Item<'_> { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. - HirId::make_owner(self.def_id) + HirId::make_owner(self.def_id.def_id) } pub fn item_id(&self) -> ItemId { @@ -3132,14 +3132,14 @@ pub enum AssocItemKind { // so it can fetched later. #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)] pub struct ForeignItemId { - pub def_id: LocalDefId, + pub def_id: OwnerId, } impl ForeignItemId { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. - HirId::make_owner(self.def_id) + HirId::make_owner(self.def_id.def_id) } } @@ -3160,7 +3160,7 @@ pub struct ForeignItemRef { pub struct ForeignItem<'hir> { pub ident: Ident, pub kind: ForeignItemKind<'hir>, - pub def_id: LocalDefId, + pub def_id: OwnerId, pub span: Span, pub vis_span: Span, } @@ -3169,7 +3169,7 @@ impl ForeignItem<'_> { #[inline] pub fn hir_id(&self) -> HirId { // Items are always HIR owners. - HirId::make_owner(self.def_id) + HirId::make_owner(self.def_id.def_id) } pub fn foreign_item_id(&self) -> ForeignItemId { @@ -3263,7 +3263,7 @@ impl<'hir> OwnerNode<'hir> { Node::generics(self.into()) } - pub fn def_id(self) -> LocalDefId { + pub fn def_id(self) -> OwnerId { match self { OwnerNode::Item(Item { def_id, .. }) | OwnerNode::TraitItem(TraitItem { def_id, .. }) diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index 84b0740c7b3..752f760ea97 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -1,6 +1,43 @@ -use crate::def_id::{LocalDefId, CRATE_DEF_ID}; +use crate::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; +use rustc_span::{def_id::DefPathHash, HashStableContext}; use std::fmt; +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Encodable, Decodable)] +pub struct OwnerId { + pub def_id: LocalDefId, +} + +impl From for HirId { + fn from(owner: OwnerId) -> HirId { + HirId { owner, local_id: ItemLocalId::from_u32(0) } + } +} + +impl OwnerId { + #[inline] + pub fn to_def_id(self) -> DefId { + self.def_id.to_def_id() + } +} + +impl HashStable for OwnerId { + #[inline] + fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { + self.to_stable_hash_key(hcx).hash_stable(hcx, hasher); + } +} + +impl ToStableHashKey for OwnerId { + type KeyType = DefPathHash; + + #[inline] + fn to_stable_hash_key(&self, hcx: &CTX) -> DefPathHash { + hcx.def_path_hash(self.to_def_id()) + } +} + /// Uniquely identifies a node in the HIR of the current crate. It is /// composed of the `owner`, which is the `LocalDefId` of the directly enclosing /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"), @@ -15,22 +52,23 @@ use std::fmt; #[derive(Encodable, Decodable, HashStable_Generic)] #[rustc_pass_by_value] pub struct HirId { - pub owner: LocalDefId, + pub owner: OwnerId, pub local_id: ItemLocalId, } impl HirId { /// Signal local id which should never be used. - pub const INVALID: HirId = HirId { owner: CRATE_DEF_ID, local_id: ItemLocalId::INVALID }; + pub const INVALID: HirId = + HirId { owner: OwnerId { def_id: CRATE_DEF_ID }, local_id: ItemLocalId::INVALID }; #[inline] - pub fn expect_owner(self) -> LocalDefId { + pub fn expect_owner(self) -> OwnerId { assert_eq!(self.local_id.index(), 0); self.owner } #[inline] - pub fn as_owner(self) -> Option { + pub fn as_owner(self) -> Option { if self.local_id.index() == 0 { Some(self.owner) } else { None } } @@ -41,11 +79,14 @@ impl HirId { #[inline] pub fn make_owner(owner: LocalDefId) -> Self { - Self { owner, local_id: ItemLocalId::from_u32(0) } + Self { owner: OwnerId { def_id: owner }, local_id: ItemLocalId::from_u32(0) } } pub fn index(self) -> (usize, usize) { - (rustc_index::vec::Idx::index(self.owner), rustc_index::vec::Idx::index(self.local_id)) + ( + rustc_index::vec::Idx::index(self.owner.def_id), + rustc_index::vec::Idx::index(self.local_id), + ) } } @@ -94,4 +135,7 @@ impl ItemLocalId { } /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_ID`. -pub const CRATE_HIR_ID: HirId = HirId { owner: CRATE_DEF_ID, local_id: ItemLocalId::from_u32(0) }; +pub const CRATE_HIR_ID: HirId = + HirId { owner: OwnerId { def_id: CRATE_DEF_ID }, local_id: ItemLocalId::from_u32(0) }; + +pub const CRATE_OWNER_ID: OwnerId = OwnerId { def_id: CRATE_DEF_ID }; diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index 5b9c42686c3..06b7a65662e 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -20,7 +20,7 @@ impl ToStableHashKey for HirId { #[inline] fn to_stable_hash_key(&self, hcx: &HirCtx) -> (DefPathHash, ItemLocalId) { - let def_path_hash = self.owner.to_stable_hash_key(hcx); + let def_path_hash = self.owner.def_id.to_stable_hash_key(hcx); (def_path_hash, self.local_id) } } @@ -49,7 +49,7 @@ impl ToStableHashKey for ItemId { #[inline] fn to_stable_hash_key(&self, hcx: &HirCtx) -> DefPathHash { - self.def_id.to_stable_hash_key(hcx) + self.def_id.def_id.to_stable_hash_key(hcx) } } @@ -58,7 +58,7 @@ impl ToStableHashKey for TraitItemId { #[inline] fn to_stable_hash_key(&self, hcx: &HirCtx) -> DefPathHash { - self.def_id.to_stable_hash_key(hcx) + self.def_id.def_id.to_stable_hash_key(hcx) } } @@ -67,7 +67,7 @@ impl ToStableHashKey for ImplItemId { #[inline] fn to_stable_hash_key(&self, hcx: &HirCtx) -> DefPathHash { - self.def_id.to_stable_hash_key(hcx) + self.def_id.def_id.to_stable_hash_key(hcx) } } @@ -76,7 +76,7 @@ impl ToStableHashKey for ForeignItemId #[inline] fn to_stable_hash_key(&self, hcx: &HirCtx) -> DefPathHash { - self.def_id.to_stable_hash_key(hcx) + self.def_id.def_id.to_stable_hash_key(hcx) } } diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 710c4a01b24..09163e4f25f 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -149,19 +149,19 @@ pub fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { let crate_items = tcx.hir_crate_items(()); for id in crate_items.items() { - dirty_clean_visitor.check_item(id.def_id); + dirty_clean_visitor.check_item(id.def_id.def_id); } for id in crate_items.trait_items() { - dirty_clean_visitor.check_item(id.def_id); + dirty_clean_visitor.check_item(id.def_id.def_id); } for id in crate_items.impl_items() { - dirty_clean_visitor.check_item(id.def_id); + dirty_clean_visitor.check_item(id.def_id.def_id); } for id in crate_items.foreign_items() { - dirty_clean_visitor.check_item(id.def_id); + dirty_clean_visitor.check_item(id.def_id.def_id); } let mut all_attrs = FindAllAttrs { tcx, found_attrs: vec![] }; diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 82099d9e3f3..0208c364e43 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -2440,7 +2440,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // We do this to avoid suggesting code that ends up as `T: 'a'b`, // instead we suggest `T: 'a + 'b` in that case. let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); - let ast_generics = self.tcx.hir().get_generics(hir_id.owner); + let ast_generics = self.tcx.hir().get_generics(hir_id.owner.def_id); let bounds = ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id)); // `sp` only covers `T`, change it so that it covers diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index ae56bea6f86..2ccfcd51b11 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -185,8 +185,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { | ObligationCauseCode::BlockTailExpression(hir_id) = cause.code() { let parent_id = tcx.hir().get_parent_item(*hir_id); - let parent_id = tcx.hir().local_def_id_to_hir_id(parent_id); - if let Some(fn_decl) = tcx.hir().fn_decl_by_hir_id(parent_id) { + if let Some(fn_decl) = tcx.hir().fn_decl_by_hir_id(parent_id.into()) { let mut span: MultiSpan = fn_decl.output.span().into(); let mut add_label = true; if let hir::FnRetTy::Return(ty) = fn_decl.output { @@ -415,7 +414,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let tcx = self.tcx(); match tcx.hir().get_if_local(def_id) { Some(Node::ImplItem(impl_item)) => { - match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id())) { + match tcx.hir().find_by_def_id(tcx.hir().get_parent_item(impl_item.hir_id()).def_id) + { Some(Node::Item(Item { kind: ItemKind::Impl(hir::Impl { self_ty, .. }), .. @@ -425,7 +425,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { } Some(Node::TraitItem(trait_item)) => { let trait_did = tcx.hir().get_parent_item(trait_item.hir_id()); - match tcx.hir().find_by_def_id(trait_did) { + match tcx.hir().find_by_def_id(trait_did.def_id) { Some(Node::Item(Item { kind: ItemKind::Trait(..), .. })) => { // The method being called is defined in the `trait`, but the `'static` // obligation comes from the `impl`. Find that `impl` so that we can point diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 55cf9b7a2ea..efc9c1ca46f 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -16,6 +16,7 @@ use rustc_data_structures::undo_log::Rollback; use rustc_data_structures::unify as ut; use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::hir_id::OwnerId; use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues}; use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue}; use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType}; @@ -583,9 +584,9 @@ impl<'tcx> InferCtxtBuilder<'tcx> { /// Used only by `rustc_typeck` during body type-checking/inference, /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. /// Will also change the scope for opaque type defining use checks to the given owner. - pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { + pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: OwnerId) -> Self { self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); - self.with_opaque_type_inference(DefiningAnchor::Bind(table_owner)) + self.with_opaque_type_inference(DefiningAnchor::Bind(table_owner.def_id)) } /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, diff --git a/compiler/rustc_infer/src/infer/opaque_types.rs b/compiler/rustc_infer/src/infer/opaque_types.rs index 76c340a5efa..9bf92f08aa5 100644 --- a/compiler/rustc_infer/src/infer/opaque_types.rs +++ b/compiler/rustc_infer/src/infer/opaque_types.rs @@ -616,7 +616,7 @@ fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hi let scope = tcx.hir().get_defining_scope(opaque_hir_id); // We walk up the node tree until we hit the root or the scope of the opaque type. while hir_id != scope && hir_id != hir::CRATE_HIR_ID { - hir_id = tcx.hir().local_def_id_to_hir_id(tcx.hir().get_parent_item(hir_id)); + hir_id = tcx.hir().get_parent_item(hir_id).into(); } // Syntactically, we are allowed to define the concrete type if: let res = hir_id == scope; diff --git a/compiler/rustc_interface/src/proc_macro_decls.rs b/compiler/rustc_interface/src/proc_macro_decls.rs index 5371c513d29..2b1b931b732 100644 --- a/compiler/rustc_interface/src/proc_macro_decls.rs +++ b/compiler/rustc_interface/src/proc_macro_decls.rs @@ -1,4 +1,3 @@ -use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; @@ -10,7 +9,7 @@ fn proc_macro_decls_static(tcx: TyCtxt<'_>, (): ()) -> Option { for id in tcx.hir().items() { let attrs = finder.tcx.hir().attrs(id.hir_id()); if finder.tcx.sess.contains_name(attrs, sym::rustc_proc_macro_decls) { - finder.decls = Some(id.def_id); + finder.decls = Some(id.def_id.def_id); } } @@ -19,7 +18,7 @@ fn proc_macro_decls_static(tcx: TyCtxt<'_>, (): ()) -> Option { struct Finder<'tcx> { tcx: TyCtxt<'tcx>, - decls: Option, + decls: Option, } pub(crate) fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 0ff2ef5cda3..5fba1d3d3c7 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -606,7 +606,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { // Issue #11592: traits are always considered exported, even when private. if cx.tcx.visibility(it.def_id) == ty::Visibility::Restricted( - cx.tcx.parent_module_from_def_id(it.def_id).to_def_id(), + cx.tcx.parent_module_from_def_id(it.def_id.def_id).to_def_id(), ) { return; @@ -627,13 +627,13 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { let (article, desc) = cx.tcx.article_and_description(it.def_id.to_def_id()); - self.check_missing_docs_attrs(cx, it.def_id, article, desc); + self.check_missing_docs_attrs(cx, it.def_id.def_id, article, desc); } fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) { let (article, desc) = cx.tcx.article_and_description(trait_item.def_id.to_def_id()); - self.check_missing_docs_attrs(cx, trait_item.def_id, article, desc); + self.check_missing_docs_attrs(cx, trait_item.def_id.def_id, article, desc); } fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { @@ -661,12 +661,12 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { } let (article, desc) = cx.tcx.article_and_description(impl_item.def_id.to_def_id()); - self.check_missing_docs_attrs(cx, impl_item.def_id, article, desc); + self.check_missing_docs_attrs(cx, impl_item.def_id.def_id, article, desc); } fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) { let (article, desc) = cx.tcx.article_and_description(foreign_item.def_id.to_def_id()); - self.check_missing_docs_attrs(cx, foreign_item.def_id, article, desc); + self.check_missing_docs_attrs(cx, foreign_item.def_id.def_id, article, desc); } fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) { @@ -719,7 +719,7 @@ declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]) impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations { fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { - if !cx.access_levels.is_reachable(item.def_id) { + if !cx.access_levels.is_reachable(item.def_id.def_id) { return; } let (def, ty) = match item.kind { @@ -809,7 +809,7 @@ impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]); impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { - if !cx.access_levels.is_reachable(item.def_id) { + if !cx.access_levels.is_reachable(item.def_id.def_id) { return; } @@ -836,7 +836,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { debug!("{:?}", self.impling_types); } - if !self.impling_types.as_ref().unwrap().contains(&item.def_id) { + if !self.impling_types.as_ref().unwrap().contains(&item.def_id.def_id) { cx.struct_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item.span, |lint| { lint.build(fluent::lint::builtin_missing_debug_impl) .set_arg("debug", cx.tcx.def_path_str(debug)) @@ -1206,7 +1206,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { check_no_mangle_on_generic_fn( no_mangle_attr, Some(generics), - cx.tcx.hir().get_generics(it.id.def_id).unwrap(), + cx.tcx.hir().get_generics(it.id.def_id.def_id).unwrap(), it.span, ); } @@ -1389,11 +1389,11 @@ impl<'tcx> LateLintPass<'tcx> for UnreachablePub { if let hir::ItemKind::Use(_, hir::UseKind::ListStem) = &item.kind { return; } - self.perform_lint(cx, "item", item.def_id, item.vis_span, true); + self.perform_lint(cx, "item", item.def_id.def_id, item.vis_span, true); } fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) { - self.perform_lint(cx, "item", foreign_item.def_id, foreign_item.vis_span, true); + self.perform_lint(cx, "item", foreign_item.def_id.def_id, foreign_item.vis_span, true); } fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) { @@ -1404,7 +1404,7 @@ impl<'tcx> LateLintPass<'tcx> for UnreachablePub { fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { // Only lint inherent impl items. if cx.tcx.associated_item(impl_item.def_id).trait_item_def_id.is_none() { - self.perform_lint(cx, "item", impl_item.def_id, impl_item.vis_span, false); + self.perform_lint(cx, "item", impl_item.def_id.def_id, impl_item.vis_span, false); } } } @@ -1841,7 +1841,7 @@ declare_lint! { } pub struct UnnameableTestItems { - boundary: Option, // Id of the item under which things are not nameable + boundary: Option, // Id of the item under which things are not nameable items_nameable: bool, } @@ -2138,7 +2138,7 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { use rustc_middle::middle::resolve_lifetime::Region; - let def_id = item.def_id; + let def_id = item.def_id.def_id; if let hir::ItemKind::Struct(_, ref hir_generics) | hir::ItemKind::Enum(_, ref hir_generics) | hir::ItemKind::Union(_, ref hir_generics) = item.kind diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 7ca6ec5d962..cbab56f2066 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -1048,7 +1048,7 @@ impl<'tcx> LateContext<'tcx> { .filter(|typeck_results| typeck_results.hir_owner == id.owner) .or_else(|| { if self.tcx.has_typeck_results(id.owner.to_def_id()) { - Some(self.tcx.typeck(id.owner)) + Some(self.tcx.typeck(id.owner.def_id)) } else { None } diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index 2a986c41d72..9abb5c74895 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -382,7 +382,7 @@ impl<'tcx> Collector<'tcx> { let link_ordinal_attr = self .tcx .hir() - .attrs(self.tcx.hir().local_def_id_to_hir_id(child_item.id.def_id)) + .attrs(child_item.id.def_id.into()) .iter() .find(|a| a.has_name(sym::link_ordinal)) .unwrap(); diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 67c28461ce5..7cf00ca41fe 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1217,14 +1217,14 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // from name resolution point of view. hir::ItemKind::ForeignMod { items, .. } => { for foreign_item in items { - yield foreign_item.id.def_id.local_def_index; + yield foreign_item.id.def_id.def_id.local_def_index; } } // Only encode named non-reexport children, reexports are encoded // separately and unnamed items are not used by name resolution. hir::ItemKind::ExternCrate(..) => continue, _ if tcx.def_key(item_id.def_id.to_def_id()).get_opt_name().is_some() => { - yield item_id.def_id.local_def_index; + yield item_id.def_id.def_id.local_def_index; } _ => continue, } @@ -1446,7 +1446,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { record!(self.tables.macro_definition[def_id] <- &*macro_def.body); } hir::ItemKind::Mod(ref m) => { - return self.encode_info_for_mod(item.def_id, m); + return self.encode_info_for_mod(item.def_id.def_id, m); } hir::ItemKind::OpaqueTy(..) => { self.encode_explicit_item_bounds(def_id); @@ -1840,7 +1840,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { for id in tcx.hir().items() { if matches!(tcx.def_kind(id.def_id), DefKind::Impl) { - if let Some(trait_ref) = tcx.impl_trait_ref(id.def_id.to_def_id()) { + if let Some(trait_ref) = tcx.impl_trait_ref(id.def_id) { let simplified_self_ty = fast_reject::simplify_type( self.tcx, trait_ref.self_ty(), @@ -1850,7 +1850,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fx_hash_map .entry(trait_ref.def_id) .or_default() - .push((id.def_id.local_def_index, simplified_self_ty)); + .push((id.def_id.def_id.local_def_index, simplified_self_ty)); } } } diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 1fa0c6babab..ac106764c02 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -62,7 +62,7 @@ use crate::ty::TyCtxt; use rustc_data_structures::fingerprint::Fingerprint; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_hir::definitions::DefPathHash; -use rustc_hir::HirId; +use rustc_hir::{HirId, OwnerId}; use rustc_query_system::dep_graph::FingerprintStyle; use rustc_span::symbol::Symbol; use std::hash::Hash; @@ -355,6 +355,28 @@ impl<'tcx> DepNodeParams> for LocalDefId { } } +impl<'tcx> DepNodeParams> for OwnerId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } + + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + self.to_def_id().to_fingerprint(tcx) + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + self.to_def_id().to_debug_str(tcx) + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + dep_node.extract_def_id(tcx).map(|id| OwnerId { def_id: id.expect_local() }) + } +} + impl<'tcx> DepNodeParams> for CrateNum { #[inline(always)] fn fingerprint_style() -> FingerprintStyle { diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 30a23c342b3..b5f7b26ea7a 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -93,7 +93,7 @@ pub struct ParentOwnerIterator<'hir> { } impl<'hir> Iterator for ParentOwnerIterator<'hir> { - type Item = (LocalDefId, OwnerNode<'hir>); + type Item = (OwnerId, OwnerNode<'hir>); fn next(&mut self) -> Option { if self.current_id.local_id.index() != 0 { @@ -107,13 +107,13 @@ impl<'hir> Iterator for ParentOwnerIterator<'hir> { } loop { // There are nodes that do not have entries, so we need to skip them. - let parent_id = self.map.def_key(self.current_id.owner).parent; + let parent_id = self.map.def_key(self.current_id.owner.def_id).parent; - let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| { + let parent_id = parent_id.map_or(CRATE_OWNER_ID, |local_def_index| { let def_id = LocalDefId { local_def_index }; self.map.local_def_id_to_hir_id(def_id).owner }); - self.current_id = HirId::make_owner(parent_id); + self.current_id = HirId::make_owner(parent_id.def_id); // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { @@ -131,7 +131,7 @@ impl<'hir> Map<'hir> { #[inline] pub fn root_module(self) -> &'hir Mod<'hir> { - match self.tcx.hir_owner(CRATE_DEF_ID).map(|o| o.node) { + match self.tcx.hir_owner(CRATE_OWNER_ID).map(|o| o.node) { Some(OwnerNode::Crate(item)) => item, _ => bug!(), } @@ -186,7 +186,7 @@ impl<'hir> Map<'hir> { #[inline] pub fn opt_local_def_id(self, hir_id: HirId) -> Option { if hir_id.local_id == ItemLocalId::new(0) { - Some(hir_id.owner) + Some(hir_id.owner.def_id) } else { self.tcx .hir_owner_nodes(hir_id.owner) @@ -352,7 +352,7 @@ impl<'hir> Map<'hir> { } pub fn get_generics(self, id: LocalDefId) -> Option<&'hir Generics<'hir>> { - let node = self.tcx.hir_owner(id)?; + let node = self.tcx.hir_owner(OwnerId { def_id: id })?; node.node.generics() } @@ -532,7 +532,7 @@ impl<'hir> Map<'hir> { pub fn get_module(self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { let hir_id = HirId::make_owner(module); - match self.tcx.hir_owner(module).map(|o| o.node) { + match self.tcx.hir_owner(hir_id.owner).map(|o| o.node) { Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => { (m, span, hir_id) } @@ -622,14 +622,14 @@ impl<'hir> Map<'hir> { pub fn for_each_module(self, mut f: impl FnMut(LocalDefId)) { let crate_items = self.tcx.hir_crate_items(()); for module in crate_items.submodules.iter() { - f(*module) + f(module.def_id) } } #[inline] pub fn par_for_each_module(self, f: impl Fn(LocalDefId) + Sync + Send) { let crate_items = self.tcx.hir_crate_items(()); - par_for_each_in(&crate_items.submodules[..], |module| f(*module)) + par_for_each_in(&crate_items.submodules[..], |module| f(module.def_id)) } /// Returns an iterator for the nodes in the ancestor tree of the `current_id` @@ -721,27 +721,27 @@ impl<'hir> Map<'hir> { None } - /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no + /// Retrieves the `OwnerId` for `id`'s parent item, or `id` itself if no /// parent item is in this map. The "parent item" is the closest parent node /// in the HIR which is recorded by the map and is an item, either an item /// in a module, trait, or impl. - pub fn get_parent_item(self, hir_id: HirId) -> LocalDefId { + pub fn get_parent_item(self, hir_id: HirId) -> OwnerId { if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() { def_id } else { - CRATE_DEF_ID + CRATE_OWNER_ID } } - /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no + /// Returns the `OwnerId` of `id`'s nearest module parent, or `id` itself if no /// module parent is in this map. - pub(super) fn get_module_parent_node(self, hir_id: HirId) -> LocalDefId { + pub(super) fn get_module_parent_node(self, hir_id: HirId) -> OwnerId { for (def_id, node) in self.parent_owner_iter(hir_id) { if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node { return def_id; } } - CRATE_DEF_ID + CRATE_OWNER_ID } /// When on an if expression, a match arm tail expression or a match arm, give back @@ -814,30 +814,30 @@ impl<'hir> Map<'hir> { } bug!( "expected foreign mod or inlined parent, found {}", - self.node_to_string(HirId::make_owner(parent)) + self.node_to_string(HirId::make_owner(parent.def_id)) ) } - pub fn expect_owner(self, id: LocalDefId) -> OwnerNode<'hir> { + pub fn expect_owner(self, id: OwnerId) -> OwnerNode<'hir> { self.tcx.hir_owner(id).unwrap_or_else(|| bug!("expected owner for {:?}", id)).node } pub fn expect_item(self, id: LocalDefId) -> &'hir Item<'hir> { - match self.tcx.hir_owner(id) { + match self.tcx.hir_owner(OwnerId { def_id: id }) { Some(Owner { node: OwnerNode::Item(item), .. }) => item, _ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))), } } pub fn expect_impl_item(self, id: LocalDefId) -> &'hir ImplItem<'hir> { - match self.tcx.hir_owner(id) { + match self.tcx.hir_owner(OwnerId { def_id: id }) { Some(Owner { node: OwnerNode::ImplItem(item), .. }) => item, _ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))), } } pub fn expect_trait_item(self, id: LocalDefId) -> &'hir TraitItem<'hir> { - match self.tcx.hir_owner(id) { + match self.tcx.hir_owner(OwnerId { def_id: id }) { Some(Owner { node: OwnerNode::TraitItem(item), .. }) => item, _ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))), } @@ -850,11 +850,14 @@ impl<'hir> Map<'hir> { } } - pub fn expect_foreign_item(self, id: LocalDefId) -> &'hir ForeignItem<'hir> { + pub fn expect_foreign_item(self, id: OwnerId) -> &'hir ForeignItem<'hir> { match self.tcx.hir_owner(id) { Some(Owner { node: OwnerNode::ForeignItem(item), .. }) => item, _ => { - bug!("expected foreign item, found {}", self.node_to_string(HirId::make_owner(id))) + bug!( + "expected foreign item, found {}", + self.node_to_string(HirId::make_owner(id.def_id)) + ) } } } @@ -1290,7 +1293,7 @@ pub(crate) fn hir_crate_items(tcx: TyCtxt<'_>, _: ()) -> ModuleItems { // A "crate collector" and "module collector" start at a // module item (the former starts at the crate root) but only // the former needs to collect it. ItemCollector does not do this for us. - collector.submodules.push(CRATE_DEF_ID); + collector.submodules.push(CRATE_OWNER_ID); tcx.hir().walk_toplevel_module(&mut collector); let ItemCollector { @@ -1318,7 +1321,7 @@ struct ItemCollector<'tcx> { // otherwise it collects items in some module. crate_collector: bool, tcx: TyCtxt<'tcx>, - submodules: Vec, + submodules: Vec, items: Vec, trait_items: Vec, impl_items: Vec, @@ -1350,7 +1353,7 @@ impl<'hir> Visitor<'hir> for ItemCollector<'hir> { fn visit_item(&mut self, item: &'hir Item<'hir>) { if associated_body(Node::Item(item)).is_some() { - self.body_owners.push(item.def_id); + self.body_owners.push(item.def_id.def_id); } self.items.push(item.item_id()); @@ -1386,7 +1389,7 @@ impl<'hir> Visitor<'hir> for ItemCollector<'hir> { fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) { if associated_body(Node::TraitItem(item)).is_some() { - self.body_owners.push(item.def_id); + self.body_owners.push(item.def_id.def_id); } self.trait_items.push(item.trait_item_id()); @@ -1395,7 +1398,7 @@ impl<'hir> Visitor<'hir> for ItemCollector<'hir> { fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) { if associated_body(Node::ImplItem(item)).is_some() { - self.body_owners.push(item.def_id); + self.body_owners.push(item.def_id.def_id); } self.impl_items.push(item.impl_item_id()); diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 211a614717f..1ce98a03c8a 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -39,7 +39,7 @@ impl<'a, 'tcx> HashStable> for Owner<'tcx> { /// bodies. The Ids are in visitor order. This is used to partition a pass between modules. #[derive(Debug, HashStable, Encodable, Decodable)] pub struct ModuleItems { - submodules: Box<[LocalDefId]>, + submodules: Box<[OwnerId]>, items: Box<[ItemId]>, trait_items: Box<[TraitItemId]>, impl_items: Box<[ImplItemId]>, @@ -67,10 +67,10 @@ impl ModuleItems { pub fn definitions(&self) -> impl Iterator + '_ { self.items .iter() - .map(|id| id.def_id) - .chain(self.trait_items.iter().map(|id| id.def_id)) - .chain(self.impl_items.iter().map(|id| id.def_id)) - .chain(self.foreign_items.iter().map(|id| id.def_id)) + .map(|id| id.def_id.def_id) + .chain(self.trait_items.iter().map(|id| id.def_id.def_id)) + .chain(self.impl_items.iter().map(|id| id.def_id.def_id)) + .chain(self.foreign_items.iter().map(|id| id.def_id.def_id)) } pub fn par_items(&self, f: impl Fn(ItemId) + Send + Sync) { @@ -97,7 +97,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn parent_module(self, id: HirId) -> LocalDefId { - self.parent_module_from_def_id(id.owner) + self.parent_module_from_def_id(id.owner.def_id) } pub fn impl_subject(self, def_id: DefId) -> ImplSubject<'tcx> { @@ -110,13 +110,13 @@ impl<'tcx> TyCtxt<'tcx> { pub fn provide(providers: &mut Providers) { providers.parent_module_from_def_id = |tcx, id| { let hir = tcx.hir(); - hir.get_module_parent_node(hir.local_def_id_to_hir_id(id)) + hir.get_module_parent_node(hir.local_def_id_to_hir_id(id)).def_id }; providers.hir_crate_items = map::hir_crate_items; providers.crate_hash = map::crate_hash; providers.hir_module_items = map::hir_module_items; providers.hir_owner = |tcx, id| { - let owner = tcx.hir_crate(()).owners.get(id)?.as_owner()?; + let owner = tcx.hir_crate(()).owners.get(id.def_id)?.as_owner()?; let node = owner.node(); Some(Owner { node, hash_without_bodies: owner.nodes.hash_without_bodies }) }; @@ -128,21 +128,24 @@ pub fn provide(providers: &mut Providers) { MaybeOwner::NonOwner(hir_id) => hir_id, } }; - providers.hir_owner_nodes = |tcx, id| tcx.hir_crate(()).owners[id].map(|i| &i.nodes); + providers.hir_owner_nodes = |tcx, id| tcx.hir_crate(()).owners[id.def_id].map(|i| &i.nodes); providers.hir_owner_parent = |tcx, id| { // Accessing the local_parent is ok since its value is hashed as part of `id`'s DefPathHash. - tcx.opt_local_parent(id).map_or(CRATE_HIR_ID, |parent| { + tcx.opt_local_parent(id.def_id).map_or(CRATE_HIR_ID, |parent| { let mut parent_hir_id = tcx.hir().local_def_id_to_hir_id(parent); - if let Some(local_id) = - tcx.hir_crate(()).owners[parent_hir_id.owner].unwrap().parenting.get(&id) + if let Some(local_id) = tcx.hir_crate(()).owners[parent_hir_id.owner.def_id] + .unwrap() + .parenting + .get(&id.def_id) { parent_hir_id.local_id = *local_id; } parent_hir_id }) }; - providers.hir_attrs = - |tcx, id| tcx.hir_crate(()).owners[id].as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs); + providers.hir_attrs = |tcx, id| { + tcx.hir_crate(()).owners[id.def_id].as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs) + }; providers.source_span = |tcx, def_id| tcx.resolutions(()).source_span.get(def_id).copied().unwrap_or(DUMMY_SP); providers.def_span = |tcx, def_id| { @@ -177,6 +180,7 @@ pub fn provide(providers: &mut Providers) { let id = id.expect_local(); tcx.resolutions(()).expn_that_defined.get(&id).copied().unwrap_or(ExpnId::root()) }; - providers.in_scope_traits_map = - |tcx, id| tcx.hir_crate(()).owners[id].as_owner().map(|owner_info| &owner_info.trait_map); + providers.in_scope_traits_map = |tcx, id| { + tcx.hir_crate(()).owners[id.def_id].as_owner().map(|owner_info| &owner_info.trait_map) + }; } diff --git a/compiler/rustc_middle/src/middle/resolve_lifetime.rs b/compiler/rustc_middle/src/middle/resolve_lifetime.rs index 2a1a0bbe2ae..c3bf1c717d9 100644 --- a/compiler/rustc_middle/src/middle/resolve_lifetime.rs +++ b/compiler/rustc_middle/src/middle/resolve_lifetime.rs @@ -3,8 +3,8 @@ use crate::ty; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::ItemLocalId; +use rustc_hir::def_id::DefId; +use rustc_hir::{ItemLocalId, OwnerId}; use rustc_macros::HashStable; #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, HashStable)] @@ -49,7 +49,7 @@ pub enum ObjectLifetimeDefault { pub struct ResolveLifetimes { /// Maps from every use of a named (not anonymous) lifetime to a /// `Region` describing how that region is bound - pub defs: FxHashMap>, + pub defs: FxHashMap>, - pub late_bound_vars: FxHashMap>>, + pub late_bound_vars: FxHashMap>>, } diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 21ae121e1ce..fdda62719ee 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -182,7 +182,7 @@ impl<'tcx> MonoItem<'tcx> { match *self { MonoItem::Fn(Instance { def, .. }) => def.def_id().as_local(), MonoItem::Static(def_id) => def_id.as_local(), - MonoItem::GlobalAsm(item_id) => Some(item_id.def_id), + MonoItem::GlobalAsm(item_id) => Some(item_id.def_id.def_id), } .map(|def_id| tcx.def_span(def_id)) } @@ -373,7 +373,7 @@ impl<'tcx> CodegenUnit<'tcx> { } } MonoItem::Static(def_id) => def_id.as_local().map(Idx::index), - MonoItem::GlobalAsm(item_id) => Some(item_id.def_id.index()), + MonoItem::GlobalAsm(item_id) => Some(item_id.def_id.def_id.index()), }, item.symbol_name(tcx), ) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 121a5b9f492..eed44240f83 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -73,7 +73,7 @@ rustc_queries! { /// /// This can be conveniently accessed by methods on `tcx.hir()`. /// Avoid calling this query directly. - query hir_owner(key: LocalDefId) -> Option> { + query hir_owner(key: hir::OwnerId) -> Option> { desc { |tcx| "HIR owner of `{}`", tcx.def_path_str(key.to_def_id()) } } @@ -89,7 +89,7 @@ rustc_queries! { /// /// This can be conveniently accessed by methods on `tcx.hir()`. /// Avoid calling this query directly. - query hir_owner_parent(key: LocalDefId) -> hir::HirId { + query hir_owner_parent(key: hir::OwnerId) -> hir::HirId { desc { |tcx| "HIR parent of `{}`", tcx.def_path_str(key.to_def_id()) } } @@ -97,7 +97,7 @@ rustc_queries! { /// /// This can be conveniently accessed by methods on `tcx.hir()`. /// Avoid calling this query directly. - query hir_owner_nodes(key: LocalDefId) -> hir::MaybeOwner<&'tcx hir::OwnerNodes<'tcx>> { + query hir_owner_nodes(key: hir::OwnerId) -> hir::MaybeOwner<&'tcx hir::OwnerNodes<'tcx>> { desc { |tcx| "HIR owner items in `{}`", tcx.def_path_str(key.to_def_id()) } } @@ -105,7 +105,7 @@ rustc_queries! { /// /// This can be conveniently accessed by methods on `tcx.hir()`. /// Avoid calling this query directly. - query hir_attrs(key: LocalDefId) -> &'tcx hir::AttributeMap<'tcx> { + query hir_attrs(key: hir::OwnerId) -> &'tcx hir::AttributeMap<'tcx> { desc { |tcx| "HIR owner attributes in `{}`", tcx.def_path_str(key.to_def_id()) } } @@ -1404,7 +1404,7 @@ rustc_queries! { query specializes(_: (DefId, DefId)) -> bool { desc { "computing whether impls specialize one another" } } - query in_scope_traits_map(_: LocalDefId) + query in_scope_traits_map(_: hir::OwnerId) -> Option<&'tcx FxHashMap>> { desc { "traits in scope at a block" } } @@ -1419,7 +1419,7 @@ rustc_queries! { separate_provide_extern } - query check_well_formed(key: LocalDefId) -> () { + query check_well_formed(key: hir::OwnerId) -> () { desc { |tcx| "checking that `{}` is well-formed", tcx.def_path_str(key.to_def_id()) } } @@ -1586,7 +1586,7 @@ rustc_queries! { arena_cache desc { "resolving lifetimes" } } - query named_region_map(_: LocalDefId) -> + query named_region_map(_: hir::OwnerId) -> Option<&'tcx FxHashMap> { desc { "looking up a named region" } } @@ -1602,7 +1602,7 @@ rustc_queries! { desc { "looking up lifetime defaults for generic parameter `{}`", tcx.def_path_str(key) } separate_provide_extern } - query late_bound_vars_map(_: LocalDefId) + query late_bound_vars_map(_: hir::OwnerId) -> Option<&'tcx FxHashMap>> { desc { "looking up late bound vars" } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 8c44f4a98df..69bb9bb6fe0 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -40,6 +40,7 @@ use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE}; use rustc_hir::definitions::Definitions; +use rustc_hir::hir_id::OwnerId; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{ @@ -289,7 +290,7 @@ pub struct CommonConsts<'tcx> { } pub struct LocalTableInContext<'a, V> { - hir_owner: LocalDefId, + hir_owner: OwnerId, data: &'a ItemLocalMap, } @@ -301,7 +302,7 @@ pub struct LocalTableInContext<'a, V> { /// would result in lookup errors, or worse, in silently wrong data being /// stored/returned. #[inline] -fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { +fn validate_hir_id_for_typeck_results(hir_owner: OwnerId, hir_id: hir::HirId) { if hir_id.owner != hir_owner { invalid_hir_id_for_typeck_results(hir_owner, hir_id); } @@ -309,7 +310,7 @@ fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) #[cold] #[inline(never)] -fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { +fn invalid_hir_id_for_typeck_results(hir_owner: OwnerId, hir_id: hir::HirId) { ty::tls::with(|tcx| { bug!( "node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}", @@ -345,7 +346,7 @@ impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { } pub struct LocalTableInContextMut<'a, V> { - hir_owner: LocalDefId, + hir_owner: OwnerId, data: &'a mut ItemLocalMap, } @@ -417,7 +418,7 @@ pub struct GeneratorDiagnosticData<'tcx> { #[derive(TyEncodable, TyDecodable, Debug, HashStable)] pub struct TypeckResults<'tcx> { /// The `HirId::owner` all `ItemLocalId`s in this table are relative to. - pub hir_owner: LocalDefId, + pub hir_owner: OwnerId, /// Resolved definitions for `::X` associated paths and /// method calls, including those of overloaded operators. @@ -592,7 +593,7 @@ pub struct TypeckResults<'tcx> { } impl<'tcx> TypeckResults<'tcx> { - pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { + pub fn new(hir_owner: OwnerId) -> TypeckResults<'tcx> { TypeckResults { hir_owner, type_dependent_defs: Default::default(), @@ -1726,7 +1727,7 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn local_visibility(self, def_id: LocalDefId) -> Visibility { - self.visibility(def_id.to_def_id()).expect_local() + self.visibility(def_id).expect_local() } } @@ -2907,7 +2908,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn is_late_bound(self, id: HirId) -> bool { - self.is_late_bound_map(id.owner).map_or(false, |set| { + self.is_late_bound_map(id.owner.def_id).map_or(false, |set| { let def_id = self.hir().local_def_id(id); set.contains(&def_id) }) diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 01e1e97b21a..52f16ad88f6 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -861,7 +861,7 @@ fn foo(&self) -> Self::T { String::new() } // When `body_owner` is an `impl` or `trait` item, look in its associated types for // `expected` and point at it. let parent_id = self.hir().get_parent_item(hir_id); - let item = self.hir().find_by_def_id(parent_id); + let item = self.hir().find_by_def_id(parent_id.def_id); debug!("expected_projection parent item {:?}", item); match item { Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => { diff --git a/compiler/rustc_middle/src/ty/query.rs b/compiler/rustc_middle/src/ty/query.rs index 00da260b1dc..169da348a29 100644 --- a/compiler/rustc_middle/src/ty/query.rs +++ b/compiler/rustc_middle/src/ty/query.rs @@ -44,6 +44,7 @@ use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId}; +use rustc_hir::hir_id::OwnerId; use rustc_hir::lang_items::{LangItem, LanguageItems}; use rustc_hir::{Crate, ItemLocalId, TraitCandidate}; use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec}; @@ -336,7 +337,7 @@ macro_rules! define_callbacks { rustc_query_append! { define_callbacks! } mod sealed { - use super::{DefId, LocalDefId}; + use super::{DefId, LocalDefId, OwnerId}; /// An analogue of the `Into` trait that's intended only for query parameters. /// @@ -366,6 +367,13 @@ mod sealed { self.to_def_id() } } + + impl IntoQueryParam for OwnerId { + #[inline(always)] + fn into_query_param(self) -> DefId { + self.to_def_id() + } + } } use sealed::IntoQueryParam; diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index f1a25a60d52..5cd7a7f760f 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1246,7 +1246,7 @@ impl<'v> RootCollector<'_, 'v> { } } DefKind::Fn => { - self.push_if_root(id.def_id); + self.push_if_root(id.def_id.def_id); } _ => {} } @@ -1254,7 +1254,7 @@ impl<'v> RootCollector<'_, 'v> { fn process_impl_item(&mut self, id: hir::ImplItemId) { if matches!(self.tcx.def_kind(id.def_id), DefKind::AssocFn) { - self.push_if_root(id.def_id); + self.push_if_root(id.def_id.def_id); } } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index f112f1274b8..a21521ff68b 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -11,9 +11,11 @@ use rustc_errors::{fluent, struct_span_err, 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,7 +37,7 @@ pub(crate) fn target_from_impl_item<'tcx>( match impl_item.kind { hir::ImplItemKind::Const(..) => Target::AssocConst, hir::ImplItemKind::Fn(..) => { - let parent_def_id = tcx.hir().get_parent_item(impl_item.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(), @@ -640,7 +642,7 @@ impl CheckAttrVisitor<'_> { let span = meta.span(); if let Some(location) = match target { Target::AssocTy => { - let parent_def_id = self.tcx.hir().get_parent_item(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") @@ -649,7 +651,7 @@ impl CheckAttrVisitor<'_> { } } Target::AssocConst => { - let parent_def_id = self.tcx.hir().get_parent_item(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"; @@ -878,7 +880,7 @@ impl CheckAttrVisitor<'_> { 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 + && 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, '!'); diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 57f7c379d04..e9d71bc93ac 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -317,7 +317,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.def_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 +374,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,7 +528,7 @@ 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.def_id.def_id); } match tcx.def_kind(id.def_id) { @@ -554,7 +554,7 @@ fn check_item<'tcx>( let of_trait = tcx.impl_trait_ref(id.def_id); if of_trait.is_some() { - worklist.push(id.def_id); + worklist.push(id.def_id.def_id); } // get DefIds from another query @@ -577,12 +577,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.def_id.def_id); } } DefKind::GlobalAsm => { // global_asm! is always live. - worklist.push(id.def_id); + worklist.push(id.def_id.def_id); } _ => {} } @@ -595,7 +595,7 @@ fn check_trait_item<'tcx>(tcx: TyCtxt<'tcx>, worklist: &mut Vec, 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.def_id.def_id); } } } @@ -608,7 +608,7 @@ fn check_foreign_item<'tcx>( if matches!(tcx.def_kind(id.def_id), DefKind::Static(_) | DefKind::Fn) && has_allow_dead_code_or_lang_attr(tcx, id.hir_id()) { - worklist.push(id.def_id); + worklist.push(id.def_id.def_id); } } @@ -871,13 +871,13 @@ 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.def_id.def_id) { + let parent = tcx.local_parent(item.def_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.def_id.def_id); continue; } @@ -926,16 +926,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.def_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.def_id.def_id); } for foreign_item in module_items.foreign_items() { - visitor.check_definition(foreign_item.def_id); + visitor.check_definition(foreign_item.def_id.def_id); } // We do not warn trait items. diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index e6b69d8986c..e428d9293db 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -74,19 +74,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.def_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.def_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.def_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.def_id.def_id); } diagnostic_items diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index cd10170d3ba..eec37d19a88 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -82,7 +82,7 @@ fn err_if_attr_found(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol, details: } 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.def_id.def_id) == Some(CRATE_DEF_ID); match entry_point_type(ctxt, id, at_root) { EntryPointType::None => { @@ -99,7 +99,7 @@ fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) { } 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.def_id.def_id, ctxt.tcx.def_span(id.def_id))); } else { struct_span_err!( ctxt.tcx.sess, @@ -118,11 +118,11 @@ fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) { EntryPointType::Start => { err_if_attr_found(ctxt, id, sym::unix_sigpipe, "can only be used on `fn main()`"); 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.def_id.def_id, ctxt.tcx.def_span(id.def_id))); } else { struct_span_err!( ctxt.tcx.sess, - ctxt.tcx.def_span(id.def_id.to_def_id()), + ctxt.tcx.def_span(id.def_id), E0138, "multiple `start` functions" ) diff --git a/compiler/rustc_passes/src/hir_id_validator.rs b/compiler/rustc_passes/src/hir_id_validator.rs index 3bb8c0bb48c..3ee8c8bcb1d 100644 --- a/compiler/rustc_passes/src/hir_id_validator.rs +++ b/compiler/rustc_passes/src/hir_id_validator.rs @@ -1,6 +1,5 @@ use rustc_data_structures::sync::Lock; use rustc_hir as hir; -use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_hir::intravisit; use rustc_hir::{HirId, ItemLocalId}; use rustc_index::bit_set::GrowableBitSet; @@ -42,7 +41,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) { struct HirIdValidator<'a, 'hir> { hir_map: Map<'hir>, - owner: Option, + owner: Option, hir_ids_seen: GrowableBitSet, errors: &'a Lock>, } @@ -63,12 +62,12 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> { self.errors.lock().push(f()); } - fn check)>(&mut self, owner: LocalDefId, walk: F) { + fn check)>(&mut self, owner: hir::OwnerId, walk: F) { assert!(self.owner.is_none()); self.owner = Some(owner); walk(self); - if owner == CRATE_DEF_ID { + if owner == hir::CRATE_OWNER_ID { return; } @@ -97,14 +96,14 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> { missing_items.push(format!( "[local_id: {}, owner: {}]", local_id, - self.hir_map.def_path(owner).to_string_no_crate_verbose() + self.hir_map.def_path(owner.def_id).to_string_no_crate_verbose() )); } self.error(|| { format!( "ItemLocalIds not assigned densely in {}. \ Max ItemLocalId = {}, missing IDs = {:#?}; seens IDs = {:#?}", - self.hir_map.def_path(owner).to_string_no_crate_verbose(), + self.hir_map.def_path(owner.def_id).to_string_no_crate_verbose(), max, missing_items, self.hir_ids_seen @@ -138,8 +137,8 @@ impl<'a, 'hir> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> { format!( "HirIdValidator: The recorded owner of {} is {} instead of {}", self.hir_map.node_to_string(hir_id), - self.hir_map.def_path(hir_id.owner).to_string_no_crate_verbose(), - self.hir_map.def_path(owner).to_string_no_crate_verbose() + self.hir_map.def_path(hir_id.owner.def_id).to_string_no_crate_verbose(), + self.hir_map.def_path(owner.def_id).to_string_no_crate_verbose() ) }); } diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index fd03f657111..46c4a702fde 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -16,7 +16,7 @@ pub fn test_layout(tcx: TyCtxt<'_>) { DefKind::TyAlias | DefKind::Enum | DefKind::Struct | DefKind::Union ) { for attr in tcx.get_attrs(id.def_id.to_def_id(), sym::rustc_layout) { - dump_layout_of(tcx, id.def_id, attr); + dump_layout_of(tcx, id.def_id.def_id, attr); } } } diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index 75244124e20..16055641aca 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -153,7 +153,7 @@ impl<'tcx> ReachableContext<'tcx> { hir::ImplItemKind::Fn(..) => { let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); let impl_did = self.tcx.hir().get_parent_item(hir_id); - method_might_be_inlined(self.tcx, impl_item, impl_did) + method_might_be_inlined(self.tcx, impl_item, impl_did.def_id) } hir::ImplItemKind::TyAlias(_) => false, }, @@ -305,8 +305,8 @@ fn check_item<'tcx>( worklist: &mut Vec, access_levels: &privacy::AccessLevels, ) { - if has_custom_linkage(tcx, id.def_id) { - worklist.push(id.def_id); + if has_custom_linkage(tcx, id.def_id.def_id) { + worklist.push(id.def_id.def_id); } if !matches!(tcx.def_kind(id.def_id), DefKind::Impl) { @@ -318,8 +318,8 @@ fn check_item<'tcx>( if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), ref items, .. }) = item.kind { - if !access_levels.is_reachable(item.def_id) { - worklist.extend(items.iter().map(|ii_ref| ii_ref.id.def_id)); + if !access_levels.is_reachable(item.def_id.def_id) { + worklist.extend(items.iter().map(|ii_ref| ii_ref.id.def_id.def_id)); let Res::Def(DefKind::Trait, trait_def_id) = trait_ref.path.res else { unreachable!(); @@ -403,8 +403,8 @@ fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> FxHashSet { } for id in crate_items.impl_items() { - if has_custom_linkage(tcx, id.def_id) { - reachable_context.worklist.push(id.def_id); + if has_custom_linkage(tcx, id.def_id.def_id) { + reachable_context.worklist.push(id.def_id.def_id); } } } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 3f23b027aef..e50beb27d2a 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -385,7 +385,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } self.annotate( - i.def_id, + i.def_id.def_id, i.span, fn_sig, kind, @@ -404,7 +404,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { }; self.annotate( - ti.def_id, + ti.def_id.def_id, ti.span, fn_sig, AnnotationKind::Required, @@ -427,7 +427,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { }; self.annotate( - ii.def_id, + ii.def_id.def_id, ii.span, fn_sig, kind, @@ -485,7 +485,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { self.annotate( - i.def_id, + i.def_id.def_id, i.span, None, AnnotationKind::Required, @@ -573,25 +573,25 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) | hir::ItemKind::ForeignMod { .. } ) { - self.check_missing_stability(i.def_id, i.span); + self.check_missing_stability(i.def_id.def_id, i.span); } // Ensure stable `const fn` have a const stability attribute. - self.check_missing_const_stability(i.def_id, i.span); + self.check_missing_const_stability(i.def_id.def_id, i.span); intravisit::walk_item(self, i) } fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { - self.check_missing_stability(ti.def_id, ti.span); + self.check_missing_stability(ti.def_id.def_id, ti.span); intravisit::walk_trait_item(self, ti); } fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id()); if self.tcx.impl_trait_ref(impl_def_id).is_none() { - self.check_missing_stability(ii.def_id, ii.span); - self.check_missing_const_stability(ii.def_id, ii.span); + self.check_missing_stability(ii.def_id.def_id, ii.span); + self.check_missing_const_stability(ii.def_id.def_id, ii.span); } intravisit::walk_impl_item(self, ii); } @@ -610,7 +610,7 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { } fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { - self.check_missing_stability(i.def_id, i.span); + self.check_missing_stability(i.def_id.def_id, i.span); intravisit::walk_foreign_item(self, i); } // Note that we don't need to `check_missing_stability` for default generic parameters, @@ -716,7 +716,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { return; } - let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id) else { + let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id.def_id) else { return; }; let def_id = cnum.as_def_id(); @@ -869,7 +869,7 @@ fn is_unstable_reexport<'tcx>(tcx: TyCtxt<'tcx>, id: hir::HirId) -> bool { } // If this is a path that isn't a use, we don't need to do anything special - if !matches!(tcx.hir().item(hir::ItemId { def_id }).kind, ItemKind::Use(..)) { + if !matches!(tcx.hir().expect_item(def_id).kind, ItemKind::Use(..)) { return false; } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 8f5ee51e6cf..72867447250 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -506,8 +506,8 @@ impl<'tcx> EmbargoVisitor<'tcx> { let module = self.tcx.hir().get_module(module_def_id).0; for item_id in module.item_ids { let def_kind = self.tcx.def_kind(item_id.def_id); - let vis = self.tcx.local_visibility(item_id.def_id); - self.update_macro_reachable_def(item_id.def_id, def_kind, vis, defining_mod); + let vis = self.tcx.local_visibility(item_id.def_id.def_id); + self.update_macro_reachable_def(item_id.def_id.def_id, def_kind, vis, defining_mod); } if let Some(exports) = self.tcx.module_reexports(module_def_id) { for export in exports { @@ -627,11 +627,14 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { let item_level = match item.kind { hir::ItemKind::Impl { .. } => { - let impl_level = - Option::::of_impl(item.def_id, self.tcx, &self.access_levels); - self.update(item.def_id, impl_level) + let impl_level = Option::::of_impl( + item.def_id.def_id, + self.tcx, + &self.access_levels, + ); + self.update(item.def_id.def_id, impl_level) } - _ => self.get(item.def_id), + _ => self.get(item.def_id.def_id), }; // Update levels of nested things. @@ -652,13 +655,13 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { if impl_.of_trait.is_some() || self.tcx.visibility(impl_item_ref.id.def_id).is_public() { - self.update(impl_item_ref.id.def_id, item_level); + self.update(impl_item_ref.id.def_id.def_id, item_level); } } } hir::ItemKind::Trait(.., trait_item_refs) => { for trait_item_ref in trait_item_refs { - self.update(trait_item_ref.id.def_id, item_level); + self.update(trait_item_ref.id.def_id.def_id, item_level); } } hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => { @@ -674,12 +677,12 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { } } hir::ItemKind::Macro(ref macro_def, _) => { - self.update_reachability_from_macro(item.def_id, macro_def); + self.update_reachability_from_macro(item.def_id.def_id, macro_def); } hir::ItemKind::ForeignMod { items, .. } => { for foreign_item in items { if self.tcx.visibility(foreign_item.id.def_id).is_public() { - self.update(foreign_item.id.def_id, item_level); + self.update(foreign_item.id.def_id.def_id, item_level); } } } @@ -717,7 +720,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { // reachable if they are returned via `impl Trait`, even from private functions. let exist_level = cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait)); - self.reach(item.def_id, exist_level).generics().predicates().ty(); + self.reach(item.def_id.def_id, exist_level).generics().predicates().ty(); } } // Visit everything. @@ -726,16 +729,16 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { | hir::ItemKind::Fn(..) | hir::ItemKind::TyAlias(..) => { if item_level.is_some() { - self.reach(item.def_id, item_level).generics().predicates().ty(); + self.reach(item.def_id.def_id, item_level).generics().predicates().ty(); } } hir::ItemKind::Trait(.., trait_item_refs) => { if item_level.is_some() { - self.reach(item.def_id, item_level).generics().predicates(); + self.reach(item.def_id.def_id, item_level).generics().predicates(); for trait_item_ref in trait_item_refs { let tcx = self.tcx; - let mut reach = self.reach(trait_item_ref.id.def_id, item_level); + let mut reach = self.reach(trait_item_ref.id.def_id.def_id, item_level); reach.generics().predicates(); if trait_item_ref.kind == AssocItemKind::Type @@ -750,18 +753,22 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { } hir::ItemKind::TraitAlias(..) => { if item_level.is_some() { - self.reach(item.def_id, item_level).generics().predicates(); + self.reach(item.def_id.def_id, item_level).generics().predicates(); } } // Visit everything except for private impl items. hir::ItemKind::Impl(ref impl_) => { if item_level.is_some() { - self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref(); + self.reach(item.def_id.def_id, item_level) + .generics() + .predicates() + .ty() + .trait_ref(); for impl_item_ref in impl_.items { - let impl_item_level = self.get(impl_item_ref.id.def_id); + let impl_item_level = self.get(impl_item_ref.id.def_id.def_id); if impl_item_level.is_some() { - self.reach(impl_item_ref.id.def_id, impl_item_level) + self.reach(impl_item_ref.id.def_id.def_id, impl_item_level) .generics() .predicates() .ty(); @@ -773,7 +780,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { // Visit everything, but enum variants have their own levels. hir::ItemKind::Enum(ref def, _) => { if item_level.is_some() { - self.reach(item.def_id, item_level).generics().predicates(); + self.reach(item.def_id.def_id, item_level).generics().predicates(); } for variant in def.variants { let variant_level = self.get(self.tcx.hir().local_def_id(variant.id)); @@ -784,13 +791,13 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { } // Corner case: if the variant is reachable, but its // enum is not, make the enum reachable as well. - self.reach(item.def_id, variant_level).ty(); + self.reach(item.def_id.def_id, variant_level).ty(); } if let Some(hir_id) = variant.data.ctor_hir_id() { let ctor_def_id = self.tcx.hir().local_def_id(hir_id); let ctor_level = self.get(ctor_def_id); if ctor_level.is_some() { - self.reach(item.def_id, ctor_level).ty(); + self.reach(item.def_id.def_id, ctor_level).ty(); } } } @@ -798,9 +805,9 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { // Visit everything, but foreign items have their own levels. hir::ItemKind::ForeignMod { items, .. } => { for foreign_item in items { - let foreign_item_level = self.get(foreign_item.id.def_id); + let foreign_item_level = self.get(foreign_item.id.def_id.def_id); if foreign_item_level.is_some() { - self.reach(foreign_item.id.def_id, foreign_item_level) + self.reach(foreign_item.id.def_id.def_id, foreign_item_level) .generics() .predicates() .ty(); @@ -810,7 +817,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { // Visit everything except for private fields. hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { if item_level.is_some() { - self.reach(item.def_id, item_level).generics().predicates(); + self.reach(item.def_id.def_id, item_level).generics().predicates(); for field in struct_def.fields() { let def_id = self.tcx.hir().local_def_id(field.hir_id); let field_level = self.get(def_id); @@ -823,7 +830,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { let ctor_def_id = self.tcx.hir().local_def_id(hir_id); let ctor_level = self.get(ctor_def_id); if ctor_level.is_some() { - self.reach(item.def_id, ctor_level).ty(); + self.reach(item.def_id.def_id, ctor_level).ty(); } } } @@ -945,7 +952,7 @@ impl<'tcx, 'a> TestReachabilityVisitor<'tcx, 'a> { impl<'tcx, 'a> Visitor<'tcx> for TestReachabilityVisitor<'tcx, 'a> { fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - self.access_level_diagnostic(item.def_id); + self.access_level_diagnostic(item.def_id.def_id); match item.kind { hir::ItemKind::Enum(ref def, _) => { @@ -969,13 +976,13 @@ impl<'tcx, 'a> Visitor<'tcx> for TestReachabilityVisitor<'tcx, 'a> { } fn visit_trait_item(&mut self, item: &'tcx hir::TraitItem<'tcx>) { - self.access_level_diagnostic(item.def_id); + self.access_level_diagnostic(item.def_id.def_id); } fn visit_impl_item(&mut self, item: &'tcx hir::ImplItem<'tcx>) { - self.access_level_diagnostic(item.def_id); + self.access_level_diagnostic(item.def_id.def_id); } fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { - self.access_level_diagnostic(item.def_id); + self.access_level_diagnostic(item.def_id.def_id); } } @@ -1058,7 +1065,7 @@ impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { } fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - let orig_current_item = mem::replace(&mut self.current_item, item.def_id); + let orig_current_item = mem::replace(&mut self.current_item, item.def_id.def_id); intravisit::walk_item(self, item); self.current_item = orig_current_item; } @@ -1361,7 +1368,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { // Check types in item interfaces. fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - let orig_current_item = mem::replace(&mut self.current_item, item.def_id); + let orig_current_item = mem::replace(&mut self.current_item, item.def_id.def_id); let old_maybe_typeck_results = self.maybe_typeck_results.take(); intravisit::walk_item(self, item); self.maybe_typeck_results = old_maybe_typeck_results; @@ -1503,7 +1510,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { hir::ItemKind::ForeignMod { .. } => {} hir::ItemKind::Trait(.., bounds, _) => { - if !self.trait_is_public(item.def_id) { + if !self.trait_is_public(item.def_id.def_id) { return; } @@ -1564,7 +1571,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); match impl_item.kind { hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => { - self.access_levels.is_reachable(impl_item_ref.id.def_id) + self.access_levels.is_reachable(impl_item_ref.id.def_id.def_id) } hir::ImplItemKind::TyAlias(_) => false, } @@ -1584,7 +1591,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); match impl_item.kind { hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) - if self.item_is_public(impl_item.def_id) => + if self.item_is_public(impl_item.def_id.def_id) => { intravisit::walk_impl_item(self, impl_item) } @@ -1625,7 +1632,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { // methods will be visible as `Public::foo`. let mut found_pub_static = false; for impl_item_ref in impl_.items { - if self.access_levels.is_reachable(impl_item_ref.id.def_id) + if self.access_levels.is_reachable(impl_item_ref.id.def_id.def_id) || self.tcx.visibility(impl_item_ref.id.def_id).is_public() { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); @@ -1654,7 +1661,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { hir::ItemKind::TyAlias(..) => return, // Not at all public, so we don't care. - _ if !self.item_is_public(item.def_id) => { + _ if !self.item_is_public(item.def_id.def_id) => { return; } @@ -1685,7 +1692,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { - if self.access_levels.is_reachable(item.def_id) { + if self.access_levels.is_reachable(item.def_id.def_id) { intravisit::walk_foreign_item(self, item) } } @@ -1922,43 +1929,44 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx> { pub fn check_item(&mut self, id: ItemId) { let tcx = self.tcx; - let item_visibility = tcx.local_visibility(id.def_id); - let def_kind = tcx.def_kind(id.def_id); + let def_id = id.def_id.def_id; + let item_visibility = tcx.local_visibility(def_id); + let def_kind = tcx.def_kind(def_id); match def_kind { DefKind::Const | DefKind::Static(_) | DefKind::Fn | DefKind::TyAlias => { - self.check(id.def_id, item_visibility).generics().predicates().ty(); + self.check(def_id, item_visibility).generics().predicates().ty(); } DefKind::OpaqueTy => { // `ty()` for opaque types is the underlying type, // it's not a part of interface, so we skip it. - self.check(id.def_id, item_visibility).generics().bounds(); + self.check(def_id, item_visibility).generics().bounds(); } DefKind::Trait => { let item = tcx.hir().item(id); if let hir::ItemKind::Trait(.., trait_item_refs) = item.kind { - self.check(item.def_id, item_visibility).generics().predicates(); + self.check(item.def_id.def_id, item_visibility).generics().predicates(); for trait_item_ref in trait_item_refs { self.check_assoc_item( - trait_item_ref.id.def_id, + trait_item_ref.id.def_id.def_id, trait_item_ref.kind, item_visibility, ); if let AssocItemKind::Type = trait_item_ref.kind { - self.check(trait_item_ref.id.def_id, item_visibility).bounds(); + self.check(trait_item_ref.id.def_id.def_id, item_visibility).bounds(); } } } } DefKind::TraitAlias => { - self.check(id.def_id, item_visibility).generics().predicates(); + self.check(def_id, item_visibility).generics().predicates(); } DefKind::Enum => { let item = tcx.hir().item(id); if let hir::ItemKind::Enum(ref def, _) = item.kind { - self.check(item.def_id, item_visibility).generics().predicates(); + self.check(item.def_id.def_id, item_visibility).generics().predicates(); for variant in def.variants { for field in variant.data.fields() { @@ -1973,8 +1981,8 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx> { let item = tcx.hir().item(id); if let hir::ItemKind::ForeignMod { items, .. } = item.kind { for foreign_item in items { - let vis = tcx.local_visibility(foreign_item.id.def_id); - self.check(foreign_item.id.def_id, vis).generics().predicates().ty(); + let vis = tcx.local_visibility(foreign_item.id.def_id.def_id); + self.check(foreign_item.id.def_id.def_id, vis).generics().predicates().ty(); } } } @@ -1984,7 +1992,7 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx> { if let hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) = item.kind { - self.check(item.def_id, item_visibility).generics().predicates(); + self.check(item.def_id.def_id, item_visibility).generics().predicates(); for field in struct_def.fields() { let def_id = tcx.hir().local_def_id(field.hir_id); @@ -2000,20 +2008,21 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx> { DefKind::Impl => { let item = tcx.hir().item(id); if let hir::ItemKind::Impl(ref impl_) = item.kind { - let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default()); + let impl_vis = + ty::Visibility::of_impl(item.def_id.def_id, tcx, &Default::default()); // check that private components do not appear in the generics or predicates of inherent impls // this check is intentionally NOT performed for impls of traits, per #90586 if impl_.of_trait.is_none() { - self.check(item.def_id, impl_vis).generics().predicates(); + self.check(item.def_id.def_id, impl_vis).generics().predicates(); } for impl_item_ref in impl_.items { let impl_item_vis = if impl_.of_trait.is_none() { - min(tcx.local_visibility(impl_item_ref.id.def_id), impl_vis, tcx) + min(tcx.local_visibility(impl_item_ref.id.def_id.def_id), impl_vis, tcx) } else { impl_vis }; self.check_assoc_item( - impl_item_ref.id.def_id, + impl_item_ref.id.def_id.def_id, impl_item_ref.kind, impl_item_vis, ); @@ -2061,7 +2070,7 @@ fn local_visibility(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Visibility { // Visibilities of trait impl items are inherited from their traits // and are not filled in resolve. Node::ImplItem(impl_item) => { - match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id)) { + match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id).def_id) { Node::Item(hir::Item { kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }), .. diff --git a/compiler/rustc_query_impl/src/keys.rs b/compiler/rustc_query_impl/src/keys.rs index 2bb7a240faa..47762440e29 100644 --- a/compiler/rustc_query_impl/src/keys.rs +++ b/compiler/rustc_query_impl/src/keys.rs @@ -1,6 +1,7 @@ //! Defines the set of legal keys that can be used in queries. use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::hir_id::OwnerId; use rustc_middle::infer::canonical::Canonical; use rustc_middle::mir; use rustc_middle::traits; @@ -104,6 +105,19 @@ impl Key for CrateNum { } } +impl Key for OwnerId { + #[inline(always)] + fn query_crate_is_local(&self) -> bool { + true + } + fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + self.to_def_id().default_span(tcx) + } + fn key_as_def_id(&self) -> Option { + Some(self.to_def_id()) + } +} + impl Key for LocalDefId { #[inline(always)] fn query_crate_is_local(&self) -> bool { diff --git a/compiler/rustc_query_system/src/ich/hcx.rs b/compiler/rustc_query_system/src/ich/hcx.rs index a09b8ca30e1..8140c243453 100644 --- a/compiler/rustc_query_system/src/ich/hcx.rs +++ b/compiler/rustc_query_system/src/ich/hcx.rs @@ -41,7 +41,10 @@ pub struct StableHashingContext<'a> { pub(super) enum BodyResolver<'tcx> { Forbidden, Ignore, - Traverse { owner: LocalDefId, bodies: &'tcx SortedMap> }, + Traverse { + owner: hir::OwnerId, + bodies: &'tcx SortedMap>, + }, } impl<'a> StableHashingContext<'a> { @@ -103,7 +106,7 @@ impl<'a> StableHashingContext<'a> { #[inline] pub fn with_hir_bodies( &mut self, - owner: LocalDefId, + owner: hir::OwnerId, bodies: &SortedMap>, f: impl FnOnce(&mut StableHashingContext<'_>), ) { diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index 4d970461712..9fb1af20ac9 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -339,24 +339,25 @@ fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetime /// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner /// other than the trait itself (like the trait methods or associated types), then we just use the regular /// `resolve_lifetimes`. -fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes { - let item_id = item_for(tcx, def_id); - if item_id == def_id { - let item = tcx.hir().item(hir::ItemId { def_id: item_id }); +fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: hir::OwnerId) -> &'tcx ResolveLifetimes { + let item_id = item_for(tcx, def_id.def_id); + let local_def_id = item_id.def_id.def_id; + if item_id.def_id == def_id { + let item = tcx.hir().item(item_id); match item.kind { - hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id), - _ => tcx.resolve_lifetimes(item_id), + hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(local_def_id), + _ => tcx.resolve_lifetimes(local_def_id), } } else { - tcx.resolve_lifetimes(item_id) + tcx.resolve_lifetimes(local_def_id) } } /// Finds the `Item` that contains the given `LocalDefId` -fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId { +fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> hir::ItemId { match tcx.hir().find_by_def_id(local_def_id) { Some(Node::Item(item)) => { - return item.def_id; + return item.item_id(); } _ => {} } @@ -366,7 +367,7 @@ fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId { loop { let node = parent_iter.next().map(|n| n.1); match node { - Some(hir::Node::Item(item)) => break item.def_id, + Some(hir::Node::Item(item)) => break item.item_id(), Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."), _ => {} } @@ -566,13 +567,12 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // their owner, we can keep going until we find the Item that owns that. We then // conservatively add all resolved lifetimes. Otherwise we run into problems in // cases like `type Foo<'a> = impl Bar`. - for (_hir_id, node) in - self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id)) - { + for (_hir_id, node) in self.tcx.hir().parent_iter(item.def_id.into()) { match node { hir::Node::Item(parent_item) => { - let resolved_lifetimes: &ResolveLifetimes = - self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id)); + let resolved_lifetimes: &ResolveLifetimes = self.tcx.resolve_lifetimes( + item_for(self.tcx, parent_item.def_id.def_id).def_id.def_id, + ); // We need to add *all* deps, since opaque tys may want them from *us* for (&owner, defs) in resolved_lifetimes.defs.iter() { defs.iter().for_each(|(&local_id, region)| { @@ -1315,7 +1315,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // regular fns. if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin && let hir::LifetimeName::Param(_, hir::ParamName::Fresh) = lifetime_ref.name - && let hir::IsAsync::NotAsync = self.tcx.asyncness(lifetime_ref.hir_id.owner) + && let hir::IsAsync::NotAsync = self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id) && !self.tcx.features().anonymous_lifetime_in_impl_trait { rustc_session::parse::feature_err( diff --git a/compiler/rustc_save_analysis/src/dump_visitor.rs b/compiler/rustc_save_analysis/src/dump_visitor.rs index 8bd42d8d216..adbc119387d 100644 --- a/compiler/rustc_save_analysis/src/dump_visitor.rs +++ b/compiler/rustc_save_analysis/src/dump_visitor.rs @@ -345,14 +345,14 @@ impl<'tcx> DumpVisitor<'tcx> { body: hir::BodyId, ) { let map = self.tcx.hir(); - self.nest_typeck_results(item.def_id, |v| { + self.nest_typeck_results(item.def_id.def_id, |v| { let body = map.body(body); if let Some(fn_data) = v.save_ctxt.get_item_data(item) { down_cast_data!(fn_data, DefData, item.span); v.process_formals(body.params, &fn_data.qualname); v.process_generic_params(ty_params, &fn_data.qualname, item.hir_id()); - v.dumper.dump_def(&access_from!(v.save_ctxt, item.def_id), fn_data); + v.dumper.dump_def(&access_from!(v.save_ctxt, item.def_id.def_id), fn_data); } for arg in decl.inputs { @@ -373,10 +373,10 @@ impl<'tcx> DumpVisitor<'tcx> { typ: &'tcx hir::Ty<'tcx>, expr: &'tcx hir::Expr<'tcx>, ) { - self.nest_typeck_results(item.def_id, |v| { + self.nest_typeck_results(item.def_id.def_id, |v| { if let Some(var_data) = v.save_ctxt.get_item_data(item) { down_cast_data!(var_data, DefData, item.span); - v.dumper.dump_def(&access_from!(v.save_ctxt, item.def_id), var_data); + v.dumper.dump_def(&access_from!(v.save_ctxt, item.def_id.def_id), var_data); } v.visit_ty(&typ); v.visit_expr(expr); @@ -473,7 +473,7 @@ impl<'tcx> DumpVisitor<'tcx> { let span = self.span_from_span(item.ident.span); let attrs = self.tcx.hir().attrs(item.hir_id()); self.dumper.dump_def( - &access_from!(self.save_ctxt, item.def_id), + &access_from!(self.save_ctxt, item.def_id.def_id), Def { kind, id: id_from_def_id(item.def_id.to_def_id()), @@ -491,7 +491,7 @@ impl<'tcx> DumpVisitor<'tcx> { ); } - self.nest_typeck_results(item.def_id, |v| { + self.nest_typeck_results(item.def_id.def_id, |v| { for field in def.fields() { v.process_struct_field_def(field, item.hir_id()); v.visit_ty(&field.ty); @@ -513,7 +513,7 @@ impl<'tcx> DumpVisitor<'tcx> { }; down_cast_data!(enum_data, DefData, item.span); - let access = access_from!(self.save_ctxt, item.def_id); + let access = access_from!(self.save_ctxt, item.def_id.def_id); for variant in enum_definition.variants { let name = variant.ident.name.to_string(); @@ -612,7 +612,7 @@ impl<'tcx> DumpVisitor<'tcx> { } let map = self.tcx.hir(); - self.nest_typeck_results(item.def_id, |v| { + self.nest_typeck_results(item.def_id.def_id, |v| { v.visit_ty(&impl_.self_ty); if let Some(trait_ref) = &impl_.of_trait { v.process_path(trait_ref.hir_ref_id, &hir::QPath::Resolved(None, &trait_ref.path)); @@ -648,7 +648,7 @@ impl<'tcx> DumpVisitor<'tcx> { methods.iter().map(|i| id_from_def_id(i.id.def_id.to_def_id())).collect(); let attrs = self.tcx.hir().attrs(item.hir_id()); self.dumper.dump_def( - &access_from!(self.save_ctxt, item.def_id), + &access_from!(self.save_ctxt, item.def_id.def_id), Def { kind: DefKind::Trait, id, @@ -710,7 +710,7 @@ impl<'tcx> DumpVisitor<'tcx> { fn process_mod(&mut self, item: &'tcx hir::Item<'tcx>) { if let Some(mod_data) = self.save_ctxt.get_item_data(item) { down_cast_data!(mod_data, DefData, item.span); - self.dumper.dump_def(&access_from!(self.save_ctxt, item.def_id), mod_data); + self.dumper.dump_def(&access_from!(self.save_ctxt, item.def_id.def_id), mod_data); } } @@ -980,7 +980,7 @@ impl<'tcx> DumpVisitor<'tcx> { let body = body.map(|b| self.tcx.hir().body(b).value); let attrs = self.tcx.hir().attrs(trait_item.hir_id()); self.process_assoc_const( - trait_item.def_id, + trait_item.def_id.def_id, trait_item.ident, &ty, body, @@ -994,7 +994,7 @@ impl<'tcx> DumpVisitor<'tcx> { self.process_method( sig, body, - trait_item.def_id, + trait_item.def_id.def_id, trait_item.ident, &trait_item.generics, trait_item.span, @@ -1050,7 +1050,7 @@ impl<'tcx> DumpVisitor<'tcx> { let body = self.tcx.hir().body(body); let attrs = self.tcx.hir().attrs(impl_item.hir_id()); self.process_assoc_const( - impl_item.def_id, + impl_item.def_id.def_id, impl_item.ident, &ty, Some(&body.value), @@ -1062,7 +1062,7 @@ impl<'tcx> DumpVisitor<'tcx> { self.process_method( sig, Some(body), - impl_item.def_id, + impl_item.def_id.def_id, impl_item.ident, &impl_item.generics, impl_item.span, @@ -1136,10 +1136,10 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { hir::ItemKind::Use(path, hir::UseKind::Single) => { let sub_span = path.segments.last().unwrap().ident.span; if !self.span.filter_generated(sub_span) { - let access = access_from!(self.save_ctxt, item.def_id); + let access = access_from!(self.save_ctxt, item.def_id.def_id); let ref_id = self.lookup_def_id(item.hir_id()).map(id_from_def_id); let span = self.span_from_span(sub_span); - let parent = self.save_ctxt.tcx.local_parent(item.def_id); + let parent = self.save_ctxt.tcx.local_parent(item.def_id.def_id); self.dumper.import( &access, Import { @@ -1157,16 +1157,16 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } hir::ItemKind::Use(path, hir::UseKind::Glob) => { // Make a comma-separated list of names of imported modules. - let names = self.tcx.names_imported_by_glob_use(item.def_id); + let names = self.tcx.names_imported_by_glob_use(item.def_id.def_id); let names: Vec<_> = names.iter().map(|n| n.to_string()).collect(); // Otherwise it's a span with wrong macro expansion info, which // we don't want to track anyway, since it's probably macro-internal `use` if let Some(sub_span) = self.span.sub_span_of_star(item.span) { if !self.span.filter_generated(item.span) { - let access = access_from!(self.save_ctxt, item.def_id); + let access = access_from!(self.save_ctxt, item.def_id.def_id); let span = self.span_from_span(sub_span); - let parent = self.save_ctxt.tcx.local_parent(item.def_id); + let parent = self.save_ctxt.tcx.local_parent(item.def_id.def_id); self.dumper.import( &access, Import { @@ -1187,7 +1187,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { let name_span = item.ident.span; if !self.span.filter_generated(name_span) { let span = self.span_from_span(name_span); - let parent = self.save_ctxt.tcx.local_parent(item.def_id); + let parent = self.save_ctxt.tcx.local_parent(item.def_id.def_id); self.dumper.import( &Access { public: false, reachable: false }, Import { @@ -1235,7 +1235,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { let attrs = self.tcx.hir().attrs(item.hir_id()); self.dumper.dump_def( - &access_from!(self.save_ctxt, item.def_id), + &access_from!(self.save_ctxt, item.def_id.def_id), Def { kind: DefKind::Type, id, @@ -1323,7 +1323,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } hir::TyKind::OpaqueDef(item_id, _, _) => { let item = self.tcx.hir().item(item_id); - self.nest_typeck_results(item_id.def_id, |v| v.visit_item(item)); + self.nest_typeck_results(item_id.def_id.def_id, |v| v.visit_item(item)); } _ => intravisit::walk_ty(self, t), } @@ -1430,7 +1430,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { - let access = access_from!(self.save_ctxt, item.def_id); + let access = access_from!(self.save_ctxt, item.def_id.def_id); match item.kind { hir::ForeignItemKind::Fn(decl, _, ref generics) => { diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs index ce03c2a8ad0..1a3511a1dc8 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -622,7 +622,7 @@ impl<'tcx> SaveContext<'tcx> { hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => { // #75962: `self.typeck_results` may be different from the `hir_id`'s result. if self.tcx.has_typeck_results(hir_id.owner.to_def_id()) { - self.tcx.typeck(hir_id.owner).qpath_res(qpath, hir_id) + self.tcx.typeck(hir_id.owner.def_id).qpath_res(qpath, hir_id) } else { Res::Err } @@ -1041,7 +1041,7 @@ fn id_from_hir_id(id: hir::HirId, scx: &SaveContext<'_>) -> rls_data::Id { // crate (very unlikely to actually happen). rls_data::Id { krate: LOCAL_CRATE.as_u32(), - index: id.owner.local_def_index.as_u32() | id.local_id.as_u32().reverse_bits(), + index: id.owner.def_id.local_def_index.as_u32() | id.local_id.as_u32().reverse_bits(), } }) } diff --git a/compiler/rustc_symbol_mangling/src/test.rs b/compiler/rustc_symbol_mangling/src/test.rs index 9d89c9c52b2..c8c6fe2bf85 100644 --- a/compiler/rustc_symbol_mangling/src/test.rs +++ b/compiler/rustc_symbol_mangling/src/test.rs @@ -26,19 +26,19 @@ pub fn report_symbol_names(tcx: TyCtxt<'_>) { let crate_items = tcx.hir_crate_items(()); for id in crate_items.items() { - symbol_names.process_attrs(id.def_id); + symbol_names.process_attrs(id.def_id.def_id); } for id in crate_items.trait_items() { - symbol_names.process_attrs(id.def_id); + symbol_names.process_attrs(id.def_id.def_id); } for id in crate_items.impl_items() { - symbol_names.process_attrs(id.def_id); + symbol_names.process_attrs(id.def_id.def_id); } for id in crate_items.foreign_items() { - symbol_names.process_attrs(id.def_id); + symbol_names.process_attrs(id.def_id.def_id); } }) } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index d62b399c1b5..b0cabc6275f 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -1898,7 +1898,9 @@ impl<'a, 'tcx> InferCtxtPrivExt<'a, 'tcx> for InferCtxt<'a, 'tcx> { // FIXME(compiler-errors): This could be generalized, both to // be more granular, and probably look past other `#[fundamental]` // types, too. - self.tcx.visibility(def.did()).is_accessible_from(body_id.owner, self.tcx) + self.tcx + .visibility(def.did()) + .is_accessible_from(body_id.owner.def_id, self.tcx) } else { true } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index d90b77fc556..fff26547be0 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -659,7 +659,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { _ => {} } - hir_id = self.tcx.hir().local_def_id_to_hir_id(self.tcx.hir().get_parent_item(hir_id)); + hir_id = self.tcx.hir().get_parent_item(hir_id).into(); } } @@ -2712,7 +2712,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { let parent_id = hir.get_parent_item(arg_hir_id); let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results { Some(t) if t.hir_owner == parent_id => t, - _ => self.tcx.typeck(parent_id), + _ => self.tcx.typeck(parent_id.def_id), }; let expr = expr.peel_blocks(); let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()); diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index 515a73ead77..3e2553c425e 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -42,7 +42,7 @@ fn impl_item_implementor_ids(tcx: TyCtxt<'_>, impl_id: DefId) -> FxHashMap, def_id: DefId) -> ty::AssocItem { let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); let parent_def_id = tcx.hir().get_parent_item(id); - let parent_item = tcx.hir().expect_item(parent_def_id); + let parent_item = tcx.hir().expect_item(parent_def_id.def_id); match parent_item.kind { hir::ItemKind::Impl(ref impl_) => { if let Some(impl_item_ref) = diff --git a/compiler/rustc_typeck/src/astconv/mod.rs b/compiler/rustc_typeck/src/astconv/mod.rs index 5432fdbb5e8..2c06ac2e139 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -3003,7 +3003,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// Make sure that we are in the condition to suggest the blanket implementation. fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) { let tcx = self.tcx(); - let parent_id = tcx.hir().get_parent_item(self_ty.hir_id); + let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id; if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(hir::Impl { diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index 27329f8eab4..201927091a6 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -140,7 +140,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let Some(ret) = self .tcx .hir() - .find_by_def_id(self.body_id.owner) + .find_by_def_id(self.body_id.owner.def_id) .and_then(|owner| owner.fn_decl()) .map(|decl| decl.output.span()) else { return; }; @@ -495,7 +495,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .typeck_results .borrow() .liberated_fn_sigs() - .get(hir::HirId::make_owner(self.body_id.owner))?; + .get(hir::HirId::make_owner(self.body_id.owner.def_id))?; let substs = sig.output().walk().find_map(|arg| { if let ty::GenericArgKind::Type(ty) = arg.unpack() diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index d6fa74c8730..d82ee8f48c5 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -782,19 +782,19 @@ fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) { let _indenter = indenter(); match tcx.def_kind(id.def_id) { DefKind::Static(..) => { - tcx.ensure().typeck(id.def_id); - maybe_check_static_with_link_section(tcx, id.def_id); - check_static_inhabited(tcx, id.def_id); + tcx.ensure().typeck(id.def_id.def_id); + maybe_check_static_with_link_section(tcx, id.def_id.def_id); + check_static_inhabited(tcx, id.def_id.def_id); } DefKind::Const => { - tcx.ensure().typeck(id.def_id); + tcx.ensure().typeck(id.def_id.def_id); } DefKind::Enum => { let item = tcx.hir().item(id); let hir::ItemKind::Enum(ref enum_definition, _) = item.kind else { return; }; - check_enum(tcx, &enum_definition.variants, item.def_id); + check_enum(tcx, &enum_definition.variants, item.def_id.def_id); } DefKind::Fn => {} // entirely within check_item_body DefKind::Impl => { @@ -807,7 +807,7 @@ fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) { check_impl_items_against_trait( tcx, it.span, - it.def_id, + it.def_id.def_id, impl_trait_ref, &impl_.items, ); @@ -845,10 +845,10 @@ fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) { } } DefKind::Struct => { - check_struct(tcx, id.def_id); + check_struct(tcx, id.def_id.def_id); } DefKind::Union => { - check_union(tcx, id.def_id); + check_union(tcx, id.def_id.def_id); } DefKind::OpaqueTy => { let item = tcx.hir().item(id); @@ -861,7 +861,7 @@ fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) { // See https://github.com/rust-lang/rust/issues/75100 if !tcx.sess.opts.actually_rustdoc { let substs = InternalSubsts::identity_for_item(tcx, item.def_id.to_def_id()); - check_opaque(tcx, item.def_id, substs, &origin); + check_opaque(tcx, item.def_id.def_id, substs, &origin); } } DefKind::TyAlias => { @@ -888,7 +888,7 @@ fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, id: hir::ItemId) { } } else { for item in items { - let def_id = item.id.def_id; + let def_id = item.id.def_id.def_id; let generics = tcx.generics_of(def_id); let own_counts = generics.own_counts(); if generics.params.len() - own_counts.lifetimes != 0 { diff --git a/compiler/rustc_typeck/src/check/coercion.rs b/compiler/rustc_typeck/src/check/coercion.rs index def592c46c2..d738e563256 100644 --- a/compiler/rustc_typeck/src/check/coercion.rs +++ b/compiler/rustc_typeck/src/check/coercion.rs @@ -1683,7 +1683,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { expected, found, can_suggest, - fcx.tcx.hir().local_def_id_to_hir_id(fcx.tcx.hir().get_parent_item(id)), + fcx.tcx.hir().get_parent_item(id).into(), ); } if !pointing_at_return_type { @@ -1692,7 +1692,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { } let parent_id = fcx.tcx.hir().get_parent_item(id); - let parent_item = fcx.tcx.hir().get_by_def_id(parent_id); + let parent_item = fcx.tcx.hir().get_by_def_id(parent_id.def_id); if let (Some(expr), Some(_), Some((fn_decl, _, _))) = (expression, blk_id, fcx.get_node_fn_decl(parent_item)) @@ -1704,7 +1704,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { expected, found, id, - fcx.tcx.hir().local_def_id_to_hir_id(parent_id), + parent_id.into(), ); } diff --git a/compiler/rustc_typeck/src/check/demand.rs b/compiler/rustc_typeck/src/check/demand.rs index e1d55ff82cb..222082497ef 100644 --- a/compiler/rustc_typeck/src/check/demand.rs +++ b/compiler/rustc_typeck/src/check/demand.rs @@ -375,7 +375,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let field_is_local = sole_field.did.is_local(); let field_is_accessible = - sole_field.vis.is_accessible_from(expr.hir_id.owner, self.tcx) + sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx) // Skip suggestions for unstable public fields (for example `Pin::pointer`) && matches!(self.tcx.eval_stability(sole_field.did, None, expr.span, None), EvalResult::Allow | EvalResult::Unmarked); diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 23fadff3248..48a4f40780b 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -752,7 +752,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { kind: hir::ImplItemKind::Fn(..), span: encl_fn_span, .. - })) = self.tcx.hir().find_by_def_id(encl_item_id) + })) = self.tcx.hir().find_by_def_id(encl_item_id.def_id) { // We are inside a function body, so reporting "return statement // outside of function body" needs an explanation. @@ -761,7 +761,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If this didn't hold, we would not have to report an error in // the first place. - assert_ne!(encl_item_id, encl_body_owner_id); + assert_ne!(encl_item_id.def_id, encl_body_owner_id); let encl_body_id = self.tcx.hir().body_owned_by(encl_body_owner_id); let encl_body = self.tcx.hir().body(encl_body_id); @@ -2338,7 +2338,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::Adt(def, _) = output_ty.kind() && !def.is_enum() { def.non_enum_variant().fields.iter().any(|field| { field.ident(self.tcx) == ident - && field.vis.is_accessible_from(expr.hir_id.owner, self.tcx) + && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx) }) } else if let ty::Tuple(tys) = output_ty.kind() && let Ok(idx) = ident.as_str().parse::() diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index 311fcaadaa9..64e7fa1a42b 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -1543,7 +1543,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } fn parent_item_span(&self, id: hir::HirId) -> Option { - let node = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(id)); + let node = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(id).def_id); match node { Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => { @@ -1559,7 +1559,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Given a function block's `HirId`, returns its `FnDecl` if it exists, or `None` otherwise. fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident)> { - let parent = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(blk_id)); + let parent = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(blk_id).def_id); self.get_node_fn_decl(parent).map(|(fn_decl, ident, _)| (fn_decl, ident)) } diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index 2d459b2cc0e..0e77ed0a4fe 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -2077,7 +2077,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Colon, Nothing, } - let ast_generics = hir.get_generics(id.owner).unwrap(); + let ast_generics = hir.get_generics(id.owner.def_id).unwrap(); let (sp, mut introducer) = if let Some(span) = ast_generics.bounds_span_for_suggestions(def_id) { diff --git a/compiler/rustc_typeck/src/check/mod.rs b/compiler/rustc_typeck/src/check/mod.rs index 1a4c888a5a4..593a9776bde 100644 --- a/compiler/rustc_typeck/src/check/mod.rs +++ b/compiler/rustc_typeck/src/check/mod.rs @@ -519,7 +519,7 @@ fn get_owner_return_paths<'tcx>( def_id: LocalDefId, ) -> Option<(LocalDefId, ReturnsVisitor<'tcx>)> { let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); - let parent_id = tcx.hir().get_parent_item(hir_id); + let parent_id = tcx.hir().get_parent_item(hir_id).def_id; tcx.hir().find_by_def_id(parent_id).and_then(|node| node.body_id()).map(|body_id| { let body = tcx.hir().body(body_id); let mut visitor = ReturnsVisitor::default(); diff --git a/compiler/rustc_typeck/src/check/wfcheck.rs b/compiler/rustc_typeck/src/check/wfcheck.rs index e4124185d15..7965ec1b43f 100644 --- a/compiler/rustc_typeck/src/check/wfcheck.rs +++ b/compiler/rustc_typeck/src/check/wfcheck.rs @@ -116,7 +116,7 @@ pub(super) fn enter_wf_checking_ctxt<'tcx, F>( }) } -fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { +fn check_well_formed(tcx: TyCtxt<'_>, def_id: hir::OwnerId) { let node = tcx.hir().expect_owner(def_id); match node { hir::OwnerNode::Crate(_) => {} @@ -148,7 +148,7 @@ fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) { /// the types first. #[instrument(skip(tcx), level = "debug")] fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) { - let def_id = item.def_id; + let def_id = item.def_id.def_id; debug!( ?item.def_id, @@ -175,7 +175,7 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) { // for `T` hir::ItemKind::Impl(ref impl_) => { let is_auto = tcx - .impl_trait_ref(item.def_id) + .impl_trait_ref(def_id) .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id)); if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) { let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span); @@ -211,13 +211,13 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) { } } hir::ItemKind::Fn(ref sig, ..) => { - check_item_fn(tcx, item.def_id, item.ident, item.span, sig.decl); + check_item_fn(tcx, def_id, item.ident, item.span, sig.decl); } hir::ItemKind::Static(ty, ..) => { - check_item_type(tcx, item.def_id, ty.span, false); + check_item_type(tcx, def_id, ty.span, false); } hir::ItemKind::Const(ty, ..) => { - check_item_type(tcx, item.def_id, ty.span, false); + check_item_type(tcx, def_id, ty.span, false); } hir::ItemKind::Struct(ref struct_def, ref ast_generics) => { check_type_defn(tcx, item, false, |wfcx| vec![wfcx.non_enum_variant(struct_def)]); @@ -247,7 +247,7 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) { } fn check_foreign_item(tcx: TyCtxt<'_>, item: &hir::ForeignItem<'_>) { - let def_id = item.def_id; + let def_id = item.def_id.def_id; debug!( ?item.def_id, @@ -256,15 +256,15 @@ fn check_foreign_item(tcx: TyCtxt<'_>, item: &hir::ForeignItem<'_>) { match item.kind { hir::ForeignItemKind::Fn(decl, ..) => { - check_item_fn(tcx, item.def_id, item.ident, item.span, decl) + check_item_fn(tcx, def_id, item.ident, item.span, decl) } - hir::ForeignItemKind::Static(ty, ..) => check_item_type(tcx, item.def_id, ty.span, true), + hir::ForeignItemKind::Static(ty, ..) => check_item_type(tcx, def_id, ty.span, true), hir::ForeignItemKind::Type => (), } } fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) { - let def_id = trait_item.def_id; + let def_id = trait_item.def_id.def_id; let (method_sig, span) = match trait_item.kind { hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span), @@ -272,7 +272,7 @@ fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) { _ => (None, trait_item.span), }; check_object_unsafe_self_trait_by_name(tcx, trait_item); - check_associated_item(tcx, trait_item.def_id, span, method_sig); + check_associated_item(tcx, def_id, span, method_sig); let encl_trait_def_id = tcx.local_parent(def_id); let encl_trait = tcx.hir().expect_item(encl_trait_def_id); @@ -393,7 +393,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe // We also assume that all of the function signature's parameter types // are well formed. &sig.inputs().iter().copied().collect(), - gat_def_id, + gat_def_id.def_id, gat_generics, ) } @@ -416,7 +416,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe .copied() .collect::>(), &FxHashSet::default(), - gat_def_id, + gat_def_id.def_id, gat_generics, ) } @@ -456,7 +456,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe } for (gat_def_id, required_bounds) in required_bounds_by_item { - let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id); + let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id.def_id); debug!(?required_bounds); let param_env = tcx.param_env(gat_def_id); let gat_hir = gat_item_hir.hir_id(); @@ -786,7 +786,7 @@ fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool { /// When this is done, suggest using `Self` instead. fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) { let (trait_name, trait_def_id) = - match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id())) { + match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id()).def_id) { hir::Node::Item(item) => match item.kind { hir::ItemKind::Trait(..) => (item.ident, item.def_id), _ => return, @@ -796,18 +796,18 @@ fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem let mut trait_should_be_self = vec![]; match &item.kind { hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty)) - if could_be_self(trait_def_id, ty) => + if could_be_self(trait_def_id.def_id, ty) => { trait_should_be_self.push(ty.span) } hir::TraitItemKind::Fn(sig, _) => { for ty in sig.decl.inputs { - if could_be_self(trait_def_id, ty) { + if could_be_self(trait_def_id.def_id, ty) { trait_should_be_self.push(ty.span); } } match sig.decl.output { - hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => { + hir::FnRetTy::Return(ty) if could_be_self(trait_def_id.def_id, ty) => { trait_should_be_self.push(ty.span); } _ => {} @@ -836,8 +836,6 @@ fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem } fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) { - let def_id = impl_item.def_id; - let (method_sig, span) = match impl_item.kind { hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span), // Constrain binding and overflow error spans to `` in `type foo = `. @@ -845,7 +843,7 @@ fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) { _ => (None, impl_item.span), }; - check_associated_item(tcx, def_id, span, method_sig); + check_associated_item(tcx, impl_item.def_id.def_id, span, method_sig); } fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { @@ -1045,7 +1043,7 @@ fn check_type_defn<'tcx, F>( ) where F: FnMut(&WfCheckingCtxt<'_, 'tcx>) -> Vec>, { - enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| { + enter_wf_checking_ctxt(tcx, item.span, item.def_id.def_id, |wfcx| { let variants = lookup_fields(wfcx); let packed = tcx.adt_def(item.def_id).repr().packed(); @@ -1124,7 +1122,7 @@ fn check_type_defn<'tcx, F>( } } - check_where_clauses(wfcx, item.span, item.def_id); + check_where_clauses(wfcx, item.span, item.def_id.def_id); }); } @@ -1132,11 +1130,12 @@ fn check_type_defn<'tcx, F>( fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) { debug!(?item.def_id); - let trait_def = tcx.trait_def(item.def_id); + let def_id = item.def_id.def_id; + let trait_def = tcx.trait_def(def_id); if trait_def.is_marker || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker) { - for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) { + for associated_def_id in &*tcx.associated_item_def_ids(def_id) { struct_span_err!( tcx.sess, tcx.def_span(*associated_def_id), @@ -1147,8 +1146,8 @@ fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) { } } - enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| { - check_where_clauses(wfcx, item.span, item.def_id) + enter_wf_checking_ctxt(tcx, item.span, def_id, |wfcx| { + check_where_clauses(wfcx, item.span, def_id) }); // Only check traits, don't check trait aliases @@ -1242,7 +1241,7 @@ fn check_impl<'tcx>( ast_trait_ref: &Option>, constness: hir::Constness, ) { - enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| { + enter_wf_checking_ctxt(tcx, item.span, item.def_id.def_id, |wfcx| { match *ast_trait_ref { Some(ref ast_trait_ref) => { // `#[rustc_reservation_impl]` impls are not real impls and @@ -1273,18 +1272,18 @@ fn check_impl<'tcx>( let self_ty = tcx.type_of(item.def_id); let self_ty = wfcx.normalize( item.span, - Some(WellFormedLoc::Ty(item.hir_id().expect_owner())), + Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)), self_ty, ); wfcx.register_wf_obligation( ast_self_ty.span, - Some(WellFormedLoc::Ty(item.hir_id().expect_owner())), + Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)), self_ty.into(), ); } } - check_where_clauses(wfcx, item.span, item.def_id); + check_where_clauses(wfcx, item.span, item.def_id.def_id); }); } diff --git a/compiler/rustc_typeck/src/coherence/inherent_impls.rs b/compiler/rustc_typeck/src/coherence/inherent_impls.rs index 52aad636fd8..308ad5d5fc2 100644 --- a/compiler/rustc_typeck/src/coherence/inherent_impls.rs +++ b/compiler/rustc_typeck/src/coherence/inherent_impls.rs @@ -105,7 +105,7 @@ impl<'tcx> InherentCollect<'tcx> { } if let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::AsInfer) { - self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id); + self.impls_map.incoherent_impls.entry(simp).or_default().push(impl_def_id.def_id); } else { bug!("unexpected self type: {:?}", self_ty); } @@ -220,7 +220,9 @@ impl<'tcx> InherentCollect<'tcx> { | ty::Ref(..) | ty::Never | ty::FnPtr(_) - | ty::Tuple(..) => self.check_primitive_impl(item.def_id, self_ty, items, ty.span), + | ty::Tuple(..) => { + self.check_primitive_impl(item.def_id.def_id, self_ty, items, ty.span) + } ty::Projection(..) | ty::Opaque(..) | ty::Param(_) => { let mut err = struct_span_err!( self.tcx.sess, diff --git a/compiler/rustc_typeck/src/coherence/orphan.rs b/compiler/rustc_typeck/src/coherence/orphan.rs index 87961890f53..7d15e5a7f3c 100644 --- a/compiler/rustc_typeck/src/coherence/orphan.rs +++ b/compiler/rustc_typeck/src/coherence/orphan.rs @@ -42,7 +42,7 @@ fn do_orphan_check_impl<'tcx>( ) -> Result<(), ErrorGuaranteed> { let trait_def_id = trait_ref.def_id; - let item = tcx.hir().item(hir::ItemId { def_id }); + let item = tcx.hir().expect_item(def_id); let hir::ItemKind::Impl(ref impl_) = item.kind else { bug!("{:?} is not an impl: {:?}", def_id, item); }; diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index 359a79e9979..23369b2f1b4 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -28,7 +28,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind}; -use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::weak_lang_items; use rustc_hir::{GenericParamKind, HirId, Node}; @@ -449,8 +449,10 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { match self.node() { hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => { - let item = - self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id())); + let item = self + .tcx + .hir() + .expect_item(self.tcx.hir().get_parent_item(self.hir_id()).def_id); match &item.kind { hir::ItemKind::Enum(_, generics) | hir::ItemKind::Struct(_, generics) @@ -728,7 +730,7 @@ impl<'tcx> ItemCtxt<'tcx> { fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { let it = tcx.hir().item(item_id); debug!("convert: item {} with id {}", it.ident, it.hir_id()); - let def_id = item_id.def_id; + let def_id = item_id.def_id.def_id; match it.kind { // These don't define types. @@ -840,20 +842,21 @@ fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) { let trait_item = tcx.hir().trait_item(trait_item_id); - tcx.ensure().generics_of(trait_item_id.def_id); + let def_id = trait_item_id.def_id; + tcx.ensure().generics_of(def_id); match trait_item.kind { hir::TraitItemKind::Fn(..) => { - tcx.ensure().type_of(trait_item_id.def_id); - tcx.ensure().fn_sig(trait_item_id.def_id); + tcx.ensure().type_of(def_id); + tcx.ensure().fn_sig(def_id); } hir::TraitItemKind::Const(.., Some(_)) => { - tcx.ensure().type_of(trait_item_id.def_id); + tcx.ensure().type_of(def_id); } hir::TraitItemKind::Const(hir_ty, _) => { - tcx.ensure().type_of(trait_item_id.def_id); + tcx.ensure().type_of(def_id); // Account for `const C: _;`. let mut visitor = HirPlaceholderCollector::default(); visitor.visit_trait_item(trait_item); @@ -863,8 +866,8 @@ fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) { } hir::TraitItemKind::Type(_, Some(_)) => { - tcx.ensure().item_bounds(trait_item_id.def_id); - tcx.ensure().type_of(trait_item_id.def_id); + tcx.ensure().item_bounds(def_id); + tcx.ensure().type_of(def_id); // Account for `type T = _;`. let mut visitor = HirPlaceholderCollector::default(); visitor.visit_trait_item(trait_item); @@ -872,7 +875,7 @@ fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) { } hir::TraitItemKind::Type(_, None) => { - tcx.ensure().item_bounds(trait_item_id.def_id); + tcx.ensure().item_bounds(def_id); // #74612: Visit and try to find bad placeholders // even if there is no concrete type. let mut visitor = HirPlaceholderCollector::default(); @@ -882,7 +885,7 @@ fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) { } }; - tcx.ensure().predicates_of(trait_item_id.def_id); + tcx.ensure().predicates_of(def_id); } fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) { @@ -1595,7 +1598,7 @@ fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics { } ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => { let parent_id = tcx.hir().get_parent_item(hir_id); - assert_ne!(parent_id, CRATE_DEF_ID); + assert_ne!(parent_id, hir::CRATE_OWNER_ID); debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id); // Opaque types are always nested within another item, and // inherit the generics of the item. @@ -3386,7 +3389,7 @@ fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: let node = tcx.hir().get(hir_id); if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node { let parent_id = tcx.hir().get_parent_item(hir_id); - let parent_item = tcx.hir().expect_item(parent_id); + let parent_item = tcx.hir().expect_item(parent_id.def_id); if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind { tcx.sess .struct_span_err( diff --git a/compiler/rustc_typeck/src/collect/type_of.rs b/compiler/rustc_typeck/src/collect/type_of.rs index 70e259b46bf..24fb0b1fd26 100644 --- a/compiler/rustc_typeck/src/collect/type_of.rs +++ b/compiler/rustc_typeck/src/collect/type_of.rs @@ -569,22 +569,22 @@ fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> T fn visit_item(&mut self, it: &'tcx Item<'tcx>) { trace!(?it.def_id); // The opaque type itself or its children are not within its reveal scope. - if it.def_id != self.def_id { - self.check(it.def_id); + if it.def_id.def_id != self.def_id { + self.check(it.def_id.def_id); intravisit::walk_item(self, it); } } fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) { trace!(?it.def_id); // The opaque type itself or its children are not within its reveal scope. - if it.def_id != self.def_id { - self.check(it.def_id); + if it.def_id.def_id != self.def_id { + self.check(it.def_id.def_id); intravisit::walk_impl_item(self, it); } } fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) { trace!(?it.def_id); - self.check(it.def_id); + self.check(it.def_id.def_id); intravisit::walk_trait_item(self, it); } } @@ -688,22 +688,22 @@ fn find_opaque_ty_constraints_for_rpit( fn visit_item(&mut self, it: &'tcx Item<'tcx>) { trace!(?it.def_id); // The opaque type itself or its children are not within its reveal scope. - if it.def_id != self.def_id { - self.check(it.def_id); + if it.def_id.def_id != self.def_id { + self.check(it.def_id.def_id); intravisit::walk_item(self, it); } } fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) { trace!(?it.def_id); // The opaque type itself or its children are not within its reveal scope. - if it.def_id != self.def_id { - self.check(it.def_id); + if it.def_id.def_id != self.def_id { + self.check(it.def_id.def_id); intravisit::walk_impl_item(self, it); } } fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) { trace!(?it.def_id); - self.check(it.def_id); + self.check(it.def_id.def_id); intravisit::walk_trait_item(self, it); } } diff --git a/compiler/rustc_typeck/src/impl_wf_check.rs b/compiler/rustc_typeck/src/impl_wf_check.rs index 9fee1eaaec9..c499364056f 100644 --- a/compiler/rustc_typeck/src/impl_wf_check.rs +++ b/compiler/rustc_typeck/src/impl_wf_check.rs @@ -58,10 +58,10 @@ fn check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { let module = tcx.hir_module_items(module_def_id); for id in module.items() { if matches!(tcx.def_kind(id.def_id), DefKind::Impl) { - enforce_impl_params_are_constrained(tcx, id.def_id); - enforce_impl_items_are_distinct(tcx, id.def_id); + enforce_impl_params_are_constrained(tcx, id.def_id.def_id); + enforce_impl_items_are_distinct(tcx, id.def_id.def_id); if min_specialization { - check_min_specialization(tcx, id.def_id); + check_min_specialization(tcx, id.def_id.def_id); } } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 375737e9bc4..bd68dffb823 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1080,7 +1080,7 @@ pub(crate) fn clean_impl_item<'tcx>( let mut what_rustc_thinks = Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx); - let impl_ref = cx.tcx.impl_trait_ref(cx.tcx.local_parent(impl_.def_id)); + let impl_ref = cx.tcx.impl_trait_ref(cx.tcx.local_parent(impl_.def_id.def_id)); // Trait impl items always inherit the impl's visibility -- // we don't want to show `pub`. @@ -1325,7 +1325,7 @@ fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(), }; register_res(cx, trait_.res); - let self_def_id = DefId::local(qself.hir_id.owner.local_def_index); + let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index); let self_type = clean_ty(qself, cx); let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type); Type::QPath(Box::new(QPathData { @@ -2037,7 +2037,7 @@ fn clean_extern_crate<'tcx>( cx: &mut DocContext<'tcx>, ) -> Vec { // this is the ID of the `extern crate` statement - let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE); + let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id.def_id).unwrap_or(LOCAL_CRATE); // this is the ID of the crate itself let crate_def_id = cnum.as_def_id(); let attrs = cx.tcx.hir().attrs(krate.hir_id()); @@ -2099,7 +2099,7 @@ fn clean_use_statement<'tcx>( let attrs = cx.tcx.hir().attrs(import.hir_id()); let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline); let pub_underscore = visibility.is_public() && name == kw::Underscore; - let current_mod = cx.tcx.parent_module_from_def_id(import.def_id); + let current_mod = cx.tcx.parent_module_from_def_id(import.def_id.def_id); // The parent of the module in which this import resides. This // is the same as `current_mod` if that's already the top diff --git a/src/librustdoc/passes/propagate_doc_cfg.rs b/src/librustdoc/passes/propagate_doc_cfg.rs index 765f7c61bd3..de3a4b33905 100644 --- a/src/librustdoc/passes/propagate_doc_cfg.rs +++ b/src/librustdoc/passes/propagate_doc_cfg.rs @@ -48,7 +48,7 @@ impl<'a, 'tcx> CfgPropagator<'a, 'tcx> { let expected_parent = hir.get_parent_item(hir_id); // If parents are different, it means that `item` is a reexport and we need // to compute the actual `cfg` by iterating through its "real" parents. - if self.parent == Some(expected_parent) { + if self.parent == Some(expected_parent.def_id) { return; } } diff --git a/src/librustdoc/scrape_examples.rs b/src/librustdoc/scrape_examples.rs index ca86ac89e85..dfa6ba38b88 100644 --- a/src/librustdoc/scrape_examples.rs +++ b/src/librustdoc/scrape_examples.rs @@ -143,14 +143,14 @@ where // then we need to exit before calling typeck (which will panic). See // test/run-make/rustdoc-scrape-examples-invalid-expr for an example. let hir = tcx.hir(); - if hir.maybe_body_owned_by(ex.hir_id.owner).is_none() { + if hir.maybe_body_owned_by(ex.hir_id.owner.def_id).is_none() { return; } // Get type of function if expression is a function call let (ty, call_span, ident_span) = match ex.kind { hir::ExprKind::Call(f, _) => { - let types = tcx.typeck(ex.hir_id.owner); + let types = tcx.typeck(ex.hir_id.owner.def_id); if let Some(ty) = types.node_type_opt(f.hir_id) { (ty, ex.span, f.span) @@ -160,7 +160,7 @@ where } } hir::ExprKind::MethodCall(path, _, _, call_span) => { - let types = tcx.typeck(ex.hir_id.owner); + let types = tcx.typeck(ex.hir_id.owner.def_id); let Some(def_id) = types.type_dependent_def_id(ex.hir_id) else { trace!("type_dependent_def_id({}) = None", ex.hir_id); return; @@ -183,9 +183,8 @@ where // If the enclosing item has a span coming from a proc macro, then we also don't want to include // the example. - let enclosing_item_span = tcx - .hir() - .span_with_body(tcx.hir().local_def_id_to_hir_id(tcx.hir().get_parent_item(ex.hir_id))); + let enclosing_item_span = + tcx.hir().span_with_body(tcx.hir().get_parent_item(ex.hir_id).into()); if enclosing_item_span.from_expansion() { trace!("Rejecting expr ({call_span:?}) from macro item: {enclosing_item_span:?}"); return; diff --git a/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs b/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs index 03ad3ca8261..03da804bd1c 100644 --- a/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs +++ b/src/test/ui-fulldeps/auxiliary/issue-40001-plugin.rs @@ -44,7 +44,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingAllowedAttrPass { ) { let item = match cx.tcx.hir().get(id) { Node::Item(item) => item, - _ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(id)), + _ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(id).def_id), }; let allowed = |attr| pprust::attribute_to_string(attr).contains("allowed_attr"); diff --git a/src/test/ui/thir-tree.stdout b/src/test/ui/thir-tree.stdout index 5fcdfca18d6..7fb90581f8a 100644 --- a/src/test/ui/thir-tree.stdout +++ b/src/test/ui/thir-tree.stdout @@ -33,7 +33,9 @@ Thir { region_scope: Node(2), lint_level: Explicit( HirId { - owner: DefId(0:3 ~ thir_tree[8f1d]::main), + owner: OwnerId { + def_id: DefId(0:3 ~ thir_tree[8f1d]::main), + }, local_id: 2, }, ), diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 501f9ef78ae..e54d71fc8e4 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -704,7 +704,7 @@ fn walk_parents<'tcx>( span, .. }) if span.ctxt() == ctxt => { - let ty = cx.tcx.type_of(def_id); + let ty = cx.tcx.type_of(def_id.def_id); Some(ty_auto_deref_stability(cx, ty, precedence).position_for_result(cx)) }, diff --git a/src/tools/clippy/clippy_lints/src/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index eb158d850fa..f48ba526d51 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -233,11 +233,11 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { cx, - typeck_results: cx.tcx.typeck(item.def_id), + typeck_results: cx.tcx.typeck(item.def_id.def_id), panic_span: None, }; fpu.visit_expr(body.value); - lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); + lint_for_missing_headers(cx, item.def_id.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); } }, hir::ItemKind::Impl(impl_) => { @@ -268,7 +268,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let headers = check_attrs(cx, &self.valid_idents, attrs); if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind { if !in_external_macro(cx.tcx.sess, item.span) { - lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, None, None); + lint_for_missing_headers(cx, item.def_id.def_id, item.span, sig, headers, None, None); } } } @@ -283,11 +283,11 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { cx, - typeck_results: cx.tcx.typeck(item.def_id), + typeck_results: cx.tcx.typeck(item.def_id.def_id), panic_span: None, }; fpu.visit_expr(body.value); - lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); + lint_for_missing_headers(cx, item.def_id.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span); } } } diff --git a/src/tools/clippy/clippy_lints/src/enum_variants.rs b/src/tools/clippy/clippy_lints/src/enum_variants.rs index cd36f9fcd72..c39a909b3cc 100644 --- a/src/tools/clippy/clippy_lints/src/enum_variants.rs +++ b/src/tools/clippy/clippy_lints/src/enum_variants.rs @@ -297,7 +297,7 @@ impl LateLintPass<'_> for EnumVariantNames { } } if let ItemKind::Enum(ref def, _) = item.kind { - if !(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) { + if !(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id.def_id)) { check_variant(cx, self.threshold, def, item_name, item.span); } } diff --git a/src/tools/clippy/clippy_lints/src/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index 327865e4c85..a6ddb26e2de 100644 --- a/src/tools/clippy/clippy_lints/src/escape.rs +++ b/src/tools/clippy/clippy_lints/src/escape.rs @@ -71,7 +71,7 @@ impl<'tcx> LateLintPass<'tcx> for BoxedLocal { } } - let parent_id = cx.tcx.hir().get_parent_item(hir_id); + let parent_id = cx.tcx.hir().get_parent_item(hir_id).def_id; let parent_node = cx.tcx.hir().find_by_def_id(parent_id); let mut trait_self_ty = None; diff --git a/src/tools/clippy/clippy_lints/src/exhaustive_items.rs b/src/tools/clippy/clippy_lints/src/exhaustive_items.rs index 173d41b4b05..f3d9ebc5f12 100644 --- a/src/tools/clippy/clippy_lints/src/exhaustive_items.rs +++ b/src/tools/clippy/clippy_lints/src/exhaustive_items.rs @@ -73,7 +73,7 @@ impl LateLintPass<'_> for ExhaustiveItems { fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Enum(..) | ItemKind::Struct(..) = item.kind; - if cx.access_levels.is_exported(item.def_id); + if cx.access_levels.is_exported(item.def_id.def_id); let attrs = cx.tcx.hir().attrs(item.hir_id()); if !attrs.iter().any(|a| a.has_name(sym::non_exhaustive)); then { diff --git a/src/tools/clippy/clippy_lints/src/exit.rs b/src/tools/clippy/clippy_lints/src/exit.rs index cbf52d19334..407dd1b3957 100644 --- a/src/tools/clippy/clippy_lints/src/exit.rs +++ b/src/tools/clippy/clippy_lints/src/exit.rs @@ -33,7 +33,7 @@ impl<'tcx> LateLintPass<'tcx> for Exit { if let ExprKind::Path(ref path) = path_expr.kind; if let Some(def_id) = cx.qpath_res(path, path_expr.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::EXIT); - let parent = cx.tcx.hir().get_parent_item(e.hir_id); + let parent = cx.tcx.hir().get_parent_item(e.hir_id).def_id; if let Some(Node::Item(Item{kind: ItemKind::Fn(..), ..})) = cx.tcx.hir().find_by_def_id(parent); // If the next item up is a function we check if it is an entry point // and only then emit a linter warning diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index 1f69f34a229..ef24a5d06ad 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -107,7 +107,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[h let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { lcx: cx, - typeck_results: cx.tcx.typeck(impl_item.id.def_id), + typeck_results: cx.tcx.typeck(impl_item.id.def_id.def_id), result: Vec::new(), }; fpu.visit_expr(body.value); diff --git a/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index 00a4937763e..d6d33bda173 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/clippy_lints/src/functions/must_use.rs @@ -21,7 +21,7 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> let attrs = cx.tcx.hir().attrs(item.hir_id()); let attr = cx.tcx.get_attr(item.def_id.to_def_id(), sym::must_use); if let hir::ItemKind::Fn(ref sig, _generics, ref body_id) = item.kind { - let is_public = cx.access_levels.is_exported(item.def_id); + let is_public = cx.access_levels.is_exported(item.def_id.def_id); let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); if let Some(attr) = attr { check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr); @@ -31,7 +31,7 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> sig.decl, cx.tcx.hir().body(*body_id), item.span, - item.def_id, + item.def_id.def_id, item.span.with_hi(sig.decl.output.span().hi()), "this function could have a `#[must_use]` attribute", ); @@ -41,19 +41,19 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) { if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind { - let is_public = cx.access_levels.is_exported(item.def_id); + let is_public = cx.access_levels.is_exported(item.def_id.def_id); let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); let attrs = cx.tcx.hir().attrs(item.hir_id()); let attr = cx.tcx.get_attr(item.def_id.to_def_id(), sym::must_use); if let Some(attr) = attr { check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr); - } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.def_id).is_none() { + } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.def_id.def_id).is_none() { check_must_use_candidate( cx, sig.decl, cx.tcx.hir().body(*body_id), item.span, - item.def_id, + item.def_id.def_id, item.span.with_hi(sig.decl.output.span().hi()), "this method could have a `#[must_use]` attribute", ); @@ -63,7 +63,7 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Imp pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) { if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind { - let is_public = cx.access_levels.is_exported(item.def_id); + let is_public = cx.access_levels.is_exported(item.def_id.def_id); let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); let attrs = cx.tcx.hir().attrs(item.hir_id()); @@ -78,7 +78,7 @@ pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Tr sig.decl, body, item.span, - item.def_id, + item.def_id.def_id, item.span.with_hi(sig.decl.output.span().hi()), "this method could have a `#[must_use]` attribute", ); @@ -171,7 +171,7 @@ fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut DefIdSet) return false; // ignore `_` patterns } if cx.tcx.has_typeck_results(pat.hir_id.owner.to_def_id()) { - is_mutable_ty(cx, cx.tcx.typeck(pat.hir_id.owner).pat_ty(pat), pat.span, tys) + is_mutable_ty(cx, cx.tcx.typeck(pat.hir_id.owner.def_id).pat_ty(pat), pat.span, tys) } else { false } @@ -218,7 +218,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { if self.cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id()) && is_mutable_ty( self.cx, - self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg), + self.cx.tcx.typeck(arg.hir_id.owner.def_id).expr_ty(arg), arg.span, &mut tys, ) @@ -236,7 +236,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { if self.cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id()) && is_mutable_ty( self.cx, - self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg), + self.cx.tcx.typeck(arg.hir_id.owner.def_id).expr_ty(arg), arg.span, &mut tys, ) diff --git a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs index 3bbfa52e810..0b50431fbaa 100644 --- a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs +++ b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs @@ -28,7 +28,7 @@ pub(super) fn check_fn<'tcx>( pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) { if let hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(eid)) = item.kind { let body = cx.tcx.hir().body(eid); - check_raw_ptr(cx, sig.header.unsafety, sig.decl, body, item.def_id); + check_raw_ptr(cx, sig.header.unsafety, sig.decl, body, item.def_id.def_id); } } diff --git a/src/tools/clippy/clippy_lints/src/functions/result.rs b/src/tools/clippy/clippy_lints/src/functions/result.rs index 9591405cb06..113c4e9f509 100644 --- a/src/tools/clippy/clippy_lints/src/functions/result.rs +++ b/src/tools/clippy/clippy_lints/src/functions/result.rs @@ -34,9 +34,9 @@ fn result_err_ty<'tcx>( pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::Item<'tcx>, large_err_threshold: u64) { if let hir::ItemKind::Fn(ref sig, _generics, _) = item.kind - && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) + && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id.def_id, item.span) { - if cx.access_levels.is_exported(item.def_id) { + if cx.access_levels.is_exported(item.def_id.def_id) { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); check_result_unit_err(cx, err_ty, fn_header_span); } @@ -47,10 +47,10 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::Item<'tcx>, l pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::ImplItem<'tcx>, large_err_threshold: u64) { // Don't lint if method is a trait's implementation, we can't do anything about those if let hir::ImplItemKind::Fn(ref sig, _) = item.kind - && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) - && trait_ref_of_method(cx, item.def_id).is_none() + && let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id.def_id, item.span) + && trait_ref_of_method(cx, item.def_id.def_id).is_none() { - if cx.access_levels.is_exported(item.def_id) { + if cx.access_levels.is_exported(item.def_id.def_id) { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); check_result_unit_err(cx, err_ty, fn_header_span); } @@ -61,8 +61,8 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::ImplItem pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &hir::TraitItem<'tcx>, large_err_threshold: u64) { if let hir::TraitItemKind::Fn(ref sig, _) = item.kind { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - if let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id, item.span) { - if cx.access_levels.is_exported(item.def_id) { + if let Some((hir_ty, err_ty)) = result_err_ty(cx, sig.decl, item.def_id.def_id, item.span) { + if cx.access_levels.is_exported(item.def_id.def_id) { check_result_unit_err(cx, err_ty, fn_header_span); } check_result_large_err(cx, err_ty, hir_ty.span, large_err_threshold); diff --git a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs index 4f9680f60fe..804fdc2da08 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs @@ -112,7 +112,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher { } } - if !cx.access_levels.is_exported(item.def_id) { + if !cx.access_levels.is_exported(item.def_id.def_id) { return; } diff --git a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs index 17d867aacb5..cb6c2ec0fb9 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs @@ -108,7 +108,7 @@ impl<'tcx> LateLintPass<'tcx> for InherentToString { if is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id()), sym::String); // Filters instances of to_string which are required by a trait - if trait_ref_of_method(cx, impl_item.def_id).is_none(); + if trait_ref_of_method(cx, impl_item.def_id.def_id).is_none(); then { show_lint(cx, impl_item); diff --git a/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs b/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs index b56d87c5348..2027c23d328 100644 --- a/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs @@ -44,7 +44,7 @@ impl<'tcx> LateLintPass<'tcx> for IterNotReturningIterator { let name = item.ident.name.as_str(); if matches!(name, "iter" | "iter_mut") { if let TraitItemKind::Fn(fn_sig, _) = &item.kind { - check_sig(cx, name, fn_sig, item.def_id); + check_sig(cx, name, fn_sig, item.def_id.def_id); } } } @@ -58,7 +58,7 @@ impl<'tcx> LateLintPass<'tcx> for IterNotReturningIterator { ) { if let ImplItemKind::Fn(fn_sig, _) = &item.kind { - check_sig(cx, name, fn_sig, item.def_id); + check_sig(cx, name, fn_sig, item.def_id.def_id); } } } diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index 7ae8ef830fa..7d15dd4cb21 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -134,7 +134,7 @@ impl<'tcx> LateLintPass<'tcx> for LenZero { if item.ident.name == sym::len; if let ImplItemKind::Fn(sig, _) = &item.kind; if sig.decl.implicit_self.has_implicit_self(); - if cx.access_levels.is_exported(item.def_id); + if cx.access_levels.is_exported(item.def_id.def_id); if matches!(sig.decl.output, FnRetTy::Return(_)); if let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id()); if imp.of_trait.is_none(); @@ -210,7 +210,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items } } - if cx.access_levels.is_exported(visited_trait.def_id) && trait_items.iter().any(|i| is_named_self(cx, i, sym::len)) + if cx.access_levels.is_exported(visited_trait.def_id.def_id) && trait_items.iter().any(|i| is_named_self(cx, i, sym::len)) { let mut current_and_super_traits = DefIdSet::default(); fill_trait_set(visited_trait.def_id.to_def_id(), &mut current_and_super_traits, cx); diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index 643a7cfd577..399a03187d9 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -102,7 +102,7 @@ impl<'tcx> LateLintPass<'tcx> for Lifetimes { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) { if let ImplItemKind::Fn(ref sig, id) = item.kind { - let report_extra_lifetimes = trait_ref_of_method(cx, item.def_id).is_none(); + let report_extra_lifetimes = trait_ref_of_method(cx, item.def_id.def_id).is_none(); check_fn_inner( cx, sig.decl, @@ -276,7 +276,7 @@ fn could_use_elision<'tcx>( let mut checker = BodyLifetimeChecker { lifetimes_used_in_body: false, }; - checker.visit_expr(body.value); + checker.visit_expr(&body.value); if checker.lifetimes_used_in_body { return false; } diff --git a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs index fce2d54639c..be7f96e9bb0 100644 --- a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs +++ b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs @@ -69,7 +69,7 @@ fn check_for_mutation<'tcx>( ExprUseVisitor::new( &mut delegate, &infcx, - body.hir_id.owner, + body.hir_id.owner.def_id, cx.param_env, cx.typeck_results(), ) diff --git a/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs b/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs index 2b04475c7a9..53e7565bd33 100644 --- a/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs +++ b/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs @@ -166,7 +166,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustiveEnum { if let Some((id, span)) = iter.next() && iter.next().is_none() { - self.potential_enums.push((item.def_id, id, item.span, span)); + self.potential_enums.push((item.def_id.def_id, id, item.span, span)); } } } diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index cdde4c54d63..ddb6d1ca26c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -3250,7 +3250,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { return; } let name = impl_item.ident.name.as_str(); - let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); + let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let item = cx.tcx.hir().expect_item(parent); let self_ty = cx.tcx.type_of(item.def_id); @@ -3259,7 +3259,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind; if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next(); - let method_sig = cx.tcx.fn_sig(impl_item.def_id); + let method_sig = cx.tcx.fn_sig(impl_item.def_id.def_id); let method_sig = cx.tcx.erase_late_bound_regions(method_sig); let first_arg_ty = method_sig.inputs().iter().next(); @@ -3269,7 +3269,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { then { // if this impl block implements a trait, lint in trait definition instead - if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) { + if !implements_trait && cx.access_levels.is_exported(impl_item.def_id.def_id) { // check missing trait implementations for method_config in &TRAIT_METHODS { if name == method_config.method_name && @@ -3301,7 +3301,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods { if sig.decl.implicit_self.has_implicit_self() && !(self.avoid_breaking_exported_api - && cx.access_levels.is_exported(impl_item.def_id)) + && cx.access_levels.is_exported(impl_item.def_id.def_id)) { wrong_self_convention::check( cx, diff --git a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs index bc304c081b9..f24b41411c8 100644 --- a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs +++ b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs @@ -136,7 +136,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn { // Const fns are not allowed as methods in a trait. { - let parent = cx.tcx.hir().get_parent_item(hir_id); + let parent = cx.tcx.hir().get_parent_item(hir_id).def_id; if parent != CRATE_DEF_ID { if let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent) { if let hir::ItemKind::Trait(..) = &item.kind { diff --git a/src/tools/clippy/clippy_lints/src/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 3701fdb4adb..47219556676 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -131,7 +131,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { hir::ItemKind::Fn(..) => { // ignore main() if it.ident.name == sym::main { - let at_root = cx.tcx.local_parent(it.def_id) == CRATE_DEF_ID; + let at_root = cx.tcx.local_parent(it.def_id.def_id) == CRATE_DEF_ID; if at_root { return; } diff --git a/src/tools/clippy/clippy_lints/src/missing_inline.rs b/src/tools/clippy/clippy_lints/src/missing_inline.rs index 07bc2ca5d3c..9d5764ac092 100644 --- a/src/tools/clippy/clippy_lints/src/missing_inline.rs +++ b/src/tools/clippy/clippy_lints/src/missing_inline.rs @@ -88,7 +88,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { return; } - if !cx.access_levels.is_exported(it.def_id) { + if !cx.access_levels.is_exported(it.def_id.def_id) { return; } match it.kind { @@ -142,7 +142,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { } // If the item being implemented is not exported, then we don't need #[inline] - if !cx.access_levels.is_exported(impl_item.def_id) { + if !cx.access_levels.is_exported(impl_item.def_id.def_id) { return; } @@ -159,7 +159,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { }; if let Some(trait_def_id) = trait_def_id { - if trait_def_id.is_local() && !cx.access_levels.is_exported(impl_item.def_id) { + if trait_def_id.is_local() && !cx.access_levels.is_exported(impl_item.def_id.def_id) { // If a trait is being implemented for an item, and the // trait is not exported, we don't need #[inline] return; diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index 4db103bbc13..25d6ca83a94 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -89,7 +89,7 @@ impl<'tcx> LateLintPass<'tcx> for MutableKeyType { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'tcx>) { if let hir::ImplItemKind::Fn(ref sig, ..) = item.kind { - if trait_ref_of_method(cx, item.def_id).is_none() { + if trait_ref_of_method(cx, item.def_id.def_id).is_none() { check_sig(cx, item.hir_id(), sig.decl); } } diff --git a/src/tools/clippy/clippy_lints/src/new_without_default.rs b/src/tools/clippy/clippy_lints/src/new_without_default.rs index 5c45ee6d94a..357a71693d2 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -84,7 +84,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { // can't be implemented for unsafe new return; } - if cx.tcx.is_doc_hidden(impl_item.def_id) { + if cx.tcx.is_doc_hidden(impl_item.def_id.def_id) { // shouldn't be implemented when it is hidden in docs return; } @@ -96,7 +96,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { if_chain! { if sig.decl.inputs.is_empty(); if name == sym::new; - if cx.access_levels.is_reachable(impl_item.def_id); + if cx.access_levels.is_reachable(impl_item.def_id.def_id); let self_def_id = cx.tcx.hir().get_parent_item(id); let self_ty = cx.tcx.type_of(self_def_id); if self_ty == return_ty(cx, id); diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index b1588452732..616ef9e2f86 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -286,7 +286,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) { if let ImplItemKind::Const(hir_ty, body_id) = &impl_item.kind { - let item_def_id = cx.tcx.hir().get_parent_item(impl_item.hir_id()); + let item_def_id = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let item = cx.tcx.hir().expect_item(item_def_id); match &item.kind { diff --git a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs index 6217110a1f3..d64a9cf71e1 100644 --- a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs @@ -243,7 +243,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { .. })) => { #[allow(trivial_casts)] - if let Some(Node::Item(item)) = get_parent_node(cx.tcx, cx.tcx.hir().local_def_id_to_hir_id(def_id)) + if let Some(Node::Item(item)) = get_parent_node(cx.tcx, def_id.into()) && let Some(trait_ref) = cx.tcx.impl_trait_ref(item.def_id) && let Some(trait_item_id) = cx.tcx.associated_item(def_id).trait_item_def_id { diff --git a/src/tools/clippy/clippy_lints/src/operators/assign_op_pattern.rs b/src/tools/clippy/clippy_lints/src/operators/assign_op_pattern.rs index 945a09a647c..2c22c8b3d08 100644 --- a/src/tools/clippy/clippy_lints/src/operators/assign_op_pattern.rs +++ b/src/tools/clippy/clippy_lints/src/operators/assign_op_pattern.rs @@ -28,7 +28,7 @@ pub(super) fn check<'tcx>( if_chain! { if let Some((_, lang_item)) = binop_traits(op.node); if let Ok(trait_id) = cx.tcx.lang_items().require(lang_item); - let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id); + let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id).def_id; if trait_ref_of_method(cx, parent_fn) .map_or(true, |t| t.path.res.def_id() != trait_id); if implements_trait(cx, ty, trait_id, &[rty.into()]); diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index 0960b050c24..6b2eea48932 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -261,7 +261,7 @@ impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue { } if let hir::TraitItemKind::Fn(method_sig, _) = &item.kind { - self.check_poly_fn(cx, item.def_id, method_sig.decl, None); + self.check_poly_fn(cx, item.def_id.def_id, method_sig.decl, None); } } diff --git a/src/tools/clippy/clippy_lints/src/redundant_pub_crate.rs b/src/tools/clippy/clippy_lints/src/redundant_pub_crate.rs index 323326381d4..3c6ca9d9897 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_pub_crate.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_pub_crate.rs @@ -46,8 +46,8 @@ impl_lint_pass!(RedundantPubCrate => [REDUNDANT_PUB_CRATE]); impl<'tcx> LateLintPass<'tcx> for RedundantPubCrate { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { if_chain! { - if cx.tcx.visibility(item.def_id) == ty::Visibility::Restricted(CRATE_DEF_ID.to_def_id()); - if !cx.access_levels.is_exported(item.def_id) && self.is_exported.last() == Some(&false); + if cx.tcx.visibility(item.def_id.def_id) == ty::Visibility::Restricted(CRATE_DEF_ID.to_def_id()); + if !cx.access_levels.is_exported(item.def_id.def_id) && self.is_exported.last() == Some(&false); if is_not_macro_export(item); then { let span = item.span.with_hi(item.ident.span.hi()); @@ -70,7 +70,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantPubCrate { } if let ItemKind::Mod { .. } = item.kind { - self.is_exported.push(cx.access_levels.is_exported(item.def_id)); + self.is_exported.push(cx.access_levels.is_exported(item.def_id.def_id)); } } diff --git a/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs index 60be6bd335f..16d702a3868 100644 --- a/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs +++ b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs @@ -128,7 +128,7 @@ impl<'tcx> LateLintPass<'tcx> for ReturnSelfNotMustUse { fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) { if let TraitItemKind::Fn(ref sig, _) = item.kind { - check_method(cx, sig.decl, item.def_id, item.span, item.hir_id()); + check_method(cx, sig.decl, item.def_id.def_id, item.span, item.hir_id()); } } } diff --git a/src/tools/clippy/clippy_lints/src/self_named_constructors.rs b/src/tools/clippy/clippy_lints/src/self_named_constructors.rs index 9cea4d88067..1ac538f4c7c 100644 --- a/src/tools/clippy/clippy_lints/src/self_named_constructors.rs +++ b/src/tools/clippy/clippy_lints/src/self_named_constructors.rs @@ -51,7 +51,7 @@ impl<'tcx> LateLintPass<'tcx> for SelfNamedConstructors { _ => return, } - let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); + let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let item = cx.tcx.hir().expect_item(parent); let self_ty = cx.tcx.type_of(item.def_id); let ret_ty = return_ty(cx, impl_item.hir_id()); diff --git a/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs b/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs index 6add20c1fb7..d47ed459387 100644 --- a/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs +++ b/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs @@ -64,11 +64,11 @@ impl<'tcx> LateLintPass<'tcx> for SuspiciousImpl { // Check for more than one binary operation in the implemented function // Linting when multiple operations are involved can result in false positives - let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id); + let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id).def_id; if let hir::Node::ImplItem(impl_item) = cx.tcx.hir().get_by_def_id(parent_fn); if let hir::ImplItemKind::Fn(_, body_id) = impl_item.kind; let body = cx.tcx.hir().body(body_id); - let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id); + let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id).def_id; if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn); let trait_id = trait_ref.path.res.def_id(); if ![binop_trait_id, op_assign_trait_id].contains(&trait_id); diff --git a/src/tools/clippy/clippy_lints/src/transmute/utils.rs b/src/tools/clippy/clippy_lints/src/transmute/utils.rs index 8bdadf24402..8e90d20265c 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/utils.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/utils.rs @@ -42,7 +42,7 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( /// messages. This function will panic if that occurs. fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option { let hir_id = e.hir_id; - let local_def_id = hir_id.owner; + let local_def_id = hir_id.owner.def_id; Inherited::build(cx.tcx, local_def_id).enter(|inherited| { let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id); diff --git a/src/tools/clippy/clippy_lints/src/types/borrowed_box.rs b/src/tools/clippy/clippy_lints/src/types/borrowed_box.rs index 94945b2e1a9..1268c23206a 100644 --- a/src/tools/clippy/clippy_lints/src/types/borrowed_box.rs +++ b/src/tools/clippy/clippy_lints/src/types/borrowed_box.rs @@ -104,7 +104,7 @@ fn get_bounds_if_impl_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, id: if let Some(Node::GenericParam(generic_param)) = cx.tcx.hir().get_if_local(did); if let GenericParamKind::Type { synthetic, .. } = generic_param.kind; if synthetic; - if let Some(generics) = cx.tcx.hir().get_generics(id.owner); + if let Some(generics) = cx.tcx.hir().get_generics(id.owner.def_id); if let Some(pred) = generics.bounds_for_param(did.expect_local()).next(); then { Some(pred.bounds) diff --git a/src/tools/clippy/clippy_lints/src/types/mod.rs b/src/tools/clippy/clippy_lints/src/types/mod.rs index 353a6f6b899..aca55817c52 100644 --- a/src/tools/clippy/clippy_lints/src/types/mod.rs +++ b/src/tools/clippy/clippy_lints/src/types/mod.rs @@ -313,7 +313,7 @@ impl_lint_pass!(Types => [BOX_COLLECTION, VEC_BOX, OPTION_OPTION, LINKEDLIST, BO impl<'tcx> LateLintPass<'tcx> for Types { fn check_fn(&mut self, cx: &LateContext<'_>, _: FnKind<'_>, decl: &FnDecl<'_>, _: &Body<'_>, _: Span, id: HirId) { let is_in_trait_impl = - if let Some(hir::Node::Item(item)) = cx.tcx.hir().find_by_def_id(cx.tcx.hir().get_parent_item(id)) { + if let Some(hir::Node::Item(item)) = cx.tcx.hir().find_by_def_id(cx.tcx.hir().get_parent_item(id).def_id) { matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })) } else { false @@ -333,7 +333,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { } fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { - let is_exported = cx.access_levels.is_exported(item.def_id); + let is_exported = cx.access_levels.is_exported(item.def_id.def_id); match item.kind { ItemKind::Static(ty, _, _) | ItemKind::Const(ty, _) => self.check_ty( @@ -353,7 +353,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { match item.kind { ImplItemKind::Const(ty, _) => { let is_in_trait_impl = if let Some(hir::Node::Item(item)) = - cx.tcx.hir().find_by_def_id(cx.tcx.hir().get_parent_item(item.hir_id())) + cx.tcx.hir().find_by_def_id(cx.tcx.hir().get_parent_item(item.hir_id()).def_id) { matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })) } else { @@ -390,7 +390,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { } fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &TraitItem<'_>) { - let is_exported = cx.access_levels.is_exported(item.def_id); + let is_exported = cx.access_levels.is_exported(item.def_id.def_id); let context = CheckTyContext { is_exported, diff --git a/src/tools/clippy/clippy_lints/src/unused_self.rs b/src/tools/clippy/clippy_lints/src/unused_self.rs index 51c65d898cf..713fe06bad4 100644 --- a/src/tools/clippy/clippy_lints/src/unused_self.rs +++ b/src/tools/clippy/clippy_lints/src/unused_self.rs @@ -54,14 +54,14 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { if impl_item.span.from_expansion() { return; } - let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); + let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let parent_item = cx.tcx.hir().expect_item(parent); let assoc_item = cx.tcx.associated_item(impl_item.def_id); if_chain! { if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind; if assoc_item.fn_has_self_parameter; if let ImplItemKind::Fn(.., body_id) = &impl_item.kind; - if !cx.access_levels.is_exported(impl_item.def_id) || !self.avoid_breaking_exported_api; + if !cx.access_levels.is_exported(impl_item.def_id.def_id) || !self.avoid_breaking_exported_api; let body = cx.tcx.hir().body(*body_id); if let [self_param, ..] = body.params; if !is_local_used(cx, body, self_param.pat.hir_id); diff --git a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs index 46020adcaa2..baa53ba664f 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs @@ -111,7 +111,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tc let body = cx.tcx.hir().body(body_id); let mut fpu = FindExpectUnwrap { lcx: cx, - typeck_results: cx.tcx.typeck(impl_item.def_id), + typeck_results: cx.tcx.typeck(impl_item.def_id.def_id), result: Vec::new(), }; fpu.visit_expr(body.value); diff --git a/src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs b/src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs index 02bf09ed506..2c71f35d490 100644 --- a/src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs +++ b/src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs @@ -105,7 +105,7 @@ impl LateLintPass<'_> for UpperCaseAcronyms { fn check_item(&mut self, cx: &LateContext<'_>, it: &Item<'_>) { // do not lint public items or in macros if in_external_macro(cx.sess(), it.span) - || (self.avoid_breaking_exported_api && cx.access_levels.is_exported(it.def_id)) + || (self.avoid_breaking_exported_api && cx.access_levels.is_exported(it.def_id.def_id)) { return; } diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 44ab9bca795..ce51cb693fc 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -106,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { if !is_from_proc_macro(cx, item); // expensive, should be last check then { StackItem::Check { - impl_id: item.def_id, + impl_id: item.def_id.def_id, in_body: 0, types_to_skip: std::iter::once(self_ty.hir_id).collect(), } diff --git a/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs index 4003fff27c0..1df3135c962 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/author.rs @@ -140,7 +140,7 @@ impl<'tcx> LateLintPass<'tcx> for Author { fn check_item(cx: &LateContext<'_>, hir_id: HirId) { let hir = cx.tcx.hir(); - if let Some(body_id) = hir.maybe_body_owned_by(hir_id.expect_owner()) { + if let Some(body_id) = hir.maybe_body_owned_by(hir_id.expect_owner().def_id) { check_node(cx, hir_id, |v| { v.expr(&v.bind("expr", hir.body(body_id).value)); }); diff --git a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs index 5418eca382d..2604b1ee7c5 100644 --- a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs +++ b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs @@ -120,14 +120,14 @@ impl LateLintPass<'_> for WildcardImports { if is_test_module_or_function(cx.tcx, item) { self.test_modules_deep = self.test_modules_deep.saturating_add(1); } - let module = cx.tcx.parent_module_from_def_id(item.def_id); - if cx.tcx.visibility(item.def_id) != ty::Visibility::Restricted(module.to_def_id()) { + let module = cx.tcx.parent_module_from_def_id(item.def_id.def_id); + if cx.tcx.visibility(item.def_id.def_id) != ty::Visibility::Restricted(module.to_def_id()) { return; } if_chain! { if let ItemKind::Use(use_path, UseKind::Glob) = &item.kind; if self.warn_on_all || !self.check_exceptions(item, use_path.segments); - let used_imports = cx.tcx.names_imported_by_glob_use(item.def_id); + let used_imports = cx.tcx.names_imported_by_glob_use(item.def_id.def_id); if !used_imports.is_empty(); // Already handled by `unused_imports` then { let mut applicability = Applicability::MachineApplicable; diff --git a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs index 8dc43c0e294..386f3c527f1 100644 --- a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs +++ b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs @@ -72,7 +72,7 @@ fn in_trait_impl(cx: &LateContext<'_>, hir_id: HirId) -> bool { let second_parent_id = cx .tcx .hir() - .get_parent_item(cx.tcx.hir().local_def_id_to_hir_id(parent_id)); + .get_parent_item(parent_id.into()).def_id; if let Some(Node::Item(item)) = cx.tcx.hir().find_by_def_id(second_parent_id) { if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind { return true; diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 62da850a15e..9343cf457b3 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -78,7 +78,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::unhash::UnhashMap; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_hir::hir_id::{HirIdMap, HirIdSet}; use rustc_hir::intravisit::{walk_expr, FnKind, Visitor}; use rustc_hir::LangItem::{OptionNone, ResultErr, ResultOk}; @@ -212,7 +212,7 @@ pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option< /// } /// ``` pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool { - let parent_id = cx.tcx.hir().get_parent_item(id); + let parent_id = cx.tcx.hir().get_parent_item(id).def_id; match cx.tcx.hir().get_by_def_id(parent_id) { Node::Item(&Item { kind: ItemKind::Const(..) | ItemKind::Static(..), @@ -597,8 +597,8 @@ pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, def_id: LocalDefId) -> let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id); let parent_impl = cx.tcx.hir().get_parent_item(hir_id); if_chain! { - if parent_impl != CRATE_DEF_ID; - if let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent_impl); + if parent_impl != hir::CRATE_OWNER_ID; + if let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent_impl.def_id); if let hir::ItemKind::Impl(impl_) = &item.kind; then { return impl_.of_trait.as_ref(); @@ -1104,7 +1104,7 @@ pub fn is_in_panic_handler(cx: &LateContext<'_>, e: &Expr<'_>) -> bool { /// Gets the name of the item the expression is in, if available. pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { - let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id); + let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id).def_id; match cx.tcx.hir().find_by_def_id(parent_id) { Some( Node::Item(Item { ident, .. }) @@ -1648,7 +1648,7 @@ pub fn any_parent_has_attr(tcx: TyCtxt<'_>, node: HirId, symbol: Symbol) -> bool return true; } prev_enclosing_node = Some(enclosing_node); - enclosing_node = map.local_def_id_to_hir_id(map.get_parent_item(enclosing_node)); + enclosing_node = map.get_parent_item(enclosing_node).into(); } false diff --git a/src/tools/clippy/clippy_utils/src/usage.rs b/src/tools/clippy/clippy_utils/src/usage.rs index 3af5dfb62f9..a7c08839f52 100644 --- a/src/tools/clippy/clippy_utils/src/usage.rs +++ b/src/tools/clippy/clippy_utils/src/usage.rs @@ -21,7 +21,7 @@ pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> ExprUseVisitor::new( &mut delegate, &infcx, - expr.hir_id.owner, + expr.hir_id.owner.def_id, cx.param_env, cx.typeck_results(), ) -- cgit 1.4.1-3-g733a5 From 93a0fb190e9a781a36f9ab2faf02f2e3dc303234 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Sun, 11 Sep 2022 21:10:53 -0500 Subject: Move `DepKindStruct` from rustc_middle to rustc_query_system --- compiler/rustc_middle/src/dep_graph/dep_node.rs | 61 ---------------------- compiler/rustc_middle/src/dep_graph/mod.rs | 4 +- .../rustc_query_system/src/dep_graph/dep_node.rs | 61 ++++++++++++++++++++++ compiler/rustc_query_system/src/dep_graph/mod.rs | 2 +- 4 files changed, 65 insertions(+), 63 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index ac106764c02..32dacc25dcb 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -69,67 +69,6 @@ use std::hash::Hash; pub use rustc_query_system::dep_graph::{DepContext, DepNodeParams}; -/// This struct stores metadata about each DepKind. -/// -/// Information is retrieved by indexing the `DEP_KINDS` array using the integer value -/// of the `DepKind`. Overall, this allows to implement `DepContext` using this manual -/// jump table instead of large matches. -pub struct DepKindStruct<'tcx> { - /// Anonymous queries cannot be replayed from one compiler invocation to the next. - /// When their result is needed, it is recomputed. They are useful for fine-grained - /// dependency tracking, and caching within one compiler invocation. - pub is_anon: bool, - - /// Eval-always queries do not track their dependencies, and are always recomputed, even if - /// their inputs have not changed since the last compiler invocation. The result is still - /// cached within one compiler invocation. - pub is_eval_always: bool, - - /// Whether the query key can be recovered from the hashed fingerprint. - /// See [DepNodeParams] trait for the behaviour of each key type. - pub fingerprint_style: FingerprintStyle, - - /// The red/green evaluation system will try to mark a specific DepNode in the - /// dependency graph as green by recursively trying to mark the dependencies of - /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode` - /// where we don't know if it is red or green and we therefore actually have - /// to recompute its value in order to find out. Since the only piece of - /// information that we have at that point is the `DepNode` we are trying to - /// re-evaluate, we need some way to re-run a query from just that. This is what - /// `force_from_dep_node()` implements. - /// - /// In the general case, a `DepNode` consists of a `DepKind` and an opaque - /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint - /// is usually constructed by computing a stable hash of the query-key that the - /// `DepNode` corresponds to. Consequently, it is not in general possible to go - /// back from hash to query-key (since hash functions are not reversible). For - /// this reason `force_from_dep_node()` is expected to fail from time to time - /// because we just cannot find out, from the `DepNode` alone, what the - /// corresponding query-key is and therefore cannot re-run the query. - /// - /// The system deals with this case letting `try_mark_green` fail which forces - /// the root query to be re-evaluated. - /// - /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless. - /// Fortunately, we can use some contextual information that will allow us to - /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we - /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a - /// valid `DefPathHash`. Since we also always build a huge table that maps every - /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have - /// everything we need to re-run the query. - /// - /// Take the `mir_promoted` query as an example. Like many other queries, it - /// just has a single parameter: the `DefId` of the item it will compute the - /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode` - /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode` - /// is actually a `DefPathHash`, and can therefore just look up the corresponding - /// `DefId` in `tcx.def_path_hash_to_def_id`. - pub force_from_dep_node: Option, dep_node: DepNode) -> bool>, - - /// Invoke a query to put the on-disk cached value in memory. - pub try_load_from_on_disk_cache: Option, DepNode)>, -} - impl DepKind { #[inline(always)] pub fn fingerprint_style(self, tcx: TyCtxt<'_>) -> FingerprintStyle { diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index c8b3b52b0fb..0e9955e2972 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -11,15 +11,17 @@ pub use rustc_query_system::dep_graph::{ SerializedDepNodeIndex, WorkProduct, WorkProductId, }; -pub use dep_node::{label_strs, DepKind, DepKindStruct, DepNode, DepNodeExt}; +pub use dep_node::{label_strs, DepKind, DepNode, DepNodeExt}; pub(crate) use dep_node::{make_compile_codegen_unit, make_compile_mono_item}; pub type DepGraph = rustc_query_system::dep_graph::DepGraph; + pub type TaskDeps = rustc_query_system::dep_graph::TaskDeps; pub type TaskDepsRef<'a> = rustc_query_system::dep_graph::TaskDepsRef<'a, DepKind>; pub type DepGraphQuery = rustc_query_system::dep_graph::DepGraphQuery; pub type SerializedDepGraph = rustc_query_system::dep_graph::SerializedDepGraph; pub type EdgeFilter = rustc_query_system::dep_graph::debug::EdgeFilter; +pub type DepKindStruct<'tcx> = rustc_query_system::dep_graph::DepKindStruct>; impl rustc_query_system::dep_graph::DepKind for DepKind { const NULL: Self = DepKind::Null; diff --git a/compiler/rustc_query_system/src/dep_graph/dep_node.rs b/compiler/rustc_query_system/src/dep_graph/dep_node.rs index 162c274d8a2..2a3657780ec 100644 --- a/compiler/rustc_query_system/src/dep_graph/dep_node.rs +++ b/compiler/rustc_query_system/src/dep_graph/dep_node.rs @@ -149,6 +149,67 @@ where } } +/// This struct stores metadata about each DepKind. +/// +/// Information is retrieved by indexing the `DEP_KINDS` array using the integer value +/// of the `DepKind`. Overall, this allows to implement `DepContext` using this manual +/// jump table instead of large matches. +pub struct DepKindStruct { + /// Anonymous queries cannot be replayed from one compiler invocation to the next. + /// When their result is needed, it is recomputed. They are useful for fine-grained + /// dependency tracking, and caching within one compiler invocation. + pub is_anon: bool, + + /// Eval-always queries do not track their dependencies, and are always recomputed, even if + /// their inputs have not changed since the last compiler invocation. The result is still + /// cached within one compiler invocation. + pub is_eval_always: bool, + + /// Whether the query key can be recovered from the hashed fingerprint. + /// See [DepNodeParams] trait for the behaviour of each key type. + pub fingerprint_style: FingerprintStyle, + + /// The red/green evaluation system will try to mark a specific DepNode in the + /// dependency graph as green by recursively trying to mark the dependencies of + /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode` + /// where we don't know if it is red or green and we therefore actually have + /// to recompute its value in order to find out. Since the only piece of + /// information that we have at that point is the `DepNode` we are trying to + /// re-evaluate, we need some way to re-run a query from just that. This is what + /// `force_from_dep_node()` implements. + /// + /// In the general case, a `DepNode` consists of a `DepKind` and an opaque + /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint + /// is usually constructed by computing a stable hash of the query-key that the + /// `DepNode` corresponds to. Consequently, it is not in general possible to go + /// back from hash to query-key (since hash functions are not reversible). For + /// this reason `force_from_dep_node()` is expected to fail from time to time + /// because we just cannot find out, from the `DepNode` alone, what the + /// corresponding query-key is and therefore cannot re-run the query. + /// + /// The system deals with this case letting `try_mark_green` fail which forces + /// the root query to be re-evaluated. + /// + /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless. + /// Fortunately, we can use some contextual information that will allow us to + /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we + /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a + /// valid `DefPathHash`. Since we also always build a huge table that maps every + /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have + /// everything we need to re-run the query. + /// + /// Take the `mir_promoted` query as an example. Like many other queries, it + /// just has a single parameter: the `DefId` of the item it will compute the + /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode` + /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode` + /// is actually a `DefPathHash`, and can therefore just look up the corresponding + /// `DefId` in `tcx.def_path_hash_to_def_id`. + pub force_from_dep_node: Option) -> bool>, + + /// Invoke a query to put the on-disk cached value in memory. + pub try_load_from_on_disk_cache: Option)>, +} + /// A "work product" corresponds to a `.o` (or other) file that we /// save in between runs. These IDs do not have a `DefId` but rather /// some independent path or string that persists between runs without diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index 342d95ca490..2b62a9ee42a 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -4,7 +4,7 @@ mod graph; mod query; mod serialized; -pub use dep_node::{DepNode, DepNodeParams, WorkProductId}; +pub use dep_node::{DepKindStruct, DepNode, DepNodeParams, WorkProductId}; pub use graph::{ hash_result, DepGraph, DepNodeColor, DepNodeIndex, TaskDeps, TaskDepsRef, WorkProduct, }; -- cgit 1.4.1-3-g733a5 From f3f91bb51477084cdff194d8908053844fc6d9ea Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Sun, 11 Sep 2022 23:18:08 -0500 Subject: Move functions on `DepKindStruct` from rustc_middle to rustc_query_system --- compiler/rustc_middle/src/dep_graph/dep_node.rs | 18 ++------ compiler/rustc_middle/src/dep_graph/mod.rs | 52 +++------------------ compiler/rustc_middle/src/ty/context.rs | 8 +--- compiler/rustc_query_system/src/dep_graph/mod.rs | 57 +++++++++++++++++++++--- 4 files changed, 64 insertions(+), 71 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 32dacc25dcb..9b5b688d98a 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -69,18 +69,6 @@ use std::hash::Hash; pub use rustc_query_system::dep_graph::{DepContext, DepNodeParams}; -impl DepKind { - #[inline(always)] - pub fn fingerprint_style(self, tcx: TyCtxt<'_>) -> FingerprintStyle { - // Only fetch the DepKindStruct once. - let data = tcx.query_kind(self); - if data.is_anon { - return FingerprintStyle::Opaque; - } - data.fingerprint_style - } -} - macro_rules! define_dep_nodes { ( $($(#[$attr:meta])* @@ -186,7 +174,7 @@ impl DepNodeExt for DepNode { /// method will assert that the given DepKind actually requires a /// single DefId/DefPathHash parameter. fn from_def_path_hash(tcx: TyCtxt<'_>, def_path_hash: DefPathHash, kind: DepKind) -> DepNode { - debug_assert!(kind.fingerprint_style(tcx) == FingerprintStyle::DefPathHash); + debug_assert!(tcx.fingerprint_style(kind) == FingerprintStyle::DefPathHash); DepNode { kind, hash: def_path_hash.0.into() } } @@ -201,7 +189,7 @@ impl DepNodeExt for DepNode { /// refers to something from the previous compilation session that /// has been removed. fn extract_def_id<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Option { - if self.kind.fingerprint_style(tcx) == FingerprintStyle::DefPathHash { + if tcx.fingerprint_style(self.kind) == FingerprintStyle::DefPathHash { Some(tcx.def_path_hash_to_def_id(DefPathHash(self.hash.into()), &mut || { panic!("Failed to extract DefId: {:?} {}", self.kind, self.hash) })) @@ -218,7 +206,7 @@ impl DepNodeExt for DepNode { ) -> Result { let kind = dep_kind_from_label_string(label)?; - match kind.fingerprint_style(tcx) { + match tcx.fingerprint_style(kind) { FingerprintStyle::Opaque => Err(()), FingerprintStyle::Unit => Ok(DepNode::new_no_params(tcx, kind)), FingerprintStyle::DefPathHash => { diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index 0e9955e2972..6226fdd923a 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -27,6 +27,10 @@ impl rustc_query_system::dep_graph::DepKind for DepKind { const NULL: Self = DepKind::Null; const RED: Self = DepKind::Red; + fn is_codegen_unit_query(self) -> bool { + self == DepKind::codegen_unit + } + fn debug_node(node: &DepNode, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}(", node.kind)?; @@ -93,50 +97,8 @@ impl<'tcx> DepContext for TyCtxt<'tcx> { self.sess } - #[inline(always)] - fn fingerprint_style(&self, kind: DepKind) -> rustc_query_system::dep_graph::FingerprintStyle { - kind.fingerprint_style(*self) - } - - #[inline(always)] - fn is_eval_always(&self, kind: DepKind) -> bool { - self.query_kind(kind).is_eval_always - } - - fn try_force_from_dep_node(&self, dep_node: DepNode) -> bool { - debug!("try_force_from_dep_node({:?}) --- trying to force", dep_node); - - // We must avoid ever having to call `force_from_dep_node()` for a - // `DepNode::codegen_unit`: - // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we - // would always end up having to evaluate the first caller of the - // `codegen_unit` query that *is* reconstructible. This might very well be - // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just - // to re-trigger calling the `codegen_unit` query with the right key. At - // that point we would already have re-done all the work we are trying to - // avoid doing in the first place. - // The solution is simple: Just explicitly call the `codegen_unit` query for - // each CGU, right after partitioning. This way `try_mark_green` will always - // hit the cache instead of having to go through `force_from_dep_node`. - // This assertion makes sure, we actually keep applying the solution above. - debug_assert!( - dep_node.kind != DepKind::codegen_unit, - "calling force_from_dep_node() on DepKind::codegen_unit" - ); - - let cb = self.query_kind(dep_node.kind); - if let Some(f) = cb.force_from_dep_node { - f(*self, dep_node); - true - } else { - false - } - } - - fn try_load_from_on_disk_cache(&self, dep_node: DepNode) { - let cb = self.query_kind(dep_node.kind); - if let Some(f) = cb.try_load_from_on_disk_cache { - f(*self, dep_node) - } + #[inline] + fn dep_kind_info(&self, dep_kind: DepKind) -> &DepKindStruct<'tcx> { + &self.query_kinds[dep_kind as usize] } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 69bb9bb6fe0..e430c327efe 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1,7 +1,7 @@ //! Type context book-keeping. use crate::arena::Arena; -use crate::dep_graph::{DepGraph, DepKind, DepKindStruct}; +use crate::dep_graph::{DepGraph, DepKindStruct}; use crate::hir::place::Place as HirPlace; use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos}; use crate::lint::{struct_lint_level, LintLevelSource}; @@ -1085,7 +1085,7 @@ pub struct GlobalCtxt<'tcx> { pub queries: &'tcx dyn query::QueryEngine<'tcx>, pub query_caches: query::QueryCaches<'tcx>, - query_kinds: &'tcx [DepKindStruct<'tcx>], + pub(crate) query_kinds: &'tcx [DepKindStruct<'tcx>], // Internal caches for metadata decoding. No need to track deps on this. pub ty_rcache: Lock>>, @@ -1292,10 +1292,6 @@ impl<'tcx> TyCtxt<'tcx> { } } - pub(crate) fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct<'tcx> { - &self.query_kinds[k as usize] - } - /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. #[track_caller] pub fn ty_error(self) -> Ty<'tcx> { diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index 2b62a9ee42a..a5c27479126 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -34,16 +34,61 @@ pub trait DepContext: Copy { /// Access the compiler session. fn sess(&self) -> &Session; - /// Return whether this kind always require evaluation. - fn is_eval_always(&self, kind: Self::DepKind) -> bool; + fn dep_kind_info(&self, dep_node: Self::DepKind) -> &DepKindStruct; + + #[inline(always)] + fn fingerprint_style(&self, kind: Self::DepKind) -> FingerprintStyle { + let data = self.dep_kind_info(kind); + if data.is_anon { + return FingerprintStyle::Opaque; + } + data.fingerprint_style + } - fn fingerprint_style(&self, kind: Self::DepKind) -> FingerprintStyle; + #[inline(always)] + /// Return whether this kind always require evaluation. + fn is_eval_always(&self, kind: Self::DepKind) -> bool { + self.dep_kind_info(kind).is_eval_always + } /// Try to force a dep node to execute and see if it's green. - fn try_force_from_dep_node(&self, dep_node: DepNode) -> bool; + fn try_force_from_dep_node(self, dep_node: DepNode) -> bool { + debug!("try_force_from_dep_node({:?}) --- trying to force", dep_node); + + // We must avoid ever having to call `force_from_dep_node()` for a + // `DepNode::codegen_unit`: + // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we + // would always end up having to evaluate the first caller of the + // `codegen_unit` query that *is* reconstructible. This might very well be + // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just + // to re-trigger calling the `codegen_unit` query with the right key. At + // that point we would already have re-done all the work we are trying to + // avoid doing in the first place. + // The solution is simple: Just explicitly call the `codegen_unit` query for + // each CGU, right after partitioning. This way `try_mark_green` will always + // hit the cache instead of having to go through `force_from_dep_node`. + // This assertion makes sure, we actually keep applying the solution above. + debug_assert!( + !dep_node.kind.is_codegen_unit_query(), + "calling force_from_dep_node() on DepKind::codegen_unit" + ); + + let cb = self.dep_kind_info(dep_node.kind); + if let Some(f) = cb.force_from_dep_node { + f(self, dep_node); + true + } else { + false + } + } /// Load data from the on-disk cache. - fn try_load_from_on_disk_cache(&self, dep_node: DepNode); + fn try_load_from_on_disk_cache(self, dep_node: DepNode) { + let cb = self.dep_kind_info(dep_node.kind); + if let Some(f) = cb.try_load_from_on_disk_cache { + f(self, dep_node) + } + } } pub trait HasDepContext: Copy { @@ -91,6 +136,8 @@ pub trait DepKind: Copy + fmt::Debug + Eq + Hash + Send + Encodable /// DepKind to use to create the initial forever-red node. const RED: Self; + fn is_codegen_unit_query(self) -> bool; + /// Implementation of `std::fmt::Debug` for `DepNode`. fn debug_node(node: &DepNode, f: &mut fmt::Formatter<'_>) -> fmt::Result; -- cgit 1.4.1-3-g733a5 From ccc8d000f2281efc17f9329214116aedada088a5 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Sun, 11 Sep 2022 23:31:50 -0500 Subject: Move some more code from rustc_middle to rustc_query_system --- compiler/rustc_middle/src/dep_graph/dep_node.rs | 15 +-------------- compiler/rustc_query_system/src/dep_graph/dep_node.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 14 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 9b5b688d98a..40b9d73db94 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -86,7 +86,7 @@ macro_rules! define_dep_nodes { $( $( #[$attr] )* $variant),* } - fn dep_kind_from_label_string(label: &str) -> Result { + pub(super) fn dep_kind_from_label_string(label: &str) -> Result { match label { $(stringify!($variant) => Ok(DepKind::$variant),)* _ => Err(()), @@ -141,11 +141,6 @@ static_assert_size!(DepNode, 18); static_assert_size!(DepNode, 24); pub trait DepNodeExt: Sized { - /// Construct a DepNode from the given DepKind and DefPathHash. This - /// method will assert that the given DepKind actually requires a - /// single DefId/DefPathHash parameter. - fn from_def_path_hash(tcx: TyCtxt<'_>, def_path_hash: DefPathHash, kind: DepKind) -> Self; - /// Extracts the DefId corresponding to this DepNode. This will work /// if two conditions are met: /// @@ -170,14 +165,6 @@ pub trait DepNodeExt: Sized { } impl DepNodeExt for DepNode { - /// Construct a DepNode from the given DepKind and DefPathHash. This - /// method will assert that the given DepKind actually requires a - /// single DefId/DefPathHash parameter. - fn from_def_path_hash(tcx: TyCtxt<'_>, def_path_hash: DefPathHash, kind: DepKind) -> DepNode { - debug_assert!(tcx.fingerprint_style(kind) == FingerprintStyle::DefPathHash); - DepNode { kind, hash: def_path_hash.0.into() } - } - /// Extracts the DefId corresponding to this DepNode. This will work /// if two conditions are met: /// diff --git a/compiler/rustc_query_system/src/dep_graph/dep_node.rs b/compiler/rustc_query_system/src/dep_graph/dep_node.rs index 2a3657780ec..5c6ce0556eb 100644 --- a/compiler/rustc_query_system/src/dep_graph/dep_node.rs +++ b/compiler/rustc_query_system/src/dep_graph/dep_node.rs @@ -47,6 +47,7 @@ use crate::ich::StableHashingContext; use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_hir::definitions::DefPathHash; use std::fmt; use std::hash::Hash; @@ -88,6 +89,17 @@ impl DepNode { dep_node } + + /// Construct a DepNode from the given DepKind and DefPathHash. This + /// method will assert that the given DepKind actually requires a + /// single DefId/DefPathHash parameter. + pub fn from_def_path_hash(tcx: Ctxt, def_path_hash: DefPathHash, kind: K) -> Self + where + Ctxt: super::DepContext, + { + debug_assert!(tcx.fingerprint_style(kind) == FingerprintStyle::DefPathHash); + DepNode { kind, hash: def_path_hash.0.into() } + } } impl fmt::Debug for DepNode { -- cgit 1.4.1-3-g733a5 From 00cde6d4b94bba23ad06b352bc589805574f62b2 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Sun, 18 Sep 2022 16:35:48 -0500 Subject: Move the `codegen_unit` debug assert from `rustc_query_system` to `query_impl` This allows removing a function from the `DepKind` trait. --- compiler/rustc_middle/src/dep_graph/mod.rs | 4 ---- compiler/rustc_query_impl/src/plumbing.rs | 18 ++++++++++++++++++ compiler/rustc_query_system/src/dep_graph/mod.rs | 20 -------------------- 3 files changed, 18 insertions(+), 24 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index 6226fdd923a..2e62bebc852 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -27,10 +27,6 @@ impl rustc_query_system::dep_graph::DepKind for DepKind { const NULL: Self = DepKind::Null; const RED: Self = DepKind::Red; - fn is_codegen_unit_query(self) -> bool { - self == DepKind::codegen_unit - } - fn debug_node(node: &DepNode, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}(", node.kind)?; diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index d819f4774d5..ac95c8edf3f 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -380,6 +380,24 @@ where Q::Key: DepNodeParams>, Q::Value: Value>, { + // We must avoid ever having to call `force_from_dep_node()` for a + // `DepNode::codegen_unit`: + // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we + // would always end up having to evaluate the first caller of the + // `codegen_unit` query that *is* reconstructible. This might very well be + // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just + // to re-trigger calling the `codegen_unit` query with the right key. At + // that point we would already have re-done all the work we are trying to + // avoid doing in the first place. + // The solution is simple: Just explicitly call the `codegen_unit` query for + // each CGU, right after partitioning. This way `try_mark_green` will always + // hit the cache instead of having to go through `force_from_dep_node`. + // This assertion makes sure, we actually keep applying the solution above. + debug_assert!( + dep_node.kind != DepKind::codegen_unit, + "calling force_from_dep_node() on DepKind::codegen_unit" + ); + if let Some(key) = Q::Key::recover(tcx, &dep_node) { #[cfg(debug_assertions)] let _guard = tracing::span!(tracing::Level::TRACE, stringify!($name), ?key).entered(); diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index a5c27479126..5003a14b910 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -55,24 +55,6 @@ pub trait DepContext: Copy { fn try_force_from_dep_node(self, dep_node: DepNode) -> bool { debug!("try_force_from_dep_node({:?}) --- trying to force", dep_node); - // We must avoid ever having to call `force_from_dep_node()` for a - // `DepNode::codegen_unit`: - // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we - // would always end up having to evaluate the first caller of the - // `codegen_unit` query that *is* reconstructible. This might very well be - // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just - // to re-trigger calling the `codegen_unit` query with the right key. At - // that point we would already have re-done all the work we are trying to - // avoid doing in the first place. - // The solution is simple: Just explicitly call the `codegen_unit` query for - // each CGU, right after partitioning. This way `try_mark_green` will always - // hit the cache instead of having to go through `force_from_dep_node`. - // This assertion makes sure, we actually keep applying the solution above. - debug_assert!( - !dep_node.kind.is_codegen_unit_query(), - "calling force_from_dep_node() on DepKind::codegen_unit" - ); - let cb = self.dep_kind_info(dep_node.kind); if let Some(f) = cb.force_from_dep_node { f(self, dep_node); @@ -136,8 +118,6 @@ pub trait DepKind: Copy + fmt::Debug + Eq + Hash + Send + Encodable /// DepKind to use to create the initial forever-red node. const RED: Self; - fn is_codegen_unit_query(self) -> bool; - /// Implementation of `std::fmt::Debug` for `DepNode`. fn debug_node(node: &DepNode, f: &mut fmt::Formatter<'_>) -> fmt::Result; -- cgit 1.4.1-3-g733a5 From 3975d55d9888392cd738708b914442de9ac2bff5 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Tue, 20 Sep 2022 15:41:42 +0200 Subject: remove cfg(bootstrap) --- compiler/rustc_ast/src/ast.rs | 1 - compiler/rustc_ast/src/lib.rs | 2 - compiler/rustc_ast_lowering/src/lib.rs | 1 - compiler/rustc_ast_passes/src/lib.rs | 1 - compiler/rustc_attr/src/lib.rs | 1 - compiler/rustc_borrowck/src/lib.rs | 1 - compiler/rustc_builtin_macros/src/lib.rs | 1 - compiler/rustc_codegen_llvm/src/lib.rs | 1 - compiler/rustc_codegen_ssa/src/lib.rs | 1 - compiler/rustc_const_eval/src/interpret/operand.rs | 2 +- compiler/rustc_const_eval/src/interpret/place.rs | 2 - compiler/rustc_const_eval/src/lib.rs | 1 - compiler/rustc_data_structures/src/lib.rs | 1 - compiler/rustc_driver/src/lib.rs | 1 - compiler/rustc_errors/src/lib.rs | 3 +- compiler/rustc_expand/src/lib.rs | 1 - compiler/rustc_hir/src/hir.rs | 5 - compiler/rustc_hir/src/lib.rs | 1 - compiler/rustc_incremental/src/lib.rs | 1 - compiler/rustc_index/src/lib.rs | 1 - compiler/rustc_infer/src/lib.rs | 2 - compiler/rustc_interface/src/lib.rs | 1 - compiler/rustc_lint/src/lib.rs | 2 +- compiler/rustc_macros/src/lib.rs | 1 - compiler/rustc_metadata/src/lib.rs | 2 - compiler/rustc_middle/src/lib.rs | 2 - compiler/rustc_middle/src/mir/syntax.rs | 1 - compiler/rustc_middle/src/thir.rs | 4 - compiler/rustc_mir_build/src/lib.rs | 1 - compiler/rustc_mir_dataflow/src/lib.rs | 1 - compiler/rustc_mir_transform/src/lib.rs | 1 - compiler/rustc_monomorphize/src/lib.rs | 1 - compiler/rustc_parse/src/lib.rs | 1 - compiler/rustc_passes/src/lib.rs | 1 - compiler/rustc_privacy/src/lib.rs | 1 - compiler/rustc_query_system/src/lib.rs | 1 - compiler/rustc_resolve/src/lib.rs | 1 - compiler/rustc_save_analysis/src/lib.rs | 1 - compiler/rustc_serialize/src/lib.rs | 1 - compiler/rustc_session/src/lib.rs | 1 - compiler/rustc_span/src/lib.rs | 1 - compiler/rustc_target/src/lib.rs | 1 - compiler/rustc_trait_selection/src/lib.rs | 2 - compiler/rustc_traits/src/lib.rs | 1 - compiler/rustc_ty_utils/src/lib.rs | 1 - compiler/rustc_typeck/src/lib.rs | 2 - library/alloc/src/boxed.rs | 14 - library/alloc/src/boxed/thin.rs | 2 - library/alloc/src/collections/btree/map/entry.rs | 1 - library/alloc/src/collections/mod.rs | 1 - library/alloc/src/ffi/c_str.rs | 3 - library/alloc/src/lib.rs | 7 +- library/alloc/src/string.rs | 3 - library/alloc/src/sync.rs | 1 - library/core/src/alloc/layout.rs | 2 - library/core/src/alloc/mod.rs | 2 - library/core/src/array/mod.rs | 2 - library/core/src/char/decode.rs | 2 - library/core/src/char/mod.rs | 2 - library/core/src/convert/mod.rs | 2 - library/core/src/intrinsics.rs | 65 -- library/core/src/lib.rs | 1 - library/core/src/marker.rs | 2 +- library/core/src/mem/transmutability.rs | 4 +- library/core/src/num/error.rs | 3 - library/core/src/num/mod.rs | 2 - library/core/src/ops/generator.rs | 1 - library/core/src/ops/try_trait.rs | 84 +- library/core/src/ptr/const_ptr.rs | 1 - library/core/src/ptr/mut_ptr.rs | 1 - library/core/src/str/error.rs | 3 - library/core/src/str/mod.rs | 1 - library/std/src/collections/hash/map.rs | 2 - library/std/src/error.rs | 1023 -------------------- library/std/src/io/error.rs | 1 - library/std/src/lib.rs | 8 +- library/std/src/rt.rs | 5 +- src/librustdoc/clean/types.rs | 1 - src/librustdoc/lib.rs | 2 - src/test/mir-opt/issue-101867.rs | 1 - src/test/ui/let-else/const-fn.rs | 1 - src/tools/clippy/clippy_dev/src/lib.rs | 1 - src/tools/clippy/clippy_lints/src/lib.rs | 1 - src/tools/clippy/clippy_utils/src/lib.rs | 1 - 84 files changed, 15 insertions(+), 1308 deletions(-) (limited to 'compiler/rustc_query_system') diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 6c514c75a50..0efde1e7b21 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -3046,7 +3046,6 @@ mod size_asserts { static_assert_size!(Block, 48); static_assert_size!(Expr, 104); static_assert_size!(ExprKind, 72); - #[cfg(not(bootstrap))] static_assert_size!(Fn, 184); static_assert_size!(ForeignItem, 96); static_assert_size!(ForeignItemKind, 24); diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index bd7a85b07a0..eeb7e56e2b1 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -13,9 +13,7 @@ #![feature(const_default_impls)] #![feature(const_trait_impl)] #![feature(if_let_guard)] -#![cfg_attr(bootstrap, feature(label_break_value))] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(negative_impls)] #![feature(slice_internals)] diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 186c10065f3..275ceed30d7 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -32,7 +32,6 @@ #![feature(box_patterns)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_ast_passes/src/lib.rs b/compiler/rustc_ast_passes/src/lib.rs index 8aa9d57f046..f58fffc9172 100644 --- a/compiler/rustc_ast_passes/src/lib.rs +++ b/compiler/rustc_ast_passes/src/lib.rs @@ -9,7 +9,6 @@ #![feature(if_let_guard)] #![feature(iter_is_partitioned)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #[macro_use] diff --git a/compiler/rustc_attr/src/lib.rs b/compiler/rustc_attr/src/lib.rs index 52e65a9c774..4580ffcc6d8 100644 --- a/compiler/rustc_attr/src/lib.rs +++ b/compiler/rustc_attr/src/lib.rs @@ -5,7 +5,6 @@ //! to this crate. #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 6b90f2daeea..a83840e1099 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -3,7 +3,6 @@ #![allow(rustc::potential_query_instability)] #![feature(box_patterns)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(rustc_attrs)] diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs index 8aeb3b82a9c..0de27d3d407 100644 --- a/compiler/rustc_builtin_macros/src/lib.rs +++ b/compiler/rustc_builtin_macros/src/lib.rs @@ -9,7 +9,6 @@ #![feature(if_let_guard)] #![feature(is_sorted)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(proc_macro_internals)] #![feature(proc_macro_quote)] #![recursion_limit = "256"] diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 42c65e04e3b..15bfa843046 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -7,7 +7,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(hash_raw_entry)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(extern_types)] #![feature(once_cell)] #![feature(iter_intersperse)] diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs index e736b2aba9c..3ef9a634e18 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -1,7 +1,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(box_patterns)] #![feature(try_blocks)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(associated_type_bounds)] #![feature(strict_provenance)] diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index dc5305aabcf..510adde6296 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -784,7 +784,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } // Some nodes are used a lot. Make sure they don't unintentionally get bigger. -#[cfg(all(target_arch = "x86_64", target_pointer_width = "64", not(bootstrap)))] +#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] mod size_asserts { use super::*; use rustc_data_structures::static_assert_size; diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index bc1aa43b73a..7a01b85381a 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -890,8 +890,6 @@ mod size_asserts { static_assert_size!(MemPlaceMeta, 24); static_assert_size!(MemPlace, 40); static_assert_size!(MPlaceTy<'_>, 64); - #[cfg(not(bootstrap))] static_assert_size!(Place, 40); - #[cfg(not(bootstrap))] static_assert_size!(PlaceTy<'_>, 64); } diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index 9f47d302a0c..7c4c7db1035 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -10,7 +10,6 @@ Rust MIR: a lowered representation of Rust. #![feature(decl_macro)] #![feature(exact_size_is_empty)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(map_try_insert)] #![feature(min_specialization)] #![feature(slice_ptr_get)] diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index 56f7823efe0..467ac401d08 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -13,7 +13,6 @@ #![feature(cell_leak)] #![feature(control_flow_enum)] #![feature(extend_one)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(hash_raw_entry)] #![feature(hasher_prefixfree_extras)] #![feature(maybe_uninit_uninit_array)] diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index c768935eb62..fcd49f5d015 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -5,7 +5,6 @@ //! This API is completely unstable and subject to change. #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index b44cf352233..4d262ae0f5e 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -7,7 +7,6 @@ #![feature(if_let_guard)] #![feature(adt_const_params)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![feature(result_option_inspect)] #![feature(rustc_attrs)] @@ -69,7 +68,7 @@ pub type PResult<'a, T> = Result>; // (See also the comment on `DiagnosticBuilder`'s `diagnostic` field.) #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16); -#[cfg(all(target_arch = "x86_64", target_pointer_width = "64", not(bootstrap)))] +#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16); #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)] diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index ffc9abe64d2..b34de94fb7d 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -3,7 +3,6 @@ #![feature(associated_type_defaults)] #![feature(if_let_guard)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(macro_metavar_expr)] #![feature(proc_macro_diagnostic)] #![feature(proc_macro_internals)] diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 018b7cc5d9d..c1948052e3c 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3520,14 +3520,11 @@ mod size_asserts { static_assert_size!(FnDecl<'_>, 40); static_assert_size!(ForeignItem<'_>, 72); static_assert_size!(ForeignItemKind<'_>, 40); - #[cfg(not(bootstrap))] static_assert_size!(GenericArg<'_>, 24); static_assert_size!(GenericBound<'_>, 48); static_assert_size!(Generics<'_>, 56); static_assert_size!(Impl<'_>, 80); - #[cfg(not(bootstrap))] static_assert_size!(ImplItem<'_>, 80); - #[cfg(not(bootstrap))] static_assert_size!(ImplItemKind<'_>, 32); static_assert_size!(Item<'_>, 80); static_assert_size!(ItemKind<'_>, 48); @@ -3540,9 +3537,7 @@ mod size_asserts { static_assert_size!(QPath<'_>, 24); static_assert_size!(Stmt<'_>, 32); static_assert_size!(StmtKind<'_>, 16); - #[cfg(not(bootstrap))] static_assert_size!(TraitItem<'_>, 88); - #[cfg(not(bootstrap))] static_assert_size!(TraitItemKind<'_>, 48); static_assert_size!(Ty<'_>, 48); static_assert_size!(TyKind<'_>, 32); diff --git a/compiler/rustc_hir/src/lib.rs b/compiler/rustc_hir/src/lib.rs index 556ff1cc48e..1c4aa420c9b 100644 --- a/compiler/rustc_hir/src/lib.rs +++ b/compiler/rustc_hir/src/lib.rs @@ -5,7 +5,6 @@ #![feature(associated_type_defaults)] #![feature(closure_track_caller)] #![feature(const_btree_len)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(min_specialization)] #![feature(never_type)] diff --git a/compiler/rustc_incremental/src/lib.rs b/compiler/rustc_incremental/src/lib.rs index 2c9e21f769f..83dd9a67e61 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -2,7 +2,6 @@ #![deny(missing_docs)] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] -#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_index/src/lib.rs b/compiler/rustc_index/src/lib.rs index a00d7bd6801..9753fb35530 100644 --- a/compiler/rustc_index/src/lib.rs +++ b/compiler/rustc_index/src/lib.rs @@ -3,7 +3,6 @@ #![feature(allow_internal_unstable)] #![feature(bench_black_box)] #![feature(extend_one)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(new_uninit)] #![feature(step_trait)] diff --git a/compiler/rustc_infer/src/lib.rs b/compiler/rustc_infer/src/lib.rs index 909a597e221..b91c098ab03 100644 --- a/compiler/rustc_infer/src/lib.rs +++ b/compiler/rustc_infer/src/lib.rs @@ -17,9 +17,7 @@ #![feature(box_patterns)] #![feature(control_flow_enum)] #![feature(extend_one)] -#![cfg_attr(bootstrap, feature(label_break_value))] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(if_let_guard)] #![feature(min_specialization)] #![feature(never_type)] diff --git a/compiler/rustc_interface/src/lib.rs b/compiler/rustc_interface/src/lib.rs index 41cd7b0e9b1..a41a749ee68 100644 --- a/compiler/rustc_interface/src/lib.rs +++ b/compiler/rustc_interface/src/lib.rs @@ -1,5 +1,4 @@ #![feature(box_patterns)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(internal_output_capture)] #![feature(thread_spawn_unchecked)] #![feature(once_cell)] diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 752a751f6bc..4408f68dd63 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -34,7 +34,7 @@ #![feature(iter_intersperse)] #![feature(iter_order_by)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] +#![feature(min_specialization)] #![feature(never_type)] #![recursion_limit = "256"] diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 8fd23ee5ced..36bda3e0f6b 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -1,5 +1,4 @@ #![feature(allow_internal_unstable)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![feature(proc_macro_diagnostic)] #![feature(proc_macro_span)] diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs index 6f5604b7e11..98cf6fef54a 100644 --- a/compiler/rustc_metadata/src/lib.rs +++ b/compiler/rustc_metadata/src/lib.rs @@ -2,10 +2,8 @@ #![feature(decl_macro)] #![feature(drain_filter)] #![feature(generators)] -#![cfg_attr(bootstrap, feature(generic_associated_types))] #![feature(iter_from_generator)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(proc_macro_internals)] #![feature(macro_metavar_expr)] diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index 01b9277b983..a180706e1cf 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -31,7 +31,6 @@ #![feature(discriminant_kind)] #![feature(exhaustive_patterns)] #![feature(get_mut_unchecked)] -#![cfg_attr(bootstrap, feature(generic_associated_types))] #![feature(if_let_guard)] #![feature(map_first_last)] #![feature(negative_impls)] @@ -40,7 +39,6 @@ #![feature(new_uninit)] #![feature(once_cell)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(trusted_len)] #![feature(type_alias_impl_trait)] diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 568d63fb062..ee8377d1987 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -1242,7 +1242,6 @@ pub enum BinOp { mod size_asserts { use super::*; // These are in alphabetical order, which is easy to maintain. - #[cfg(not(bootstrap))] static_assert_size!(AggregateKind<'_>, 40); static_assert_size!(Operand<'_>, 24); static_assert_size!(Place<'_>, 16); diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 86b4150505f..84374a25ed8 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -852,12 +852,8 @@ mod size_asserts { static_assert_size!(Block, 56); static_assert_size!(Expr<'_>, 64); static_assert_size!(ExprKind<'_>, 40); - #[cfg(not(bootstrap))] static_assert_size!(Pat<'_>, 72); - #[cfg(not(bootstrap))] static_assert_size!(PatKind<'_>, 56); - #[cfg(not(bootstrap))] static_assert_size!(Stmt<'_>, 48); - #[cfg(not(bootstrap))] static_assert_size!(StmtKind<'_>, 40); } diff --git a/compiler/rustc_mir_build/src/lib.rs b/compiler/rustc_mir_build/src/lib.rs index 0c0a2fe9c9e..8236b1528c0 100644 --- a/compiler/rustc_mir_build/src/lib.rs +++ b/compiler/rustc_mir_build/src/lib.rs @@ -6,7 +6,6 @@ #![feature(control_flow_enum)] #![feature(if_let_guard)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(once_cell)] #![recursion_limit = "256"] diff --git a/compiler/rustc_mir_dataflow/src/lib.rs b/compiler/rustc_mir_dataflow/src/lib.rs index b45c32ee986..b471d04fd60 100644 --- a/compiler/rustc_mir_dataflow/src/lib.rs +++ b/compiler/rustc_mir_dataflow/src/lib.rs @@ -1,7 +1,6 @@ #![feature(associated_type_defaults)] #![feature(box_patterns)] #![feature(exact_size_is_empty)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(once_cell)] #![feature(stmt_expr_attributes)] diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index e6fc8559571..2230c3399f0 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -1,7 +1,6 @@ #![allow(rustc::potential_query_instability)] #![feature(box_patterns)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(map_try_insert)] #![feature(min_specialization)] #![feature(never_type)] diff --git a/compiler/rustc_monomorphize/src/lib.rs b/compiler/rustc_monomorphize/src/lib.rs index ba6ce9fd40f..42781bd25f0 100644 --- a/compiler/rustc_monomorphize/src/lib.rs +++ b/compiler/rustc_monomorphize/src/lib.rs @@ -1,6 +1,5 @@ #![feature(array_windows)] #![feature(control_flow_enum)] -#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] #![deny(rustc::untranslatable_diagnostic)] diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index a37327f4294..06245380927 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -4,7 +4,6 @@ #![feature(box_patterns)] #![feature(if_let_guard)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![feature(rustc_attrs)] #![recursion_limit = "256"] diff --git a/compiler/rustc_passes/src/lib.rs b/compiler/rustc_passes/src/lib.rs index 39ebb8db21c..6e621b7eb5e 100644 --- a/compiler/rustc_passes/src/lib.rs +++ b/compiler/rustc_passes/src/lib.rs @@ -8,7 +8,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(iter_intersperse)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(map_try_insert)] #![feature(min_specialization)] #![feature(try_blocks)] diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 72867447250..41d5f54b366 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1,7 +1,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(associated_type_defaults)] #![feature(control_flow_enum)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(rustc_private)] #![feature(try_blocks)] #![recursion_limit = "256"] diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index 5987651322a..8f6da73d1f2 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -1,7 +1,6 @@ #![feature(assert_matches)] #![feature(core_intrinsics)] #![feature(hash_raw_entry)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(extern_types)] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 54a7f416ce6..583030b0e50 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -12,7 +12,6 @@ #![feature(if_let_guard)] #![feature(iter_intersperse)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![recursion_limit = "256"] #![allow(rustdoc::private_intra_doc_links)] diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs index 1a3511a1dc8..ad7aca3cb94 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -1,6 +1,5 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(if_let_guard)] -#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] #![feature(never_type)] diff --git a/compiler/rustc_serialize/src/lib.rs b/compiler/rustc_serialize/src/lib.rs index fa9c7bd54c3..1f8d2336c4e 100644 --- a/compiler/rustc_serialize/src/lib.rs +++ b/compiler/rustc_serialize/src/lib.rs @@ -14,7 +14,6 @@ Core encoding and decoding interfaces. #![feature(min_specialization)] #![feature(core_intrinsics)] #![feature(maybe_uninit_slice)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(new_uninit)] #![feature(allocator_api)] #![cfg_attr(test, feature(test))] diff --git a/compiler/rustc_session/src/lib.rs b/compiler/rustc_session/src/lib.rs index f6bab775e76..39e871f532c 100644 --- a/compiler/rustc_session/src/lib.rs +++ b/compiler/rustc_session/src/lib.rs @@ -1,6 +1,5 @@ #![feature(if_let_guard)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(once_cell)] diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 366fd9d2cd1..f8df4169715 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -15,7 +15,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(array_windows)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(if_let_guard)] #![feature(negative_impls)] #![feature(min_specialization)] diff --git a/compiler/rustc_target/src/lib.rs b/compiler/rustc_target/src/lib.rs index a7deab9d2ef..aaba0d7f093 100644 --- a/compiler/rustc_target/src/lib.rs +++ b/compiler/rustc_target/src/lib.rs @@ -11,7 +11,6 @@ #![feature(assert_matches)] #![feature(associated_type_bounds)] #![feature(exhaustive_patterns)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(rustc_attrs)] diff --git a/compiler/rustc_trait_selection/src/lib.rs b/compiler/rustc_trait_selection/src/lib.rs index d35f74974fd..5d52aa07523 100644 --- a/compiler/rustc_trait_selection/src/lib.rs +++ b/compiler/rustc_trait_selection/src/lib.rs @@ -16,9 +16,7 @@ #![feature(control_flow_enum)] #![feature(drain_filter)] #![feature(hash_drain_filter)] -#![cfg_attr(bootstrap, feature(label_break_value))] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(if_let_guard)] #![feature(never_type)] #![feature(type_alias_impl_trait)] diff --git a/compiler/rustc_traits/src/lib.rs b/compiler/rustc_traits/src/lib.rs index 2d39e973ed9..0da28737f69 100644 --- a/compiler/rustc_traits/src/lib.rs +++ b/compiler/rustc_traits/src/lib.rs @@ -3,7 +3,6 @@ #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] -#![cfg_attr(bootstrap, feature(let_else))] #![recursion_limit = "256"] #[macro_use] diff --git a/compiler/rustc_ty_utils/src/lib.rs b/compiler/rustc_ty_utils/src/lib.rs index 8524e57cb58..10c18789f74 100644 --- a/compiler/rustc_ty_utils/src/lib.rs +++ b/compiler/rustc_ty_utils/src/lib.rs @@ -6,7 +6,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(control_flow_enum)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(never_type)] #![feature(box_patterns)] #![recursion_limit = "256"] diff --git a/compiler/rustc_typeck/src/lib.rs b/compiler/rustc_typeck/src/lib.rs index b1ce972e1d6..1859473166a 100644 --- a/compiler/rustc_typeck/src/lib.rs +++ b/compiler/rustc_typeck/src/lib.rs @@ -64,9 +64,7 @@ This API is completely unstable and subject to change. #![feature(if_let_guard)] #![feature(is_sorted)] #![feature(iter_intersperse)] -#![cfg_attr(bootstrap, feature(label_break_value))] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(never_type)] #![feature(once_cell)] diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 0aff1323f97..f651cb02176 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -151,7 +151,6 @@ use core::async_iter::AsyncIterator; use core::borrow; use core::cmp::Ordering; use core::convert::{From, TryFrom}; -#[cfg(not(bootstrap))] use core::error::Error; use core::fmt; use core::future::Future; @@ -176,7 +175,6 @@ use crate::borrow::Cow; use crate::raw_vec::RawVec; #[cfg(not(no_global_oom_handling))] use crate::str::from_boxed_utf8_unchecked; -#[cfg(not(bootstrap))] #[cfg(not(no_global_oom_handling))] use crate::string::String; #[cfg(not(no_global_oom_handling))] @@ -2090,7 +2088,6 @@ impl AsyncIterator for Box { } } -#[cfg(not(bootstrap))] impl dyn Error { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] @@ -2108,7 +2105,6 @@ impl dyn Error { } } -#[cfg(not(bootstrap))] impl dyn Error + Send { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] @@ -2123,7 +2119,6 @@ impl dyn Error + Send { } } -#[cfg(not(bootstrap))] impl dyn Error + Send + Sync { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] @@ -2138,7 +2133,6 @@ impl dyn Error + Send + Sync { } } -#[cfg(not(bootstrap))] #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl<'a, E: Error + 'a> From for Box { @@ -2172,7 +2166,6 @@ impl<'a, E: Error + 'a> From for Box { } } -#[cfg(not(bootstrap))] #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl<'a, E: Error + Send + Sync + 'a> From for Box { @@ -2212,7 +2205,6 @@ impl<'a, E: Error + Send + Sync + 'a> From for Box for Box { @@ -2257,7 +2249,6 @@ impl From for Box { } } -#[cfg(not(bootstrap))] #[cfg(not(no_global_oom_handling))] #[stable(feature = "string_box_error", since = "1.6.0")] impl From for Box { @@ -2280,7 +2271,6 @@ impl From for Box { } } -#[cfg(not(bootstrap))] #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl<'a> From<&str> for Box { @@ -2305,7 +2295,6 @@ impl<'a> From<&str> for Box { } } -#[cfg(not(bootstrap))] #[cfg(not(no_global_oom_handling))] #[stable(feature = "string_box_error", since = "1.6.0")] impl From<&str> for Box { @@ -2328,7 +2317,6 @@ impl From<&str> for Box { } } -#[cfg(not(bootstrap))] #[cfg(not(no_global_oom_handling))] #[stable(feature = "cow_box_error", since = "1.22.0")] impl<'a, 'b> From> for Box { @@ -2351,7 +2339,6 @@ impl<'a, 'b> From> for Box { } } -#[cfg(not(bootstrap))] #[cfg(not(no_global_oom_handling))] #[stable(feature = "cow_box_error", since = "1.22.0")] impl<'a> From> for Box { @@ -2373,7 +2360,6 @@ impl<'a> From> for Box { } } -#[cfg(not(bootstrap))] #[stable(feature = "box_error", since = "1.8.0")] impl core::error::Error for Box { #[allow(deprecated, deprecated_in_future)] diff --git a/library/alloc/src/boxed/thin.rs b/library/alloc/src/boxed/thin.rs index 0a20c74b00f..c477c44906c 100644 --- a/library/alloc/src/boxed/thin.rs +++ b/library/alloc/src/boxed/thin.rs @@ -2,7 +2,6 @@ // https://github.com/matthieu-m/rfc2580/blob/b58d1d3cba0d4b5e859d3617ea2d0943aaa31329/examples/thin.rs // by matthieu-m use crate::alloc::{self, Layout, LayoutError}; -#[cfg(not(bootstrap))] use core::error::Error; use core::fmt::{self, Debug, Display, Formatter}; use core::marker::PhantomData; @@ -274,7 +273,6 @@ impl WithHeader { } } -#[cfg(not(bootstrap))] #[unstable(feature = "thin_box", issue = "92791")] impl Error for ThinBox { fn source(&self) -> Option<&(dyn Error + 'static)> { diff --git a/library/alloc/src/collections/btree/map/entry.rs b/library/alloc/src/collections/btree/map/entry.rs index cd7cdc19207..370b58864af 100644 --- a/library/alloc/src/collections/btree/map/entry.rs +++ b/library/alloc/src/collections/btree/map/entry.rs @@ -133,7 +133,6 @@ impl<'a, K: Debug + Ord, V: Debug, A: Allocator + Clone> fmt::Display } } -#[cfg(not(bootstrap))] #[unstable(feature = "map_try_insert", issue = "82766")] impl<'a, K: core::fmt::Debug + Ord, V: core::fmt::Debug> core::error::Error for crate::collections::btree_map::OccupiedError<'a, K, V> diff --git a/library/alloc/src/collections/mod.rs b/library/alloc/src/collections/mod.rs index 21d0def0866..161a375736c 100644 --- a/library/alloc/src/collections/mod.rs +++ b/library/alloc/src/collections/mod.rs @@ -153,6 +153,5 @@ trait SpecExtend { fn spec_extend(&mut self, iter: I); } -#[cfg(not(bootstrap))] #[stable(feature = "try_reserve", since = "1.57.0")] impl core::error::Error for TryReserveError {} diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index aede6d54c6c..11bd4c4dc1b 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -1122,7 +1122,6 @@ impl CStr { } } -#[cfg(not(bootstrap))] #[stable(feature = "rust1", since = "1.0.0")] impl core::error::Error for NulError { #[allow(deprecated)] @@ -1131,11 +1130,9 @@ impl core::error::Error for NulError { } } -#[cfg(not(bootstrap))] #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")] impl core::error::Error for FromVecWithNulError {} -#[cfg(not(bootstrap))] #[stable(feature = "cstring_into", since = "1.7.0")] impl core::error::Error for IntoStringError { #[allow(deprecated)] diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index de58f22daae..7fde8f670a2 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -114,8 +114,8 @@ #![feature(const_waker)] #![feature(cstr_from_bytes_until_nul)] #![feature(dispatch_from_dyn)] -#![cfg_attr(not(bootstrap), feature(error_generic_member_access))] -#![cfg_attr(not(bootstrap), feature(error_in_core))] +#![feature(error_generic_member_access)] +#![feature(error_in_core)] #![feature(exact_size_is_empty)] #![feature(extend_one)] #![feature(fmt_internals)] @@ -132,7 +132,7 @@ #![feature(nonnull_slice_from_raw_parts)] #![feature(pattern)] #![feature(pointer_byte_offsets)] -#![cfg_attr(not(bootstrap), feature(provide_any))] +#![feature(provide_any)] #![feature(ptr_internals)] #![feature(ptr_metadata)] #![feature(ptr_sub_ptr)] @@ -173,7 +173,6 @@ #![cfg_attr(not(test), feature(generator_trait))] #![feature(hashmap_internals)] #![feature(lang_items)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(min_specialization)] #![feature(negative_impls)] #![feature(never_type)] diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index f2448396ce8..983376a282b 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -44,7 +44,6 @@ #[cfg(not(no_global_oom_handling))] use core::char::{decode_utf16, REPLACEMENT_CHARACTER}; -#[cfg(not(bootstrap))] use core::error::Error; use core::fmt; use core::hash; @@ -1941,7 +1940,6 @@ impl fmt::Display for FromUtf16Error { } } -#[cfg(not(bootstrap))] #[stable(feature = "rust1", since = "1.0.0")] impl Error for FromUtf8Error { #[allow(deprecated)] @@ -1950,7 +1948,6 @@ impl Error for FromUtf8Error { } } -#[cfg(not(bootstrap))] #[stable(feature = "rust1", since = "1.0.0")] impl Error for FromUtf16Error { #[allow(deprecated)] diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 4377edeee87..a5322953d49 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -2764,7 +2764,6 @@ fn data_offset_align(align: usize) -> usize { layout.size() + layout.padding_needed_for(align) } -#[cfg(not(bootstrap))] #[stable(feature = "arc_error", since = "1.52.0")] impl core::error::Error for Arc { #[allow(deprecated, deprecated_in_future)] diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs index f03502429ab..5bb44b40859 100644 --- a/library/core/src/alloc/layout.rs +++ b/library/core/src/alloc/layout.rs @@ -5,7 +5,6 @@ // Your performance intuition is useless. Run perf. use crate::cmp; -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt; use crate::mem::{self, ValidAlign}; @@ -463,7 +462,6 @@ pub type LayoutErr = LayoutError; #[derive(Clone, PartialEq, Eq, Debug)] pub struct LayoutError; -#[cfg(not(bootstrap))] #[stable(feature = "alloc_layout", since = "1.28.0")] impl Error for LayoutError {} diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 61553157478..a4bf6a853a6 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -21,7 +21,6 @@ pub use self::layout::LayoutErr; #[stable(feature = "alloc_layout_error", since = "1.50.0")] pub use self::layout::LayoutError; -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt; use crate::ptr::{self, NonNull}; @@ -34,7 +33,6 @@ use crate::ptr::{self, NonNull}; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; -#[cfg(not(bootstrap))] #[unstable( feature = "allocator_api", reason = "the precise API and guarantees it provides may be tweaked.", diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index 36e89a95fd2..b82bbf2267a 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -7,7 +7,6 @@ use crate::borrow::{Borrow, BorrowMut}; use crate::cmp::Ordering; use crate::convert::{Infallible, TryFrom}; -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt; use crate::hash::{self, Hash}; @@ -121,7 +120,6 @@ impl fmt::Display for TryFromSliceError { } } -#[cfg(not(bootstrap))] #[stable(feature = "try_from", since = "1.34.0")] impl Error for TryFromSliceError { #[allow(deprecated)] diff --git a/library/core/src/char/decode.rs b/library/core/src/char/decode.rs index dc8ea66cc6d..11f1c30f6d5 100644 --- a/library/core/src/char/decode.rs +++ b/library/core/src/char/decode.rs @@ -1,6 +1,5 @@ //! UTF-8 and UTF-16 decoding iterators -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt; @@ -124,7 +123,6 @@ impl fmt::Display for DecodeUtf16Error { } } -#[cfg(not(bootstrap))] #[stable(feature = "decode_utf16", since = "1.9.0")] impl Error for DecodeUtf16Error { #[allow(deprecated)] diff --git a/library/core/src/char/mod.rs b/library/core/src/char/mod.rs index 72d63ac4b4b..b34a7121631 100644 --- a/library/core/src/char/mod.rs +++ b/library/core/src/char/mod.rs @@ -38,7 +38,6 @@ pub use self::methods::encode_utf16_raw; #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] pub use self::methods::encode_utf8_raw; -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt::{self, Write}; use crate::iter::FusedIterator; @@ -587,6 +586,5 @@ impl fmt::Display for TryFromCharError { } } -#[cfg(not(bootstrap))] #[stable(feature = "u8_from_char", since = "1.59.0")] impl Error for TryFromCharError {} diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index 0480704a6d6..c42adda8da5 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -34,7 +34,6 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt; use crate::hash::{Hash, Hasher}; @@ -724,7 +723,6 @@ impl fmt::Display for Infallible { } } -#[cfg(not(bootstrap))] #[stable(feature = "str_parse_error2", since = "1.8.0")] impl Error for Infallible { fn description(&self) -> &str { diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 11c75e2c912..12b43da5a42 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -54,8 +54,6 @@ )] #![allow(missing_docs)] -#[cfg(bootstrap)] -use crate::marker::Destruct; use crate::marker::DiscriminantKind; use crate::mem; @@ -1297,7 +1295,6 @@ extern "rust-intrinsic" { /// any safety invariants. /// /// Consider using [`pointer::mask`] instead. - #[cfg(not(bootstrap))] pub fn ptr_mask(ptr: *const T, mask: usize) -> *const T; /// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with @@ -2022,17 +2019,8 @@ extern "rust-intrinsic" { /// Therefore, implementations must not require the user to uphold /// any safety invariants. #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] - #[cfg(not(bootstrap))] pub fn ptr_guaranteed_cmp(ptr: *const T, other: *const T) -> u8; - #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] - #[cfg(bootstrap)] - pub fn ptr_guaranteed_eq(ptr: *const T, other: *const T) -> bool; - - #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] - #[cfg(bootstrap)] - pub fn ptr_guaranteed_ne(ptr: *const T, other: *const T) -> bool; - /// Allocates a block of memory at compile time. /// At runtime, just returns a null pointer. /// @@ -2143,7 +2131,6 @@ extern "rust-intrinsic" { /// `unreachable_unchecked` is actually being reached. The bug is in *crate A*, /// which violates the principle that a `const fn` must behave the same at /// compile-time and at run-time. The unsafe code in crate B is fine. - #[cfg(not(bootstrap))] #[rustc_const_unstable(feature = "const_eval_select", issue = "none")] pub fn const_eval_select(arg: ARG, called_in_const: F, called_at_rt: G) -> RET where @@ -2216,16 +2203,6 @@ pub(crate) fn is_nonoverlapping(src: *const T, dst: *const T, count: usize) - diff >= size } -#[cfg(bootstrap)] -pub const fn ptr_guaranteed_cmp(a: *const (), b: *const ()) -> u8 { - match (ptr_guaranteed_eq(a, b), ptr_guaranteed_ne(a, b)) { - (false, false) => 2, - (true, false) => 1, - (false, true) => 0, - (true, true) => unreachable!(), - } -} - /// Copies `count * size_of::()` bytes from `src` to `dst`. The source /// and destination must *not* overlap. /// @@ -2484,45 +2461,3 @@ pub const unsafe fn write_bytes(dst: *mut T, val: u8, count: usize) { write_bytes(dst, val, count) } } - -#[cfg(bootstrap)] -#[unstable( - feature = "const_eval_select", - issue = "none", - reason = "const_eval_select will never be stable" -)] -#[rustc_const_unstable(feature = "const_eval_select", issue = "none")] -#[lang = "const_eval_select"] -#[rustc_do_not_const_check] -#[inline] -pub const unsafe fn const_eval_select( - arg: ARG, - _called_in_const: F, - called_at_rt: G, -) -> RET -where - F: ~const FnOnce, - G: FnOnce + ~const Destruct, -{ - called_at_rt.call_once(arg) -} - -#[cfg(bootstrap)] -#[unstable( - feature = "const_eval_select", - issue = "none", - reason = "const_eval_select will never be stable" -)] -#[rustc_const_unstable(feature = "const_eval_select", issue = "none")] -#[lang = "const_eval_select_ct"] -pub const unsafe fn const_eval_select_ct( - arg: ARG, - called_in_const: F, - _called_at_rt: G, -) -> RET -where - F: ~const FnOnce, - G: FnOnce + ~const Destruct, -{ - called_in_const.call_once(arg) -} diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index a48290ea08e..5690b5256e8 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -310,7 +310,6 @@ pub mod clone; pub mod cmp; pub mod convert; pub mod default; -#[cfg(not(bootstrap))] pub mod error; pub mod marker; pub mod ops; diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 40a7b696193..5cb5e4458cc 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -806,7 +806,7 @@ pub trait Destruct {} /// The implementation of this trait is built-in and cannot be implemented /// for any user type. #[unstable(feature = "tuple_trait", issue = "none")] -#[cfg_attr(not(bootstrap), lang = "tuple_trait")] +#[lang = "tuple_trait"] #[rustc_on_unimplemented(message = "`{Self}` is not a tuple")] pub trait Tuple {} diff --git a/library/core/src/mem/transmutability.rs b/library/core/src/mem/transmutability.rs index 87a37863105..3b98efff293 100644 --- a/library/core/src/mem/transmutability.rs +++ b/library/core/src/mem/transmutability.rs @@ -4,7 +4,7 @@ /// any value of type `Self` are safely transmutable into a value of type `Dst`, in a given `Context`, /// notwithstanding whatever safety checks you have asked the compiler to [`Assume`] are satisfied. #[unstable(feature = "transmutability", issue = "99571")] -#[cfg_attr(not(bootstrap), lang = "transmute_trait")] +#[lang = "transmute_trait"] #[rustc_on_unimplemented( message = "`{Src}` cannot be safely transmuted into `{Self}` in the defining scope of `{Context}`.", label = "`{Src}` cannot be safely transmuted into `{Self}` in the defining scope of `{Context}`." @@ -17,7 +17,7 @@ where /// What transmutation safety conditions shall the compiler assume that *you* are checking? #[unstable(feature = "transmutability", issue = "99571")] -#[cfg_attr(not(bootstrap), lang = "transmute_opts")] +#[lang = "transmute_opts"] #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub struct Assume { /// When `true`, the compiler assumes that *you* are ensuring (either dynamically or statically) that diff --git a/library/core/src/num/error.rs b/library/core/src/num/error.rs index 1f6b40e5df5..768dd87816d 100644 --- a/library/core/src/num/error.rs +++ b/library/core/src/num/error.rs @@ -1,7 +1,6 @@ //! Error types for conversion to integral types. use crate::convert::Infallible; -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt; @@ -147,7 +146,6 @@ impl fmt::Display for ParseIntError { } } -#[cfg(not(bootstrap))] #[stable(feature = "rust1", since = "1.0.0")] impl Error for ParseIntError { #[allow(deprecated)] @@ -156,7 +154,6 @@ impl Error for ParseIntError { } } -#[cfg(not(bootstrap))] #[stable(feature = "try_from", since = "1.34.0")] impl Error for TryFromIntError { #[allow(deprecated)] diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index dd4409198e3..c0be235c120 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -3,7 +3,6 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::ascii; -#[cfg(not(bootstrap))] use crate::error::Error; use crate::intrinsics; use crate::mem; @@ -59,7 +58,6 @@ pub use wrapping::Wrapping; #[cfg(not(no_fp_fmt_parse))] pub use dec2flt::ParseFloatError; -#[cfg(not(bootstrap))] #[cfg(not(no_fp_fmt_parse))] #[stable(feature = "rust1", since = "1.0.0")] impl Error for ParseFloatError { diff --git a/library/core/src/ops/generator.rs b/library/core/src/ops/generator.rs index 3ebd6f8cdbd..fee4beb1e84 100644 --- a/library/core/src/ops/generator.rs +++ b/library/core/src/ops/generator.rs @@ -83,7 +83,6 @@ pub trait Generator { /// `return` statement or implicitly as the last expression of a generator /// literal. For example futures would use this as `Result` as it /// represents a completed future. - #[cfg_attr(bootstrap, lang = "generator_return")] type Return; /// Resumes the execution of this generator. diff --git a/library/core/src/ops/try_trait.rs b/library/core/src/ops/try_trait.rs index 4d0d4e12adb..33df9e6c5cd 100644 --- a/library/core/src/ops/try_trait.rs +++ b/library/core/src/ops/try_trait.rs @@ -223,7 +223,7 @@ pub trait Try: ~const FromResidual { /// Every `Try` type needs to be recreatable from its own associated /// `Residual` type, but can also have additional `FromResidual` implementations /// to support interconversion with other `Try` types. -#[cfg_attr(not(bootstrap), rustc_on_unimplemented( +#[rustc_on_unimplemented( on( all( from_desugaring = "QuestionMark", @@ -302,87 +302,7 @@ pub trait Try: ~const FromResidual { label = "cannot use the `?` operator in {ItemContext} that returns `{Self}`", parent_label = "this function should return `Result` or `Option` to accept `?`" ), -))] -#[cfg_attr(bootstrap, rustc_on_unimplemented( - on( - all( - from_desugaring = "QuestionMark", - _Self = "std::result::Result", - R = "std::option::Option" - ), - message = "the `?` operator can only be used on `Result`s, not `Option`s, \ - in {ItemContext} that returns `Result`", - label = "use `.ok_or(...)?` to provide an error compatible with `{Self}`", - enclosing_scope = "this function returns a `Result`" - ), - on( - all( - from_desugaring = "QuestionMark", - _Self = "std::result::Result", - ), - // There's a special error message in the trait selection code for - // `From` in `?`, so this is not shown for result-in-result errors, - // and thus it can be phrased more strongly than `ControlFlow`'s. - message = "the `?` operator can only be used on `Result`s \ - in {ItemContext} that returns `Result`", - label = "this `?` produces `{R}`, which is incompatible with `{Self}`", - enclosing_scope = "this function returns a `Result`" - ), - on( - all( - from_desugaring = "QuestionMark", - _Self = "std::option::Option", - R = "std::result::Result", - ), - message = "the `?` operator can only be used on `Option`s, not `Result`s, \ - in {ItemContext} that returns `Option`", - label = "use `.ok()?` if you want to discard the `{R}` error information", - enclosing_scope = "this function returns an `Option`" - ), - on( - all( - from_desugaring = "QuestionMark", - _Self = "std::option::Option", - ), - // `Option`-in-`Option` always works, as there's only one possible - // residual, so this can also be phrased strongly. - message = "the `?` operator can only be used on `Option`s \ - in {ItemContext} that returns `Option`", - label = "this `?` produces `{R}`, which is incompatible with `{Self}`", - enclosing_scope = "this function returns an `Option`" - ), - on( - all( - from_desugaring = "QuestionMark", - _Self = "std::ops::ControlFlow", - R = "std::ops::ControlFlow", - ), - message = "the `?` operator in {ItemContext} that returns `ControlFlow` \ - can only be used on other `ControlFlow`s (with the same Break type)", - label = "this `?` produces `{R}`, which is incompatible with `{Self}`", - enclosing_scope = "this function returns a `ControlFlow`", - note = "unlike `Result`, there's no `From`-conversion performed for `ControlFlow`" - ), - on( - all( - from_desugaring = "QuestionMark", - _Self = "std::ops::ControlFlow", - // `R` is not a `ControlFlow`, as that case was matched previously - ), - message = "the `?` operator can only be used on `ControlFlow`s \ - in {ItemContext} that returns `ControlFlow`", - label = "this `?` produces `{R}`, which is incompatible with `{Self}`", - enclosing_scope = "this function returns a `ControlFlow`", - ), - on( - all(from_desugaring = "QuestionMark"), - message = "the `?` operator can only be used in {ItemContext} \ - that returns `Result` or `Option` \ - (or another type that implements `{FromResidual}`)", - label = "cannot use the `?` operator in {ItemContext} that returns `{Self}`", - enclosing_scope = "this function should return `Result` or `Option` to accept `?`" - ), -))] +)] #[rustc_diagnostic_item = "FromResidual"] #[unstable(feature = "try_trait_v2", issue = "84277")] #[const_trait] diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 43e883b8bf7..d898108be58 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -568,7 +568,6 @@ impl *const T { /// /// For non-`Sized` pointees this operation changes only the data pointer, /// leaving the metadata untouched. - #[cfg(not(bootstrap))] #[unstable(feature = "ptr_mask", issue = "98290")] #[must_use = "returns a new pointer rather than modifying its argument"] #[inline(always)] diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index e277b818175..543ab826c4e 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -584,7 +584,6 @@ impl *mut T { /// /// For non-`Sized` pointees this operation changes only the data pointer, /// leaving the metadata untouched. - #[cfg(not(bootstrap))] #[unstable(feature = "ptr_mask", issue = "98290")] #[must_use = "returns a new pointer rather than modifying its argument"] #[inline(always)] diff --git a/library/core/src/str/error.rs b/library/core/src/str/error.rs index 343889b6999..a11b5add42e 100644 --- a/library/core/src/str/error.rs +++ b/library/core/src/str/error.rs @@ -1,6 +1,5 @@ //! Defines utf8 error type. -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt; @@ -124,7 +123,6 @@ impl fmt::Display for Utf8Error { } } -#[cfg(not(bootstrap))] #[stable(feature = "rust1", since = "1.0.0")] impl Error for Utf8Error { #[allow(deprecated)] @@ -148,7 +146,6 @@ impl fmt::Display for ParseBoolError { } } -#[cfg(not(bootstrap))] #[stable(feature = "rust1", since = "1.0.0")] impl Error for ParseBoolError { #[allow(deprecated)] diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index f673aa2a44b..fbc0fc397a5 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -2642,5 +2642,4 @@ impl_fn_for_zst! { } #[stable(feature = "rust1", since = "1.0.0")] -#[cfg(not(bootstrap))] impl !crate::error::Error for &str {} diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index 9845d1faf9a..d2db4bb7a46 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -9,7 +9,6 @@ use crate::borrow::Borrow; use crate::cell::Cell; use crate::collections::TryReserveError; use crate::collections::TryReserveErrorKind; -#[cfg(not(bootstrap))] use crate::error::Error; use crate::fmt::{self, Debug}; #[allow(deprecated)] @@ -2160,7 +2159,6 @@ impl<'a, K: Debug, V: Debug> fmt::Display for OccupiedError<'a, K, V> { } } -#[cfg(not(bootstrap))] #[unstable(feature = "map_try_insert", issue = "82766")] impl<'a, K: fmt::Debug, V: fmt::Debug> Error for OccupiedError<'a, K, V> { #[allow(deprecated)] diff --git a/library/std/src/error.rs b/library/std/src/error.rs index e4505959536..05f8fd8de32 100644 --- a/library/std/src/error.rs +++ b/library/std/src/error.rs @@ -4,242 +4,12 @@ #[cfg(test)] mod tests; -#[cfg(bootstrap)] -use core::array; -#[cfg(bootstrap)] -use core::convert::Infallible; - -#[cfg(bootstrap)] -use crate::alloc::{AllocError, LayoutError}; -#[cfg(bootstrap)] -use crate::any::Demand; -#[cfg(bootstrap)] -use crate::any::{Provider, TypeId}; use crate::backtrace::Backtrace; -#[cfg(bootstrap)] -use crate::borrow::Cow; -#[cfg(bootstrap)] -use crate::cell; -#[cfg(bootstrap)] -use crate::char; -#[cfg(bootstrap)] -use crate::fmt::Debug; -#[cfg(bootstrap)] -use crate::fmt::Display; use crate::fmt::{self, Write}; -#[cfg(bootstrap)] -use crate::io; -#[cfg(bootstrap)] -use crate::mem::transmute; -#[cfg(bootstrap)] -use crate::num; -#[cfg(bootstrap)] -use crate::str; -#[cfg(bootstrap)] -use crate::string; -#[cfg(bootstrap)] -use crate::sync::Arc; -#[cfg(bootstrap)] -use crate::time; -#[cfg(not(bootstrap))] #[stable(feature = "rust1", since = "1.0.0")] pub use core::error::Error; -/// `Error` is a trait representing the basic expectations for error values, -/// i.e., values of type `E` in [`Result`]. -/// -/// Errors must describe themselves through the [`Display`] and [`Debug`] -/// traits. Error messages are typically concise lowercase sentences without -/// trailing punctuation: -/// -/// ``` -/// let err = "NaN".parse::().unwrap_err(); -/// assert_eq!(err.to_string(), "invalid digit found in string"); -/// ``` -/// -/// Errors may provide cause information. [`Error::source()`] is generally -/// used when errors cross "abstraction boundaries". If one module must report -/// an error that is caused by an error from a lower-level module, it can allow -/// accessing that error via [`Error::source()`]. This makes it possible for the -/// high-level module to provide its own errors while also revealing some of the -/// implementation for debugging. -#[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Error")] -#[cfg(bootstrap)] -pub trait Error: Debug + Display { - /// The lower-level source of this error, if any. - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::fmt; - /// - /// #[derive(Debug)] - /// struct SuperError { - /// source: SuperErrorSideKick, - /// } - /// - /// impl fmt::Display for SuperError { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "SuperError is here!") - /// } - /// } - /// - /// impl Error for SuperError { - /// fn source(&self) -> Option<&(dyn Error + 'static)> { - /// Some(&self.source) - /// } - /// } - /// - /// #[derive(Debug)] - /// struct SuperErrorSideKick; - /// - /// impl fmt::Display for SuperErrorSideKick { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "SuperErrorSideKick is here!") - /// } - /// } - /// - /// impl Error for SuperErrorSideKick {} - /// - /// fn get_super_error() -> Result<(), SuperError> { - /// Err(SuperError { source: SuperErrorSideKick }) - /// } - /// - /// fn main() { - /// match get_super_error() { - /// Err(e) => { - /// println!("Error: {e}"); - /// println!("Caused by: {}", e.source().unwrap()); - /// } - /// _ => println!("No error"), - /// } - /// } - /// ``` - #[stable(feature = "error_source", since = "1.30.0")] - fn source(&self) -> Option<&(dyn Error + 'static)> { - None - } - - /// Gets the `TypeId` of `self`. - #[doc(hidden)] - #[unstable( - feature = "error_type_id", - reason = "this is memory-unsafe to override in user code", - issue = "60784" - )] - fn type_id(&self, _: private::Internal) -> TypeId - where - Self: 'static, - { - TypeId::of::() - } - - /// ``` - /// if let Err(e) = "xc".parse::() { - /// // Print `e` itself, no need for description(). - /// eprintln!("Error: {e}"); - /// } - /// ``` - #[stable(feature = "rust1", since = "1.0.0")] - #[deprecated(since = "1.42.0", note = "use the Display impl or to_string()")] - fn description(&self) -> &str { - "description() is deprecated; use Display" - } - - #[stable(feature = "rust1", since = "1.0.0")] - #[deprecated( - since = "1.33.0", - note = "replaced by Error::source, which can support downcasting" - )] - #[allow(missing_docs)] - fn cause(&self) -> Option<&dyn Error> { - self.source() - } - - /// Provides type based access to context intended for error reports. - /// - /// Used in conjunction with [`Demand::provide_value`] and [`Demand::provide_ref`] to extract - /// references to member variables from `dyn Error` trait objects. - /// - /// # Example - /// - /// ```rust - /// #![feature(provide_any)] - /// #![feature(error_generic_member_access)] - /// use core::fmt; - /// use core::any::Demand; - /// - /// #[derive(Debug)] - /// struct MyBacktrace { - /// // ... - /// } - /// - /// impl MyBacktrace { - /// fn new() -> MyBacktrace { - /// // ... - /// # MyBacktrace {} - /// } - /// } - /// - /// #[derive(Debug)] - /// struct SourceError { - /// // ... - /// } - /// - /// impl fmt::Display for SourceError { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "Example Source Error") - /// } - /// } - /// - /// impl std::error::Error for SourceError {} - /// - /// #[derive(Debug)] - /// struct Error { - /// source: SourceError, - /// backtrace: MyBacktrace, - /// } - /// - /// impl fmt::Display for Error { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "Example Error") - /// } - /// } - /// - /// impl std::error::Error for Error { - /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) { - /// demand - /// .provide_ref::(&self.backtrace) - /// .provide_ref::(&self.source); - /// } - /// } - /// - /// fn main() { - /// let backtrace = MyBacktrace::new(); - /// let source = SourceError {}; - /// let error = Error { source, backtrace }; - /// let dyn_error = &error as &dyn std::error::Error; - /// let backtrace_ref = dyn_error.request_ref::().unwrap(); - /// - /// assert!(core::ptr::eq(&error.backtrace, backtrace_ref)); - /// } - /// ``` - #[unstable(feature = "error_generic_member_access", issue = "99301")] - #[allow(unused_variables)] - fn provide<'a>(&'a self, demand: &mut Demand<'a>) {} -} - -#[cfg(bootstrap)] -#[unstable(feature = "error_generic_member_access", issue = "99301")] -impl<'b> Provider for dyn Error + 'b { - fn provide<'a>(&'a self, demand: &mut Demand<'a>) { - self.provide(demand) - } -} - mod private { // This is a hack to prevent `type_id` from being overridden by `Error` // implementations, since that can enable unsound downcasting. @@ -248,799 +18,6 @@ mod private { pub struct Internal; } -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl<'a, E: Error + 'a> From for Box { - /// Converts a type of [`Error`] into a box of dyn [`Error`]. - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::fmt; - /// use std::mem; - /// - /// #[derive(Debug)] - /// struct AnError; - /// - /// impl fmt::Display for AnError { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "An error") - /// } - /// } - /// - /// impl Error for AnError {} - /// - /// let an_error = AnError; - /// assert!(0 == mem::size_of_val(&an_error)); - /// let a_boxed_error = Box::::from(an_error); - /// assert!(mem::size_of::>() == mem::size_of_val(&a_boxed_error)) - /// ``` - fn from(err: E) -> Box { - Box::new(err) - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl<'a, E: Error + Send + Sync + 'a> From for Box { - /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of - /// dyn [`Error`] + [`Send`] + [`Sync`]. - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::fmt; - /// use std::mem; - /// - /// #[derive(Debug)] - /// struct AnError; - /// - /// impl fmt::Display for AnError { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "An error") - /// } - /// } - /// - /// impl Error for AnError {} - /// - /// unsafe impl Send for AnError {} - /// - /// unsafe impl Sync for AnError {} - /// - /// let an_error = AnError; - /// assert!(0 == mem::size_of_val(&an_error)); - /// let a_boxed_error = Box::::from(an_error); - /// assert!( - /// mem::size_of::>() == mem::size_of_val(&a_boxed_error)) - /// ``` - fn from(err: E) -> Box { - Box::new(err) - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl From for Box { - /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`]. - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::mem; - /// - /// let a_string_error = "a string error".to_string(); - /// let a_boxed_error = Box::::from(a_string_error); - /// assert!( - /// mem::size_of::>() == mem::size_of_val(&a_boxed_error)) - /// ``` - #[inline] - fn from(err: String) -> Box { - struct StringError(String); - - impl Error for StringError { - #[allow(deprecated)] - fn description(&self) -> &str { - &self.0 - } - } - - impl Display for StringError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - Display::fmt(&self.0, f) - } - } - - // Purposefully skip printing "StringError(..)" - impl Debug for StringError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - Debug::fmt(&self.0, f) - } - } - - Box::new(StringError(err)) - } -} - -#[cfg(bootstrap)] -#[stable(feature = "string_box_error", since = "1.6.0")] -impl From for Box { - /// Converts a [`String`] into a box of dyn [`Error`]. - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::mem; - /// - /// let a_string_error = "a string error".to_string(); - /// let a_boxed_error = Box::::from(a_string_error); - /// assert!(mem::size_of::>() == mem::size_of_val(&a_boxed_error)) - /// ``` - fn from(str_err: String) -> Box { - let err1: Box = From::from(str_err); - let err2: Box = err1; - err2 - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl<'a> From<&str> for Box { - /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`]. - /// - /// [`str`]: prim@str - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::mem; - /// - /// let a_str_error = "a str error"; - /// let a_boxed_error = Box::::from(a_str_error); - /// assert!( - /// mem::size_of::>() == mem::size_of_val(&a_boxed_error)) - /// ``` - #[inline] - fn from(err: &str) -> Box { - From::from(String::from(err)) - } -} - -#[cfg(bootstrap)] -#[stable(feature = "string_box_error", since = "1.6.0")] -impl From<&str> for Box { - /// Converts a [`str`] into a box of dyn [`Error`]. - /// - /// [`str`]: prim@str - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::mem; - /// - /// let a_str_error = "a str error"; - /// let a_boxed_error = Box::::from(a_str_error); - /// assert!(mem::size_of::>() == mem::size_of_val(&a_boxed_error)) - /// ``` - fn from(err: &str) -> Box { - From::from(String::from(err)) - } -} - -#[cfg(bootstrap)] -#[stable(feature = "cow_box_error", since = "1.22.0")] -impl<'a, 'b> From> for Box { - /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`]. - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::mem; - /// use std::borrow::Cow; - /// - /// let a_cow_str_error = Cow::from("a str error"); - /// let a_boxed_error = Box::::from(a_cow_str_error); - /// assert!( - /// mem::size_of::>() == mem::size_of_val(&a_boxed_error)) - /// ``` - fn from(err: Cow<'b, str>) -> Box { - From::from(String::from(err)) - } -} - -#[cfg(bootstrap)] -#[stable(feature = "cow_box_error", since = "1.22.0")] -impl<'a> From> for Box { - /// Converts a [`Cow`] into a box of dyn [`Error`]. - /// - /// # Examples - /// - /// ``` - /// use std::error::Error; - /// use std::mem; - /// use std::borrow::Cow; - /// - /// let a_cow_str_error = Cow::from("a str error"); - /// let a_boxed_error = Box::::from(a_cow_str_error); - /// assert!(mem::size_of::>() == mem::size_of_val(&a_boxed_error)) - /// ``` - fn from(err: Cow<'a, str>) -> Box { - From::from(String::from(err)) - } -} - -#[cfg(bootstrap)] -#[unstable(feature = "never_type", issue = "35121")] -impl Error for ! {} - -#[cfg(bootstrap)] -#[unstable( - feature = "allocator_api", - reason = "the precise API and guarantees it provides may be tweaked.", - issue = "32838" -)] -impl Error for AllocError {} - -#[cfg(bootstrap)] -#[stable(feature = "alloc_layout", since = "1.28.0")] -impl Error for LayoutError {} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for str::ParseBoolError { - #[allow(deprecated)] - fn description(&self) -> &str { - "failed to parse bool" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for str::Utf8Error { - #[allow(deprecated)] - fn description(&self) -> &str { - "invalid utf-8: corrupt contents" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for num::ParseIntError { - #[allow(deprecated)] - fn description(&self) -> &str { - self.__description() - } -} - -#[cfg(bootstrap)] -#[stable(feature = "try_from", since = "1.34.0")] -impl Error for num::TryFromIntError { - #[allow(deprecated)] - fn description(&self) -> &str { - self.__description() - } -} - -#[cfg(bootstrap)] -#[stable(feature = "try_from", since = "1.34.0")] -impl Error for array::TryFromSliceError { - #[allow(deprecated)] - fn description(&self) -> &str { - self.__description() - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for num::ParseFloatError { - #[allow(deprecated)] - fn description(&self) -> &str { - self.__description() - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for string::FromUtf8Error { - #[allow(deprecated)] - fn description(&self) -> &str { - "invalid utf-8" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for string::FromUtf16Error { - #[allow(deprecated)] - fn description(&self) -> &str { - "invalid utf-16" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "str_parse_error2", since = "1.8.0")] -impl Error for Infallible { - fn description(&self) -> &str { - match *self {} - } -} - -#[cfg(bootstrap)] -#[stable(feature = "decode_utf16", since = "1.9.0")] -impl Error for char::DecodeUtf16Error { - #[allow(deprecated)] - fn description(&self) -> &str { - "unpaired surrogate found" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "u8_from_char", since = "1.59.0")] -impl Error for char::TryFromCharError {} - -#[cfg(bootstrap)] -#[unstable(feature = "map_try_insert", issue = "82766")] -impl<'a, K: Debug + Ord, V: Debug> Error - for crate::collections::btree_map::OccupiedError<'a, K, V> -{ - #[allow(deprecated)] - fn description(&self) -> &str { - "key already exists" - } -} - -#[cfg(bootstrap)] -#[unstable(feature = "map_try_insert", issue = "82766")] -impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> { - #[allow(deprecated)] - fn description(&self) -> &str { - "key already exists" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "box_error", since = "1.8.0")] -impl Error for Box { - #[allow(deprecated, deprecated_in_future)] - fn description(&self) -> &str { - Error::description(&**self) - } - - #[allow(deprecated)] - fn cause(&self) -> Option<&dyn Error> { - Error::cause(&**self) - } - - fn source(&self) -> Option<&(dyn Error + 'static)> { - Error::source(&**self) - } -} - -#[cfg(bootstrap)] -#[unstable(feature = "thin_box", issue = "92791")] -impl crate::error::Error for crate::boxed::ThinBox { - fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> { - use core::ops::Deref; - self.deref().source() - } -} - -#[cfg(bootstrap)] -#[stable(feature = "error_by_ref", since = "1.51.0")] -impl<'a, T: Error + ?Sized> Error for &'a T { - #[allow(deprecated, deprecated_in_future)] - fn description(&self) -> &str { - Error::description(&**self) - } - - #[allow(deprecated)] - fn cause(&self) -> Option<&dyn Error> { - Error::cause(&**self) - } - - fn source(&self) -> Option<&(dyn Error + 'static)> { - Error::source(&**self) - } - - fn provide<'b>(&'b self, demand: &mut Demand<'b>) { - Error::provide(&**self, demand); - } -} - -#[cfg(bootstrap)] -#[stable(feature = "arc_error", since = "1.52.0")] -impl Error for Arc { - #[allow(deprecated, deprecated_in_future)] - fn description(&self) -> &str { - Error::description(&**self) - } - - #[allow(deprecated)] - fn cause(&self) -> Option<&dyn Error> { - Error::cause(&**self) - } - - fn source(&self) -> Option<&(dyn Error + 'static)> { - Error::source(&**self) - } - - fn provide<'a>(&'a self, demand: &mut Demand<'a>) { - Error::provide(&**self, demand); - } -} - -#[cfg(bootstrap)] -#[stable(feature = "fmt_error", since = "1.11.0")] -impl Error for fmt::Error { - #[allow(deprecated)] - fn description(&self) -> &str { - "an error occurred when formatting an argument" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "try_borrow", since = "1.13.0")] -impl Error for cell::BorrowError { - #[allow(deprecated)] - fn description(&self) -> &str { - "already mutably borrowed" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "try_borrow", since = "1.13.0")] -impl Error for cell::BorrowMutError { - #[allow(deprecated)] - fn description(&self) -> &str { - "already borrowed" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "try_from", since = "1.34.0")] -impl Error for char::CharTryFromError { - #[allow(deprecated)] - fn description(&self) -> &str { - "converted integer out of range for `char`" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "char_from_str", since = "1.20.0")] -impl Error for char::ParseCharError { - #[allow(deprecated)] - fn description(&self) -> &str { - self.__description() - } -} - -#[cfg(bootstrap)] -#[stable(feature = "try_reserve", since = "1.57.0")] -impl Error for alloc::collections::TryReserveError {} - -#[cfg(bootstrap)] -#[unstable(feature = "duration_checked_float", issue = "83400")] -impl Error for time::FromFloatSecsError {} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for alloc::ffi::NulError { - #[allow(deprecated)] - fn description(&self) -> &str { - "nul byte found in data" - } -} - -#[cfg(bootstrap)] -#[stable(feature = "rust1", since = "1.0.0")] -impl From for io::Error { - /// Converts a [`alloc::ffi::NulError`] into a [`io::Error`]. - fn from(_: alloc::ffi::NulError) -> io::Error { - io::const_io_error!(io::ErrorKind::InvalidInput, "data provided contains a nul byte") - } -} - -#[cfg(bootstrap)] -#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")] -impl Error for core::ffi::FromBytesWithNulError { - #[allow(deprecated)] - fn description(&self) -> &str { - self.__description() - } -} - -#[cfg(bootstrap)] -#[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")] -impl Error for core::ffi::FromBytesUntilNulError {} - -#[cfg(bootstrap)] -#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")] -impl Error for alloc::ffi::FromVecWithNulError {} - -#[cfg(bootstrap)] -#[stable(feature = "cstring_into", since = "1.7.0")] -impl Error for alloc::ffi::IntoStringError { - #[allow(deprecated)] - fn description(&self) -> &str { - "C string contained non-utf8 bytes" - } - - fn source(&self) -> Option<&(dyn Error + 'static)> { - Some(self.__source()) - } -} - -#[cfg(bootstrap)] -impl<'a> dyn Error + 'a { - /// Request a reference of type `T` as context about this error. - #[unstable(feature = "error_generic_member_access", issue = "99301")] - pub fn request_ref(&'a self) -> Option<&'a T> { - core::any::request_ref(self) - } - - /// Request a value of type `T` as context about this error. - #[unstable(feature = "error_generic_member_access", issue = "99301")] - pub fn request_value(&'a self) -> Option { - core::any::request_value(self) - } -} - -// Copied from `any.rs`. -#[cfg(bootstrap)] -impl dyn Error + 'static { - /// Returns `true` if the inner type is the same as `T`. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn is(&self) -> bool { - // Get `TypeId` of the type this function is instantiated with. - let t = TypeId::of::(); - - // Get `TypeId` of the type in the trait object (`self`). - let concrete = self.type_id(private::Internal); - - // Compare both `TypeId`s on equality. - t == concrete - } - - /// Returns some reference to the inner value if it is of type `T`, or - /// `None` if it isn't. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn downcast_ref(&self) -> Option<&T> { - if self.is::() { - unsafe { Some(&*(self as *const dyn Error as *const T)) } - } else { - None - } - } - - /// Returns some mutable reference to the inner value if it is of type `T`, or - /// `None` if it isn't. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn downcast_mut(&mut self) -> Option<&mut T> { - if self.is::() { - unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) } - } else { - None - } - } -} - -#[cfg(bootstrap)] -impl dyn Error + 'static + Send { - /// Forwards to the method defined on the type `dyn Error`. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn is(&self) -> bool { - ::is::(self) - } - - /// Forwards to the method defined on the type `dyn Error`. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn downcast_ref(&self) -> Option<&T> { - ::downcast_ref::(self) - } - - /// Forwards to the method defined on the type `dyn Error`. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn downcast_mut(&mut self) -> Option<&mut T> { - ::downcast_mut::(self) - } - - /// Request a reference of type `T` as context about this error. - #[unstable(feature = "error_generic_member_access", issue = "99301")] - pub fn request_ref(&self) -> Option<&T> { - ::request_ref(self) - } - - /// Request a value of type `T` as context about this error. - #[unstable(feature = "error_generic_member_access", issue = "99301")] - pub fn request_value(&self) -> Option { - ::request_value(self) - } -} - -#[cfg(bootstrap)] -impl dyn Error + 'static + Send + Sync { - /// Forwards to the method defined on the type `dyn Error`. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn is(&self) -> bool { - ::is::(self) - } - - /// Forwards to the method defined on the type `dyn Error`. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn downcast_ref(&self) -> Option<&T> { - ::downcast_ref::(self) - } - - /// Forwards to the method defined on the type `dyn Error`. - #[stable(feature = "error_downcast", since = "1.3.0")] - #[inline] - pub fn downcast_mut(&mut self) -> Option<&mut T> { - ::downcast_mut::(self) - } - - /// Request a reference of type `T` as context about this error. - #[unstable(feature = "error_generic_member_access", issue = "99301")] - pub fn request_ref(&self) -> Option<&T> { - ::request_ref(self) - } - - /// Request a value of type `T` as context about this error. - #[unstable(feature = "error_generic_member_access", issue = "99301")] - pub fn request_value(&self) -> Option { - ::request_value(self) - } -} - -#[cfg(bootstrap)] -impl dyn Error { - #[inline] - #[stable(feature = "error_downcast", since = "1.3.0")] - /// Attempts to downcast the box to a concrete type. - pub fn downcast(self: Box) -> Result, Box> { - if self.is::() { - unsafe { - let raw: *mut dyn Error = Box::into_raw(self); - Ok(Box::from_raw(raw as *mut T)) - } - } else { - Err(self) - } - } - - /// Returns an iterator starting with the current error and continuing with - /// recursively calling [`Error::source`]. - /// - /// If you want to omit the current error and only use its sources, - /// use `skip(1)`. - /// - /// # Examples - /// - /// ``` - /// #![feature(error_iter)] - /// use std::error::Error; - /// use std::fmt; - /// - /// #[derive(Debug)] - /// struct A; - /// - /// #[derive(Debug)] - /// struct B(Option>); - /// - /// impl fmt::Display for A { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "A") - /// } - /// } - /// - /// impl fmt::Display for B { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "B") - /// } - /// } - /// - /// impl Error for A {} - /// - /// impl Error for B { - /// fn source(&self) -> Option<&(dyn Error + 'static)> { - /// self.0.as_ref().map(|e| e.as_ref()) - /// } - /// } - /// - /// let b = B(Some(Box::new(A))); - /// - /// // let err : Box = b.into(); // or - /// let err = &b as &(dyn Error); - /// - /// let mut iter = err.sources(); - /// - /// assert_eq!("B".to_string(), iter.next().unwrap().to_string()); - /// assert_eq!("A".to_string(), iter.next().unwrap().to_string()); - /// assert!(iter.next().is_none()); - /// assert!(iter.next().is_none()); - /// ``` - #[unstable(feature = "error_iter", issue = "58520")] - #[inline] - pub fn sources(&self) -> Sources<'_> { - // You may think this method would be better in the Error trait, and you'd be right. - // Unfortunately that doesn't work, not because of the object safety rules but because we - // save a reference to self in Sources below as a trait object. If this method was - // declared in Error, then self would have the type &T where T is some concrete type which - // implements Error. We would need to coerce self to have type &dyn Error, but that requires - // that Self has a known size (i.e., Self: Sized). We can't put that bound on Error - // since that would forbid Error trait objects, and we can't put that bound on the method - // because that means the method can't be called on trait objects (we'd also need the - // 'static bound, but that isn't allowed because methods with bounds on Self other than - // Sized are not object-safe). Requiring an Unsize bound is not backwards compatible. - - Sources { current: Some(self) } - } -} - -/// An iterator over an [`Error`] and its sources. -/// -/// If you want to omit the initial error and only process -/// its sources, use `skip(1)`. -#[unstable(feature = "error_iter", issue = "58520")] -#[derive(Clone, Debug)] -#[cfg(bootstrap)] -pub struct Sources<'a> { - current: Option<&'a (dyn Error + 'static)>, -} - -#[cfg(bootstrap)] -#[unstable(feature = "error_iter", issue = "58520")] -impl<'a> Iterator for Sources<'a> { - type Item = &'a (dyn Error + 'static); - - fn next(&mut self) -> Option { - let current = self.current; - self.current = self.current.and_then(Error::source); - current - } -} - -#[cfg(bootstrap)] -impl dyn Error + Send { - #[inline] - #[stable(feature = "error_downcast", since = "1.3.0")] - /// Attempts to downcast the box to a concrete type. - pub fn downcast(self: Box) -> Result, Box> { - let err: Box = self; - ::downcast(err).map_err(|s| unsafe { - // Reapply the `Send` marker. - transmute::, Box>(s) - }) - } -} - -#[cfg(bootstrap)] -impl dyn Error + Send + Sync { - #[inline] - #[stable(feature = "error_downcast", since = "1.3.0")] - /// Attempts to downcast the box to a concrete type. - pub fn downcast(self: Box) -> Result, Box> { - let err: Box = self; - ::downcast(err).map_err(|s| unsafe { - // Reapply the `Send + Sync` marker. - transmute::, Box>(s) - }) - } -} - /// An error reporter that prints an error and its sources. /// /// Report also exposes configuration options for formatting the error sources, either entirely on a diff --git a/library/std/src/io/error.rs b/library/std/src/io/error.rs index 29b09fcc527..feb3fb989a7 100644 --- a/library/std/src/io/error.rs +++ b/library/std/src/io/error.rs @@ -76,7 +76,6 @@ impl fmt::Debug for Error { } } -#[cfg(not(bootstrap))] #[stable(feature = "rust1", since = "1.0.0")] impl From for Error { /// Converts a [`alloc::ffi::NulError`] into a [`Error`]. diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 3131dd47269..c2b7a4d8648 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -252,10 +252,8 @@ #![feature(dropck_eyepatch)] #![feature(exhaustive_patterns)] #![feature(intra_doc_pointers)] -#![cfg_attr(bootstrap, feature(label_break_value))] #![feature(lang_items)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(linkage)] #![feature(link_cfg)] #![feature(min_specialization)] @@ -282,9 +280,9 @@ #![feature(cstr_internals)] #![feature(duration_checked_float)] #![feature(duration_constants)] -#![cfg_attr(not(bootstrap), feature(error_generic_member_access))] -#![cfg_attr(not(bootstrap), feature(error_in_core))] -#![cfg_attr(not(bootstrap), feature(error_iter))] +#![feature(error_generic_member_access)] +#![feature(error_in_core)] +#![feature(error_iter)] #![feature(exact_size_is_empty)] #![feature(exclusive_wrapper)] #![feature(extend_one)] diff --git a/library/std/src/rt.rs b/library/std/src/rt.rs index 98f6cc7aa3e..b8bcdbece0a 100644 --- a/library/std/src/rt.rs +++ b/library/std/src/rt.rs @@ -160,15 +160,12 @@ fn lang_start( main: fn() -> T, argc: isize, argv: *const *const u8, - #[cfg(not(bootstrap))] sigpipe: u8, + sigpipe: u8, ) -> isize { let Ok(v) = lang_start_internal( &move || crate::sys_common::backtrace::__rust_begin_short_backtrace(main).report().to_i32(), argc, argv, - #[cfg(bootstrap)] - 2, // Temporary inlining of sigpipe::DEFAULT until bootstrap stops being special - #[cfg(not(bootstrap))] sigpipe, ); v diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index f973fd0889e..f06d2cf108d 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -2535,7 +2535,6 @@ mod size_asserts { // These are in alphabetical order, which is easy to maintain. static_assert_size!(Crate, 72); // frequently moved by-value static_assert_size!(DocFragment, 32); - #[cfg(not(bootstrap))] static_assert_size!(GenericArg, 56); static_assert_size!(GenericArgs, 32); static_assert_size!(GenericParamDef, 56); diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 23ad0c30f21..23e3de45fa5 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -9,14 +9,12 @@ #![feature(control_flow_enum)] #![feature(drain_filter)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(test)] #![feature(never_type)] #![feature(once_cell)] #![feature(type_ascription)] #![feature(iter_intersperse)] #![feature(type_alias_impl_trait)] -#![cfg_attr(bootstrap, feature(generic_associated_types))] #![recursion_limit = "256"] #![warn(rustc::internal)] #![allow(clippy::collapsible_if, clippy::collapsible_else_if)] diff --git a/src/test/mir-opt/issue-101867.rs b/src/test/mir-opt/issue-101867.rs index 931396e2171..fcbe5a2b90a 100644 --- a/src/test/mir-opt/issue-101867.rs +++ b/src/test/mir-opt/issue-101867.rs @@ -1,4 +1,3 @@ -#![cfg_attr(bootstrap, feature(let_else))] // EMIT_MIR issue_101867.main.mir_map.0.mir fn main() { diff --git a/src/test/ui/let-else/const-fn.rs b/src/test/ui/let-else/const-fn.rs index 336b0b4b72a..a3921b8033f 100644 --- a/src/test/ui/let-else/const-fn.rs +++ b/src/test/ui/let-else/const-fn.rs @@ -1,7 +1,6 @@ // run-pass // issue #101932 -#![cfg_attr(bootstrap, feature(let_else))] const fn foo(a: Option) -> i32 { let Some(a) = a else { diff --git a/src/tools/clippy/clippy_dev/src/lib.rs b/src/tools/clippy/clippy_dev/src/lib.rs index 54c7456a2a3..80bb83af43b 100644 --- a/src/tools/clippy/clippy_dev/src/lib.rs +++ b/src/tools/clippy/clippy_dev/src/lib.rs @@ -1,5 +1,4 @@ #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(rustc_private)] #![cfg_attr(feature = "deny-warnings", deny(warnings))] diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index 298566cb5b6..00bf6445c12 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -5,7 +5,6 @@ #![feature(drain_filter)] #![feature(iter_intersperse)] #![feature(let_chains)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(lint_reasons)] #![feature(never_type)] #![feature(once_cell)] diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 9343cf457b3..b1abd3b04c9 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -3,7 +3,6 @@ #![feature(control_flow_enum)] #![feature(let_chains)] #![feature(lint_reasons)] -#![cfg_attr(bootstrap, feature(let_else))] #![feature(once_cell)] #![feature(rustc_private)] #![recursion_limit = "512"] -- cgit 1.4.1-3-g733a5