From 073e6496f6e482eb25dbd2bbbb61f7e441f74cef Mon Sep 17 00:00:00 2001 From: Crystal Durham Date: Fri, 5 Jun 2026 21:53:22 -0400 Subject: [PATCH 01/13] Add xdg_basedir API --- library/std/src/env.rs | 1 + library/std/src/os/unix/mod.rs | 1 + library/std/src/os/unix/xdg.rs | 166 +++++++++++++++++++++++++++++++++ 3 files changed, 168 insertions(+) create mode 100644 library/std/src/os/unix/xdg.rs diff --git a/library/std/src/env.rs b/library/std/src/env.rs index a4a5e8561dfcf..b377110462d61 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -600,6 +600,7 @@ impl Error for JoinPathsError { /// For example, [XDG Base Directories] on Unix or the `LOCALAPPDATA` and `APPDATA` environment variables on Windows. /// /// [XDG Base Directories]: https://specifications.freedesktop.org/basedir-spec/latest/ +// feature(xdg_basedir): This should link to std::os::unix::xdg once it's stabilized /// /// # Unix /// diff --git a/library/std/src/os/unix/mod.rs b/library/std/src/os/unix/mod.rs index 78c957270c451..e3f15a00a0944 100644 --- a/library/std/src/os/unix/mod.rs +++ b/library/std/src/os/unix/mod.rs @@ -94,6 +94,7 @@ pub mod net; pub mod process; pub mod raw; pub mod thread; +pub mod xdg; /// A prelude for conveniently writing platform-specific code. /// diff --git a/library/std/src/os/unix/xdg.rs b/library/std/src/os/unix/xdg.rs new file mode 100644 index 0000000000000..6f54e7f266444 --- /dev/null +++ b/library/std/src/os/unix/xdg.rs @@ -0,0 +1,166 @@ +//! XDG (X Desktop Group) related functionality for Unix platforms. +//! +//! The [XDG Base Directory Specification][basedir] defines where user-specific +//! files should be looked for relative to a set of base directories. The +//! functions in this module provide those directory paths as configured by +//! the environment. +//! +//! Note that the use of these functions is not enforced by the system, and as +//! such, not all programs will necessarily respect all details of the XDG path +//! environment. This is a set of guidelines, and each program is ultimately +//! responsible for defining where and how it both reads and writes files. +//! +//! Use of XDG paths can be generally considered the conventional expectation +//! on Linux-based systems. Other Unix-based systems may or may not play well +//! with the XDG conventions. +//! +//! Directories returned by this module are not guaranteed to exist yet. If the +//! directory does not exist, an application should attempt to create it with +//! [permissions mode][super::fs::PermissionsExt::from_mode] `0o700`. +//! +//! [basedir]: https://specifications.freedesktop.org/basedir/latest/ +#![unstable(feature = "xdg_basedir", issue = "157515")] + +use crate::env::{home_dir, split_paths, var_os}; +use crate::ffi::{OsStr, OsString}; +use crate::path::{Path, PathBuf}; + +fn xdg_home_dir() -> PathBuf { + // Note: home_dir can return `Some("")` in some cases. We assume that in + // this case the expected behavior is for `$HOME/path` to become `/path`, + // i.e. the home directory is effectively `/`. + match home_dir() { + None => panic!("an XDG environment should have a home directory"), + Some(home) if home.is_empty() => PathBuf::from("/"), + Some(home) => home, + } +} + +fn xdg_dir(env: &str, fallback_home_subdir: impl AsRef) -> PathBuf { + var_os(env) + .filter(|s| !s.is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| xdg_home_dir().join(fallback_home_subdir)) +} + +/// A base directory relative to which user-specific data files should be written. +/// +/// An application `appid` would typically be expected to write its data files +/// to `{data_home_dir}/{appid}/**/*`. +pub fn data_home_dir() -> PathBuf { + xdg_dir("XDG_DATA_HOME", ".local/share") +} + +/// A base directory relative to which user-specific configuration files should be written. +/// +/// An application `appid` would typically be expected to write its configuration +/// files to `{config_home_dir}/{appid}/**/*`. +pub fn config_home_dir() -> PathBuf { + xdg_dir("XDG_CONFIG_HOME", ".config") +} + +/// A base directory relative to which user-specific state data should be written. +/// +/// An application `appid` would typically be expected to write its state data to +/// `{state_home_dir}/{appid}/**/*`. +/// +/// Common kinds of state data include actions history (such as logs, history, +/// recently used files, etc.) and state of the application that can be reused +/// after application restart (such as view, layout, open files, undo history, +/// etc.). +pub fn state_home_dir() -> PathBuf { + xdg_dir("XDG_STATE_HOME", ".local/state") +} + +/// A base directory relative to which user-specific non-essential caches should be written. +/// +/// An application `appid` would typically be expected to write its cache data to +/// `{cache_home_dir}/{appid}/**/*`. +pub fn cache_home_dir() -> PathBuf { + xdg_dir("XDG_CACHE_HOME", ".cache") +} + +/// An iterator that produces directory paths from XDG environment configuration. +/// +/// The iterator element type is [`PathBuf`]. +/// +/// This structure is created by [`xdg::data_dirs`] and [`xdg::config_dirs`]. +/// See the documentation of those functions for more. +/// +/// [`xdg::data_dirs`]: data_dirs +/// [`xdg::config_dirs`]: config_dirs +// +// This stores Option so we can track when we have a trailing empty component. +// None is an exhausted iterator, Some("") is a trailing empty component. +#[derive(Debug, Clone)] +pub struct XdgDirsIter(Option); + +impl XdgDirsIter { + fn new(env: &str, default: impl AsRef) -> Self { + let dirs = var_os(env).filter(|s| !s.is_empty()).unwrap_or_else(|| default.as_ref().into()); + Self(Some(dirs)) + } +} + +impl Iterator for XdgDirsIter { + type Item = PathBuf; + + fn next(&mut self) -> Option { + let dirs = self.0.take()?; + let next = split_paths(&dirs).next()?; + let len = next.as_os_str().len(); + let mut bytes = dirs.into_encoded_bytes(); + if len < bytes.len() { + // Remove the path about to be returned and the separator after it. + bytes.drain(..len + 1); + // SAFETY: UNIX guarantees that the path separator is b':'. As `bytes` + // now holds the suffix after the separator, it's a valid OsStr. + self.0 = Some(unsafe { OsString::from_encoded_bytes_unchecked(bytes) }); + } + Some(next) + } + + fn size_hint(&self) -> (usize, Option) { + let Some(dirs) = &self.0 else { return (0, Some(0)) }; + split_paths(dirs).size_hint() + } +} + +/// A set of preference ordered directories relative to which data files should be searched. +/// +/// If an application defines a data file to be at `$XDG_DATA_DIRS/appid/file.name`, this means that: +/// +/// - The initial data file should be installed to `{system_data_dir}/appid/file.name`. +/// - A user-specific version of the data file may be created at +/// {[data_home_dir][]()}/appid/file.name. +/// - Lookups for the data file should search for `./appid/file.name` relative to +/// `data_home_dir` and each directory in `data_dirs`, giving preference to +/// files found relative to an earlier directory in the search order. +/// +/// An application may choose to handle a file being located under multiple base +/// directories however it sees fit, so long as it respects the search order. +/// For example, it could say that only the first file found is used, or that +/// data within the files is merged in some way. +pub fn data_dirs() -> XdgDirsIter { + // NB: the spec uses trailing slashes only for this default, for some reason + XdgDirsIter::new("XDG_DATA_DIRS", "/usr/local/share/:/usr/share/") +} + +/// A set of preference ordered directories relative to which configuration files should be searched. +/// +/// If an application defines a configuration file to be at `$XDG_CONFIG_DIRS/appid/file.name`, this means that: +/// +/// - The initial configuration file should be installed to `{system_config_dir}/xdg/appid/file.name`. +/// - A user-specific version of the configuration file may be created at +/// {[config_home_dir][]()}/appid/file.name. +/// - Lookups for the configuration file should search for `./appid/file.name` +/// relative to `config_home_dir` and each directory in `config_dirs`, giving +/// preference to files found relative to an earlier directory in the search order. +/// +/// An application may choose to handle a file being located under multiple base +/// directories however it sees fit, so long as it respects the search order. +/// For example, it could say that only the first file found is used, or that +/// data within the files is merged in some way. +pub fn config_dirs() -> XdgDirsIter { + XdgDirsIter::new("XDG_CONFIG_DIRS", "/etc/xdg") +} From 9534d0f0639f76ca67f5f10376515491e0988662 Mon Sep 17 00:00:00 2001 From: Crystal Durham Date: Sun, 7 Jun 2026 21:11:11 -0400 Subject: [PATCH 02/13] update module doc comment after review --- library/std/src/os/unix/xdg.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/os/unix/xdg.rs b/library/std/src/os/unix/xdg.rs index 6f54e7f266444..e1540db702342 100644 --- a/library/std/src/os/unix/xdg.rs +++ b/library/std/src/os/unix/xdg.rs @@ -1,7 +1,7 @@ //! XDG (X Desktop Group) related functionality for Unix platforms. //! -//! The [XDG Base Directory Specification][basedir] defines where user-specific -//! files should be looked for relative to a set of base directories. The +//! The [XDG Base Directory Specification][basedir] defines where a set of base +//! directories, relative to which user-specific files should be looked for. The //! functions in this module provide those directory paths as configured by //! the environment. //! From 2b3d2733eeaea93921502337a94241d94d739de7 Mon Sep 17 00:00:00 2001 From: Crystal Durham Date: Sun, 7 Jun 2026 21:12:30 -0400 Subject: [PATCH 03/13] reword xdg::cache_home_dir doc per review --- library/std/src/os/unix/xdg.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/os/unix/xdg.rs b/library/std/src/os/unix/xdg.rs index e1540db702342..cb04722bd55b8 100644 --- a/library/std/src/os/unix/xdg.rs +++ b/library/std/src/os/unix/xdg.rs @@ -36,7 +36,7 @@ fn xdg_home_dir() -> PathBuf { } } -fn xdg_dir(env: &str, fallback_home_subdir: impl AsRef) -> PathBuf { +fn xdg_dir(env: &str, fallback_home_subdir: impl AsRef) -> PathBuf { var_os(env) .filter(|s| !s.is_empty()) .map(PathBuf::from) @@ -72,7 +72,7 @@ pub fn state_home_dir() -> PathBuf { xdg_dir("XDG_STATE_HOME", ".local/state") } -/// A base directory relative to which user-specific non-essential caches should be written. +/// A base directory relative to which user-specific non-essential (cached) data should be written. /// /// An application `appid` would typically be expected to write its cache data to /// `{cache_home_dir}/{appid}/**/*`. From 7b4630613a45751b592d093ae647c2898907e4f4 Mon Sep 17 00:00:00 2001 From: Crystal Durham Date: Sun, 7 Jun 2026 21:14:25 -0400 Subject: [PATCH 04/13] remove unnecessary helper generics --- library/std/src/os/unix/xdg.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/std/src/os/unix/xdg.rs b/library/std/src/os/unix/xdg.rs index cb04722bd55b8..23ba125f64ca7 100644 --- a/library/std/src/os/unix/xdg.rs +++ b/library/std/src/os/unix/xdg.rs @@ -36,7 +36,7 @@ fn xdg_home_dir() -> PathBuf { } } -fn xdg_dir(env: &str, fallback_home_subdir: impl AsRef) -> PathBuf { +fn xdg_dir(env: &str, fallback_home_subdir: &str) -> PathBuf { var_os(env) .filter(|s| !s.is_empty()) .map(PathBuf::from) @@ -96,8 +96,8 @@ pub fn cache_home_dir() -> PathBuf { pub struct XdgDirsIter(Option); impl XdgDirsIter { - fn new(env: &str, default: impl AsRef) -> Self { - let dirs = var_os(env).filter(|s| !s.is_empty()).unwrap_or_else(|| default.as_ref().into()); + fn new(env: &str, default: &str) -> Self { + let dirs = var_os(env).filter(|s| !s.is_empty()).unwrap_or_else(|| default.into()); Self(Some(dirs)) } } From 593a847e5fe4f1e8d886b4ce6ce38518ed60af13 Mon Sep 17 00:00:00 2001 From: Crystal Durham Date: Sun, 7 Jun 2026 21:25:10 -0400 Subject: [PATCH 05/13] reduce byte shuffling in XdgDirsIter --- library/std/src/os/unix/xdg.rs | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/library/std/src/os/unix/xdg.rs b/library/std/src/os/unix/xdg.rs index 23ba125f64ca7..f15926e98500b 100644 --- a/library/std/src/os/unix/xdg.rs +++ b/library/std/src/os/unix/xdg.rs @@ -89,16 +89,24 @@ pub fn cache_home_dir() -> PathBuf { /// /// [`xdg::data_dirs`]: data_dirs /// [`xdg::config_dirs`]: config_dirs -// -// This stores Option so we can track when we have a trailing empty component. -// None is an exhausted iterator, Some("") is a trailing empty component. #[derive(Debug, Clone)] -pub struct XdgDirsIter(Option); +pub struct XdgDirsIter { + list: OsString, + off: usize, +} impl XdgDirsIter { fn new(env: &str, default: &str) -> Self { let dirs = var_os(env).filter(|s| !s.is_empty()).unwrap_or_else(|| default.into()); - Self(Some(dirs)) + Self { list: dirs, off: 0 } + } + + fn remaining(&self) -> Option<&OsStr> { + self.list.as_encoded_bytes().get(self.off..).map(|bytes| { + // SAFETY: `self.off` is the index after a path separator (or the + // start of the string), so is a valid OsStr boundary. + unsafe { OsStr::from_encoded_bytes_unchecked(bytes) } + }) } } @@ -106,22 +114,15 @@ impl Iterator for XdgDirsIter { type Item = PathBuf; fn next(&mut self) -> Option { - let dirs = self.0.take()?; - let next = split_paths(&dirs).next()?; + let rest = self.remaining()?; + let next = split_paths(rest).next()?; let len = next.as_os_str().len(); - let mut bytes = dirs.into_encoded_bytes(); - if len < bytes.len() { - // Remove the path about to be returned and the separator after it. - bytes.drain(..len + 1); - // SAFETY: UNIX guarantees that the path separator is b':'. As `bytes` - // now holds the suffix after the separator, it's a valid OsStr. - self.0 = Some(unsafe { OsString::from_encoded_bytes_unchecked(bytes) }); - } + self.off += len + 1; // Offset after this path and the separator after it. Some(next) } fn size_hint(&self) -> (usize, Option) { - let Some(dirs) = &self.0 else { return (0, Some(0)) }; + let Some(dirs) = self.remaining() else { return (0, Some(0)) }; split_paths(dirs).size_hint() } } From 6e670de6167f2ada1469b7441200a64c889189b6 Mon Sep 17 00:00:00 2001 From: Crystal Durham Date: Sun, 7 Jun 2026 22:04:48 -0400 Subject: [PATCH 06/13] remove unused import --- library/std/src/os/unix/xdg.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/os/unix/xdg.rs b/library/std/src/os/unix/xdg.rs index f15926e98500b..cd03ead26b48a 100644 --- a/library/std/src/os/unix/xdg.rs +++ b/library/std/src/os/unix/xdg.rs @@ -23,7 +23,7 @@ use crate::env::{home_dir, split_paths, var_os}; use crate::ffi::{OsStr, OsString}; -use crate::path::{Path, PathBuf}; +use crate::path::PathBuf; fn xdg_home_dir() -> PathBuf { // Note: home_dir can return `Some("")` in some cases. We assume that in From 378da804d6fdf2d7beb63ab3943d688897e4c870 Mon Sep 17 00:00:00 2001 From: Crystal Durham Date: Thu, 11 Jun 2026 17:10:05 -0400 Subject: [PATCH 07/13] Remove redundant word in doc comment --- library/std/src/os/unix/xdg.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/os/unix/xdg.rs b/library/std/src/os/unix/xdg.rs index cd03ead26b48a..b51b8ac916c24 100644 --- a/library/std/src/os/unix/xdg.rs +++ b/library/std/src/os/unix/xdg.rs @@ -1,6 +1,6 @@ //! XDG (X Desktop Group) related functionality for Unix platforms. //! -//! The [XDG Base Directory Specification][basedir] defines where a set of base +//! The [XDG Base Directory Specification][basedir] defines a set of base //! directories, relative to which user-specific files should be looked for. The //! functions in this module provide those directory paths as configured by //! the environment. From dea3ed868c6532964b2034bff28ce66a23afb761 Mon Sep 17 00:00:00 2001 From: Ian McCormack Date: Fri, 12 Jun 2026 12:15:31 -0400 Subject: [PATCH 08/13] Added initial support for building a `RetagPlan`. --- compiler/rustc_codegen_ssa/src/mir/retag.rs | 165 ++++++++++++++++++++ 1 file changed, 165 insertions(+) diff --git a/compiler/rustc_codegen_ssa/src/mir/retag.rs b/compiler/rustc_codegen_ssa/src/mir/retag.rs index a08a434326bb5..b8bb926ead67d 100644 --- a/compiler/rustc_codegen_ssa/src/mir/retag.rs +++ b/compiler/rustc_codegen_ssa/src/mir/retag.rs @@ -1,7 +1,18 @@ //! Experimental support for emitting retags as function calls in generated code. +//! +//! We attempt to retag every argument and return value of a function, and every rvalue +//! of an assignment. The first step to retagging is to generate a [`RetagPlan`], which +//! describes which pointers within the place or operand can be retagged. +#![allow(unused)] +use rustc_abi::{BackendRepr, FieldIdx, FieldsShape, VariantIdx, Variants}; +use rustc_ast::Mutability; +use rustc_data_structures::fx::FxIndexMap; use rustc_middle::mir::{Rvalue, WithRetag}; +use rustc_middle::ty; +use rustc_middle::ty::layout::TyAndLayout; +use crate::RetagInfo; use crate::mir::FunctionCx; use crate::mir::operand::OperandRef; use crate::mir::place::PlaceRef; @@ -12,6 +23,160 @@ pub(crate) fn rvalue_needs_retag(rvalue: &Rvalue<'_>) -> bool { !matches!(rvalue, Rvalue::Ref(..)) && !matches!(rvalue, Rvalue::Use(.., WithRetag::No)) } +/// A description of the pointers within a type that need to be retagged. +#[derive(Debug)] +enum RetagPlan { + /// Indicates that a pointer should be retagged. + EmitRetag(RetagInfo), + /// Indicates that one or more fields or variants of this type + /// contain pointers that need to be retagged. + Recurse { + field_plans: FxIndexMap>, + variant_plans: FxIndexMap>, + }, +} + +impl RetagPlan { + /// A helper function to move a [`RetagPlan`] into a particular field. + fn for_field(self, ix: FieldIdx) -> Self { + let mut field_plans = FxIndexMap::default(); + field_plans.insert(ix, self); + RetagPlan::Recurse { field_plans, variant_plans: FxIndexMap::default() } + } +} + +impl<'a, 'tcx, V> RetagPlan { + /// Attempts to create a [`RetagPlan`] for a place or operand with the given layout. + fn build>( + bx: &mut Bx, + layout: TyAndLayout<'tcx>, + is_fn_entry: bool, + ) -> Option> { + // If the value being retagged is smaller than a pointer, then it can't contain any + // pointers we need to retag, so we can stop recursion early. This optimization is + // crucial for ZSTs, because they can contain way more fields than we can ever visit. + if layout.is_sized() && layout.size < bx.tcx().data_layout.pointer_size() { + return None; + } + // SIMD vectors may only contain raw pointers, integers, and floating point values, + // which do not need to be retagged. + if matches!(layout.backend_repr, BackendRepr::SimdVector { .. }) { + return None; + } + + // Check the type of this value to see what to do with it (retag, or recurse). + match layout.ty.kind() { + &ty::Ref(_, pointee, mt) => { + let pointee_layout = bx.layout_of(pointee); + Self::emit_retag(bx, pointee_layout, Some(mt), is_fn_entry) + } + &ty::RawPtr(_, _) => None, + // `Box` needs special handling, since the innermost pointer is what gets retagged, but + // the outermost `Box` is what determines the permission that gets created. + ty::Adt(adt, _) if adt.is_box() => Self::visit_box(bx, layout, is_fn_entry), + // Skip traversing for everything inside of `MaybeDangling` + ty::Adt(adt, _) if adt.is_maybe_dangling() => None, + _ => Self::walk_value(bx, layout, is_fn_entry), + } + } + + /// Recurses through the fields and variants of a value in memory order to create a [`RetagPlan`]. + fn walk_value>( + bx: &mut Bx, + layout: TyAndLayout<'tcx>, + is_fn_entry: bool, + ) -> Option> { + let mut field_plans = FxIndexMap::default(); + let mut variant_plans = FxIndexMap::default(); + + match &layout.fields { + FieldsShape::Union(_) | FieldsShape::Primitive => {} + _ => { + for ix in layout.fields.index_by_increasing_offset() { + let field_layout = layout.field(bx, ix); + if let Some(plan) = Self::build(bx, field_layout, is_fn_entry) { + field_plans.insert(FieldIdx::from_usize(ix), plan); + } + } + } + } + + match &layout.variants { + Variants::Single { .. } | Variants::Empty => {} + Variants::Multiple { variants, .. } => { + for ix in variants.indices() { + let variant_layout = layout.for_variant(bx, ix); + if let Some(plan) = Self::build(bx, variant_layout, is_fn_entry) { + variant_plans.insert(ix, plan); + } + } + } + } + + (!field_plans.is_empty() || !variant_plans.is_empty()) + .then(|| RetagPlan::Recurse { field_plans, variant_plans }) + } + + /// Emits a retag for a `Box`. + fn visit_box>( + bx: &mut Bx, + layout: TyAndLayout<'tcx>, + is_fn_entry: bool, + ) -> Option> { + assert!(layout.ty.is_box()); + assert_eq!(layout.fields.count(), 2, "`Box` must have exactly 2 fields"); + let mut field_plans = FxIndexMap::default(); + + // Only retag the inner pointer of a `Box` if it came from the global allocator. + if layout.ty.is_box_global(bx.tcx()) { + let boxed_ty = layout.ty.expect_boxed_ty(); + let boxed_layout = bx.layout_of(boxed_ty); + if let Some(mut plan) = Self::emit_retag(bx, boxed_layout, None, is_fn_entry) { + // `Unique` + let unique = layout.field(bx, 0); + assert_eq!(unique.fields.count(), 2); + plan = plan.for_field(FieldIdx::ZERO); + + // `NonNull` + let nonnull = unique.field(bx, 0); + assert_eq!(nonnull.fields.count(), 1); + plan = plan.for_field(FieldIdx::ZERO); + + // `*mut T is !null` + let pattern = nonnull.field(bx, 0); + let ty::Pat(base, _) = pattern.ty.kind() else { + unreachable!("`NonNull` should contain a pattern type") + }; + assert_eq!(base.builtin_deref(true), Some(boxed_ty)); + + field_plans.insert(FieldIdx::ZERO, plan); + } + } + + // We always try to retag the second field (the allocator) + let field_layout = layout.field(bx, 1); + if let Some(plan) = Self::build(bx, field_layout, is_fn_entry) { + field_plans.insert(FieldIdx::ONE, plan); + } + + (!field_plans.is_empty()) + .then(|| RetagPlan::Recurse { field_plans, variant_plans: FxIndexMap::default() }) + } + + /// Determines if a pointer needs to be retagged, when it points to + /// a type with the given layout. Returns `None` for mutable pointers + /// to types that are entirely covered by `UnsafePinned`, for which retags + /// are a no-op. + fn emit_retag>( + _bx: &mut Bx, + _pointee_layout: TyAndLayout<'tcx>, + _ptr_kind: Option, + _is_fn_entry: bool, + ) -> Option> { + None + } +} + impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { /// Retags the pointers within an [`OperandRef`]. pub(crate) fn codegen_retag_operand( From d050769aa829d22640e7f499ae253726b143ff20 Mon Sep 17 00:00:00 2001 From: Alex Celeste Date: Thu, 11 Jun 2026 15:02:29 +0100 Subject: [PATCH 09/13] Match expressions had not been updated to also show the match_source, since the time that was added update existing match tests as well remove hashes from output remove specific DefIds for core from output remove additional specifics that can vary and which are not relevant to the test --- compiler/rustc_mir_build/src/thir/print.rs | 3 +- tests/ui/thir-print/thir-tree-match-for.rs | 33 + .../ui/thir-print/thir-tree-match-for.stdout | 1419 +++++++++++++++++ tests/ui/thir-print/thir-tree-match.stdout | 1 + 4 files changed, 1455 insertions(+), 1 deletion(-) create mode 100644 tests/ui/thir-print/thir-tree-match-for.rs create mode 100644 tests/ui/thir-print/thir-tree-match-for.stdout diff --git a/compiler/rustc_mir_build/src/thir/print.rs b/compiler/rustc_mir_build/src/thir/print.rs index 5330e3397db8e..ddb56a04c308d 100644 --- a/compiler/rustc_mir_build/src/thir/print.rs +++ b/compiler/rustc_mir_build/src/thir/print.rs @@ -357,7 +357,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { print_indented!(self, format!("pat: {:?}", pat), depth_lvl + 1); print_indented!(self, "}", depth_lvl); } - Match { scrutinee, arms, .. } => { + Match { scrutinee, arms, match_source } => { print_indented!(self, "Match {", depth_lvl); print_indented!(self, "scrutinee:", depth_lvl + 1); self.print_expr(*scrutinee, depth_lvl + 2); @@ -367,6 +367,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { self.print_arm(*arm_id, depth_lvl + 2); } print_indented!(self, "]", depth_lvl + 1); + print_indented!(self, format!("match_source: {:?}", match_source), depth_lvl + 1); print_indented!(self, "}", depth_lvl); } Block { block } => self.print_block(*block, depth_lvl), diff --git a/tests/ui/thir-print/thir-tree-match-for.rs b/tests/ui/thir-print/thir-tree-match-for.rs new file mode 100644 index 0000000000000..41346b947df91 --- /dev/null +++ b/tests/ui/thir-print/thir-tree-match-for.rs @@ -0,0 +1,33 @@ +//@ check-pass +//@ compile-flags: -Zunpretty=thir-tree +//@ normalize-stdout: "\[[a-z0-9]{4}\]" -> "" +//@ normalize-stdout: "DefId\(\d+:\d+" -> "DefId(N:M" +//@ normalize-stdout: "ReprOptions\s*\{[^}]+\}" -> "ReprOptions {}" + +fn match_non_loop(x:u32, y: u32) { + match x { + 0 | 1 => 0, + 2..3 => 1, + y => 2, + }; +} + +fn match_from_for(x: u32, y: u32) { + for i in x..y { + i; + } +} + +// same resulting structure +fn match_loop_nonfor(x: u32, y: u32) { + match IntoIterator::into_iter(x..y) { + mut iter => loop { + match Iterator::next(&mut iter) { + Option::None => break, + Option::Some(i) => { i; }, + }; + } + } +} + +fn main() {} diff --git a/tests/ui/thir-print/thir-tree-match-for.stdout b/tests/ui/thir-print/thir-tree-match-for.stdout new file mode 100644 index 0000000000000..774261865802f --- /dev/null +++ b/tests/ui/thir-print/thir-tree-match-for.stdout @@ -0,0 +1,1419 @@ +DefId(N:M ~ thir_tree_match_for::match_non_loop): +params: [ + Param { + ty: u32 + ty_span: Some($DIR/thir-tree-match-for.rs:7:21: 7:24 (#0)) + self_kind: None + hir_id: Some(HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).1)) + param: Some( + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:7:19: 7:20 (#0) + kind: PatKind { + Binding { + name: "x" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).2)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ) + } + Param { + ty: u32 + ty_span: Some($DIR/thir-tree-match-for.rs:7:29: 7:32 (#0)) + self_kind: None + hir_id: Some(HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).3)) + param: Some( + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:7:26: 7:27 (#0) + kind: PatKind { + Binding { + name: "y" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).4)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ) + } +] +body: + Expr { + ty: () + temp_scope_id: 25 + span: $DIR/thir-tree-match-for.rs:7:34: 13:2 (#0) + kind: + Scope { + region_scope: Node(25) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).25) + value: + Expr { + ty: () + temp_scope_id: 25 + span: $DIR/thir-tree-match-for.rs:7:34: 13:2 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-match-for.rs:7:34: 13:2 (#0) + region_scope: Node(5) + safety_mode: Safe + stmts: [ + Stmt { + kind: Expr { + scope: Node(24) + expr: + Expr { + ty: i32 + temp_scope_id: 6 + span: $DIR/thir-tree-match-for.rs:8:3: 12:4 (#0) + kind: + Scope { + region_scope: Node(6) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).6) + value: + Expr { + ty: i32 + temp_scope_id: 6 + span: $DIR/thir-tree-match-for.rs:8:3: 12:4 (#0) + kind: + Match { + scrutinee: + Expr { + ty: u32 + temp_scope_id: 7 + span: $DIR/thir-tree-match-for.rs:8:9: 8:10 (#0) + kind: + Scope { + region_scope: Node(7) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).7) + value: + Expr { + ty: u32 + temp_scope_id: 7 + span: $DIR/thir-tree-match-for.rs:8:9: 8:10 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).2)) + } + } + } + } + arms: [ + Arm { + pattern: + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:9:5: 9:10 (#0) + kind: PatKind { + Or { + pats: [ + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:9:5: 9:6 (#0) + kind: PatKind { + Constant { + value: 0_u32 + } + } + } + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:9:9: 9:10 (#0) + kind: PatKind { + Constant { + value: 1_u32 + } + } + } + ] + } + } + } + guard: None + body: + Expr { + ty: i32 + temp_scope_id: 15 + span: $DIR/thir-tree-match-for.rs:9:14: 9:15 (#0) + kind: + Scope { + region_scope: Node(15) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).15) + value: + Expr { + ty: i32 + temp_scope_id: 15 + span: $DIR/thir-tree-match-for.rs:9:14: 9:15 (#0) + kind: + Literal( lit: Spanned { node: Int(Pu128(0), Unsuffixed), span: $DIR/thir-tree-match-for.rs:9:14: 9:15 (#0) }, neg: false) + + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).14) + scope: Node(14) + span: $DIR/thir-tree-match-for.rs:9:5: 9:15 (#0) + } + Arm { + pattern: + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:10:5: 10:9 (#0) + extra: PatExtra { + expanded_const: None + ascriptions: [] + } + kind: PatKind { + Range ( PatRange { lo: Finite(Leaf(0x00000002)), hi: Finite(Leaf(0x00000003)), end: Excluded, ty: u32 } ) + } + } + guard: None + body: + Expr { + ty: i32 + temp_scope_id: 20 + span: $DIR/thir-tree-match-for.rs:10:14: 10:15 (#0) + kind: + Scope { + region_scope: Node(20) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).20) + value: + Expr { + ty: i32 + temp_scope_id: 20 + span: $DIR/thir-tree-match-for.rs:10:14: 10:15 (#0) + kind: + Literal( lit: Spanned { node: Int(Pu128(1), Unsuffixed), span: $DIR/thir-tree-match-for.rs:10:14: 10:15 (#0) }, neg: false) + + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).19) + scope: Node(19) + span: $DIR/thir-tree-match-for.rs:10:5: 10:15 (#0) + } + Arm { + pattern: + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:11:8: 11:9 (#0) + kind: PatKind { + Binding { + name: "y" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).21)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + guard: None + body: + Expr { + ty: i32 + temp_scope_id: 23 + span: $DIR/thir-tree-match-for.rs:11:14: 11:15 (#0) + kind: + Scope { + region_scope: Node(23) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).23) + value: + Expr { + ty: i32 + temp_scope_id: 23 + span: $DIR/thir-tree-match-for.rs:11:14: 11:15 (#0) + kind: + Literal( lit: Spanned { node: Int(Pu128(2), Unsuffixed), span: $DIR/thir-tree-match-for.rs:11:14: 11:15 (#0) }, neg: false) + + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_non_loop).22) + scope: Node(22) + span: $DIR/thir-tree-match-for.rs:11:8: 11:15 (#0) + } + ] + match_source: Normal + } + } + } + } + } + } + ] + expr: [] + } + } + } + } + + +DefId(N:M ~ thir_tree_match_for::match_from_for): +params: [ + Param { + ty: u32 + ty_span: Some($DIR/thir-tree-match-for.rs:15:22: 15:25 (#0)) + self_kind: None + hir_id: Some(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).1)) + param: Some( + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:15:19: 15:20 (#0) + kind: PatKind { + Binding { + name: "x" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).2)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ) + } + Param { + ty: u32 + ty_span: Some($DIR/thir-tree-match-for.rs:15:30: 15:33 (#0)) + self_kind: None + hir_id: Some(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).3)) + param: Some( + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:15:27: 15:28 (#0) + kind: PatKind { + Binding { + name: "y" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).4)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ) + } +] +body: + Expr { + ty: () + temp_scope_id: 45 + span: $DIR/thir-tree-match-for.rs:15:35: 19:2 (#0) + kind: + Scope { + region_scope: Node(45) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).45) + value: + Expr { + ty: () + temp_scope_id: 45 + span: $DIR/thir-tree-match-for.rs:15:35: 19:2 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-match-for.rs:15:35: 19:2 (#0) + region_scope: Node(5) + safety_mode: Safe + stmts: [] + expr: + Expr { + ty: () + temp_scope_id: 44 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Scope { + region_scope: Node(44) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).44) + value: + Expr { + ty: () + temp_scope_id: 44 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Use { + source: + Expr { + ty: () + temp_scope_id: 43 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Scope { + region_scope: Node(43) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).43) + value: + Expr { + ty: () + temp_scope_id: 43 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Match { + scrutinee: + Expr { + ty: std::ops::Range + temp_scope_id: 42 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Scope { + region_scope: Node(42) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).42) + value: + Expr { + ty: std::ops::Range + temp_scope_id: 42 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Call { + ty: FnDef(DefId(N:M ~ core::iter::traits::collect::IntoIterator::into_iter), [std::ops::Range]) + from_hir_call: true + fn_span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + fun: + Expr { + ty: FnDef(DefId(N:M ~ core::iter::traits::collect::IntoIterator::into_iter), [std::ops::Range]) + temp_scope_id: 41 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Scope { + region_scope: Node(41) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).41) + value: + Expr { + ty: FnDef(DefId(N:M ~ core::iter::traits::collect::IntoIterator::into_iter), [std::ops::Range]) + temp_scope_id: 41 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + ZstLiteral(user_ty: None) + } + } + } + args: [ + Expr { + ty: std::ops::Range + temp_scope_id: 6 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#4) + kind: + Scope { + region_scope: Node(6) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).6) + value: + Expr { + ty: std::ops::Range + temp_scope_id: 6 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#4) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(N:M ~ core::ops::range::Range) + variants: [VariantDef { def_id: DefId(N:M ~ core::ops::range::Range), ctor: None, name: "Range", discr: Relative(0), fields: [FieldDef { did: DefId(N:M ~ core::ops::range::Range::start), name: "start", vis: Public, safety: Safe, value: None }, FieldDef { did: DefId(N:M ~ core::ops::range::Range::end), name: "end", vis: Public, safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions {} + } + variant_index: 0 + args: [u32] + user_ty: None + field 0: + Expr { + ty: u32 + temp_scope_id: 7 + span: $DIR/thir-tree-match-for.rs:16:12: 16:13 (#0) + kind: + Scope { + region_scope: Node(7) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).7) + value: + Expr { + ty: u32 + temp_scope_id: 7 + span: $DIR/thir-tree-match-for.rs:16:12: 16:13 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).2)) + } + } + } + } + field 1: + Expr { + ty: u32 + temp_scope_id: 10 + span: $DIR/thir-tree-match-for.rs:16:15: 16:16 (#0) + kind: + Scope { + region_scope: Node(10) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).10) + value: + Expr { + ty: u32 + temp_scope_id: 10 + span: $DIR/thir-tree-match-for.rs:16:15: 16:16 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).4)) + } + } + } + } + base: None + } + } + } + } + ] + } + } + } + } + arms: [ + Arm { + pattern: + Pat { + ty: std::ops::Range + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: PatKind { + Binding { + name: "iter" + mode: BindingMode(No, Mut) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).29)) + ty: std::ops::Range + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + guard: None + body: + Expr { + ty: () + temp_scope_id: 15 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Scope { + region_scope: Node(15) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).15) + value: + Expr { + ty: () + temp_scope_id: 15 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Loop ( + body: + Expr { + ty: () + temp_scope_id: 38 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + region_scope: Node(38) + safety_mode: Safe + stmts: [ + Stmt { + kind: Expr { + scope: Node(37) + expr: + Expr { + ty: () + temp_scope_id: 36 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Scope { + region_scope: Node(36) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).36) + value: + Expr { + ty: () + temp_scope_id: 36 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Match { + scrutinee: + Expr { + ty: std::option::Option + temp_scope_id: 35 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Scope { + region_scope: Node(35) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).35) + value: + Expr { + ty: std::option::Option + temp_scope_id: 35 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Call { + ty: FnDef(DefId(N:M ~ core::iter::traits::iterator::Iterator::next), [std::ops::Range]) + from_hir_call: true + fn_span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + fun: + Expr { + ty: FnDef(DefId(N:M ~ core::iter::traits::iterator::Iterator::next), [std::ops::Range]) + temp_scope_id: 34 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Scope { + region_scope: Node(34) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).34) + value: + Expr { + ty: FnDef(DefId(N:M ~ core::iter::traits::iterator::Iterator::next), [std::ops::Range]) + temp_scope_id: 34 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + ZstLiteral(user_ty: None) + } + } + } + args: [ + Expr { + ty: &'{erased} mut std::ops::Range + temp_scope_id: 32 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Scope { + region_scope: Node(32) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).32) + value: + Expr { + ty: &'{erased} mut std::ops::Range + temp_scope_id: 32 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Borrow ( + borrow_kind: Mut { kind: TwoPhaseBorrow } + arg: + Expr { + ty: std::ops::Range + temp_scope_id: 32 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Deref { + Expr { + ty: &'{erased} mut std::ops::Range + temp_scope_id: 32 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Borrow ( + borrow_kind: Mut { kind: Default } + arg: + Expr { + ty: std::ops::Range + temp_scope_id: 31 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + Scope { + region_scope: Node(31) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).31) + value: + Expr { + ty: std::ops::Range + temp_scope_id: 31 + span: $DIR/thir-tree-match-for.rs:16:12: 16:16 (#7) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).29)) + } + } + } + } + ) + } + } + } + ) + } + } + } + ] + } + } + } + } + arms: [ + Arm { + pattern: + Pat { + ty: std::option::Option + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: PatKind { + Variant { + adt_def: + AdtDef { + did: DefId(N:M ~ core::option::Option) + variants: [VariantDef { def_id: DefId(N:M ~ core::option::Option::None), ctor: Some((Const, DefId(N:M ~ core::option::Option::None::{constructor#0}))), name: "None", discr: Relative(0), fields: [], tainted: None, flags: }, VariantDef { def_id: DefId(N:M ~ core::option::Option::Some), ctor: Some((Fn, DefId(N:M ~ core::option::Option::Some::{constructor#0}))), name: "Some", discr: Relative(1), fields: [FieldDef { did: DefId(N:M ~ core::option::Option::Some::0), name: "0", vis: Public, safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_ENUM + repr: ReprOptions {} + } + args: [u32] + variant_index: 0 + subpatterns: [] + } + } + } + guard: None + body: + Expr { + ty: () + temp_scope_id: 16 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Scope { + region_scope: Node(16) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).16) + value: + Expr { + ty: () + temp_scope_id: 16 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + NeverToAny { + source: + Expr { + ty: ! + temp_scope_id: 16 + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + kind: + Break ( + label: Node(15) + ) + } + } + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).19) + scope: Node(19) + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + } + Arm { + pattern: + Pat { + ty: std::option::Option + span: $DIR/thir-tree-match-for.rs:16:7: 16:8 (#7) + kind: PatKind { + Variant { + adt_def: + AdtDef { + did: DefId(N:M ~ core::option::Option) + variants: [VariantDef { def_id: DefId(N:M ~ core::option::Option::None), ctor: Some((Const, DefId(N:M ~ core::option::Option::None::{constructor#0}))), name: "None", discr: Relative(0), fields: [], tainted: None, flags: }, VariantDef { def_id: DefId(N:M ~ core::option::Option::Some), ctor: Some((Fn, DefId(N:M ~ core::option::Option::Some::{constructor#0}))), name: "Some", discr: Relative(1), fields: [FieldDef { did: DefId(N:M ~ core::option::Option::Some::0), name: "0", vis: Public, safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_ENUM + repr: ReprOptions {} + } + args: [u32] + variant_index: 1 + subpatterns: [ + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:16:7: 16:8 (#0) + kind: PatKind { + Binding { + name: "i" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).14)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ] + } + } + } + guard: None + body: + Expr { + ty: () + temp_scope_id: 27 + span: $DIR/thir-tree-match-for.rs:16:17: 18:4 (#0) + kind: + Scope { + region_scope: Node(27) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).27) + value: + Expr { + ty: () + temp_scope_id: 27 + span: $DIR/thir-tree-match-for.rs:16:17: 18:4 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-match-for.rs:16:17: 18:4 (#0) + region_scope: Node(23) + safety_mode: Safe + stmts: [ + Stmt { + kind: Expr { + scope: Node(26) + expr: + Expr { + ty: u32 + temp_scope_id: 24 + span: $DIR/thir-tree-match-for.rs:17:5: 17:6 (#0) + kind: + Scope { + region_scope: Node(24) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).24) + value: + Expr { + ty: u32 + temp_scope_id: 24 + span: $DIR/thir-tree-match-for.rs:17:5: 17:6 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).14)) + } + } + } + } + } + } + ] + expr: [] + } + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).28) + scope: Node(28) + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + } + ] + match_source: ForLoopDesugar + } + } + } + } + } + } + ] + expr: [] + } + } + ) + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_from_for).39) + scope: Node(39) + span: $DIR/thir-tree-match-for.rs:16:3: 18:4 (#7) + } + ] + match_source: ForLoopDesugar + } + } + } + } + } + } + } + } + } + } + } + } + + +DefId(N:M ~ thir_tree_match_for::match_loop_nonfor): +params: [ + Param { + ty: u32 + ty_span: Some($DIR/thir-tree-match-for.rs:22:25: 22:28 (#0)) + self_kind: None + hir_id: Some(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).1)) + param: Some( + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:22:22: 22:23 (#0) + kind: PatKind { + Binding { + name: "x" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).2)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ) + } + Param { + ty: u32 + ty_span: Some($DIR/thir-tree-match-for.rs:22:33: 22:36 (#0)) + self_kind: None + hir_id: Some(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).3)) + param: Some( + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:22:30: 22:31 (#0) + kind: PatKind { + Binding { + name: "y" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).4)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ) + } +] +body: + Expr { + ty: () + temp_scope_id: 48 + span: $DIR/thir-tree-match-for.rs:22:38: 31:2 (#0) + kind: + Scope { + region_scope: Node(48) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).48) + value: + Expr { + ty: () + temp_scope_id: 48 + span: $DIR/thir-tree-match-for.rs:22:38: 31:2 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-match-for.rs:22:38: 31:2 (#0) + region_scope: Node(5) + safety_mode: Safe + stmts: [] + expr: + Expr { + ty: () + temp_scope_id: 6 + span: $DIR/thir-tree-match-for.rs:23:3: 30:4 (#0) + kind: + Scope { + region_scope: Node(6) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).6) + value: + Expr { + ty: () + temp_scope_id: 6 + span: $DIR/thir-tree-match-for.rs:23:3: 30:4 (#0) + kind: + Match { + scrutinee: + Expr { + ty: std::ops::Range + temp_scope_id: 7 + span: $DIR/thir-tree-match-for.rs:23:9: 23:38 (#0) + kind: + Scope { + region_scope: Node(7) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).7) + value: + Expr { + ty: std::ops::Range + temp_scope_id: 7 + span: $DIR/thir-tree-match-for.rs:23:9: 23:38 (#0) + kind: + Call { + ty: FnDef(DefId(N:M ~ core::iter::traits::collect::IntoIterator::into_iter), [std::ops::Range]) + from_hir_call: true + fn_span: $DIR/thir-tree-match-for.rs:23:9: 23:38 (#0) + fun: + Expr { + ty: FnDef(DefId(N:M ~ core::iter::traits::collect::IntoIterator::into_iter), [std::ops::Range]) + temp_scope_id: 8 + span: $DIR/thir-tree-match-for.rs:23:9: 23:32 (#0) + kind: + Scope { + region_scope: Node(8) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).8) + value: + Expr { + ty: FnDef(DefId(N:M ~ core::iter::traits::collect::IntoIterator::into_iter), [std::ops::Range]) + temp_scope_id: 8 + span: $DIR/thir-tree-match-for.rs:23:9: 23:32 (#0) + kind: + ZstLiteral(user_ty: None) + } + } + } + args: [ + Expr { + ty: std::ops::Range + temp_scope_id: 11 + span: $DIR/thir-tree-match-for.rs:23:33: 23:37 (#8) + kind: + Scope { + region_scope: Node(11) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).11) + value: + Expr { + ty: std::ops::Range + temp_scope_id: 11 + span: $DIR/thir-tree-match-for.rs:23:33: 23:37 (#8) + kind: + Adt { + adt_def: + AdtDef { + did: DefId(N:M ~ core::ops::range::Range) + variants: [VariantDef { def_id: DefId(N:M ~ core::ops::range::Range), ctor: None, name: "Range", discr: Relative(0), fields: [FieldDef { did: DefId(N:M ~ core::ops::range::Range::start), name: "start", vis: Public, safety: Safe, value: None }, FieldDef { did: DefId(N:M ~ core::ops::range::Range::end), name: "end", vis: Public, safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_STRUCT + repr: ReprOptions {} + } + variant_index: 0 + args: [u32] + user_ty: None + field 0: + Expr { + ty: u32 + temp_scope_id: 12 + span: $DIR/thir-tree-match-for.rs:23:33: 23:34 (#0) + kind: + Scope { + region_scope: Node(12) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).12) + value: + Expr { + ty: u32 + temp_scope_id: 12 + span: $DIR/thir-tree-match-for.rs:23:33: 23:34 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).2)) + } + } + } + } + field 1: + Expr { + ty: u32 + temp_scope_id: 15 + span: $DIR/thir-tree-match-for.rs:23:36: 23:37 (#0) + kind: + Scope { + region_scope: Node(15) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).15) + value: + Expr { + ty: u32 + temp_scope_id: 15 + span: $DIR/thir-tree-match-for.rs:23:36: 23:37 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).4)) + } + } + } + } + base: None + } + } + } + } + ] + } + } + } + } + arms: [ + Arm { + pattern: + Pat { + ty: std::ops::Range + span: $DIR/thir-tree-match-for.rs:24:5: 24:13 (#0) + kind: PatKind { + Binding { + name: "iter" + mode: BindingMode(No, Mut) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).19)) + ty: std::ops::Range + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + guard: None + body: + Expr { + ty: () + temp_scope_id: 21 + span: $DIR/thir-tree-match-for.rs:24:17: 29:6 (#0) + kind: + Scope { + region_scope: Node(21) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).21) + value: + Expr { + ty: () + temp_scope_id: 21 + span: $DIR/thir-tree-match-for.rs:24:17: 29:6 (#0) + kind: + Loop ( + body: + Expr { + ty: () + temp_scope_id: 22 + span: $DIR/thir-tree-match-for.rs:24:22: 29:6 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-match-for.rs:24:22: 29:6 (#0) + region_scope: Node(22) + safety_mode: Safe + stmts: [ + Stmt { + kind: Expr { + scope: Node(47) + expr: + Expr { + ty: () + temp_scope_id: 23 + span: $DIR/thir-tree-match-for.rs:25:7: 28:8 (#0) + kind: + Scope { + region_scope: Node(23) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).23) + value: + Expr { + ty: () + temp_scope_id: 23 + span: $DIR/thir-tree-match-for.rs:25:7: 28:8 (#0) + kind: + Match { + scrutinee: + Expr { + ty: std::option::Option + temp_scope_id: 24 + span: $DIR/thir-tree-match-for.rs:25:13: 25:38 (#0) + kind: + Scope { + region_scope: Node(24) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).24) + value: + Expr { + ty: std::option::Option + temp_scope_id: 24 + span: $DIR/thir-tree-match-for.rs:25:13: 25:38 (#0) + kind: + Call { + ty: FnDef(DefId(N:M ~ core::iter::traits::iterator::Iterator::next), [std::ops::Range]) + from_hir_call: true + fn_span: $DIR/thir-tree-match-for.rs:25:13: 25:38 (#0) + fun: + Expr { + ty: FnDef(DefId(N:M ~ core::iter::traits::iterator::Iterator::next), [std::ops::Range]) + temp_scope_id: 25 + span: $DIR/thir-tree-match-for.rs:25:13: 25:27 (#0) + kind: + Scope { + region_scope: Node(25) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).25) + value: + Expr { + ty: FnDef(DefId(N:M ~ core::iter::traits::iterator::Iterator::next), [std::ops::Range]) + temp_scope_id: 25 + span: $DIR/thir-tree-match-for.rs:25:13: 25:27 (#0) + kind: + ZstLiteral(user_ty: None) + } + } + } + args: [ + Expr { + ty: &'{erased} mut std::ops::Range + temp_scope_id: 28 + span: $DIR/thir-tree-match-for.rs:25:28: 25:37 (#0) + kind: + Scope { + region_scope: Node(28) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).28) + value: + Expr { + ty: &'{erased} mut std::ops::Range + temp_scope_id: 28 + span: $DIR/thir-tree-match-for.rs:25:28: 25:37 (#0) + kind: + Borrow ( + borrow_kind: Mut { kind: TwoPhaseBorrow } + arg: + Expr { + ty: std::ops::Range + temp_scope_id: 28 + span: $DIR/thir-tree-match-for.rs:25:28: 25:37 (#0) + kind: + Deref { + Expr { + ty: &'{erased} mut std::ops::Range + temp_scope_id: 28 + span: $DIR/thir-tree-match-for.rs:25:28: 25:37 (#0) + kind: + Borrow ( + borrow_kind: Mut { kind: Default } + arg: + Expr { + ty: std::ops::Range + temp_scope_id: 29 + span: $DIR/thir-tree-match-for.rs:25:33: 25:37 (#0) + kind: + Scope { + region_scope: Node(29) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).29) + value: + Expr { + ty: std::ops::Range + temp_scope_id: 29 + span: $DIR/thir-tree-match-for.rs:25:33: 25:37 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).19)) + } + } + } + } + ) + } + } + } + ) + } + } + } + ] + } + } + } + } + arms: [ + Arm { + pattern: + Pat { + ty: std::option::Option + span: $DIR/thir-tree-match-for.rs:26:11: 26:23 (#0) + kind: PatKind { + Variant { + adt_def: + AdtDef { + did: DefId(N:M ~ core::option::Option) + variants: [VariantDef { def_id: DefId(N:M ~ core::option::Option::None), ctor: Some((Const, DefId(N:M ~ core::option::Option::None::{constructor#0}))), name: "None", discr: Relative(0), fields: [], tainted: None, flags: }, VariantDef { def_id: DefId(N:M ~ core::option::Option::Some), ctor: Some((Fn, DefId(N:M ~ core::option::Option::Some::{constructor#0}))), name: "Some", discr: Relative(1), fields: [FieldDef { did: DefId(N:M ~ core::option::Option::Some::0), name: "0", vis: Public, safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_ENUM + repr: ReprOptions {} + } + args: [u32] + variant_index: 0 + subpatterns: [] + } + } + } + guard: None + body: + Expr { + ty: () + temp_scope_id: 36 + span: $DIR/thir-tree-match-for.rs:26:27: 26:32 (#0) + kind: + Scope { + region_scope: Node(36) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).36) + value: + Expr { + ty: () + temp_scope_id: 36 + span: $DIR/thir-tree-match-for.rs:26:27: 26:32 (#0) + kind: + NeverToAny { + source: + Expr { + ty: ! + temp_scope_id: 36 + span: $DIR/thir-tree-match-for.rs:26:27: 26:32 (#0) + kind: + Break ( + label: Node(21) + ) + } + } + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).35) + scope: Node(35) + span: $DIR/thir-tree-match-for.rs:26:11: 26:32 (#0) + } + Arm { + pattern: + Pat { + ty: std::option::Option + span: $DIR/thir-tree-match-for.rs:27:11: 27:26 (#0) + kind: PatKind { + Variant { + adt_def: + AdtDef { + did: DefId(N:M ~ core::option::Option) + variants: [VariantDef { def_id: DefId(N:M ~ core::option::Option::None), ctor: Some((Const, DefId(N:M ~ core::option::Option::None::{constructor#0}))), name: "None", discr: Relative(0), fields: [], tainted: None, flags: }, VariantDef { def_id: DefId(N:M ~ core::option::Option::Some), ctor: Some((Fn, DefId(N:M ~ core::option::Option::Some::{constructor#0}))), name: "Some", discr: Relative(1), fields: [FieldDef { did: DefId(N:M ~ core::option::Option::Some::0), name: "0", vis: Public, safety: Safe, value: None }], tainted: None, flags: }] + flags: IS_ENUM + repr: ReprOptions {} + } + args: [u32] + variant_index: 1 + subpatterns: [ + Pat { + ty: u32 + span: $DIR/thir-tree-match-for.rs:27:24: 27:25 (#0) + kind: PatKind { + Binding { + name: "i" + mode: BindingMode(No, Not) + var: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).40)) + ty: u32 + is_primary: true + is_shorthand: false + subpattern: None + } + } + } + ] + } + } + } + guard: None + body: + Expr { + ty: () + temp_scope_id: 42 + span: $DIR/thir-tree-match-for.rs:27:30: 27:36 (#0) + kind: + Scope { + region_scope: Node(42) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).42) + value: + Expr { + ty: () + temp_scope_id: 42 + span: $DIR/thir-tree-match-for.rs:27:30: 27:36 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-match-for.rs:27:30: 27:36 (#0) + region_scope: Node(43) + safety_mode: Safe + stmts: [ + Stmt { + kind: Expr { + scope: Node(46) + expr: + Expr { + ty: u32 + temp_scope_id: 44 + span: $DIR/thir-tree-match-for.rs:27:32: 27:33 (#0) + kind: + Scope { + region_scope: Node(44) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).44) + value: + Expr { + ty: u32 + temp_scope_id: 44 + span: $DIR/thir-tree-match-for.rs:27:32: 27:33 (#0) + kind: + VarRef { + id: LocalVarId(HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).40)) + } + } + } + } + } + } + ] + expr: [] + } + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).41) + scope: Node(41) + span: $DIR/thir-tree-match-for.rs:27:11: 27:36 (#0) + } + ] + match_source: Normal + } + } + } + } + } + } + ] + expr: [] + } + } + ) + } + } + } + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::match_loop_nonfor).20) + scope: Node(20) + span: $DIR/thir-tree-match-for.rs:24:5: 29:6 (#0) + } + ] + match_source: Normal + } + } + } + } + } + } + } + } + + +DefId(N:M ~ thir_tree_match_for::main): +params: [ +] +body: + Expr { + ty: () + temp_scope_id: 2 + span: $DIR/thir-tree-match-for.rs:33:11: 33:13 (#0) + kind: + Scope { + region_scope: Node(2) + hir_id: HirId(DefId(N:M ~ thir_tree_match_for::main).2) + value: + Expr { + ty: () + temp_scope_id: 2 + span: $DIR/thir-tree-match-for.rs:33:11: 33:13 (#0) + kind: + Block { + targeted_by_break: false + span: $DIR/thir-tree-match-for.rs:33:11: 33:13 (#0) + region_scope: Node(1) + safety_mode: Safe + stmts: [] + expr: [] + } + } + } + } + + diff --git a/tests/ui/thir-print/thir-tree-match.stdout b/tests/ui/thir-print/thir-tree-match.stdout index 31f8d368736c0..33baafeb48b26 100644 --- a/tests/ui/thir-print/thir-tree-match.stdout +++ b/tests/ui/thir-print/thir-tree-match.stdout @@ -246,6 +246,7 @@ body: span: $DIR/thir-tree-match.rs:19:9: 19:28 (#0) } ] + match_source: Normal } } } From f6e99c16a586dbaf906824af8f7781730e285c68 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 11 Jun 2026 11:57:54 +0200 Subject: [PATCH 10/13] Rename `rustc_hir_analysis/src/errors.rs` into `rustc_hir_analysis/src/diagnostics.rs` --- compiler/rustc_hir_analysis/src/autoderef.rs | 2 +- .../src/check/always_applicable.rs | 12 +-- .../rustc_hir_analysis/src/check/check.rs | 41 +++++----- .../src/check/compare_eii.rs | 2 +- .../src/check/compare_impl_item.rs | 2 +- .../src/check/compare_impl_item/refine.rs | 4 +- .../rustc_hir_analysis/src/check/entry.rs | 19 ++--- .../rustc_hir_analysis/src/check/intrinsic.rs | 2 +- compiler/rustc_hir_analysis/src/check/mod.rs | 18 ++--- .../rustc_hir_analysis/src/check/wfcheck.rs | 35 ++++---- .../src/coherence/builtin.rs | 80 ++++++++++--------- .../src/coherence/inherent_impls.rs | 34 +++++--- .../rustc_hir_analysis/src/coherence/mod.rs | 8 +- .../src/coherence/orphan.rs | 49 +++++++----- compiler/rustc_hir_analysis/src/collect.rs | 43 +++++----- .../rustc_hir_analysis/src/collect/dump.rs | 2 +- .../src/collect/resolve_bound_vars.rs | 22 ++--- .../rustc_hir_analysis/src/collect/type_of.rs | 7 +- .../src/collect/type_of/opaque.rs | 2 +- compiler/rustc_hir_analysis/src/delegation.rs | 4 +- .../src/{errors.rs => diagnostics.rs} | 0 .../precise_captures.rs | 0 .../remove_or_use_generic.rs | 0 .../wrong_number_of_generic_args.rs | 0 .../src/hir_ty_lowering/bounds.rs | 57 +++++++------ .../src/hir_ty_lowering/cmse.rs | 12 +-- .../src/hir_ty_lowering/dyn_trait.rs | 6 +- .../src/hir_ty_lowering/errors.rs | 52 ++++++------ .../src/hir_ty_lowering/generics.rs | 2 +- .../src/hir_ty_lowering/mod.rs | 6 +- .../rustc_hir_analysis/src/impl_wf_check.rs | 4 +- .../src/impl_wf_check/min_specialization.rs | 8 +- compiler/rustc_hir_analysis/src/lib.rs | 6 +- compiler/rustc_hir_typeck/src/expr.rs | 2 +- 34 files changed, 296 insertions(+), 247 deletions(-) rename compiler/rustc_hir_analysis/src/{errors.rs => diagnostics.rs} (100%) rename compiler/rustc_hir_analysis/src/{errors => diagnostics}/precise_captures.rs (100%) rename compiler/rustc_hir_analysis/src/{errors => diagnostics}/remove_or_use_generic.rs (100%) rename compiler/rustc_hir_analysis/src/{errors => diagnostics}/wrong_number_of_generic_args.rs (100%) diff --git a/compiler/rustc_hir_analysis/src/autoderef.rs b/compiler/rustc_hir_analysis/src/autoderef.rs index 1637f022a4a78..3742999d05b5d 100644 --- a/compiler/rustc_hir_analysis/src/autoderef.rs +++ b/compiler/rustc_hir_analysis/src/autoderef.rs @@ -7,7 +7,7 @@ use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::traits::ObligationCtxt; use tracing::{debug, instrument}; -use crate::errors::AutoDerefReachedRecursionLimit; +use crate::diagnostics::AutoDerefReachedRecursionLimit; use crate::traits; use crate::traits::query::evaluate_obligation::InferCtxtExt; diff --git a/compiler/rustc_hir_analysis/src/check/always_applicable.rs b/compiler/rustc_hir_analysis/src/check/always_applicable.rs index 02870afeb4ef1..7a12b1bf8142a 100644 --- a/compiler/rustc_hir_analysis/src/check/always_applicable.rs +++ b/compiler/rustc_hir_analysis/src/check/always_applicable.rs @@ -16,7 +16,7 @@ use rustc_span::sym; use rustc_trait_selection::regions::InferCtxtRegionExt; use rustc_trait_selection::traits::{self, ObligationCtxt}; -use crate::errors; +use crate::diagnostics; use crate::hir::def_id::{DefId, LocalDefId}; /// This function confirms that the `Drop` implementation identified by @@ -42,12 +42,12 @@ pub(crate) fn check_drop_impl( match tcx.impl_polarity(drop_impl_did) { ty::ImplPolarity::Positive => {} ty::ImplPolarity::Negative => { - return Err(tcx.dcx().emit_err(errors::DropImplPolarity::Negative { + return Err(tcx.dcx().emit_err(diagnostics::DropImplPolarity::Negative { span: tcx.def_span(drop_impl_did), })); } ty::ImplPolarity::Reservation => { - return Err(tcx.dcx().emit_err(errors::DropImplPolarity::Reservation { + return Err(tcx.dcx().emit_err(diagnostics::DropImplPolarity::Reservation { span: tcx.def_span(drop_impl_did), })); } @@ -393,7 +393,7 @@ fn check_drop_xor_pin_drop<'tcx>( match (drop_span, pin_drop_span) { (None, None) => { if tcx.features().pin_ergonomics() { - return Err(tcx.dcx().emit_err(crate::errors::MissingOneOfTraitItem { + return Err(tcx.dcx().emit_err(crate::diagnostics::MissingOneOfTraitItem { span: tcx.def_span(drop_impl_did), note: None, missing_items_msg: "drop`, `pin_drop".to_string(), @@ -408,7 +408,7 @@ fn check_drop_xor_pin_drop<'tcx>( if tcx.adt_def(adt_def_id).is_pin_project() { let pin_v2_span = rustc_hir::find_attr!(tcx, adt_def_id, PinV2(attr) => *attr); let adt_name = tcx.item_name(adt_def_id); - return Err(tcx.dcx().emit_err(crate::errors::PinV2WithoutPinDrop { + return Err(tcx.dcx().emit_err(crate::diagnostics::PinV2WithoutPinDrop { span, pin_v2_span, adt_name, @@ -424,7 +424,7 @@ fn check_drop_xor_pin_drop<'tcx>( } } (Some(drop_span), Some(pin_drop_span)) => { - return Err(tcx.dcx().emit_err(crate::errors::ConflictImplDropAndPinDrop { + return Err(tcx.dcx().emit_err(crate::diagnostics::ConflictImplDropAndPinDrop { span: tcx.def_span(drop_impl_did), drop_span, pin_drop_span, diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 319e987be6947..917360ab8119e 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -38,6 +38,7 @@ use crate::check::wfcheck::{ check_associated_item, check_trait_item, check_type_defn, check_variances_for_type_defn, check_where_clauses, enter_wf_checking_ctxt, }; +use crate::diagnostics; fn add_abi_diag_help(abi: ExternAbi, diag: &mut Diag<'_, T>) { if let ExternAbi::Cdecl { unwind } = abi { @@ -95,7 +96,7 @@ pub fn check_custom_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, fn_sig: FnSig<'_>, if fn_sig.abi() == ExternAbi::Custom { // Function definitions that use `extern "custom"` must be naked functions. if !find_attr!(tcx, def_id, Naked(_)) { - tcx.dcx().emit_err(crate::errors::AbiCustomClothedFunction { + tcx.dcx().emit_err(crate::diagnostics::AbiCustomClothedFunction { span: fn_sig_span, naked_span: tcx.def_span(def_id).shrink_to_lo(), }); @@ -181,9 +182,9 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b Some(Node::Field(field)) => (field.span, field.ty.span), _ => unreachable!("mir field has to correspond to hir field"), }; - tcx.dcx().emit_err(errors::InvalidUnionField { + tcx.dcx().emit_err(diagnostics::InvalidUnionField { field_span, - sugg: errors::InvalidUnionFieldSuggestion { + sugg: diagnostics::InvalidUnionFieldSuggestion { lo: ty_span.shrink_to_lo(), hi: ty_span.shrink_to_hi(), }, @@ -217,7 +218,7 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) { if matches!(tcx.def_kind(def_id), DefKind::Static{ .. } if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) => { - tcx.dcx().emit_err(errors::TooLargeStatic { span }); + tcx.dcx().emit_err(diagnostics::TooLargeStatic { span }); return; } // SIMD types with invalid layout (e.g., zero-length) should emit an error @@ -599,7 +600,7 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe } hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => { if let Some(prev_non_lifetime_param) = prev_non_lifetime_param { - tcx.dcx().emit_err(errors::LifetimesMustBeFirst { + tcx.dcx().emit_err(diagnostics::LifetimesMustBeFirst { lifetime_span: ident.span, name: ident.name, other_span: prev_non_lifetime_param.span, @@ -611,7 +612,7 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe let ident = ident.normalize_to_macros_2_0(); if let Some(span) = seen_params.insert(ident, ident.span) { - tcx.dcx().emit_err(errors::DuplicatePreciseCapture { + tcx.dcx().emit_err(diagnostics::DuplicatePreciseCapture { name: ident.name, first_span: span, second_span: ident.span, @@ -675,14 +676,14 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()) .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id())) { - tcx.dcx().emit_err(errors::LifetimeNotCaptured { + tcx.dcx().emit_err(diagnostics::LifetimeNotCaptured { opaque_span, use_span, param_span: tcx.def_span(def_id), }); } else { if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait { - tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured { + tcx.dcx().emit_err(diagnostics::LifetimeImplicitlyCaptured { opaque_span, param_span: tcx.def_span(param.def_id), }); @@ -691,7 +692,7 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe // have not duplicated the lifetime but captured the original. // The "effective" `use_span` will be the span of the opaque itself, // and the param span will be the def span of the param. - tcx.dcx().emit_err(errors::LifetimeNotCaptured { + tcx.dcx().emit_err(diagnostics::LifetimeNotCaptured { opaque_span, use_span: opaque_span, param_span: use_span, @@ -704,13 +705,13 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe ty::GenericParamDefKind::Type { .. } => { if matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) { // FIXME(precise_capturing): Structured suggestion for this would be useful - tcx.dcx().emit_err(errors::SelfTyNotCaptured { + tcx.dcx().emit_err(diagnostics::SelfTyNotCaptured { trait_span: tcx.def_span(param.def_id), opaque_span: tcx.def_span(opaque_def_id), }); } else { // FIXME(precise_capturing): Structured suggestion for this would be useful - tcx.dcx().emit_err(errors::ParamNotCaptured { + tcx.dcx().emit_err(diagnostics::ParamNotCaptured { param_span: tcx.def_span(param.def_id), opaque_span: tcx.def_span(opaque_def_id), kind: "type", @@ -719,7 +720,7 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe } ty::GenericParamDefKind::Const { .. } => { // FIXME(precise_capturing): Structured suggestion for this would be useful - tcx.dcx().emit_err(errors::ParamNotCaptured { + tcx.dcx().emit_err(diagnostics::ParamNotCaptured { param_span: tcx.def_span(param.def_id), opaque_span: tcx.def_span(opaque_def_id), kind: "const", @@ -755,7 +756,7 @@ fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) { ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args), _ => true, } { - tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) }); + tcx.dcx().emit_err(diagnostics::LinkageType { span: tcx.def_span(def_id) }); } } } @@ -1238,8 +1239,8 @@ pub(super) fn check_specialization_validity<'tcx>( let ident = tcx.item_ident(impl_item); let err = match tcx.span_of_impl(parent_impl) { - Ok(sp) => errors::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp }, - Err(cname) => errors::ImplNotMarkedDefault::Err { span, ident, cname }, + Ok(sp) => diagnostics::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp }, + Err(cname) => diagnostics::ImplNotMarkedDefault::Err { span, ident, cname }, }; tcx.dcx().emit_err(err); @@ -1255,7 +1256,7 @@ fn check_overriding_final_trait_item<'tcx>( impl_item: ty::AssocItem, ) { if trait_item.defaultness(tcx).is_final() { - tcx.dcx().emit_err(errors::OverridingFinalTraitFunction { + tcx.dcx().emit_err(diagnostics::OverridingFinalTraitFunction { impl_span: tcx.def_span(impl_item.def_id), trait_span: tcx.def_span(trait_item.def_id), ident: tcx.item_ident(impl_item.def_id), @@ -1330,7 +1331,7 @@ fn check_impl_items_against_trait<'tcx>( rustc_lint_defs::builtin::DEAD_CODE, tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()), tcx.def_span(ty_impl_item.def_id), - errors::UselessImplItem, + diagnostics::UselessImplItem, ) } @@ -1638,7 +1639,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) { // over-aligned field to an aligned location before running its destructor, which would // move a structurally pinned field out from under a `Pin<&mut _>` that was handed out. if def.is_pin_project() { - tcx.dcx().emit_err(errors::PinV2OnPacked { + tcx.dcx().emit_err(diagnostics::PinV2OnPacked { span: sp, pin_v2_span: find_attr!(tcx, def.did(), PinV2(span) => *span), adt_name: tcx.item_name(def.did()), @@ -2119,11 +2120,11 @@ fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalD || (*bounded_params).get(¶m.index).is_some_and(|&&pred_sp| pred_sp != span); let const_param_help = !has_explicit_bounds; - let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter { + let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter { span, param_name, param_def_kind: tcx.def_descr(param.def_id), - help: errors::UnusedGenericParameterHelp::TyAlias { param_name }, + help: diagnostics::UnusedGenericParameterHelp::TyAlias { param_name }, usage_spans: vec![], const_param_help, }); diff --git a/compiler/rustc_hir_analysis/src/check/compare_eii.rs b/compiler/rustc_hir_analysis/src/check/compare_eii.rs index 1bcdfd9f25a5b..57824a91a680f 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_eii.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_eii.rs @@ -26,7 +26,7 @@ use super::potentially_plural_count; use crate::check::compare_impl_item::{ CheckNumberOfEarlyBoundRegionsError, check_number_of_early_bound_regions, }; -use crate::errors::{ +use crate::diagnostics::{ EiiDefkindMismatch, EiiDefkindMismatchStaticMutability, EiiDefkindMismatchStaticSafety, EiiWithGenerics, LifetimesOrBoundsMismatchOnEii, }; diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 964f801e53819..b3d1f2a1489a5 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -29,7 +29,7 @@ use rustc_trait_selection::traits::{ use tracing::{debug, instrument}; use super::potentially_plural_count; -use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture}; +use crate::diagnostics::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture}; pub(super) mod refine; diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs index cdda54f7eb943..1ef1b39d4aab1 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs @@ -367,7 +367,7 @@ fn report_mismatched_rpitit_signature<'tcx>( if is_internal { REFINING_IMPL_TRAIT_INTERNAL } else { REFINING_IMPL_TRAIT_REACHABLE }, tcx.local_def_id_to_hir_id(impl_m_def_id.expect_local()), span, - crate::errors::ReturnPositionImplTraitInTraitRefined { + crate::diagnostics::ReturnPositionImplTraitInTraitRefined { impl_return_span, trait_return_span, pre, @@ -464,7 +464,7 @@ fn report_mismatched_rpitit_captures<'tcx>( if is_internal { REFINING_IMPL_TRAIT_INTERNAL } else { REFINING_IMPL_TRAIT_REACHABLE }, tcx.local_def_id_to_hir_id(impl_opaque_def_id), use_bound_span, - crate::errors::ReturnPositionImplTraitInTraitRefinedLifetimes { + crate::diagnostics::ReturnPositionImplTraitInTraitRefinedLifetimes { suggestion_span: use_bound_span, suggestion, }, diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs index 9c9ac5b75afe6..9fae7ddaca64e 100644 --- a/compiler/rustc_hir_analysis/src/check/entry.rs +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -13,7 +13,7 @@ use rustc_trait_selection::regions::InferCtxtRegionExt; use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode}; use super::check_function_signature; -use crate::errors; +use crate::diagnostics; pub(crate) fn check_for_entry_fn(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> { match tcx.entry_fn(()) { @@ -92,15 +92,16 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) -> Result<(), ErrorGuar let main_asyncness = tcx.asyncness(main_def_id); if main_asyncness.is_async() { let asyncness_span = main_fn_asyncness_span(tcx, main_def_id); - return Err(tcx - .dcx() - .emit_err(errors::MainFunctionAsync { span: main_span, asyncness: asyncness_span })); + return Err(tcx.dcx().emit_err(diagnostics::MainFunctionAsync { + span: main_span, + asyncness: asyncness_span, + })); } if let Some(attr_span) = find_attr!(tcx, main_def_id, TrackCaller(span) => *span) { return Err(tcx .dcx() - .emit_err(errors::TrackCallerOnMain { span: attr_span, annotated: main_span })); + .emit_err(diagnostics::TrackCallerOnMain { span: attr_span, annotated: main_span })); } if !tcx.codegen_fn_attrs(main_def_id).target_features.is_empty() @@ -108,7 +109,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) -> Result<(), ErrorGuar && !tcx.sess.target.is_like_wasm && !tcx.sess.opts.actually_rustdoc { - return Err(tcx.dcx().emit_err(errors::TargetFeatureOnMain { main: main_span })); + return Err(tcx.dcx().emit_err(diagnostics::TargetFeatureOnMain { main: main_span })); } // Main should have no WC, so empty param env is OK here. @@ -120,7 +121,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) -> Result<(), ErrorGuar let Some(return_ty) = return_ty.no_bound_vars() else { return Err(tcx .dcx() - .emit_err(errors::MainFunctionReturnTypeGeneric { span: return_ty_span })); + .emit_err(diagnostics::MainFunctionReturnTypeGeneric { span: return_ty_span })); }; let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis()); let cause = traits::ObligationCause::new( @@ -168,14 +169,14 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) -> Result<(), ErrorGuar let main_fn_predicates = tcx.predicates_of(main_def_id); if main_fn_generics.count() != 0 || !main_fnsig.bound_vars().is_empty() { let generics_param_span = main_fn_generics_params_span(tcx, main_def_id); - return Err(tcx.dcx().emit_err(errors::MainFunctionGenericParameters { + return Err(tcx.dcx().emit_err(diagnostics::MainFunctionGenericParameters { span: generics_param_span.unwrap_or(main_span), label_span: generics_param_span, })); } else if !main_fn_predicates.predicates.is_empty() { // generics may bring in implicit predicates, so we skip this check if generics is present. let generics_where_clauses_span = main_fn_where_clauses_span(tcx, main_def_id); - return Err(tcx.dcx().emit_err(errors::WhereClauseOnMain { + return Err(tcx.dcx().emit_err(diagnostics::WhereClauseOnMain { span: generics_where_clauses_span.unwrap_or(main_span), generics_span: generics_where_clauses_span, })); diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index a4d6056e47bdc..09a3cf4d182f8 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -8,7 +8,7 @@ use rustc_span::def_id::LocalDefId; use rustc_span::{Span, Symbol, sym}; use crate::check::check_function_signature; -use crate::errors::{UnrecognizedIntrinsicFunction, WrongNumberOfGenericArgumentsToIntrinsic}; +use crate::diagnostics::{UnrecognizedIntrinsicFunction, WrongNumberOfGenericArgumentsToIntrinsic}; fn equate_intrinsic_type<'tcx>( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 45dd7c15526a8..0b57b4e259a85 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -103,7 +103,7 @@ use tracing::debug; use self::compare_impl_item::collect_return_position_impl_trait_in_trait_tys; use self::region::region_scope_tree; -use crate::{check_c_variadic_abi, errors}; +use crate::{check_c_variadic_abi, diagnostics}; /// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`] pub(super) fn provide(providers: &mut Providers) { @@ -127,7 +127,7 @@ fn adt_destructor(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option if let Some(async_dtor) = adt_async_destructor(tcx, def_id) { // When type has AsyncDrop impl, but doesn't have Drop impl, generate error let span = tcx.def_span(async_dtor.impl_did); - tcx.dcx().emit_err(errors::AsyncDropWithoutSyncDrop { span }); + tcx.dcx().emit_err(diagnostics::AsyncDropWithoutSyncDrop { span }); } } dtor @@ -244,14 +244,14 @@ fn missing_items_err( let code = format!("{padding}{snippet}\n{padding}"); if let Some(span) = tcx.hir_span_if_local(trait_item.def_id) { missing_trait_item_label - .push(errors::MissingTraitItemLabel { span, item: trait_item.name() }); - missing_trait_item.push(errors::MissingTraitItemSuggestion { + .push(diagnostics::MissingTraitItemLabel { span, item: trait_item.name() }); + missing_trait_item.push(diagnostics::MissingTraitItemSuggestion { span: sugg_sp, code, snippet, }); } else { - missing_trait_item_none.push(errors::MissingTraitItemSuggestionNone { + missing_trait_item_none.push(diagnostics::MissingTraitItemSuggestionNone { span: sugg_sp, code, snippet, @@ -259,7 +259,7 @@ fn missing_items_err( } } - tcx.dcx().emit_err(errors::MissingTraitItem { + tcx.dcx().emit_err(diagnostics::MissingTraitItem { span: tcx.span_of_impl(impl_def_id.to_def_id()).unwrap(), missing_items_msg, missing_trait_item_label, @@ -277,7 +277,7 @@ fn missing_items_must_implement_one_of_err( let missing_items_msg = missing_items.iter().map(Ident::to_string).collect::>().join("`, `"); - tcx.dcx().emit_err(errors::MissingOneOfTraitItem { + tcx.dcx().emit_err(diagnostics::MissingOneOfTraitItem { span: impl_span, note: annotation_span, missing_items_msg, @@ -302,7 +302,7 @@ fn default_body_is_unstable( None => none_note = true, }; - let mut err = tcx.dcx().create_err(errors::MissingTraitItemUnstable { + let mut err = tcx.dcx().create_err(diagnostics::MissingTraitItemUnstable { span: impl_span, some_note, none_note, @@ -582,7 +582,7 @@ fn bad_variant_count<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>, sp: Span, d spans = start.to_vec(); many = Some(*end); } - tcx.dcx().emit_err(errors::TransparentEnumVariant { + tcx.dcx().emit_err(diagnostics::TransparentEnumVariant { span: sp, spans, many, diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 4fca6b93f1fff..51c345a455f90 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -44,8 +44,8 @@ use tracing::{debug, instrument}; use super::compare_eii::{compare_eii_function_types, compare_eii_statics}; use crate::autoderef::Autoderef; use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params}; -use crate::errors; -use crate::errors::InvalidReceiverTyHint; +use crate::diagnostics; +use crate::diagnostics::InvalidReceiverTyHint; pub(super) struct WfCheckingCtxt<'a, 'tcx> { pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>, @@ -815,7 +815,7 @@ fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_i .collect(); if !shadowed.is_empty() { let shadowee = if let [shadowed] = shadowed[..] { - errors::SupertraitItemShadowee::Labeled { + diagnostics::SupertraitItemShadowee::Labeled { span: tcx.def_span(shadowed.def_id), supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()), } @@ -826,14 +826,17 @@ fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_i (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id)) }) .unzip(); - errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() } + diagnostics::SupertraitItemShadowee::Several { + traits: traits.into(), + spans: spans.into(), + } }; tcx.emit_node_span_lint( SHADOWING_SUPERTRAIT_ITEMS, tcx.local_def_id_to_hir_id(trait_item_def_id), tcx.def_span(trait_item_def_id), - errors::SupertraitItemShadowing { + diagnostics::SupertraitItemShadowing { item: item_name, subtrait: tcx.item_name(trait_def_id.to_def_id()), shadowee, @@ -1874,17 +1877,21 @@ fn check_method_receiver<'tcx>( _ => None, }; - tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint }) + tcx.dcx().emit_err(diagnostics::InvalidReceiverTy { + span, + receiver_ty, + hint, + }) } ReceiverValidityError::DoesNotDeref => { - tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes { + tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes { span, receiver_ty, }) } - ReceiverValidityError::MethodGenericParamUsed => { - tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty }) - } + ReceiverValidityError::MethodGenericParamUsed => tcx + .dcx() + .emit_err(diagnostics::InvalidGenericReceiverTy { span, receiver_ty }), } } }); @@ -2191,12 +2198,12 @@ fn report_bivariance<'tcx>( let help = match item.kind { ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => { if let Some(def_id) = tcx.lang_items().phantom_data() { - errors::UnusedGenericParameterHelp::Adt { + diagnostics::UnusedGenericParameterHelp::Adt { param_name, phantom_data: tcx.def_path_str(def_id), } } else { - errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name } + diagnostics::UnusedGenericParameterHelp::AdtNoPhantomData { param_name } } } item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"), @@ -2226,7 +2233,7 @@ fn report_bivariance<'tcx>( // subset is very involved, and the fact we're mentioning recursion at all is // likely to guide the user in the right direction. if is_probably_cyclical { - return tcx.dcx().emit_err(errors::RecursiveGenericParameter { + return tcx.dcx().emit_err(diagnostics::RecursiveGenericParameter { spans: usage_spans, param_span: param.span, param_name, @@ -2240,7 +2247,7 @@ fn report_bivariance<'tcx>( let const_param_help = matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds); - let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter { + let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter { span: param.span, param_name, param_def_kind: tcx.def_descr(param.def_id.to_def_id()), diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 2ba7e026461f3..1b174631aa890 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -26,7 +26,7 @@ use rustc_trait_selection::traits::misc::{ use rustc_trait_selection::traits::{self, FulfillmentError, ObligationCause, ObligationCtxt}; use tracing::debug; -use crate::errors; +use crate::diagnostics; pub(super) fn check_trait<'tcx>( tcx: TyCtxt<'tcx>, @@ -84,7 +84,7 @@ fn visit_implementation_of_drop(checker: &Checker<'_>) -> Result<(), ErrorGuaran let impl_ = tcx.hir_expect_item(impl_did).expect_impl(); - Err(tcx.dcx().emit_err(errors::DropImplOnWrongItem { + Err(tcx.dcx().emit_err(diagnostics::DropImplOnWrongItem { span: impl_.self_ty.span, trait_: tcx.item_name(checker.impl_header.trait_ref.skip_binder().def_id), })) @@ -123,12 +123,12 @@ fn visit_implementation_of_copy(checker: &Checker<'_>) -> Result<(), ErrorGuaran } Err(CopyImplementationError::NotAnAdt) => { let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span; - Err(tcx.dcx().emit_err(errors::CopyImplOnNonAdt { span })) + Err(tcx.dcx().emit_err(diagnostics::CopyImplOnNonAdt { span })) } Err(CopyImplementationError::HasDestructor(did)) => { let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span; let impl_ = tcx.def_span(did); - Err(tcx.dcx().emit_err(errors::CopyImplOnTypeWithDtor { span, impl_ })) + Err(tcx.dcx().emit_err(diagnostics::CopyImplOnTypeWithDtor { span, impl_ })) } Err(CopyImplementationError::HasUnsafeFields) => { let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span; @@ -159,7 +159,7 @@ fn visit_implementation_of_unpin(checker: &Checker<'_>) -> Result<(), ErrorGuara // `&mut T` that dereferenced by `Pin<&mut T>`, which breaks the safety contract of // `Pin<&mut U>` for `U: !Unpin`. ty::Adt(adt, _) if adt.is_pin_project() => { - return Err(tcx.dcx().emit_err(crate::errors::ImplUnpinForPinProjectedType { + return Err(tcx.dcx().emit_err(crate::diagnostics::ImplUnpinForPinProjectedType { span, adt_span: tcx.def_span(adt.did()), adt_name: tcx.item_name(adt.did()), @@ -201,7 +201,7 @@ fn visit_implementation_of_const_param_ty(checker: &Checker<'_>) -> Result<(), E let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span; return Err(tcx .dcx() - .emit_err(errors::ConstParamTyFieldVisMismatch { span })); + .emit_err(diagnostics::ConstParamTyFieldVisMismatch { span })); } } } @@ -226,13 +226,13 @@ fn visit_implementation_of_const_param_ty(checker: &Checker<'_>) -> Result<(), E } Err(ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed) => { let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span; - Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnNonAdt { span })) + Err(tcx.dcx().emit_err(diagnostics::ConstParamTyImplOnNonAdt { span })) } Err(ConstParamTyImplementationError::NonExhaustive(attr_span)) => { let defn_span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span; Err(tcx .dcx() - .emit_err(errors::ConstParamTyImplOnNonExhaustive { defn_span, attr_span })) + .emit_err(diagnostics::ConstParamTyImplOnNonExhaustive { defn_span, attr_span })) } Err(ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(infringing_tys)) => { let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span; @@ -246,7 +246,7 @@ fn visit_implementation_of_const_param_ty(checker: &Checker<'_>) -> Result<(), E } Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => { let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span; - Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnUnsized { span })) + Err(tcx.dcx().emit_err(diagnostics::ConstParamTyImplOnUnsized { span })) } } } @@ -337,7 +337,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() match (source.kind(), target.kind()) { (&ty::Pat(_, pat_a), &ty::Pat(_, pat_b)) => { if pat_a != pat_b { - return Err(tcx.dcx().emit_err(errors::CoerceSamePatKind { + return Err(tcx.dcx().emit_err(diagnostics::CoerceSamePatKind { span, trait_name, pat_a: pat_a.to_string(), @@ -359,7 +359,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() if def_a != def_b { let source_path = tcx.def_path_str(def_a.did()); let target_path = tcx.def_path_str(def_b.did()); - return Err(tcx.dcx().emit_err(errors::CoerceSameStruct { + return Err(tcx.dcx().emit_err(diagnostics::CoerceSameStruct { span, trait_name, note: true, @@ -369,7 +369,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() } if def_a.repr().c() || def_a.repr().packed() { - return Err(tcx.dcx().emit_err(errors::DispatchFromDynRepr { span })); + return Err(tcx.dcx().emit_err(diagnostics::DispatchFromDynRepr { span })); } let fields = &def_a.non_enum_variant().fields; @@ -409,7 +409,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() return None; } - res = Err(tcx.dcx().emit_err(errors::DispatchFromDynZST { + res = Err(tcx.dcx().emit_err(diagnostics::DispatchFromDynZST { span, name: field.ident(tcx), ty: ty_a, @@ -424,7 +424,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() res?; if coerced_fields.is_empty() { - return Err(tcx.dcx().emit_err(errors::CoerceNoField { + return Err(tcx.dcx().emit_err(diagnostics::CoerceNoField { span, trait_name, note: true, @@ -440,7 +440,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() let errors = ocx.evaluate_obligations_error_on_ambiguity(); if !errors.is_empty() { if is_from_coerce_pointee_derive(tcx, span) { - return Err(tcx.dcx().emit_err(errors::CoerceFieldValidity { + return Err(tcx.dcx().emit_err(diagnostics::CoerceFieldValidity { span, trait_name, ty: trait_ref.self_ty(), @@ -457,7 +457,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() Ok(()) } else { - return Err(tcx.dcx().emit_err(errors::CoerceMulti { + return Err(tcx.dcx().emit_err(diagnostics::CoerceMulti { span, trait_name, number: coerced_fields.len(), @@ -465,7 +465,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() })); } } - _ => Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name })), + _ => Err(tcx.dcx().emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name })), } } @@ -517,7 +517,7 @@ pub(crate) fn reborrow_info<'tcx>( if trait_impl_lifetime_params_count(tcx, impl_did) != 1 { return Err(tcx .dcx() - .emit_err(errors::CoerceSharedNotSingleLifetimeParam { span, trait_name })); + .emit_err(diagnostics::CoerceSharedNotSingleLifetimeParam { span, trait_name })); } assert_eq!(trait_ref.def_id, reborrow_trait); @@ -528,7 +528,9 @@ pub(crate) fn reborrow_info<'tcx>( &ty::Adt(def, args) if def.is_struct() => (def, args), _ => { // Note: reusing error here as it takes trait_name as argument. - return Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name })); + return Err(tcx + .dcx() + .emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name })); } }; @@ -543,7 +545,7 @@ pub(crate) fn reborrow_info<'tcx>( tcx.def_span(impl_did) }; - return Err(tcx.dcx().emit_err(errors::CoerceSharedMulti { span, trait_name })); + return Err(tcx.dcx().emit_err(diagnostics::CoerceSharedMulti { span, trait_name })); } if data_fields.is_empty() { @@ -614,7 +616,7 @@ pub(crate) fn coerce_shared_info<'tcx>( if trait_impl_lifetime_params_count(tcx, impl_did) != 1 { return Err(tcx .dcx() - .emit_err(errors::CoerceSharedNotSingleLifetimeParam { span, trait_name })); + .emit_err(diagnostics::CoerceSharedNotSingleLifetimeParam { span, trait_name })); } assert_eq!(trait_ref.def_id, coerce_shared_trait); @@ -660,7 +662,9 @@ pub(crate) fn coerce_shared_info<'tcx>( tcx.def_span(impl_did) }; - return Err(tcx.dcx().emit_err(errors::CoerceSharedMulti { span, trait_name })); + return Err(tcx + .dcx() + .emit_err(diagnostics::CoerceSharedMulti { span, trait_name })); } if a_data_fields.len() == 1 { @@ -679,7 +683,9 @@ pub(crate) fn coerce_shared_info<'tcx>( _ => { // Note: reusing CoerceUnsizedNonStruct error as it takes trait_name as argument. - return Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name })); + return Err(tcx + .dcx() + .emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name })); } }; @@ -836,7 +842,7 @@ pub(crate) fn coerce_unsized_info<'tcx>( let (source, target, trait_def_id, kind, field_span) = match (source.kind(), target.kind()) { (&ty::Pat(ty_a, pat_a), &ty::Pat(ty_b, pat_b)) => { if pat_a != pat_b { - return Err(tcx.dcx().emit_err(errors::CoerceSamePatKind { + return Err(tcx.dcx().emit_err(diagnostics::CoerceSamePatKind { span, trait_name, pat_a: pat_a.to_string(), @@ -871,7 +877,7 @@ pub(crate) fn coerce_unsized_info<'tcx>( if def_a != def_b { let source_path = tcx.def_path_str(def_a.did()); let target_path = tcx.def_path_str(def_b.did()); - return Err(tcx.dcx().emit_err(errors::CoerceSameStruct { + return Err(tcx.dcx().emit_err(diagnostics::CoerceSameStruct { span, trait_name, note: true, @@ -959,7 +965,7 @@ pub(crate) fn coerce_unsized_info<'tcx>( .collect::>(); if diff_fields.is_empty() { - return Err(tcx.dcx().emit_err(errors::CoerceNoField { + return Err(tcx.dcx().emit_err(diagnostics::CoerceNoField { span, trait_name, note: true, @@ -974,7 +980,7 @@ pub(crate) fn coerce_unsized_info<'tcx>( tcx.def_span(impl_did) }; - return Err(tcx.dcx().emit_err(errors::CoerceMulti { + return Err(tcx.dcx().emit_err(diagnostics::CoerceMulti { span, trait_name, number: diff_fields.len(), @@ -988,7 +994,9 @@ pub(crate) fn coerce_unsized_info<'tcx>( } _ => { - return Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name })); + return Err(tcx + .dcx() + .emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name })); } }; @@ -1006,7 +1014,7 @@ pub(crate) fn coerce_unsized_info<'tcx>( if !errors.is_empty() { if is_from_coerce_pointee_derive(tcx, span) { - return Err(tcx.dcx().emit_err(errors::CoerceFieldValidity { + return Err(tcx.dcx().emit_err(diagnostics::CoerceFieldValidity { span, trait_name, ty: trait_ref.self_ty(), @@ -1119,7 +1127,7 @@ fn infringing_fields_error<'tcx>( let mut notes = Vec::new(); for ((ty, error_predicate), spans) in errors { let span: MultiSpan = spans.into(); - notes.push(errors::ImplForTyRequires { + notes.push(diagnostics::ImplForTyRequires { span, error_predicate, trait_name: trait_name.clone(), @@ -1127,7 +1135,7 @@ fn infringing_fields_error<'tcx>( }); } - let mut err = tcx.dcx().create_err(errors::TraitCannotImplForTy { + let mut err = tcx.dcx().create_err(diagnostics::TraitCannotImplForTy { span: impl_span, trait_name, label_spans, @@ -1155,10 +1163,10 @@ fn visit_implementation_of_coerce_pointee_validity( tcx.impl_trait_ref(checker.impl_def_id).instantiate_identity().skip_norm_wip().self_ty(); let span = tcx.def_span(checker.impl_def_id); if !tcx.is_builtin_derived(checker.impl_def_id.into()) { - return Err(tcx.dcx().emit_err(errors::CoercePointeeNoUserValidityAssertion { span })); + return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNoUserValidityAssertion { span })); } let ty::Adt(def, _args) = self_ty.kind() else { - return Err(tcx.dcx().emit_err(errors::CoercePointeeNotConcreteType { span })); + return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNotConcreteType { span })); }; let did = def.did(); // Now get a more precise span of the `struct`. @@ -1166,13 +1174,13 @@ fn visit_implementation_of_coerce_pointee_validity( if !def.is_struct() { return Err(tcx .dcx() - .emit_err(errors::CoercePointeeNotStruct { span, kind: def.descr().into() })); + .emit_err(diagnostics::CoercePointeeNotStruct { span, kind: def.descr().into() })); } if !def.repr().transparent() { - return Err(tcx.dcx().emit_err(errors::CoercePointeeNotTransparent { span })); + return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNotTransparent { span })); } if def.all_fields().next().is_none() { - return Err(tcx.dcx().emit_err(errors::CoercePointeeNoField { span })); + return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNoField { span })); } Ok(()) } diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index 52567667b0fe6..d154503f4ec04 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -16,7 +16,7 @@ use rustc_middle::ty::fast_reject::{SimplifiedType, TreatParams, simplify_type}; use rustc_middle::ty::{self, CrateInherentImpls, Ty, TyCtxt}; use rustc_span::ErrorGuaranteed; -use crate::errors; +use crate::diagnostics; /// On-demand query: yields a map containing all types mapped to their inherent impls. pub(crate) fn crate_inherent_impls( @@ -80,14 +80,17 @@ impl<'tcx> InherentCollect<'tcx> { if self.tcx.features().rustc_attrs() { if !find_attr!(self.tcx, ty_def_id, RustcHasIncoherentInherentImpls) { let impl_span = self.tcx.def_span(impl_def_id); - return Err(self.tcx.dcx().emit_err(errors::InherentTyOutside { span: impl_span })); + return Err(self + .tcx + .dcx() + .emit_err(diagnostics::InherentTyOutside { span: impl_span })); } let items = self.tcx.associated_item_def_ids(impl_def_id); for &impl_item in items { if !find_attr!(self.tcx, impl_item, RustcAllowIncoherentImpl(_)) { let impl_span = self.tcx.def_span(impl_def_id); - return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsideRelevant { + return Err(self.tcx.dcx().emit_err(diagnostics::InherentTyOutsideRelevant { span: impl_span, help_span: self.tcx.def_span(impl_item), })); @@ -103,7 +106,7 @@ impl<'tcx> InherentCollect<'tcx> { Ok(()) } else { let impl_span = self.tcx.def_span(impl_def_id); - let mut err = errors::InherentTyOutsideNew { span: impl_span, note: None }; + let mut err = diagnostics::InherentTyOutsideNew { span: impl_span, note: None }; if let hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)) = self.tcx.hir_node_by_def_id(impl_def_id).expect_item().expect_impl().self_ty.kind @@ -111,7 +114,7 @@ impl<'tcx> InherentCollect<'tcx> { { let ty_name = self.tcx.def_path_str(def_id); let alias_ty_name = self.tcx.type_of(def_id).skip_binder().to_string(); - err.note = Some(errors::InherentTyOutsideNewAliasNote { + err.note = Some(diagnostics::InherentTyOutsideNewAliasNote { span: self.tcx.def_span(def_id), ty_name, alias_ty_name, @@ -133,19 +136,24 @@ impl<'tcx> InherentCollect<'tcx> { for &impl_item in items { if !find_attr!(self.tcx, impl_item, RustcAllowIncoherentImpl(_)) { let span = self.tcx.def_span(impl_def_id); - return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsidePrimitive { - span, - help_span: self.tcx.def_span(impl_item), - })); + return Err(self.tcx.dcx().emit_err( + diagnostics::InherentTyOutsidePrimitive { + span, + help_span: self.tcx.def_span(impl_item), + }, + )); } } } else { let span = self.tcx.def_span(impl_def_id); let mut note = None; if let ty::Ref(_, subty, _) = ty.kind() { - note = Some(errors::InherentPrimitiveTyNote { subty: *subty }); + note = Some(diagnostics::InherentPrimitiveTyNote { subty: *subty }); } - return Err(self.tcx.dcx().emit_err(errors::InherentPrimitiveTy { span, note })); + return Err(self + .tcx + .dcx() + .emit_err(diagnostics::InherentPrimitiveTy { span, note })); } } @@ -178,7 +186,7 @@ impl<'tcx> InherentCollect<'tcx> { self.check_def_id(id, self_ty, data.principal_def_id().unwrap()) } ty::Dynamic(..) => { - Err(self.tcx.dcx().emit_err(errors::InherentDyn { span: item_span })) + Err(self.tcx.dcx().emit_err(diagnostics::InherentDyn { span: item_span })) } ty::Pat(_, _) => unreachable!(), ty::Bool @@ -200,7 +208,7 @@ impl<'tcx> InherentCollect<'tcx> { .. }) | ty::Param(_) => { - Err(self.tcx.dcx().emit_err(errors::InherentNominal { span: item_span })) + Err(self.tcx.dcx().emit_err(diagnostics::InherentNominal { span: item_span })) } ty::FnDef(..) | ty::Closure(..) diff --git a/compiler/rustc_hir_analysis/src/coherence/mod.rs b/compiler/rustc_hir_analysis/src/coherence/mod.rs index 05a9f68131819..237c2c72ca3bc 100644 --- a/compiler/rustc_hir_analysis/src/coherence/mod.rs +++ b/compiler/rustc_hir_analysis/src/coherence/mod.rs @@ -16,7 +16,7 @@ use rustc_span::{ErrorGuaranteed, sym}; use tracing::debug; use crate::check::always_applicable; -use crate::errors; +use crate::diagnostics; mod builtin; mod inherent_impls; @@ -97,12 +97,14 @@ fn enforce_trait_manually_implementable( && !impl_header_span.allows_unstable(sym::specialization) && !impl_header_span.allows_unstable(sym::min_specialization) { - return Err(tcx.dcx().emit_err(errors::SpecializationTrait { span: impl_header_span })); + return Err(tcx + .dcx() + .emit_err(diagnostics::SpecializationTrait { span: impl_header_span })); } } if !trait_def.impl_restriction.is_allowed_in(impl_def_id.to_def_id(), tcx) { - return Err(tcx.dcx().emit_err(errors::ImplOfRestrictedTrait { + return Err(tcx.dcx().emit_err(diagnostics::ImplOfRestrictedTrait { impl_span: impl_header_span, restriction_span: trait_def.impl_restriction.expect_span(), restriction_path: trait_def.impl_restriction.restriction_path(tcx), diff --git a/compiler/rustc_hir_analysis/src/coherence/orphan.rs b/compiler/rustc_hir_analysis/src/coherence/orphan.rs index bacc1f1549973..7042849c11bfd 100644 --- a/compiler/rustc_hir_analysis/src/coherence/orphan.rs +++ b/compiler/rustc_hir_analysis/src/coherence/orphan.rs @@ -16,7 +16,7 @@ use rustc_trait_selection::traits::{ }; use tracing::{debug, instrument}; -use crate::errors; +use crate::diagnostics; #[instrument(level = "debug", skip(tcx))] pub(crate) fn orphan_check_impl( @@ -242,7 +242,7 @@ pub(crate) fn orphan_check_impl( match local_impl { LocalImpl::Allow => {} LocalImpl::Disallow { problematic_kind } => { - return Err(tcx.dcx().emit_err(errors::TraitsWithDefaultImpl { + return Err(tcx.dcx().emit_err(diagnostics::TraitsWithDefaultImpl { span: tcx.def_span(impl_def_id), traits: tcx.def_path_str(trait_def_id), problematic_kind, @@ -254,13 +254,13 @@ pub(crate) fn orphan_check_impl( match nonlocal_impl { NonlocalImpl::Allow => {} NonlocalImpl::DisallowBecauseNonlocal => { - return Err(tcx.dcx().emit_err(errors::CrossCrateTraitsDefined { + return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraitsDefined { span: tcx.def_span(impl_def_id), traits: tcx.def_path_str(trait_def_id), })); } NonlocalImpl::DisallowOther => { - return Err(tcx.dcx().emit_err(errors::CrossCrateTraits { + return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraits { span: tcx.def_span(impl_def_id), traits: tcx.def_path_str(trait_def_id), self_ty, @@ -374,11 +374,11 @@ fn emit_orphan_check_error<'tcx>( let span = tcx.def_span(impl_def_id); let mut diag = tcx.dcx().create_err(match trait_ref.self_ty().kind() { - ty::Adt(..) => errors::OnlyCurrentTraits::Outside { span, note: () }, + ty::Adt(..) => diagnostics::OnlyCurrentTraits::Outside { span, note: () }, _ if trait_ref.self_ty().is_primitive() => { - errors::OnlyCurrentTraits::Primitive { span, note: () } + diagnostics::OnlyCurrentTraits::Primitive { span, note: () } } - _ => errors::OnlyCurrentTraits::Arbitrary { span, note: () }, + _ => diagnostics::OnlyCurrentTraits::Arbitrary { span, note: () }, }); for &(mut ty, is_target_ty) in &tys { @@ -398,9 +398,9 @@ fn emit_orphan_check_error<'tcx>( match *ty.kind() { ty::Slice(_) => { if is_foreign { - diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span }); + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span }); } else { - diag.subdiagnostic(errors::OnlyCurrentTraitsName { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName { span, name: "slices", }); @@ -408,9 +408,9 @@ fn emit_orphan_check_error<'tcx>( } ty::Array(..) => { if is_foreign { - diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span }); + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span }); } else { - diag.subdiagnostic(errors::OnlyCurrentTraitsName { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName { span, name: "arrays", }); @@ -418,36 +418,39 @@ fn emit_orphan_check_error<'tcx>( } ty::Tuple(..) => { if is_foreign { - diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span }); + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span }); } else { - diag.subdiagnostic(errors::OnlyCurrentTraitsName { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName { span, name: "tuples", }); } } ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }) => { - diag.subdiagnostic(errors::OnlyCurrentTraitsOpaque { span }); + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsOpaque { span }); } ty::RawPtr(ptr_ty, mutbl) => { if !trait_ref.self_ty().has_param() { - diag.subdiagnostic(errors::OnlyCurrentTraitsPointerSugg { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsPointerSugg { wrapper_span: impl_.self_ty.span, struct_span: item.span.shrink_to_lo(), mut_key: mutbl.prefix_str(), ptr_ty, }); } - diag.subdiagnostic(errors::OnlyCurrentTraitsPointer { span, pointer: ty }); + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsPointer { + span, + pointer: ty, + }); } ty::Adt(adt_def, _) => { - diag.subdiagnostic(errors::OnlyCurrentTraitsAdt { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsAdt { span, name: tcx.def_path_str(adt_def.did()), }); } _ => { - diag.subdiagnostic(errors::OnlyCurrentTraitsTy { span, ty }); + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsTy { span, ty }); } } } @@ -461,13 +464,15 @@ fn emit_orphan_check_error<'tcx>( let span = name.span; reported.get_or_insert(match local_ty { - Some(local_type) => tcx.dcx().emit_err(errors::TyParamFirstLocal { + Some(local_type) => tcx.dcx().emit_err(diagnostics::TyParamFirstLocal { span, note: (), param: name, local_type, }), - None => tcx.dcx().emit_err(errors::TyParamSome { span, note: (), param: name }), + None => { + tcx.dcx().emit_err(diagnostics::TyParamSome { span, note: (), param: name }) + } }); } reported.unwrap() // FIXME(fmease): This is very likely reachable. @@ -491,13 +496,13 @@ fn lint_uncovered_ty_params<'tcx>( UNCOVERED_PARAM_IN_PROJECTION, hir_id, span, - errors::TyParamFirstLocalLint { span, note: (), param: name, local_type }, + diagnostics::TyParamFirstLocalLint { span, note: (), param: name, local_type }, ), None => tcx.emit_node_span_lint( UNCOVERED_PARAM_IN_PROJECTION, hir_id, span, - errors::TyParamSomeLint { span, note: (), param: name }, + diagnostics::TyParamSomeLint { span, note: (), param: name }, ), }; } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 48b281851d3db..c8f6e5da69b56 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -44,7 +44,7 @@ use rustc_trait_selection::traits::{ }; use tracing::{debug, instrument}; -use crate::errors::{self, ElidedLifetimesAreNotAllowedInDelegations}; +use crate::diagnostics::{self, ElidedLifetimesAreNotAllowedInDelegations}; use crate::hir_ty_lowering::{HirTyLowerer, InherentAssocCandidate, RegionInferReason}; pub(crate) mod dump; @@ -235,7 +235,7 @@ fn bad_placeholder<'cx, 'tcx>( let kind = if kind.ends_with('s') { format!("{kind}es") } else { format!("{kind}s") }; spans.sort(); - cx.dcx().create_err(errors::PlaceholderNotAllowedItemSignatures { spans, kind }) + cx.dcx().create_err(diagnostics::PlaceholderNotAllowedItemSignatures { spans, kind }) } impl<'tcx> ItemCtxt<'tcx> { @@ -479,7 +479,7 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { [] => (generics.span, format!("<{lt_name}>")), [bound, ..] => (bound.span.shrink_to_lo(), format!("{lt_name}, ")), }; - mpart_sugg = Some(errors::AssociatedItemTraitUninferredGenericParamsMultipartSuggestion { + mpart_sugg = Some(diagnostics::AssociatedItemTraitUninferredGenericParamsMultipartSuggestion { fspan: lt_sp, first: sugg, sspan: span.with_hi(item_segment.ident.span.lo()), @@ -520,13 +520,15 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { _ => {} } - Err(self.tcx().dcx().emit_err(errors::AssociatedItemTraitUninferredGenericParams { - span, - inferred_sugg, - bound, - mpart_sugg, - what: self.tcx.def_descr(item_def_id), - })) + Err(self.tcx().dcx().emit_err( + diagnostics::AssociatedItemTraitUninferredGenericParams { + span, + inferred_sugg, + bound, + mpart_sugg, + what: self.tcx.def_descr(item_def_id), + }, + )) } } @@ -666,7 +668,7 @@ pub(super) fn check_enum_variant_types(tcx: TyCtxt<'_>, def_id: LocalDefId) { Some(discr) } else { let span = tcx.def_span(variant.def_id); - tcx.dcx().emit_err(errors::EnumDiscriminantOverflowed { + tcx.dcx().emit_err(diagnostics::EnumDiscriminantOverflowed { span, discr: prev_discr.unwrap().to_string(), item_name: tcx.item_ident(variant.def_id), @@ -728,8 +730,8 @@ struct NestedSpan { } impl NestedSpan { - fn to_field_already_declared_nested_help(&self) -> errors::FieldAlreadyDeclaredNestedHelp { - errors::FieldAlreadyDeclaredNestedHelp { span: self.span } + fn to_field_already_declared_nested_help(&self) -> diagnostics::FieldAlreadyDeclaredNestedHelp { + diagnostics::FieldAlreadyDeclaredNestedHelp { span: self.span } } } @@ -767,14 +769,14 @@ impl<'tcx> FieldUniquenessCheckContext<'tcx> { let field_name = field_name.normalize_to_macros_2_0(); match (field_decl, self.seen_fields.get(&field_name).copied()) { (NotNested(span), Some(NotNested(prev_span))) => { - self.tcx.dcx().emit_err(errors::FieldAlreadyDeclared::NotNested { + self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::NotNested { field_name, span, prev_span, }); } (NotNested(span), Some(Nested(prev))) => { - self.tcx.dcx().emit_err(errors::FieldAlreadyDeclared::PreviousNested { + self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::PreviousNested { field_name, span, prev_span: prev.span, @@ -786,7 +788,7 @@ impl<'tcx> FieldUniquenessCheckContext<'tcx> { Nested(current @ NestedSpan { span, nested_field_span, .. }), Some(NotNested(prev_span)), ) => { - self.tcx.dcx().emit_err(errors::FieldAlreadyDeclared::CurrentNested { + self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::CurrentNested { field_name, span, nested_field_span, @@ -795,7 +797,7 @@ impl<'tcx> FieldUniquenessCheckContext<'tcx> { }); } (Nested(current @ NestedSpan { span, nested_field_span }), Some(Nested(prev))) => { - self.tcx.dcx().emit_err(errors::FieldAlreadyDeclared::BothNested { + self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::BothNested { field_name, span, nested_field_span, @@ -945,7 +947,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { let paren_sugar = find_attr!(attrs, RustcParenSugar); if paren_sugar && !tcx.features().unboxed_closures() { - tcx.dcx().emit_err(errors::ParenSugarAttribute { span: item.span }); + tcx.dcx().emit_err(diagnostics::ParenSugarAttribute { span: item.span }); } // Only regular traits can be marker. @@ -1442,7 +1444,7 @@ fn check_impl_constness( } (None, _) | (_, false) => (None, ""), }; - tcx.dcx().emit_err(errors::ConstImplForNonConstTrait { + tcx.dcx().emit_err(diagnostics::ConstImplForNonConstTrait { trait_ref_span: hir_trait_ref.path.span, trait_name, suggestion, @@ -1511,7 +1513,8 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( .source_map() .span_to_snippet(hir_ty.span) .map_or_else(|_| String::new(), |s| format!(" `{s}`")); - tcx.dcx().emit_err(errors::SIMDFFIHighlyExperimental { span: hir_ty.span, snip }); + tcx.dcx() + .emit_err(diagnostics::SIMDFFIHighlyExperimental { span: hir_ty.span, snip }); } }; for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) { diff --git a/compiler/rustc_hir_analysis/src/collect/dump.rs b/compiler/rustc_hir_analysis/src/collect/dump.rs index 6f875a5bbde49..87769531f1f5a 100644 --- a/compiler/rustc_hir_analysis/src/collect/dump.rs +++ b/compiler/rustc_hir_analysis/src/collect/dump.rs @@ -22,7 +22,7 @@ pub(crate) fn opaque_hidden_types(tcx: TyCtxt<'_>) { let ty = tcx.type_of(id).instantiate_identity().skip_norm_wip(); let span = tcx.def_span(id); - tcx.dcx().emit_err(crate::errors::TypeOf { span, ty }); + tcx.dcx().emit_err(crate::diagnostics::TypeOf { span, ty }); } } diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 7c6f73e1f2bc7..70129192faa2c 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -30,7 +30,7 @@ use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::{Ident, Span, sym}; use tracing::{debug, debug_span, instrument}; -use crate::errors; +use crate::diagnostics; use crate::hir::definitions::PerParentDisambiguatorState; #[extension(trait RegionExt)] @@ -482,7 +482,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { if !infer_spans.is_empty() { self.tcx .dcx() - .emit_err(errors::ClosureImplicitHrtb { spans: infer_spans, for_sp }); + .emit_err(diagnostics::ClosureImplicitHrtb { spans: infer_spans, for_sp }); } } @@ -669,7 +669,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { LifetimeKind::ImplicitObjectLifetimeDefault | LifetimeKind::Infer | LifetimeKind::Static => { - self.tcx.dcx().emit_err(errors::BadPreciseCapture { + self.tcx.dcx().emit_err(diagnostics::BadPreciseCapture { span: lt.ident.span, kind: "lifetime", found: format!("`{}`", lt.ident.name), @@ -682,7 +682,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { self.resolve_type_ref(def_id.expect_local(), param.hir_id); } Res::SelfTyAlias { alias_to, .. } => { - self.tcx.dcx().emit_err(errors::PreciseCaptureSelfAlias { + self.tcx.dcx().emit_err(diagnostics::PreciseCaptureSelfAlias { span: param.ident.span, self_span: self.tcx.def_span(alias_to), what: self.tcx.def_descr(alias_to), @@ -1380,7 +1380,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { let def_span = self.tcx.def_span(param_def_id); let guar = match self.tcx.def_kind(param_def_id) { DefKind::LifetimeParam => { - self.tcx.dcx().emit_err(errors::CannotCaptureLateBound::Lifetime { + self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Lifetime { use_span, def_span, what, @@ -1435,7 +1435,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { Scope::Binder { where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), .. } => { - self.tcx.dcx().emit_err(errors::LateBoundInApit::Lifetime { + self.tcx.dcx().emit_err(diagnostics::LateBoundInApit::Lifetime { span: lifetime_ref.ident.span, param_span: self.tcx.def_span(region_def_id), }); @@ -1526,7 +1526,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { let decl_span = rustc_errors::MultiSpan::from_spans(errors.decl_spans); // Ensure that the parent of the def is an item, not HRTB - let guar = self.tcx.dcx().emit_err(errors::OpaqueCapturesHigherRankedLifetime { + let guar = self.tcx.dcx().emit_err(diagnostics::OpaqueCapturesHigherRankedLifetime { span, label: Some(errors.capture_spans[0]), decl_span, @@ -1634,14 +1634,14 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { let def_span = self.tcx.def_span(param_def_id); let guar = match self.tcx.def_kind(param_def_id) { DefKind::ConstParam => { - self.tcx.dcx().emit_err(errors::CannotCaptureLateBound::Const { + self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Const { use_span, def_span, what, }) } DefKind::TyParam => { - self.tcx.dcx().emit_err(errors::CannotCaptureLateBound::Type { + self.tcx.dcx().emit_err(diagnostics::CannotCaptureLateBound::Type { use_span, def_span, what, @@ -1676,11 +1676,11 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), .. } => { let guar = self.tcx.dcx().emit_err(match self.tcx.def_kind(param_def_id) { - DefKind::TyParam => errors::LateBoundInApit::Type { + DefKind::TyParam => diagnostics::LateBoundInApit::Type { span: self.tcx.hir_span(hir_id), param_span: self.tcx.def_span(param_def_id), }, - DefKind::ConstParam => errors::LateBoundInApit::Const { + DefKind::ConstParam => diagnostics::LateBoundInApit::Const { span: self.tcx.hir_span(hir_id), param_span: self.tcx.def_span(param_def_id), }, diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 2214319af4cd9..d729a4adacec2 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -154,9 +154,10 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_ ItemKind::TyAlias(_, _, self_ty) => icx.lower_ty(self_ty), ItemKind::Impl(hir::Impl { self_ty, .. }) => match self_ty.find_self_aliases() { spans if spans.len() > 0 => { - let guar = tcx - .dcx() - .emit_err(crate::errors::SelfInImplSelf { span: spans.into(), note: () }); + let guar = tcx.dcx().emit_err(crate::diagnostics::SelfInImplSelf { + span: spans.into(), + note: (), + }); Ty::new_error(tcx, guar) } _ => icx.lower_ty(self_ty), diff --git a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs index b31da6b387299..aae06aedc7b7a 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs @@ -7,7 +7,7 @@ use rustc_middle::ty::{self, DefiningScopeKind, EarlyBinder, Ty, TyCtxt, TypeVis use rustc_trait_selection::opaque_types::report_item_does_not_constrain_error; use tracing::{debug, instrument, trace}; -use crate::errors::UnconstrainedOpaqueType; +use crate::diagnostics::UnconstrainedOpaqueType; /// Checks "defining uses" of opaque `impl Trait` in associated types. /// These can only be defined by associated items of the same trait. diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs index 0f0449c0aa9b3..7f3edd7f09231 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -14,7 +14,7 @@ use rustc_middle::ty::{ use rustc_span::{ErrorGuaranteed, Span, kw}; use crate::collect::ItemCtxt; -use crate::errors::DelegationSelfTypeNotSpecified; +use crate::diagnostics::DelegationSelfTypeNotSpecified; use crate::hir_ty_lowering::HirTyLowerer; type RemapTable = FxHashMap; @@ -586,7 +586,7 @@ fn check_constraints<'tcx>( let mut ret = Ok(()); let mut emit = |descr| { - ret = Err(tcx.dcx().emit_err(crate::errors::UnsupportedDelegation { + ret = Err(tcx.dcx().emit_err(crate::diagnostics::UnsupportedDelegation { span: tcx.def_span(def_id), descr, callee_span: tcx.def_span(sig_id), diff --git a/compiler/rustc_hir_analysis/src/errors.rs b/compiler/rustc_hir_analysis/src/diagnostics.rs similarity index 100% rename from compiler/rustc_hir_analysis/src/errors.rs rename to compiler/rustc_hir_analysis/src/diagnostics.rs diff --git a/compiler/rustc_hir_analysis/src/errors/precise_captures.rs b/compiler/rustc_hir_analysis/src/diagnostics/precise_captures.rs similarity index 100% rename from compiler/rustc_hir_analysis/src/errors/precise_captures.rs rename to compiler/rustc_hir_analysis/src/diagnostics/precise_captures.rs diff --git a/compiler/rustc_hir_analysis/src/errors/remove_or_use_generic.rs b/compiler/rustc_hir_analysis/src/diagnostics/remove_or_use_generic.rs similarity index 100% rename from compiler/rustc_hir_analysis/src/errors/remove_or_use_generic.rs rename to compiler/rustc_hir_analysis/src/diagnostics/remove_or_use_generic.rs diff --git a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/diagnostics/wrong_number_of_generic_args.rs similarity index 100% rename from compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs rename to compiler/rustc_hir_analysis/src/diagnostics/wrong_number_of_generic_args.rs diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index 4b2e51f74b973..9d6c647329aa0 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -16,7 +16,7 @@ use rustc_span::{ErrorGuaranteed, Ident, Span, kw}; use rustc_trait_selection::traits; use tracing::{debug, instrument}; -use crate::errors; +use crate::diagnostics; use crate::hir_ty_lowering::{ AssocItemQSelf, GenericsArgsErrExtend, HirTyLowerer, ImpliedBoundsContext, OverlappingAsssocItemConstraints, PredicateFilter, RegionInferReason, @@ -441,7 +441,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { duplicates .entry(assoc_item.def_id) .and_modify(|prev_span| { - self.dcx().emit_err(errors::ValueOfAssociatedStructAlreadySpecified { + self.dcx().emit_err(diagnostics::ValueOfAssociatedStructAlreadySpecified { span: constraint.span, prev_span: *prev_span, item_name: constraint.ident, @@ -484,9 +484,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { match constraint.kind { hir::AssocItemConstraintKind::Equality { .. } if let ty::AssocTag::Fn = assoc_tag => { - return Err(self.dcx().emit_err(crate::errors::ReturnTypeNotationEqualityBound { - span: constraint.span, - })); + return Err(self.dcx().emit_err( + crate::diagnostics::ReturnTypeNotationEqualityBound { span: constraint.span }, + )); } // Lower an equality constraint like `Item = u32` as found in HIR bound `T: Iterator` // to a projection predicate: `::Item = u32`. @@ -712,13 +712,18 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { if bound.has_bound_vars() { return Ty::new_error( tcx, - self.dcx().emit_err(errors::AssociatedItemTraitUninferredGenericParams { - span: hir_ty.span, - inferred_sugg: Some(hir_ty.span.with_hi(segment.ident.span.lo())), - bound: format!("{}::", tcx.anonymize_bound_vars(bound).skip_binder()), - mpart_sugg: None, - what: tcx.def_descr(item_def_id), - }), + self.dcx().emit_err( + diagnostics::AssociatedItemTraitUninferredGenericParams { + span: hir_ty.span, + inferred_sugg: Some(hir_ty.span.with_hi(segment.ident.span.lo())), + bound: format!( + "{}::", + tcx.anonymize_bound_vars(bound).skip_binder() + ), + mpart_sugg: None, + what: tcx.def_descr(item_def_id), + }, + ), ); } @@ -759,19 +764,23 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { .into(), ty::GenericParamDefKind::Type { .. } => { let guar = *emitted_bad_param_err.get_or_insert_with(|| { - self.dcx().emit_err(crate::errors::ReturnTypeNotationIllegalParam::Type { - span: path_span, - param_span: tcx.def_span(param.def_id), - }) + self.dcx().emit_err( + crate::diagnostics::ReturnTypeNotationIllegalParam::Type { + span: path_span, + param_span: tcx.def_span(param.def_id), + }, + ) }); Ty::new_error(tcx, guar).into() } ty::GenericParamDefKind::Const { .. } => { let guar = *emitted_bad_param_err.get_or_insert_with(|| { - self.dcx().emit_err(crate::errors::ReturnTypeNotationIllegalParam::Const { - span: path_span, - param_span: tcx.def_span(param.def_id), - }) + self.dcx().emit_err( + crate::diagnostics::ReturnTypeNotationIllegalParam::Const { + span: path_span, + param_span: tcx.def_span(param.def_id), + }, + ) }); ty::Const::new_error(tcx, guar).into() } @@ -789,7 +798,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { { alias_ty } else { - return Err(self.dcx().emit_err(crate::errors::ReturnTypeNotationOnNonRpitit { + return Err(self.dcx().emit_err(crate::diagnostics::ReturnTypeNotationOnNonRpitit { span: path_span, ty: tcx.liberate_late_bound_regions(item_def_id, output), fn_span: tcx.hir_span_if_local(item_def_id), @@ -845,7 +854,7 @@ pub(crate) fn check_assoc_const_binding_type<'tcx>( let tcx = cx.tcx(); let ty_note = ty .make_suggestable(tcx, false, None) - .map(|ty| crate::errors::TyOfAssocConstBindingNote { assoc_const, ty }); + .map(|ty| crate::diagnostics::TyOfAssocConstBindingNote { assoc_const, ty }); let enclosing_item_owner_id = tcx .hir_parent_owner_iter(hir_id) @@ -855,7 +864,7 @@ pub(crate) fn check_assoc_const_binding_type<'tcx>( for index in collector.params { let param = generics.param_at(index as _, tcx); let is_self_param = param.name == kw::SelfUpper; - guar.get_or_insert(cx.dcx().emit_err(crate::errors::ParamInTyOfAssocConstBinding { + guar.get_or_insert(cx.dcx().emit_err(crate::diagnostics::ParamInTyOfAssocConstBinding { span: assoc_const.span, assoc_const, param_name: param.name, @@ -874,7 +883,7 @@ pub(crate) fn check_assoc_const_binding_type<'tcx>( } for var_def_id in collector.vars { guar.get_or_insert(cx.dcx().emit_err( - crate::errors::EscapingBoundVarInTyOfAssocConstBinding { + crate::diagnostics::EscapingBoundVarInTyOfAssocConstBinding { span: assoc_const.span, assoc_const, var_name: cx.tcx().item_name(var_def_id), diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs index f4dca6371696e..e4874c41d5cdd 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs @@ -6,7 +6,7 @@ use rustc_middle::ty::layout::{LayoutCx, LayoutError, TyAndLayout}; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_span::Span; -use crate::errors; +use crate::diagnostics; /// Check conditions on inputs and outputs that the cmse ABIs impose: arguments and results MUST be /// returned via registers (i.e. MUST NOT spill to the stack). LLVM will also validate these @@ -59,13 +59,13 @@ pub(crate) fn validate_cmse_abi<'tcx>( if let Err((span, layout_err)) = is_valid_cmse_inputs(tcx, dcx, fn_sig, fn_decl, abi) { if should_emit_layout_error(abi, layout_err) { - dcx.emit_err(errors::CmseGeneric { span, abi }); + dcx.emit_err(diagnostics::CmseGeneric { span, abi }); } } if let Err(layout_err) = is_valid_cmse_output(tcx, dcx, fn_sig, fn_decl, abi) { if should_emit_layout_error(abi, layout_err) { - dcx.emit_err(errors::CmseGeneric { span: fn_decl.output.span(), abi }); + dcx.emit_err(diagnostics::CmseGeneric { span: fn_decl.output.span(), abi }); } } } @@ -110,7 +110,7 @@ fn is_valid_cmse_inputs<'tcx>( if !excess_argument_spans.is_empty() { // fn f(x: u32, y: u32, z: u32, w: u16, q: u16) -> u32, // ^^^^^^ - dcx.emit_err(errors::CmseInputsStackSpill { spans: excess_argument_spans, abi }); + dcx.emit_err(diagnostics::CmseInputsStackSpill { spans: excess_argument_spans, abi }); } Ok(()) @@ -139,7 +139,7 @@ fn is_valid_cmse_output<'tcx>( // // see also https://github.com/rust-lang/rust/issues/147242. if abi == ExternAbi::CmseNonSecureEntry && return_type.has_opaque_types() { - dcx.emit_err(errors::CmseImplTrait { span: fn_decl.output.span(), abi }); + dcx.emit_err(diagnostics::CmseImplTrait { span: fn_decl.output.span(), abi }); return Ok(()); } @@ -153,7 +153,7 @@ fn is_valid_cmse_output<'tcx>( let layout_cx = LayoutCx::new(tcx, typing_env); if !is_valid_cmse_output_layout(layout_cx, layout) { - dcx.emit_err(errors::CmseOutputStackSpill { span: fn_decl.output.span(), abi }); + dcx.emit_err(diagnostics::CmseOutputStackSpill { span: fn_decl.output.span(), abi }); } Ok(()) diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs index fea7b48e03a0f..761af258822dd 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs @@ -23,7 +23,7 @@ use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; use super::HirTyLowerer; -use crate::errors::DynTraitAssocItemBindingMentionsSelf; +use crate::diagnostics::DynTraitAssocItemBindingMentionsSelf; use crate::hir_ty_lowering::{ GenericArgCountMismatch, ImpliedBoundsContext, OverlappingAsssocItemConstraints, PredicateFilter, RegionInferReason, @@ -297,7 +297,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { UNUSED_ASSOCIATED_TYPE_BOUNDS, hir_id, span, - crate::errors::UnusedAssociatedTypeBounds { span }, + crate::diagnostics::UnusedAssociatedTypeBounds { span }, ); } } @@ -557,7 +557,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // error. let r = derived_region_bounds[0]; if derived_region_bounds[1..].iter().any(|r1| r != *r1) { - self.dcx().emit_err(crate::errors::AmbiguousLifetimeBound { span }); + self.dcx().emit_err(crate::diagnostics::AmbiguousLifetimeBound { span }); } Some(r) } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index c387855838779..39402cfc35dce 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -27,7 +27,7 @@ use smallvec::SmallVec; use tracing::debug; use super::InherentAssocCandidate; -use crate::errors::{ +use crate::diagnostics::{ self, AssocItemConstraintsNotAllowedHere, ManualImplementation, ParenthesizedFnTraitExpansion, TraitObjectDeclaredWithNoTraits, }; @@ -45,7 +45,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { return; } - self.dcx().emit_err(errors::MissingGenericParams { + self.dcx().emit_err(diagnostics::MissingGenericParams { span, def_span: self.tcx().def_span(def_id), span_snippet: self.tcx().sess.source_map().span_to_snippet(span).ok(), @@ -148,7 +148,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // valid span, so we point at the whole path segment instead. let is_dummy = assoc_ident.span == DUMMY_SP; - let mut err = errors::AssocItemNotFound { + let mut err = diagnostics::AssocItemNotFound { span: if is_dummy { span } else { assoc_ident.span }, assoc_ident, assoc_kind, @@ -161,8 +161,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { }; if is_dummy { - err.label = - Some(errors::AssocItemNotFoundLabel::NotFound { span, assoc_ident, assoc_kind }); + err.label = Some(diagnostics::AssocItemNotFoundLabel::NotFound { + span, + assoc_ident, + assoc_kind, + }); return self.dcx().emit_err(err); } @@ -180,7 +183,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { if let Some(suggested_name) = find_best_match_for_name(&all_candidate_names, assoc_ident.name, None) { - err.sugg = Some(errors::AssocItemNotFoundSugg::Similar { + err.sugg = Some(diagnostics::AssocItemNotFoundSugg::Similar { span: assoc_ident.span, assoc_kind, suggested_name, @@ -223,7 +226,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { .collect::>()[..] { let trait_name = tcx.def_path_str(best_trait); - err.label = Some(errors::AssocItemNotFoundLabel::FoundInOtherTrait { + err.label = Some(diagnostics::AssocItemNotFoundLabel::FoundInOtherTrait { span: assoc_ident.span, assoc_kind, trait_name: &trait_name, @@ -254,7 +257,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { { // The type param already has a bound for `trait_name`, we just need to // change the associated item. - err.sugg = Some(errors::AssocItemNotFoundSugg::SimilarInOtherTrait { + err.sugg = Some(diagnostics::AssocItemNotFoundSugg::SimilarInOtherTrait { span: assoc_ident.span, trait_name: &trait_name, assoc_kind, @@ -280,16 +283,17 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { if let DefKind::TyAlias = tcx.def_kind(item_def_id) && !tcx.type_alias_is_lazy(item_def_id) { - err.sugg = Some(errors::AssocItemNotFoundSugg::SimilarInOtherTraitQPath { - lo: ty_param_span.shrink_to_lo(), - mi: ty_param_span.shrink_to_hi(), - hi: (!identically_named).then_some(assoc_ident.span), - trait_ref, - identically_named, - suggested_name, - assoc_kind, - applicability, - }); + err.sugg = + Some(diagnostics::AssocItemNotFoundSugg::SimilarInOtherTraitQPath { + lo: ty_param_span.shrink_to_lo(), + mi: ty_param_span.shrink_to_hi(), + hi: (!identically_named).then_some(assoc_ident.span), + trait_ref, + identically_named, + suggested_name, + assoc_kind, + applicability, + }); } else { let mut err = self.dcx().create_err(err); if suggest_constraining_type_param( @@ -321,14 +325,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // If we still couldn't find any associated item, and only one associated item exists, // suggest using it. if let [candidate_name] = all_candidate_names.as_slice() { - err.sugg = Some(errors::AssocItemNotFoundSugg::Other { + err.sugg = Some(diagnostics::AssocItemNotFoundSugg::Other { span: assoc_ident.span, qself: &qself_str, assoc_kind, suggested_name: *candidate_name, }); } else { - err.label = Some(errors::AssocItemNotFoundLabel::NotFound { + err.label = Some(diagnostics::AssocItemNotFoundLabel::NotFound { span: assoc_ident.span, assoc_ident, assoc_kind, @@ -369,7 +373,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { && (ty.is_enum() || ty.references_error()) && tcx.features().min_generic_const_args() { - Some(errors::AssocKindMismatchWrapInBracesSugg { + Some(diagnostics::AssocKindMismatchWrapInBracesSugg { lo: hir_ty.span.shrink_to_lo(), hi: hir_ty.span.shrink_to_hi(), }) @@ -391,7 +395,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { (ident.span, None, assoc_tag, assoc_item.tag()) }; - self.dcx().emit_err(errors::AssocKindMismatch { + self.dcx().emit_err(diagnostics::AssocKindMismatch { span, expected: assoc_tag_str(expected), got: assoc_tag_str(got), @@ -418,7 +422,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let assoc_kind_str = assoc_tag_str(assoc_tag); let qself_str = qself.to_string(tcx); - let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem { + let mut err = self.dcx().create_err(crate::diagnostics::AmbiguousAssocItem { span, assoc_kind: assoc_kind_str, assoc_ident, @@ -604,7 +608,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let msg = format!("expected {kind_str}, found variant `{ident}`"); self.dcx().span_err(span, msg) } else if self_ty.is_enum() { - let mut err = self.dcx().create_err(errors::NoVariantNamed { + let mut err = self.dcx().create_err(diagnostics::NoVariantNamed { span: ident.span, ident, ty: self_ty, diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs index 91d82ed6e0758..a26d84291e42d 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs @@ -17,7 +17,7 @@ use smallvec::SmallVec; use tracing::{debug, instrument}; use super::{HirTyLowerer, IsMethodCall}; -use crate::errors::wrong_number_of_generic_args::{GenericArgsInfo, WrongNumberOfGenericArgs}; +use crate::diagnostics::wrong_number_of_generic_args::{GenericArgsInfo, WrongNumberOfGenericArgs}; use crate::hir_ty_lowering::errors::prohibit_assoc_item_constraint; use crate::hir_ty_lowering::{ ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgPosition, diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 61bde9e7e39b8..7909fdbf2365e 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -50,7 +50,7 @@ use rustc_trait_selection::traits::{self, FulfillmentError}; use tracing::{debug, instrument}; use crate::check::check_abi; -use crate::errors::{BadReturnTypeNotation, NoFieldOnType}; +use crate::diagnostics::{BadReturnTypeNotation, NoFieldOnType}; use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint}; use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args}; use crate::middle::resolve_bound_vars as rbv; @@ -1078,7 +1078,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""), }; - self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait { + self.dcx().emit_err(crate::diagnostics::ConstBoundForNonConstTrait { span, modifier: constness.as_str(), def_span, @@ -1750,7 +1750,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let tcx = self.tcx(); if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) { - self.dcx().emit_err(crate::errors::AssocItemIsPrivate { + self.dcx().emit_err(crate::diagnostics::AssocItemIsPrivate { span, kind: tcx.def_descr(item_def_id), name: ident, diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check.rs b/compiler/rustc_hir_analysis/src/impl_wf_check.rs index bbb40ef0a87ad..9e4a06e95fd1f 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check.rs @@ -20,8 +20,8 @@ use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt, Unnormalized}; use rustc_span::{ErrorGuaranteed, kw}; use crate::constrained_generic_params as cgp; -use crate::errors::UnconstrainedGenericParameter; -use crate::errors::remove_or_use_generic::suggest_to_remove_or_use_generic; +use crate::diagnostics::UnconstrainedGenericParameter; +use crate::diagnostics::remove_or_use_generic::suggest_to_remove_or_use_generic; mod min_specialization; diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index 1fb126fe3d69f..df8ac8b2de999 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -79,8 +79,8 @@ use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::{self, ObligationCtxt, translate_args_with_cause, wf}; use tracing::{debug, instrument}; -use crate::errors::GenericArgsOnOverriddenImpl; -use crate::{constrained_generic_params as cgp, errors}; +use crate::diagnostics::GenericArgsOnOverriddenImpl; +use crate::{constrained_generic_params as cgp, diagnostics}; pub(super) fn check_min_specialization( tcx: TyCtxt<'_>, @@ -146,7 +146,7 @@ fn check_has_items( && tcx.associated_item_def_ids(impl1_def_id).is_empty() { let base_impl_span = tcx.def_span(impl2_id); - return Err(tcx.dcx().emit_err(errors::EmptySpecialization { span, base_impl_span })); + return Err(tcx.dcx().emit_err(diagnostics::EmptySpecialization { span, base_impl_span })); } Ok(()) } @@ -300,7 +300,7 @@ fn check_static_lifetimes<'tcx>( span: Span, ) -> Result<(), ErrorGuaranteed> { if tcx.any_free_region_meets(parent_args, |r| r.is_static()) { - return Err(tcx.dcx().emit_err(errors::StaticSpecialize { span })); + return Err(tcx.dcx().emit_err(diagnostics::StaticSpecialize { span })); } Ok(()) } diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 4d60f878c6fc4..14961abfd92c9 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -74,14 +74,14 @@ mod coherence; mod collect; mod constrained_generic_params; pub mod delegation; -pub mod errors; +pub mod diagnostics; pub mod hir_ty_lowering; pub mod hir_wf_check; mod impl_wf_check; mod outlives; mod variance; -pub use errors::NoVariantNamed; +pub use diagnostics::NoVariantNamed; use rustc_abi::{CVariadicStatus, ExternAbi}; use rustc_hir as hir; use rustc_hir::def::DefKind; @@ -106,7 +106,7 @@ fn check_c_variadic_abi(tcx: TyCtxt<'_>, decl: &hir::FnDecl<'_>, abi: ExternAbi, CVariadicStatus::Stable => {} CVariadicStatus::NotSupported => { tcx.dcx() - .create_err(errors::VariadicFunctionCompatibleConvention { + .create_err(diagnostics::VariadicFunctionCompatibleConvention { span, convention: &format!("{abi}"), }) diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index f1d9100a1d5f6..6a8cc1b27657c 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -22,7 +22,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_hir::{ExprKind, HirId, QPath, find_attr, is_range_literal}; use rustc_hir_analysis::NoVariantNamed; -use rustc_hir_analysis::errors::NoFieldOnType; +use rustc_hir_analysis::diagnostics::NoFieldOnType; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _; use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, RegionVariableOrigin}; use rustc_infer::traits::query::NoSolution; From 579cac249f4bb67fe35536b2ddafb2236ef61e0e Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 13 Jun 2026 14:43:13 +0200 Subject: [PATCH 11/13] Rename `rustc_infer/src/errors.rs` into `rustc_infer/src/diagnostics.rs` --- compiler/rustc_infer/src/{errors.rs => diagnostics.rs} | 0 compiler/rustc_infer/src/infer/opaque_types/mod.rs | 2 +- compiler/rustc_infer/src/lib.rs | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename compiler/rustc_infer/src/{errors.rs => diagnostics.rs} (100%) diff --git a/compiler/rustc_infer/src/errors.rs b/compiler/rustc_infer/src/diagnostics.rs similarity index 100% rename from compiler/rustc_infer/src/errors.rs rename to compiler/rustc_infer/src/diagnostics.rs diff --git a/compiler/rustc_infer/src/infer/opaque_types/mod.rs b/compiler/rustc_infer/src/infer/opaque_types/mod.rs index 786eec30f05c9..c5c58ae1a29b4 100644 --- a/compiler/rustc_infer/src/infer/opaque_types/mod.rs +++ b/compiler/rustc_infer/src/infer/opaque_types/mod.rs @@ -12,7 +12,7 @@ use rustc_span::Span; use tracing::{debug, instrument}; use super::{DefineOpaqueTypes, RegionVariableOrigin}; -use crate::errors::OpaqueHiddenTypeDiag; +use crate::diagnostics::OpaqueHiddenTypeDiag; use crate::infer::{InferCtxt, InferOk}; use crate::traits::{self, Obligation, PredicateObligations}; diff --git a/compiler/rustc_infer/src/lib.rs b/compiler/rustc_infer/src/lib.rs index 2595c1a7b2764..f2cf938a48385 100644 --- a/compiler/rustc_infer/src/lib.rs +++ b/compiler/rustc_infer/src/lib.rs @@ -18,6 +18,6 @@ #![recursion_limit = "512"] // For rustdoc // tidy-alphabetical-end -mod errors; +mod diagnostics; pub mod infer; pub mod traits; From d4b261017282d8e8fbe40ba8683ffd54ca80bdc7 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 13 Jun 2026 14:51:05 +0200 Subject: [PATCH 12/13] Rename `rustc_interface/src/errors.rs` into `rustc_interface/src/diagnostics.rs` --- .../src/{errors.rs => diagnostics.rs} | 0 compiler/rustc_interface/src/lib.rs | 2 +- compiler/rustc_interface/src/passes.rs | 38 +++++++++++-------- compiler/rustc_interface/src/queries.rs | 2 +- compiler/rustc_interface/src/util.rs | 16 ++++---- 5 files changed, 33 insertions(+), 25 deletions(-) rename compiler/rustc_interface/src/{errors.rs => diagnostics.rs} (100%) diff --git a/compiler/rustc_interface/src/errors.rs b/compiler/rustc_interface/src/diagnostics.rs similarity index 100% rename from compiler/rustc_interface/src/errors.rs rename to compiler/rustc_interface/src/diagnostics.rs diff --git a/compiler/rustc_interface/src/lib.rs b/compiler/rustc_interface/src/lib.rs index b5e4a384861f6..77ee7b8896beb 100644 --- a/compiler/rustc_interface/src/lib.rs +++ b/compiler/rustc_interface/src/lib.rs @@ -6,7 +6,7 @@ // tidy-alphabetical-end mod callbacks; -pub mod errors; +pub mod diagnostics; pub mod interface; mod limits; pub mod passes; diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 62cdc2ca60f34..25f2882345358 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -49,7 +49,7 @@ use rustc_trait_selection::{solve, traits}; use tracing::{info, instrument}; use crate::interface::Compiler; -use crate::{errors, limits, proc_macro_decls, util}; +use crate::{diagnostics, limits, proc_macro_decls, util}; pub fn parse<'a>(sess: &'a Session) -> ast::Crate { let mut krate = sess @@ -271,10 +271,10 @@ fn configure_and_expand( if crate_types.len() > 1 { if is_executable_crate { - sess.dcx().emit_err(errors::MixedBinCrate); + sess.dcx().emit_err(diagnostics::MixedBinCrate); } if is_proc_macro_crate { - sess.dcx().emit_err(errors::MixedProcMacroCrate); + sess.dcx().emit_err(diagnostics::MixedProcMacroCrate); } } if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() { @@ -282,7 +282,7 @@ fn configure_and_expand( } if is_proc_macro_crate && !sess.panic_strategy().unwinds() { - sess.dcx().emit_warn(errors::ProcMacroCratePanicAbort); + sess.dcx().emit_warn(diagnostics::ProcMacroCratePanicAbort); } sess.time("maybe_create_a_macro_crate", || { @@ -458,9 +458,13 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { }) .as_str(); - sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix }); + sess.dcx().emit_err(diagnostics::FerrisIdentifier { + spans, + first_span, + ferris_fix, + }); } else { - sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident }); + sess.dcx().emit_err(diagnostics::EmojiIdentifier { spans, ident }); } } }); @@ -773,7 +777,8 @@ fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[P } } Err(error) => { - sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error }); + sess.dcx() + .emit_fatal(diagnostics::ErrorWritingDependencies { path: deps_filename, error }); } } } @@ -824,10 +829,11 @@ pub fn write_dep_info(tcx: TyCtxt<'_>) { if let Some(input_path) = sess.io.input.opt_path() { if sess.opts.will_create_output_file() { if output_contains_path(&output_paths, input_path) { - sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path }); + sess.dcx() + .emit_fatal(diagnostics::InputFileWouldBeOverWritten { path: input_path }); } if let Some(dir_path) = output_conflicts_with_dir(&output_paths) { - sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory { + sess.dcx().emit_fatal(diagnostics::GeneratedFileConflictsWithDirectory { input_path, dir_path, }); @@ -837,7 +843,7 @@ pub fn write_dep_info(tcx: TyCtxt<'_>) { if let Some(ref dir) = sess.io.temps_dir { if fs::create_dir_all(dir).is_err() { - sess.dcx().emit_fatal(errors::TempsDirError); + sess.dcx().emit_fatal(diagnostics::TempsDirError); } } @@ -849,7 +855,7 @@ pub fn write_dep_info(tcx: TyCtxt<'_>) { if !only_dep_info { if let Some(ref dir) = sess.io.output_dir { if fs::create_dir_all(dir).is_err() { - sess.dcx().emit_fatal(errors::OutDirError); + sess.dcx().emit_fatal(diagnostics::OutDirError); } } } @@ -1353,7 +1359,7 @@ pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol if let Some((attr_crate_name, span)) = attr_crate_name && attr_crate_name != crate_name { - sess.dcx().emit_err(errors::CrateNameDoesNotMatch { + sess.dcx().emit_err(diagnostics::CrateNameDoesNotMatch { span, crate_name, attr_crate_name, @@ -1370,7 +1376,7 @@ pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str()) { if file_stem.starts_with('-') { - sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem }); + sess.dcx().emit_err(diagnostics::CrateNameInvalid { crate_name: file_stem }); } else { return validate(Symbol::intern(&file_stem.replace('-', "_")), None); } @@ -1413,7 +1419,7 @@ pub fn collect_crate_types( // styles at all other locations if session.opts.test { if !session.target.executables { - session.dcx().emit_warn(errors::UnsupportedCrateTypeForTarget { + session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget { crate_type: CrateType::Executable, target_triple: &session.opts.target_triple, }); @@ -1459,13 +1465,13 @@ pub fn collect_crate_types( base.retain(|crate_type| { if invalid_output_for_target(session, *crate_type) { - session.dcx().emit_warn(errors::UnsupportedCrateTypeForTarget { + session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget { crate_type: *crate_type, target_triple: &session.opts.target_triple, }); false } else if !backend_crate_types.contains(crate_type) { - session.dcx().emit_warn(errors::UnsupportedCrateTypeForCodegenBackend { + session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForCodegenBackend { crate_type: *crate_type, codegen_backend: codegen_backend_name, }); diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 6026cfd5f71fe..025a5a55d0abd 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -12,7 +12,7 @@ use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_session::config::{self, OutputFilenames, OutputType}; -use crate::errors::FailedWritingFile; +use crate::diagnostics::FailedWritingFile; use crate::passes; pub struct Linker { diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index 6e74ec64ad241..c78e419033d78 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -30,7 +30,7 @@ use rustc_span::{SessionGlobals, Symbol, sym}; use rustc_target::spec::Target; use tracing::info; -use crate::errors; +use crate::diagnostics; use crate::passes::parse_crate_name; /// Function pointer type that constructs a new CodegenBackend. @@ -90,12 +90,14 @@ pub(crate) fn check_abi_required_features(sess: &Session) { for feature in abi_feature_constraints.required { if !sess.unstable_target_features.contains(&Symbol::intern(feature)) { - sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "enabled" }); + sess.dcx() + .emit_warn(diagnostics::AbiRequiredTargetFeature { feature, enabled: "enabled" }); } } for feature in abi_feature_constraints.incompatible { if sess.unstable_target_features.contains(&Symbol::intern(feature)) { - sess.dcx().emit_warn(errors::AbiRequiredTargetFeature { feature, enabled: "disabled" }); + sess.dcx() + .emit_warn(diagnostics::AbiRequiredTargetFeature { feature, enabled: "disabled" }); } } } @@ -609,7 +611,7 @@ pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> Outpu &sess.opts.output_types, sess.io.output_file == Some(OutFileName::Stdout), ) { - sess.dcx().emit_fatal(errors::MultipleOutputTypesToStdout); + sess.dcx().emit_fatal(diagnostics::MultipleOutputTypesToStdout); } let crate_name = @@ -650,16 +652,16 @@ pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> Outpu let unnamed_output_types = sess.opts.output_types.values().filter(|a| a.is_none()).count(); let ofile = if unnamed_output_types > 1 { - sess.dcx().emit_warn(errors::MultipleOutputTypesAdaption); + sess.dcx().emit_warn(diagnostics::MultipleOutputTypesAdaption); None } else { if !sess.opts.cg.extra_filename.is_empty() { - sess.dcx().emit_warn(errors::IgnoringExtraFilename); + sess.dcx().emit_warn(diagnostics::IgnoringExtraFilename); } Some(out_file.clone()) }; if sess.io.output_dir.is_some() { - sess.dcx().emit_warn(errors::IgnoringOutDir); + sess.dcx().emit_warn(diagnostics::IgnoringOutDir); } let out_filestem = From 190a22ddf3926e374a543256bc990dbbf04fc85d Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 11 Jun 2026 12:08:36 +0200 Subject: [PATCH 13/13] Rename `rustc_hir_typeck/src/errors.rs` into `rustc_hir_typeck/src/diagnostics.rs` --- compiler/rustc_hir_typeck/src/_match.rs | 2 +- compiler/rustc_hir_typeck/src/callee.rs | 18 ++++---- compiler/rustc_hir_typeck/src/cast.rs | 41 ++++++++++------- compiler/rustc_hir_typeck/src/coercion.rs | 2 +- .../src/{errors.rs => diagnostics.rs} | 0 compiler/rustc_hir_typeck/src/expr.rs | 2 +- compiler/rustc_hir_typeck/src/fallback.rs | 36 ++++++++------- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 10 ++--- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 10 ++--- .../src/fn_ctxt/suggestions.rs | 45 ++++++++++--------- compiler/rustc_hir_typeck/src/inline_asm.rs | 2 +- compiler/rustc_hir_typeck/src/lib.rs | 2 +- compiler/rustc_hir_typeck/src/loops.rs | 2 +- .../rustc_hir_typeck/src/method/confirm.rs | 2 +- .../rustc_hir_typeck/src/method/suggest.rs | 16 ++++--- .../rustc_hir_typeck/src/naked_functions.rs | 2 +- compiler/rustc_hir_typeck/src/op.rs | 4 +- compiler/rustc_hir_typeck/src/pat.rs | 14 +++--- 18 files changed, 115 insertions(+), 95 deletions(-) rename compiler/rustc_hir_typeck/src/{errors.rs => diagnostics.rs} (100%) diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index bc155dc67c233..e043e1afaf61f 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -254,7 +254,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let semi = expr.span.shrink_to_hi().with_hi(semi_span.hi()); - let sugg = crate::errors::RemoveSemiForCoerce { expr: expr.span, ret, semi }; + let sugg = crate::diagnostics::RemoveSemiForCoerce { expr: expr.span, ret, semi }; diag.subdiagnostic(sugg); } diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 4711fd22d5729..57ab29ac752ad 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -25,7 +25,7 @@ use tracing::{debug, instrument}; use super::method::MethodCallee; use super::method::probe::ProbeScope; use super::{Expectation, FnCtxt, TupleArgumentsFlag}; -use crate::errors; +use crate::diagnostics; use crate::method::TreatNotYetDefinedOpaques; use crate::method::confirm::ConfirmContext; use crate::method::probe::{IsSuggestion, Mode}; @@ -46,14 +46,14 @@ pub(crate) fn check_legal_trait_for_method_call( && !tcx.is_lang_item(tcx.parent(body_id), LangItem::Drop) { let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) { - errors::ExplicitDestructorCallSugg::Snippet { + diagnostics::ExplicitDestructorCallSugg::Snippet { lo: expr_span.shrink_to_lo().to(receiver.shrink_to_lo()), hi: receiver.shrink_to_hi().to(expr_span.shrink_to_hi()), } } else { - errors::ExplicitDestructorCallSugg::Empty(span) + diagnostics::ExplicitDestructorCallSugg::Empty(span) }; - return Err(tcx.dcx().emit_err(errors::ExplicitDestructorCall { span, sugg })); + return Err(tcx.dcx().emit_err(diagnostics::ExplicitDestructorCall { span, sugg })); } tcx.ensure_result().coherent_trait(trait_id) } @@ -105,7 +105,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } if self.is_scalable_vector_ctor(autoderef.final_ty()) { - let mut err = self.dcx().create_err(errors::ScalableVectorCtor { + let mut err = self.dcx().create_err(diagnostics::ScalableVectorCtor { span: callee_expr.span, ty: autoderef.final_ty(), }); @@ -190,13 +190,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // The interrupt ABIs should only be called by the CPU. They have complex // pre- and postconditions, and can use non-standard instructions like `iret` on x86. | CanonAbi::Interrupt(_) => { - let err = crate::errors::AbiCannotBeCalled { span, abi }; + let err = crate::diagnostics::AbiCannotBeCalled { span, abi }; self.tcx.dcx().emit_err(err); } // This is an entry point for the host, and cannot be called directly. CanonAbi::GpuKernel => { - let err = crate::errors::GpuKernelAbiCannotBeCalled { span }; + let err = crate::diagnostics::GpuKernelAbiCannotBeCalled { span }; self.tcx.dcx().emit_err(err); } @@ -608,7 +608,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall); } else { - self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp }); + self.dcx().emit_err(diagnostics::RustCallIncorrectArgs { span: sp }); } } @@ -845,7 +845,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let callee_ty = self.resolve_vars_if_possible(callee_ty); let mut path = None; - let mut err = self.dcx().create_err(errors::InvalidCallee { + let mut err = self.dcx().create_err(diagnostics::InvalidCallee { span: callee_expr.span, found: match &unit_variant { Some((_, kind, path)) => format!("{kind} `{path}`"), diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 65ca99fb67d6c..c8680be6de718 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -49,7 +49,7 @@ use rustc_trait_selection::infer::InferCtxtExt; use tracing::{debug, instrument}; use super::FnCtxt; -use crate::{errors, type_error_struct}; +use crate::{diagnostics, type_error_struct}; /// Reifies a cast check to be checked once we have full type information for /// a function context. @@ -389,13 +389,17 @@ impl<'a, 'tcx> CastCheck<'tcx> { CastError::CastToBool => { let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty); let help = if self.expr_ty.is_numeric() { - errors::CannotCastToBoolHelp::Numeric( + diagnostics::CannotCastToBoolHelp::Numeric( self.expr_span.shrink_to_hi().with_hi(self.span.hi()), ) } else { - errors::CannotCastToBoolHelp::Unsupported(self.span) + diagnostics::CannotCastToBoolHelp::Unsupported(self.span) }; - fcx.dcx().emit_err(errors::CannotCastToBool { span: self.span, expr_ty, help }); + fcx.dcx().emit_err(diagnostics::CannotCastToBool { + span: self.span, + expr_ty, + help, + }); } CastError::CastToChar => { let mut err = type_error_struct!( @@ -588,7 +592,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { CastError::SizedUnsizedCast => { let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty); let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty); - fcx.dcx().emit_err(errors::CastThinPointerToWidePointer { + fcx.dcx().emit_err(diagnostics::CastThinPointerToWidePointer { span: self.span, expr_ty, cast_ty, @@ -606,14 +610,14 @@ impl<'a, 'tcx> CastCheck<'tcx> { .then(|| match cast_ty.kind() { ty::RawPtr(pointee, _) => match pointee.kind() { ty::Param(param) => { - Some(errors::IntToWideParamNote { param: param.name }) + Some(diagnostics::IntToWideParamNote { param: param.name }) } _ => None, }, _ => None, }) .flatten(); - fcx.dcx().emit_err(errors::IntToWide { + fcx.dcx().emit_err(diagnostics::IntToWide { span, metadata, expr_ty, @@ -630,17 +634,21 @@ impl<'a, 'tcx> CastCheck<'tcx> { e => unreachable!("control flow means we should never encounter a {e:?}"), }; let (span, sub) = if unknown_cast_to { - (self.cast_span, errors::CastUnknownPointerSub::To(self.cast_span)) + (self.cast_span, diagnostics::CastUnknownPointerSub::To(self.cast_span)) } else { - (self.cast_span, errors::CastUnknownPointerSub::From(self.span)) + (self.cast_span, diagnostics::CastUnknownPointerSub::From(self.span)) }; - fcx.dcx().emit_err(errors::CastUnknownPointer { span, to: unknown_cast_to, sub }); + fcx.dcx().emit_err(diagnostics::CastUnknownPointer { + span, + to: unknown_cast_to, + sub, + }); } CastError::CastEnumDrop => { let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty); let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty); - fcx.dcx().emit_err(errors::CastEnumDrop { span: self.span, expr_ty, cast_ty }); + fcx.dcx().emit_err(diagnostics::CastEnumDrop { span: self.span, expr_ty, cast_ty }); } CastError::ForeignNonExhaustiveAdt => { make_invalid_casting_error( @@ -653,7 +661,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { .emit(); } CastError::PtrPtrAddingAutoTrait(added) => { - fcx.dcx().emit_err(errors::PtrCastAddAutoToObject { + fcx.dcx().emit_err(diagnostics::PtrCastAddAutoToObject { span: self.span, traits_len: added.len(), traits: { @@ -727,7 +735,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { lint, self.expr.hir_id, self.span, - errors::TrivialCast { numeric, expr_ty, cast_ty }, + diagnostics::TrivialCast { numeric, expr_ty, cast_ty }, ); } @@ -1144,12 +1152,15 @@ impl<'a, 'tcx> CastCheck<'tcx> { if let Some((deref_ty, _)) = derefed { // Give a note about what the expr derefs to. if deref_ty != self.expr_ty.peel_refs() { - err.subdiagnostic(errors::DerefImplsIsEmpty { span: self.expr_span, deref_ty }); + err.subdiagnostic(diagnostics::DerefImplsIsEmpty { + span: self.expr_span, + deref_ty, + }); } // Create a multipart suggestion: add `!` and `.is_empty()` in // place of the cast. - err.subdiagnostic(errors::UseIsEmpty { + err.subdiagnostic(diagnostics::UseIsEmpty { lo: self.expr_span.shrink_to_lo(), hi: self.span.with_lo(self.expr_span.hi()), expr_ty: self.expr_ty, diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 4bd3dc82d6133..f7a58d278a519 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -67,7 +67,7 @@ use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; use crate::FnCtxt; -use crate::errors::SuggestBoxingForReturnImplTrait; +use crate::diagnostics::SuggestBoxingForReturnImplTrait; struct Coerce<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/diagnostics.rs similarity index 100% rename from compiler/rustc_hir_typeck/src/errors.rs rename to compiler/rustc_hir_typeck/src/diagnostics.rs diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 6a8cc1b27657c..4465bbc34a562 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -40,7 +40,7 @@ use tracing::{debug, instrument, trace}; use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation}; use crate::coercion::CoerceMany; -use crate::errors::{ +use crate::diagnostics::{ AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr, BaseExpressionDoubleDotRemove, CantDereference, FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct, HelpUseLatestEdition, NakedAsmOutsideNakedFn, diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 886bcc8c21823..9af35b55f40b1 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -18,7 +18,7 @@ use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; use tracing::debug; -use crate::{FnCtxt, errors}; +use crate::{FnCtxt, diagnostics}; impl<'tcx> FnCtxt<'_, 'tcx> { /// Performs type inference fallback, setting [`FnCtxt::diverging_fallback_has_occurred`] @@ -182,7 +182,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { FLOAT_LITERAL_F32_FALLBACK, origin.lint_id.unwrap_or(CRATE_HIR_ID), origin.span, - errors::FloatLiteralF32Fallback { + diagnostics::FloatLiteralF32Fallback { span: literal.as_ref().map(|_| origin.span), literal: literal.unwrap_or_default(), }, @@ -312,21 +312,25 @@ impl<'tcx> FnCtxt<'_, 'tcx> { span, match reason { UnsafeUseReason::Call => { - errors::NeverTypeFallbackFlowingIntoUnsafe::Call { sugg: sugg.clone() } + diagnostics::NeverTypeFallbackFlowingIntoUnsafe::Call { sugg: sugg.clone() } } UnsafeUseReason::Method => { - errors::NeverTypeFallbackFlowingIntoUnsafe::Method { sugg: sugg.clone() } + diagnostics::NeverTypeFallbackFlowingIntoUnsafe::Method { + sugg: sugg.clone(), + } } UnsafeUseReason::Path => { - errors::NeverTypeFallbackFlowingIntoUnsafe::Path { sugg: sugg.clone() } + diagnostics::NeverTypeFallbackFlowingIntoUnsafe::Path { sugg: sugg.clone() } } UnsafeUseReason::UnionField => { - errors::NeverTypeFallbackFlowingIntoUnsafe::UnionField { + diagnostics::NeverTypeFallbackFlowingIntoUnsafe::UnionField { sugg: sugg.clone(), } } UnsafeUseReason::Deref => { - errors::NeverTypeFallbackFlowingIntoUnsafe::Deref { sugg: sugg.clone() } + diagnostics::NeverTypeFallbackFlowingIntoUnsafe::Deref { + sugg: sugg.clone(), + } } }, ); @@ -376,7 +380,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { lint::builtin::DEPENDENCY_ON_UNIT_NEVER_TYPE_FALLBACK, self.tcx.local_def_id_to_hir_id(self.body_id), self.tcx.def_span(self.body_id), - errors::DependencyOnUnitNeverTypeFallback { + diagnostics::DependencyOnUnitNeverTypeFallback { obligation_span: never_error.obligation.cause.span, obligation: never_error.obligation.predicate, sugg, @@ -441,7 +445,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { &self, diverging_vids: &[ty::TyVid], coercions: &VecGraph, - ) -> errors::SuggestAnnotations { + ) -> diagnostics::SuggestAnnotations { let body = self.tcx.hir_maybe_body_owned_by(self.body_id).expect("body id must have an owner"); // For each diverging var, look through the HIR for a place to give it @@ -458,7 +462,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { .break_value() }) .collect(); - errors::SuggestAnnotations { suggestions } + diagnostics::SuggestAnnotations { suggestions } } } @@ -479,7 +483,7 @@ impl<'tcx> AnnotateUnitFallbackVisitor<'_, 'tcx> { arg_segment: &'tcx hir::PathSegment<'tcx>, def_id: DefId, id: HirId, - ) -> ControlFlow { + ) -> ControlFlow { if arg_segment.args.is_none() && let Some(all_args) = self.fcx.typeck_results.borrow().node_args_opt(id) && let generics = self.fcx.tcx.generics_of(def_id) @@ -497,7 +501,7 @@ impl<'tcx> AnnotateUnitFallbackVisitor<'_, 'tcx> { && let Some(vid) = self.fcx.root_vid(ty) && self.reachable_vids.contains(&vid) { - return ControlFlow::Break(errors::SuggestAnnotation::Turbo( + return ControlFlow::Break(diagnostics::SuggestAnnotation::Turbo( arg_segment.ident.span.shrink_to_hi(), n_tys, idx, @@ -509,7 +513,7 @@ impl<'tcx> AnnotateUnitFallbackVisitor<'_, 'tcx> { } } impl<'tcx> Visitor<'tcx> for AnnotateUnitFallbackVisitor<'_, 'tcx> { - type Result = ControlFlow; + type Result = ControlFlow; fn visit_infer( &mut self, @@ -523,7 +527,7 @@ impl<'tcx> Visitor<'tcx> for AnnotateUnitFallbackVisitor<'_, 'tcx> { && self.reachable_vids.contains(&vid) && inf_span.can_be_used_for_suggestions() { - return ControlFlow::Break(errors::SuggestAnnotation::Unit(inf_span)); + return ControlFlow::Break(diagnostics::SuggestAnnotation::Unit(inf_span)); } ControlFlow::Continue(()) @@ -570,7 +574,7 @@ impl<'tcx> Visitor<'tcx> for AnnotateUnitFallbackVisitor<'_, 'tcx> { && expr.span.can_be_used_for_suggestions() { let span = path.span.shrink_to_lo().to(trait_segment.ident.span); - return ControlFlow::Break(errors::SuggestAnnotation::Path(span)); + return ControlFlow::Break(diagnostics::SuggestAnnotation::Path(span)); } // Or else, try suggesting turbofishing the method args. @@ -594,7 +598,7 @@ impl<'tcx> Visitor<'tcx> for AnnotateUnitFallbackVisitor<'_, 'tcx> { && self.reachable_vids.contains(&vid) && local.span.can_be_used_for_suggestions() { - return ControlFlow::Break(errors::SuggestAnnotation::Local( + return ControlFlow::Break(diagnostics::SuggestAnnotation::Local( local.pat.span.shrink_to_hi(), )); } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index b922f09c459f2..c8c6de4f99c03 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -42,7 +42,7 @@ use rustc_trait_selection::traits::{ use tracing::{debug, instrument}; use crate::callee::{self, DeferredCallResolution}; -use crate::errors::{self, CtorIsPrivate}; +use crate::diagnostics::{self, CtorIsPrivate}; use crate::method::{self, MethodCallee}; use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy}; @@ -1158,7 +1158,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) .all(|def_id| def_id != impl_def_id) { - let sugg = ty.normalized.ty_adt_def().map(|def| errors::ReplaceWithName { + let sugg = ty.normalized.ty_adt_def().map(|def| diagnostics::ReplaceWithName { span: path_span, name: self.tcx.item_name(def.did()).to_ident_string(), }); @@ -1166,13 +1166,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .tcx .hir_node_by_def_id(self.tcx.hir_get_parent_item(hir_id).def_id) { - hir::Node::Item(item) => Some(errors::InnerItem { + hir::Node::Item(item) => Some(diagnostics::InnerItem { span: item.kind.ident().map(|i| i.span).unwrap_or(item.span), }), _ => None, }; if ty.raw.has_param() { - let guar = self.dcx().emit_err(errors::SelfCtorFromOuterItem { + let guar = self.dcx().emit_err(diagnostics::SelfCtorFromOuterItem { span: path_span, impl_span: tcx.def_span(impl_def_id), sugg, @@ -1184,7 +1184,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { SELF_CONSTRUCTOR_FROM_OUTER_ITEM, hir_id, path_span, - errors::SelfCtorFromOuterItemLint { + diagnostics::SelfCtorFromOuterItemLint { impl_span: tcx.def_span(impl_def_id), sugg, item, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index f3bf57ab4cd34..a295cc4127b67 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -32,7 +32,7 @@ use tracing::debug; use crate::Expectation::*; use crate::TupleArgumentsFlag::*; use crate::coercion::CoerceMany; -use crate::errors::SuggestPtrNullMut; +use crate::diagnostics::SuggestPtrNullMut; use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx}; use crate::gather_locals::Declaration; use crate::inline_asm::InlineAsmCtxt; @@ -41,7 +41,7 @@ use crate::method::probe::Mode::MethodCall; use crate::method::probe::ProbeScope::TraitsInScope; use crate::{ BreakableCtxt, Diverges, Expectation, FnCtxt, GatherLocalsVisitor, LoweredTy, Needs, - TupleArgumentsFlag, errors, struct_span_code_err, + TupleArgumentsFlag, diagnostics, struct_span_code_err, }; rustc_index::newtype_index! { @@ -470,7 +470,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty: Ty<'tcx>, cast_ty: &str, ) { - sess.dcx().emit_err(errors::PassToVariadicFunction { + sess.dcx().emit_err(diagnostics::PassToVariadicFunction { span, ty, cast_ty, @@ -511,7 +511,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let fn_ptr = self.resolve_vars_if_possible(fn_ptr).to_string(); let fn_item_spa = arg.span; - tcx.sess.dcx().emit_err(errors::PassFnItemToVariadicFunction { + tcx.sess.dcx().emit_err(diagnostics::PassFnItemToVariadicFunction { span: fn_item_spa, sugg_span: fn_item_spa.shrink_to_hi(), replace: fn_ptr, @@ -2053,7 +2053,7 @@ impl<'a, 'tcx> FnCallDiagCtxt<'a, 'tcx> { if cfg!(debug_assertions) { span_bug!(self.call_metadata.error_span, "expected errors from argument matrix"); } else { - let mut err = self.dcx().create_err(errors::ArgMismatchIndeterminate { + let mut err = self.dcx().create_err(diagnostics::ArgMismatchIndeterminate { span: self.call_metadata.error_span, }); self.arg_matching_ctxt.suggest_confusable(&mut err); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 1b4364946e2a7..24e2b030cdc72 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -34,7 +34,7 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _ use tracing::{debug, instrument}; use super::FnCtxt; -use crate::errors::{self, SuggestBoxingForReturnImplTrait}; +use crate::diagnostics::{self, SuggestBoxingForReturnImplTrait}; use crate::fn_ctxt::rustc_span::BytePos; use crate::method::probe; use crate::method::probe::{IsSuggestion, Mode, ProbeScope}; @@ -527,7 +527,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // but those checks need to be a bit more delicate and the benefit is diminishing. if self.can_eq(self.param_env, found_ty_inner, peeled) && error_tys_equate_as_ref { let sugg = prefix_wrap(".as_ref()"); - err.subdiagnostic(errors::SuggestConvertViaMethod { + err.subdiagnostic(diagnostics::SuggestConvertViaMethod { span: expr.span.shrink_to_hi(), sugg, expected, @@ -561,7 +561,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && self.can_eq(self.param_env, deref_ty, peeled) { let sugg = prefix_wrap(".as_deref()"); - err.subdiagnostic(errors::SuggestConvertViaMethod { + err.subdiagnostic(diagnostics::SuggestConvertViaMethod { span: expr.span.shrink_to_hi(), sugg, expected, @@ -574,7 +574,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if self.can_eq(self.param_env, deref_ty, peeled) { let explicit_deref = "*".repeat(n_step); let sugg = prefix_wrap(&format!(".map(|v| &{explicit_deref}v)")); - err.subdiagnostic(errors::SuggestConvertViaMethod { + err.subdiagnostic(diagnostics::SuggestConvertViaMethod { span: expr.span.shrink_to_hi(), sugg, expected, @@ -638,7 +638,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if self.may_coerce(Ty::new_box(self.tcx, found), expected) { let suggest_boxing = match *found.kind() { ty::Tuple(tuple) if tuple.is_empty() => { - errors::SuggestBoxing::Unit { start: span.shrink_to_lo(), end: span } + diagnostics::SuggestBoxing::Unit { start: span.shrink_to_lo(), end: span } } ty::Coroutine(def_id, ..) if matches!( @@ -649,18 +649,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { )) ) => { - errors::SuggestBoxing::AsyncBody + diagnostics::SuggestBoxing::AsyncBody } _ if let Node::ExprField(expr_field) = self.tcx.parent_hir_node(hir_id) && expr_field.is_shorthand => { - errors::SuggestBoxing::ExprFieldShorthand { + diagnostics::SuggestBoxing::ExprFieldShorthand { start: span.shrink_to_lo(), end: span.shrink_to_hi(), ident: expr_field.ident, } } - _ => errors::SuggestBoxing::Other { + _ => diagnostics::SuggestBoxing::Other { start: span.shrink_to_lo(), end: span.shrink_to_hi(), }, @@ -970,17 +970,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &hir::FnRetTy::DefaultReturn(_) if self.tcx.is_closure_like(fn_id.to_def_id()) => {} &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => { if !self.can_add_return_type(fn_id) { - err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span }); + err.subdiagnostic(diagnostics::ExpectedReturnTypeLabel::Unit { span }); } else if let Some(found) = found.make_suggestable(self.tcx, false, None) { - err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { + err.subdiagnostic(diagnostics::AddReturnTypeSuggestion::Add { span, found: found.to_string(), }); } else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) { - err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: sugg }); + err.subdiagnostic(diagnostics::AddReturnTypeSuggestion::Add { + span, + found: sugg, + }); } else { // FIXME: if `found` could be `impl Iterator` we should suggest that. - err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere { span }); + err.subdiagnostic(diagnostics::AddReturnTypeSuggestion::MissingHere { span }); } return true; @@ -1006,7 +1009,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .collect::>() .join("::"); - err.subdiagnostic(errors::ExpectedReturnTypeLabel::ImplTrait { + err.subdiagnostic(diagnostics::ExpectedReturnTypeLabel::ImplTrait { span: hir_ty.span, trait_name, }); @@ -1069,13 +1072,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!(?found); if found.is_suggestable(self.tcx, false) { if ty.span.is_empty() { - err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { + err.subdiagnostic(diagnostics::AddReturnTypeSuggestion::Add { span: ty.span, found: found.to_string(), }); return true; } else { - err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other { + err.subdiagnostic(diagnostics::ExpectedReturnTypeLabel::Other { span: ty.span, expected, }); @@ -1094,7 +1097,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = self.normalize(hir_ty.span, Unnormalized::new_wip(ty)); let ty = self.tcx.instantiate_bound_regions_with_erased(ty); if self.may_coerce(expected, ty) { - err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other { + err.subdiagnostic(diagnostics::ExpectedReturnTypeLabel::Other { span: hir_ty.span, expected, }); @@ -1156,7 +1159,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } - diag.subdiagnostic(errors::NoteCallerChoosesTyForTyParam { + diag.subdiagnostic(diagnostics::NoteCallerChoosesTyForTyParam { ty_param_name: expected_ty_as_param.name, found_ty: found, }); @@ -1539,9 +1542,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let def_path = self.tcx.def_path_str(adt_def.did()); let span = expr.span.shrink_to_hi(); let subdiag = if self.type_is_copy_modulo_regions(self.param_env, ty) { - errors::OptionResultRefMismatch::Copied { span, def_path } + diagnostics::OptionResultRefMismatch::Copied { span, def_path } } else if self.type_is_clone_modulo_regions(self.param_env, ty) { - errors::OptionResultRefMismatch::Cloned { span, def_path } + diagnostics::OptionResultRefMismatch::Cloned { span, def_path } } else { return false; }; @@ -2549,7 +2552,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && self.type_is_clone_modulo_regions(self.param_env, first_ty) && (expr.is_size_lit() || expr_ty.is_usize_like()) { - err.subdiagnostic(errors::ReplaceCommaWithSemicolon { + err.subdiagnostic(diagnostics::ReplaceCommaWithSemicolon { comma_span, descr: "a vector", }); @@ -2562,7 +2565,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if self.type_is_copy_modulo_regions(self.param_env, first_ty) && (expr.is_size_lit() || expr_is_const_usize) { - err.subdiagnostic(errors::ReplaceCommaWithSemicolon { + err.subdiagnostic(diagnostics::ReplaceCommaWithSemicolon { comma_span, descr: "an array", }); diff --git a/compiler/rustc_hir_typeck/src/inline_asm.rs b/compiler/rustc_hir_typeck/src/inline_asm.rs index 68822a2eec2e7..9dfbcd9dda760 100644 --- a/compiler/rustc_hir_typeck/src/inline_asm.rs +++ b/compiler/rustc_hir_typeck/src/inline_asm.rs @@ -17,7 +17,7 @@ use rustc_target::asm::{ use rustc_trait_selection::infer::InferCtxtExt; use crate::FnCtxt; -use crate::errors::RegisterTypeUnstable; +use crate::diagnostics::RegisterTypeUnstable; pub(crate) struct InlineAsmCtxt<'a, 'tcx> { target_features: &'tcx FxIndexSet, diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index b5ab51d593be3..bf5ca9a6c8229 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -15,8 +15,8 @@ mod check; mod closure; mod coercion; mod demand; +mod diagnostics; mod diverges; -mod errors; mod expectation; mod expr; mod inline_asm; diff --git a/compiler/rustc_hir_typeck/src/loops.rs b/compiler/rustc_hir_typeck/src/loops.rs index d0009c36f97a4..21aad64f58d38 100644 --- a/compiler/rustc_hir_typeck/src/loops.rs +++ b/compiler/rustc_hir_typeck/src/loops.rs @@ -13,7 +13,7 @@ use rustc_middle::ty::TyCtxt; use rustc_span::hygiene::DesugaringKind; use rustc_span::{BytePos, Span}; -use crate::errors::{ +use crate::diagnostics::{ BreakInsideClosure, BreakInsideCoroutine, BreakNonLoop, ConstContinueBadLabel, ContinueLabeledBlock, OutsideLoop, OutsideLoopSuggestion, UnlabeledCfInWhileCondition, UnlabeledInLabeledBlock, diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 4ef6de12f7623..d5169cd30aa9a 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -31,7 +31,7 @@ use rustc_trait_selection::traits; use tracing::debug; use super::{MethodCallee, probe}; -use crate::errors::{SupertraitItemShadowee, SupertraitItemShadower, SupertraitItemShadowing}; +use crate::diagnostics::{SupertraitItemShadowee, SupertraitItemShadower, SupertraitItemShadowing}; use crate::{FnCtxt, callee}; pub(crate) struct ConfirmContext<'a, 'tcx> { diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 941f62e8f8cb4..8c9f764c0bded 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -47,7 +47,7 @@ use tracing::{debug, info, instrument}; use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope}; use super::{CandidateSource, MethodError, NoMatchData}; -use crate::errors::{self, CandidateTraitNote, NoAssociatedItem}; +use crate::diagnostics::{self, CandidateTraitNote, NoAssociatedItem}; use crate::expr_use_visitor::expr_place; use crate::method::probe::UnsatisfiedPredicates; use crate::{Expectation, FnCtxt}; @@ -2956,15 +2956,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); if pick.is_ok() { let range_span = parent_expr.span.with_hi(expr.span.hi()); - return Err(self.dcx().emit_err(errors::MissingParenthesesInRange { + return Err(self.dcx().emit_err(diagnostics::MissingParenthesesInRange { span, ty: actual, method_name: item_name.as_str().to_string(), - add_missing_parentheses: Some(errors::AddMissingParenthesesInRange { - func_name: item_name.name.as_str().to_string(), - left: range_span.shrink_to_lo(), - right: range_span.shrink_to_hi(), - }), + add_missing_parentheses: Some( + diagnostics::AddMissingParenthesesInRange { + func_name: item_name.name.as_str().to_string(), + left: range_span.shrink_to_lo(), + right: range_span.shrink_to_hi(), + }, + ), })); } } diff --git a/compiler/rustc_hir_typeck/src/naked_functions.rs b/compiler/rustc_hir_typeck/src/naked_functions.rs index c118f49dca6df..ddeec25acad7a 100644 --- a/compiler/rustc_hir_typeck/src/naked_functions.rs +++ b/compiler/rustc_hir_typeck/src/naked_functions.rs @@ -8,7 +8,7 @@ use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; use rustc_span::Span; -use crate::errors::{ +use crate::diagnostics::{ NakedFunctionsAsmBlock, NakedFunctionsMustNakedAsm, NoPatterns, ParamsNotAllowed, }; diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index 1e9986fa761c4..ad35dc3f7a04b 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -22,7 +22,7 @@ use tracing::debug; use super::FnCtxt; use super::method::MethodCallee; use crate::method::TreatNotYetDefinedOpaques; -use crate::{Expectation, errors}; +use crate::{Expectation, diagnostics}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Checks a `a = b` @@ -347,7 +347,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // used instead of `==` in a let-chain Op::AssignOp(assign_op) => { if let Err(e) = - errors::maybe_emit_plus_equals_diagnostic(&self, assign_op, lhs_expr) + diagnostics::maybe_emit_plus_equals_diagnostic(&self, assign_op, lhs_expr) { (e, None) } else { diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index ae716e4dc6870..9e0ca938a438d 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -35,7 +35,7 @@ use ty::adjustment::{PatAdjust, PatAdjustment}; use super::report_unexpected_variant_res; use crate::expectation::Expectation; use crate::gather_locals::DeclOrigin; -use crate::{FnCtxt, errors}; +use crate::{FnCtxt, diagnostics}; const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\ This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \ @@ -1533,7 +1533,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { let def_span: Option = self.tcx.hir_span_if_local(adt.did()); let sugg_span = def_span.map(|span| span.shrink_to_lo()); - self.dcx().emit_err(crate::errors::ProjectOnNonPinProjectType { + self.dcx().emit_err(crate::diagnostics::ProjectOnNonPinProjectType { span: pat.span, def_span, sugg_span, @@ -2147,10 +2147,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Report an error if an incorrect number of fields was specified. if adt.is_union() { if fields.len() != 1 { - self.dcx().emit_err(errors::UnionPatMultipleFields { span: pat.span }); + self.dcx().emit_err(diagnostics::UnionPatMultipleFields { span: pat.span }); } if has_rest_pat { - self.dcx().emit_err(errors::UnionPatDotDot { span: pat.span }); + self.dcx().emit_err(diagnostics::UnionPatDotDot { span: pat.span }); } } else if !unmentioned_fields.is_empty() { let accessible_unmentioned_fields: Vec<_> = unmentioned_fields @@ -3275,17 +3275,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { || self.tcx.is_diagnostic_item(sym::Result, adt_def.did()) => { // Slicing won't work here, but `.as_deref()` might (issue #91328). - as_deref = Some(errors::AsDerefSuggestion { span: span.shrink_to_hi() }); + as_deref = Some(diagnostics::AsDerefSuggestion { span: span.shrink_to_hi() }); } _ => (), } let is_top_level = current_depth <= 1; if is_slice_or_array_or_vector && is_top_level { - slicing = Some(errors::SlicingSuggestion { span: span.shrink_to_hi() }); + slicing = Some(diagnostics::SlicingSuggestion { span: span.shrink_to_hi() }); } } - self.dcx().emit_err(errors::ExpectedArrayOrSlice { + self.dcx().emit_err(diagnostics::ExpectedArrayOrSlice { span, ty: expected_ty, slice_pat_semantics,