From 02dac5cd78ff36663facc7863e6b4ed4b8df92b2 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Tue, 17 Jun 2025 23:42:57 +0800 Subject: add test suggest-clone-in-macro-issue-139253.rs Signed-off-by: xizheyin --- .../suggest-clone-in-macro-issue-139253.rs | 19 ++++++++++ .../suggest-clone-in-macro-issue-139253.stderr | 41 ++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.rs create mode 100644 tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr diff --git a/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.rs b/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.rs new file mode 100644 index 00000000000..3b3ea058630 --- /dev/null +++ b/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.rs @@ -0,0 +1,19 @@ +#[derive(Debug, Clone)] +struct Struct { field: S } + +#[derive(Debug, Clone)] +struct S; + +macro_rules! expand { + ($ident:ident) => { Struct { $ident } } +} + +fn test1() { + let field = &S; + let a: Struct = dbg!(expand!(field)); //~ ERROR mismatched types [E0308] + let b: Struct = dbg!(Struct { field }); //~ ERROR mismatched types [E0308] + let c: S = dbg!(field); //~ ERROR mismatched types [E0308] + let c: S = dbg!(dbg!(field)); //~ ERROR mismatched types [E0308] +} + +fn main() {} diff --git a/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr b/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr new file mode 100644 index 00000000000..e615cecb365 --- /dev/null +++ b/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr @@ -0,0 +1,41 @@ +error[E0308]: mismatched types + --> $DIR/suggest-clone-in-macro-issue-139253.rs:13:34 + | +LL | let a: Struct = dbg!(expand!(field)); + | ^^^^^ expected `S`, found `&S` + | +help: consider using clone here + | +LL | let a: Struct = dbg!(expand!(field: field.clone())); + | +++++++++++++++ + +error[E0308]: mismatched types + --> $DIR/suggest-clone-in-macro-issue-139253.rs:14:35 + | +LL | let b: Struct = dbg!(Struct { field }); + | ^^^^^ expected `S`, found `&S` + | +help: consider using clone here + | +LL | let b: Struct = dbg!(Struct { field: field.clone() }); + | +++++++++++++++ + +error[E0308]: mismatched types + --> $DIR/suggest-clone-in-macro-issue-139253.rs:15:16 + | +LL | let c: S = dbg!(field); + | ^^^^^^^^^^^ expected `S`, found `&S` + | + = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0308]: mismatched types + --> $DIR/suggest-clone-in-macro-issue-139253.rs:16:16 + | +LL | let c: S = dbg!(dbg!(field)); + | ^^^^^^^^^^^^^^^^^ expected `S`, found `&S` + | + = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0308`. -- cgit 1.4.1-3-g733a5 From fd9c1b962ae29ff928c2c6310a227b56b9db19bd Mon Sep 17 00:00:00 2001 From: xizheyin Date: Tue, 17 Jun 2025 23:48:03 +0800 Subject: Find correct span when suggesting using clone Signed-off-by: xizheyin --- compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs | 4 +++- .../typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 7e5f1d97a8b..1154cc26c59 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1302,8 +1302,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => ".clone()".to_string(), }; + let span = expr.span.find_oldest_ancestor_in_same_ctxt().shrink_to_hi(); + diag.span_suggestion_verbose( - expr.span.shrink_to_hi(), + span, "consider using clone here", suggestion, Applicability::MachineApplicable, diff --git a/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr b/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr index e615cecb365..59e56f67237 100644 --- a/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr +++ b/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr @@ -27,6 +27,10 @@ LL | let c: S = dbg!(field); | ^^^^^^^^^^^ expected `S`, found `&S` | = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider using clone here + | +LL | let c: S = dbg!(field).clone(); + | ++++++++ error[E0308]: mismatched types --> $DIR/suggest-clone-in-macro-issue-139253.rs:16:16 @@ -35,6 +39,10 @@ LL | let c: S = dbg!(dbg!(field)); | ^^^^^^^^^^^^^^^^^ expected `S`, found `&S` | = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider using clone here + | +LL | let c: S = dbg!(dbg!(field)).clone(); + | ++++++++ error: aborting due to 4 previous errors -- cgit 1.4.1-3-g733a5 From b315e9a2ceb341e07983f028347beafaa60cda0a Mon Sep 17 00:00:00 2001 From: Marijn Schouten Date: Fri, 4 Jul 2025 11:27:13 +0000 Subject: clippy fix: rely on autoderef --- library/core/src/borrow.rs | 6 +++--- library/core/src/clone.rs | 2 +- library/core/src/ops/deref.rs | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/library/core/src/borrow.rs b/library/core/src/borrow.rs index ccb1cc4e974..da05f236d2f 100644 --- a/library/core/src/borrow.rs +++ b/library/core/src/borrow.rs @@ -223,20 +223,20 @@ impl BorrowMut for T { #[stable(feature = "rust1", since = "1.0.0")] impl Borrow for &T { fn borrow(&self) -> &T { - &**self + self } } #[stable(feature = "rust1", since = "1.0.0")] impl Borrow for &mut T { fn borrow(&self) -> &T { - &**self + self } } #[stable(feature = "rust1", since = "1.0.0")] impl BorrowMut for &mut T { fn borrow_mut(&mut self) -> &mut T { - &mut **self + self } } diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index a34d1b4a064..51d037ddfd2 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -590,7 +590,7 @@ mod impls { #[inline(always)] #[rustc_diagnostic_item = "noop_method_clone"] fn clone(&self) -> Self { - *self + self } } diff --git a/library/core/src/ops/deref.rs b/library/core/src/ops/deref.rs index 9d9d18095bc..c2dede9fa08 100644 --- a/library/core/src/ops/deref.rs +++ b/library/core/src/ops/deref.rs @@ -158,7 +158,7 @@ impl const Deref for &T { #[rustc_diagnostic_item = "noop_method_deref"] fn deref(&self) -> &T { - *self + self } } @@ -171,7 +171,7 @@ impl const Deref for &mut T { type Target = T; fn deref(&self) -> &T { - *self + self } } @@ -280,7 +280,7 @@ pub trait DerefMut: ~const Deref + PointeeSized { #[rustc_const_unstable(feature = "const_deref", issue = "88955")] impl const DerefMut for &mut T { fn deref_mut(&mut self) -> &mut T { - *self + self } } -- cgit 1.4.1-3-g733a5 From 54cc45d5b4a949fa29813253efc7897e27f48fe2 Mon Sep 17 00:00:00 2001 From: Martin Nordholts Date: Thu, 3 Jul 2025 23:24:14 +0200 Subject: tests: Don't check for self-printed output in std-backtrace.rs test The `Display` implementation for `Backtrace` used to print stack backtrace: but that print was later removed. To make the existing test pass, the print was added to the existing test. But it doesn't make sense to check for something that the test itself does since that will not detect any regressions in the implementation of `Backtrace`. Fully remove the checks. --- tests/ui/backtrace/std-backtrace.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/tests/ui/backtrace/std-backtrace.rs b/tests/ui/backtrace/std-backtrace.rs index 7ccbd46152b..b81bdee44e4 100644 --- a/tests/ui/backtrace/std-backtrace.rs +++ b/tests/ui/backtrace/std-backtrace.rs @@ -13,9 +13,9 @@ use std::str; fn main() { let args: Vec = env::args().collect(); if args.len() >= 2 && args[1] == "force" { - println!("stack backtrace:\n{}", std::backtrace::Backtrace::force_capture()); + println!("{}", std::backtrace::Backtrace::force_capture()); } else if args.len() >= 2 { - println!("stack backtrace:\n{}", std::backtrace::Backtrace::capture()); + println!("{}", std::backtrace::Backtrace::capture()); } else { runtest(&args[0]); println!("test ok"); @@ -28,7 +28,6 @@ fn runtest(me: &str) { let p = Command::new(me).arg("a").env("RUST_BACKTRACE", "1").output().unwrap(); assert!(p.status.success()); - assert!(String::from_utf8_lossy(&p.stdout).contains("stack backtrace:\n")); assert!(String::from_utf8_lossy(&p.stdout).contains("backtrace::main")); let p = Command::new(me).arg("a").env("RUST_BACKTRACE", "0").output().unwrap(); @@ -46,7 +45,6 @@ fn runtest(me: &str) { .output() .unwrap(); assert!(p.status.success()); - assert!(String::from_utf8_lossy(&p.stdout).contains("stack backtrace:\n")); let p = Command::new(me) .arg("a") @@ -64,9 +62,7 @@ fn runtest(me: &str) { .output() .unwrap(); assert!(p.status.success()); - assert!(String::from_utf8_lossy(&p.stdout).contains("stack backtrace:\n")); let p = Command::new(me).arg("force").output().unwrap(); assert!(p.status.success()); - assert!(String::from_utf8_lossy(&p.stdout).contains("stack backtrace:\n")); } -- cgit 1.4.1-3-g733a5 From d77c38727298ee442db4d927c13bc8b2de1db448 Mon Sep 17 00:00:00 2001 From: Daniel Paoliello Date: Sun, 13 Jul 2025 15:01:48 -0700 Subject: Fixes for Arm64EC --- tests/ui/cfg/conditional-compile-arch.rs | 3 +++ tests/ui/linkage-attr/incompatible-flavor.rs | 2 +- tests/ui/runtime/backtrace-debuginfo.rs | 3 ++- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/ui/cfg/conditional-compile-arch.rs b/tests/ui/cfg/conditional-compile-arch.rs index 594d9344561..f1680547407 100644 --- a/tests/ui/cfg/conditional-compile-arch.rs +++ b/tests/ui/cfg/conditional-compile-arch.rs @@ -38,3 +38,6 @@ pub fn main() { } #[cfg(target_arch = "loongarch64")] pub fn main() { } + +#[cfg(target_arch = "arm64ec")] +pub fn main() { } diff --git a/tests/ui/linkage-attr/incompatible-flavor.rs b/tests/ui/linkage-attr/incompatible-flavor.rs index 7f583f47e2f..4711343f9c9 100644 --- a/tests/ui/linkage-attr/incompatible-flavor.rs +++ b/tests/ui/linkage-attr/incompatible-flavor.rs @@ -1,5 +1,5 @@ //@ compile-flags: --target=x86_64-unknown-linux-gnu -C linker-flavor=msvc --crate-type=rlib -//@ needs-llvm-components: +//@ needs-llvm-components: x86 #![feature(no_core)] #![no_core] diff --git a/tests/ui/runtime/backtrace-debuginfo.rs b/tests/ui/runtime/backtrace-debuginfo.rs index 37fce2788b7..5fb9943d6c3 100644 --- a/tests/ui/runtime/backtrace-debuginfo.rs +++ b/tests/ui/runtime/backtrace-debuginfo.rs @@ -43,12 +43,13 @@ macro_rules! dump_and_die { // rust-lang/rust to test it as well, but sometimes we just gotta keep // landing PRs. // - // aarch64-msvc is broken as its backtraces are truncated. + // aarch64-msvc/arm64ec-msvc is broken as its backtraces are truncated. // See https://github.com/rust-lang/rust/issues/140489 if cfg!(any(target_os = "android", all(target_os = "linux", target_arch = "arm"), all(target_env = "msvc", target_arch = "x86"), all(target_env = "msvc", target_arch = "aarch64"), + all(target_env = "msvc", target_arch = "arm64ec"), target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd")) { -- cgit 1.4.1-3-g733a5 From 05154af3e857f23b41072793e401a78a5aa952d9 Mon Sep 17 00:00:00 2001 From: SunkenPotato <3.14radius02@gmail.com> Date: Tue, 15 Jul 2025 16:26:24 +0200 Subject: docs: update documentation of core::mem::copy to include const on the fn signature --- library/core/src/mem/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index 1bd12d818cf..164fcdad5c4 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -960,7 +960,7 @@ pub fn drop(_x: T) {} /// /// This function is not magic; it is literally defined as /// ``` -/// pub fn copy(x: &T) -> T { *x } +/// pub const fn copy(x: &T) -> T { *x } /// ``` /// /// It is useful when you want to pass a function pointer to a combinator, rather than defining a new closure. -- cgit 1.4.1-3-g733a5 From 690ae523e5c0ac9602db7bbe2b8094ee422e4d0f Mon Sep 17 00:00:00 2001 From: Esteban Küber Date: Sun, 20 Jul 2025 01:19:55 +0000 Subject: Tweak borrowck label pointing at `!Copy` value moved into closure When encountering a non-`Copy` value that is moved into a closure which is coming directly from a fn parameter, point at the parameter's type when mentioning it is not `Copy`. Before: ``` error[E0507]: cannot move out of `foo`, a captured variable in an `Fn` closure --> f111.rs:14:25 | 13 | fn do_stuff(foo: Option) { | --- captured outer variable 14 | require_fn_trait(|| async { | -- ^^^^^ `foo` is moved here | | | captured by this `Fn` closure 15 | if foo.map_or(false, |f| f.foo()) { | --- | | | variable moved due to use in coroutine | move occurs because `foo` has type `Option`, which does not implement the `Copy` trait ``` After: ``` error[E0507]: cannot move out of `foo`, a captured variable in an `Fn` closure --> f111.rs:14:25 | 13 | fn do_stuff(foo: Option) { | --- ----------- move occurs because `foo` has type `Option`, which does not implement the `Copy` trait | | | captured outer variable 14 | require_fn_trait(|| async { | -- ^^^^^ `foo` is moved here | | | captured by this `Fn` closure 15 | if foo.map_or(false, |f| f.foo()) { | --- variable moved due to use in coroutine ``` --- .../rustc_borrowck/src/diagnostics/move_errors.rs | 129 +++++++++++++-------- tests/ui/issues/issue-4335.stderr | 6 +- 2 files changed, 82 insertions(+), 53 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 92ca868eb99..28024e6fece 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -115,10 +115,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { fn append_to_grouped_errors( &self, grouped_errors: &mut Vec>, - error: MoveError<'tcx>, + MoveError { place: original_path, location, kind }: MoveError<'tcx>, ) { - let MoveError { place: original_path, location, kind } = error; - // Note: that the only time we assign a place isn't a temporary // to a user variable is when initializing it. // If that ever stops being the case, then the ever initialized @@ -251,54 +249,47 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } fn report(&mut self, error: GroupedMoveError<'tcx>) { - let (mut err, err_span) = { - let (span, use_spans, original_path, kind) = match error { - GroupedMoveError::MovesFromPlace { span, original_path, ref kind, .. } - | GroupedMoveError::MovesFromValue { span, original_path, ref kind, .. } => { - (span, None, original_path, kind) - } - GroupedMoveError::OtherIllegalMove { use_spans, original_path, ref kind } => { - (use_spans.args_or_use(), Some(use_spans), original_path, kind) - } - }; - debug!( - "report: original_path={:?} span={:?}, kind={:?} \ - original_path.is_upvar_field_projection={:?}", - original_path, - span, - kind, - self.is_upvar_field_projection(original_path.as_ref()) - ); - if self.has_ambiguous_copy(original_path.ty(self.body, self.infcx.tcx).ty) { - // If the type may implement Copy, skip the error. - // It's an error with the Copy implementation (e.g. duplicate Copy) rather than borrow check - self.dcx().span_delayed_bug( + let (span, use_spans, original_path, kind) = match error { + GroupedMoveError::MovesFromPlace { span, original_path, ref kind, .. } + | GroupedMoveError::MovesFromValue { span, original_path, ref kind, .. } => { + (span, None, original_path, kind) + } + GroupedMoveError::OtherIllegalMove { use_spans, original_path, ref kind } => { + (use_spans.args_or_use(), Some(use_spans), original_path, kind) + } + }; + debug!( + "report: original_path={:?} span={:?}, kind={:?} \ + original_path.is_upvar_field_projection={:?}", + original_path, + span, + kind, + self.is_upvar_field_projection(original_path.as_ref()) + ); + if self.has_ambiguous_copy(original_path.ty(self.body, self.infcx.tcx).ty) { + // If the type may implement Copy, skip the error. + // It's an error with the Copy implementation (e.g. duplicate Copy) rather than borrow check + self.dcx() + .span_delayed_bug(span, "Type may implement copy, but there is no other error."); + return; + } + let mut err = match kind { + &IllegalMoveOriginKind::BorrowedContent { target_place } => self + .report_cannot_move_from_borrowed_content( + original_path, + target_place, span, - "Type may implement copy, but there is no other error.", - ); - return; + use_spans, + ), + &IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => { + self.cannot_move_out_of_interior_of_drop(span, ty) + } + &IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => { + self.cannot_move_out_of_interior_noncopy(span, ty, Some(is_index)) } - ( - match kind { - &IllegalMoveOriginKind::BorrowedContent { target_place } => self - .report_cannot_move_from_borrowed_content( - original_path, - target_place, - span, - use_spans, - ), - &IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => { - self.cannot_move_out_of_interior_of_drop(span, ty) - } - &IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => { - self.cannot_move_out_of_interior_noncopy(span, ty, Some(is_index)) - } - }, - span, - ) }; - self.add_move_hints(error, &mut err, err_span); + self.add_move_hints(error, &mut err, span); self.buffer_error(err); } @@ -482,7 +473,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { self.cannot_move_out_of_interior_noncopy(span, ty, None) } ty::Closure(def_id, closure_args) - if def_id.as_local() == Some(self.mir_def_id()) && upvar_field.is_some() => + if def_id.as_local() == Some(self.mir_def_id()) + && let Some(upvar_field) = upvar_field => { let closure_kind_ty = closure_args.as_closure().kind_ty(); let closure_kind = match closure_kind_ty.to_opt_closure_kind() { @@ -495,7 +487,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let capture_description = format!("captured variable in an `{closure_kind}` closure"); - let upvar = &self.upvars[upvar_field.unwrap().index()]; + let upvar = &self.upvars[upvar_field.index()]; let upvar_hir_id = upvar.get_root_variable(); let upvar_name = upvar.to_string(tcx); let upvar_span = tcx.hir_span(upvar_hir_id); @@ -604,8 +596,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { self.add_move_error_details(err, &binds_to); } // No binding. Nothing to suggest. - GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => { - let use_span = use_spans.var_or_use(); + GroupedMoveError::OtherIllegalMove { + ref original_path, use_spans, ref kind, .. + } => { + let mut use_span = use_spans.var_or_use(); let place_ty = original_path.ty(self.body, self.infcx.tcx).ty; let place_desc = match self.describe_place(original_path.as_ref()) { Some(desc) => format!("`{desc}`"), @@ -622,6 +616,39 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { ); } + if let IllegalMoveOriginKind::BorrowedContent { target_place } = &kind + && let ty = target_place.ty(self.body, self.infcx.tcx).ty + && let ty::Closure(def_id, _) = ty.kind() + && def_id.as_local() == Some(self.mir_def_id()) + && let Some(upvar_field) = self + .prefixes(original_path.as_ref(), PrefixSet::All) + .find_map(|p| self.is_upvar_field_projection(p)) + && let upvar = &self.upvars[upvar_field.index()] + && let upvar_hir_id = upvar.get_root_variable() + && let hir::Node::Param(param) = self.infcx.tcx.parent_hir_node(upvar_hir_id) + { + // Instead of pointing at the path where we access the value within a closure, + // we point at the type on the parameter from the definition of the outer + // function: + // + // error[E0507]: cannot move out of `foo`, a captured + // variable in an `Fn` closure + // --> file.rs:14:25 + // | + // 13 | fn do_stuff(foo: Option) { + // | --- ----------- move occurs because `foo` has type + // | | `Option`, which does not implement + // | | the `Copy` trait + // | captured outer variable + // 14 | require_fn_trait(|| async { + // | -- ^^^^^ `foo` is moved here + // | | + // | captured by this `Fn` closure + // 15 | if foo.map_or(false, |f| f.foo()) { + // | --- variable moved due to use in coroutine + use_span = param.ty_span; + } + err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { is_partial_move: false, ty: place_ty, diff --git a/tests/ui/issues/issue-4335.stderr b/tests/ui/issues/issue-4335.stderr index 14b5cfa9f9a..1f1a2595a31 100644 --- a/tests/ui/issues/issue-4335.stderr +++ b/tests/ui/issues/issue-4335.stderr @@ -2,9 +2,11 @@ error[E0507]: cannot move out of `*v`, as `v` is a captured variable in an `FnMu --> $DIR/issue-4335.rs:6:20 | LL | fn f<'r, T>(v: &'r T) -> Box T + 'r> { - | - captured outer variable + | - ----- move occurs because `*v` has type `T`, which does not implement the `Copy` trait + | | + | captured outer variable LL | id(Box::new(|| *v)) - | -- ^^ move occurs because `*v` has type `T`, which does not implement the `Copy` trait + | -- ^^ | | | captured by this `FnMut` closure | -- cgit 1.4.1-3-g733a5 From 5082e6a300974459aec6dc73e76cc039c3a517c1 Mon Sep 17 00:00:00 2001 From: Esteban Küber Date: Sun, 20 Jul 2025 02:15:45 +0000 Subject: Generalize logic pointing at binding moved into closure Account not only for `fn` parameters when moving non-`Copy` values into closure, but also for let bindings. ``` error[E0507]: cannot move out of `bar`, a captured variable in an `FnMut` closure --> $DIR/borrowck-move-by-capture.rs:9:29 | LL | let bar: Box<_> = Box::new(3); | --- ------ move occurs because `bar` has type `Box`, which does not implement the `Copy` trait | | | captured outer variable LL | let _g = to_fn_mut(|| { | -- captured by this `FnMut` closure LL | let _h = to_fn_once(move || -> isize { *bar }); | ^^^^^^^^^^^^^^^^ ---- variable moved due to use in closure | | | `bar` is moved here | help: consider cloning the value before moving it into the closure | LL ~ let value = bar.clone(); LL ~ let _h = to_fn_once(move || -> isize { value }); | ``` ``` error[E0507]: cannot move out of `y`, a captured variable in an `Fn` closure --> $DIR/unboxed-closures-move-upvar-from-non-once-ref-closure.rs:12:9 | LL | let y = vec![format!("World")]; | - ---------------------- move occurs because `y` has type `Vec`, which does not implement the `Copy` trait | | | captured outer variable LL | call(|| { | -- captured by this `Fn` closure LL | y.into_iter(); | ^ ----------- `y` moved due to this method call | | | `y` is moved here | note: `into_iter` takes ownership of the receiver `self`, which moves `y` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | as Clone>::clone(&y).into_iter(); | +++++++++++++++++++++++++++++++ + help: consider cloning the value if the performance cost is acceptable | LL | y.clone().into_iter(); | ++++++++ ``` --- .../rustc_borrowck/src/diagnostics/move_errors.rs | 79 +++++++++++++++------- tests/ui/borrowck/borrowck-in-static.stderr | 6 +- tests/ui/borrowck/borrowck-move-by-capture.stderr | 10 +-- tests/ui/borrowck/issue-103624.stderr | 7 +- ...res-move-upvar-from-non-once-ref-closure.stderr | 6 +- tests/ui/issues/issue-4335.stderr | 2 +- ...-type-move-out-of-closure-env-issue-1965.stderr | 6 +- .../issue-52663-span-decl-captured-variable.stderr | 6 +- .../borrowck-call-is-borrow-issue-12224.stderr | 18 +++-- tests/ui/suggestions/option-content-move2.stderr | 18 +++-- tests/ui/suggestions/option-content-move3.stderr | 18 +++-- .../unboxed-closure-illegal-move.stderr | 24 ++++--- 12 files changed, 125 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 28024e6fece..56f7fe68854 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -623,30 +623,51 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { && let Some(upvar_field) = self .prefixes(original_path.as_ref(), PrefixSet::All) .find_map(|p| self.is_upvar_field_projection(p)) - && let upvar = &self.upvars[upvar_field.index()] - && let upvar_hir_id = upvar.get_root_variable() - && let hir::Node::Param(param) = self.infcx.tcx.parent_hir_node(upvar_hir_id) { - // Instead of pointing at the path where we access the value within a closure, - // we point at the type on the parameter from the definition of the outer - // function: - // - // error[E0507]: cannot move out of `foo`, a captured - // variable in an `Fn` closure - // --> file.rs:14:25 - // | - // 13 | fn do_stuff(foo: Option) { - // | --- ----------- move occurs because `foo` has type - // | | `Option`, which does not implement - // | | the `Copy` trait - // | captured outer variable - // 14 | require_fn_trait(|| async { - // | -- ^^^^^ `foo` is moved here - // | | - // | captured by this `Fn` closure - // 15 | if foo.map_or(false, |f| f.foo()) { - // | --- variable moved due to use in coroutine - use_span = param.ty_span; + let upvar = &self.upvars[upvar_field.index()]; + let upvar_hir_id = upvar.get_root_variable(); + use_span = match self.infcx.tcx.parent_hir_node(upvar_hir_id) { + hir::Node::Param(param) => { + // Instead of pointing at the path where we access the value within a + // closure, we point at the type on the parameter from the definition + // of the outer function: + // + // error[E0507]: cannot move out of `foo`, a captured + // variable in an `Fn` closure + // --> file.rs:14:25 + // | + // 13 | fn do_stuff(foo: Option) { + // | --- ----------- move occurs because `foo` has type + // | | `Option`, which does not + // | | implement the `Copy` trait + // | captured outer variable + // 14 | require_fn_trait(|| async { + // | -- ^^^^^ `foo` is moved here + // | | + // | captured by this `Fn` closure + // 15 | if foo.map_or(false, |f| f.foo()) { + // | --- variable moved due to use in coroutine + param.ty_span + } + hir::Node::LetStmt(stmt) => match (stmt.ty, stmt.init) { + // 13 | fn do_stuff(foo: Option) { + // 14 | let foo: Option = foo; + // | --- ----------- move occurs because `foo` has type + // | | `Option`, which does not implement + // | | the `Copy` trait + // | captured outer variable + (Some(ty), _) => ty.span, + // 13 | fn do_stuff(bar: Option) { + // 14 | let foo = bar; + // | --- --- move occurs because `foo` has type + // | | `Option`, which does not implement the + // | | `Copy` trait + // | captured outer variable + (None, Some(init)) => init.span, + (None, None) => use_span, + }, + _ => use_span, + }; } err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { @@ -656,12 +677,22 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { span: use_span, }); + let mut pointed_at_span = false; use_spans.args_subdiag(err, |args_span| { + if args_span == span || args_span == use_span { + pointed_at_span = true; + } crate::session_diagnostics::CaptureArgLabel::MoveOutPlace { - place: place_desc, + place: place_desc.clone(), args_span, } }); + if !pointed_at_span && use_span != span { + err.subdiagnostic(crate::session_diagnostics::CaptureArgLabel::MoveOutPlace { + place: place_desc, + args_span: span, + }); + } self.add_note_for_packed_struct_derive(err, original_path.local); } diff --git a/tests/ui/borrowck/borrowck-in-static.stderr b/tests/ui/borrowck/borrowck-in-static.stderr index 745b02ae21b..9bcf64dd62e 100644 --- a/tests/ui/borrowck/borrowck-in-static.stderr +++ b/tests/ui/borrowck/borrowck-in-static.stderr @@ -2,9 +2,11 @@ error[E0507]: cannot move out of `x`, a captured variable in an `Fn` closure --> $DIR/borrowck-in-static.rs:5:17 | LL | let x = Box::new(0); - | - captured outer variable + | - ----------- move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | | + | captured outer variable LL | Box::new(|| x) - | -- ^ move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | -- ^ `x` is moved here | | | captured by this `Fn` closure | diff --git a/tests/ui/borrowck/borrowck-move-by-capture.stderr b/tests/ui/borrowck/borrowck-move-by-capture.stderr index 58d5e90e990..732af1593d6 100644 --- a/tests/ui/borrowck/borrowck-move-by-capture.stderr +++ b/tests/ui/borrowck/borrowck-move-by-capture.stderr @@ -2,14 +2,14 @@ error[E0507]: cannot move out of `bar`, a captured variable in an `FnMut` closur --> $DIR/borrowck-move-by-capture.rs:9:29 | LL | let bar: Box<_> = Box::new(3); - | --- captured outer variable + | --- ------ move occurs because `bar` has type `Box`, which does not implement the `Copy` trait + | | + | captured outer variable LL | let _g = to_fn_mut(|| { | -- captured by this `FnMut` closure LL | let _h = to_fn_once(move || -> isize { *bar }); - | ^^^^^^^^^^^^^^^^ ---- - | | | - | | variable moved due to use in closure - | | move occurs because `bar` has type `Box`, which does not implement the `Copy` trait + | ^^^^^^^^^^^^^^^^ ---- variable moved due to use in closure + | | | `bar` is moved here | help: consider cloning the value before moving it into the closure diff --git a/tests/ui/borrowck/issue-103624.stderr b/tests/ui/borrowck/issue-103624.stderr index 603055beadc..af65deb16dc 100644 --- a/tests/ui/borrowck/issue-103624.stderr +++ b/tests/ui/borrowck/issue-103624.stderr @@ -2,13 +2,16 @@ error[E0507]: cannot move out of `self.b`, as `self` is a captured variable in a --> $DIR/issue-103624.rs:16:13 | LL | async fn foo(&self) { - | ----- captured outer variable + | ----- + | | + | captured outer variable + | move occurs because `self.b` has type `StructB`, which does not implement the `Copy` trait LL | let bar = self.b.bar().await; LL | spawn_blocking(move || { | ------- captured by this `Fn` closure LL | LL | self.b; - | ^^^^^^ move occurs because `self.b` has type `StructB`, which does not implement the `Copy` trait + | ^^^^^^ `self.b` is moved here | note: if `StructB` implemented `Clone`, you could clone the value --> $DIR/issue-103624.rs:23:1 diff --git a/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr b/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr index 177e9c8d248..da0e133ba02 100644 --- a/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr +++ b/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr @@ -2,13 +2,15 @@ error[E0507]: cannot move out of `y`, a captured variable in an `Fn` closure --> $DIR/unboxed-closures-move-upvar-from-non-once-ref-closure.rs:12:9 | LL | let y = vec![format!("World")]; - | - captured outer variable + | - ---------------------- move occurs because `y` has type `Vec`, which does not implement the `Copy` trait + | | + | captured outer variable LL | call(|| { | -- captured by this `Fn` closure LL | y.into_iter(); | ^ ----------- `y` moved due to this method call | | - | move occurs because `y` has type `Vec`, which does not implement the `Copy` trait + | `y` is moved here | note: `into_iter` takes ownership of the receiver `self`, which moves `y` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL diff --git a/tests/ui/issues/issue-4335.stderr b/tests/ui/issues/issue-4335.stderr index 1f1a2595a31..42ac6322564 100644 --- a/tests/ui/issues/issue-4335.stderr +++ b/tests/ui/issues/issue-4335.stderr @@ -6,7 +6,7 @@ LL | fn f<'r, T>(v: &'r T) -> Box T + 'r> { | | | captured outer variable LL | id(Box::new(|| *v)) - | -- ^^ + | -- ^^ `*v` is moved here | | | captured by this `FnMut` closure | diff --git a/tests/ui/moves/moves-based-on-type-move-out-of-closure-env-issue-1965.stderr b/tests/ui/moves/moves-based-on-type-move-out-of-closure-env-issue-1965.stderr index 523134a9425..51d0f85c031 100644 --- a/tests/ui/moves/moves-based-on-type-move-out-of-closure-env-issue-1965.stderr +++ b/tests/ui/moves/moves-based-on-type-move-out-of-closure-env-issue-1965.stderr @@ -2,9 +2,11 @@ error[E0507]: cannot move out of `i`, a captured variable in an `Fn` closure --> $DIR/moves-based-on-type-move-out-of-closure-env-issue-1965.rs:9:28 | LL | let i = Box::new(3); - | - captured outer variable + | - ----------- move occurs because `i` has type `Box`, which does not implement the `Copy` trait + | | + | captured outer variable LL | let _f = to_fn(|| test(i)); - | -- ^ move occurs because `i` has type `Box`, which does not implement the `Copy` trait + | -- ^ `i` is moved here | | | captured by this `Fn` closure | diff --git a/tests/ui/nll/issue-52663-span-decl-captured-variable.stderr b/tests/ui/nll/issue-52663-span-decl-captured-variable.stderr index fbaec8a6008..57546037006 100644 --- a/tests/ui/nll/issue-52663-span-decl-captured-variable.stderr +++ b/tests/ui/nll/issue-52663-span-decl-captured-variable.stderr @@ -2,9 +2,11 @@ error[E0507]: cannot move out of `x.0`, as `x` is a captured variable in an `Fn` --> $DIR/issue-52663-span-decl-captured-variable.rs:8:26 | LL | let x = (vec![22], vec![44]); - | - captured outer variable + | - -------------------- move occurs because `x.0` has type `Vec`, which does not implement the `Copy` trait + | | + | captured outer variable LL | expect_fn(|| drop(x.0)); - | -- ^^^ move occurs because `x.0` has type `Vec`, which does not implement the `Copy` trait + | -- ^^^ `x.0` is moved here | | | captured by this `Fn` closure | diff --git a/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr b/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr index f37dc320fa3..28761692413 100644 --- a/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr +++ b/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr @@ -35,14 +35,18 @@ LL | fn test4(f: &mut Test) { error[E0507]: cannot move out of `f`, a captured variable in an `FnMut` closure --> $DIR/borrowck-call-is-borrow-issue-12224.rs:57:13 | -LL | let mut f = move |g: Box, b: isize| { - | ----- captured outer variable -... -LL | f(Box::new(|a| { - | --- captured by this `FnMut` closure +LL | let mut f = move |g: Box, b: isize| { + | _________-----___- + | | | + | | captured outer variable +LL | | let _ = s.len(); +LL | | }; + | |_____- move occurs because `f` has type `{closure@$DIR/borrowck-call-is-borrow-issue-12224.rs:52:17: 52:58}`, which does not implement the `Copy` trait +LL | f(Box::new(|a| { + | --- captured by this `FnMut` closure LL | -LL | foo(f); - | ^ move occurs because `f` has type `{closure@$DIR/borrowck-call-is-borrow-issue-12224.rs:52:17: 52:58}`, which does not implement the `Copy` trait +LL | foo(f); + | ^ `f` is moved here | help: consider cloning the value if the performance cost is acceptable | diff --git a/tests/ui/suggestions/option-content-move2.stderr b/tests/ui/suggestions/option-content-move2.stderr index be97cba17b9..436441d6f1b 100644 --- a/tests/ui/suggestions/option-content-move2.stderr +++ b/tests/ui/suggestions/option-content-move2.stderr @@ -2,7 +2,9 @@ error[E0507]: cannot move out of `var`, a captured variable in an `FnMut` closur --> $DIR/option-content-move2.rs:11:9 | LL | let mut var = None; - | ------- captured outer variable + | ------- ---- move occurs because `var` has type `Option`, which does not implement the `Copy` trait + | | + | captured outer variable LL | func(|| { | -- captured by this `FnMut` closure LL | // Shouldn't suggest `move ||.as_ref()` here @@ -10,16 +12,15 @@ LL | move || { | ^^^^^^^ `var` is moved here LL | LL | var = Some(NotCopyable); - | --- - | | - | variable moved due to use in closure - | move occurs because `var` has type `Option`, which does not implement the `Copy` trait + | --- variable moved due to use in closure error[E0507]: cannot move out of `var`, a captured variable in an `FnMut` closure --> $DIR/option-content-move2.rs:21:9 | LL | let mut var = None; - | ------- captured outer variable + | ------- ---- move occurs because `var` has type `Option`, which does not implement the `Copy` trait + | | + | captured outer variable LL | func(|| { | -- captured by this `FnMut` closure LL | // Shouldn't suggest `move ||.as_ref()` nor to `clone()` here @@ -27,10 +28,7 @@ LL | move || { | ^^^^^^^ `var` is moved here LL | LL | var = Some(NotCopyableButCloneable); - | --- - | | - | variable moved due to use in closure - | move occurs because `var` has type `Option`, which does not implement the `Copy` trait + | --- variable moved due to use in closure error: aborting due to 2 previous errors diff --git a/tests/ui/suggestions/option-content-move3.stderr b/tests/ui/suggestions/option-content-move3.stderr index faaf8a9df9d..68c52352a65 100644 --- a/tests/ui/suggestions/option-content-move3.stderr +++ b/tests/ui/suggestions/option-content-move3.stderr @@ -26,17 +26,16 @@ error[E0507]: cannot move out of `var`, a captured variable in an `FnMut` closur --> $DIR/option-content-move3.rs:12:9 | LL | let var = NotCopyable; - | --- captured outer variable + | --- ----------- move occurs because `var` has type `NotCopyable`, which does not implement the `Copy` trait + | | + | captured outer variable LL | func(|| { | -- captured by this `FnMut` closure LL | // Shouldn't suggest `move ||.as_ref()` here LL | move || { | ^^^^^^^ `var` is moved here LL | let x = var; - | --- - | | - | variable moved due to use in closure - | move occurs because `var` has type `NotCopyable`, which does not implement the `Copy` trait + | --- variable moved due to use in closure | note: if `NotCopyable` implemented `Clone`, you could clone the value --> $DIR/option-content-move3.rs:2:1 @@ -67,17 +66,16 @@ error[E0507]: cannot move out of `var`, a captured variable in an `FnMut` closur --> $DIR/option-content-move3.rs:23:9 | LL | let var = NotCopyableButCloneable; - | --- captured outer variable + | --- ----------------------- move occurs because `var` has type `NotCopyableButCloneable`, which does not implement the `Copy` trait + | | + | captured outer variable LL | func(|| { | -- captured by this `FnMut` closure LL | // Shouldn't suggest `move ||.as_ref()` here LL | move || { | ^^^^^^^ `var` is moved here LL | let x = var; - | --- - | | - | variable moved due to use in closure - | move occurs because `var` has type `NotCopyableButCloneable`, which does not implement the `Copy` trait + | --- variable moved due to use in closure | help: consider cloning the value before moving it into the closure | diff --git a/tests/ui/unboxed-closures/unboxed-closure-illegal-move.stderr b/tests/ui/unboxed-closures/unboxed-closure-illegal-move.stderr index cf4391311d0..8d9a61cb681 100644 --- a/tests/ui/unboxed-closures/unboxed-closure-illegal-move.stderr +++ b/tests/ui/unboxed-closures/unboxed-closure-illegal-move.stderr @@ -2,9 +2,11 @@ error[E0507]: cannot move out of `x`, a captured variable in an `Fn` closure --> $DIR/unboxed-closure-illegal-move.rs:15:31 | LL | let x = Box::new(0); - | - captured outer variable + | - ----------- move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | | + | captured outer variable LL | let f = to_fn(|| drop(x)); - | -- ^ move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | -- ^ `x` is moved here | | | captured by this `Fn` closure | @@ -17,9 +19,11 @@ error[E0507]: cannot move out of `x`, a captured variable in an `FnMut` closure --> $DIR/unboxed-closure-illegal-move.rs:19:35 | LL | let x = Box::new(0); - | - captured outer variable + | - ----------- move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | | + | captured outer variable LL | let f = to_fn_mut(|| drop(x)); - | -- ^ move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | -- ^ `x` is moved here | | | captured by this `FnMut` closure | @@ -32,9 +36,11 @@ error[E0507]: cannot move out of `x`, a captured variable in an `Fn` closure --> $DIR/unboxed-closure-illegal-move.rs:28:36 | LL | let x = Box::new(0); - | - captured outer variable + | - ----------- move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | | + | captured outer variable LL | let f = to_fn(move || drop(x)); - | ------- ^ move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | ------- ^ `x` is moved here | | | captured by this `Fn` closure @@ -42,9 +48,11 @@ error[E0507]: cannot move out of `x`, a captured variable in an `FnMut` closure --> $DIR/unboxed-closure-illegal-move.rs:32:40 | LL | let x = Box::new(0); - | - captured outer variable + | - ----------- move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | | + | captured outer variable LL | let f = to_fn_mut(move || drop(x)); - | ------- ^ move occurs because `x` has type `Box`, which does not implement the `Copy` trait + | ------- ^ `x` is moved here | | | captured by this `FnMut` closure -- cgit 1.4.1-3-g733a5 From 8df93e6966e71da8a249a0022680b83eff105f42 Mon Sep 17 00:00:00 2001 From: Esteban Küber Date: Sun, 20 Jul 2025 02:22:55 +0000 Subject: Tweak spans when encountering multiline initializer in move error ``` error[E0507]: cannot move out of `f`, a captured variable in an `FnMut` closure --> $DIR/borrowck-call-is-borrow-issue-12224.rs:57:13 | LL | let mut f = move |g: Box, b: isize| { | ----- captured outer variable ... LL | f(Box::new(|a| { | --- captured by this `FnMut` closure LL | LL | foo(f); | ^ move occurs because `f` has type `{closure@$DIR/borrowck-call-is-borrow-issue-12224.rs:52:17: 52:58}`, which does not implement the `Copy` trait ``` instead of ``` error[E0507]: cannot move out of `f`, a captured variable in an `FnMut` closure --> $DIR/borrowck-call-is-borrow-issue-12224.rs:57:13 | LL | let mut f = move |g: Box, b: isize| { | _________-----___- | | | | | captured outer variable LL | | let _ = s.len(); LL | | }; | |_____- move occurs because `f` has type `{closure@$DIR/borrowck-call-is-borrow-issue-12224.rs:52:17: 52:58}`, which does not implement the `Copy` trait LL | f(Box::new(|a| { | --- captured by this `FnMut` closure LL | LL | foo(f); | ^ `f` is moved here ``` --- compiler/rustc_borrowck/src/diagnostics/move_errors.rs | 11 +++++++++-- ...losures-move-upvar-from-non-once-ref-closure.stderr | 6 ++---- .../ui/span/borrowck-call-is-borrow-issue-12224.stderr | 18 +++++++----------- 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 56f7fe68854..40361906e04 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -663,8 +663,15 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // | | `Option`, which does not implement the // | | `Copy` trait // | captured outer variable - (None, Some(init)) => init.span, - (None, None) => use_span, + // + // We don't want the case where the initializer is something that spans + // multiple lines, like a closure, as the ASCII art gets messy. + (None, Some(init)) + if !self.infcx.tcx.sess.source_map().is_multiline(init.span) => + { + init.span + } + _ => use_span, }, _ => use_span, }; diff --git a/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr b/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr index da0e133ba02..177e9c8d248 100644 --- a/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr +++ b/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr @@ -2,15 +2,13 @@ error[E0507]: cannot move out of `y`, a captured variable in an `Fn` closure --> $DIR/unboxed-closures-move-upvar-from-non-once-ref-closure.rs:12:9 | LL | let y = vec![format!("World")]; - | - ---------------------- move occurs because `y` has type `Vec`, which does not implement the `Copy` trait - | | - | captured outer variable + | - captured outer variable LL | call(|| { | -- captured by this `Fn` closure LL | y.into_iter(); | ^ ----------- `y` moved due to this method call | | - | `y` is moved here + | move occurs because `y` has type `Vec`, which does not implement the `Copy` trait | note: `into_iter` takes ownership of the receiver `self`, which moves `y` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL diff --git a/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr b/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr index 28761692413..f37dc320fa3 100644 --- a/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr +++ b/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr @@ -35,18 +35,14 @@ LL | fn test4(f: &mut Test) { error[E0507]: cannot move out of `f`, a captured variable in an `FnMut` closure --> $DIR/borrowck-call-is-borrow-issue-12224.rs:57:13 | -LL | let mut f = move |g: Box, b: isize| { - | _________-----___- - | | | - | | captured outer variable -LL | | let _ = s.len(); -LL | | }; - | |_____- move occurs because `f` has type `{closure@$DIR/borrowck-call-is-borrow-issue-12224.rs:52:17: 52:58}`, which does not implement the `Copy` trait -LL | f(Box::new(|a| { - | --- captured by this `FnMut` closure +LL | let mut f = move |g: Box, b: isize| { + | ----- captured outer variable +... +LL | f(Box::new(|a| { + | --- captured by this `FnMut` closure LL | -LL | foo(f); - | ^ `f` is moved here +LL | foo(f); + | ^ move occurs because `f` has type `{closure@$DIR/borrowck-call-is-borrow-issue-12224.rs:52:17: 52:58}`, which does not implement the `Copy` trait | help: consider cloning the value if the performance cost is acceptable | -- cgit 1.4.1-3-g733a5 From dafc9f9b534c8d1a50ba87f776eb1d6dfb1a7c94 Mon Sep 17 00:00:00 2001 From: Esteban Küber Date: Mon, 21 Jul 2025 16:23:13 +0000 Subject: Reduce comment verbosity --- .../rustc_borrowck/src/diagnostics/move_errors.rs | 38 +++------------------- 1 file changed, 5 insertions(+), 33 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 40361906e04..67dce7615c0 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -629,43 +629,15 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { use_span = match self.infcx.tcx.parent_hir_node(upvar_hir_id) { hir::Node::Param(param) => { // Instead of pointing at the path where we access the value within a - // closure, we point at the type on the parameter from the definition - // of the outer function: - // - // error[E0507]: cannot move out of `foo`, a captured - // variable in an `Fn` closure - // --> file.rs:14:25 - // | - // 13 | fn do_stuff(foo: Option) { - // | --- ----------- move occurs because `foo` has type - // | | `Option`, which does not - // | | implement the `Copy` trait - // | captured outer variable - // 14 | require_fn_trait(|| async { - // | -- ^^^^^ `foo` is moved here - // | | - // | captured by this `Fn` closure - // 15 | if foo.map_or(false, |f| f.foo()) { - // | --- variable moved due to use in coroutine + // closure, we point at the type of the outer `fn` argument. param.ty_span } hir::Node::LetStmt(stmt) => match (stmt.ty, stmt.init) { - // 13 | fn do_stuff(foo: Option) { - // 14 | let foo: Option = foo; - // | --- ----------- move occurs because `foo` has type - // | | `Option`, which does not implement - // | | the `Copy` trait - // | captured outer variable + // We point at the type of the outer let-binding. (Some(ty), _) => ty.span, - // 13 | fn do_stuff(bar: Option) { - // 14 | let foo = bar; - // | --- --- move occurs because `foo` has type - // | | `Option`, which does not implement the - // | | `Copy` trait - // | captured outer variable - // - // We don't want the case where the initializer is something that spans - // multiple lines, like a closure, as the ASCII art gets messy. + // We point at the initializer of the outer let-binding, but only if it + // isn't something that spans multiple lines, like a closure, as the + // ASCII art gets messy. (None, Some(init)) if !self.infcx.tcx.sess.source_map().is_multiline(init.span) => { -- cgit 1.4.1-3-g733a5 From 01fdafc9aac788e96af33f8daada26809ea2bff7 Mon Sep 17 00:00:00 2001 From: Kornel Date: Tue, 22 Jul 2025 17:07:16 +0100 Subject: Hint that choose_pivot returns index in bounds --- library/core/src/slice/sort/select.rs | 3 +-- library/core/src/slice/sort/shared/pivot.rs | 10 ++++++++-- library/core/src/slice/sort/stable/quicksort.rs | 4 ---- library/core/src/slice/sort/unstable/quicksort.rs | 3 +-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/library/core/src/slice/sort/select.rs b/library/core/src/slice/sort/select.rs index 82194db7fd8..fc31013caf8 100644 --- a/library/core/src/slice/sort/select.rs +++ b/library/core/src/slice/sort/select.rs @@ -101,8 +101,7 @@ fn partition_at_index_loop<'a, T, F>( // slice. Partition the slice into elements equal to and elements greater than the pivot. // This case is usually hit when the slice contains many duplicate elements. if let Some(p) = ancestor_pivot { - // SAFETY: choose_pivot promises to return a valid pivot position. - let pivot = unsafe { v.get_unchecked(pivot_pos) }; + let pivot = &v[pivot_pos]; if !is_less(p, pivot) { let num_lt = partition(v, pivot_pos, &mut |a, b| !is_less(b, a)); diff --git a/library/core/src/slice/sort/shared/pivot.rs b/library/core/src/slice/sort/shared/pivot.rs index 3aace484b6a..9eb60f854ce 100644 --- a/library/core/src/slice/sort/shared/pivot.rs +++ b/library/core/src/slice/sort/shared/pivot.rs @@ -1,6 +1,6 @@ //! This module contains the logic for pivot selection. -use crate::intrinsics; +use crate::{hint, intrinsics}; // Recursively select a pseudomedian if above this threshold. const PSEUDO_MEDIAN_REC_THRESHOLD: usize = 64; @@ -9,6 +9,7 @@ const PSEUDO_MEDIAN_REC_THRESHOLD: usize = 64; /// /// This chooses a pivot by sampling an adaptive amount of points, approximating /// the quality of a median of sqrt(n) elements. +#[inline] pub fn choose_pivot bool>(v: &[T], is_less: &mut F) -> usize { // We use unsafe code and raw pointers here because we're dealing with // heavy recursion. Passing safe slices around would involve a lot of @@ -22,7 +23,7 @@ pub fn choose_pivot bool>(v: &[T], is_less: &mut F) -> us // SAFETY: a, b, c point to initialized regions of len_div_8 elements, // satisfying median3 and median3_rec's preconditions as v_base points // to an initialized region of n = len elements. - unsafe { + let index = unsafe { let v_base = v.as_ptr(); let len_div_8 = len / 8; @@ -35,6 +36,11 @@ pub fn choose_pivot bool>(v: &[T], is_less: &mut F) -> us } else { median3_rec(a, b, c, len_div_8, is_less).offset_from_unsigned(v_base) } + }; + // SAFETY: preconditions must have been met for offset_from_unsigned() + unsafe { + hint::assert_unchecked(index < v.len()); + index } } diff --git a/library/core/src/slice/sort/stable/quicksort.rs b/library/core/src/slice/sort/stable/quicksort.rs index 3c9688790c4..0439ba870bd 100644 --- a/library/core/src/slice/sort/stable/quicksort.rs +++ b/library/core/src/slice/sort/stable/quicksort.rs @@ -37,10 +37,6 @@ pub fn quicksort bool>( limit -= 1; let pivot_pos = choose_pivot(v, is_less); - // SAFETY: choose_pivot promises to return a valid pivot index. - unsafe { - intrinsics::assume(pivot_pos < v.len()); - } // SAFETY: We only access the temporary copy for Freeze types, otherwise // self-modifications via `is_less` would not be observed and this would diff --git a/library/core/src/slice/sort/unstable/quicksort.rs b/library/core/src/slice/sort/unstable/quicksort.rs index 98efee242eb..bdf56a80803 100644 --- a/library/core/src/slice/sort/unstable/quicksort.rs +++ b/library/core/src/slice/sort/unstable/quicksort.rs @@ -48,8 +48,7 @@ pub(crate) fn quicksort<'a, T, F>( // slice. Partition the slice into elements equal to and elements greater than the pivot. // This case is usually hit when the slice contains many duplicate elements. if let Some(p) = ancestor_pivot { - // SAFETY: We assume choose_pivot yields an in-bounds position. - if !is_less(p, unsafe { v.get_unchecked(pivot_pos) }) { + if !is_less(p, &v[pivot_pos]) { let num_lt = partition(v, pivot_pos, &mut |a, b| !is_less(b, a)); // Continue sorting elements greater than the pivot. We know that `num_lt` contains -- cgit 1.4.1-3-g733a5 From 6237e735c4dc165b3efec236e11a44bdccf1dfd7 Mon Sep 17 00:00:00 2001 From: Esteban Küber Date: Mon, 21 Jul 2025 16:53:31 +0000 Subject: Point at the type that doesn't impl `Clone` in more cases beyond closures --- compiler/rustc_borrowck/src/diagnostics/move_errors.rs | 15 +++++---------- .../async-closures/closure-shim-borrowck-error.stderr | 7 +++---- .../ui/async-await/async-closures/move-out-of-ref.stderr | 5 ++++- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 67dce7615c0..a0c1f66d35c 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -596,9 +596,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { self.add_move_error_details(err, &binds_to); } // No binding. Nothing to suggest. - GroupedMoveError::OtherIllegalMove { - ref original_path, use_spans, ref kind, .. - } => { + GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => { let mut use_span = use_spans.var_or_use(); let place_ty = original_path.ty(self.body, self.infcx.tcx).ty; let place_desc = match self.describe_place(original_path.as_ref()) { @@ -616,14 +614,11 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { ); } - if let IllegalMoveOriginKind::BorrowedContent { target_place } = &kind - && let ty = target_place.ty(self.body, self.infcx.tcx).ty - && let ty::Closure(def_id, _) = ty.kind() - && def_id.as_local() == Some(self.mir_def_id()) - && let Some(upvar_field) = self - .prefixes(original_path.as_ref(), PrefixSet::All) - .find_map(|p| self.is_upvar_field_projection(p)) + if let Some(upvar_field) = self + .prefixes(original_path.as_ref(), PrefixSet::All) + .find_map(|p| self.is_upvar_field_projection(p)) { + // Look for the introduction of the original binding being moved. let upvar = &self.upvars[upvar_field.index()]; let upvar_hir_id = upvar.get_root_variable(); use_span = match self.infcx.tcx.parent_hir_node(upvar_hir_id) { diff --git a/tests/ui/async-await/async-closures/closure-shim-borrowck-error.stderr b/tests/ui/async-await/async-closures/closure-shim-borrowck-error.stderr index 03fa220b0bf..3fe1431fda7 100644 --- a/tests/ui/async-await/async-closures/closure-shim-borrowck-error.stderr +++ b/tests/ui/async-await/async-closures/closure-shim-borrowck-error.stderr @@ -1,14 +1,13 @@ error[E0507]: cannot move out of `x` which is behind a mutable reference --> $DIR/closure-shim-borrowck-error.rs:11:18 | +LL | fn hello(x: Ty) { + | -- move occurs because `x` has type `Ty`, which does not implement the `Copy` trait LL | needs_fn_mut(async || { | ^^^^^^^^ `x` is moved here LL | LL | x.hello(); - | - - | | - | variable moved due to use in coroutine - | move occurs because `x` has type `Ty`, which does not implement the `Copy` trait + | - variable moved due to use in coroutine | note: if `Ty` implemented `Clone`, you could clone the value --> $DIR/closure-shim-borrowck-error.rs:17:1 diff --git a/tests/ui/async-await/async-closures/move-out-of-ref.stderr b/tests/ui/async-await/async-closures/move-out-of-ref.stderr index 8a63515a8a9..d443dc9d483 100644 --- a/tests/ui/async-await/async-closures/move-out-of-ref.stderr +++ b/tests/ui/async-await/async-closures/move-out-of-ref.stderr @@ -1,8 +1,11 @@ error[E0507]: cannot move out of `*x` which is behind a shared reference --> $DIR/move-out-of-ref.rs:9:9 | +LL | fn hello(x: &Ty) { + | --- move occurs because `*x` has type `Ty`, which does not implement the `Copy` trait +LL | let c = async || { LL | *x; - | ^^ move occurs because `*x` has type `Ty`, which does not implement the `Copy` trait + | ^^ `*x` is moved here | note: if `Ty` implemented `Clone`, you could clone the value --> $DIR/move-out-of-ref.rs:5:1 -- cgit 1.4.1-3-g733a5 From a93a9aa2d57564660b2c28e5c1cdda7943989f17 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 20 Jul 2025 00:17:22 -0700 Subject: Don't emit two `assume`s in transmutes when one is a subset of the other For example, transmuting between `bool` and `Ordering` doesn't need two `assume`s because one range is a superset of the other. Multiple are still used for things like `char` <-> `NonZero`, which overlap but where neither fully contains the other. --- compiler/rustc_abi/src/lib.rs | 22 ++++++++ compiler/rustc_abi/src/tests.rs | 63 +++++++++++++++++++++++ compiler/rustc_codegen_ssa/src/mir/rvalue.rs | 28 ++++++++-- tests/codegen-llvm/intrinsics/transmute-niched.rs | 49 +++++++++++++++--- 4 files changed, 150 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 5bd73502d98..8e346706877 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1376,6 +1376,28 @@ impl WrappingRange { } } + /// Returns `true` if all the values in `other` are contained in this range, + /// when the values are considered as having width `size`. + #[inline(always)] + pub fn contains_range(&self, other: Self, size: Size) -> bool { + if self.is_full_for(size) { + true + } else { + let trunc = |x| size.truncate(x); + + let delta = self.start; + let max = trunc(self.end.wrapping_sub(delta)); + + let other_start = trunc(other.start.wrapping_sub(delta)); + let other_end = trunc(other.end.wrapping_sub(delta)); + + // Having shifted both input ranges by `delta`, now we only need to check + // whether `0..=max` contains `other_start..=other_end`, which can only + // happen if the other doesn't wrap since `self` isn't everything. + (other_start <= other_end) && (other_end <= max) + } + } + /// Returns `self` with replaced `start` #[inline(always)] fn with_start(mut self, start: u128) -> Self { diff --git a/compiler/rustc_abi/src/tests.rs b/compiler/rustc_abi/src/tests.rs index d993012378c..d49c2d44af8 100644 --- a/compiler/rustc_abi/src/tests.rs +++ b/compiler/rustc_abi/src/tests.rs @@ -5,3 +5,66 @@ fn align_constants() { assert_eq!(Align::ONE, Align::from_bytes(1).unwrap()); assert_eq!(Align::EIGHT, Align::from_bytes(8).unwrap()); } + +#[test] +fn wrapping_range_contains_range() { + let size16 = Size::from_bytes(16); + + let a = WrappingRange { start: 10, end: 20 }; + assert!(a.contains_range(a, size16)); + assert!(a.contains_range(WrappingRange { start: 11, end: 19 }, size16)); + assert!(a.contains_range(WrappingRange { start: 10, end: 10 }, size16)); + assert!(a.contains_range(WrappingRange { start: 20, end: 20 }, size16)); + assert!(!a.contains_range(WrappingRange { start: 10, end: 21 }, size16)); + assert!(!a.contains_range(WrappingRange { start: 9, end: 20 }, size16)); + assert!(!a.contains_range(WrappingRange { start: 4, end: 6 }, size16)); + assert!(!a.contains_range(WrappingRange { start: 24, end: 26 }, size16)); + + assert!(!a.contains_range(WrappingRange { start: 16, end: 14 }, size16)); + + let b = WrappingRange { start: 20, end: 10 }; + assert!(b.contains_range(b, size16)); + assert!(b.contains_range(WrappingRange { start: 20, end: 20 }, size16)); + assert!(b.contains_range(WrappingRange { start: 10, end: 10 }, size16)); + assert!(b.contains_range(WrappingRange { start: 0, end: 10 }, size16)); + assert!(b.contains_range(WrappingRange { start: 20, end: 30 }, size16)); + assert!(b.contains_range(WrappingRange { start: 20, end: 9 }, size16)); + assert!(b.contains_range(WrappingRange { start: 21, end: 10 }, size16)); + assert!(b.contains_range(WrappingRange { start: 999, end: 9999 }, size16)); + assert!(b.contains_range(WrappingRange { start: 999, end: 9 }, size16)); + assert!(!b.contains_range(WrappingRange { start: 19, end: 19 }, size16)); + assert!(!b.contains_range(WrappingRange { start: 11, end: 11 }, size16)); + assert!(!b.contains_range(WrappingRange { start: 19, end: 11 }, size16)); + assert!(!b.contains_range(WrappingRange { start: 11, end: 19 }, size16)); + + let f = WrappingRange { start: 0, end: u128::MAX }; + assert!(f.contains_range(WrappingRange { start: 10, end: 20 }, size16)); + assert!(f.contains_range(WrappingRange { start: 20, end: 10 }, size16)); + + let g = WrappingRange { start: 2, end: 1 }; + assert!(g.contains_range(WrappingRange { start: 10, end: 20 }, size16)); + assert!(g.contains_range(WrappingRange { start: 20, end: 10 }, size16)); + + let size1 = Size::from_bytes(1); + let u8r = WrappingRange { start: 0, end: 255 }; + let i8r = WrappingRange { start: 128, end: 127 }; + assert!(u8r.contains_range(i8r, size1)); + assert!(i8r.contains_range(u8r, size1)); + assert!(!u8r.contains_range(i8r, size16)); + assert!(i8r.contains_range(u8r, size16)); + + let boolr = WrappingRange { start: 0, end: 1 }; + assert!(u8r.contains_range(boolr, size1)); + assert!(i8r.contains_range(boolr, size1)); + assert!(!boolr.contains_range(u8r, size1)); + assert!(!boolr.contains_range(i8r, size1)); + + let cmpr = WrappingRange { start: 255, end: 1 }; + assert!(u8r.contains_range(cmpr, size1)); + assert!(i8r.contains_range(cmpr, size1)); + assert!(!cmpr.contains_range(u8r, size1)); + assert!(!cmpr.contains_range(i8r, size1)); + + assert!(!boolr.contains_range(cmpr, size1)); + assert!(cmpr.contains_range(boolr, size1)); +} diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 610e2fd2311..a5759b79be4 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -288,7 +288,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // valid ranges. For example, `char`s are passed as just `i32`, with no // way for LLVM to know that they're 0x10FFFF at most. Thus we assume // the range of the input value too, not just the output range. - assume_scalar_range(bx, imm, from_scalar, from_backend_ty); + assume_scalar_range(bx, imm, from_scalar, from_backend_ty, None); imm = match (from_scalar.primitive(), to_scalar.primitive()) { (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed), @@ -1064,7 +1064,7 @@ pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( // That said, last time we tried removing this, it didn't actually help // the rustc-perf results, so might as well keep doing it // - assume_scalar_range(bx, imm, from_scalar, from_backend_ty); + assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar)); imm = match (from_scalar.primitive(), to_scalar.primitive()) { (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty), @@ -1092,22 +1092,42 @@ pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( // since it's never passed to something with parameter metadata (especially // after MIR inlining) so the only way to tell the backend about the // constraint that the `transmute` introduced is to `assume` it. - assume_scalar_range(bx, imm, to_scalar, to_backend_ty); + assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar)); imm = bx.to_immediate_scalar(imm, to_scalar); imm } +/// Emits an `assume` call that `imm`'s value is within the known range of `scalar`. +/// +/// If `known` is `Some`, only emits the assume if it's more specific than +/// whatever is already known from the range of *that* scalar. fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx: &mut Bx, imm: Bx::Value, scalar: abi::Scalar, backend_ty: Bx::Type, + known: Option<&abi::Scalar>, ) { - if matches!(bx.cx().sess().opts.optimize, OptLevel::No) || scalar.is_always_valid(bx.cx()) { + if matches!(bx.cx().sess().opts.optimize, OptLevel::No) { return; } + match (scalar, known) { + (abi::Scalar::Union { .. }, _) => return, + (_, None) => { + if scalar.is_always_valid(bx.cx()) { + return; + } + } + (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => { + let known_range = known.valid_range(bx.cx()); + if valid_range.contains_range(known_range, scalar.size(bx.cx())) { + return; + } + } + } + match scalar.primitive() { abi::Primitive::Int(..) => { let range = scalar.valid_range(bx.cx()); diff --git a/tests/codegen-llvm/intrinsics/transmute-niched.rs b/tests/codegen-llvm/intrinsics/transmute-niched.rs index 8ff5cc8ee4f..a886d9eee59 100644 --- a/tests/codegen-llvm/intrinsics/transmute-niched.rs +++ b/tests/codegen-llvm/intrinsics/transmute-niched.rs @@ -163,11 +163,8 @@ pub unsafe fn check_swap_pair(x: (char, NonZero)) -> (NonZero, char) { pub unsafe fn check_bool_from_ordering(x: std::cmp::Ordering) -> bool { // CHECK-NOT: icmp // CHECK-NOT: assume - // OPT: %0 = sub i8 %x, -1 - // OPT: %1 = icmp ule i8 %0, 2 - // OPT: call void @llvm.assume(i1 %1) - // OPT: %2 = icmp ule i8 %x, 1 - // OPT: call void @llvm.assume(i1 %2) + // OPT: %0 = icmp ule i8 %x, 1 + // OPT: call void @llvm.assume(i1 %0) // CHECK-NOT: icmp // CHECK-NOT: assume // CHECK: %[[R:.+]] = trunc{{( nuw)?}} i8 %x to i1 @@ -184,9 +181,6 @@ pub unsafe fn check_bool_to_ordering(x: bool) -> std::cmp::Ordering { // CHECK-NOT: assume // OPT: %0 = icmp ule i8 %_0, 1 // OPT: call void @llvm.assume(i1 %0) - // OPT: %1 = sub i8 %_0, -1 - // OPT: %2 = icmp ule i8 %1, 2 - // OPT: call void @llvm.assume(i1 %2) // CHECK-NOT: icmp // CHECK-NOT: assume // CHECK: ret i8 %_0 @@ -221,3 +215,42 @@ pub unsafe fn check_ptr_to_nonnull(x: *const u8) -> NonNull { transmute(x) } + +#[repr(usize)] +pub enum FourOrEight { + Four = 4, + Eight = 8, +} + +// CHECK-LABEL: @check_nonnull_to_four_or_eight( +#[no_mangle] +pub unsafe fn check_nonnull_to_four_or_eight(x: NonNull) -> FourOrEight { + // CHECK: start + // CHECK-NEXT: %[[RET:.+]] = ptrtoint ptr %x to i64 + // CHECK-NOT: icmp + // CHECK-NOT: assume + // OPT: %0 = sub i64 %[[RET]], 4 + // OPT: %1 = icmp ule i64 %0, 4 + // OPT: call void @llvm.assume(i1 %1) + // CHECK-NOT: icmp + // CHECK-NOT: assume + // CHECK: ret i64 %[[RET]] + + transmute(x) +} + +// CHECK-LABEL: @check_four_or_eight_to_nonnull( +#[no_mangle] +pub unsafe fn check_four_or_eight_to_nonnull(x: FourOrEight) -> NonNull { + // CHECK-NOT: icmp + // CHECK-NOT: assume + // OPT: %0 = sub i64 %x, 4 + // OPT: %1 = icmp ule i64 %0, 4 + // OPT: call void @llvm.assume(i1 %1) + // CHECK-NOT: icmp + // CHECK-NOT: assume + // CHECK: %[[RET:.+]] = getelementptr i8, ptr null, i64 %x + // CHECK-NEXT: ret ptr %[[RET]] + + transmute(x) +} -- cgit 1.4.1-3-g733a5 From e44a7386c27f821515804fa90ed39ca1e931f8de Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Thu, 24 Jul 2025 08:15:03 +0000 Subject: Remove dead code and extend test coverage and diagnostics around it We lost the following comment during refactorings: The current code for niche-filling relies on variant indices instead of actual discriminants, so enums with explicit discriminants (RFC 2363) would misbehave. --- compiler/rustc_abi/src/layout.rs | 12 ++----- compiler/rustc_hir_analysis/src/check/check.rs | 38 +++++++++++++++++----- compiler/rustc_ty_utils/src/layout.rs | 8 ----- .../rust-analyzer/crates/hir-ty/src/layout/adt.rs | 16 ++------- .../arbitrary_enum_discriminant-no-repr.rs | 19 ++++++++--- .../arbitrary_enum_discriminant-no-repr.stderr | 20 ++++++++++-- 6 files changed, 65 insertions(+), 48 deletions(-) diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 80b44e432ee..716bb716cdb 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -313,7 +313,6 @@ impl LayoutCalculator { scalar_valid_range: (Bound, Bound), discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool), discriminants: impl Iterator, - dont_niche_optimize_enum: bool, always_sized: bool, ) -> LayoutCalculatorResult { let (present_first, present_second) = { @@ -352,13 +351,7 @@ impl LayoutCalculator { // structs. (We have also handled univariant enums // that allow representation optimization.) assert!(is_enum); - self.layout_of_enum( - repr, - variants, - discr_range_of_repr, - discriminants, - dont_niche_optimize_enum, - ) + self.layout_of_enum(repr, variants, discr_range_of_repr, discriminants) } } @@ -599,7 +592,6 @@ impl LayoutCalculator { variants: &IndexSlice>, discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool), discriminants: impl Iterator, - dont_niche_optimize_enum: bool, ) -> LayoutCalculatorResult { // Until we've decided whether to use the tagged or // niche filling LayoutData, we don't want to intern the @@ -618,7 +610,7 @@ impl LayoutCalculator { } let calculate_niche_filling_layout = || -> Option> { - if dont_niche_optimize_enum { + if repr.inhibit_enum_layout_opt() { return None; } diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 03c026cd6c8..bb1de5bcfc3 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -1642,20 +1642,40 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) { if def.repr().int.is_none() { let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const)); - let has_disr = |var: &ty::VariantDef| matches!(var.discr, ty::VariantDiscr::Explicit(_)); + let get_disr = |var: &ty::VariantDef| match var.discr { + ty::VariantDiscr::Explicit(disr) => Some(disr), + ty::VariantDiscr::Relative(_) => None, + }; - let has_non_units = def.variants().iter().any(|var| !is_unit(var)); - let disr_units = def.variants().iter().any(|var| is_unit(var) && has_disr(var)); - let disr_non_unit = def.variants().iter().any(|var| !is_unit(var) && has_disr(var)); + let non_unit = def.variants().iter().find(|var| !is_unit(var)); + let disr_unit = + def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var)); + let disr_non_unit = + def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var)); - if disr_non_unit || (disr_units && has_non_units) { - struct_span_code_err!( + if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) { + let mut err = struct_span_code_err!( tcx.dcx(), tcx.def_span(def_id), E0732, - "`#[repr(inttype)]` must be specified" - ) - .emit(); + "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants" + ); + if let Some(disr_non_unit) = disr_non_unit { + err.span_label( + tcx.def_span(disr_non_unit), + "explicit discriminant on non-unit variant specified here", + ); + } else { + err.span_label( + tcx.def_span(disr_unit.unwrap()), + "explicit discriminant specified here", + ); + err.span_label( + tcx.def_span(non_unit.unwrap().def_id), + "non-unit discriminant declared here", + ); + } + err.emit(); } } diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 163e2b30883..79f7e228e2a 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -603,12 +603,6 @@ fn layout_of_uncached<'tcx>( .flatten() }; - let dont_niche_optimize_enum = def.repr().inhibit_enum_layout_opt() - || def - .variants() - .iter_enumerated() - .any(|(i, v)| v.discr != ty::VariantDiscr::Relative(i.as_u32())); - let maybe_unsized = def.is_struct() && def.non_enum_variant().tail_opt().is_some_and(|last_field| { let typing_env = ty::TypingEnv::post_analysis(tcx, def.did()); @@ -625,7 +619,6 @@ fn layout_of_uncached<'tcx>( tcx.layout_scalar_valid_range(def.did()), get_discriminant_type, discriminants_iter(), - dont_niche_optimize_enum, !maybe_unsized, ) .map_err(|err| map_error(cx, ty, err))?; @@ -651,7 +644,6 @@ fn layout_of_uncached<'tcx>( tcx.layout_scalar_valid_range(def.did()), get_discriminant_type, discriminants_iter(), - dont_niche_optimize_enum, !maybe_unsized, ) else { bug!("failed to compute unsized layout of {ty:?}"); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/layout/adt.rs b/src/tools/rust-analyzer/crates/hir-ty/src/layout/adt.rs index 236f316366d..372a9dfc43d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/layout/adt.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/layout/adt.rs @@ -3,9 +3,9 @@ use std::{cmp, ops::Bound}; use hir_def::{ - AdtId, VariantId, layout::{Integer, ReprOptions, TargetDataLayout}, signatures::{StructFlags, VariantFields}, + AdtId, VariantId, }; use intern::sym; use rustc_index::IndexVec; @@ -13,9 +13,9 @@ use smallvec::SmallVec; use triomphe::Arc; use crate::{ - Substitution, TraitEnvironment, db::HirDatabase, - layout::{Layout, LayoutError, field_ty}, + layout::{field_ty, Layout, LayoutError}, + Substitution, TraitEnvironment, }; use super::LayoutCx; @@ -85,16 +85,6 @@ pub fn layout_of_adt_query( let d = db.const_eval_discriminant(e.enum_variants(db).variants[id.0].0).ok()?; Some((id, d)) }), - // FIXME: The current code for niche-filling relies on variant indices - // instead of actual discriminants, so enums with - // explicit discriminants (RFC #2363) would misbehave and we should disable - // niche optimization for them. - // The code that do it in rustc: - // repr.inhibit_enum_layout_opt() || def - // .variants() - // .iter_enumerated() - // .any(|(i, v)| v.discr != ty::VariantDiscr::Relative(i.as_u32())) - repr.inhibit_enum_layout_opt(), !matches!(def, AdtId::EnumId(..)) && variants .iter() diff --git a/tests/ui/enum-discriminant/arbitrary_enum_discriminant-no-repr.rs b/tests/ui/enum-discriminant/arbitrary_enum_discriminant-no-repr.rs index a6e5f70fdef..6bbafbf1434 100644 --- a/tests/ui/enum-discriminant/arbitrary_enum_discriminant-no-repr.rs +++ b/tests/ui/enum-discriminant/arbitrary_enum_discriminant-no-repr.rs @@ -1,8 +1,17 @@ -#![crate_type="lib"] +#![crate_type = "lib"] +// Test that if any variant is non-unit, +// we need a repr. enum Enum { -//~^ ERROR `#[repr(inttype)]` must be specified - Unit = 1, - Tuple() = 2, - Struct{} = 3, + //~^ ERROR `#[repr(inttype)]` must be specified + Unit = 1, + Tuple(), + Struct {}, +} + +// Test that if any non-unit variant has an explicit +// discriminant we need a repr. +enum Enum2 { + //~^ ERROR `#[repr(inttype)]` must be specified + Tuple() = 2, } diff --git a/tests/ui/enum-discriminant/arbitrary_enum_discriminant-no-repr.stderr b/tests/ui/enum-discriminant/arbitrary_enum_discriminant-no-repr.stderr index 3b718c6465b..35c0208951a 100644 --- a/tests/ui/enum-discriminant/arbitrary_enum_discriminant-no-repr.stderr +++ b/tests/ui/enum-discriminant/arbitrary_enum_discriminant-no-repr.stderr @@ -1,9 +1,23 @@ -error[E0732]: `#[repr(inttype)]` must be specified - --> $DIR/arbitrary_enum_discriminant-no-repr.rs:3:1 +error[E0732]: `#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants + --> $DIR/arbitrary_enum_discriminant-no-repr.rs:5:1 | LL | enum Enum { | ^^^^^^^^^ +LL | +LL | Unit = 1, + | - explicit discriminant specified here +LL | Tuple(), + | ----- non-unit discriminant declared here -error: aborting due to 1 previous error +error[E0732]: `#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants + --> $DIR/arbitrary_enum_discriminant-no-repr.rs:14:1 + | +LL | enum Enum2 { + | ^^^^^^^^^^ +LL | +LL | Tuple() = 2, + | - explicit discriminant on non-unit variant specified here + +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0732`. -- cgit 1.4.1-3-g733a5 From 642deb3c8f88073b8417a067e8de6b4dc5b84a6a Mon Sep 17 00:00:00 2001 From: Makai Date: Thu, 24 Jul 2025 18:26:08 +0800 Subject: remove movability from `RigidTy::Coroutine` and `AggregateKind::Coroutine` --- compiler/rustc_public/src/mir/body.rs | 7 ++----- compiler/rustc_public/src/mir/pretty.rs | 2 +- compiler/rustc_public/src/ty.rs | 7 +++---- compiler/rustc_public/src/unstable/convert/internal.rs | 2 +- compiler/rustc_public/src/unstable/convert/stable/mir.rs | 1 - compiler/rustc_public/src/unstable/convert/stable/ty.rs | 1 - compiler/rustc_public/src/visitor.rs | 2 +- 7 files changed, 8 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_public/src/mir/body.rs b/compiler/rustc_public/src/mir/body.rs index 3320b98cd61..3d595286041 100644 --- a/compiler/rustc_public/src/mir/body.rs +++ b/compiler/rustc_public/src/mir/body.rs @@ -654,9 +654,7 @@ impl Rvalue { )), AggregateKind::Adt(def, _, ref args, _, _) => Ok(def.ty_with_args(args)), AggregateKind::Closure(def, ref args) => Ok(Ty::new_closure(def, args.clone())), - AggregateKind::Coroutine(def, ref args, mov) => { - Ok(Ty::new_coroutine(def, args.clone(), mov)) - } + AggregateKind::Coroutine(def, ref args) => Ok(Ty::new_coroutine(def, args.clone())), AggregateKind::CoroutineClosure(def, ref args) => { Ok(Ty::new_coroutine_closure(def, args.clone())) } @@ -674,8 +672,7 @@ pub enum AggregateKind { Tuple, Adt(AdtDef, VariantIdx, GenericArgs, Option, Option), Closure(ClosureDef, GenericArgs), - // FIXME(rustc_public): Movability here is redundant - Coroutine(CoroutineDef, GenericArgs, Movability), + Coroutine(CoroutineDef, GenericArgs), CoroutineClosure(CoroutineClosureDef, GenericArgs), RawPtr(Ty, Mutability), } diff --git a/compiler/rustc_public/src/mir/pretty.rs b/compiler/rustc_public/src/mir/pretty.rs index a433df2dba1..3183c020772 100644 --- a/compiler/rustc_public/src/mir/pretty.rs +++ b/compiler/rustc_public/src/mir/pretty.rs @@ -428,7 +428,7 @@ fn pretty_aggregate( write!(writer, "{{closure@{}}}(", def.span().diagnostic())?; ")" } - AggregateKind::Coroutine(def, _, _) => { + AggregateKind::Coroutine(def, _) => { write!(writer, "{{coroutine@{}}}(", def.span().diagnostic())?; ")" } diff --git a/compiler/rustc_public/src/ty.rs b/compiler/rustc_public/src/ty.rs index bc67a2f987d..de4b21b1764 100644 --- a/compiler/rustc_public/src/ty.rs +++ b/compiler/rustc_public/src/ty.rs @@ -60,8 +60,8 @@ impl Ty { } /// Create a new coroutine type. - pub fn new_coroutine(def: CoroutineDef, args: GenericArgs, mov: Movability) -> Ty { - Ty::from_rigid_kind(RigidTy::Coroutine(def, args, mov)) + pub fn new_coroutine(def: CoroutineDef, args: GenericArgs) -> Ty { + Ty::from_rigid_kind(RigidTy::Coroutine(def, args)) } /// Create a new closure type. @@ -560,8 +560,7 @@ pub enum RigidTy { FnDef(FnDef, GenericArgs), FnPtr(PolyFnSig), Closure(ClosureDef, GenericArgs), - // FIXME(rustc_public): Movability here is redundant - Coroutine(CoroutineDef, GenericArgs, Movability), + Coroutine(CoroutineDef, GenericArgs), CoroutineClosure(CoroutineClosureDef, GenericArgs), Dynamic(Vec>, Region, DynKind), Never, diff --git a/compiler/rustc_public/src/unstable/convert/internal.rs b/compiler/rustc_public/src/unstable/convert/internal.rs index b2d38e497bc..66f767a98f5 100644 --- a/compiler/rustc_public/src/unstable/convert/internal.rs +++ b/compiler/rustc_public/src/unstable/convert/internal.rs @@ -177,7 +177,7 @@ impl RustcInternal for RigidTy { RigidTy::Closure(def, args) => { rustc_ty::TyKind::Closure(def.0.internal(tables, tcx), args.internal(tables, tcx)) } - RigidTy::Coroutine(def, args, _mov) => { + RigidTy::Coroutine(def, args) => { rustc_ty::TyKind::Coroutine(def.0.internal(tables, tcx), args.internal(tables, tcx)) } RigidTy::CoroutineClosure(def, args) => rustc_ty::TyKind::CoroutineClosure( diff --git a/compiler/rustc_public/src/unstable/convert/stable/mir.rs b/compiler/rustc_public/src/unstable/convert/stable/mir.rs index 8dee579e598..be8ee80bed3 100644 --- a/compiler/rustc_public/src/unstable/convert/stable/mir.rs +++ b/compiler/rustc_public/src/unstable/convert/stable/mir.rs @@ -653,7 +653,6 @@ impl<'tcx> Stable<'tcx> for mir::AggregateKind<'tcx> { crate::mir::AggregateKind::Coroutine( tables.coroutine_def(*def_id), generic_arg.stable(tables, cx), - cx.coroutine_movability(*def_id).stable(tables, cx), ) } mir::AggregateKind::CoroutineClosure(def_id, generic_args) => { diff --git a/compiler/rustc_public/src/unstable/convert/stable/ty.rs b/compiler/rustc_public/src/unstable/convert/stable/ty.rs index d679615b3bd..5a661072bc7 100644 --- a/compiler/rustc_public/src/unstable/convert/stable/ty.rs +++ b/compiler/rustc_public/src/unstable/convert/stable/ty.rs @@ -457,7 +457,6 @@ impl<'tcx> Stable<'tcx> for ty::TyKind<'tcx> { ty::Coroutine(def_id, generic_args) => TyKind::RigidTy(RigidTy::Coroutine( tables.coroutine_def(*def_id), generic_args.stable(tables, cx), - cx.coroutine_movability(*def_id).stable(tables, cx), )), ty::Never => TyKind::RigidTy(RigidTy::Never), ty::Tuple(fields) => TyKind::RigidTy(RigidTy::Tuple( diff --git a/compiler/rustc_public/src/visitor.rs b/compiler/rustc_public/src/visitor.rs index 45e2a815470..87f1cc6ae69 100644 --- a/compiler/rustc_public/src/visitor.rs +++ b/compiler/rustc_public/src/visitor.rs @@ -166,7 +166,7 @@ impl Visitable for RigidTy { } RigidTy::Adt(_, args) | RigidTy::Closure(_, args) - | RigidTy::Coroutine(_, args, _) + | RigidTy::Coroutine(_, args) | RigidTy::CoroutineWitness(_, args) | RigidTy::CoroutineClosure(_, args) | RigidTy::FnDef(_, args) => args.visit(visitor), -- cgit 1.4.1-3-g733a5 From 9ffa77523284d9301a2dacdf0e1064844d640592 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Tue, 22 Jul 2025 23:13:09 +0300 Subject: resolve: Remove `Scope::CrateRoot` Use `Scope::Module` with the crate root module inside instead, which should be identical. --- compiler/rustc_resolve/src/diagnostics.rs | 5 --- compiler/rustc_resolve/src/ident.rs | 72 +++++++++++++------------------ compiler/rustc_resolve/src/imports.rs | 8 ++-- compiler/rustc_resolve/src/lib.rs | 11 ++--- 4 files changed, 39 insertions(+), 57 deletions(-) diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index d72fbc189e7..75eed1e9ad3 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1076,11 +1076,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } } } - Scope::CrateRoot => { - let root_ident = Ident::new(kw::PathRoot, ident.span); - let root_module = this.resolve_crate_root(root_ident); - this.add_module_candidates(root_module, &mut suggestions, filter_fn, None); - } Scope::Module(module, _) => { this.add_module_candidates(module, &mut suggestions, filter_fn, None); } diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index 34941398a2b..71cc68af499 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -93,20 +93,21 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { // 6. Language prelude: builtin attributes (closed, controlled). let rust_2015 = ctxt.edition().is_rust_2015(); - let (ns, macro_kind, is_absolute_path) = match scope_set { - ScopeSet::All(ns) => (ns, None, false), - ScopeSet::AbsolutePath(ns) => (ns, None, true), - ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false), - ScopeSet::Late(ns, ..) => (ns, None, false), + let (ns, macro_kind) = match scope_set { + ScopeSet::All(ns) + | ScopeSet::ModuleAndExternPrelude(ns, _) + | ScopeSet::Late(ns, ..) => (ns, None), + ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)), }; let module = match scope_set { // Start with the specified module. - ScopeSet::Late(_, module, _) => module, + ScopeSet::Late(_, module, _) | ScopeSet::ModuleAndExternPrelude(_, module) => module, // Jump out of trait or enum modules, they do not act as scopes. _ => parent_scope.module.nearest_item_scope(), }; + let module_and_extern_prelude = matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..)); let mut scope = match ns { - _ if is_absolute_path => Scope::CrateRoot, + _ if module_and_extern_prelude => Scope::Module(module, None), TypeNS | ValueNS => Scope::Module(module, None), MacroNS => Scope::DeriveHelpers(parent_scope.expansion), }; @@ -134,11 +135,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } true } - Scope::CrateRoot => true, Scope::Module(..) => true, Scope::MacroUsePrelude => use_prelude || rust_2015, Scope::BuiltinAttrs => true, - Scope::ExternPrelude => use_prelude || is_absolute_path, + Scope::ExternPrelude => use_prelude || module_and_extern_prelude, Scope::ToolPrelude => use_prelude, Scope::StdLibPrelude => use_prelude || ns == MacroNS, Scope::BuiltinTypes => true, @@ -174,7 +174,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } MacroRulesScope::Empty => Scope::Module(module, None), }, - Scope::CrateRoot => match ns { + Scope::Module(..) if module_and_extern_prelude => match ns { TypeNS => { ctxt.adjust(ExpnId::root()); Scope::ExternPrelude @@ -203,7 +203,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } Scope::MacroUsePrelude => Scope::StdLibPrelude, Scope::BuiltinAttrs => break, // nowhere else to search - Scope::ExternPrelude if is_absolute_path => break, + Scope::ExternPrelude if module_and_extern_prelude => break, Scope::ExternPrelude => Scope::ToolPrelude, Scope::ToolPrelude => Scope::StdLibPrelude, Scope::StdLibPrelude => match ns { @@ -404,10 +404,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } let (ns, macro_kind) = match scope_set { - ScopeSet::All(ns) => (ns, None), - ScopeSet::AbsolutePath(ns) => (ns, None), + ScopeSet::All(ns) + | ScopeSet::ModuleAndExternPrelude(ns, _) + | ScopeSet::Late(ns, ..) => (ns, None), ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)), - ScopeSet::Late(ns, ..) => (ns, None), }; // This is *the* result, resolution from the scope closest to the resolved identifier. @@ -487,31 +487,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined), _ => Err(Determinacy::Determined), }, - Scope::CrateRoot => { - let root_ident = Ident::new(kw::PathRoot, ident.span); - let root_module = this.resolve_crate_root(root_ident); - let binding = this.resolve_ident_in_module( - ModuleOrUniformRoot::Module(root_module), - ident, - ns, - parent_scope, - finalize, - ignore_binding, - ignore_import, - ); - match binding { - Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)), - Err((Determinacy::Undetermined, Weak::No)) => { - return Some(Err(Determinacy::determined(force))); - } - Err((Determinacy::Undetermined, Weak::Yes)) => { - Err(Determinacy::Undetermined) - } - Err((Determinacy::Determined, _)) => Err(Determinacy::Determined), - } - } Scope::Module(module, derive_fallback_lint_id) => { - let adjusted_parent_scope = &ParentScope { module, ..*parent_scope }; + let (adjusted_parent_scope, finalize) = + if matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..)) { + (parent_scope, finalize) + } else { + ( + &ParentScope { module, ..*parent_scope }, + finalize.map(|f| Finalize { used: Used::Scope, ..f }), + ) + }; let binding = this.resolve_ident_in_module_unadjusted( ModuleOrUniformRoot::Module(module), ident, @@ -522,7 +507,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } else { Shadowing::Restricted }, - finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }), + finalize, ignore_binding, ignore_import, ); @@ -776,7 +761,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { ModuleOrUniformRoot::ExternPrelude => { ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root()); } - ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => { + ModuleOrUniformRoot::ModuleAndExternPrelude(..) | ModuleOrUniformRoot::CurrentScope => { // No adjustments } } @@ -810,11 +795,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { ) -> Result, (Determinacy, Weak)> { let module = match module { ModuleOrUniformRoot::Module(module) => module, - ModuleOrUniformRoot::CrateRootAndExternPrelude => { + ModuleOrUniformRoot::ModuleAndExternPrelude(module) => { assert_eq!(shadowing, Shadowing::Unrestricted); let binding = self.early_resolve_ident_in_lexical_scope( ident, - ScopeSet::AbsolutePath(ns), + ScopeSet::ModuleAndExternPrelude(ns, module), parent_scope, finalize, finalize.is_some(), @@ -1531,7 +1516,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { && self.tcx.sess.at_least_rust_2018() { // `::a::b` from 2015 macro on 2018 global edition - module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude); + let crate_root = self.resolve_crate_root(ident); + module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root)); continue; } if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate { diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 783c5005cca..986e703c0d2 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -181,10 +181,10 @@ pub(crate) struct ImportData<'ra> { /// /// | `module_path` | `imported_module` | remark | /// |-|-|-| - /// |`use prefix::foo`| `ModuleOrUniformRoot::Module(prefix)` | - | - /// |`use ::foo` | `ModuleOrUniformRoot::ExternPrelude` | 2018+ editions | - /// |`use ::foo` | `ModuleOrUniformRoot::CrateRootAndExternPrelude` | a special case in 2015 edition | - /// |`use foo` | `ModuleOrUniformRoot::CurrentScope` | - | + /// |`use prefix::foo`| `ModuleOrUniformRoot::Module(prefix)` | - | + /// |`use ::foo` | `ModuleOrUniformRoot::ExternPrelude` | 2018+ editions | + /// |`use ::foo` | `ModuleOrUniformRoot::ModuleAndExternPrelude` | a special case in 2015 edition | + /// |`use foo` | `ModuleOrUniformRoot::CurrentScope` | - | pub imported_module: Cell>>, pub vis: Visibility, } diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 08f1f61ea86..27e14e0e62b 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -119,7 +119,6 @@ enum Scope<'ra> { DeriveHelpers(LocalExpnId), DeriveHelpersCompat, MacroRules(MacroRulesScopeRef<'ra>), - CrateRoot, // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK` // lint if it should be reported. Module(Module<'ra>, Option), @@ -139,8 +138,8 @@ enum Scope<'ra> { enum ScopeSet<'ra> { /// All scopes with the given namespace. All(Namespace), - /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros). - AbsolutePath(Namespace), + /// A module, then extern prelude (used for mixed 2015-2018 mode in macros). + ModuleAndExternPrelude(Namespace, Module<'ra>), /// All scopes with macro namespace and the given macro kind restriction. Macro(MacroKind), /// All scopes with the given namespace, used for partially performing late resolution. @@ -419,8 +418,10 @@ enum ModuleOrUniformRoot<'ra> { /// Regular module. Module(Module<'ra>), - /// Virtual module that denotes resolution in crate root with fallback to extern prelude. - CrateRootAndExternPrelude, + /// Virtual module that denotes resolution in a module with fallback to extern prelude. + /// Used for paths starting with `::` coming from 2015 edition macros + /// used in 2018+ edition crates. + ModuleAndExternPrelude(Module<'ra>), /// Virtual module that denotes resolution in extern prelude. /// Used for paths starting with `::` on 2018 edition. -- cgit 1.4.1-3-g733a5 From 94c0cf891e4427083072b9050b89dd0332a616ae Mon Sep 17 00:00:00 2001 From: Oneirical Date: Tue, 22 Jul 2025 21:42:50 -0400 Subject: Rename tests/ui/SUMMARY.md and update rustc dev guide on error-pattern --- src/doc/rustc-dev-guide/src/tests/ui.md | 8 +- tests/ui/README.md | 1592 +++++++++++++++++++++++++++++++ tests/ui/SUMMARY.md | 1592 ------------------------------- 3 files changed, 1596 insertions(+), 1596 deletions(-) create mode 100644 tests/ui/README.md delete mode 100644 tests/ui/SUMMARY.md diff --git a/src/doc/rustc-dev-guide/src/tests/ui.md b/src/doc/rustc-dev-guide/src/tests/ui.md index 9bfc60e08a6..b1feef9ed0c 100644 --- a/src/doc/rustc-dev-guide/src/tests/ui.md +++ b/src/doc/rustc-dev-guide/src/tests/ui.md @@ -309,7 +309,8 @@ fn main((ؼ Use `//~?` to match an error without line information. `//~?` is precise and will not match errors if their line information is available. -It should be preferred to using `error-pattern`, which is imprecise and non-exhaustive. +For tests wishing to match against compiler diagnostics, error annotations should +be preferred over //@ error-pattern, //@ error-pattern is imprecise and non-exhaustive. ```rust,ignore //@ compile-flags: --print yyyy @@ -347,8 +348,6 @@ fn main() { } ``` -Use of `error-pattern` is not recommended in general. - For strict testing of compile time output, try to use the line annotations `//~` as much as possible, including `//~?` annotations for diagnostics without spans. @@ -359,7 +358,8 @@ Some of the compiler messages can stay uncovered by annotations in this mode. For checking runtime output, `//@ check-run-results` may be preferable. -Only use `error-pattern` if none of the above works. +Only use `error-pattern` if none of the above works, such as when finding a +specific string pattern in a runtime panic output. Line annotations `//~` and `error-pattern` are compatible and can be used in the same test. diff --git a/tests/ui/README.md b/tests/ui/README.md new file mode 100644 index 00000000000..b635b6326fc --- /dev/null +++ b/tests/ui/README.md @@ -0,0 +1,1592 @@ +# UI Test Suite Categories + +This is a high-level summary of the organization of the UI test suite (`tests/ui/`). It is not intended to be *prescriptive*, but instead provide a quick survey of existing groupings. + +For now, only immediate subdirectories under `tests/ui/` are described, but these subdirectories can themselves include a `SUMMARY.md` to further describe their own organization and intent, should that be helpful. + +## `tests/ui/abi` + +These tests deal with *Application Binary Interfaces* (ABI), mostly relating to function name mangling (and the `#[no_mangle]` attribute), calling conventions, or compiler flags which affect ABI. + +Tests for unsupported ABIs can be made cross-platform by using the `extern "rust-invalid"` ABI, which is considered unsupported on every platform. + +## `tests/ui/allocator` + +These tests exercise `#![feature(allocator_api)]` and the `#[global_allocator]` attribute. + +See [Allocator traits and `std::heap` #32838](https://github.com/rust-lang/rust/issues/32838). + +## `tests/ui/alloc-error` + +These tests exercise alloc error handling. + +See . + +## `tests/ui/annotate-snippet` + +These tests exercise the [`annotate-snippets`]-based emitter implementation. + +[`annotate-snippets`] is an initiative to share the diagnostics emitting infrastructure between rustc and cargo to reduce duplicate maintenance effort and divergence. See about the initiative. + +[`annotate-snippets`]: https://github.com/rust-lang/annotate-snippets-rs + +## `tests/ui/anon-params` + +These tests deal with anonymous parameters (no name, only type), a deprecated feature that becomes a hard error in Edition 2018. + +## `tests/ui/argfile`: External files providing command line arguments + +These tests exercise rustc reading command line arguments from an externally provided argfile (`@argsfile`). + +See [Implement `@argsfile` to read arguments from command line #63576](https://github.com/rust-lang/rust/issues/63576). + +## `tests/ui/array-slice-vec`: Arrays, slices and vectors + +Exercises various aspects surrounding basic collection types `[]`, `&[]` and `Vec`. E.g. type-checking, out-of-bounds indices, attempted instructions which are allowed in other programming languages, and more. + +## `tests/ui/argument-suggestions`: Argument suggestions + +Calling a function with the wrong number of arguments causes a compilation failure, but the compiler is able to, in some cases, provide suggestions on how to fix the error, such as which arguments to add or delete. These tests exercise the quality of such diagnostics. + +## `tests/ui/asm`: `asm!` macro + +These tests exercise the `asm!` macro, which is used for adding inline assembly. + +See: + +- [Inline assembly | Reference](https://doc.rust-lang.org/reference/inline-assembly.html) +- [`core::arch::asm`](https://doc.rust-lang.org/core/arch/macro.asm.html) +- [`core::arch::global_asm`](https://doc.rust-lang.org/core/arch/macro.global_asm.html) + +This directory contains subdirectories representing various architectures such as `riscv` or `aarch64`. If a test is specifically related to an architecture's particularities, it should be placed within the appropriate subdirectory.Architecture-agnostic tests should be placed below `tests/ui/asm/` directly. + +## `tests/ui/associated-consts`: Associated Constants + +These tests exercise associated constants in traits and impls, on aspects such as definitions, usage, and type checking in associated contexts. + +## `tests/ui/associated-inherent-types`: Inherent Associated Types + +These tests cover associated types defined directly within inherent impls (not in traits). + +See [RFC 0195 Associated items - Inherent associated items](https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md#inherent-associated-items). + +## `tests/ui/associated-item`: Associated Items + +Tests for all kinds of associated items within traits and implementations. This directory serves as a catch-all for tests that don't fit the other more specific associated item directories. + +## `tests/ui/associated-type-bounds`: Associated Type Bounds + +These tests exercise associated type bounds, the feature that gives users a shorthand to express nested type bounds that would otherwise need to be expressed with nested `impl Trait` or broken into several `where` clauses. + +See: + +- [RFC 2289 Associated Type Bounds](https://rust-lang.github.io/rfcs/2289-associated-type-bounds.html) +- [Stabilize associated type bounds (RFC 2289) #122055](https://github.com/rust-lang/rust/pull/122055) + +## `tests/ui/associated-types`: Trait Associated Types + +Tests focused on associated types. If the associated type is not in a trait definition, it belongs in the `tests/ui/associated-inherent-types/` directory. Aspects exercised include e.g. default associated types, overriding defaults, and type inference. + +See [Associated Types | Reference](https://doc.rust-lang.org/reference/items/associated-items.html#associated-types). + +## `tests/ui/async-await`: Async/Await + +Tests for the async/await related features. E.g. async functions, await expressions, and their interaction with other language features. + +## `tests/ui/attributes`: Compiler Attributes + +Tests for language attributes and compiler attributes. E.g. built-in attributes like `#[derive(..)]`, `#[cfg(..)]`, and `#[repr(..)]`, or proc-macro attributes. See [Attributes | Reference](https://doc.rust-lang.org/reference/attributes.html). + +## `tests/ui/auto-traits`: Auto Traits + +There are built-in auto traits (`Send`, `Sync`, etc.) but it is possible to define more with the unstable keyword `auto` through `#![feature(auto_traits)]`. + +See [Tracking Issue for auto traits (`auto_traits`) -- formerly called opt-in built-in traits (`optin_builtin_traits`) #13231](https://github.com/rust-lang/rust/issues/13231). + +## `tests/ui/autodiff`: Automatic Differentiation + +The `#[autodiff]` macro supports automatic differentiation. + +See [Tracking Issue for autodiff #124509](https://github.com/rust-lang/rust/issues/124509). + +## `tests/ui/autoref-autoderef`: Automatic Referencing/Dereferencing + +Tests for automatic referencing and dereferencing behavior, such as automatically adding reference operations (`&` or `&mut`) to make a value match a method's receiver type. Sometimes abbreviated as "auto-ref" or "auto-deref". + +## `tests/ui/auxiliary/`: Auxiliary files for tests directly under `tests/ui`. + +This top-level `auxiliary` subdirectory contains support files for tests immediately under `tests/ui/`. + +**FIXME(#133895)**: tests immediately under `tests/ui/` should be rehomed to more suitable subdirectories, after which this subdirectory can be removed. + +## `tests/ui/backtrace/`: Backtraces + +Runtime panics and error handling generate backtraces to assist in debugging and diagnostics. + +## `tests/ui/bench/`: Benchmarks and performance + +This directory was originally meant to contain tests related to time complexity and benchmarking. + +However, only a single test was ever added to this category: https://github.com/rust-lang/rust/pull/32062 + +**FIXME**: It is also unclear what would happen were this test to "fail" - would it cause the test suite to remain stuck on this test for a much greater duration than normal? + +## `tests/ui/binding/`: Pattern Binding + +Tests for pattern binding in match expressions, let statements, and other binding contexts. E.g. binding modes and refutability. See [Patterns | Reference](https://doc.rust-lang.org/reference/patterns.html). + +## `tests/ui/binop/`: Binary operators + +Tests for binary operators (such as `==`, `&&` or `^`). E.g. overloading, type checking, and diagnostics for invalid operations. + +## `tests/ui/blind/`: `struct` or `mod` inside a `mod` having a duplicate identifier + +Tests exercising name resolution. + +**FIXME**: Probably move to `tests/ui/resolve/`. + +## `tests/ui/block-result/`: Block results and returning + +Tests for block expression results. E.g. specifying the correct return types, semicolon handling, type inference, and expression/statement differences (for example, the difference between `1` and `1;`). + +## `tests/ui/bootstrap/`: RUSTC_BOOTSTRAP environment variable + +Meta tests for stability mechanisms surrounding [`RUSTC_BOOTSTRAP`](https://doc.rust-lang.org/nightly/unstable-book/compiler-environment-variables/RUSTC_BOOTSTRAP.html), which is coordinated between `rustc` and the build system, `bootstrap`. + +## `tests/ui/borrowck/`: Borrow Checking + +Tests for borrow checking. E.g. lifetime analysis, borrowing rules, and diagnostics. + +## `tests/ui/box/`: Box Behavior + +Tests for `Box` smart pointer and `#![feature(box_patterns)]`. E.g. allocation, deref coercion, and edge cases in box pattern matching and placement. + +See: + +- [`std::box::Boxed`](https://doc.rust-lang.org/std/boxed/struct.Box.html) +- [Tracking issue for `box_patterns` feature #29641](https://github.com/rust-lang/rust/issues/29641) + +## `tests/ui/btreemap/`: B-Tree Maps + +Tests focused on `BTreeMap` collections and their compiler interactions. E.g. collection patterns, iterator behavior, and trait implementations specific to `BTreeMap`. See [`std::collections::BTreeMap`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html). + +## `tests/ui/builtin-superkinds/`: Built-in Trait Hierarchy Tests + +Tests for built-in trait hierarchy (Send, Sync, Sized, etc.) and their supertrait relationships. E.g. auto traits and marker trait constraints. + +See [RFC 3729: Hierarchy of Sized traits](https://github.com/rust-lang/rfcs/pull/3729). + +Defining custom auto traits with the `auto` keyword belongs to `tests/ui/auto-traits/` instead. + +## `tests/ui/cast/`: Type Casting + +Tests for type casting using the `as` operator. Includes tests for valid/invalid casts between primitive types, trait objects, and custom types. For example, check that trying to cast `i32` into `bool` results in a helpful error message. + +See [Type cast expressions | Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html). + +## `tests/ui/cfg/`: Configuration Attribute + +Tests for `#[cfg]` conditional compilation attribute. E.g. feature flags, target architectures, and other configuration predicates and options. + +See [Conditional compilation | Reference](https://doc.rust-lang.org/reference/conditional-compilation.html). + +## `tests/ui/check-cfg/`: Configuration Checks + +Tests for the `--check-cfg` compiler mechanism for checking cfg configurations, for `#[cfg(..)]` and `cfg!(..)`. + +See [Checking conditional configurations | The rustc book](https://doc.rust-lang.org/rustc/check-cfg.html). + +## `tests/ui/closure_context/`: Closure type inference in context + +Tests for closure type inference with respect to surrounding scopes, mostly quality of diagnostics. + +## `tests/ui/closure-expected-type/`: Closure type inference + +Tests targeted at how we deduce the types of closure arguments. This process is a result of some heuristics which take into account the *expected type* we have alongside the *actual types* that we get from inputs. + +**FIXME**: Appears to have significant overlap with `tests/ui/closure_context` and `tests/ui/functions-closures/closure-expected-type`. Needs further investigation. + +## `tests/ui/closures/`: General Closure Tests + +Any closure-focused tests that does not fit in the other more specific closure subdirectories belong here. E.g. syntax, `move`, lifetimes. + +## `tests/ui/cmse-nonsecure/`: `cmse-nonsecure` ABIs + +Tests for `extern "cmse-nonsecure-call"` and `extern "cmse-nonsecure-entry"` functions. Used specifically for the Armv8-M architecture, the former marks Secure functions with additional behaviours, such as adding a special symbol and constraining the number of parameters, while the latter alters function pointers to indicate they are non-secure and to handle them differently than usual. + +See: + +- [`cmse_nonsecure_entry` | The Unstable book](https://doc.rust-lang.org/nightly/unstable-book/language-features/cmse-nonsecure-entry.html) +- [`abi_cmse_nonsecure_call` | The Unstable book](https://doc.rust-lang.org/nightly/unstable-book/language-features/abi-cmse-nonsecure-call.html) + +## `tests/ui/codegen/`: Code Generation + +Tests that exercise code generation. E.g. codegen flags (starting with `-C` on the command line), LLVM IR output, optimizations (and the various `opt-level`s), and target-specific code generation (such as tests specific to `x86_64`). + +## `tests/ui/codemap_tests/`: Source Mapping + +Tests that exercise source code mapping. + +## `tests/ui/coercion/`: Type Coercion + +Tests for implicit type coercion behavior, where the types of some values are changed automatically when compatible depending on the context. E.g. automatic dereferencing or downgrading a `&mut` into a `&`. + +See [Type coercions | Reference](https://doc.rust-lang.org/reference/type-coercions.html). + +## `tests/ui/coherence/`: Trait Implementation Coherence + +Tests for trait coherence rules, which govern where trait implementations can be defined. E.g. orphan rule, and overlap checks. + +See [Coherence | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/coherence.html#coherence). + +## `tests/ui/coinduction/`: Coinductive Trait Resolution + +Tests for coinduction in trait solving which may involve infinite proof trees. + +See: + +- [Coinduction | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/solve/coinduction.html). +- [Inductive cycles | Chalk](https://rust-lang.github.io/chalk/book/recursive/inductive_cycles.html#inductive-cycles)/ + +This directory only contains one highly specific test. Other coinduction tests can be found down the deeply located `tests/ui/traits/next-solver/cycles/coinduction/` subdirectory. + +## `tests/ui/command/`: `std::process::Command` + +This directory is actually for the standard library [`std::process::Command`](https://doc.rust-lang.org/std/process/struct.Command.html) type, where some tests are too difficult or inconvenient to write as unit tests or integration tests within the standard library itself. + +**FIXME**: the test `command-line-diagnostics` seems to have been misplaced in this category. + +## `tests/ui/compare-method/`: Trait implementation and definition comparisons + +Some traits' implementation must be compared with their definition, checking for problems such as the implementation having stricter requirements (such as needing to implement `Copy`). + +This subdirectory is *not* intended comparison traits (`PartialEq`, `Eq`, `PartialOrd`, `Ord`). + +## `tests/ui/compiletest-self-test/`: compiletest "meta" tests + +Meta test suite of the test harness `compiletest` itself. + +## `tests/ui/conditional-compilation/`: Conditional Compilation + +Tests for `#[cfg]` attribute or `--cfg` flags, used to compile certain files or code blocks only if certain conditions are met (such as developing on a specific architecture). + +**FIXME**: There is significant overlap with `tests/ui/cfg`, which even contains a `tests/ui/cfg/conditional-compile.rs` test. Also investigate `tests/ui/check-cfg`. + +## `tests/ui/confuse-field-and-method/`: Field/Method Ambiguity + +If a developer tries to create a `struct` where one of the fields is a closure function, it becomes unclear whether `struct.field()` is accessing the field itself or trying to call the closure function within as a method. + +**FIXME**: does this really need to be its own immediate subdirectory? + +## `tests/ui/const-generics/`: Constant Generics + +Tests for const generics, allowing types to be parameterized by constant values. It is generally observed in the form `` after the `fn` or `struct` keywords. Includes tests for const expressions in generic contexts and associated type bounds. + +See: + +- [Tracking Issue for complex generic constants: `feature(generic_const_exprs)` #76560](https://github.com/rust-lang/rust/issues/76560) +- [Const generics | Reference](https://doc.rust-lang.org/reference/items/generics.html#const-generics) + +## `tests/ui/const_prop/`: Constant Propagation + +Tests exercising `ConstProp` mir-opt pass (mostly regression tests). See . + +## `tests/ui/const-ptr/`: Constant Pointers + +Tests exercise const raw pointers. E.g. pointer arithmetic, casting and dereferencing, always with a `const`. + +See: + +- [`std::primitive::pointer`](https://doc.rust-lang.org/std/primitive.pointer.html) +- [`std::ptr`](https://doc.rust-lang.org/std/ptr/index.html) +- [Pointer types | Reference](https://doc.rust-lang.org/reference/types/pointer.html) + +## `tests/ui/consts/`: General Constant Evaluation + +Anything to do with constants, which does not fit in the previous two `const` categories, goes here. This does not always imply use of the `const` keyword - other values considered constant, such as defining an enum variant as `enum Foo { Variant = 5 }` also counts. + +## `tests/ui/contracts/`: Contracts feature + +Tests exercising `#![feature(contracts)]`. + +See [Tracking Issue for Contracts #128044](https://github.com/rust-lang/rust/issues/128044). + +## `tests/ui/coroutine/`: Coroutines feature and `gen` blocks + +Tests for `#![feature(coroutines)]` and `gen` blocks, it belongs here. + +See: + +- [Coroutines | The Unstable book](https://doc.rust-lang.org/beta/unstable-book/language-features/coroutines.html) +- [RFC 3513 Gen blocks](https://rust-lang.github.io/rfcs/3513-gen-blocks.html) + +## `tests/ui/coverage-attr/`: `#[coverage]` attribute + +Tests for `#![feature(coverage_attribute)]`. See [Tracking issue for function attribute `#[coverage]`](https://github.com/rust-lang/rust/issues/84605). + +## `tests/ui/crate-loading/`: Crate Loading + +Tests for crate resolution and loading behavior, including `extern crate` declarations, `--extern` flags, or the `use` keyword. + +## `tests/ui/cross/`: Various tests related to the concept of "cross" + +**FIXME**: The unifying topic of these tests appears to be that their filenames begin with the word "cross". The similarities end there - one test is about "cross-borrowing" a `Box` into `&T`, while another is about a global trait used "across" files. Some of these terminology are really outdated and does not match the current terminology. Additionally, "cross" is also way too generic, it's easy to confuse with cross-compile. + +## `tests/ui/cross-crate/`: Cross-Crate Interaction + +Tests for behavior spanning multiple crates, including visibility rules, trait implementations, and type resolution across crate boundaries. + +## `tests/ui/custom_test_frameworks/` + +Tests for `#[bench]`, `#[test_case]` attributes and the `custom_test_frameworks` lang item. + +See [Tracking issue for eRFC 2318, Custom test frameworks #50297](https://github.com/rust-lang/rust/issues/50297). + +## `tests/ui/c-variadic/`: C Variadic Function + +Tests for FFI with C varargs (`va_list`). + +## `tests/ui/cycle-trait/`: Trait Cycle Detection + +Tests for detection and handling of cyclic trait dependencies. + +## `tests/ui/dataflow_const_prop/` + +Contains a single regression test for const prop in `SwitchInt` pass crashing when `ptr2int` transmute is involved. + +**FIXME**: A category with a single test. Maybe it would fit inside the category `const-prop` or some kind of `mir-opt` directory. + +## `tests/ui/debuginfo/` + +Tests for generation of debug information (DWARF, etc.) including variable locations, type information, and source line mapping. Also exercises `-C split-debuginfo` and `-C debuginfo`. + +## `tests/ui/definition-reachable/`: Definition Reachability + +Tests to check whether definitions are reachable. + +## `tests/ui/delegation/`: `#![feature(fn_delegation)]` + +Tests for `#![feature(fn_delegation)]`. See [Implement function delegation in rustc #3530](https://github.com/rust-lang/rfcs/pull/3530) for the proposed prototype experimentation. + +## `tests/ui/dep-graph/`: `-Z query-dep-graph` + +These tests use the unstable command line option `query-dep-graph` to examine the dependency graph of a Rust program, which is useful for debugging. + +## `tests/ui/deprecation/`: Deprecation Attribute + +Tests for `#[deprecated]` attribute and `deprecated_in_future` internal lint. + +## `tests/ui/deref-patterns/`: `#![feature(deref_patterns)]` and `#![feature(string_deref_patterns)]` + +Tests for `#![feature(deref_patterns)]` and `#![feature(string_deref_patterns)]`. See [Deref patterns | The Unstable book](https://doc.rust-lang.org/nightly/unstable-book/language-features/deref-patterns.html). + +**FIXME**: May have some overlap with `tests/ui/pattern/deref-patterns`. + +## `tests/ui/derived-errors/`: Derived Error Messages + +Tests for quality of diagnostics involving suppression of cascading errors in some cases to avoid overwhelming the user. + +## `tests/ui/derives/`: Derive Macro + +Tests for built-in derive macros (`Debug`, `Clone`, etc.) when used in conjunction with built-in `#[derive(..)]` attributes. + +## `tests/ui/deriving/`: Derive Macro + +**FIXME**: Coalesce with `tests/ui/derives`. + +## `tests/ui/dest-prop/` Destination Propagation + +**FIXME**: Contains a single test for the `DestProp` mir-opt, should probably be rehomed. + +## `tests/ui/destructuring-assignment/` + +Exercises destructuring assignments. See [RFC 2909 Destructuring assignment](https://github.com/rust-lang/rfcs/blob/master/text/2909-destructuring-assignment.md). + +## `tests/ui/diagnostic-flags/` + +These tests revolve around command-line flags which change the way error/warning diagnostics are emitted. For example, `--error-format=human --color=always`. + +**FIXME**: Check redundancy with `annotate-snippet`, which is another emitter. + +## `tests/ui/diagnostic_namespace/` + +Exercises `#[diagnostic::*]` namespaced attributes. See [RFC 3368 Diagnostic attribute namespace](https://github.com/rust-lang/rfcs/blob/master/text/3368-diagnostic-attribute-namespace.md). + +## `tests/ui/diagnostic-width/`: `--diagnostic-width` + +Everything to do with `--diagnostic-width`. + +## `tests/ui/did_you_mean/` + +Tests for miscellaneous suggestions. + +## `tests/ui/directory_ownership/`: Declaring `mod` inside a block + +Exercises diagnostics for when a code block attempts to gain ownership of a non-inline module with a `mod` keyword placed inside of it. + +## `tests/ui/disallowed-deconstructing/`: Incorrect struct deconstruction + +Exercises diagnostics for disallowed struct destructuring. + +## `tests/ui/dollar-crate/`: `$crate` used with the `use` keyword + +There are a few rules - which are checked in this directory - to follow when using `$crate` - it must be used in the start of a `use` line and is a reserved identifier. + +**FIXME**: There are a few other tests in other directories with a filename starting with `dollar-crate`. They should perhaps be redirected here. + +## `tests/ui/drop/`: `Drop` and drop order + +Not necessarily about `Drop` and its implementation, but also about the drop order of fields inside a struct. + +## `tests/ui/drop-bounds/` + +Tests for linting on bounding a generic type on `Drop`. + +## `tests/ui/dropck/`: Drop Checking + +Mostly about checking the validity of `Drop` implementations. + +See: + +- [Dropck | The Nomicon](https://doc.rust-lang.org/nomicon/dropck.html) +- [Drop check | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/borrow_check/drop_check.html) + +## `tests/ui/dst/`: Dynamically Sized Types + +Tests for dynamically-sized types (DSTs). See [Dynamically Sized Types | Reference](https://doc.rust-lang.org/reference/dynamically-sized-types.html). + +## `tests/ui/duplicate/`: Duplicate Symbols + +Tests about duplicated symbol names and associated errors, such as using the `#[export_name]` attribute to rename a function with the same name as another function. + +## `tests/ui/dynamically-sized-types/`: Dynamically Sized Types + +**FIXME**: should be coalesced with `tests/ui/dst`. + +## `tests/ui/dyn-compatibility/`: Dyn-compatibility + +Tests for dyn-compatibility of traits. + +See: + +- [Trait object | Reference](https://doc.rust-lang.org/reference/types/trait-object.html) +- [Dyn compatibility | Reference](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility) + +Previously known as "object safety". + +## `tests/ui/dyn-drop/`: `dyn Drop` + +**FIXME**: Contains a single test, used only to check the `dyn_drop` lint (which is normally `warn` level). + +## `tests/ui/dyn-keyword/`: `dyn` and Dynamic Dispatch + +The `dyn` keyword is used to highlight that calls to methods on the associated Trait are dynamically dispatched. To use the trait this way, it must be dyn-compatible - tests about dyn-compatibility belong in `tests/ui/dyn-compatibility/`, while more general tests on dynamic dispatch belong here. + +See [`dyn` keyword](https://doc.rust-lang.org/std/keyword.dyn.html). + +## `tests/ui/editions/`: Rust edition-specific peculiarities + +These tests run in specific Rust editions, such as Rust 2015 or Rust 2018, and check errors and functionality related to specific now-deprecated idioms and features. + +**FIXME**: Maybe regroup `rust-2018`, `rust-2021` and `rust-2024` under this umbrella? + +## `tests/ui/empty/`: Various tests related to the concept of "empty" + +**FIXME**: These tests need better homes, this is not very informative. + +## `tests/ui/entry-point/`: `main` function + +Tests exercising the `main` entry-point. + +## `tests/ui/enum/` + +General-purpose tests on `enum`s. See [Enumerations | Reference](https://doc.rust-lang.org/reference/items/enumerations.html). + +## `tests/ui/enum-discriminant/` + +`enum` variants can be differentiated independently of their potential field contents with `discriminant`, which returns the type `Discriminant`. See [`std::mem::discriminant`](https://doc.rust-lang.org/std/mem/fn.discriminant.html). + +## `tests/ui/env-macro/`: `env!` + +Exercises `env!` and `option_env!` macros. + +## `tests/ui/ergonomic-clones/` + +See [RFC 3680 Ergonomic clones](https://github.com/rust-lang/rfcs/pull/3680). + +## `tests/ui/error-codes/`: Error codes + +Tests for errors with dedicated error codes. + +## `tests/ui/error-emitter/` + +Quite similar to `ui/diagnostic-flags` in some of its tests, this category checks some behaviours of Rust's error emitter into the user's terminal window, such as truncating error in the case of an excessive amount of them. + +## `tests/ui/errors/` + +These tests are about very different topics, only unified by the fact that they result in errors. + +**FIXME**: "Errors" is way too generic, the tests probably need to be rehomed into more descriptive subdirectories. + +## `tests/ui/explain/`: `rustc --explain EXXXX` + +Accompanies `tests/ui/error-codes/`, exercises the `--explain` cli flag. + +## `tests/ui/explicit/`: Errors involving the concept of "explicit" + +This category contains three tests: two which are about the specific error `explicit use of destructor method`, and one which is about explicit annotation of lifetimes: https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime/explicit.html. + +**FIXME**: Rehome the two tests about the destructor method with `drop`-related categories, and rehome the last test with a category related to lifetimes. + +## `tests/ui/explicit-tail-calls/` + +Exercises `#![feature(explicit_tail_calls)]` and the `become` keyword. See [Explicit Tail Calls #3407](https://github.com/rust-lang/rfcs/pull/3407). + +## `tests/ui/expr/`: Expressions + +A broad directory for tests on expressions. + +## `tests/ui/extern/` + +Tests on the `extern` keyword and `extern` blocks and functions. + +## `tests/ui/extern-flag/`: `--extern` command line flag + +Tests for the `--extern` CLI flag. + +## `tests/ui/feature-gates/` + +Tests on feature-gating, and the `#![feature(..)]` mechanism itself. + +## `tests/ui/ffi-attrs/`: `#![feature(ffi_const, ffi_pure)]` + +The `#[ffi_const]` and `#[ffi_pure]` attributes applies clang's `const` and `pure` attributes to foreign functions declarations, respectively. These attributes are the core element of the tests in this category. + +See: + +- [`ffi_const` | The Unstable book](https://doc.rust-lang.org/unstable-book/language-features/ffi-const.html) +- [`ffi_pure` | The Unstable book](https://doc.rust-lang.org/beta/unstable-book/language-features/ffi-pure.html) + +## `tests/ui/fmt/` + +Exercises the `format!` macro. + +## `tests/ui/fn/` + +A broad category of tests on functions. + +## `tests/ui/fn-main/` + +**FIXME**: Serves a duplicate purpose with `ui/entry-point`, should be combined. + +## `tests/ui/for/`: `for` keyword + +Tests on the `for` keyword and some of its associated errors, such as attempting to write the faulty pattern `for _ in 0..1 {} else {}`. + +**FIXME**: Should be merged with `ui/for-loop-while`. + +## `tests/ui/force-inlining/`: `#[rustc_force_inline]` + +Tests for `#[rustc_force_inline]`, which will force a function to always be labelled as inline by the compiler (it will be inserted at the point of its call instead of being used as a normal function call.) If the compiler is unable to inline the function, an error will be reported. See . + +## `tests/ui/foreign/`: Foreign Function Interface (FFI) + +Tests for `extern "C"` and `extern "Rust`. + +**FIXME**: Check for potential overlap/merge with `ui/c-variadic` and/or `ui/extern`. + +## `tests/ui/for-loop-while/` + +Anything to do with loops and `for`, `loop` and `while` keywords to express them. + +**FIXME**: After `ui/for` is merged into this, also carry over its SUMMARY text. + +## `tests/ui/frontmatter/` + +Tests for `#![feature(frontmatter)]`. See [Tracking Issue for `frontmatter` #136889](https://github.com/rust-lang/rust/issues/136889). + +## `tests/ui/fully-qualified-type/` + +Tests for diagnostics when there may be identically named types that need further qualifications to disambiguate. + +## `tests/ui/functional-struct-update/` + +Functional Struct Update is the name for the idiom by which one can write `..` at the end of a struct literal expression to fill in all remaining fields of the struct literal by using `` as the source for them. + +See [RFC 0736 Privacy-respecting Functional Struct Update](https://github.com/rust-lang/rfcs/blob/master/text/0736-privacy-respecting-fru.md). + +## `tests/ui/function-pointer/` + +Tests on function pointers, such as testing their compatibility with higher-ranked trait bounds. + +See: + +- [Function pointer types | Reference](https://doc.rust-lang.org/reference/types/function-pointer.html) +- [Higher-ranked trait bounds | Nomicon](https://doc.rust-lang.org/nomicon/hrtb.html) + +## `tests/ui/functions-closures/` + +Tests on closures. See [Closure expressions | Reference](https://doc.rust-lang.org/reference/expressions/closure-expr.html). + +## `tests/ui/generic-associated-types/` + +Tests on Generic Associated Types (GATs). + +## `tests/ui/generic-const-items/` + +Tests for `#![feature(generic_const_items)]`. See [Tracking issue for generic const items #113521](https://github.com/rust-lang/rust/issues/113521). + +## `tests/ui/generics/` + +A broad category of tests on generics, usually used when no more specific subdirectories are fitting. + +## `tests/ui/half-open-range-patterns/`: `x..` or `..x` range patterns + +Tests on range patterns where one of the bounds is not a direct value. + +**FIXME**: Overlaps with `ui/range`. `impossible_range.rs` is particularly suspected to be a duplicate test. + +## `tests/ui/hashmap/` + +Tests for the standard library collection [`std::collections::HashMap`](https://doc.rust-lang.org/std/collections/struct.HashMap.html). + +## `tests/ui/hello_world/` + +Tests that the basic hello-world program is not somehow broken. + +## `tests/ui/higher-ranked/` + +Tests for higher-ranked trait bounds. + +See: + +- [Higher-ranked trait bounds | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/traits/hrtb.html) +- [Higher-ranked trait bounds | Nomicon](https://doc.rust-lang.org/nomicon/hrtb.html) + +## `tests/ui/hygiene/` + +This seems to have been originally intended for "hygienic macros" - macros which work in all contexts, independent of what surrounds them. However, this category has grown into a mish-mash of many tests that may belong in the other directories. + +**FIXME**: Reorganize this directory properly. + +## `tests/ui/illegal-sized-bound/` + +This test category revolves around trait objects with `Sized` having illegal operations performed on them. + +**FIXME**: There seems to be unrelated testing in this directory, such as `tests/ui/illegal-sized-bound/mutability-mismatch-arg.rs`. Investigate. + +## `tests/ui/impl-header-lifetime-elision/` + +Tests on lifetime elision in impl function signatures. See [Lifetime elision | Nomicon](https://doc.rust-lang.org/nomicon/lifetime-elision.html). + +## `tests/ui/implied-bounds/` + +See [Implied bounds | Reference](https://doc.rust-lang.org/reference/trait-bounds.html#implied-bounds). + +## `tests/ui/impl-trait/` + +Tests for trait impls. + +## `tests/ui/imports/` + +Tests for module system and imports. + +## `tests/ui/include-macros/` + +Exercise `include!`, `include_str!`, and `include_bytes!` macros. + +## `tests/ui/incoherent-inherent-impls/` + +Exercise forbidding inherent impls on a type defined in a different crate. + +## `tests/ui/indexing/` + +Tests on collection types (arrays, slices, vectors) and various errors encountered when indexing their contents, such as accessing out-of-bounds values. + +**FIXME**: (low-priority) could maybe be a subdirectory of `ui/array-slice-vec` + +## `tests/ui/inference/` + +Tests on type inference. + +## `tests/ui/infinite/` + +Tests for diagnostics on infinitely recursive types without indirection. + +## `tests/ui/inherent-impls-overlap-check/` + +Checks that repeating the same function names across separate `impl` blocks triggers an informative error, but not if the `impl` are for different types, such as `Bar` and `Bar`. + +NOTE: This should maybe be a subdirectory within another related to duplicate definitions, such as `tests/ui/duplicate/`. + +## `tests/ui/inline-const/` + +These tests revolve around the inline `const` block that forces the compiler to const-eval its content. + +## `tests/ui/instrument-coverage/`: `-Cinstrument-coverage` command line flag + +See [Instrument coverage | The rustc book](https://doc.rust-lang.org/rustc/instrument-coverage.html). + +## `tests/ui/instrument-xray/`: `-Z instrument-xray` + +See [Tracking issue for `-Z instrument-xray` #102921](https://github.com/rust-lang/rust/issues/102921). + +## `tests/ui/interior-mutability/` + +**FIXME**: contains a single test, probably better rehomed. + +## `tests/ui/internal/` + +Tests for `internal_unstable` and the attribute header `#![feature(allow_internal_unstable)]`, which lets compiler developers mark features as internal to the compiler, and unstable for standard library use. + +## `tests/ui/internal-lints/` + +Tests for rustc-internal lints. + +## `tests/ui/intrinsics/` + +Tests for the `{std,core}::intrinsics`, internal implementation detail. + +## `tests/ui/invalid/` + +Various tests related to rejecting invalid inputs. + +**FIXME**: This is rather uninformative, possibly rehome into more meaningful directories. + +## `tests/ui/invalid-compile-flags/` + +Tests for checking that invalid usage of compiler flags are rejected. + +## `tests/ui/invalid-module-declaration/` + +**FIXME**: Consider merging into module/resolve directories. + +## `tests/ui/invalid-self-argument/`: `self` as a function argument incorrectly + +Tests with erroneous ways of using `self`, such as having it not be the first argument, or using it in a non-associated function (no `impl` or `trait`). + +**FIXME**: Maybe merge with `ui/self`. + +## `tests/ui/io-checks/` + +Contains a single test. The test tries to output a file into an invalid directory with `-o`, then checks that the result is an error, not an internal compiler error. + +**FIXME**: Rehome to invalid compiler flags maybe. + +## `tests/ui/issues/`: Tests directly related to GitHub issues + +**FIXME (#133895)**: Random collection of regression tests and tests for issues, tests in this directory should be audited and rehomed. + +## `tests/ui/iterators/` + +These tests revolve around anything to do with iterators, e.g. mismatched types. + +**FIXME**: Check for potential overlap with `ui/for-loop-while`. + +## `tests/ui/json/` + +These tests revolve around the `--json` compiler flag. See [JSON Output](https://doc.rust-lang.org/rustc/json.html#json-output). + +## `tests/ui/keyword/` + +Tests exercising keywords, such as attempting to use them as identifiers when not contextual keywords. + +## `tests/ui/kindck/` + +**FIXME**: `kindck` is no longer a thing, these tests probably need to be audited and rehomed. + +## `tests/ui/label/` + +Exercises block and loop `'label`s. + +## `tests/ui/lang-items/` + +See [Lang items | The Unstable book](https://doc.rust-lang.org/unstable-book/language-features/lang-items.html). + +## `tests/ui/late-bound-lifetimes/` + +See [Early vs Late bound parameters | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/early_late_parameters.html#early-vs-late-bound-parameters). + +## `tests/ui/layout/` + +See [Type Layout | Reference](https://doc.rust-lang.org/reference/type-layout.html). + +## `tests/ui/lazy-type-alias/` + +Tests for `#![feature(lazy_type_alias)]`. See [Tracking issue for lazy type aliases #112792 +](https://github.com/rust-lang/rust/issues/112792). + +## `tests/ui/lazy-type-alias-impl-trait/` + +This feature allows use of an `impl Trait` in multiple locations while actually using the same concrete type (`type Alias = impl Trait;`) everywhere, keeping the original `impl Trait` hidden. + +**FIXME**: merge this with `tests/ui/type-alias-impl-trait/`? + +## `tests/ui/let-else/` + +Exercises let-else constructs. + +## `tests/ui/lexer/` + +Exercises of the lexer. + +## `tests/ui/lifetimes/` + +Broad directory on lifetimes, including proper specifiers, lifetimes not living long enough, or undeclared lifetime names. + +## `tests/ui/limits/` + +These tests exercises numerical limits, such as `[[u8; 1518599999]; 1518600000]`. + +## `tests/ui/linkage-attr/` + +Tests for the linkage attribute `#[linkage]` of `#![feature(linkage)]`. + +**FIXME**: Some of these tests do not use the feature at all, which should be moved under `ui/linking` instead. + +## `tests/ui/linking/` + +Tests on code which fails during the linking stage, or which contain arguments and lines that have been known to cause unjustified errors in the past, such as specifying an unusual `#[export_name]`. + +See [Linkage | Reference](https://doc.rust-lang.org/reference/linkage.html). + +## `tests/ui/link-native-libs/` + +Tests for `#[link(name = "", kind = "")]` and `-l` command line flag. + +See [Tracking Issue for linking modifiers for native libraries #81490](https://github.com/rust-lang/rust/issues/81490). + +## `tests/ui/lint/` + +Tests for the lint infrastructure, lint levels, lint reasons, etc. + +See: + +- [Lints | The rustc book](https://doc.rust-lang.org/rustc/lints/index.html) +- [Lint reasons | Reference](https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-reasons) + +## `tests/ui/liveness/` + +Tests exercising analysis for unused variables, unreachable statements, functions which are supposed to return a value but do not, as well as values moved elsewhere before they could be used by a function. + +**FIXME**: This seems unrelated to "liveness" as defined in the rustc compiler guide. Is this misleadingly named? https://rustc-dev-guide.rust-lang.org/borrow_check/region_inference/lifetime_parameters.html#liveness-and-universal-regions + +## `tests/ui/loops/` + +Tests on the `loop` construct. + +**FIXME**: Consider merging with `ui/for-loop-while`. + +## `tests/ui/lowering/` + +Tests on [AST lowering](https://rustc-dev-guide.rust-lang.org/ast-lowering.html). + +## `tests/ui/lto/` + +Exercise *Link-Time Optimization* (LTO), involving the flags `-C lto` or `-Z thinlto`. + +## `tests/ui/lub-glb/`: LUB/GLB algorithm update + +Tests on changes to inference variable lattice LUB/GLB, see . + +## `tests/ui/macro_backtrace/`: `-Zmacro-backtrace` + +Contains a single test, checking the unstable command-line flag to enable detailed macro backtraces. + +**FIXME**: This could be merged with `ui/macros`, which already contains other macro backtrace tests. + +## `tests/ui/macros/` + +Broad category of tests on macros. + +## `tests/ui/malformed/` + +Broad category of tests on malformed inputs. + +**FIXME**: this is kinda vague, probably best to audit and rehome tests. + +## `tests/ui/marker_trait_attr/` + +See [Tracking issue for allowing overlapping implementations for marker trait #29864](https://github.com/rust-lang/rust/issues/29864). + +## `tests/ui/match/` + +Broad category of tests on `match` constructs. + +## `tests/ui/meta/`: Tests for compiletest itself + +These tests check the function of the UI test suite at large and Compiletest in itself. + +**FIXME**: This should absolutely be merged with `tests/ui/compiletest-self-test/`. + +## `tests/ui/methods/` + +A broad category for anything related to methods and method resolution. + +## `tests/ui/mir/` + +Certain mir-opt regression tests. + +## `tests/ui/mir-dataflow` + +Tests for MIR dataflow analysis. + +See [MIR Dataflow | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/mir/dataflow.html). + +## `tests/ui/mismatched_types/` + +Exercises on mismatched type diagnostics. + +## `tests/ui/missing/` + +Something is missing which could be added to fix (e.g. suggestions). + +**FIXME**: this is way too vague, tests should be rehomed. + +## `tests/ui/missing_non_modrs_mod/` + +This directory is a small tree of `mod` dependencies, but the root, `foo.rs`, is looking for a file which does not exist. The test checks that the error is reported at the top-level module. + +**FIXME**: Merge with `tests/ui/modules/`. + +## `tests/ui/missing-trait-bounds/` + +Tests for checking missing trait bounds, and their diagnostics. + +**FIMXE**: Maybe a subdirectory of `ui/trait-bounds` would be more appropriate. + +## `tests/ui/modules/` + +Tests on the module system. + +**FIXME**: `tests/ui/imports/` should probably be merged with this. + +## `tests/ui/modules_and_files_visibility/` + +**FIXME**: Merge with `tests/ui/modules/`. + +## `tests/ui/moves` + +Tests on moves (destructive moves). + +## `tests/ui/mut/` + +Broad category of tests on mutability, such as the `mut` keyword, borrowing a value as both immutable and mutable (and the associated error), or adding mutable references to `const` declarations. + +## `tests/ui/namespace/` + +Contains a single test. It imports a massive amount of very similar types from a crate, then attempts various permutations of their namespace paths, checking for errors or the lackthereof. + +**FIXME**: Move under either `tests/ui/modules/` or `tests/ui/resolve/`. + +## `tests/ui/never_type/` + +See [Tracking issue for promoting `!` to a type (RFC 1216) #35121](https://github.com/rust-lang/rust/issues/35121). + +## `tests/ui/new-range/` + +See [RFC 3550 New Range](https://github.com/rust-lang/rfcs/blob/master/text/3550-new-range.md). + +## `tests/ui/nll/`: Non-lexical lifetimes + +Tests for Non-lexical lifetimes. See [RFC 2094 NLL](https://rust-lang.github.io/rfcs/2094-nll.html). + +## `tests/ui/non_modrs_mods/` + +Despite the size of the directory, this is a single test, spawning a sprawling `mod` dependency tree and checking its successful build. + +**FIXME**: Consider merge with `tests/ui/modules/`, keeping the directory structure. + +## `tests/ui/non_modrs_mods_and_inline_mods/` + +A very similar principle as `non_modrs_mods`, but with an added inline `mod` statement inside another `mod`'s code block. + +**FXIME**: Consider merge with `tests/ui/modules/`, keeping the directory structure. + +## `tests/ui/no_std/` + +Tests for where the standard library is disabled through `#![no_std]`. + +## `tests/ui/not-panic/` + +Tests checking various types, such as `&RefCell`, and whether they are not `UnwindSafe` as expected. + +## `tests/ui/numbers-arithmetic/` + +Tests that exercises edge cases, such as specific floats, large or very small numbers, or bit conversion, and check that the arithmetic results are as expected. + +## `tests/ui/numeric/` + +Tests that checks numeric types and their interactions, such as casting among them with `as` or providing the wrong numeric suffix. + +## `tests/ui/object-lifetime/` + +Tests on lifetimes on objects, such as a lifetime bound not being able to be deduced from context, or checking that lifetimes are inherited properly. + +**FIXME**: Just a more specific subset of `ui/lifetimes`. + +## `tests/ui/obsolete-in-place/` + +Contains a single test. Check that we reject the ancient Rust syntax `x <- y` and `in(BINDING) {}` construct. + +**FIXME**: Definitely should be rehomed, maybe to `tests/ui/deprecation/`. + +## `tests/ui/offset-of/` + +Exercises the [`std::mem::offset_of` macro](https://doc.rust-lang.org/beta/std/mem/macro.offset_of.html). + +## `tests/ui/on-unimplemented/` + +Exercises the `#[rustc_on_unimplemented]`. + +## `tests/ui/operator-recovery/` + +**FIXME**: Probably move under `tests/ui/binop/` or `tests/ui/parser/`. + +## `tests/ui/or-patterns/` + +Exercises `||` and `|` in patterns. + +## `tests/ui/overloaded/` + +Exercises operator overloading via [`std::ops`](https://doc.rust-lang.org/std/ops/index.html). + +## `tests/ui/packed/` + +See [`repr(packed)` | Nomicon](https://doc.rust-lang.org/nomicon/other-reprs.html#reprpacked-reprpackedn). + +## `tests/ui/panic-handler/` + +See [panic handler | Nomicon](https://doc.rust-lang.org/nomicon/panic-handler.html). + +## `tests/ui/panic-runtime/` + +Exercises `#![panic_runtime]`, `-C panic`, panic runtimes and panic unwind strategy. + +See [RFC 1513 Less unwinding](https://github.com/rust-lang/rfcs/blob/master/text/1513-less-unwinding.md). + +## `tests/ui/panics/` + +Broad category of tests about panics in general, often but not necessarily using the `panic!` macro. + +## `tests/ui/parallel-rustc/` + +Efforts towards a [Parallel Rustc Front-end](https://github.com/rust-lang/rust/issues/113349). Includes `-Zthreads=`. + +## `tests/ui/parser/` + +Various parser tests + +**FIXME**: Maybe move `tests/ui/keywords/` under this? + +## `tests/ui/patchable-function-entry/` + +See [Patchable function entry | The Unstable book](https://doc.rust-lang.org/unstable-book/compiler-flags/patchable-function-entry.html). + +## `tests/ui/pattern/` + +Broad category of tests surrounding patterns. See [Patterns | Reference](https://doc.rust-lang.org/reference/patterns.html). + +**FIXME**: Some overlap with `tests/ui/match/`. + +## `tests/ui/pin-macro/` + +See [`std::pin`](https://doc.rust-lang.org/std/pin/). + +## `tests/ui/precondition-checks/` + +Exercises on some unsafe precondition checks. + +## `tests/ui/print-request/` + +Tests on `--print` compiler flag. See [print options | The rustc book](https://doc.rust-lang.org/rustc/command-line-arguments/print-options.html). + +## `tests/ui/print_type_sizes/` + +Exercises the `-Z print-type-sizes` flag. + +## `tests/ui/privacy/` + +Exercises on name privacy. E.g. the meaning of `pub`, `pub(crate)`, etc. + +## `tests/ui/process/` + +Some standard library process tests which are hard to write within standard library crate tests. + +## `tests/ui/process-termination/` + +Some standard library process termination tests which are hard to write within standard library crate tests. + +## `tests/ui/proc-macro/` + +Broad category of tests on proc-macros. See [Procedural Macros | Reference](https://doc.rust-lang.org/reference/procedural-macros.html). + +## `tests/ui/ptr_ops/`: Using operations on a pointer + +Contains only 2 tests, related to a single issue, which was about an error caused by using addition on a pointer to `i8`. + +**FIXME**: Probably rehome under some typecheck / binop directory. + +## `tests/ui/pub/`: `pub` keyword + +A large category about function and type public/private visibility, and its impact when using features across crates. Checks both visibility-related error messages and previously buggy cases. + +**FIXME**: merge with `tests/ui/privacy/`. + +## `tests/ui/qualified/` + +Contains few tests on qualified paths where a type parameter is provided at the end: `type A = ::A::f;`. The tests check if this fails during type checking, not parsing. + +**FIXME**: Should be rehomed to `ui/typeck`. + +## `tests/ui/query-system/` + +Tests on Rust methods and functions which use the query system, such as `std::mem::size_of`. These compute information about the current runtime and return it. See [Query system | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/query.html). + +## `tests/ui/range/` + +Broad category of tests ranges, both in their `..` or `..=` form, as well as the standard library `Range`, `RangeTo`, `RangeFrom` or `RangeBounds` types. + +**FIXME**: May have some duplicate tests with `ui/new-range`. + +## `tests/ui/raw-ref-op/`: Using operators on `&raw` values + +Exercises `&raw mut ` and `&raw const `. See [RFC 2582 Raw reference MIR operator](https://github.com/rust-lang/rfcs/blob/master/text/2582-raw-reference-mir-operator.md). + +## `tests/ui/reachable` + +Reachability tests, primarily unreachable code and coercions into the never type `!` from diverging expressions. + +**FIXME**: Check for overlap with `ui/liveness`. + +## `tests/ui/recursion/` + +Broad category of tests exercising recursions (compile test and run time), in functions, macros, `type` definitions, and more. + +Also exercises the `#![recursion_limit = ""]` attribute. + +## `tests/ui/recursion_limit/`: `#![recursion_limit = ""]` + +Sets a recursion limit on recursive code. + +**FIXME**: Should be merged with `tests/ui/recursion/`. + +## `tests/ui/regions/` + +**FIXME**: Maybe merge with `ui/lifetimes`. + +## `tests/ui/repeat-expr/` + +Exercises `[Type; n]` syntax for creating arrays with repeated types across a set size. + +**FIXME**: Maybe make this a subdirectory of `ui/array-slice-vec`. + +## `tests/ui/repr/`: `#[repr(_)]` + +Tests on the `#[repr(..)]` attribute. See [Representations | Reference](https://doc.rust-lang.org/reference/type-layout.html#representations). + +## `tests/ui/reserved/` + +Reserved keywords and attribute names. + +See e.g. [Reserved keywords | Reference](https://doc.rust-lang.org/reference/keywords.html). + +**FIXME**: maybe merge under `tests/ui/keyword/`. + +## `tests/ui/resolve/`: Name resolution + +See [Name resolution | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/name-resolution.html). + +## `tests/ui/return/` + +Exercises the `return` keyword, return expressions and statements. + +## `tests/ui/rfcs/` + +Tests that accompanies an implementation for an RFC. + +## `tests/ui/rmeta/` + +Exercises `.rmeta` crate metadata and the `--emit=metadata` cli flag. + +## `tests/ui/runtime/` + +Tests for runtime environment on which Rust programs are executed. E.g. Unix `SIGPIPE`. + +## `tests/ui/rust-{2018,2021,2024}/` + +Tests that exercise behaviors and features that are specific to editions. + +## `tests/ui/rustc-env` + +Tests on environmental variables that affect `rustc`. + +## `tests/ui/rustdoc` + +Hybrid tests that exercises `rustdoc`, and also some joint `rustdoc`/`rustc` interactions. + +## `tests/ui/sanitizer/` + +Exercises sanitizer support. See [Sanitizer | The rustc book](https://doc.rust-lang.org/unstable-book/compiler-flags/sanitizer.html). + +## `tests/ui/self/`: `self` keyword + +Tests with erroneous ways of using `self`, such as using `this.x` syntax as seen in other languages, having it not be the first argument, or using it in a non-associated function (no `impl` or `trait`). It also contains correct uses of `self` which have previously been observed to cause ICEs. + +## `tests/ui/sepcomp/`: Separate Compilation + +In this directory, multiple crates are compiled, but some of them have `inline` functions, meaning they must be inlined into a different crate despite having been compiled separately. + +**FIXME**: this directory might need some better docs, also this directory might want a better name. + +## `tests/ui/shadowed/` + +Tests on name shadowing. + +## `tests/ui/shell-argfiles/`: `-Z shell-argfiles` command line flag + +The `-Zshell-argfiles` compiler flag allows argfiles to be parsed using POSIX "shell-style" quoting. When enabled, the compiler will use shlex to parse the arguments from argfiles specified with `@shell:`. + +Because this feature controls the parsing of input arguments, the `-Zshell-argfiles` flag must be present before the argument specifying the shell-style argument file. + +**FIXME**: maybe group this with `tests/ui/argfile/` + +## `tests/ui/simd/` + +Some tests exercising SIMD support. + +## `tests/ui/single-use-lifetime/` + +This is a test directory for the specific error case where a lifetime never gets used beyond a single annotation on, for example, a `struct`. + +## `tests/ui/sized/`: `Sized` trait, sized types + +While many tests here involve the `Sized` trait directly, some instead test, for example the slight variations between returning a zero-sized `Vec` and a `Vec` with one item, where one has no known type and the other does. + +## `tests/ui/span/` + +An assorted collection of tests that involves specific diagnostic spans. + +**FIXME**: This is a big directory with numerous only-tangentially related tests. Maybe some moving is in order. + +## `tests/ui/specialization` + +See [Tracking issue for specialization (RFC 1210) #31844](https://github.com/rust-lang/rust/issues/31844). + +## `tests/ui/stability-attribute/` + +Stability attributes used internally by the standard library: `#[stable()]` and `#[unstable()]`. + +## `tests/ui/rustc_public-ir-print/` + +Some tests for pretty printing of rustc_public's IR. + +## `tests/ui/stack-protector/`: `-Z stack-protector` command line flag + +See [Tracking Issue for stabilizing stack smashing protection (i.e., `-Z stack-protector`) #114903](https://github.com/rust-lang/rust/issues/114903). + +## `tests/ui/static/` + +Tests on static items. + +## `tests/ui/statics/` + +**FIXME**: should probably be merged with `tests/ui/static/`. + +## `tests/ui/stats/` + +Tests for compiler-internal stats; `-Z meta-stats` and `-Z input-stats` flags. + +## `tests/ui/std/`: Tests which use features from the standard library + +A catch-all category about anything that can come from `std`. + +**FIXME**: this directory is probably too vague, tests might need to be audited and rehomed. + +## `tests/ui/stdlib-unit-tests/` + +Some standard library tests which are too inconvenient or annoying to implement as std crate tests. + +## `tests/ui/str/` + +Exercise `str` keyword and string slices. + +## `tests/ui/structs/` + +Assorted tests surrounding the `struct` keyword, struct type definitions and usages. + +## `tests/ui/structs-enums/` + +Tests on both structs and enums. + +**FIXME**: maybe coalesce {`tests/ui/structs/`, `tests/ui/structs-enums/`, `tests/ui/enums/`} into one `tests/ui/adts` directory... + +## `tests/ui/suggestions/` + +Generic collection of tests for suggestions, when no more specific directories are applicable. + +**FIXME**: Some overlap with `tests/ui/did_you_mean/`, that directory should probably be moved under here. + +## `tests/ui/svh/`: Strict Version Hash + +Tests on the *Strict Version Hash* (SVH, also known as the "crate hash"). + +See [Strict Version Hash](https://rustc-dev-guide.rust-lang.org/backend/libs-and-metadata.html#strict-version-hash). + +## `tests/ui/symbol-mangling-version/`: `-Csymbol-mangling-version` command line flag + +**FIXME**: Should be merged with `ui/symbol-names`. + +## `tests/ui/symbol-names/`: Symbol mangling and related attributes + +These tests revolve around `#[no_mangle]` attribute, as well as consistently mangled symbol names (checked with the `rustc_symbol_name` attribute), which is important to build reproducible binaries. + +## `tests/ui/sync/`: `Sync` trait + +Exercises `Sync` trait and auto-derive thereof. + +## `tests/ui/target-cpu/`: `-C target-cpu` command line flag + +This command line option instructs rustc to generate code specifically for a particular processor. + +**FIXME**: Contains a single test, maybe put it in a directory about misc codegen options? + +## `tests/ui/target-feature/`: `#[target_feature(enable = "relaxed-simd")]` + +Exercises the `#[target_feature(..)]` attribute. See [Target feature attribute | Reference](https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute). + +## `tests/ui/target_modifiers/` + +Tests for [RFC 3716: Target Modifiers](https://github.com/rust-lang/rfcs/pull/3716). + +See [Tracking Issue for target modifiers #136966](https://github.com/rust-lang/rust/issues/136966). + +## `tests/ui/test-attrs/` + +Exercises the [`#[test]` attribute](https://doc.rust-lang.org/reference/attributes/testing.html#testing-attributes). + +## `tests/ui/thir-print/` + +Pretty print of THIR trees via `-Zunpretty=thir-tree`. + +## `tests/ui/thread-local/` + +Exercises thread local values and `#[thread_local]` attribute. + +See [Tracking issue for thread_local stabilization #29594](https://github.com/rust-lang/rust/issues/29594). + +## `tests/ui/threads-sendsync/` + +Broad category for parallelism and multi-threaded tests, including attempting to send types across threads which are not thread-safe. + +## `tests/ui/tool-attributes/`: External tool attributes + +Exercises [tool attributes](https://doc.rust-lang.org/reference/attributes.html#tool-attributes). + +## `tests/ui/track-diagnostics/` + +Exercises `#[track_caller]` and `-Z track-diagnostics`. + +## `tests/ui/trait-bounds/` + +Collection of tests for [trait bounds](https://doc.rust-lang.org/reference/trait-bounds.html). + +## `tests/ui/traits/` + +Broad collection of tests on traits in general. + +**FIXME**: This could be better organized in subdirectories containing tests such as `ui/traits/trait-bounds`. + +## `tests/ui/transmutability/`: `#![feature(transmutability)]` + +See [Tracking Issue for Transmutability Trait: `#[transmutability]` #99571](https://github.com/rust-lang/rust/issues/99571). + +See also [Project Safe Transmute](https://github.com/rust-lang/project-safe-transmute). + +## `tests/ui/transmute/` + +Tests surrounding [`std::mem::transmute`](https://doc.rust-lang.org/std/mem/fn.transmute.html). + +## `tests/ui/treat-err-as-bug/` + +Exercises compiler development support flag `-Z treat-err-as-bug`. + +## `tests/ui/trivial-bounds/` + +`#![feature(trivial_bounds)]`. See [RFC 2056 Allow trivial where clause constraints](https://github.com/rust-lang/rfcs/blob/master/text/2056-allow-trivial-where-clause-constraints.md). + +## `tests/ui/try-block/` + +`#![feature(try_blocks)]`. See [Tracking issue for `?` operator and `try` blocks (RFC 243, `question_mark` & `try_blocks` features)](https://github.com/rust-lang/rust/issues/31436). + +## `tests/ui/try-trait/` + +`#![feature(try_trait_v2)]`. See [RFC 3058 Try Trait v2](https://github.com/rust-lang/rfcs/blob/master/text/3058-try-trait-v2.md). + +## `tests/ui/tuple/` + +Tests surrounding the tuple type `()`. + +## `tests/ui/type/` + +Assorted collection of tests surrounding the concept of a "type". + +**FIXME**: There is very little consistency across tests of this category, and should probably be sent to other subdirectories. + +## `tests/ui/type-alias/` + +Exercises [type aliases](https://doc.rust-lang.org/reference/items/type-aliases.html). + +## `tests/ui/type-alias-enum-variants/` + +Tests for `type` aliases in the context of `enum` variants, such as that applied type arguments of enums are respected independently of being the original type or the `type` alias. + +## `tests/ui/type-alias-impl-trait/` + +`#![feature(type_alias_impl_trait)]`. See [Type Alias Impl Trait | The Unstable book](https://doc.rust-lang.org/nightly/unstable-book/language-features/type-alias-impl-trait.html). + +## `tests/ui/typeck/` + +General collection of type checking related tests. + +## `tests/ui/type-inference/` + +General collection of type inference related tests. + +## `tests/ui/typeof/` + +`typeof` keyword, reserved but unimplemented. + +## `tests/ui/ufcs/` + +See [RFC 0132 Unified Function Call Syntax](https://github.com/rust-lang/rfcs/blob/master/text/0132-ufcs.md). + +## `tests/ui/unboxed-closures/` + +`#![feature(unboxed_closures)]`, `Fn`, `FnMut` and `FnOnce` traits + +See [Tracking issue for Fn traits (`unboxed_closures` & `fn_traits` feature)](https://github.com/rust-lang/rust/issues/29625). + +## `tests/ui/underscore-imports/` + +See [Underscore imports | Reference](https://doc.rust-lang.org/reference/items/use-declarations.html#underscore-imports). + +**FIXME**: should become a subdirectory of `tests/ui/imports/`. + +## `tests/ui/underscore-lifetime/`: `'_` elided lifetime + +Exercises [anonymous elided lifetimes](https://doc.rust-lang.org/reference/lifetime-elision.html). + +## `tests/ui/uniform-paths/` + +In uniform paths, if a submodule and an external dependencies have the same name, to depend on the external dependency, one needs to disambiguate it from the submodule using `use ::foo`. Tests revolve around this, for example, check that `self::foo` and `::foo` are not considered ambiguously identical by the compiler. + +Remark: As they are an important Rust 2018 feature, they also get a big subdirectory in `ui/rust-2018/uniform-paths` + +## `tests/ui/uninhabited/`: Uninhabited types + +See [Uninhabited | Reference](https://doc.rust-lang.org/reference/glossary.html?highlight=Uninhabit#uninhabited). + +## `tests/ui/union/` + +See [Unions | Reference](https://doc.rust-lang.org/reference/items/unions.html). + +## `tests/ui/unknown-unstable-lints/`: Attempting to refer to an unstable lint which does not exist + +Tests for trying to use non-existent unstable lints. + +**FIXME**: move this under `tests/ui/lints/`. + +## `tests/ui/unop/`: Unary operators `-`, `*` and `!` + +Tests the three unary operators for negating, dereferencing and inverting, across different contexts. + +## `tests/ui/unpretty/`: `-Z unpretty` command line flag + +The `-Z unpretty` flag outputs various representations of a program's tree in a certain way. + +## `tests/ui/unresolved/` + +Exercises various unresolved errors, ranging from earlier name resolution failures to later method resolution failures. + +## `tests/ui/unsafe/` + +A broad category of tests about unsafe Rust code. + +## `tests/ui/unsafe-binders/`: `#![feature(unsafe_binders)]` + +See [Tracking issue for unsafe binder types #130516](https://github.com/rust-lang/rust/issues/130516). + +## `tests/ui/unsafe-fields/`: `struct`s and `enum`s with an `unsafe` field + +See [Tracking issue for RFC 3458: Unsafe fields #132922](https://github.com/rust-lang/rust/issues/132922). + +## `tests/ui/unsized/`: Zero-sized types, `Sized` trait, object has no known size at compile time + +**FIXME**: between `tests/ui/zero-sized/`, `tests/ui/sized/` and this directory, might need to reorganize them a bit. + +## `tests/ui/unsized-locals/`: `#![feature(unsized_locals, unsized_fn_params)]` + +See: + +- [RFC 1909 Unsized rvalues](https://github.com/rust-lang/rfcs/blob/master/text/1909-unsized-rvalues.md) +- [de-RFC 3829: Remove unsized_locals](https://github.com/rust-lang/rfcs/pull/3829) +- [Tracking issue for RFC #1909: Unsized Rvalues (`unsized_locals`, `unsized_fn_params`)](https://github.com/rust-lang/rust/issues/48055) + +**FIXME**: Seems to also contain more generic tests that fit in `tests/ui/unsized/`. + +## `tests/ui/unused-crate-deps/` + +Exercises the `unused_crate_dependencies` lint. + +## `tests/ui/unwind-abis/` + +**FIXME**: Contains a single test, should likely be rehomed to `tests/ui/abi/`. + +## `tests/ui/use/` + +**FIXME**: merge with `ui/imports`. + +## `tests/ui/variance/`: Covariants, invariants and contravariants + +See [Variance | Reference](https://doc.rust-lang.org/reference/subtyping.html#variance). + +## `tests/ui/variants/`: `enum` variants + +Tests on `enum` variants. + +**FIXME**: Should be rehomed with `tests/ui/enum/`. + +## `tests/ui/version/` + +**FIXME**: Contains a single test described as "Check that rustc accepts various version info flags.", should be rehomed. + +## `tests/ui/warnings/` + +**FIXME**: Contains a single test on non-explicit paths (`::one()`). Should be rehomed probably to `tests/ui/resolve/`. + +## `tests/ui/wasm/` + +These tests target the `wasm32` architecture specifically. They are usually regression tests for WASM-specific bugs which were observed in the past. + +## `tests/ui/wf/`: Well-formedness checking + +Tests on various well-formedness checks, e.g. [Type-checking normal functions](https://rustc-dev-guide.rust-lang.org/traits/lowering-to-logic.html). + +## `tests/ui/where-clauses/` + +Tests on `where` clauses. See [Where clauses | Reference](https://doc.rust-lang.org/reference/items/generics.html#where-clauses). + +## `tests/ui/while/` + +Tests on the `while` keyword and the `while` construct. + +**FIXME**: merge with `ui/for-loop-while`. + +## `tests/ui/windows-subsystem/`: `#![windows_subsystem = ""]` + +See [the `windows_subsystem` attribute](https://doc.rust-lang.org/reference/runtime.html#the-windows_subsystem-attribute). + +## `tests/ui/zero-sized/`: Zero-sized types + +See [Zero-Sized Types | Reference](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts). diff --git a/tests/ui/SUMMARY.md b/tests/ui/SUMMARY.md deleted file mode 100644 index b635b6326fc..00000000000 --- a/tests/ui/SUMMARY.md +++ /dev/null @@ -1,1592 +0,0 @@ -# UI Test Suite Categories - -This is a high-level summary of the organization of the UI test suite (`tests/ui/`). It is not intended to be *prescriptive*, but instead provide a quick survey of existing groupings. - -For now, only immediate subdirectories under `tests/ui/` are described, but these subdirectories can themselves include a `SUMMARY.md` to further describe their own organization and intent, should that be helpful. - -## `tests/ui/abi` - -These tests deal with *Application Binary Interfaces* (ABI), mostly relating to function name mangling (and the `#[no_mangle]` attribute), calling conventions, or compiler flags which affect ABI. - -Tests for unsupported ABIs can be made cross-platform by using the `extern "rust-invalid"` ABI, which is considered unsupported on every platform. - -## `tests/ui/allocator` - -These tests exercise `#![feature(allocator_api)]` and the `#[global_allocator]` attribute. - -See [Allocator traits and `std::heap` #32838](https://github.com/rust-lang/rust/issues/32838). - -## `tests/ui/alloc-error` - -These tests exercise alloc error handling. - -See . - -## `tests/ui/annotate-snippet` - -These tests exercise the [`annotate-snippets`]-based emitter implementation. - -[`annotate-snippets`] is an initiative to share the diagnostics emitting infrastructure between rustc and cargo to reduce duplicate maintenance effort and divergence. See about the initiative. - -[`annotate-snippets`]: https://github.com/rust-lang/annotate-snippets-rs - -## `tests/ui/anon-params` - -These tests deal with anonymous parameters (no name, only type), a deprecated feature that becomes a hard error in Edition 2018. - -## `tests/ui/argfile`: External files providing command line arguments - -These tests exercise rustc reading command line arguments from an externally provided argfile (`@argsfile`). - -See [Implement `@argsfile` to read arguments from command line #63576](https://github.com/rust-lang/rust/issues/63576). - -## `tests/ui/array-slice-vec`: Arrays, slices and vectors - -Exercises various aspects surrounding basic collection types `[]`, `&[]` and `Vec`. E.g. type-checking, out-of-bounds indices, attempted instructions which are allowed in other programming languages, and more. - -## `tests/ui/argument-suggestions`: Argument suggestions - -Calling a function with the wrong number of arguments causes a compilation failure, but the compiler is able to, in some cases, provide suggestions on how to fix the error, such as which arguments to add or delete. These tests exercise the quality of such diagnostics. - -## `tests/ui/asm`: `asm!` macro - -These tests exercise the `asm!` macro, which is used for adding inline assembly. - -See: - -- [Inline assembly | Reference](https://doc.rust-lang.org/reference/inline-assembly.html) -- [`core::arch::asm`](https://doc.rust-lang.org/core/arch/macro.asm.html) -- [`core::arch::global_asm`](https://doc.rust-lang.org/core/arch/macro.global_asm.html) - -This directory contains subdirectories representing various architectures such as `riscv` or `aarch64`. If a test is specifically related to an architecture's particularities, it should be placed within the appropriate subdirectory.Architecture-agnostic tests should be placed below `tests/ui/asm/` directly. - -## `tests/ui/associated-consts`: Associated Constants - -These tests exercise associated constants in traits and impls, on aspects such as definitions, usage, and type checking in associated contexts. - -## `tests/ui/associated-inherent-types`: Inherent Associated Types - -These tests cover associated types defined directly within inherent impls (not in traits). - -See [RFC 0195 Associated items - Inherent associated items](https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md#inherent-associated-items). - -## `tests/ui/associated-item`: Associated Items - -Tests for all kinds of associated items within traits and implementations. This directory serves as a catch-all for tests that don't fit the other more specific associated item directories. - -## `tests/ui/associated-type-bounds`: Associated Type Bounds - -These tests exercise associated type bounds, the feature that gives users a shorthand to express nested type bounds that would otherwise need to be expressed with nested `impl Trait` or broken into several `where` clauses. - -See: - -- [RFC 2289 Associated Type Bounds](https://rust-lang.github.io/rfcs/2289-associated-type-bounds.html) -- [Stabilize associated type bounds (RFC 2289) #122055](https://github.com/rust-lang/rust/pull/122055) - -## `tests/ui/associated-types`: Trait Associated Types - -Tests focused on associated types. If the associated type is not in a trait definition, it belongs in the `tests/ui/associated-inherent-types/` directory. Aspects exercised include e.g. default associated types, overriding defaults, and type inference. - -See [Associated Types | Reference](https://doc.rust-lang.org/reference/items/associated-items.html#associated-types). - -## `tests/ui/async-await`: Async/Await - -Tests for the async/await related features. E.g. async functions, await expressions, and their interaction with other language features. - -## `tests/ui/attributes`: Compiler Attributes - -Tests for language attributes and compiler attributes. E.g. built-in attributes like `#[derive(..)]`, `#[cfg(..)]`, and `#[repr(..)]`, or proc-macro attributes. See [Attributes | Reference](https://doc.rust-lang.org/reference/attributes.html). - -## `tests/ui/auto-traits`: Auto Traits - -There are built-in auto traits (`Send`, `Sync`, etc.) but it is possible to define more with the unstable keyword `auto` through `#![feature(auto_traits)]`. - -See [Tracking Issue for auto traits (`auto_traits`) -- formerly called opt-in built-in traits (`optin_builtin_traits`) #13231](https://github.com/rust-lang/rust/issues/13231). - -## `tests/ui/autodiff`: Automatic Differentiation - -The `#[autodiff]` macro supports automatic differentiation. - -See [Tracking Issue for autodiff #124509](https://github.com/rust-lang/rust/issues/124509). - -## `tests/ui/autoref-autoderef`: Automatic Referencing/Dereferencing - -Tests for automatic referencing and dereferencing behavior, such as automatically adding reference operations (`&` or `&mut`) to make a value match a method's receiver type. Sometimes abbreviated as "auto-ref" or "auto-deref". - -## `tests/ui/auxiliary/`: Auxiliary files for tests directly under `tests/ui`. - -This top-level `auxiliary` subdirectory contains support files for tests immediately under `tests/ui/`. - -**FIXME(#133895)**: tests immediately under `tests/ui/` should be rehomed to more suitable subdirectories, after which this subdirectory can be removed. - -## `tests/ui/backtrace/`: Backtraces - -Runtime panics and error handling generate backtraces to assist in debugging and diagnostics. - -## `tests/ui/bench/`: Benchmarks and performance - -This directory was originally meant to contain tests related to time complexity and benchmarking. - -However, only a single test was ever added to this category: https://github.com/rust-lang/rust/pull/32062 - -**FIXME**: It is also unclear what would happen were this test to "fail" - would it cause the test suite to remain stuck on this test for a much greater duration than normal? - -## `tests/ui/binding/`: Pattern Binding - -Tests for pattern binding in match expressions, let statements, and other binding contexts. E.g. binding modes and refutability. See [Patterns | Reference](https://doc.rust-lang.org/reference/patterns.html). - -## `tests/ui/binop/`: Binary operators - -Tests for binary operators (such as `==`, `&&` or `^`). E.g. overloading, type checking, and diagnostics for invalid operations. - -## `tests/ui/blind/`: `struct` or `mod` inside a `mod` having a duplicate identifier - -Tests exercising name resolution. - -**FIXME**: Probably move to `tests/ui/resolve/`. - -## `tests/ui/block-result/`: Block results and returning - -Tests for block expression results. E.g. specifying the correct return types, semicolon handling, type inference, and expression/statement differences (for example, the difference between `1` and `1;`). - -## `tests/ui/bootstrap/`: RUSTC_BOOTSTRAP environment variable - -Meta tests for stability mechanisms surrounding [`RUSTC_BOOTSTRAP`](https://doc.rust-lang.org/nightly/unstable-book/compiler-environment-variables/RUSTC_BOOTSTRAP.html), which is coordinated between `rustc` and the build system, `bootstrap`. - -## `tests/ui/borrowck/`: Borrow Checking - -Tests for borrow checking. E.g. lifetime analysis, borrowing rules, and diagnostics. - -## `tests/ui/box/`: Box Behavior - -Tests for `Box` smart pointer and `#![feature(box_patterns)]`. E.g. allocation, deref coercion, and edge cases in box pattern matching and placement. - -See: - -- [`std::box::Boxed`](https://doc.rust-lang.org/std/boxed/struct.Box.html) -- [Tracking issue for `box_patterns` feature #29641](https://github.com/rust-lang/rust/issues/29641) - -## `tests/ui/btreemap/`: B-Tree Maps - -Tests focused on `BTreeMap` collections and their compiler interactions. E.g. collection patterns, iterator behavior, and trait implementations specific to `BTreeMap`. See [`std::collections::BTreeMap`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html). - -## `tests/ui/builtin-superkinds/`: Built-in Trait Hierarchy Tests - -Tests for built-in trait hierarchy (Send, Sync, Sized, etc.) and their supertrait relationships. E.g. auto traits and marker trait constraints. - -See [RFC 3729: Hierarchy of Sized traits](https://github.com/rust-lang/rfcs/pull/3729). - -Defining custom auto traits with the `auto` keyword belongs to `tests/ui/auto-traits/` instead. - -## `tests/ui/cast/`: Type Casting - -Tests for type casting using the `as` operator. Includes tests for valid/invalid casts between primitive types, trait objects, and custom types. For example, check that trying to cast `i32` into `bool` results in a helpful error message. - -See [Type cast expressions | Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html). - -## `tests/ui/cfg/`: Configuration Attribute - -Tests for `#[cfg]` conditional compilation attribute. E.g. feature flags, target architectures, and other configuration predicates and options. - -See [Conditional compilation | Reference](https://doc.rust-lang.org/reference/conditional-compilation.html). - -## `tests/ui/check-cfg/`: Configuration Checks - -Tests for the `--check-cfg` compiler mechanism for checking cfg configurations, for `#[cfg(..)]` and `cfg!(..)`. - -See [Checking conditional configurations | The rustc book](https://doc.rust-lang.org/rustc/check-cfg.html). - -## `tests/ui/closure_context/`: Closure type inference in context - -Tests for closure type inference with respect to surrounding scopes, mostly quality of diagnostics. - -## `tests/ui/closure-expected-type/`: Closure type inference - -Tests targeted at how we deduce the types of closure arguments. This process is a result of some heuristics which take into account the *expected type* we have alongside the *actual types* that we get from inputs. - -**FIXME**: Appears to have significant overlap with `tests/ui/closure_context` and `tests/ui/functions-closures/closure-expected-type`. Needs further investigation. - -## `tests/ui/closures/`: General Closure Tests - -Any closure-focused tests that does not fit in the other more specific closure subdirectories belong here. E.g. syntax, `move`, lifetimes. - -## `tests/ui/cmse-nonsecure/`: `cmse-nonsecure` ABIs - -Tests for `extern "cmse-nonsecure-call"` and `extern "cmse-nonsecure-entry"` functions. Used specifically for the Armv8-M architecture, the former marks Secure functions with additional behaviours, such as adding a special symbol and constraining the number of parameters, while the latter alters function pointers to indicate they are non-secure and to handle them differently than usual. - -See: - -- [`cmse_nonsecure_entry` | The Unstable book](https://doc.rust-lang.org/nightly/unstable-book/language-features/cmse-nonsecure-entry.html) -- [`abi_cmse_nonsecure_call` | The Unstable book](https://doc.rust-lang.org/nightly/unstable-book/language-features/abi-cmse-nonsecure-call.html) - -## `tests/ui/codegen/`: Code Generation - -Tests that exercise code generation. E.g. codegen flags (starting with `-C` on the command line), LLVM IR output, optimizations (and the various `opt-level`s), and target-specific code generation (such as tests specific to `x86_64`). - -## `tests/ui/codemap_tests/`: Source Mapping - -Tests that exercise source code mapping. - -## `tests/ui/coercion/`: Type Coercion - -Tests for implicit type coercion behavior, where the types of some values are changed automatically when compatible depending on the context. E.g. automatic dereferencing or downgrading a `&mut` into a `&`. - -See [Type coercions | Reference](https://doc.rust-lang.org/reference/type-coercions.html). - -## `tests/ui/coherence/`: Trait Implementation Coherence - -Tests for trait coherence rules, which govern where trait implementations can be defined. E.g. orphan rule, and overlap checks. - -See [Coherence | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/coherence.html#coherence). - -## `tests/ui/coinduction/`: Coinductive Trait Resolution - -Tests for coinduction in trait solving which may involve infinite proof trees. - -See: - -- [Coinduction | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/solve/coinduction.html). -- [Inductive cycles | Chalk](https://rust-lang.github.io/chalk/book/recursive/inductive_cycles.html#inductive-cycles)/ - -This directory only contains one highly specific test. Other coinduction tests can be found down the deeply located `tests/ui/traits/next-solver/cycles/coinduction/` subdirectory. - -## `tests/ui/command/`: `std::process::Command` - -This directory is actually for the standard library [`std::process::Command`](https://doc.rust-lang.org/std/process/struct.Command.html) type, where some tests are too difficult or inconvenient to write as unit tests or integration tests within the standard library itself. - -**FIXME**: the test `command-line-diagnostics` seems to have been misplaced in this category. - -## `tests/ui/compare-method/`: Trait implementation and definition comparisons - -Some traits' implementation must be compared with their definition, checking for problems such as the implementation having stricter requirements (such as needing to implement `Copy`). - -This subdirectory is *not* intended comparison traits (`PartialEq`, `Eq`, `PartialOrd`, `Ord`). - -## `tests/ui/compiletest-self-test/`: compiletest "meta" tests - -Meta test suite of the test harness `compiletest` itself. - -## `tests/ui/conditional-compilation/`: Conditional Compilation - -Tests for `#[cfg]` attribute or `--cfg` flags, used to compile certain files or code blocks only if certain conditions are met (such as developing on a specific architecture). - -**FIXME**: There is significant overlap with `tests/ui/cfg`, which even contains a `tests/ui/cfg/conditional-compile.rs` test. Also investigate `tests/ui/check-cfg`. - -## `tests/ui/confuse-field-and-method/`: Field/Method Ambiguity - -If a developer tries to create a `struct` where one of the fields is a closure function, it becomes unclear whether `struct.field()` is accessing the field itself or trying to call the closure function within as a method. - -**FIXME**: does this really need to be its own immediate subdirectory? - -## `tests/ui/const-generics/`: Constant Generics - -Tests for const generics, allowing types to be parameterized by constant values. It is generally observed in the form `` after the `fn` or `struct` keywords. Includes tests for const expressions in generic contexts and associated type bounds. - -See: - -- [Tracking Issue for complex generic constants: `feature(generic_const_exprs)` #76560](https://github.com/rust-lang/rust/issues/76560) -- [Const generics | Reference](https://doc.rust-lang.org/reference/items/generics.html#const-generics) - -## `tests/ui/const_prop/`: Constant Propagation - -Tests exercising `ConstProp` mir-opt pass (mostly regression tests). See . - -## `tests/ui/const-ptr/`: Constant Pointers - -Tests exercise const raw pointers. E.g. pointer arithmetic, casting and dereferencing, always with a `const`. - -See: - -- [`std::primitive::pointer`](https://doc.rust-lang.org/std/primitive.pointer.html) -- [`std::ptr`](https://doc.rust-lang.org/std/ptr/index.html) -- [Pointer types | Reference](https://doc.rust-lang.org/reference/types/pointer.html) - -## `tests/ui/consts/`: General Constant Evaluation - -Anything to do with constants, which does not fit in the previous two `const` categories, goes here. This does not always imply use of the `const` keyword - other values considered constant, such as defining an enum variant as `enum Foo { Variant = 5 }` also counts. - -## `tests/ui/contracts/`: Contracts feature - -Tests exercising `#![feature(contracts)]`. - -See [Tracking Issue for Contracts #128044](https://github.com/rust-lang/rust/issues/128044). - -## `tests/ui/coroutine/`: Coroutines feature and `gen` blocks - -Tests for `#![feature(coroutines)]` and `gen` blocks, it belongs here. - -See: - -- [Coroutines | The Unstable book](https://doc.rust-lang.org/beta/unstable-book/language-features/coroutines.html) -- [RFC 3513 Gen blocks](https://rust-lang.github.io/rfcs/3513-gen-blocks.html) - -## `tests/ui/coverage-attr/`: `#[coverage]` attribute - -Tests for `#![feature(coverage_attribute)]`. See [Tracking issue for function attribute `#[coverage]`](https://github.com/rust-lang/rust/issues/84605). - -## `tests/ui/crate-loading/`: Crate Loading - -Tests for crate resolution and loading behavior, including `extern crate` declarations, `--extern` flags, or the `use` keyword. - -## `tests/ui/cross/`: Various tests related to the concept of "cross" - -**FIXME**: The unifying topic of these tests appears to be that their filenames begin with the word "cross". The similarities end there - one test is about "cross-borrowing" a `Box` into `&T`, while another is about a global trait used "across" files. Some of these terminology are really outdated and does not match the current terminology. Additionally, "cross" is also way too generic, it's easy to confuse with cross-compile. - -## `tests/ui/cross-crate/`: Cross-Crate Interaction - -Tests for behavior spanning multiple crates, including visibility rules, trait implementations, and type resolution across crate boundaries. - -## `tests/ui/custom_test_frameworks/` - -Tests for `#[bench]`, `#[test_case]` attributes and the `custom_test_frameworks` lang item. - -See [Tracking issue for eRFC 2318, Custom test frameworks #50297](https://github.com/rust-lang/rust/issues/50297). - -## `tests/ui/c-variadic/`: C Variadic Function - -Tests for FFI with C varargs (`va_list`). - -## `tests/ui/cycle-trait/`: Trait Cycle Detection - -Tests for detection and handling of cyclic trait dependencies. - -## `tests/ui/dataflow_const_prop/` - -Contains a single regression test for const prop in `SwitchInt` pass crashing when `ptr2int` transmute is involved. - -**FIXME**: A category with a single test. Maybe it would fit inside the category `const-prop` or some kind of `mir-opt` directory. - -## `tests/ui/debuginfo/` - -Tests for generation of debug information (DWARF, etc.) including variable locations, type information, and source line mapping. Also exercises `-C split-debuginfo` and `-C debuginfo`. - -## `tests/ui/definition-reachable/`: Definition Reachability - -Tests to check whether definitions are reachable. - -## `tests/ui/delegation/`: `#![feature(fn_delegation)]` - -Tests for `#![feature(fn_delegation)]`. See [Implement function delegation in rustc #3530](https://github.com/rust-lang/rfcs/pull/3530) for the proposed prototype experimentation. - -## `tests/ui/dep-graph/`: `-Z query-dep-graph` - -These tests use the unstable command line option `query-dep-graph` to examine the dependency graph of a Rust program, which is useful for debugging. - -## `tests/ui/deprecation/`: Deprecation Attribute - -Tests for `#[deprecated]` attribute and `deprecated_in_future` internal lint. - -## `tests/ui/deref-patterns/`: `#![feature(deref_patterns)]` and `#![feature(string_deref_patterns)]` - -Tests for `#![feature(deref_patterns)]` and `#![feature(string_deref_patterns)]`. See [Deref patterns | The Unstable book](https://doc.rust-lang.org/nightly/unstable-book/language-features/deref-patterns.html). - -**FIXME**: May have some overlap with `tests/ui/pattern/deref-patterns`. - -## `tests/ui/derived-errors/`: Derived Error Messages - -Tests for quality of diagnostics involving suppression of cascading errors in some cases to avoid overwhelming the user. - -## `tests/ui/derives/`: Derive Macro - -Tests for built-in derive macros (`Debug`, `Clone`, etc.) when used in conjunction with built-in `#[derive(..)]` attributes. - -## `tests/ui/deriving/`: Derive Macro - -**FIXME**: Coalesce with `tests/ui/derives`. - -## `tests/ui/dest-prop/` Destination Propagation - -**FIXME**: Contains a single test for the `DestProp` mir-opt, should probably be rehomed. - -## `tests/ui/destructuring-assignment/` - -Exercises destructuring assignments. See [RFC 2909 Destructuring assignment](https://github.com/rust-lang/rfcs/blob/master/text/2909-destructuring-assignment.md). - -## `tests/ui/diagnostic-flags/` - -These tests revolve around command-line flags which change the way error/warning diagnostics are emitted. For example, `--error-format=human --color=always`. - -**FIXME**: Check redundancy with `annotate-snippet`, which is another emitter. - -## `tests/ui/diagnostic_namespace/` - -Exercises `#[diagnostic::*]` namespaced attributes. See [RFC 3368 Diagnostic attribute namespace](https://github.com/rust-lang/rfcs/blob/master/text/3368-diagnostic-attribute-namespace.md). - -## `tests/ui/diagnostic-width/`: `--diagnostic-width` - -Everything to do with `--diagnostic-width`. - -## `tests/ui/did_you_mean/` - -Tests for miscellaneous suggestions. - -## `tests/ui/directory_ownership/`: Declaring `mod` inside a block - -Exercises diagnostics for when a code block attempts to gain ownership of a non-inline module with a `mod` keyword placed inside of it. - -## `tests/ui/disallowed-deconstructing/`: Incorrect struct deconstruction - -Exercises diagnostics for disallowed struct destructuring. - -## `tests/ui/dollar-crate/`: `$crate` used with the `use` keyword - -There are a few rules - which are checked in this directory - to follow when using `$crate` - it must be used in the start of a `use` line and is a reserved identifier. - -**FIXME**: There are a few other tests in other directories with a filename starting with `dollar-crate`. They should perhaps be redirected here. - -## `tests/ui/drop/`: `Drop` and drop order - -Not necessarily about `Drop` and its implementation, but also about the drop order of fields inside a struct. - -## `tests/ui/drop-bounds/` - -Tests for linting on bounding a generic type on `Drop`. - -## `tests/ui/dropck/`: Drop Checking - -Mostly about checking the validity of `Drop` implementations. - -See: - -- [Dropck | The Nomicon](https://doc.rust-lang.org/nomicon/dropck.html) -- [Drop check | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/borrow_check/drop_check.html) - -## `tests/ui/dst/`: Dynamically Sized Types - -Tests for dynamically-sized types (DSTs). See [Dynamically Sized Types | Reference](https://doc.rust-lang.org/reference/dynamically-sized-types.html). - -## `tests/ui/duplicate/`: Duplicate Symbols - -Tests about duplicated symbol names and associated errors, such as using the `#[export_name]` attribute to rename a function with the same name as another function. - -## `tests/ui/dynamically-sized-types/`: Dynamically Sized Types - -**FIXME**: should be coalesced with `tests/ui/dst`. - -## `tests/ui/dyn-compatibility/`: Dyn-compatibility - -Tests for dyn-compatibility of traits. - -See: - -- [Trait object | Reference](https://doc.rust-lang.org/reference/types/trait-object.html) -- [Dyn compatibility | Reference](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility) - -Previously known as "object safety". - -## `tests/ui/dyn-drop/`: `dyn Drop` - -**FIXME**: Contains a single test, used only to check the `dyn_drop` lint (which is normally `warn` level). - -## `tests/ui/dyn-keyword/`: `dyn` and Dynamic Dispatch - -The `dyn` keyword is used to highlight that calls to methods on the associated Trait are dynamically dispatched. To use the trait this way, it must be dyn-compatible - tests about dyn-compatibility belong in `tests/ui/dyn-compatibility/`, while more general tests on dynamic dispatch belong here. - -See [`dyn` keyword](https://doc.rust-lang.org/std/keyword.dyn.html). - -## `tests/ui/editions/`: Rust edition-specific peculiarities - -These tests run in specific Rust editions, such as Rust 2015 or Rust 2018, and check errors and functionality related to specific now-deprecated idioms and features. - -**FIXME**: Maybe regroup `rust-2018`, `rust-2021` and `rust-2024` under this umbrella? - -## `tests/ui/empty/`: Various tests related to the concept of "empty" - -**FIXME**: These tests need better homes, this is not very informative. - -## `tests/ui/entry-point/`: `main` function - -Tests exercising the `main` entry-point. - -## `tests/ui/enum/` - -General-purpose tests on `enum`s. See [Enumerations | Reference](https://doc.rust-lang.org/reference/items/enumerations.html). - -## `tests/ui/enum-discriminant/` - -`enum` variants can be differentiated independently of their potential field contents with `discriminant`, which returns the type `Discriminant`. See [`std::mem::discriminant`](https://doc.rust-lang.org/std/mem/fn.discriminant.html). - -## `tests/ui/env-macro/`: `env!` - -Exercises `env!` and `option_env!` macros. - -## `tests/ui/ergonomic-clones/` - -See [RFC 3680 Ergonomic clones](https://github.com/rust-lang/rfcs/pull/3680). - -## `tests/ui/error-codes/`: Error codes - -Tests for errors with dedicated error codes. - -## `tests/ui/error-emitter/` - -Quite similar to `ui/diagnostic-flags` in some of its tests, this category checks some behaviours of Rust's error emitter into the user's terminal window, such as truncating error in the case of an excessive amount of them. - -## `tests/ui/errors/` - -These tests are about very different topics, only unified by the fact that they result in errors. - -**FIXME**: "Errors" is way too generic, the tests probably need to be rehomed into more descriptive subdirectories. - -## `tests/ui/explain/`: `rustc --explain EXXXX` - -Accompanies `tests/ui/error-codes/`, exercises the `--explain` cli flag. - -## `tests/ui/explicit/`: Errors involving the concept of "explicit" - -This category contains three tests: two which are about the specific error `explicit use of destructor method`, and one which is about explicit annotation of lifetimes: https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime/explicit.html. - -**FIXME**: Rehome the two tests about the destructor method with `drop`-related categories, and rehome the last test with a category related to lifetimes. - -## `tests/ui/explicit-tail-calls/` - -Exercises `#![feature(explicit_tail_calls)]` and the `become` keyword. See [Explicit Tail Calls #3407](https://github.com/rust-lang/rfcs/pull/3407). - -## `tests/ui/expr/`: Expressions - -A broad directory for tests on expressions. - -## `tests/ui/extern/` - -Tests on the `extern` keyword and `extern` blocks and functions. - -## `tests/ui/extern-flag/`: `--extern` command line flag - -Tests for the `--extern` CLI flag. - -## `tests/ui/feature-gates/` - -Tests on feature-gating, and the `#![feature(..)]` mechanism itself. - -## `tests/ui/ffi-attrs/`: `#![feature(ffi_const, ffi_pure)]` - -The `#[ffi_const]` and `#[ffi_pure]` attributes applies clang's `const` and `pure` attributes to foreign functions declarations, respectively. These attributes are the core element of the tests in this category. - -See: - -- [`ffi_const` | The Unstable book](https://doc.rust-lang.org/unstable-book/language-features/ffi-const.html) -- [`ffi_pure` | The Unstable book](https://doc.rust-lang.org/beta/unstable-book/language-features/ffi-pure.html) - -## `tests/ui/fmt/` - -Exercises the `format!` macro. - -## `tests/ui/fn/` - -A broad category of tests on functions. - -## `tests/ui/fn-main/` - -**FIXME**: Serves a duplicate purpose with `ui/entry-point`, should be combined. - -## `tests/ui/for/`: `for` keyword - -Tests on the `for` keyword and some of its associated errors, such as attempting to write the faulty pattern `for _ in 0..1 {} else {}`. - -**FIXME**: Should be merged with `ui/for-loop-while`. - -## `tests/ui/force-inlining/`: `#[rustc_force_inline]` - -Tests for `#[rustc_force_inline]`, which will force a function to always be labelled as inline by the compiler (it will be inserted at the point of its call instead of being used as a normal function call.) If the compiler is unable to inline the function, an error will be reported. See . - -## `tests/ui/foreign/`: Foreign Function Interface (FFI) - -Tests for `extern "C"` and `extern "Rust`. - -**FIXME**: Check for potential overlap/merge with `ui/c-variadic` and/or `ui/extern`. - -## `tests/ui/for-loop-while/` - -Anything to do with loops and `for`, `loop` and `while` keywords to express them. - -**FIXME**: After `ui/for` is merged into this, also carry over its SUMMARY text. - -## `tests/ui/frontmatter/` - -Tests for `#![feature(frontmatter)]`. See [Tracking Issue for `frontmatter` #136889](https://github.com/rust-lang/rust/issues/136889). - -## `tests/ui/fully-qualified-type/` - -Tests for diagnostics when there may be identically named types that need further qualifications to disambiguate. - -## `tests/ui/functional-struct-update/` - -Functional Struct Update is the name for the idiom by which one can write `..` at the end of a struct literal expression to fill in all remaining fields of the struct literal by using `` as the source for them. - -See [RFC 0736 Privacy-respecting Functional Struct Update](https://github.com/rust-lang/rfcs/blob/master/text/0736-privacy-respecting-fru.md). - -## `tests/ui/function-pointer/` - -Tests on function pointers, such as testing their compatibility with higher-ranked trait bounds. - -See: - -- [Function pointer types | Reference](https://doc.rust-lang.org/reference/types/function-pointer.html) -- [Higher-ranked trait bounds | Nomicon](https://doc.rust-lang.org/nomicon/hrtb.html) - -## `tests/ui/functions-closures/` - -Tests on closures. See [Closure expressions | Reference](https://doc.rust-lang.org/reference/expressions/closure-expr.html). - -## `tests/ui/generic-associated-types/` - -Tests on Generic Associated Types (GATs). - -## `tests/ui/generic-const-items/` - -Tests for `#![feature(generic_const_items)]`. See [Tracking issue for generic const items #113521](https://github.com/rust-lang/rust/issues/113521). - -## `tests/ui/generics/` - -A broad category of tests on generics, usually used when no more specific subdirectories are fitting. - -## `tests/ui/half-open-range-patterns/`: `x..` or `..x` range patterns - -Tests on range patterns where one of the bounds is not a direct value. - -**FIXME**: Overlaps with `ui/range`. `impossible_range.rs` is particularly suspected to be a duplicate test. - -## `tests/ui/hashmap/` - -Tests for the standard library collection [`std::collections::HashMap`](https://doc.rust-lang.org/std/collections/struct.HashMap.html). - -## `tests/ui/hello_world/` - -Tests that the basic hello-world program is not somehow broken. - -## `tests/ui/higher-ranked/` - -Tests for higher-ranked trait bounds. - -See: - -- [Higher-ranked trait bounds | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/traits/hrtb.html) -- [Higher-ranked trait bounds | Nomicon](https://doc.rust-lang.org/nomicon/hrtb.html) - -## `tests/ui/hygiene/` - -This seems to have been originally intended for "hygienic macros" - macros which work in all contexts, independent of what surrounds them. However, this category has grown into a mish-mash of many tests that may belong in the other directories. - -**FIXME**: Reorganize this directory properly. - -## `tests/ui/illegal-sized-bound/` - -This test category revolves around trait objects with `Sized` having illegal operations performed on them. - -**FIXME**: There seems to be unrelated testing in this directory, such as `tests/ui/illegal-sized-bound/mutability-mismatch-arg.rs`. Investigate. - -## `tests/ui/impl-header-lifetime-elision/` - -Tests on lifetime elision in impl function signatures. See [Lifetime elision | Nomicon](https://doc.rust-lang.org/nomicon/lifetime-elision.html). - -## `tests/ui/implied-bounds/` - -See [Implied bounds | Reference](https://doc.rust-lang.org/reference/trait-bounds.html#implied-bounds). - -## `tests/ui/impl-trait/` - -Tests for trait impls. - -## `tests/ui/imports/` - -Tests for module system and imports. - -## `tests/ui/include-macros/` - -Exercise `include!`, `include_str!`, and `include_bytes!` macros. - -## `tests/ui/incoherent-inherent-impls/` - -Exercise forbidding inherent impls on a type defined in a different crate. - -## `tests/ui/indexing/` - -Tests on collection types (arrays, slices, vectors) and various errors encountered when indexing their contents, such as accessing out-of-bounds values. - -**FIXME**: (low-priority) could maybe be a subdirectory of `ui/array-slice-vec` - -## `tests/ui/inference/` - -Tests on type inference. - -## `tests/ui/infinite/` - -Tests for diagnostics on infinitely recursive types without indirection. - -## `tests/ui/inherent-impls-overlap-check/` - -Checks that repeating the same function names across separate `impl` blocks triggers an informative error, but not if the `impl` are for different types, such as `Bar` and `Bar`. - -NOTE: This should maybe be a subdirectory within another related to duplicate definitions, such as `tests/ui/duplicate/`. - -## `tests/ui/inline-const/` - -These tests revolve around the inline `const` block that forces the compiler to const-eval its content. - -## `tests/ui/instrument-coverage/`: `-Cinstrument-coverage` command line flag - -See [Instrument coverage | The rustc book](https://doc.rust-lang.org/rustc/instrument-coverage.html). - -## `tests/ui/instrument-xray/`: `-Z instrument-xray` - -See [Tracking issue for `-Z instrument-xray` #102921](https://github.com/rust-lang/rust/issues/102921). - -## `tests/ui/interior-mutability/` - -**FIXME**: contains a single test, probably better rehomed. - -## `tests/ui/internal/` - -Tests for `internal_unstable` and the attribute header `#![feature(allow_internal_unstable)]`, which lets compiler developers mark features as internal to the compiler, and unstable for standard library use. - -## `tests/ui/internal-lints/` - -Tests for rustc-internal lints. - -## `tests/ui/intrinsics/` - -Tests for the `{std,core}::intrinsics`, internal implementation detail. - -## `tests/ui/invalid/` - -Various tests related to rejecting invalid inputs. - -**FIXME**: This is rather uninformative, possibly rehome into more meaningful directories. - -## `tests/ui/invalid-compile-flags/` - -Tests for checking that invalid usage of compiler flags are rejected. - -## `tests/ui/invalid-module-declaration/` - -**FIXME**: Consider merging into module/resolve directories. - -## `tests/ui/invalid-self-argument/`: `self` as a function argument incorrectly - -Tests with erroneous ways of using `self`, such as having it not be the first argument, or using it in a non-associated function (no `impl` or `trait`). - -**FIXME**: Maybe merge with `ui/self`. - -## `tests/ui/io-checks/` - -Contains a single test. The test tries to output a file into an invalid directory with `-o`, then checks that the result is an error, not an internal compiler error. - -**FIXME**: Rehome to invalid compiler flags maybe. - -## `tests/ui/issues/`: Tests directly related to GitHub issues - -**FIXME (#133895)**: Random collection of regression tests and tests for issues, tests in this directory should be audited and rehomed. - -## `tests/ui/iterators/` - -These tests revolve around anything to do with iterators, e.g. mismatched types. - -**FIXME**: Check for potential overlap with `ui/for-loop-while`. - -## `tests/ui/json/` - -These tests revolve around the `--json` compiler flag. See [JSON Output](https://doc.rust-lang.org/rustc/json.html#json-output). - -## `tests/ui/keyword/` - -Tests exercising keywords, such as attempting to use them as identifiers when not contextual keywords. - -## `tests/ui/kindck/` - -**FIXME**: `kindck` is no longer a thing, these tests probably need to be audited and rehomed. - -## `tests/ui/label/` - -Exercises block and loop `'label`s. - -## `tests/ui/lang-items/` - -See [Lang items | The Unstable book](https://doc.rust-lang.org/unstable-book/language-features/lang-items.html). - -## `tests/ui/late-bound-lifetimes/` - -See [Early vs Late bound parameters | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/early_late_parameters.html#early-vs-late-bound-parameters). - -## `tests/ui/layout/` - -See [Type Layout | Reference](https://doc.rust-lang.org/reference/type-layout.html). - -## `tests/ui/lazy-type-alias/` - -Tests for `#![feature(lazy_type_alias)]`. See [Tracking issue for lazy type aliases #112792 -](https://github.com/rust-lang/rust/issues/112792). - -## `tests/ui/lazy-type-alias-impl-trait/` - -This feature allows use of an `impl Trait` in multiple locations while actually using the same concrete type (`type Alias = impl Trait;`) everywhere, keeping the original `impl Trait` hidden. - -**FIXME**: merge this with `tests/ui/type-alias-impl-trait/`? - -## `tests/ui/let-else/` - -Exercises let-else constructs. - -## `tests/ui/lexer/` - -Exercises of the lexer. - -## `tests/ui/lifetimes/` - -Broad directory on lifetimes, including proper specifiers, lifetimes not living long enough, or undeclared lifetime names. - -## `tests/ui/limits/` - -These tests exercises numerical limits, such as `[[u8; 1518599999]; 1518600000]`. - -## `tests/ui/linkage-attr/` - -Tests for the linkage attribute `#[linkage]` of `#![feature(linkage)]`. - -**FIXME**: Some of these tests do not use the feature at all, which should be moved under `ui/linking` instead. - -## `tests/ui/linking/` - -Tests on code which fails during the linking stage, or which contain arguments and lines that have been known to cause unjustified errors in the past, such as specifying an unusual `#[export_name]`. - -See [Linkage | Reference](https://doc.rust-lang.org/reference/linkage.html). - -## `tests/ui/link-native-libs/` - -Tests for `#[link(name = "", kind = "")]` and `-l` command line flag. - -See [Tracking Issue for linking modifiers for native libraries #81490](https://github.com/rust-lang/rust/issues/81490). - -## `tests/ui/lint/` - -Tests for the lint infrastructure, lint levels, lint reasons, etc. - -See: - -- [Lints | The rustc book](https://doc.rust-lang.org/rustc/lints/index.html) -- [Lint reasons | Reference](https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-reasons) - -## `tests/ui/liveness/` - -Tests exercising analysis for unused variables, unreachable statements, functions which are supposed to return a value but do not, as well as values moved elsewhere before they could be used by a function. - -**FIXME**: This seems unrelated to "liveness" as defined in the rustc compiler guide. Is this misleadingly named? https://rustc-dev-guide.rust-lang.org/borrow_check/region_inference/lifetime_parameters.html#liveness-and-universal-regions - -## `tests/ui/loops/` - -Tests on the `loop` construct. - -**FIXME**: Consider merging with `ui/for-loop-while`. - -## `tests/ui/lowering/` - -Tests on [AST lowering](https://rustc-dev-guide.rust-lang.org/ast-lowering.html). - -## `tests/ui/lto/` - -Exercise *Link-Time Optimization* (LTO), involving the flags `-C lto` or `-Z thinlto`. - -## `tests/ui/lub-glb/`: LUB/GLB algorithm update - -Tests on changes to inference variable lattice LUB/GLB, see . - -## `tests/ui/macro_backtrace/`: `-Zmacro-backtrace` - -Contains a single test, checking the unstable command-line flag to enable detailed macro backtraces. - -**FIXME**: This could be merged with `ui/macros`, which already contains other macro backtrace tests. - -## `tests/ui/macros/` - -Broad category of tests on macros. - -## `tests/ui/malformed/` - -Broad category of tests on malformed inputs. - -**FIXME**: this is kinda vague, probably best to audit and rehome tests. - -## `tests/ui/marker_trait_attr/` - -See [Tracking issue for allowing overlapping implementations for marker trait #29864](https://github.com/rust-lang/rust/issues/29864). - -## `tests/ui/match/` - -Broad category of tests on `match` constructs. - -## `tests/ui/meta/`: Tests for compiletest itself - -These tests check the function of the UI test suite at large and Compiletest in itself. - -**FIXME**: This should absolutely be merged with `tests/ui/compiletest-self-test/`. - -## `tests/ui/methods/` - -A broad category for anything related to methods and method resolution. - -## `tests/ui/mir/` - -Certain mir-opt regression tests. - -## `tests/ui/mir-dataflow` - -Tests for MIR dataflow analysis. - -See [MIR Dataflow | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/mir/dataflow.html). - -## `tests/ui/mismatched_types/` - -Exercises on mismatched type diagnostics. - -## `tests/ui/missing/` - -Something is missing which could be added to fix (e.g. suggestions). - -**FIXME**: this is way too vague, tests should be rehomed. - -## `tests/ui/missing_non_modrs_mod/` - -This directory is a small tree of `mod` dependencies, but the root, `foo.rs`, is looking for a file which does not exist. The test checks that the error is reported at the top-level module. - -**FIXME**: Merge with `tests/ui/modules/`. - -## `tests/ui/missing-trait-bounds/` - -Tests for checking missing trait bounds, and their diagnostics. - -**FIMXE**: Maybe a subdirectory of `ui/trait-bounds` would be more appropriate. - -## `tests/ui/modules/` - -Tests on the module system. - -**FIXME**: `tests/ui/imports/` should probably be merged with this. - -## `tests/ui/modules_and_files_visibility/` - -**FIXME**: Merge with `tests/ui/modules/`. - -## `tests/ui/moves` - -Tests on moves (destructive moves). - -## `tests/ui/mut/` - -Broad category of tests on mutability, such as the `mut` keyword, borrowing a value as both immutable and mutable (and the associated error), or adding mutable references to `const` declarations. - -## `tests/ui/namespace/` - -Contains a single test. It imports a massive amount of very similar types from a crate, then attempts various permutations of their namespace paths, checking for errors or the lackthereof. - -**FIXME**: Move under either `tests/ui/modules/` or `tests/ui/resolve/`. - -## `tests/ui/never_type/` - -See [Tracking issue for promoting `!` to a type (RFC 1216) #35121](https://github.com/rust-lang/rust/issues/35121). - -## `tests/ui/new-range/` - -See [RFC 3550 New Range](https://github.com/rust-lang/rfcs/blob/master/text/3550-new-range.md). - -## `tests/ui/nll/`: Non-lexical lifetimes - -Tests for Non-lexical lifetimes. See [RFC 2094 NLL](https://rust-lang.github.io/rfcs/2094-nll.html). - -## `tests/ui/non_modrs_mods/` - -Despite the size of the directory, this is a single test, spawning a sprawling `mod` dependency tree and checking its successful build. - -**FIXME**: Consider merge with `tests/ui/modules/`, keeping the directory structure. - -## `tests/ui/non_modrs_mods_and_inline_mods/` - -A very similar principle as `non_modrs_mods`, but with an added inline `mod` statement inside another `mod`'s code block. - -**FXIME**: Consider merge with `tests/ui/modules/`, keeping the directory structure. - -## `tests/ui/no_std/` - -Tests for where the standard library is disabled through `#![no_std]`. - -## `tests/ui/not-panic/` - -Tests checking various types, such as `&RefCell`, and whether they are not `UnwindSafe` as expected. - -## `tests/ui/numbers-arithmetic/` - -Tests that exercises edge cases, such as specific floats, large or very small numbers, or bit conversion, and check that the arithmetic results are as expected. - -## `tests/ui/numeric/` - -Tests that checks numeric types and their interactions, such as casting among them with `as` or providing the wrong numeric suffix. - -## `tests/ui/object-lifetime/` - -Tests on lifetimes on objects, such as a lifetime bound not being able to be deduced from context, or checking that lifetimes are inherited properly. - -**FIXME**: Just a more specific subset of `ui/lifetimes`. - -## `tests/ui/obsolete-in-place/` - -Contains a single test. Check that we reject the ancient Rust syntax `x <- y` and `in(BINDING) {}` construct. - -**FIXME**: Definitely should be rehomed, maybe to `tests/ui/deprecation/`. - -## `tests/ui/offset-of/` - -Exercises the [`std::mem::offset_of` macro](https://doc.rust-lang.org/beta/std/mem/macro.offset_of.html). - -## `tests/ui/on-unimplemented/` - -Exercises the `#[rustc_on_unimplemented]`. - -## `tests/ui/operator-recovery/` - -**FIXME**: Probably move under `tests/ui/binop/` or `tests/ui/parser/`. - -## `tests/ui/or-patterns/` - -Exercises `||` and `|` in patterns. - -## `tests/ui/overloaded/` - -Exercises operator overloading via [`std::ops`](https://doc.rust-lang.org/std/ops/index.html). - -## `tests/ui/packed/` - -See [`repr(packed)` | Nomicon](https://doc.rust-lang.org/nomicon/other-reprs.html#reprpacked-reprpackedn). - -## `tests/ui/panic-handler/` - -See [panic handler | Nomicon](https://doc.rust-lang.org/nomicon/panic-handler.html). - -## `tests/ui/panic-runtime/` - -Exercises `#![panic_runtime]`, `-C panic`, panic runtimes and panic unwind strategy. - -See [RFC 1513 Less unwinding](https://github.com/rust-lang/rfcs/blob/master/text/1513-less-unwinding.md). - -## `tests/ui/panics/` - -Broad category of tests about panics in general, often but not necessarily using the `panic!` macro. - -## `tests/ui/parallel-rustc/` - -Efforts towards a [Parallel Rustc Front-end](https://github.com/rust-lang/rust/issues/113349). Includes `-Zthreads=`. - -## `tests/ui/parser/` - -Various parser tests - -**FIXME**: Maybe move `tests/ui/keywords/` under this? - -## `tests/ui/patchable-function-entry/` - -See [Patchable function entry | The Unstable book](https://doc.rust-lang.org/unstable-book/compiler-flags/patchable-function-entry.html). - -## `tests/ui/pattern/` - -Broad category of tests surrounding patterns. See [Patterns | Reference](https://doc.rust-lang.org/reference/patterns.html). - -**FIXME**: Some overlap with `tests/ui/match/`. - -## `tests/ui/pin-macro/` - -See [`std::pin`](https://doc.rust-lang.org/std/pin/). - -## `tests/ui/precondition-checks/` - -Exercises on some unsafe precondition checks. - -## `tests/ui/print-request/` - -Tests on `--print` compiler flag. See [print options | The rustc book](https://doc.rust-lang.org/rustc/command-line-arguments/print-options.html). - -## `tests/ui/print_type_sizes/` - -Exercises the `-Z print-type-sizes` flag. - -## `tests/ui/privacy/` - -Exercises on name privacy. E.g. the meaning of `pub`, `pub(crate)`, etc. - -## `tests/ui/process/` - -Some standard library process tests which are hard to write within standard library crate tests. - -## `tests/ui/process-termination/` - -Some standard library process termination tests which are hard to write within standard library crate tests. - -## `tests/ui/proc-macro/` - -Broad category of tests on proc-macros. See [Procedural Macros | Reference](https://doc.rust-lang.org/reference/procedural-macros.html). - -## `tests/ui/ptr_ops/`: Using operations on a pointer - -Contains only 2 tests, related to a single issue, which was about an error caused by using addition on a pointer to `i8`. - -**FIXME**: Probably rehome under some typecheck / binop directory. - -## `tests/ui/pub/`: `pub` keyword - -A large category about function and type public/private visibility, and its impact when using features across crates. Checks both visibility-related error messages and previously buggy cases. - -**FIXME**: merge with `tests/ui/privacy/`. - -## `tests/ui/qualified/` - -Contains few tests on qualified paths where a type parameter is provided at the end: `type A = ::A::f;`. The tests check if this fails during type checking, not parsing. - -**FIXME**: Should be rehomed to `ui/typeck`. - -## `tests/ui/query-system/` - -Tests on Rust methods and functions which use the query system, such as `std::mem::size_of`. These compute information about the current runtime and return it. See [Query system | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/query.html). - -## `tests/ui/range/` - -Broad category of tests ranges, both in their `..` or `..=` form, as well as the standard library `Range`, `RangeTo`, `RangeFrom` or `RangeBounds` types. - -**FIXME**: May have some duplicate tests with `ui/new-range`. - -## `tests/ui/raw-ref-op/`: Using operators on `&raw` values - -Exercises `&raw mut ` and `&raw const `. See [RFC 2582 Raw reference MIR operator](https://github.com/rust-lang/rfcs/blob/master/text/2582-raw-reference-mir-operator.md). - -## `tests/ui/reachable` - -Reachability tests, primarily unreachable code and coercions into the never type `!` from diverging expressions. - -**FIXME**: Check for overlap with `ui/liveness`. - -## `tests/ui/recursion/` - -Broad category of tests exercising recursions (compile test and run time), in functions, macros, `type` definitions, and more. - -Also exercises the `#![recursion_limit = ""]` attribute. - -## `tests/ui/recursion_limit/`: `#![recursion_limit = ""]` - -Sets a recursion limit on recursive code. - -**FIXME**: Should be merged with `tests/ui/recursion/`. - -## `tests/ui/regions/` - -**FIXME**: Maybe merge with `ui/lifetimes`. - -## `tests/ui/repeat-expr/` - -Exercises `[Type; n]` syntax for creating arrays with repeated types across a set size. - -**FIXME**: Maybe make this a subdirectory of `ui/array-slice-vec`. - -## `tests/ui/repr/`: `#[repr(_)]` - -Tests on the `#[repr(..)]` attribute. See [Representations | Reference](https://doc.rust-lang.org/reference/type-layout.html#representations). - -## `tests/ui/reserved/` - -Reserved keywords and attribute names. - -See e.g. [Reserved keywords | Reference](https://doc.rust-lang.org/reference/keywords.html). - -**FIXME**: maybe merge under `tests/ui/keyword/`. - -## `tests/ui/resolve/`: Name resolution - -See [Name resolution | rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/name-resolution.html). - -## `tests/ui/return/` - -Exercises the `return` keyword, return expressions and statements. - -## `tests/ui/rfcs/` - -Tests that accompanies an implementation for an RFC. - -## `tests/ui/rmeta/` - -Exercises `.rmeta` crate metadata and the `--emit=metadata` cli flag. - -## `tests/ui/runtime/` - -Tests for runtime environment on which Rust programs are executed. E.g. Unix `SIGPIPE`. - -## `tests/ui/rust-{2018,2021,2024}/` - -Tests that exercise behaviors and features that are specific to editions. - -## `tests/ui/rustc-env` - -Tests on environmental variables that affect `rustc`. - -## `tests/ui/rustdoc` - -Hybrid tests that exercises `rustdoc`, and also some joint `rustdoc`/`rustc` interactions. - -## `tests/ui/sanitizer/` - -Exercises sanitizer support. See [Sanitizer | The rustc book](https://doc.rust-lang.org/unstable-book/compiler-flags/sanitizer.html). - -## `tests/ui/self/`: `self` keyword - -Tests with erroneous ways of using `self`, such as using `this.x` syntax as seen in other languages, having it not be the first argument, or using it in a non-associated function (no `impl` or `trait`). It also contains correct uses of `self` which have previously been observed to cause ICEs. - -## `tests/ui/sepcomp/`: Separate Compilation - -In this directory, multiple crates are compiled, but some of them have `inline` functions, meaning they must be inlined into a different crate despite having been compiled separately. - -**FIXME**: this directory might need some better docs, also this directory might want a better name. - -## `tests/ui/shadowed/` - -Tests on name shadowing. - -## `tests/ui/shell-argfiles/`: `-Z shell-argfiles` command line flag - -The `-Zshell-argfiles` compiler flag allows argfiles to be parsed using POSIX "shell-style" quoting. When enabled, the compiler will use shlex to parse the arguments from argfiles specified with `@shell:`. - -Because this feature controls the parsing of input arguments, the `-Zshell-argfiles` flag must be present before the argument specifying the shell-style argument file. - -**FIXME**: maybe group this with `tests/ui/argfile/` - -## `tests/ui/simd/` - -Some tests exercising SIMD support. - -## `tests/ui/single-use-lifetime/` - -This is a test directory for the specific error case where a lifetime never gets used beyond a single annotation on, for example, a `struct`. - -## `tests/ui/sized/`: `Sized` trait, sized types - -While many tests here involve the `Sized` trait directly, some instead test, for example the slight variations between returning a zero-sized `Vec` and a `Vec` with one item, where one has no known type and the other does. - -## `tests/ui/span/` - -An assorted collection of tests that involves specific diagnostic spans. - -**FIXME**: This is a big directory with numerous only-tangentially related tests. Maybe some moving is in order. - -## `tests/ui/specialization` - -See [Tracking issue for specialization (RFC 1210) #31844](https://github.com/rust-lang/rust/issues/31844). - -## `tests/ui/stability-attribute/` - -Stability attributes used internally by the standard library: `#[stable()]` and `#[unstable()]`. - -## `tests/ui/rustc_public-ir-print/` - -Some tests for pretty printing of rustc_public's IR. - -## `tests/ui/stack-protector/`: `-Z stack-protector` command line flag - -See [Tracking Issue for stabilizing stack smashing protection (i.e., `-Z stack-protector`) #114903](https://github.com/rust-lang/rust/issues/114903). - -## `tests/ui/static/` - -Tests on static items. - -## `tests/ui/statics/` - -**FIXME**: should probably be merged with `tests/ui/static/`. - -## `tests/ui/stats/` - -Tests for compiler-internal stats; `-Z meta-stats` and `-Z input-stats` flags. - -## `tests/ui/std/`: Tests which use features from the standard library - -A catch-all category about anything that can come from `std`. - -**FIXME**: this directory is probably too vague, tests might need to be audited and rehomed. - -## `tests/ui/stdlib-unit-tests/` - -Some standard library tests which are too inconvenient or annoying to implement as std crate tests. - -## `tests/ui/str/` - -Exercise `str` keyword and string slices. - -## `tests/ui/structs/` - -Assorted tests surrounding the `struct` keyword, struct type definitions and usages. - -## `tests/ui/structs-enums/` - -Tests on both structs and enums. - -**FIXME**: maybe coalesce {`tests/ui/structs/`, `tests/ui/structs-enums/`, `tests/ui/enums/`} into one `tests/ui/adts` directory... - -## `tests/ui/suggestions/` - -Generic collection of tests for suggestions, when no more specific directories are applicable. - -**FIXME**: Some overlap with `tests/ui/did_you_mean/`, that directory should probably be moved under here. - -## `tests/ui/svh/`: Strict Version Hash - -Tests on the *Strict Version Hash* (SVH, also known as the "crate hash"). - -See [Strict Version Hash](https://rustc-dev-guide.rust-lang.org/backend/libs-and-metadata.html#strict-version-hash). - -## `tests/ui/symbol-mangling-version/`: `-Csymbol-mangling-version` command line flag - -**FIXME**: Should be merged with `ui/symbol-names`. - -## `tests/ui/symbol-names/`: Symbol mangling and related attributes - -These tests revolve around `#[no_mangle]` attribute, as well as consistently mangled symbol names (checked with the `rustc_symbol_name` attribute), which is important to build reproducible binaries. - -## `tests/ui/sync/`: `Sync` trait - -Exercises `Sync` trait and auto-derive thereof. - -## `tests/ui/target-cpu/`: `-C target-cpu` command line flag - -This command line option instructs rustc to generate code specifically for a particular processor. - -**FIXME**: Contains a single test, maybe put it in a directory about misc codegen options? - -## `tests/ui/target-feature/`: `#[target_feature(enable = "relaxed-simd")]` - -Exercises the `#[target_feature(..)]` attribute. See [Target feature attribute | Reference](https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute). - -## `tests/ui/target_modifiers/` - -Tests for [RFC 3716: Target Modifiers](https://github.com/rust-lang/rfcs/pull/3716). - -See [Tracking Issue for target modifiers #136966](https://github.com/rust-lang/rust/issues/136966). - -## `tests/ui/test-attrs/` - -Exercises the [`#[test]` attribute](https://doc.rust-lang.org/reference/attributes/testing.html#testing-attributes). - -## `tests/ui/thir-print/` - -Pretty print of THIR trees via `-Zunpretty=thir-tree`. - -## `tests/ui/thread-local/` - -Exercises thread local values and `#[thread_local]` attribute. - -See [Tracking issue for thread_local stabilization #29594](https://github.com/rust-lang/rust/issues/29594). - -## `tests/ui/threads-sendsync/` - -Broad category for parallelism and multi-threaded tests, including attempting to send types across threads which are not thread-safe. - -## `tests/ui/tool-attributes/`: External tool attributes - -Exercises [tool attributes](https://doc.rust-lang.org/reference/attributes.html#tool-attributes). - -## `tests/ui/track-diagnostics/` - -Exercises `#[track_caller]` and `-Z track-diagnostics`. - -## `tests/ui/trait-bounds/` - -Collection of tests for [trait bounds](https://doc.rust-lang.org/reference/trait-bounds.html). - -## `tests/ui/traits/` - -Broad collection of tests on traits in general. - -**FIXME**: This could be better organized in subdirectories containing tests such as `ui/traits/trait-bounds`. - -## `tests/ui/transmutability/`: `#![feature(transmutability)]` - -See [Tracking Issue for Transmutability Trait: `#[transmutability]` #99571](https://github.com/rust-lang/rust/issues/99571). - -See also [Project Safe Transmute](https://github.com/rust-lang/project-safe-transmute). - -## `tests/ui/transmute/` - -Tests surrounding [`std::mem::transmute`](https://doc.rust-lang.org/std/mem/fn.transmute.html). - -## `tests/ui/treat-err-as-bug/` - -Exercises compiler development support flag `-Z treat-err-as-bug`. - -## `tests/ui/trivial-bounds/` - -`#![feature(trivial_bounds)]`. See [RFC 2056 Allow trivial where clause constraints](https://github.com/rust-lang/rfcs/blob/master/text/2056-allow-trivial-where-clause-constraints.md). - -## `tests/ui/try-block/` - -`#![feature(try_blocks)]`. See [Tracking issue for `?` operator and `try` blocks (RFC 243, `question_mark` & `try_blocks` features)](https://github.com/rust-lang/rust/issues/31436). - -## `tests/ui/try-trait/` - -`#![feature(try_trait_v2)]`. See [RFC 3058 Try Trait v2](https://github.com/rust-lang/rfcs/blob/master/text/3058-try-trait-v2.md). - -## `tests/ui/tuple/` - -Tests surrounding the tuple type `()`. - -## `tests/ui/type/` - -Assorted collection of tests surrounding the concept of a "type". - -**FIXME**: There is very little consistency across tests of this category, and should probably be sent to other subdirectories. - -## `tests/ui/type-alias/` - -Exercises [type aliases](https://doc.rust-lang.org/reference/items/type-aliases.html). - -## `tests/ui/type-alias-enum-variants/` - -Tests for `type` aliases in the context of `enum` variants, such as that applied type arguments of enums are respected independently of being the original type or the `type` alias. - -## `tests/ui/type-alias-impl-trait/` - -`#![feature(type_alias_impl_trait)]`. See [Type Alias Impl Trait | The Unstable book](https://doc.rust-lang.org/nightly/unstable-book/language-features/type-alias-impl-trait.html). - -## `tests/ui/typeck/` - -General collection of type checking related tests. - -## `tests/ui/type-inference/` - -General collection of type inference related tests. - -## `tests/ui/typeof/` - -`typeof` keyword, reserved but unimplemented. - -## `tests/ui/ufcs/` - -See [RFC 0132 Unified Function Call Syntax](https://github.com/rust-lang/rfcs/blob/master/text/0132-ufcs.md). - -## `tests/ui/unboxed-closures/` - -`#![feature(unboxed_closures)]`, `Fn`, `FnMut` and `FnOnce` traits - -See [Tracking issue for Fn traits (`unboxed_closures` & `fn_traits` feature)](https://github.com/rust-lang/rust/issues/29625). - -## `tests/ui/underscore-imports/` - -See [Underscore imports | Reference](https://doc.rust-lang.org/reference/items/use-declarations.html#underscore-imports). - -**FIXME**: should become a subdirectory of `tests/ui/imports/`. - -## `tests/ui/underscore-lifetime/`: `'_` elided lifetime - -Exercises [anonymous elided lifetimes](https://doc.rust-lang.org/reference/lifetime-elision.html). - -## `tests/ui/uniform-paths/` - -In uniform paths, if a submodule and an external dependencies have the same name, to depend on the external dependency, one needs to disambiguate it from the submodule using `use ::foo`. Tests revolve around this, for example, check that `self::foo` and `::foo` are not considered ambiguously identical by the compiler. - -Remark: As they are an important Rust 2018 feature, they also get a big subdirectory in `ui/rust-2018/uniform-paths` - -## `tests/ui/uninhabited/`: Uninhabited types - -See [Uninhabited | Reference](https://doc.rust-lang.org/reference/glossary.html?highlight=Uninhabit#uninhabited). - -## `tests/ui/union/` - -See [Unions | Reference](https://doc.rust-lang.org/reference/items/unions.html). - -## `tests/ui/unknown-unstable-lints/`: Attempting to refer to an unstable lint which does not exist - -Tests for trying to use non-existent unstable lints. - -**FIXME**: move this under `tests/ui/lints/`. - -## `tests/ui/unop/`: Unary operators `-`, `*` and `!` - -Tests the three unary operators for negating, dereferencing and inverting, across different contexts. - -## `tests/ui/unpretty/`: `-Z unpretty` command line flag - -The `-Z unpretty` flag outputs various representations of a program's tree in a certain way. - -## `tests/ui/unresolved/` - -Exercises various unresolved errors, ranging from earlier name resolution failures to later method resolution failures. - -## `tests/ui/unsafe/` - -A broad category of tests about unsafe Rust code. - -## `tests/ui/unsafe-binders/`: `#![feature(unsafe_binders)]` - -See [Tracking issue for unsafe binder types #130516](https://github.com/rust-lang/rust/issues/130516). - -## `tests/ui/unsafe-fields/`: `struct`s and `enum`s with an `unsafe` field - -See [Tracking issue for RFC 3458: Unsafe fields #132922](https://github.com/rust-lang/rust/issues/132922). - -## `tests/ui/unsized/`: Zero-sized types, `Sized` trait, object has no known size at compile time - -**FIXME**: between `tests/ui/zero-sized/`, `tests/ui/sized/` and this directory, might need to reorganize them a bit. - -## `tests/ui/unsized-locals/`: `#![feature(unsized_locals, unsized_fn_params)]` - -See: - -- [RFC 1909 Unsized rvalues](https://github.com/rust-lang/rfcs/blob/master/text/1909-unsized-rvalues.md) -- [de-RFC 3829: Remove unsized_locals](https://github.com/rust-lang/rfcs/pull/3829) -- [Tracking issue for RFC #1909: Unsized Rvalues (`unsized_locals`, `unsized_fn_params`)](https://github.com/rust-lang/rust/issues/48055) - -**FIXME**: Seems to also contain more generic tests that fit in `tests/ui/unsized/`. - -## `tests/ui/unused-crate-deps/` - -Exercises the `unused_crate_dependencies` lint. - -## `tests/ui/unwind-abis/` - -**FIXME**: Contains a single test, should likely be rehomed to `tests/ui/abi/`. - -## `tests/ui/use/` - -**FIXME**: merge with `ui/imports`. - -## `tests/ui/variance/`: Covariants, invariants and contravariants - -See [Variance | Reference](https://doc.rust-lang.org/reference/subtyping.html#variance). - -## `tests/ui/variants/`: `enum` variants - -Tests on `enum` variants. - -**FIXME**: Should be rehomed with `tests/ui/enum/`. - -## `tests/ui/version/` - -**FIXME**: Contains a single test described as "Check that rustc accepts various version info flags.", should be rehomed. - -## `tests/ui/warnings/` - -**FIXME**: Contains a single test on non-explicit paths (`::one()`). Should be rehomed probably to `tests/ui/resolve/`. - -## `tests/ui/wasm/` - -These tests target the `wasm32` architecture specifically. They are usually regression tests for WASM-specific bugs which were observed in the past. - -## `tests/ui/wf/`: Well-formedness checking - -Tests on various well-formedness checks, e.g. [Type-checking normal functions](https://rustc-dev-guide.rust-lang.org/traits/lowering-to-logic.html). - -## `tests/ui/where-clauses/` - -Tests on `where` clauses. See [Where clauses | Reference](https://doc.rust-lang.org/reference/items/generics.html#where-clauses). - -## `tests/ui/while/` - -Tests on the `while` keyword and the `while` construct. - -**FIXME**: merge with `ui/for-loop-while`. - -## `tests/ui/windows-subsystem/`: `#![windows_subsystem = ""]` - -See [the `windows_subsystem` attribute](https://doc.rust-lang.org/reference/runtime.html#the-windows_subsystem-attribute). - -## `tests/ui/zero-sized/`: Zero-sized types - -See [Zero-Sized Types | Reference](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts). -- cgit 1.4.1-3-g733a5