From 4983fdaada0c78d48e57f177453e5b954d5caad3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=BD=D0=B0=D0=B1?= Date: Sun, 23 Feb 2025 19:40:57 +0100 Subject: [PATCH 0001/1134] libstd: init(): dup() subsequent /dev/nulls instead of opening them again This will be faster, and also it deduplicates the code so win/win The dup() is actually infallible here. But whatever. Before: poll([{fd=0, events=0}, {fd=1, events=0}, {fd=2, events=0}], 3, 0) = 1 ([{fd=2, revents=POLLNVAL}]) openat(AT_FDCWD, "/dev/null", O_RDWR) = 2 rt_sigaction(SIGPIPE, {sa_handler=SIG_IGN, sa_mask=[PIPE], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7f5749313050}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 poll([{fd=0, events=0}, {fd=1, events=0}, {fd=2, events=0}], 3, 0) = 2 ([{fd=0, revents=POLLNVAL}, {fd=2, revents=POLLNVAL}]) openat(AT_FDCWD, "/dev/null", O_RDWR) = 0 openat(AT_FDCWD, "/dev/null", O_RDWR) = 2 rt_sigaction(SIGPIPE, {sa_handler=SIG_IGN, sa_mask=[PIPE], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7efe12006050}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 poll([{fd=0, events=0}, {fd=1, events=0}, {fd=2, events=0}], 3, 0) = 3 ([{fd=0, revents=POLLNVAL}, {fd=1, revents=POLLNVAL}, {fd=2, revents=POLLNVAL}]) openat(AT_FDCWD, "/dev/null", O_RDWR) = 0 openat(AT_FDCWD, "/dev/null", O_RDWR) = 1 openat(AT_FDCWD, "/dev/null", O_RDWR) = 2 rt_sigaction(SIGPIPE, {sa_handler=SIG_IGN, sa_mask=[PIPE], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7fc2dc7ca050}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 After: poll([{fd=0, events=0}, {fd=1, events=0}, {fd=2, events=0}], 3, 0) = 1 ([{fd=1, revents=POLLNVAL}]) openat(AT_FDCWD, "/dev/null", O_RDWR) = 1 rt_sigaction(SIGPIPE, {sa_handler=SIG_IGN, sa_mask=[PIPE], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7f488a3fb050}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 poll([{fd=0, events=0}, {fd=1, events=0}, {fd=2, events=0}], 3, 0) = 2 ([{fd=1, revents=POLLNVAL}, {fd=2, revents=POLLNVAL}]) openat(AT_FDCWD, "/dev/null", O_RDWR) = 1 dup(1) = 2 rt_sigaction(SIGPIPE, {sa_handler=SIG_IGN, sa_mask=[PIPE], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7f1a8943c050}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 poll([{fd=0, events=0}, {fd=1, events=0}, {fd=2, events=0}], 3, 0) = 3 ([{fd=0, revents=POLLNVAL}, {fd=1, revents=POLLNVAL}, {fd=2, revents=POLLNVAL}]) openat(AT_FDCWD, "/dev/null", O_RDWR) = 0 dup(0) = 1 dup(0) = 2 rt_sigaction(SIGPIPE, {sa_handler=SIG_IGN, sa_mask=[PIPE], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7f4e3a4c7050}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 --- library/std/src/sys/pal/unix/mod.rs | 48 ++++++++++++++--------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index c0b56d8d2b28..ec61fcad7e88 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -61,6 +61,28 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { } unsafe fn sanitize_standard_fds() { + let mut opened_devnull = -1; + let mut open_devnull = || { + #[cfg(not(all(target_os = "linux", target_env = "gnu")))] + use libc::open as open64; + #[cfg(all(target_os = "linux", target_env = "gnu"))] + use libc::open64; + + if opened_devnull != -1 { + if libc::dup(opened_devnull) != -1 { + return; + } + } + opened_devnull = open64(c"/dev/null".as_ptr(), libc::O_RDWR, 0); + if opened_devnull == -1 { + // If the stream is closed but we failed to reopen it, abort the + // process. Otherwise we wouldn't preserve the safety of + // operations on the corresponding Rust object Stdin, Stdout, or + // Stderr. + libc::abort(); + } + }; + // fast path with a single syscall for systems with poll() #[cfg(not(any( miri, @@ -76,11 +98,6 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_vendor = "apple", )))] 'poll: { - #[cfg(not(all(target_os = "linux", target_env = "gnu")))] - use libc::open as open64; - #[cfg(all(target_os = "linux", target_env = "gnu"))] - use libc::open64; - use crate::sys::os::errno; let pfds: &mut [_] = &mut [ libc::pollfd { fd: 0, events: 0, revents: 0 }, @@ -108,13 +125,7 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { if pfd.revents & libc::POLLNVAL == 0 { continue; } - if open64(c"/dev/null".as_ptr(), libc::O_RDWR, 0) == -1 { - // If the stream is closed but we failed to reopen it, abort the - // process. Otherwise we wouldn't preserve the safety of - // operations on the corresponding Rust object Stdin, Stdout, or - // Stderr. - libc::abort(); - } + open_devnull(); } return; } @@ -131,21 +142,10 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_os = "vita", )))] { - #[cfg(not(all(target_os = "linux", target_env = "gnu")))] - use libc::open as open64; - #[cfg(all(target_os = "linux", target_env = "gnu"))] - use libc::open64; - use crate::sys::os::errno; for fd in 0..3 { if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF { - if open64(c"/dev/null".as_ptr(), libc::O_RDWR, 0) == -1 { - // If the stream is closed but we failed to reopen it, abort the - // process. Otherwise we wouldn't preserve the safety of - // operations on the corresponding Rust object Stdin, Stdout, or - // Stderr. - libc::abort(); - } + open_devnull(); } } } From c73cfb83b7b7855f19603420990775ebb3d32d95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=BD=D0=B0=D0=B1?= Date: Wed, 26 Mar 2025 02:08:15 +0100 Subject: [PATCH 0002/1134] #[allow(dead_code)] --- library/std/src/sys/pal/unix/mod.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index ec61fcad7e88..20b670fdd19b 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -61,19 +61,21 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { } unsafe fn sanitize_standard_fds() { + #[allow(dead_code)] let mut opened_devnull = -1; + #[allow(dead_code)] let mut open_devnull = || { #[cfg(not(all(target_os = "linux", target_env = "gnu")))] - use libc::open as open64; + use libc::open; #[cfg(all(target_os = "linux", target_env = "gnu"))] - use libc::open64; + use libc::open64 as open; if opened_devnull != -1 { if libc::dup(opened_devnull) != -1 { return; } } - opened_devnull = open64(c"/dev/null".as_ptr(), libc::O_RDWR, 0); + opened_devnull = open(c"/dev/null".as_ptr(), libc::O_RDWR, 0); if opened_devnull == -1 { // If the stream is closed but we failed to reopen it, abort the // process. Otherwise we wouldn't preserve the safety of From ac761f28d15764887a0a1df4fa9067dcc7e0e94f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=BD=D0=B0=D0=B1?= Date: Sat, 12 Apr 2025 23:20:51 +0200 Subject: [PATCH 0003/1134] =?UTF-8?q?https://github.com/rust-lang/rust/pul?= =?UTF-8?q?l/139717#issuecomment-2799036117=20=F0=9F=A5=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/std/src/sys/pal/unix/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index 20b670fdd19b..ebfc92ebfeee 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -61,9 +61,9 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { } unsafe fn sanitize_standard_fds() { - #[allow(dead_code)] + #[allow(dead_code, unused_variables, unused_mut)] let mut opened_devnull = -1; - #[allow(dead_code)] + #[allow(dead_code, unused_variables, unused_mut)] let mut open_devnull = || { #[cfg(not(all(target_os = "linux", target_env = "gnu")))] use libc::open; From e836a2f5ff6d3317db06891feb3087e6164c282b Mon Sep 17 00:00:00 2001 From: Jonathan Gruner Date: Thu, 24 Apr 2025 21:14:47 +0200 Subject: [PATCH 0004/1134] implement continue_ok and break_ok for ControlFlow --- library/core/src/ops/control_flow.rs | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index 26661b20c12d..ee450209f447 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -187,6 +187,28 @@ impl ControlFlow { } } + /// Converts the `ControlFlow` into an `Result` which is `Ok` if the + /// `ControlFlow` was `Break` and `Err` if otherwise. + /// + /// # Examples + /// + /// ``` + /// #![feature(control_flow_ok)] + /// + /// use std::ops::ControlFlow; + /// + /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").break_ok(), Ok("Stop right there!")); + /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).break_ok(), Err(3)); + /// ``` + #[inline] + #[unstable(feature = "control_flow_ok", issue = "140266")] + pub fn break_ok(self) -> Result { + match self { + ControlFlow::Continue(c) => Err(c), + ControlFlow::Break(b) => Ok(b), + } + } + /// Maps `ControlFlow` to `ControlFlow` by applying a function /// to the break value in case it exists. #[inline] @@ -218,6 +240,28 @@ impl ControlFlow { } } + /// Converts the `ControlFlow` into an `Result` which is `Ok` if the + /// `ControlFlow` was `Continue` and `Err` if otherwise. + /// + /// # Examples + /// + /// ``` + /// #![feature(control_flow_ok)] + /// + /// use std::ops::ControlFlow; + /// + /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").continue_ok(), Err("Stop right there!")); + /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).continue_ok(), Ok(3)); + /// ``` + #[inline] + #[unstable(feature = "control_flow_ok", issue = "140266")] + pub fn continue_ok(self) -> Result { + match self { + ControlFlow::Continue(c) => Ok(c), + ControlFlow::Break(b) => Err(b), + } + } + /// Maps `ControlFlow` to `ControlFlow` by applying a function /// to the continue value in case it exists. #[inline] From b981b84e031b0316c9e1ba244395c7bb2fdb68a9 Mon Sep 17 00:00:00 2001 From: Jonathan Gruner Date: Sat, 26 Apr 2025 12:57:12 +0200 Subject: [PATCH 0005/1134] moved simple test to coretests, introduced more fleshed out doctests for break_ok/continue_ok --- library/core/src/ops/control_flow.rs | 111 +++++++++++++++++++- library/coretests/tests/lib.rs | 1 + library/coretests/tests/ops/control_flow.rs | 12 +++ 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index ee450209f447..7489a8bb6e74 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -197,8 +197,60 @@ impl ControlFlow { /// /// use std::ops::ControlFlow; /// - /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").break_ok(), Ok("Stop right there!")); - /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).break_ok(), Err(3)); + /// struct TreeNode { + /// value: T, + /// left: Option>>, + /// right: Option>>, + /// } + /// + /// impl TreeNode { + /// fn find<'a>(&'a self, mut predicate: impl FnMut(&T) -> bool) -> Result<&'a T, ()> { + /// let mut f = |t: &'a T| -> ControlFlow<&'a T> { + /// if predicate(t) { + /// ControlFlow::Break(t) + /// } else { + /// ControlFlow::Continue(()) + /// } + /// }; + /// + /// self.traverse_inorder(&mut f).break_ok() + /// } + /// + /// fn traverse_inorder<'a, B>( + /// &'a self, + /// f: &mut impl FnMut(&'a T) -> ControlFlow, + /// ) -> ControlFlow { + /// if let Some(left) = &self.left { + /// left.traverse_inorder(f)?; + /// } + /// f(&self.value)?; + /// if let Some(right) = &self.right { + /// right.traverse_inorder(f)?; + /// } + /// ControlFlow::Continue(()) + /// } + /// + /// fn leaf(value: T) -> Option>> { + /// Some(Box::new(Self { + /// value, + /// left: None, + /// right: None, + /// })) + /// } + /// } + /// + /// let node = TreeNode { + /// value: 0, + /// left: TreeNode::leaf(1), + /// right: Some(Box::new(TreeNode { + /// value: -1, + /// left: TreeNode::leaf(5), + /// right: TreeNode::leaf(2), + /// })), + /// }; + /// + /// let res = node.find(|val: &i32| *val > 3); + /// assert_eq!(res, Ok(&5)); /// ``` #[inline] #[unstable(feature = "control_flow_ok", issue = "140266")] @@ -250,8 +302,59 @@ impl ControlFlow { /// /// use std::ops::ControlFlow; /// - /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").continue_ok(), Err("Stop right there!")); - /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).continue_ok(), Ok(3)); + /// struct TreeNode { + /// value: T, + /// left: Option>>, + /// right: Option>>, + /// } + /// + /// impl TreeNode { + /// fn validate(&self, f: &mut impl FnMut(&T) -> ControlFlow) -> Result<(), B> { + /// self.traverse_inorder(f).continue_ok() + /// } + /// + /// fn traverse_inorder(&self, f: &mut impl FnMut(&T) -> ControlFlow) -> ControlFlow { + /// if let Some(left) = &self.left { + /// left.traverse_inorder(f)?; + /// } + /// f(&self.value)?; + /// if let Some(right) = &self.right { + /// right.traverse_inorder(f)?; + /// } + /// ControlFlow::Continue(()) + /// } + /// + /// fn leaf(value: T) -> Option>> { + /// Some(Box::new(Self { + /// value, + /// left: None, + /// right: None, + /// })) + /// } + /// } + /// + /// let node = TreeNode { + /// value: 0, + /// left: TreeNode::leaf(1), + /// right: Some(Box::new(TreeNode { + /// value: -1, + /// left: TreeNode::leaf(5), + /// right: TreeNode::leaf(2), + /// })), + /// }; + /// + /// let res = node.validate(&mut |val| { + /// if *val < 0 { + /// return ControlFlow::Break("negative value detected"); + /// } + /// + /// if *val > 4 { + /// return ControlFlow::Break("too big value detected"); + /// } + /// + /// ControlFlow::Continue(()) + /// }); + /// assert_eq!(res, Err("too big value detected")); /// ``` #[inline] #[unstable(feature = "control_flow_ok", issue = "140266")] diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 0a9c0c61c958..a0c594d2d596 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -22,6 +22,7 @@ #![feature(const_ref_cell)] #![feature(const_result_trait_fn)] #![feature(const_trait_impl)] +#![feature(control_flow_ok)] #![feature(core_float_math)] #![feature(core_intrinsics)] #![feature(core_intrinsics_fallbacks)] diff --git a/library/coretests/tests/ops/control_flow.rs b/library/coretests/tests/ops/control_flow.rs index eacfd63a6c48..1df6599ac4a5 100644 --- a/library/coretests/tests/ops/control_flow.rs +++ b/library/coretests/tests/ops/control_flow.rs @@ -16,3 +16,15 @@ fn control_flow_discriminants_match_result() { discriminant_value(&Result::::Ok(3)), ); } + +#[test] +fn control_flow_break_ok() { + assert_eq!(ControlFlow::::Break('b').break_ok(), Ok('b')); + assert_eq!(ControlFlow::::Continue(3).break_ok(), Err(3)); +} + +#[test] +fn control_flow_continue_ok() { + assert_eq!(ControlFlow::::Break('b').continue_ok(), Err('b')); + assert_eq!(ControlFlow::::Continue(3).continue_ok(), Ok(3)); +} From 1ddb4d0062fbe55b88e55cffc00fe8b898512536 Mon Sep 17 00:00:00 2001 From: Michael Rieder Date: Fri, 4 Apr 2025 10:01:37 +0200 Subject: [PATCH 0006/1134] Fix parameter order for `_by()` variants of `min` / `max`/ `minmax` in `std::cmp` --- library/core/src/cmp.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index c315131f4136..b407dc5f6ef1 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -1552,6 +1552,9 @@ pub fn min(v1: T, v2: T) -> T { /// /// Returns the first argument if the comparison determines them to be equal. /// +/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is +/// always passed as the first argument and `v2` as the second. +/// /// # Examples /// /// ``` @@ -1567,12 +1570,17 @@ pub fn min(v1: T, v2: T) -> T { /// /// let result = cmp::min_by(1, -1, abs_cmp); /// assert_eq!(result, 1); +/// +/// let rhs_abs_cmp = |x: &i32, y: &i32| x.cmp(&y.abs()); +/// +/// let result = cmp::min_by(-2, 1, rhs_abs_cmp); +/// assert_eq!(result, -2); /// ``` #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T { - if compare(&v2, &v1).is_lt() { v2 } else { v1 } + if compare(&v1, &v2).is_le() { v1 } else { v2 } } /// Returns the element that gives the minimum value from the specified function. @@ -1644,6 +1652,9 @@ pub fn max(v1: T, v2: T) -> T { /// /// Returns the second argument if the comparison determines them to be equal. /// +/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is +/// always passed as the first argument and `v2` as the second. +/// /// # Examples /// /// ``` @@ -1659,12 +1670,17 @@ pub fn max(v1: T, v2: T) -> T { /// /// let result = cmp::max_by(1, -1, abs_cmp); /// assert_eq!(result, -1); +/// +/// let rhs_abs_cmp = |x: &i32, y: &i32| x.cmp(&y.abs()); +/// +/// let result = cmp::max_by(-2, 1, rhs_abs_cmp); +/// assert_eq!(result, 1); /// ``` #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { - if compare(&v2, &v1).is_lt() { v1 } else { v2 } + if compare(&v1, &v2).is_gt() { v1 } else { v2 } } /// Returns the element that gives the maximum value from the specified function. @@ -1743,6 +1759,9 @@ where /// /// Returns `[v1, v2]` if the comparison determines them to be equal. /// +/// The parameter order is preserved when calling the `compare` function, i.e. `v1` is +/// always passed as the first argument and `v2` as the second. +/// /// # Examples /// /// ``` @@ -1755,6 +1774,10 @@ where /// assert_eq!(cmp::minmax_by(-1, 2, abs_cmp), [-1, 2]); /// assert_eq!(cmp::minmax_by(-2, 2, abs_cmp), [-2, 2]); /// +/// let rhs_abs_cmp = |x: &i32, y: &i32| x.cmp(&y.abs()); +/// +/// assert_eq!(cmp::minmax_by(-2, 1, rhs_abs_cmp), [-2, 1]); +/// /// // You can destructure the result using array patterns /// let [min, max] = cmp::minmax_by(-42, 17, abs_cmp); /// assert_eq!(min, 17); @@ -1767,7 +1790,7 @@ pub fn minmax_by(v1: T, v2: T, compare: F) -> [T; 2] where F: FnOnce(&T, &T) -> Ordering, { - if compare(&v2, &v1).is_lt() { [v2, v1] } else { [v1, v2] } + if compare(&v1, &v2).is_le() { [v1, v2] } else { [v2, v1] } } /// Returns minimum and maximum values with respect to the specified key function. From aab1563d42ed7cf54b017ad414f95fa45526f566 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Sun, 18 Dec 2022 19:36:39 +0100 Subject: [PATCH 0007/1134] `impl PartialEq<{str,String}> for {Path,PathBuf}` Comparison of paths and strings is expected to be possible and needed e.g. in tests. This change adds the impls os `PartialEq` between strings and paths, both owned and unsized, in both directions. ACP: https://github.com/rust-lang/libs-team/issues/151 --- library/std/src/path.rs | 65 +++++++++++++++++++ tests/ui/inference/issue-72616.stderr | 12 ++-- .../partialeq_suggest_swap_on_e0277.stderr | 2 + 3 files changed, 71 insertions(+), 8 deletions(-) diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 1a4a7aa7448c..30b12a0e7967 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -2068,6 +2068,38 @@ impl PartialEq for PathBuf { } } +#[stable(feature = "eq_str_for_path", since = "CURRENT_RUSTC_VERSION")] +impl cmp::PartialEq for PathBuf { + #[inline] + fn eq(&self, other: &str) -> bool { + &*self == other + } +} + +#[stable(feature = "eq_str_for_path", since = "CURRENT_RUSTC_VERSION")] +impl cmp::PartialEq for str { + #[inline] + fn eq(&self, other: &PathBuf) -> bool { + other == self + } +} + +#[stable(feature = "eq_str_for_path", since = "CURRENT_RUSTC_VERSION")] +impl cmp::PartialEq for PathBuf { + #[inline] + fn eq(&self, other: &String) -> bool { + **self == **other + } +} + +#[stable(feature = "eq_str_for_path", since = "CURRENT_RUSTC_VERSION")] +impl cmp::PartialEq for String { + #[inline] + fn eq(&self, other: &PathBuf) -> bool { + other == self + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl Hash for PathBuf { fn hash(&self, h: &mut H) { @@ -3242,6 +3274,39 @@ impl PartialEq for Path { } } +#[stable(feature = "eq_str_for_path", since = "CURRENT_RUSTC_VERSION")] +impl cmp::PartialEq for Path { + #[inline] + fn eq(&self, other: &str) -> bool { + let other: &OsStr = other.as_ref(); + self == other + } +} + +#[stable(feature = "eq_str_for_path", since = "CURRENT_RUSTC_VERSION")] +impl cmp::PartialEq for str { + #[inline] + fn eq(&self, other: &Path) -> bool { + other == self + } +} + +#[stable(feature = "eq_str_for_path", since = "CURRENT_RUSTC_VERSION")] +impl cmp::PartialEq for Path { + #[inline] + fn eq(&self, other: &String) -> bool { + self == &*other + } +} + +#[stable(feature = "eq_str_for_path", since = "CURRENT_RUSTC_VERSION")] +impl cmp::PartialEq for String { + #[inline] + fn eq(&self, other: &Path) -> bool { + other == self + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl Hash for Path { fn hash(&self, h: &mut H) { diff --git a/tests/ui/inference/issue-72616.stderr b/tests/ui/inference/issue-72616.stderr index 31a0586301df..a271639996fd 100644 --- a/tests/ui/inference/issue-72616.stderr +++ b/tests/ui/inference/issue-72616.stderr @@ -6,14 +6,10 @@ LL | if String::from("a") == "a".try_into().unwrap() {} | | | type must be known at this point | - = note: cannot satisfy `String: PartialEq<_>` - = help: the following types implement trait `PartialEq`: - `String` implements `PartialEq<&str>` - `String` implements `PartialEq` - `String` implements `PartialEq` - `String` implements `PartialEq>` - `String` implements `PartialEq` - `String` implements `PartialEq` + = note: multiple `impl`s satisfying `String: PartialEq<_>` found in the following crates: `alloc`, `std`: + - impl PartialEq for String; + - impl PartialEq for String; + - impl PartialEq for String; help: try using a fully qualified path to specify the expected types | LL - if String::from("a") == "a".try_into().unwrap() {} diff --git a/tests/ui/suggestions/partialeq_suggest_swap_on_e0277.stderr b/tests/ui/suggestions/partialeq_suggest_swap_on_e0277.stderr index ebe103ef19a1..c5984f53f68b 100644 --- a/tests/ui/suggestions/partialeq_suggest_swap_on_e0277.stderr +++ b/tests/ui/suggestions/partialeq_suggest_swap_on_e0277.stderr @@ -10,6 +10,8 @@ LL | String::from("Girls Band Cry") == T(String::from("Girls Band Cry")); `String` implements `PartialEq` `String` implements `PartialEq` `String` implements `PartialEq>` + `String` implements `PartialEq` + `String` implements `PartialEq` `String` implements `PartialEq` `String` implements `PartialEq` = note: `T` implements `PartialEq` From 8c6eea85a171bdd54811f5562884e8e706da34ce Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Sat, 8 Feb 2025 19:47:27 -0500 Subject: [PATCH 0008/1134] Extend `implicit_clone` to handle `to_string` calls --- clippy_lints/src/methods/implicit_clone.rs | 4 +--- clippy_lints/src/methods/mod.rs | 2 +- clippy_lints/src/methods/unnecessary_to_owned.rs | 4 ++-- tests/ui/implicit_clone.fixed | 6 ++++++ tests/ui/implicit_clone.rs | 6 ++++++ tests/ui/implicit_clone.stderr | 14 +++++++++++++- tests/ui/string_to_string.fixed | 8 ++++++++ tests/ui/string_to_string.rs | 4 ++-- tests/ui/string_to_string.stderr | 9 ++++----- 9 files changed, 43 insertions(+), 14 deletions(-) create mode 100644 tests/ui/string_to_string.fixed diff --git a/clippy_lints/src/methods/implicit_clone.rs b/clippy_lints/src/methods/implicit_clone.rs index 9724463f0c08..adb2002feea9 100644 --- a/clippy_lints/src/methods/implicit_clone.rs +++ b/clippy_lints/src/methods/implicit_clone.rs @@ -40,14 +40,12 @@ pub fn check(cx: &LateContext<'_>, method_name: Symbol, expr: &hir::Expr<'_>, re } /// Returns true if the named method can be used to clone the receiver. -/// Note that `to_string` is not flagged by `implicit_clone`. So other lints that call -/// `is_clone_like` and that do flag `to_string` must handle it separately. See, e.g., -/// `is_to_owned_like` in `unnecessary_to_owned.rs`. pub fn is_clone_like(cx: &LateContext<'_>, method_name: Symbol, method_def_id: hir::def_id::DefId) -> bool { match method_name { sym::to_os_string => is_diag_item_method(cx, method_def_id, sym::OsStr), sym::to_owned => is_diag_trait_item(cx, method_def_id, sym::ToOwned), sym::to_path_buf => is_diag_item_method(cx, method_def_id, sym::Path), + sym::to_string => is_diag_trait_item(cx, method_def_id, sym::ToString), sym::to_vec => cx .tcx .impl_of_method(method_def_id) diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index d2d59f0013c0..a79ccba19e15 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -5403,7 +5403,7 @@ impl Methods { implicit_clone::check(cx, name, expr, recv); } }, - (sym::to_os_string | sym::to_path_buf | sym::to_vec, []) => { + (sym::to_os_string | sym::to_path_buf | sym::to_string | sym::to_vec, []) => { implicit_clone::check(cx, name, expr, recv); }, (sym::type_id, []) => { diff --git a/clippy_lints/src/methods/unnecessary_to_owned.rs b/clippy_lints/src/methods/unnecessary_to_owned.rs index 29a0d2950bc6..74cb95359c59 100644 --- a/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -619,8 +619,8 @@ fn is_cloned_or_copied(cx: &LateContext<'_>, method_name: Symbol, method_def_id: /// Returns true if the named method can be used to convert the receiver to its "owned" /// representation. fn is_to_owned_like<'a>(cx: &LateContext<'a>, call_expr: &Expr<'a>, method_name: Symbol, method_def_id: DefId) -> bool { - is_clone_like(cx, method_name, method_def_id) - || is_cow_into_owned(cx, method_name, method_def_id) + is_cow_into_owned(cx, method_name, method_def_id) + || (method_name != sym::to_string && is_clone_like(cx, method_name, method_def_id)) || is_to_string_on_string_like(cx, call_expr, method_name, method_def_id) } diff --git a/tests/ui/implicit_clone.fixed b/tests/ui/implicit_clone.fixed index d60d1cb0ec04..267514c5f3d3 100644 --- a/tests/ui/implicit_clone.fixed +++ b/tests/ui/implicit_clone.fixed @@ -135,4 +135,10 @@ fn main() { } let no_clone = &NoClone; let _ = no_clone.to_owned(); + + let s = String::from("foo"); + let _ = s.clone(); + //~^ implicit_clone + let _ = s.clone(); + //~^ implicit_clone } diff --git a/tests/ui/implicit_clone.rs b/tests/ui/implicit_clone.rs index b96828f28c82..fba954026e7f 100644 --- a/tests/ui/implicit_clone.rs +++ b/tests/ui/implicit_clone.rs @@ -135,4 +135,10 @@ fn main() { } let no_clone = &NoClone; let _ = no_clone.to_owned(); + + let s = String::from("foo"); + let _ = s.to_owned(); + //~^ implicit_clone + let _ = s.to_string(); + //~^ implicit_clone } diff --git a/tests/ui/implicit_clone.stderr b/tests/ui/implicit_clone.stderr index 1eb6ff1fe429..4cca9b0d0c07 100644 --- a/tests/ui/implicit_clone.stderr +++ b/tests/ui/implicit_clone.stderr @@ -67,5 +67,17 @@ error: implicitly cloning a `PathBuf` by calling `to_path_buf` on its dereferenc LL | let _ = pathbuf_ref.to_path_buf(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `(**pathbuf_ref).clone()` -error: aborting due to 11 previous errors +error: implicitly cloning a `String` by calling `to_owned` on its dereferenced type + --> tests/ui/implicit_clone.rs:140:13 + | +LL | let _ = s.to_owned(); + | ^^^^^^^^^^^^ help: consider using: `s.clone()` + +error: implicitly cloning a `String` by calling `to_string` on its dereferenced type + --> tests/ui/implicit_clone.rs:142:13 + | +LL | let _ = s.to_string(); + | ^^^^^^^^^^^^^ help: consider using: `s.clone()` + +error: aborting due to 13 previous errors diff --git a/tests/ui/string_to_string.fixed b/tests/ui/string_to_string.fixed new file mode 100644 index 000000000000..354b6c7c9fb6 --- /dev/null +++ b/tests/ui/string_to_string.fixed @@ -0,0 +1,8 @@ +#![warn(clippy::implicit_clone)] +#![allow(clippy::redundant_clone)] + +fn main() { + let mut message = String::from("Hello"); + let mut v = message.clone(); + //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type +} diff --git a/tests/ui/string_to_string.rs b/tests/ui/string_to_string.rs index 7c5bd8a897ba..43a1cc18cd06 100644 --- a/tests/ui/string_to_string.rs +++ b/tests/ui/string_to_string.rs @@ -1,10 +1,10 @@ -#![warn(clippy::string_to_string)] +#![warn(clippy::implicit_clone, clippy::string_to_string)] #![allow(clippy::redundant_clone, clippy::unnecessary_literal_unwrap)] fn main() { let mut message = String::from("Hello"); let mut v = message.to_string(); - //~^ string_to_string + //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type let variable1 = String::new(); let v = &variable1; diff --git a/tests/ui/string_to_string.stderr b/tests/ui/string_to_string.stderr index 99eea06f18eb..0e33c6c1bf35 100644 --- a/tests/ui/string_to_string.stderr +++ b/tests/ui/string_to_string.stderr @@ -1,12 +1,11 @@ -error: `to_string()` called on a `String` +error: implicitly cloning a `String` by calling `to_string` on its dereferenced type --> tests/ui/string_to_string.rs:6:17 | LL | let mut v = message.to_string(); - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^ help: consider using: `message.clone()` | - = help: consider using `.clone()` - = note: `-D clippy::string-to-string` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::string_to_string)]` + = note: `-D clippy::implicit-clone` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::implicit_clone)]` error: `to_string()` called on a `String` --> tests/ui/string_to_string.rs:14:9 From 8a9adba8525e7bf40ca5f3b08d359742173f6fa7 Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Sat, 8 Feb 2025 19:29:02 -0500 Subject: [PATCH 0009/1134] Fix adjacent code --- clippy_lints/src/blocks_in_conditions.rs | 3 +-- clippy_lints/src/copies.rs | 6 +++--- clippy_lints/src/if_not_else.rs | 2 +- clippy_lints/src/manual_async_fn.rs | 2 +- clippy_lints/src/matches/match_single_binding.rs | 4 +--- clippy_lints/src/matches/single_match.rs | 8 +++----- clippy_lints/src/methods/unnecessary_sort_by.rs | 2 +- clippy_lints/src/redundant_else.rs | 2 +- lintcheck/src/input.rs | 2 +- lintcheck/src/output.rs | 2 +- 10 files changed, 14 insertions(+), 19 deletions(-) diff --git a/clippy_lints/src/blocks_in_conditions.rs b/clippy_lints/src/blocks_in_conditions.rs index 011962846cb3..10fe1a4174f8 100644 --- a/clippy_lints/src/blocks_in_conditions.rs +++ b/clippy_lints/src/blocks_in_conditions.rs @@ -100,8 +100,7 @@ impl<'tcx> LateLintPass<'tcx> for BlocksInConditions { cond.span, BRACED_EXPR_MESSAGE, "try", - snippet_block_with_applicability(cx, ex.span, "..", Some(expr.span), &mut applicability) - .to_string(), + snippet_block_with_applicability(cx, ex.span, "..", Some(expr.span), &mut applicability), applicability, ); } diff --git a/clippy_lints/src/copies.rs b/clippy_lints/src/copies.rs index 2467fc95fd05..6cffb508fe64 100644 --- a/clippy_lints/src/copies.rs +++ b/clippy_lints/src/copies.rs @@ -245,9 +245,9 @@ fn lint_branches_sharing_code<'tcx>( let cond_snippet = reindent_multiline(&snippet(cx, cond_span, "_"), false, None); let cond_indent = indent_of(cx, cond_span); let moved_snippet = reindent_multiline(&snippet(cx, span, "_"), true, None); - let suggestion = moved_snippet.to_string() + "\n" + &cond_snippet + "{"; + let suggestion = moved_snippet + "\n" + &cond_snippet + "{"; let suggestion = reindent_multiline(&suggestion, true, cond_indent); - (replace_span, suggestion.to_string()) + (replace_span, suggestion) }); let end_suggestion = res.end_span(last_block, sm).map(|span| { let moved_snipped = reindent_multiline(&snippet(cx, span, "_"), true, None); @@ -263,7 +263,7 @@ fn lint_branches_sharing_code<'tcx>( .then_some(range.start - 4..range.end) }) .map_or(span, |range| range.with_ctxt(span.ctxt())); - (span, suggestion.to_string()) + (span, suggestion.clone()) }); let (span, msg, end_span) = match (&start_suggestion, &end_suggestion) { diff --git a/clippy_lints/src/if_not_else.rs b/clippy_lints/src/if_not_else.rs index 45f9aa0a53e4..5e7eb26a4f90 100644 --- a/clippy_lints/src/if_not_else.rs +++ b/clippy_lints/src/if_not_else.rs @@ -89,7 +89,7 @@ impl LateLintPass<'_> for IfNotElse { e.span, msg, "try", - make_sugg(cx, &cond.kind, cond_inner.span, els.span, "..", Some(e.span)).to_string(), + make_sugg(cx, &cond.kind, cond_inner.span, els.span, "..", Some(e.span)), Applicability::MachineApplicable, ), _ => span_lint_and_help(cx, IF_NOT_ELSE, e.span, msg, None, help), diff --git a/clippy_lints/src/manual_async_fn.rs b/clippy_lints/src/manual_async_fn.rs index abd1ac954cda..ba1ad599e116 100644 --- a/clippy_lints/src/manual_async_fn.rs +++ b/clippy_lints/src/manual_async_fn.rs @@ -83,7 +83,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn { format!("{} async {}", vis_snip, &header_snip[vis_snip.len() + 1..ret_pos]) }; - let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block.span)).to_string(); + let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block.span)); diag.multipart_suggestion( "make the function `async` and return the output of the future directly", diff --git a/clippy_lints/src/matches/match_single_binding.rs b/clippy_lints/src/matches/match_single_binding.rs index adda35869900..5c2837d6b1a0 100644 --- a/clippy_lints/src/matches/match_single_binding.rs +++ b/clippy_lints/src/matches/match_single_binding.rs @@ -25,9 +25,7 @@ pub(crate) fn check<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], e let match_body = peel_blocks(arms[0].body); let mut app = Applicability::MaybeIncorrect; let ctxt = expr.span.ctxt(); - let mut snippet_body = snippet_block_with_context(cx, match_body.span, ctxt, "..", Some(expr.span), &mut app) - .0 - .to_string(); + let mut snippet_body = snippet_block_with_context(cx, match_body.span, ctxt, "..", Some(expr.span), &mut app).0; // Do we need to add ';' to suggestion ? if let Node::Stmt(stmt) = cx.tcx.parent_hir_node(expr.hir_id) diff --git a/clippy_lints/src/matches/single_match.rs b/clippy_lints/src/matches/single_match.rs index 08c0caa4266c..7c0cd6ee0dea 100644 --- a/clippy_lints/src/matches/single_match.rs +++ b/clippy_lints/src/matches/single_match.rs @@ -112,9 +112,7 @@ fn report_single_pattern( let (sugg, help) = if is_unit_expr(arm.body) { (String::new(), "`match` expression can be removed") } else { - let mut sugg = snippet_block_with_context(cx, arm.body.span, ctxt, "..", Some(expr.span), &mut app) - .0 - .to_string(); + let mut sugg = snippet_block_with_context(cx, arm.body.span, ctxt, "..", Some(expr.span), &mut app).0; if let Node::Stmt(stmt) = cx.tcx.parent_hir_node(expr.hir_id) && let StmtKind::Expr(_) = stmt.kind && match arm.body.kind { @@ -127,7 +125,7 @@ fn report_single_pattern( (sugg, "try") }; span_lint_and_then(cx, lint, expr.span, msg, |diag| { - diag.span_suggestion(expr.span, help, sugg.to_string(), app); + diag.span_suggestion(expr.span, help, sugg, app); note(diag); }); return; @@ -183,7 +181,7 @@ fn report_single_pattern( }; span_lint_and_then(cx, lint, expr.span, msg, |diag| { - diag.span_suggestion(expr.span, "try", sugg.to_string(), app); + diag.span_suggestion(expr.span, "try", sugg, app); note(diag); }); } diff --git a/clippy_lints/src/methods/unnecessary_sort_by.rs b/clippy_lints/src/methods/unnecessary_sort_by.rs index 235fdac29433..437f353746f5 100644 --- a/clippy_lints/src/methods/unnecessary_sort_by.rs +++ b/clippy_lints/src/methods/unnecessary_sort_by.rs @@ -216,7 +216,7 @@ pub(super) fn check<'tcx>( { format!("{}::cmp::Reverse({})", std_or_core, trigger.closure_body) } else { - trigger.closure_body.to_string() + trigger.closure_body }, ), if trigger.reverse { diff --git a/clippy_lints/src/redundant_else.rs b/clippy_lints/src/redundant_else.rs index a3be16ed858e..79353dc9247e 100644 --- a/clippy_lints/src/redundant_else.rs +++ b/clippy_lints/src/redundant_else.rs @@ -97,7 +97,7 @@ impl EarlyLintPass for RedundantElse { els.span.with_lo(then.span.hi()), "redundant else block", "remove the `else` block and move the contents out", - make_sugg(cx, els.span, "..", Some(expr.span)).to_string(), + make_sugg(cx, els.span, "..", Some(expr.span)), app, ); } diff --git a/lintcheck/src/input.rs b/lintcheck/src/input.rs index 83eb0a577d6b..60182fc2293a 100644 --- a/lintcheck/src/input.rs +++ b/lintcheck/src/input.rs @@ -117,7 +117,7 @@ pub fn read_crates(toml_path: &Path) -> (Vec, RecursiveOptions) crate_sources.push(CrateWithSource { name: tk.name.clone(), source: CrateSource::CratesIo { - version: version.to_string(), + version: version.clone(), }, file_link: tk.file_link(DEFAULT_DOCS_LINK), options: tk.options.clone(), diff --git a/lintcheck/src/output.rs b/lintcheck/src/output.rs index dcc1ec339ef9..e38e21015702 100644 --- a/lintcheck/src/output.rs +++ b/lintcheck/src/output.rs @@ -220,7 +220,7 @@ fn print_stats(old_stats: HashMap, new_stats: HashMap<&String, us let same_in_both_hashmaps = old_stats .iter() .filter(|(old_key, old_val)| new_stats.get::<&String>(old_key) == Some(old_val)) - .map(|(k, v)| (k.to_string(), *v)) + .map(|(k, v)| (k.clone(), *v)) .collect::>(); let mut old_stats_deduped = old_stats; From 8e5b0cdae1aaffcee5455852cb0eec0c6b56b17f Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Thu, 20 Mar 2025 14:01:04 -0400 Subject: [PATCH 0010/1134] Account for changes from issue 14396 --- clippy_lints/src/strings.rs | 16 ++-------------- tests/ui/string_to_string.fixed | 17 +++++++++++++++-- tests/ui/string_to_string.rs | 4 ++-- tests/ui/string_to_string.stderr | 12 ++++-------- 4 files changed, 23 insertions(+), 26 deletions(-) diff --git a/clippy_lints/src/strings.rs b/clippy_lints/src/strings.rs index 73a9fe71e001..9fcef84eeb34 100644 --- a/clippy_lints/src/strings.rs +++ b/clippy_lints/src/strings.rs @@ -494,21 +494,9 @@ impl<'tcx> LateLintPass<'tcx> for StringToString { if path.ident.name == sym::to_string && let ty = cx.typeck_results().expr_ty(self_arg) && is_type_lang_item(cx, ty.peel_refs(), LangItem::String) + && let Some(parent_span) = is_called_from_map_like(cx, expr) { - if let Some(parent_span) = is_called_from_map_like(cx, expr) { - suggest_cloned_string_to_string(cx, parent_span); - } else { - #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] - span_lint_and_then( - cx, - STRING_TO_STRING, - expr.span, - "`to_string()` called on a `String`", - |diag| { - diag.help("consider using `.clone()`"); - }, - ); - } + suggest_cloned_string_to_string(cx, parent_span); } }, ExprKind::Path(QPath::TypeRelative(ty, segment)) => { diff --git a/tests/ui/string_to_string.fixed b/tests/ui/string_to_string.fixed index 354b6c7c9fb6..751f451cb685 100644 --- a/tests/ui/string_to_string.fixed +++ b/tests/ui/string_to_string.fixed @@ -1,8 +1,21 @@ -#![warn(clippy::implicit_clone)] -#![allow(clippy::redundant_clone)] +#![warn(clippy::implicit_clone, clippy::string_to_string)] +#![allow(clippy::redundant_clone, clippy::unnecessary_literal_unwrap)] fn main() { let mut message = String::from("Hello"); let mut v = message.clone(); //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type + + let variable1 = String::new(); + let v = &variable1; + let variable2 = Some(v); + let _ = variable2.map(|x| { + println!(); + x.clone() + //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type + }); + + let x = Some(String::new()); + let _ = x.unwrap_or_else(|| v.clone()); + //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type } diff --git a/tests/ui/string_to_string.rs b/tests/ui/string_to_string.rs index 43a1cc18cd06..d519677d59ec 100644 --- a/tests/ui/string_to_string.rs +++ b/tests/ui/string_to_string.rs @@ -12,10 +12,10 @@ fn main() { let _ = variable2.map(|x| { println!(); x.to_string() + //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type }); - //~^^ string_to_string let x = Some(String::new()); let _ = x.unwrap_or_else(|| v.to_string()); - //~^ string_to_string + //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type } diff --git a/tests/ui/string_to_string.stderr b/tests/ui/string_to_string.stderr index 0e33c6c1bf35..220fe3170c6e 100644 --- a/tests/ui/string_to_string.stderr +++ b/tests/ui/string_to_string.stderr @@ -7,21 +7,17 @@ LL | let mut v = message.to_string(); = note: `-D clippy::implicit-clone` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::implicit_clone)]` -error: `to_string()` called on a `String` +error: implicitly cloning a `String` by calling `to_string` on its dereferenced type --> tests/ui/string_to_string.rs:14:9 | LL | x.to_string() - | ^^^^^^^^^^^^^ - | - = help: consider using `.clone()` + | ^^^^^^^^^^^^^ help: consider using: `x.clone()` -error: `to_string()` called on a `String` +error: implicitly cloning a `String` by calling `to_string` on its dereferenced type --> tests/ui/string_to_string.rs:19:33 | LL | let _ = x.unwrap_or_else(|| v.to_string()); - | ^^^^^^^^^^^^^ - | - = help: consider using `.clone()` + | ^^^^^^^^^^^^^ help: consider using: `v.clone()` error: aborting due to 3 previous errors From 6cea9ccf0f256e00936baf1db0cfbb223a5e8812 Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Mon, 10 Mar 2025 22:55:21 +0000 Subject: [PATCH 0011/1134] Replace `string_to_string` with `char_lit_as_u8` in driver.sh --- .github/driver.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/driver.sh b/.github/driver.sh index 5a81b4112918..2874aaf2110c 100755 --- a/.github/driver.sh +++ b/.github/driver.sh @@ -47,9 +47,9 @@ unset CARGO_MANIFEST_DIR # Run a lint and make sure it produces the expected output. It's also expected to exit with code 1 # FIXME: How to match the clippy invocation in compile-test.rs? -./target/debug/clippy-driver -Dwarnings -Aunused -Zui-testing --emit metadata --crate-type bin tests/ui/string_to_string.rs 2>string_to_string.stderr && exit 1 -sed -e "/= help: for/d" string_to_string.stderr > normalized.stderr -diff -u normalized.stderr tests/ui/string_to_string.stderr +./target/debug/clippy-driver -Dwarnings -Aunused -Zui-testing --emit metadata --crate-type bin tests/ui/char_lit_as_u8.rs 2>char_lit_as_u8.stderr && exit 1 +sed -e "/= help: for/d" char_lit_as_u8.stderr > normalized.stderr +diff -u normalized.stderr tests/ui/char_lit_as_u8.stderr # make sure "clippy-driver --rustc --arg" and "rustc --arg" behave the same SYSROOT=$(rustc --print sysroot) From d78e7628d1376d1fe1feaff4079f590ba305aac9 Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 25 Apr 2025 15:26:52 -0500 Subject: [PATCH 0012/1134] scrape-examples.js: give each function a signature --- .../html/static/js/scrape-examples.js | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/librustdoc/html/static/js/scrape-examples.js b/src/librustdoc/html/static/js/scrape-examples.js index d641405c8753..7ffa5d5b42a7 100644 --- a/src/librustdoc/html/static/js/scrape-examples.js +++ b/src/librustdoc/html/static/js/scrape-examples.js @@ -1,7 +1,4 @@ -/* global addClass, hasClass, removeClass, onEachLazy */ - -// Eventually fix this. -// @ts-nocheck +/* global addClass, hasClass, removeClass, onEachLazy, nonnull */ "use strict"; @@ -14,7 +11,12 @@ const DEFAULT_MAX_LINES = 5; const HIDDEN_MAX_LINES = 10; - // Scroll code block to the given code location + /** + * Scroll code block to the given code location + * @param {HTMLElement} elt + * @param {[number, number]} loc + * @param {boolean} isHidden + */ function scrollToLoc(elt, loc, isHidden) { const lines = elt.querySelectorAll("[data-nosnippet]"); let scrollOffset; @@ -35,10 +37,15 @@ scrollOffset = offsetMid - halfHeight; } - lines[0].parentElement.scrollTo(0, scrollOffset); - elt.querySelector(".rust").scrollTo(0, scrollOffset); + nonnull(lines[0].parentElement).scrollTo(0, scrollOffset); + nonnull(elt.querySelector(".rust")).scrollTo(0, scrollOffset); } + /** + * @param {HTMLElement} parent + * @param {string} className + * @param {string} content + */ function createScrapeButton(parent, className, content) { const button = document.createElement("button"); button.className = className; @@ -50,14 +57,15 @@ window.updateScrapedExample = (example, buttonHolder) => { let locIndex = 0; const highlights = Array.prototype.slice.call(example.querySelectorAll(".highlight")); - const link = example.querySelector(".scraped-example-title a"); + const link = nonnull(example.querySelector(".scraped-example-title a")); let expandButton = null; if (!example.classList.contains("expanded")) { expandButton = createScrapeButton(buttonHolder, "expand", "Show all"); } - const isHidden = example.parentElement.classList.contains("more-scraped-examples"); + const isHidden = nonnull(example.parentElement).classList.contains("more-scraped-examples"); + // @ts-expect-error const locs = example.locs; if (locs.length > 1) { const next = createScrapeButton(buttonHolder, "next", "Next usage"); @@ -106,7 +114,14 @@ } }; + /** + * Intitialize the `locs` field + * + * @param {HTMLElement} example + * @param {boolean} isHidden + */ function setupLoc(example, isHidden) { + // @ts-expect-error example.locs = JSON.parse(example.attributes.getNamedItem("data-locs").textContent); // Start with the first example in view scrollToLoc(example, example.locs[0][0], isHidden); From b4c77e12408a3ae05ef6779eff0d8af3613716e4 Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 25 Apr 2025 16:16:18 -0500 Subject: [PATCH 0013/1134] rustdoc js: add ScrapedLoc type --- src/librustdoc/html/static/js/rustdoc.d.ts | 7 +++++++ src/librustdoc/html/static/js/scrape-examples.js | 13 +++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/librustdoc/html/static/js/rustdoc.d.ts b/src/librustdoc/html/static/js/rustdoc.d.ts index 0d2e19e019f3..a10f72414920 100644 --- a/src/librustdoc/html/static/js/rustdoc.d.ts +++ b/src/librustdoc/html/static/js/rustdoc.d.ts @@ -491,4 +491,11 @@ declare namespace rustdoc { options?: string[], default: string | boolean, } + + /** + * Single element in the data-locs field of a scraped example. + * First field is the start and end char index, + * other fields seem to be unused. + */ + type ScrapedLoc = [[number, number], string, string] } diff --git a/src/librustdoc/html/static/js/scrape-examples.js b/src/librustdoc/html/static/js/scrape-examples.js index 7ffa5d5b42a7..32642799d887 100644 --- a/src/librustdoc/html/static/js/scrape-examples.js +++ b/src/librustdoc/html/static/js/scrape-examples.js @@ -18,6 +18,9 @@ * @param {boolean} isHidden */ function scrollToLoc(elt, loc, isHidden) { + /** @type {HTMLElement[]} */ + // blocked on https://github.com/microsoft/TypeScript/issues/29037 + // @ts-expect-error const lines = elt.querySelectorAll("[data-nosnippet]"); let scrollOffset; @@ -57,6 +60,8 @@ window.updateScrapedExample = (example, buttonHolder) => { let locIndex = 0; const highlights = Array.prototype.slice.call(example.querySelectorAll(".highlight")); + + /** @type {HTMLAnchorElement} */ const link = nonnull(example.querySelector(".scraped-example-title a")); let expandButton = null; @@ -72,6 +77,7 @@ const prev = createScrapeButton(buttonHolder, "prev", "Previous usage"); // Toggle through list of examples in a given file + /** @type {function(function(): void): void} */ const onChangeLoc = changeIndex => { removeClass(highlights[locIndex], "focus"); changeIndex(); @@ -117,14 +123,13 @@ /** * Intitialize the `locs` field * - * @param {HTMLElement} example + * @param {HTMLElement & {locs?: rustdoc.ScrapedLoc[]}} example * @param {boolean} isHidden */ function setupLoc(example, isHidden) { - // @ts-expect-error - example.locs = JSON.parse(example.attributes.getNamedItem("data-locs").textContent); + const locs = example.locs = JSON.parse(nonnull(nonnull(example.attributes.getNamedItem("data-locs")).textContent)); // Start with the first example in view - scrollToLoc(example, example.locs[0][0], isHidden); + scrollToLoc(example, locs[0][0], isHidden); } const firstExamples = document.querySelectorAll(".scraped-example-list > .scraped-example"); From 35ba7dd217f3a1af420189927205d89cc2c02718 Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 25 Apr 2025 16:28:50 -0500 Subject: [PATCH 0014/1134] rustdoc js: add rustdoc.ScrapedLoc type --- src/librustdoc/html/static/js/rustdoc.d.ts | 2 ++ src/librustdoc/html/static/js/scrape-examples.js | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/librustdoc/html/static/js/rustdoc.d.ts b/src/librustdoc/html/static/js/rustdoc.d.ts index a10f72414920..2c0d47447c0b 100644 --- a/src/librustdoc/html/static/js/rustdoc.d.ts +++ b/src/librustdoc/html/static/js/rustdoc.d.ts @@ -496,6 +496,8 @@ declare namespace rustdoc { * Single element in the data-locs field of a scraped example. * First field is the start and end char index, * other fields seem to be unused. + * + * generated by `render_call_locations` in `render/mod.rs`. */ type ScrapedLoc = [[number, number], string, string] } diff --git a/src/librustdoc/html/static/js/scrape-examples.js b/src/librustdoc/html/static/js/scrape-examples.js index 32642799d887..5dab4cc01561 100644 --- a/src/librustdoc/html/static/js/scrape-examples.js +++ b/src/librustdoc/html/static/js/scrape-examples.js @@ -127,7 +127,9 @@ * @param {boolean} isHidden */ function setupLoc(example, isHidden) { - const locs = example.locs = JSON.parse(nonnull(nonnull(example.attributes.getNamedItem("data-locs")).textContent)); + const locs_str = example.attributes.getNamedItem("data-locs")).textContent; + const locs = example.locs = + JSON.parse(nonnull(nonnull(locs_str)); // Start with the first example in view scrollToLoc(example, locs[0][0], isHidden); } From 8799d3dd97e38af3e31a2e76369d647e01b8a423 Mon Sep 17 00:00:00 2001 From: binarycat Date: Mon, 28 Apr 2025 18:44:46 -0500 Subject: [PATCH 0015/1134] fix typo --- src/librustdoc/html/static/js/scrape-examples.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/librustdoc/html/static/js/scrape-examples.js b/src/librustdoc/html/static/js/scrape-examples.js index 5dab4cc01561..7a231dc3b774 100644 --- a/src/librustdoc/html/static/js/scrape-examples.js +++ b/src/librustdoc/html/static/js/scrape-examples.js @@ -1,4 +1,4 @@ -/* global addClass, hasClass, removeClass, onEachLazy, nonnull */ + /* global addClass, hasClass, removeClass, onEachLazy, nonnull */ "use strict"; @@ -127,9 +127,10 @@ * @param {boolean} isHidden */ function setupLoc(example, isHidden) { - const locs_str = example.attributes.getNamedItem("data-locs")).textContent; - const locs = example.locs = - JSON.parse(nonnull(nonnull(locs_str)); + const locs_str = example.attributes.getNamedItem("data-locs").textContent; + const locs = + JSON.parse(nonnull(nonnull(locs_str))); + example.locs = locs; // Start with the first example in view scrollToLoc(example, locs[0][0], isHidden); } From b06113dc5cd6fbb2cc63918f9e861929537f41fd Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 22 May 2025 16:14:15 -0500 Subject: [PATCH 0016/1134] scrape-examples.js: add another nonnull() invokation --- src/librustdoc/html/static/js/scrape-examples.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/html/static/js/scrape-examples.js b/src/librustdoc/html/static/js/scrape-examples.js index 7a231dc3b774..ec472666ce16 100644 --- a/src/librustdoc/html/static/js/scrape-examples.js +++ b/src/librustdoc/html/static/js/scrape-examples.js @@ -127,7 +127,7 @@ * @param {boolean} isHidden */ function setupLoc(example, isHidden) { - const locs_str = example.attributes.getNamedItem("data-locs").textContent; + const locs_str = nonnull(example.attributes.getNamedItem("data-locs")).textContent; const locs = JSON.parse(nonnull(nonnull(locs_str))); example.locs = locs; From 30721b0e909d7451a37bbb4ae371e1c909a0cbaf Mon Sep 17 00:00:00 2001 From: jyn Date: Mon, 26 May 2025 20:10:17 -0400 Subject: [PATCH 0017/1134] Add stubs for environment variables; document some of the important ones This uses a very hacky regex that will probably miss some variables. But having some docs seems better than none at all. This uses a very hacky regex that will probably miss some variables. But having some docs seems better than none at all. In particular, this generates stubs for the following env vars: - COLORTERM - QNX_TARGET - RUST_BACKTRACE - RUSTC_BLESS - RUSTC_BOOTSTRAP - RUSTC_BREAK_ON_ICE - RUSTC_CTFE_BACKTRACE - RUSTC_FORCE_RUSTC_VERSION - RUSTC_GRAPHVIZ_FONT - RUSTC_ICE - RUSTC_LOG - RUSTC_OVERRIDE_VERSION_STRING - RUSTC_RETRY_LINKER_ON_SEGFAULT - RUSTC_TRANSLATION_NO_DEBUG_ASSERT - RUST_DEP_GRAPH_FILTER - RUST_DEP_GRAPH - RUST_FORBID_DEP_GRAPH_EDGE - RUST_MIN_STACK - RUST_TARGET_PATH - SDKROOT - TERM - UNSTABLE_RUSTDOC_TEST_LINE - UNSTABLE_RUSTDOC_TEST_PATH [rendered](![screenshot of unstable-book running locally, with 14 environment variables shown in the sidebar](https://github.com/user-attachments/assets/8238d094-fb7a-456f-ad43-7c07aa2c44dd)) --- .../COLORTERM.md | 5 +++ .../QNX_TARGET.md | 11 ++++++ .../compiler-environment-variables/SDKROOT.md | 6 ++++ .../compiler-environment-variables/TERM.md | 5 +++ .../src/compiler-flags/terminal-urls.md | 13 +++++++ src/tools/tidy/src/features.rs | 35 +++++++++++++++++++ src/tools/tidy/src/unstable_book.rs | 2 ++ src/tools/unstable-book-gen/src/main.rs | 29 +++++++++++---- .../unstable-book-gen/src/stub-env-var.md | 9 +++++ 9 files changed, 109 insertions(+), 6 deletions(-) create mode 100644 src/doc/unstable-book/src/compiler-environment-variables/COLORTERM.md create mode 100644 src/doc/unstable-book/src/compiler-environment-variables/QNX_TARGET.md create mode 100644 src/doc/unstable-book/src/compiler-environment-variables/SDKROOT.md create mode 100644 src/doc/unstable-book/src/compiler-environment-variables/TERM.md create mode 100644 src/doc/unstable-book/src/compiler-flags/terminal-urls.md create mode 100644 src/tools/unstable-book-gen/src/stub-env-var.md diff --git a/src/doc/unstable-book/src/compiler-environment-variables/COLORTERM.md b/src/doc/unstable-book/src/compiler-environment-variables/COLORTERM.md new file mode 100644 index 000000000000..f5be63b796c9 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-environment-variables/COLORTERM.md @@ -0,0 +1,5 @@ +# `COLORTERM` + +This environment variable is used by [`-Zterminal-urls`] to detect if URLs are supported by the terminal emulator. + +[`-Zterminal-urls`]: ../compiler-flags/terminal-urls.html diff --git a/src/doc/unstable-book/src/compiler-environment-variables/QNX_TARGET.md b/src/doc/unstable-book/src/compiler-environment-variables/QNX_TARGET.md new file mode 100644 index 000000000000..cc98fc3b3b28 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-environment-variables/QNX_TARGET.md @@ -0,0 +1,11 @@ +# `QNX_TARGET` + +---- + +This environment variable is mandatory when linking on `nto-qnx*_iosock` platforms. It is used to determine an `-L` path to pass to the QNX linker. + +You should [set this variable] by running `source qnxsdp-env.sh`. +See [the QNX docs] for more background information. + +[set this variable]: https://www.qnx.com/developers/docs/qsc/com.qnx.doc.qsc.inst_larg_org/topic/build_server_developer_steps.html +[the QNX docs]: https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.io_sock/topic/migrate_app.html. diff --git a/src/doc/unstable-book/src/compiler-environment-variables/SDKROOT.md b/src/doc/unstable-book/src/compiler-environment-variables/SDKROOT.md new file mode 100644 index 000000000000..b00c2f773ad6 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-environment-variables/SDKROOT.md @@ -0,0 +1,6 @@ +# `SDKROOT` + +This environment variable is used on MacOS targets. +It is passed through to the linker (either as `-isysroot` or `-syslibroot`) without changes. + +Note that this variable is not always respected. When the SDKROOT is clearly wrong (e.g. when the platform of the SDK does not match the `--target` used by rustc), this is ignored and rustc does its own detection. diff --git a/src/doc/unstable-book/src/compiler-environment-variables/TERM.md b/src/doc/unstable-book/src/compiler-environment-variables/TERM.md new file mode 100644 index 000000000000..9208fd378a3a --- /dev/null +++ b/src/doc/unstable-book/src/compiler-environment-variables/TERM.md @@ -0,0 +1,5 @@ +# `TERM` + +This environment variable is used by [`-Zterminal-urls`] to detect if URLs are supported by the terminal emulator. + +[`-Zterminal-urls`]: ../compiler-flags/terminal-urls.html diff --git a/src/doc/unstable-book/src/compiler-flags/terminal-urls.md b/src/doc/unstable-book/src/compiler-flags/terminal-urls.md new file mode 100644 index 000000000000..a5427978f258 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/terminal-urls.md @@ -0,0 +1,13 @@ +# `-Z terminal-urls` + +The tracking feature for this issue is [#125586] + +[#125586]: https://github.com/rust-lang/rust/issues/125586 + +--- + +This flag takes either a boolean or the string "auto". + +When enabled, use the OSC 8 hyperlink terminal specification to print hyperlinks in the compiler output. +Use "auto" to try and autodetect whether the terminal emulator supports hyperlinks. +Currently, "auto" only enables hyperlinks if `COLORTERM=truecolor` and `TERM=xterm-256color`. diff --git a/src/tools/tidy/src/features.rs b/src/tools/tidy/src/features.rs index fcd7943e6e0a..cbb7e18a8db7 100644 --- a/src/tools/tidy/src/features.rs +++ b/src/tools/tidy/src/features.rs @@ -9,6 +9,7 @@ //! * All unstable lang features have tests to ensure they are actually unstable. //! * Language features in a group are sorted by feature name. +use std::collections::BTreeSet; use std::collections::hash_map::{Entry, HashMap}; use std::ffi::OsStr; use std::num::NonZeroU32; @@ -21,6 +22,7 @@ use crate::walk::{filter_dirs, filter_not_rust, walk, walk_many}; mod tests; mod version; +use regex::Regex; use version::Version; const FEATURE_GROUP_START_PREFIX: &str = "// feature-group-start"; @@ -610,3 +612,36 @@ fn map_lib_features( }, ); } + +fn should_document(var: &str) -> bool { + if var.starts_with("RUSTC_") || var.starts_with("RUST_") || var.starts_with("UNSTABLE_RUSTDOC_") + { + return true; + } + ["SDKROOT", "QNX_TARGET", "COLORTERM", "TERM"].contains(&var) +} + +pub fn collect_env_vars(compiler: &Path) -> BTreeSet { + let env_var_regex: Regex = Regex::new(r#"env::var(_os)?\("([^"]+)"#).unwrap(); + + let mut vars = BTreeSet::new(); + walk( + compiler, + // skip build scripts, tests, and non-rust files + |path, _is_dir| { + filter_dirs(path) + || filter_not_rust(path) + || path.ends_with("build.rs") + || path.ends_with("tests.rs") + }, + &mut |_entry, contents| { + for env_var in env_var_regex.captures_iter(contents).map(|c| c.get(2).unwrap().as_str()) + { + if should_document(env_var) { + vars.insert(env_var.to_owned()); + } + } + }, + ); + vars +} diff --git a/src/tools/tidy/src/unstable_book.rs b/src/tools/tidy/src/unstable_book.rs index a2453a6c9605..5b0bf2201c17 100644 --- a/src/tools/tidy/src/unstable_book.rs +++ b/src/tools/tidy/src/unstable_book.rs @@ -6,6 +6,8 @@ use crate::features::{CollectedFeatures, Features, Status}; pub const PATH_STR: &str = "doc/unstable-book"; +pub const ENV_VARS_DIR: &str = "src/compiler-environment-variables"; + pub const COMPILER_FLAGS_DIR: &str = "src/compiler-flags"; pub const LANG_FEATURES_DIR: &str = "src/language-features"; diff --git a/src/tools/unstable-book-gen/src/main.rs b/src/tools/unstable-book-gen/src/main.rs index b9a2d313182f..2a3388590cdf 100644 --- a/src/tools/unstable-book-gen/src/main.rs +++ b/src/tools/unstable-book-gen/src/main.rs @@ -5,11 +5,11 @@ use std::env; use std::fs::{self, write}; use std::path::Path; -use tidy::features::{Features, collect_lang_features, collect_lib_features}; +use tidy::features::{Features, collect_env_vars, collect_lang_features, collect_lib_features}; use tidy::t; use tidy::unstable_book::{ - LANG_FEATURES_DIR, LIB_FEATURES_DIR, PATH_STR, collect_unstable_book_section_file_names, - collect_unstable_feature_names, + ENV_VARS_DIR, LANG_FEATURES_DIR, LIB_FEATURES_DIR, PATH_STR, + collect_unstable_book_section_file_names, collect_unstable_feature_names, }; fn generate_stub_issue(path: &Path, name: &str, issue: u32) { @@ -22,6 +22,11 @@ fn generate_stub_no_issue(path: &Path, name: &str) { t!(write(path, content), path); } +fn generate_stub_env_var(path: &Path, name: &str) { + let content = format!(include_str!("stub-env-var.md"), name = name); + t!(write(path, content), path); +} + fn set_to_summary_str(set: &BTreeSet, dir: &str) -> String { set.iter() .map(|ref n| format!(" - [{}]({}/{}.md)", n.replace('-', "_"), dir, n)) @@ -54,7 +59,7 @@ fn generate_summary(path: &Path, lang_features: &Features, lib_features: &Featur t!(write(&summary_path, content), summary_path); } -fn generate_unstable_book_files(src: &Path, out: &Path, features: &Features) { +fn generate_feature_files(src: &Path, out: &Path, features: &Features) { let unstable_features = collect_unstable_feature_names(features); let unstable_section_file_names = collect_unstable_book_section_file_names(src); t!(fs::create_dir_all(&out)); @@ -72,6 +77,16 @@ fn generate_unstable_book_files(src: &Path, out: &Path, features: &Features) { } } +fn generate_env_files(src: &Path, out: &Path, env_vars: &BTreeSet) { + let env_var_file_names = collect_unstable_book_section_file_names(src); + t!(fs::create_dir_all(&out)); + for env_var in env_vars - &env_var_file_names { + let file_name = format!("{env_var}.md"); + let out_file_path = out.join(&file_name); + generate_stub_env_var(&out_file_path, &env_var); + } +} + fn copy_recursive(from: &Path, to: &Path) { for entry in t!(fs::read_dir(from)) { let e = t!(entry); @@ -101,21 +116,23 @@ fn main() { .into_iter() .filter(|&(ref name, _)| !lang_features.contains_key(name)) .collect(); + let env_vars = collect_env_vars(compiler_path); let doc_src_path = src_path.join(PATH_STR); t!(fs::create_dir_all(&dest_path)); - generate_unstable_book_files( + generate_feature_files( &doc_src_path.join(LANG_FEATURES_DIR), &dest_path.join(LANG_FEATURES_DIR), &lang_features, ); - generate_unstable_book_files( + generate_feature_files( &doc_src_path.join(LIB_FEATURES_DIR), &dest_path.join(LIB_FEATURES_DIR), &lib_features, ); + generate_env_files(&doc_src_path.join(ENV_VARS_DIR), &dest_path.join(ENV_VARS_DIR), &env_vars); copy_recursive(&doc_src_path, &dest_path); diff --git a/src/tools/unstable-book-gen/src/stub-env-var.md b/src/tools/unstable-book-gen/src/stub-env-var.md new file mode 100644 index 000000000000..e8a7ddb855a6 --- /dev/null +++ b/src/tools/unstable-book-gen/src/stub-env-var.md @@ -0,0 +1,9 @@ +# `{name}` + +Environment variables have no tracking issue. This environment variable has no documentation, and therefore is likely internal to the compiler and not meant for general use. + +See [the code][github search] for more information. + +[github search]: https://github.com/search?q=repo%3Arust-lang%2Frust+%22{name}%22+path%3Acompiler&type=code + +------------------------ From c021e7a9d2818e7d9f71bd38124d4e2c212007d6 Mon Sep 17 00:00:00 2001 From: lolbinarycat Date: Tue, 27 May 2025 12:50:14 -0500 Subject: [PATCH 0018/1134] scrape-examples.js: fix typos Co-authored-by: Guillaume Gomez --- src/librustdoc/html/static/js/rustdoc.d.ts | 2 +- src/librustdoc/html/static/js/scrape-examples.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/librustdoc/html/static/js/rustdoc.d.ts b/src/librustdoc/html/static/js/rustdoc.d.ts index 2c0d47447c0b..686d77abde51 100644 --- a/src/librustdoc/html/static/js/rustdoc.d.ts +++ b/src/librustdoc/html/static/js/rustdoc.d.ts @@ -497,7 +497,7 @@ declare namespace rustdoc { * First field is the start and end char index, * other fields seem to be unused. * - * generated by `render_call_locations` in `render/mod.rs`. + * Generated by `render_call_locations` in `render/mod.rs`. */ type ScrapedLoc = [[number, number], string, string] } diff --git a/src/librustdoc/html/static/js/scrape-examples.js b/src/librustdoc/html/static/js/scrape-examples.js index ec472666ce16..eeab591bcd80 100644 --- a/src/librustdoc/html/static/js/scrape-examples.js +++ b/src/librustdoc/html/static/js/scrape-examples.js @@ -121,7 +121,7 @@ }; /** - * Intitialize the `locs` field + * Initialize the `locs` field * * @param {HTMLElement & {locs?: rustdoc.ScrapedLoc[]}} example * @param {boolean} isHidden From 964eb82b63f7c99f951e5b5f262dc8800f7bd6ec Mon Sep 17 00:00:00 2001 From: Pavel Grigorenko Date: Thu, 29 May 2025 22:10:40 +0300 Subject: [PATCH 0019/1134] Stabilize `ip_from` --- library/core/src/net/ip_addr.rs | 12 ++++++------ library/coretests/tests/lib.rs | 1 - 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/library/core/src/net/ip_addr.rs b/library/core/src/net/ip_addr.rs index aaa68e8d7d1a..1d1d184bb21a 100644 --- a/library/core/src/net/ip_addr.rs +++ b/library/core/src/net/ip_addr.rs @@ -627,13 +627,13 @@ impl Ipv4Addr { /// # Examples /// /// ``` - /// #![feature(ip_from)] /// use std::net::Ipv4Addr; /// /// let addr = Ipv4Addr::from_octets([13u8, 12u8, 11u8, 10u8]); /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr); /// ``` - #[unstable(feature = "ip_from", issue = "131360")] + #[stable(feature = "ip_from", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "ip_from", since = "CURRENT_RUSTC_VERSION")] #[must_use] #[inline] pub const fn from_octets(octets: [u8; 4]) -> Ipv4Addr { @@ -1460,7 +1460,6 @@ impl Ipv6Addr { /// # Examples /// /// ``` - /// #![feature(ip_from)] /// use std::net::Ipv6Addr; /// /// let addr = Ipv6Addr::from_segments([ @@ -1475,7 +1474,8 @@ impl Ipv6Addr { /// addr /// ); /// ``` - #[unstable(feature = "ip_from", issue = "131360")] + #[stable(feature = "ip_from", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "ip_from", since = "CURRENT_RUSTC_VERSION")] #[must_use] #[inline] pub const fn from_segments(segments: [u16; 8]) -> Ipv6Addr { @@ -2025,7 +2025,6 @@ impl Ipv6Addr { /// # Examples /// /// ``` - /// #![feature(ip_from)] /// use std::net::Ipv6Addr; /// /// let addr = Ipv6Addr::from_octets([ @@ -2040,7 +2039,8 @@ impl Ipv6Addr { /// addr /// ); /// ``` - #[unstable(feature = "ip_from", issue = "131360")] + #[stable(feature = "ip_from", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "ip_from", since = "CURRENT_RUSTC_VERSION")] #[must_use] #[inline] pub const fn from_octets(octets: [u8; 16]) -> Ipv6Addr { diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 693b14ef7620..b9c642461ead 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -47,7 +47,6 @@ #![feature(hashmap_internals)] #![feature(int_roundings)] #![feature(ip)] -#![feature(ip_from)] #![feature(is_ascii_octdigit)] #![feature(isolate_most_least_significant_one)] #![feature(iter_advance_by)] From 9e9c9170a50ba34a3cb66540a2079884b92ed480 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Sun, 8 Jun 2025 00:49:00 +0800 Subject: [PATCH 0020/1134] fix: `iter_on_single_items` FP on function pointers --- .../iter_on_single_or_empty_collections.rs | 65 ++++++++++--------- clippy_utils/src/ty/mod.rs | 2 +- tests/ui/iter_on_single_items.fixed | 11 ++++ tests/ui/iter_on_single_items.rs | 11 ++++ 4 files changed, 56 insertions(+), 33 deletions(-) diff --git a/clippy_lints/src/methods/iter_on_single_or_empty_collections.rs b/clippy_lints/src/methods/iter_on_single_or_empty_collections.rs index c0366765234f..bda74ab173b6 100644 --- a/clippy_lints/src/methods/iter_on_single_or_empty_collections.rs +++ b/clippy_lints/src/methods/iter_on_single_or_empty_collections.rs @@ -2,11 +2,11 @@ use std::iter::once; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet; +use clippy_utils::ty::{ExprFnSig, expr_sig, ty_sig}; use clippy_utils::{get_expr_use_or_unification_node, is_res_lang_ctor, path_res, std_or_core, sym}; use rustc_errors::Applicability; use rustc_hir::LangItem::{OptionNone, OptionSome}; -use rustc_hir::def_id::DefId; use rustc_hir::hir_id::HirId; use rustc_hir::{Expr, ExprKind, Node}; use rustc_lint::LateContext; @@ -32,24 +32,34 @@ impl IterType { fn is_arg_ty_unified_in_fn<'tcx>( cx: &LateContext<'tcx>, - fn_id: DefId, + fn_sig: ExprFnSig<'tcx>, arg_id: HirId, args: impl IntoIterator>, + is_method: bool, ) -> bool { - let fn_sig = cx.tcx.fn_sig(fn_id).instantiate_identity(); let arg_id_in_args = args.into_iter().position(|e| e.hir_id == arg_id).unwrap(); - let arg_ty_in_args = fn_sig.input(arg_id_in_args).skip_binder(); + let Some(arg_ty_in_args) = fn_sig.input(arg_id_in_args).map(|binder| binder.skip_binder()) else { + return false; + }; - cx.tcx.predicates_of(fn_id).predicates.iter().any(|(clause, _)| { - clause - .as_projection_clause() - .and_then(|p| p.map_bound(|p| p.term.as_type()).transpose()) - .is_some_and(|ty| ty.skip_binder() == arg_ty_in_args) - }) || fn_sig - .inputs() - .iter() - .enumerate() - .any(|(i, ty)| i != arg_id_in_args && ty.skip_binder().walk().any(|arg| arg.as_type() == Some(arg_ty_in_args))) + fn_sig + .predicates_id() + .map(|def_id| cx.tcx.predicates_of(def_id)) + .is_some_and(|generics| { + generics.predicates.iter().any(|(clause, _)| { + clause + .as_projection_clause() + .and_then(|p| p.map_bound(|p| p.term.as_type()).transpose()) + .is_some_and(|ty| ty.skip_binder() == arg_ty_in_args) + }) + }) + || (!is_method + && fn_sig.input(arg_id_in_args).is_some_and(|binder| { + binder + .skip_binder() + .walk() + .any(|arg| arg.as_type() == Some(arg_ty_in_args)) + })) } pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, method_name: Symbol, recv: &'tcx Expr<'tcx>) { @@ -70,25 +80,16 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, method let is_unified = match get_expr_use_or_unification_node(cx.tcx, expr) { Some((Node::Expr(parent), child_id)) => match parent.kind { ExprKind::If(e, _, _) | ExprKind::Match(e, _, _) if e.hir_id == child_id => false, - ExprKind::Call( - Expr { - kind: ExprKind::Path(path), - hir_id, - .. - }, - args, - ) => cx + ExprKind::Call(recv, args) => { + expr_sig(cx, recv).is_some_and(|fn_sig| is_arg_ty_unified_in_fn(cx, fn_sig, child_id, args, false)) + }, + ExprKind::MethodCall(_name, recv, args, _span) => cx .typeck_results() - .qpath_res(path, *hir_id) - .opt_def_id() - .filter(|fn_id| cx.tcx.def_kind(fn_id).is_fn_like()) - .is_some_and(|fn_id| is_arg_ty_unified_in_fn(cx, fn_id, child_id, args)), - ExprKind::MethodCall(_name, recv, args, _span) => is_arg_ty_unified_in_fn( - cx, - cx.typeck_results().type_dependent_def_id(parent.hir_id).unwrap(), - child_id, - once(recv).chain(args.iter()), - ), + .type_dependent_def_id(parent.hir_id) + .and_then(|def_id| ty_sig(cx, cx.tcx.type_of(def_id).instantiate_identity())) + .is_some_and(|fn_sig| { + is_arg_ty_unified_in_fn(cx, fn_sig, child_id, once(recv).chain(args.iter()), true) + }), ExprKind::If(_, _, _) | ExprKind::Match(_, _, _) | ExprKind::Closure(_) diff --git a/clippy_utils/src/ty/mod.rs b/clippy_utils/src/ty/mod.rs index 1f0a0f2b02ac..c9100d97bcfc 100644 --- a/clippy_utils/src/ty/mod.rs +++ b/clippy_utils/src/ty/mod.rs @@ -581,7 +581,7 @@ pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator { Sig(Binder<'tcx, FnSig<'tcx>>, Option), Closure(Option<&'tcx FnDecl<'tcx>>, Binder<'tcx, FnSig<'tcx>>), diff --git a/tests/ui/iter_on_single_items.fixed b/tests/ui/iter_on_single_items.fixed index b43fad6449c1..bdab6121b1f6 100644 --- a/tests/ui/iter_on_single_items.fixed +++ b/tests/ui/iter_on_single_items.fixed @@ -66,3 +66,14 @@ fn main() { custom_option::custom_option(); in_macros!(); } + +fn issue14981() { + use std::option::IntoIter; + fn some_func(_: IntoIter) -> IntoIter { + todo!() + } + some_func(Some(5).into_iter()); + + const C: fn(IntoIter) -> IntoIter = as IntoIterator>::into_iter; + C(Some(5).into_iter()); +} diff --git a/tests/ui/iter_on_single_items.rs b/tests/ui/iter_on_single_items.rs index 625c96d3ef1f..40ed6d3ec1a6 100644 --- a/tests/ui/iter_on_single_items.rs +++ b/tests/ui/iter_on_single_items.rs @@ -66,3 +66,14 @@ fn main() { custom_option::custom_option(); in_macros!(); } + +fn issue14981() { + use std::option::IntoIter; + fn some_func(_: IntoIter) -> IntoIter { + todo!() + } + some_func(Some(5).into_iter()); + + const C: fn(IntoIter) -> IntoIter = as IntoIterator>::into_iter; + C(Some(5).into_iter()); +} From 20670f78fdd63fbf1597457fcb35a562a428e0e9 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Sun, 8 Jun 2025 01:13:18 +0800 Subject: [PATCH 0021/1134] fix: `iter_on_single_item` FP on let stmt with type annotation --- .../iter_on_single_or_empty_collections.rs | 6 +++-- tests/ui/iter_on_single_items.fixed | 25 ++++++++++++++----- tests/ui/iter_on_single_items.rs | 25 ++++++++++++++----- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/clippy_lints/src/methods/iter_on_single_or_empty_collections.rs b/clippy_lints/src/methods/iter_on_single_or_empty_collections.rs index bda74ab173b6..83e565562af0 100644 --- a/clippy_lints/src/methods/iter_on_single_or_empty_collections.rs +++ b/clippy_lints/src/methods/iter_on_single_or_empty_collections.rs @@ -10,6 +10,7 @@ use rustc_hir::LangItem::{OptionNone, OptionSome}; use rustc_hir::hir_id::HirId; use rustc_hir::{Expr, ExprKind, Node}; use rustc_lint::LateContext; +use rustc_middle::ty::Binder; use rustc_span::Symbol; use super::{ITER_ON_EMPTY_COLLECTIONS, ITER_ON_SINGLE_ITEMS}; @@ -38,7 +39,7 @@ fn is_arg_ty_unified_in_fn<'tcx>( is_method: bool, ) -> bool { let arg_id_in_args = args.into_iter().position(|e| e.hir_id == arg_id).unwrap(); - let Some(arg_ty_in_args) = fn_sig.input(arg_id_in_args).map(|binder| binder.skip_binder()) else { + let Some(arg_ty_in_args) = fn_sig.input(arg_id_in_args).map(Binder::skip_binder) else { return false; }; @@ -97,7 +98,8 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, method | ExprKind::Break(_, _) => true, _ => false, }, - Some((Node::Stmt(_) | Node::LetStmt(_), _)) => false, + Some((Node::LetStmt(let_stmt), _)) => let_stmt.ty.is_some(), + Some((Node::Stmt(_), _)) => false, _ => true, }; diff --git a/tests/ui/iter_on_single_items.fixed b/tests/ui/iter_on_single_items.fixed index bdab6121b1f6..044037aac2e3 100644 --- a/tests/ui/iter_on_single_items.fixed +++ b/tests/ui/iter_on_single_items.fixed @@ -67,13 +67,26 @@ fn main() { in_macros!(); } -fn issue14981() { +mod issue14981 { use std::option::IntoIter; - fn some_func(_: IntoIter) -> IntoIter { - todo!() + fn takes_into_iter(_: impl IntoIterator) {} + + fn let_stmt() { + macro_rules! x { + ($e:expr) => { + let _: IntoIter = $e; + }; + } + x!(Some(5).into_iter()); } - some_func(Some(5).into_iter()); - const C: fn(IntoIter) -> IntoIter = as IntoIterator>::into_iter; - C(Some(5).into_iter()); + fn fn_ptr() { + fn some_func(_: IntoIter) -> IntoIter { + todo!() + } + some_func(Some(5).into_iter()); + + const C: fn(IntoIter) -> IntoIter = as IntoIterator>::into_iter; + C(Some(5).into_iter()); + } } diff --git a/tests/ui/iter_on_single_items.rs b/tests/ui/iter_on_single_items.rs index 40ed6d3ec1a6..c925d0e480fa 100644 --- a/tests/ui/iter_on_single_items.rs +++ b/tests/ui/iter_on_single_items.rs @@ -67,13 +67,26 @@ fn main() { in_macros!(); } -fn issue14981() { +mod issue14981 { use std::option::IntoIter; - fn some_func(_: IntoIter) -> IntoIter { - todo!() + fn takes_into_iter(_: impl IntoIterator) {} + + fn let_stmt() { + macro_rules! x { + ($e:expr) => { + let _: IntoIter = $e; + }; + } + x!(Some(5).into_iter()); } - some_func(Some(5).into_iter()); - const C: fn(IntoIter) -> IntoIter = as IntoIterator>::into_iter; - C(Some(5).into_iter()); + fn fn_ptr() { + fn some_func(_: IntoIter) -> IntoIter { + todo!() + } + some_func(Some(5).into_iter()); + + const C: fn(IntoIter) -> IntoIter = as IntoIterator>::into_iter; + C(Some(5).into_iter()); + } } From d9ca835db4ead44eba68345f32e0e8226822440c Mon Sep 17 00:00:00 2001 From: Paolo Barbolini Date: Sun, 8 Jun 2025 18:15:33 +0000 Subject: [PATCH 0022/1134] Mark `slice::swap_with_slice` unstably const --- library/core/src/slice/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 4f7e14408804..9ad3fd5cd339 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -3927,8 +3927,9 @@ impl [T] { /// /// [`split_at_mut`]: slice::split_at_mut #[stable(feature = "swap_with_slice", since = "1.27.0")] + #[rustc_const_unstable(feature = "const_swap_with_slice", issue = "142204")] #[track_caller] - pub fn swap_with_slice(&mut self, other: &mut [T]) { + pub const fn swap_with_slice(&mut self, other: &mut [T]) { assert!(self.len() == other.len(), "destination and source slices have different lengths"); // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was // checked to have the same length. The slices cannot overlap because From 1140e90074b0cbcfdea8535e4b51877e2838227e Mon Sep 17 00:00:00 2001 From: binarycat Date: Tue, 27 May 2025 12:42:25 -0500 Subject: [PATCH 0023/1134] rustdoc search: prefer stable items in search results fixes https://github.com/rust-lang/rust/issues/138067 --- src/librustdoc/formats/cache.rs | 1 + src/librustdoc/html/render/mod.rs | 9 ++++++++- src/librustdoc/html/render/search_index.rs | 6 ++++++ src/librustdoc/html/static/js/rustdoc.d.ts | 5 ++++- src/librustdoc/html/static/js/search.js | 21 ++++++++++++++++++++- tests/rustdoc-js-std/core-transmute.js | 2 +- tests/rustdoc-js-std/transmute-fail.js | 2 +- tests/rustdoc-js-std/transmute.js | 2 +- tests/rustdoc-js/sort-stability.js | 9 +++++++++ tests/rustdoc-js/sort-stability.rs | 16 ++++++++++++++++ 10 files changed, 67 insertions(+), 6 deletions(-) create mode 100644 tests/rustdoc-js/sort-stability.js create mode 100644 tests/rustdoc-js/sort-stability.rs diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index 4989bd718c9f..c3251ca78062 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -586,6 +586,7 @@ fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::It search_type, aliases, deprecation, + stability: item.stability(tcx), }; cache.search_index.push(index_item); } diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 66d5aafa3c1e..29917bb0fca2 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -50,7 +50,8 @@ use std::{fs, str}; use askama::Template; use itertools::Either; use rustc_attr_data_structures::{ - ConstStability, DeprecatedSince, Deprecation, RustcVersion, StabilityLevel, StableSince, + ConstStability, DeprecatedSince, Deprecation, RustcVersion, Stability, StabilityLevel, + StableSince, }; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_hir::Mutability; @@ -140,6 +141,12 @@ pub(crate) struct IndexItem { pub(crate) search_type: Option, pub(crate) aliases: Box<[Symbol]>, pub(crate) deprecation: Option, + pub(crate) stability: Option, +} +impl IndexItem { + fn is_unstable(&self) -> bool { + matches!(&self.stability, Some(Stability { level: StabilityLevel::Unstable { .. }, .. })) + } } /// A type used for the search index. diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index aff8684ee3a0..6635aa02e97d 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -93,6 +93,7 @@ pub(crate) fn build_index( ), aliases: item.attrs.get_doc_aliases(), deprecation: item.deprecation(tcx), + stability: item.stability(tcx), }); } } @@ -642,6 +643,7 @@ pub(crate) fn build_index( let mut parents_backref_queue = VecDeque::new(); let mut functions = String::with_capacity(self.items.len()); let mut deprecated = Vec::with_capacity(self.items.len()); + let mut unstable = Vec::with_capacity(self.items.len()); let mut type_backref_queue = VecDeque::new(); @@ -698,6 +700,9 @@ pub(crate) fn build_index( // bitmasks always use 1-indexing for items, with 0 as the crate itself deprecated.push(u32::try_from(index + 1).unwrap()); } + if item.is_unstable() { + unstable.push(u32::try_from(index + 1).unwrap()); + } } for (index, path) in &revert_extra_paths { @@ -736,6 +741,7 @@ pub(crate) fn build_index( crate_data.serialize_field("r", &re_exports)?; crate_data.serialize_field("b", &self.associated_item_disambiguators)?; crate_data.serialize_field("c", &bitmap_to_string(&deprecated))?; + crate_data.serialize_field("u", &bitmap_to_string(&unstable))?; crate_data.serialize_field("e", &bitmap_to_string(&self.empty_desc))?; crate_data.serialize_field("P", ¶m_names)?; if has_aliases { diff --git a/src/librustdoc/html/static/js/rustdoc.d.ts b/src/librustdoc/html/static/js/rustdoc.d.ts index 0d2e19e019f3..8110f1f5a5e5 100644 --- a/src/librustdoc/html/static/js/rustdoc.d.ts +++ b/src/librustdoc/html/static/js/rustdoc.d.ts @@ -129,7 +129,7 @@ declare namespace rustdoc { /** * A single parsed "atom" in a search query. For example, - * + * * std::fmt::Formatter, Write -> Result<()> * ┏━━━━━━━━━━━━━━━━━━ ┌──── ┏━━━━━┅┅┅┅┄┄┄┄┄┄┄┄┄┄┄┄┄┄┐ * ┃ │ ┗ QueryElement { ┊ @@ -442,6 +442,8 @@ declare namespace rustdoc { * of `p`) but is used for modules items like free functions. * * `c` is an array of item indices that are deprecated. + * + * `u` is an array of item indices that are unstable. */ type RawSearchIndexCrate = { doc: string, @@ -456,6 +458,7 @@ declare namespace rustdoc { p: Array<[number, string] | [number, string, number] | [number, string, number, number] | [number, string, number, number, string]>, b: Array<[number, String]>, c: string, + u: string, r: Array<[number, number]>, P: Array<[number, string]>, }; diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index dce5fddb3177..da15433622af 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -1463,6 +1463,11 @@ class DocSearch { * @type {Map} */ this.searchIndexEmptyDesc = new Map(); + /** + * @type {Map} + */ + this.searchIndexUnstable = new Map(); + /** * @type {Uint32Array} */ @@ -2048,9 +2053,10 @@ class DocSearch { }; const descShardList = [descShard]; - // Deprecated items and items with no description + // Deprecated and unstable items and items with no description this.searchIndexDeprecated.set(crate, new RoaringBitmap(crateCorpus.c)); this.searchIndexEmptyDesc.set(crate, new RoaringBitmap(crateCorpus.e)); + this.searchIndexUnstable.set(crate, new RoaringBitmap(crateCorpus.u)); let descIndex = 0; /** @@ -3284,6 +3290,19 @@ class DocSearch { return a - b; } + // sort unstable items later + a = Number( + // @ts-expect-error + this.searchIndexUnstable.get(aaa.item.crate).contains(aaa.item.bitIndex), + ); + b = Number( + // @ts-expect-error + this.searchIndexUnstable.get(bbb.item.crate).contains(bbb.item.bitIndex), + ); + if (a !== b) { + return a - b; + } + // sort by crate (current crate comes first) a = Number(aaa.item.crate !== preferredCrate); b = Number(bbb.item.crate !== preferredCrate); diff --git a/tests/rustdoc-js-std/core-transmute.js b/tests/rustdoc-js-std/core-transmute.js index 8c9910a32d7f..b15f398902c3 100644 --- a/tests/rustdoc-js-std/core-transmute.js +++ b/tests/rustdoc-js-std/core-transmute.js @@ -3,9 +3,9 @@ const EXPECTED = [ { 'query': 'generic:T -> generic:U', 'others': [ + { 'path': 'core::mem', 'name': 'transmute' }, { 'path': 'core::intrinsics::simd', 'name': 'simd_as' }, { 'path': 'core::intrinsics::simd', 'name': 'simd_cast' }, - { 'path': 'core::mem', 'name': 'transmute' }, ], }, ]; diff --git a/tests/rustdoc-js-std/transmute-fail.js b/tests/rustdoc-js-std/transmute-fail.js index ddfb27619481..459e8dc3f002 100644 --- a/tests/rustdoc-js-std/transmute-fail.js +++ b/tests/rustdoc-js-std/transmute-fail.js @@ -6,9 +6,9 @@ const EXPECTED = [ // should-fail tag and the search query below: 'query': 'generic:T -> generic:T', 'others': [ + { 'path': 'std::mem', 'name': 'transmute' }, { 'path': 'std::intrinsics::simd', 'name': 'simd_as' }, { 'path': 'std::intrinsics::simd', 'name': 'simd_cast' }, - { 'path': 'std::mem', 'name': 'transmute' }, ], }, ]; diff --git a/tests/rustdoc-js-std/transmute.js b/tests/rustdoc-js-std/transmute.js index f52e0ab14362..a85b02e29947 100644 --- a/tests/rustdoc-js-std/transmute.js +++ b/tests/rustdoc-js-std/transmute.js @@ -5,9 +5,9 @@ const EXPECTED = [ // should-fail tag and the search query below: 'query': 'generic:T -> generic:U', 'others': [ + { 'path': 'std::mem', 'name': 'transmute' }, { 'path': 'std::intrinsics::simd', 'name': 'simd_as' }, { 'path': 'std::intrinsics::simd', 'name': 'simd_cast' }, - { 'path': 'std::mem', 'name': 'transmute' }, ], }, ]; diff --git a/tests/rustdoc-js/sort-stability.js b/tests/rustdoc-js/sort-stability.js new file mode 100644 index 000000000000..8c095619a086 --- /dev/null +++ b/tests/rustdoc-js/sort-stability.js @@ -0,0 +1,9 @@ +const EXPECTED = [ + { + 'query': 'foo', + 'others': [ + {"path": "sort_stability::old", "name": "foo"}, + {"path": "sort_stability::new", "name": "foo"}, + ], + }, +]; diff --git a/tests/rustdoc-js/sort-stability.rs b/tests/rustdoc-js/sort-stability.rs new file mode 100644 index 000000000000..68662bb3aab6 --- /dev/null +++ b/tests/rustdoc-js/sort-stability.rs @@ -0,0 +1,16 @@ +#![feature(staged_api)] +#![stable(feature = "foo_lib", since = "1.0.0")] + +#[stable(feature = "old_foo", since = "1.0.1")] +pub mod old { + /// Old, stable foo + #[stable(feature = "old_foo", since = "1.0.1")] + pub fn foo() {} +} + +#[unstable(feature = "new_foo", issue = "none")] +pub mod new { + /// New, unstable foo + #[unstable(feature = "new_foo", issue = "none")] + pub fn foo() {} +} From f4b77355c6849085b0a841f962abae4ced5e50ba Mon Sep 17 00:00:00 2001 From: Boxy Date: Tue, 17 Jun 2025 15:02:38 +0100 Subject: [PATCH 0024/1134] Rename hir const arg walking functions --- compiler/rustc_ast_lowering/src/index.rs | 2 +- compiler/rustc_hir/src/intravisit.rs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index 956cb580d103..a0a3a973fbec 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -311,7 +311,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { ); self.with_parent(const_arg.hir_id, |this| { - intravisit::walk_ambig_const_arg(this, const_arg); + intravisit::walk_const_arg(this, const_arg); }); } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index 57e49625148c..c8f6978ee8be 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -380,7 +380,7 @@ pub trait Visitor<'v>: Sized { /// /// The [`Visitor::visit_infer`] method should be overridden in order to handle infer vars. fn visit_const_arg(&mut self, c: &'v ConstArg<'v, AmbigArg>) -> Self::Result { - walk_ambig_const_arg(self, c) + walk_const_arg(self, c) } #[allow(unused_variables)] @@ -525,7 +525,7 @@ pub trait VisitorExt<'v>: Visitor<'v> { /// Named `visit_const_arg_unambig` instead of `visit_unambig_const_arg` to aid in /// discovery by IDes when `v.visit_const_arg` is written. fn visit_const_arg_unambig(&mut self, c: &'v ConstArg<'v>) -> Self::Result { - walk_const_arg(self, c) + walk_unambig_const_arg(self, c) } } impl<'v, V: Visitor<'v>> VisitorExt<'v> for V {} @@ -1038,7 +1038,7 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v, AmbigArg>) - V::Result::output() } -pub fn walk_const_arg<'v, V: Visitor<'v>>( +pub fn walk_unambig_const_arg<'v, V: Visitor<'v>>( visitor: &mut V, const_arg: &'v ConstArg<'v>, ) -> V::Result { @@ -1052,7 +1052,7 @@ pub fn walk_const_arg<'v, V: Visitor<'v>>( } } -pub fn walk_ambig_const_arg<'v, V: Visitor<'v>>( +pub fn walk_const_arg<'v, V: Visitor<'v>>( visitor: &mut V, const_arg: &'v ConstArg<'v, AmbigArg>, ) -> V::Result { From c9264a1f4963182fb31c1da32d191bb3bac930ca Mon Sep 17 00:00:00 2001 From: Boxy Date: Tue, 17 Jun 2025 15:03:02 +0100 Subject: [PATCH 0025/1134] Don't double visit `HirId`s of inferred const/types --- compiler/rustc_hir/src/intravisit.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index c8f6978ee8be..cb971bedecd2 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -980,7 +980,6 @@ pub fn walk_unambig_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) -> Some(ambig_ty) => visitor.visit_ty(ambig_ty), None => { let Ty { hir_id, span, kind: _ } = typ; - try_visit!(visitor.visit_id(*hir_id)); visitor.visit_infer(*hir_id, *span, InferKind::Ty(typ)) } } @@ -1046,7 +1045,6 @@ pub fn walk_unambig_const_arg<'v, V: Visitor<'v>>( Some(ambig_ct) => visitor.visit_const_arg(ambig_ct), None => { let ConstArg { hir_id, kind: _ } = const_arg; - try_visit!(visitor.visit_id(*hir_id)); visitor.visit_infer(*hir_id, const_arg.span(), InferKind::Const(const_arg)) } } From 2411fbaa49f8c10d0fc8bc1a41d39d0df2f73f0f Mon Sep 17 00:00:00 2001 From: Boxy Date: Wed, 18 Jun 2025 15:58:00 +0100 Subject: [PATCH 0026/1134] Link to dev-guide docs --- compiler/rustc_hir/src/hir.rs | 32 ++++++++++++++++++++-------- compiler/rustc_hir/src/intravisit.rs | 22 +++++++++++++++---- 2 files changed, 41 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 556f50a85af7..bd59ad613d63 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -407,10 +407,8 @@ impl<'hir> PathSegment<'hir> { /// that are [just paths](ConstArgKind::Path) (currently just bare const params) /// versus const args that are literals or have arbitrary computations (e.g., `{ 1 + 3 }`). /// -/// The `Unambig` generic parameter represents whether the position this const is from is -/// unambiguously a const or ambiguous as to whether it is a type or a const. When in an -/// ambiguous context the parameter is instantiated with an uninhabited type making the -/// [`ConstArgKind::Infer`] variant unusable and [`GenericArg::Infer`] is used instead. +/// For an explanation of the `Unambig` generic parameter see the dev-guide: +/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html #[derive(Clone, Copy, Debug, HashStable_Generic)] #[repr(C)] pub struct ConstArg<'hir, Unambig = ()> { @@ -429,6 +427,9 @@ impl<'hir> ConstArg<'hir, AmbigArg> { /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or /// specifically matching on [`GenericArg::Infer`] when handling generic arguments. /// + /// For an explanation of what it means for a const arg to be ambig or unambig, see the dev-guide: + /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html + /// /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer] pub fn as_unambig_ct(&self) -> &ConstArg<'hir> { // SAFETY: `ConstArg` is `repr(C)` and `ConstArgKind` is marked `repr(u8)` so that the @@ -444,6 +445,9 @@ impl<'hir> ConstArg<'hir> { /// /// Functions accepting ambiguous consts will not handle the [`ConstArgKind::Infer`] variant, if /// infer consts are relevant to you then care should be taken to handle them separately. + /// + /// For an explanation of what it means for a const arg to be ambig or unambig, see the dev-guide: + /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> { if let ConstArgKind::Infer(_, ()) = self.kind { return None; @@ -475,6 +479,9 @@ impl<'hir, Unambig> ConstArg<'hir, Unambig> { } /// See [`ConstArg`]. +/// +/// For an explanation of the `Unambig` generic parameter see the dev-guide: +/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html #[derive(Clone, Copy, Debug, HashStable_Generic)] #[repr(u8, C)] pub enum ConstArgKind<'hir, Unambig = ()> { @@ -3302,10 +3309,8 @@ pub enum AmbigArg {} #[repr(C)] /// Represents a type in the `HIR`. /// -/// The `Unambig` generic parameter represents whether the position this type is from is -/// unambiguously a type or ambiguous as to whether it is a type or a const. When in an -/// ambiguous context the parameter is instantiated with an uninhabited type making the -/// [`TyKind::Infer`] variant unusable and [`GenericArg::Infer`] is used instead. +/// For an explanation of the `Unambig` generic parameter see the dev-guide: +/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub struct Ty<'hir, Unambig = ()> { #[stable_hasher(ignore)] pub hir_id: HirId, @@ -3323,6 +3328,9 @@ impl<'hir> Ty<'hir, AmbigArg> { /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or /// specifically matching on [`GenericArg::Infer`] when handling generic arguments. /// + /// For an explanation of what it means for a type to be ambig or unambig, see the dev-guide: + /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html + /// /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer] pub fn as_unambig_ty(&self) -> &Ty<'hir> { // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is @@ -3338,6 +3346,9 @@ impl<'hir> Ty<'hir> { /// /// Functions accepting ambiguous types will not handle the [`TyKind::Infer`] variant, if /// infer types are relevant to you then care should be taken to handle them separately. + /// + /// For an explanation of what it means for a type to be ambig or unambig, see the dev-guide: + /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> { if let TyKind::Infer(()) = self.kind { return None; @@ -3640,9 +3651,12 @@ pub enum InferDelegationKind { } /// The various kinds of types recognized by the compiler. -#[derive(Debug, Clone, Copy, HashStable_Generic)] +/// +/// For an explanation of the `Unambig` generic parameter see the dev-guide: +/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html // SAFETY: `repr(u8)` is required so that `TyKind<()>` and `TyKind` are layout compatible #[repr(u8, C)] +#[derive(Debug, Clone, Copy, HashStable_Generic)] pub enum TyKind<'hir, Unambig = ()> { /// Actual type should be inherited from `DefId` signature InferDelegation(DefId, InferDelegationKind), diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index cb971bedecd2..95fee05a71b9 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -364,8 +364,8 @@ pub trait Visitor<'v>: Sized { /// All types are treated as ambiguous types for the purposes of hir visiting in /// order to ensure that visitors can handle infer vars without it being too error-prone. /// - /// See the doc comments on [`Ty`] for an explanation of what it means for a type to be - /// ambiguous. + /// For an explanation of what it means for a type to be ambig, see the dev-guide: + /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html /// /// The [`Visitor::visit_infer`] method should be overridden in order to handle infer vars. fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) -> Self::Result { @@ -375,8 +375,8 @@ pub trait Visitor<'v>: Sized { /// All consts are treated as ambiguous consts for the purposes of hir visiting in /// order to ensure that visitors can handle infer vars without it being too error-prone. /// - /// See the doc comments on [`ConstArg`] for an explanation of what it means for a const to be - /// ambiguous. + /// For an explanation of what it means for a const arg to be ambig, see the dev-guide: + /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html /// /// The [`Visitor::visit_infer`] method should be overridden in order to handle infer vars. fn visit_const_arg(&mut self, c: &'v ConstArg<'v, AmbigArg>) -> Self::Result { @@ -516,6 +516,9 @@ pub trait VisitorExt<'v>: Visitor<'v> { /// /// Named `visit_ty_unambig` instead of `visit_unambig_ty` to aid in discovery /// by IDes when `v.visit_ty` is written. + /// + /// For an explanation of what it means for a type to be unambig, see the dev-guide: + /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html fn visit_ty_unambig(&mut self, t: &'v Ty<'v>) -> Self::Result { walk_unambig_ty(self, t) } @@ -524,6 +527,9 @@ pub trait VisitorExt<'v>: Visitor<'v> { /// /// Named `visit_const_arg_unambig` instead of `visit_unambig_const_arg` to aid in /// discovery by IDes when `v.visit_const_arg` is written. + /// + /// For an explanation of what it means for a const arg to be unambig, see the dev-guide: + /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html fn visit_const_arg_unambig(&mut self, c: &'v ConstArg<'v>) -> Self::Result { walk_unambig_const_arg(self, c) } @@ -975,6 +981,8 @@ pub fn walk_generic_arg<'v, V: Visitor<'v>>( } } +/// For an explanation of what it means for a type to be unambig, see the dev-guide: +/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn walk_unambig_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) -> V::Result { match typ.try_as_ambig_ty() { Some(ambig_ty) => visitor.visit_ty(ambig_ty), @@ -985,6 +993,8 @@ pub fn walk_unambig_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) -> } } +/// For an explanation of what it means for a type to be ambig, see the dev-guide: +/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v, AmbigArg>) -> V::Result { let Ty { hir_id, span: _, kind } = typ; try_visit!(visitor.visit_id(*hir_id)); @@ -1037,6 +1047,8 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v, AmbigArg>) - V::Result::output() } +/// For an explanation of what it means for a const arg to be unambig, see the dev-guide: +/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn walk_unambig_const_arg<'v, V: Visitor<'v>>( visitor: &mut V, const_arg: &'v ConstArg<'v>, @@ -1050,6 +1062,8 @@ pub fn walk_unambig_const_arg<'v, V: Visitor<'v>>( } } +/// For an explanation of what it means for a const arg to be ambig, see the dev-guide: +/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn walk_const_arg<'v, V: Visitor<'v>>( visitor: &mut V, const_arg: &'v ConstArg<'v, AmbigArg>, From eb2913b01b3e423b2bcd73cc62406ffecbe59ea3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20du=20Garreau?= Date: Thu, 19 Jun 2025 21:55:55 +0200 Subject: [PATCH 0027/1134] Fix unsoundness in some tests --- library/coretests/tests/io/borrowed_buf.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/coretests/tests/io/borrowed_buf.rs b/library/coretests/tests/io/borrowed_buf.rs index fbd3864dcac1..8fbf9c3e8a2a 100644 --- a/library/coretests/tests/io/borrowed_buf.rs +++ b/library/coretests/tests/io/borrowed_buf.rs @@ -66,7 +66,7 @@ fn clear() { #[test] fn set_init() { - let buf: &mut [_] = &mut [MaybeUninit::uninit(); 16]; + let buf: &mut [_] = &mut [MaybeUninit::zeroed(); 16]; let mut rbuf: BorrowedBuf<'_> = buf.into(); unsafe { @@ -134,7 +134,7 @@ fn reborrow_written() { #[test] fn cursor_set_init() { - let buf: &mut [_] = &mut [MaybeUninit::uninit(); 16]; + let buf: &mut [_] = &mut [MaybeUninit::zeroed(); 16]; let mut rbuf: BorrowedBuf<'_> = buf.into(); unsafe { From 31b9de6965d955bc95d107ed2e58a75a3d902488 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Fri, 20 Jun 2025 15:49:14 +0800 Subject: [PATCH 0028/1134] fix: `let_unit_value` suggests wrongly for format macros --- clippy_lints/src/lib.rs | 3 +- clippy_lints/src/unit_types/let_unit_value.rs | 109 +++++++++++++----- clippy_lints/src/unit_types/mod.rs | 17 ++- tests/ui/let_unit.fixed | 11 ++ tests/ui/let_unit.rs | 10 ++ tests/ui/let_unit.stderr | 16 ++- 6 files changed, 131 insertions(+), 35 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 96a6dee58852..792acec9e527 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -523,7 +523,8 @@ pub fn register_lint_passes(store: &mut rustc_lint::LintStore, conf: &'static Co store.register_late_pass(|_| Box::new(same_name_method::SameNameMethod)); store.register_late_pass(move |_| Box::new(index_refutable_slice::IndexRefutableSlice::new(conf))); store.register_late_pass(|_| Box::::default()); - store.register_late_pass(|_| Box::new(unit_types::UnitTypes)); + let format_args = format_args_storage.clone(); + store.register_late_pass(move |_| Box::new(unit_types::UnitTypes::new(format_args.clone()))); store.register_late_pass(move |_| Box::new(loops::Loops::new(conf))); store.register_late_pass(|_| Box::::default()); store.register_late_pass(move |_| Box::new(lifetimes::Lifetimes::new(conf))); diff --git a/clippy_lints/src/unit_types/let_unit_value.rs b/clippy_lints/src/unit_types/let_unit_value.rs index 87f184e13ce1..d5b6c1758549 100644 --- a/clippy_lints/src/unit_types/let_unit_value.rs +++ b/clippy_lints/src/unit_types/let_unit_value.rs @@ -1,17 +1,20 @@ use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::snippet_with_context; +use clippy_utils::macros::{FormatArgsStorage, find_format_arg_expr, is_format_macro, root_macro_call_first_node}; +use clippy_utils::source::{indent_of, reindent_multiline, snippet_with_context}; use clippy_utils::visitors::{for_each_local_assignment, for_each_value_source}; use core::ops::ControlFlow; +use rustc_ast::{FormatArgs, FormatArgumentKind}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::intravisit::{Visitor, walk_body}; +use rustc_hir::intravisit::{Visitor, walk_body, walk_expr}; use rustc_hir::{Expr, ExprKind, HirId, HirIdSet, LetStmt, MatchSource, Node, PatKind, QPath, TyKind}; use rustc_lint::{LateContext, LintContext}; use rustc_middle::ty; +use rustc_span::Span; use super::LET_UNIT_VALUE; -pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, local: &'tcx LetStmt<'_>) { +pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, format_args: &FormatArgsStorage, local: &'tcx LetStmt<'_>) { // skip `let () = { ... }` if let PatKind::Tuple(fields, ..) = local.pat.kind && fields.is_empty() @@ -73,11 +76,8 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, local: &'tcx LetStmt<'_>) { let mut suggestions = Vec::new(); // Suggest omitting the `let` binding - if let Some(expr) = &local.init { - let mut app = Applicability::MachineApplicable; - let snip = snippet_with_context(cx, expr.span, local.span.ctxt(), "()", &mut app).0; - suggestions.push((local.span, format!("{snip};"))); - } + let mut app = Applicability::MachineApplicable; + let snip = snippet_with_context(cx, init.span, local.span.ctxt(), "()", &mut app).0; // If this is a binding pattern, we need to add suggestions to remove any usages // of the variable @@ -85,53 +85,102 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, local: &'tcx LetStmt<'_>) { && let Some(body_id) = cx.enclosing_body.as_ref() { let body = cx.tcx.hir_body(*body_id); - - // Collect variable usages - let mut visitor = UnitVariableCollector::new(binding_hir_id); + let mut visitor = UnitVariableCollector::new(cx, format_args, binding_hir_id); walk_body(&mut visitor, body); - // Add suggestions for replacing variable usages - suggestions.extend(visitor.spans.into_iter().map(|span| (span, "()".to_string()))); - } + let mut has_in_format_capture = false; + suggestions.extend(visitor.spans.iter().filter_map(|span| match span { + MaybeInFormatCapture::Yes => { + has_in_format_capture = true; + None + }, + MaybeInFormatCapture::No(span) => Some((*span, "()".to_string())), + })); - // Emit appropriate diagnostic based on whether there are usages of the let binding - if !suggestions.is_empty() { - let message = if suggestions.len() == 1 { - "omit the `let` binding" - } else { - "omit the `let` binding and replace variable usages with `()`" - }; - diag.multipart_suggestion(message, suggestions, Applicability::MachineApplicable); + if has_in_format_capture { + suggestions.push(( + init.span, + format!("();\n{}", reindent_multiline(&snip, false, indent_of(cx, local.span))), + )); + diag.multipart_suggestion( + "replace variable usages with `()`", + suggestions, + Applicability::MachineApplicable, + ); + return; + } } + + suggestions.push((local.span, format!("{snip};"))); + let message = if suggestions.len() == 1 { + "omit the `let` binding" + } else { + "omit the `let` binding and replace variable usages with `()`" + }; + diag.multipart_suggestion(message, suggestions, Applicability::MachineApplicable); }, ); } } } -struct UnitVariableCollector { +struct UnitVariableCollector<'a, 'tcx> { + cx: &'a LateContext<'tcx>, + format_args: &'a FormatArgsStorage, id: HirId, - spans: Vec, + spans: Vec, + macro_call: Option<&'a FormatArgs>, } -impl UnitVariableCollector { - fn new(id: HirId) -> Self { - Self { id, spans: vec![] } +enum MaybeInFormatCapture { + Yes, + No(Span), +} + +impl<'a, 'tcx> UnitVariableCollector<'a, 'tcx> { + fn new(cx: &'a LateContext<'tcx>, format_args: &'a FormatArgsStorage, id: HirId) -> Self { + Self { + cx, + format_args, + id, + spans: Vec::new(), + macro_call: None, + } } } /** * Collect all instances where a variable is used based on its `HirId`. */ -impl<'tcx> Visitor<'tcx> for UnitVariableCollector { +impl<'tcx> Visitor<'tcx> for UnitVariableCollector<'_, 'tcx> { fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) -> Self::Result { + if let Some(macro_call) = root_macro_call_first_node(self.cx, ex) + && is_format_macro(self.cx, macro_call.def_id) + && let Some(format_args) = self.format_args.get(self.cx, ex, macro_call.expn) + { + let parent_macro_call = self.macro_call; + self.macro_call = Some(format_args); + walk_expr(self, ex); + self.macro_call = parent_macro_call; + return; + } + if let ExprKind::Path(QPath::Resolved(None, path)) = ex.kind && let Res::Local(id) = path.res && id == self.id { - self.spans.push(path.span); + if let Some(macro_call) = self.macro_call + && macro_call.arguments.all_args().iter().any(|arg| { + matches!(arg.kind, FormatArgumentKind::Captured(_)) && find_format_arg_expr(ex, arg).is_some() + }) + { + self.spans.push(MaybeInFormatCapture::Yes); + } else { + self.spans.push(MaybeInFormatCapture::No(path.span)); + } } - rustc_hir::intravisit::walk_expr(self, ex); + + walk_expr(self, ex); } } diff --git a/clippy_lints/src/unit_types/mod.rs b/clippy_lints/src/unit_types/mod.rs index e016bd3434b1..4ffcc247acf6 100644 --- a/clippy_lints/src/unit_types/mod.rs +++ b/clippy_lints/src/unit_types/mod.rs @@ -3,9 +3,10 @@ mod unit_arg; mod unit_cmp; mod utils; +use clippy_utils::macros::FormatArgsStorage; use rustc_hir::{Expr, LetStmt}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_session::declare_lint_pass; +use rustc_session::impl_lint_pass; declare_clippy_lint! { /// ### What it does @@ -96,11 +97,21 @@ declare_clippy_lint! { "passing unit to a function" } -declare_lint_pass!(UnitTypes => [LET_UNIT_VALUE, UNIT_CMP, UNIT_ARG]); +pub struct UnitTypes { + format_args: FormatArgsStorage, +} + +impl_lint_pass!(UnitTypes => [LET_UNIT_VALUE, UNIT_CMP, UNIT_ARG]); + +impl UnitTypes { + pub fn new(format_args: FormatArgsStorage) -> Self { + Self { format_args } + } +} impl<'tcx> LateLintPass<'tcx> for UnitTypes { fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx LetStmt<'tcx>) { - let_unit_value::check(cx, local); + let_unit_value::check(cx, &self.format_args, local); } fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { diff --git a/tests/ui/let_unit.fixed b/tests/ui/let_unit.fixed index 5e7a2ad37a84..0484ab297306 100644 --- a/tests/ui/let_unit.fixed +++ b/tests/ui/let_unit.fixed @@ -198,3 +198,14 @@ pub fn issue12594() { returns_result(res).unwrap(); } } + +fn issue15061() { + fn return_unit() {} + fn do_something(x: ()) {} + + let res = (); + return_unit(); + //~^ let_unit_value + do_something(()); + println!("{res:?}"); +} diff --git a/tests/ui/let_unit.rs b/tests/ui/let_unit.rs index 7b06f6940121..a0afc995b6f9 100644 --- a/tests/ui/let_unit.rs +++ b/tests/ui/let_unit.rs @@ -198,3 +198,13 @@ pub fn issue12594() { returns_result(res).unwrap(); } } + +fn issue15061() { + fn return_unit() {} + fn do_something(x: ()) {} + + let res = return_unit(); + //~^ let_unit_value + do_something(res); + println!("{res:?}"); +} diff --git a/tests/ui/let_unit.stderr b/tests/ui/let_unit.stderr index d7d01d304cad..0bc4da8b9c60 100644 --- a/tests/ui/let_unit.stderr +++ b/tests/ui/let_unit.stderr @@ -68,5 +68,19 @@ LL ~ returns_result(()).unwrap(); LL ~ returns_result(()).unwrap(); | -error: aborting due to 4 previous errors +error: this let-binding has unit value + --> tests/ui/let_unit.rs:206:5 + | +LL | let res = return_unit(); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: replace variable usages with `()` + | +LL ~ let res = (); +LL ~ return_unit(); +LL | +LL ~ do_something(()); + | + +error: aborting due to 5 previous errors From 6dbac3f09e67c853f343df9d75a7eb213f16c959 Mon Sep 17 00:00:00 2001 From: Jed Brown Date: Wed, 26 Feb 2025 20:06:25 -0700 Subject: [PATCH 0029/1134] add nvptx_target_feature Add target features for sm_* and ptx*, both of which form a partial order, but cannot be combined to a single partial order. These mirror the LLVM target features, but we do not provide LLVM target processors (which imply both an sm_* and ptx* feature). Add some documentation for the nvptx target. --- compiler/rustc_codegen_llvm/src/llvm_util.rs | 9 +++ compiler/rustc_feature/src/unstable.rs | 1 + compiler/rustc_span/src/symbol.rs | 1 + compiler/rustc_target/src/target_features.rs | 69 ++++++++++++++++++- library/core/src/lib.rs | 1 + .../platform-support/nvptx64-nvidia-cuda.md | 40 +++++++++++ tests/ui/check-cfg/target_feature.stderr | 56 +++++++++++++++ tests/ui/target-feature/gate.rs | 1 + tests/ui/target-feature/gate.stderr | 2 +- 9 files changed, 178 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 6fd07d562afd..202b9641e567 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -262,6 +262,15 @@ pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option None, // only existed in 18 ("arm", "fp16") => Some(LLVMFeature::new("fullfp16")), + // NVPTX targets added in LLVM 20 + ("nvptx64", "sm_100") if get_version().0 < 20 => None, + ("nvptx64", "sm_100a") if get_version().0 < 20 => None, + ("nvptx64", "sm_101") if get_version().0 < 20 => None, + ("nvptx64", "sm_101a") if get_version().0 < 20 => None, + ("nvptx64", "sm_120") if get_version().0 < 20 => None, + ("nvptx64", "sm_120a") if get_version().0 < 20 => None, + ("nvptx64", "ptx86") if get_version().0 < 20 => None, + ("nvptx64", "ptx87") if get_version().0 < 20 => None, // Filter out features that are not supported by the current LLVM version ("loongarch64", "div32" | "lam-bh" | "lamcas" | "ld-seq-sa" | "scq") if get_version().0 < 20 => diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 91715851226b..bc48b45bce17 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -329,6 +329,7 @@ declare_features! ( (unstable, m68k_target_feature, "1.85.0", Some(134328)), (unstable, mips_target_feature, "1.27.0", Some(44839)), (unstable, movrs_target_feature, "1.88.0", Some(137976)), + (unstable, nvptx_target_feature, "CURRENT_RUSTC_VERSION", Some(44839)), (unstable, powerpc_target_feature, "1.27.0", Some(44839)), (unstable, prfchw_target_feature, "1.78.0", Some(44839)), (unstable, riscv_target_feature, "1.45.0", Some(44839)), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index da69f6c44927..b0dd144bf47e 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1509,6 +1509,7 @@ symbols! { not, notable_trait, note, + nvptx_target_feature, object_safe_for_dispatch, of, off, diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 3eea1e070a66..3449c16ee4ae 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -517,6 +517,71 @@ const MIPS_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-end ]; +const NVPTX_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ + // tidy-alphabetical-start + ("sm_20", Unstable(sym::nvptx_target_feature), &[]), + ("sm_21", Unstable(sym::nvptx_target_feature), &["sm_20"]), + ("sm_30", Unstable(sym::nvptx_target_feature), &["sm_21"]), + ("sm_32", Unstable(sym::nvptx_target_feature), &["sm_30"]), + ("sm_35", Unstable(sym::nvptx_target_feature), &["sm_32"]), + ("sm_37", Unstable(sym::nvptx_target_feature), &["sm_35"]), + ("sm_50", Unstable(sym::nvptx_target_feature), &["sm_37"]), + ("sm_52", Unstable(sym::nvptx_target_feature), &["sm_50"]), + ("sm_53", Unstable(sym::nvptx_target_feature), &["sm_52"]), + ("sm_60", Unstable(sym::nvptx_target_feature), &["sm_53"]), + ("sm_61", Unstable(sym::nvptx_target_feature), &["sm_60"]), + ("sm_62", Unstable(sym::nvptx_target_feature), &["sm_61"]), + ("sm_70", Unstable(sym::nvptx_target_feature), &["sm_62"]), + ("sm_72", Unstable(sym::nvptx_target_feature), &["sm_70"]), + ("sm_75", Unstable(sym::nvptx_target_feature), &["sm_72"]), + ("sm_80", Unstable(sym::nvptx_target_feature), &["sm_75"]), + ("sm_86", Unstable(sym::nvptx_target_feature), &["sm_80"]), + ("sm_87", Unstable(sym::nvptx_target_feature), &["sm_86"]), + ("sm_89", Unstable(sym::nvptx_target_feature), &["sm_87"]), + ("sm_90", Unstable(sym::nvptx_target_feature), &["sm_89"]), + ("sm_90a", Unstable(sym::nvptx_target_feature), &["sm_90"]), + // tidy-alphabetical-end + // tidy-alphabetical-start + ("sm_100", Unstable(sym::nvptx_target_feature), &["sm_90"]), + ("sm_100a", Unstable(sym::nvptx_target_feature), &["sm_100"]), + ("sm_101", Unstable(sym::nvptx_target_feature), &["sm_100"]), + ("sm_101a", Unstable(sym::nvptx_target_feature), &["sm_101"]), + ("sm_120", Unstable(sym::nvptx_target_feature), &["sm_101"]), + ("sm_120a", Unstable(sym::nvptx_target_feature), &["sm_120"]), + // tidy-alphabetical-end + // tidy-alphabetical-start + ("ptx32", Unstable(sym::nvptx_target_feature), &[]), + ("ptx40", Unstable(sym::nvptx_target_feature), &["ptx32"]), + ("ptx41", Unstable(sym::nvptx_target_feature), &["ptx40"]), + ("ptx42", Unstable(sym::nvptx_target_feature), &["ptx41"]), + ("ptx43", Unstable(sym::nvptx_target_feature), &["ptx42"]), + ("ptx50", Unstable(sym::nvptx_target_feature), &["ptx43"]), + ("ptx60", Unstable(sym::nvptx_target_feature), &["ptx50"]), + ("ptx61", Unstable(sym::nvptx_target_feature), &["ptx60"]), + ("ptx62", Unstable(sym::nvptx_target_feature), &["ptx61"]), + ("ptx63", Unstable(sym::nvptx_target_feature), &["ptx62"]), + ("ptx64", Unstable(sym::nvptx_target_feature), &["ptx63"]), + ("ptx65", Unstable(sym::nvptx_target_feature), &["ptx64"]), + ("ptx70", Unstable(sym::nvptx_target_feature), &["ptx65"]), + ("ptx71", Unstable(sym::nvptx_target_feature), &["ptx70"]), + ("ptx72", Unstable(sym::nvptx_target_feature), &["ptx71"]), + ("ptx73", Unstable(sym::nvptx_target_feature), &["ptx72"]), + ("ptx74", Unstable(sym::nvptx_target_feature), &["ptx73"]), + ("ptx75", Unstable(sym::nvptx_target_feature), &["ptx74"]), + ("ptx76", Unstable(sym::nvptx_target_feature), &["ptx75"]), + ("ptx77", Unstable(sym::nvptx_target_feature), &["ptx76"]), + ("ptx78", Unstable(sym::nvptx_target_feature), &["ptx77"]), + ("ptx80", Unstable(sym::nvptx_target_feature), &["ptx78"]), + ("ptx81", Unstable(sym::nvptx_target_feature), &["ptx80"]), + ("ptx82", Unstable(sym::nvptx_target_feature), &["ptx81"]), + ("ptx83", Unstable(sym::nvptx_target_feature), &["ptx82"]), + ("ptx84", Unstable(sym::nvptx_target_feature), &["ptx83"]), + ("ptx85", Unstable(sym::nvptx_target_feature), &["ptx84"]), + ("ptx86", Unstable(sym::nvptx_target_feature), &["ptx85"]), + ("ptx87", Unstable(sym::nvptx_target_feature), &["ptx86"]), + // tidy-alphabetical-end +]; + static RISCV_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-start ("a", Stable, &["zaamo", "zalrsc"]), @@ -782,6 +847,7 @@ pub fn all_rust_features() -> impl Iterator { .chain(HEXAGON_FEATURES.iter()) .chain(POWERPC_FEATURES.iter()) .chain(MIPS_FEATURES.iter()) + .chain(NVPTX_FEATURES.iter()) .chain(RISCV_FEATURES.iter()) .chain(WASM_FEATURES.iter()) .chain(BPF_FEATURES.iter()) @@ -847,6 +913,7 @@ impl Target { "x86" | "x86_64" => X86_FEATURES, "hexagon" => HEXAGON_FEATURES, "mips" | "mips32r6" | "mips64" | "mips64r6" => MIPS_FEATURES, + "nvptx64" => NVPTX_FEATURES, "powerpc" | "powerpc64" => POWERPC_FEATURES, "riscv32" | "riscv64" => RISCV_FEATURES, "wasm32" | "wasm64" => WASM_FEATURES, @@ -873,7 +940,7 @@ impl Target { "sparc" | "sparc64" => SPARC_FEATURES_FOR_CORRECT_VECTOR_ABI, "hexagon" => HEXAGON_FEATURES_FOR_CORRECT_VECTOR_ABI, "mips" | "mips32r6" | "mips64" | "mips64r6" => MIPS_FEATURES_FOR_CORRECT_VECTOR_ABI, - "bpf" | "m68k" => &[], // no vector ABI + "nvptx64" | "bpf" | "m68k" => &[], // no vector ABI "csky" => CSKY_FEATURES_FOR_CORRECT_VECTOR_ABI, // FIXME: for some tier3 targets, we are overly cautious and always give warnings // when passing args in vector registers. diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 39d5399101da..4ff142bf5d05 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -192,6 +192,7 @@ #![feature(hexagon_target_feature)] #![feature(loongarch_target_feature)] #![feature(mips_target_feature)] +#![feature(nvptx_target_feature)] #![feature(powerpc_target_feature)] #![feature(riscv_target_feature)] #![feature(rtm_target_feature)] diff --git a/src/doc/rustc/src/platform-support/nvptx64-nvidia-cuda.md b/src/doc/rustc/src/platform-support/nvptx64-nvidia-cuda.md index 106ec562bfc7..36598982481b 100644 --- a/src/doc/rustc/src/platform-support/nvptx64-nvidia-cuda.md +++ b/src/doc/rustc/src/platform-support/nvptx64-nvidia-cuda.md @@ -10,6 +10,46 @@ platform. [@RDambrosio016](https://github.com/RDambrosio016) [@kjetilkjeka](https://github.com/kjetilkjeka) +## Requirements + +This target is `no_std` and will typically be built with crate-type `cdylib` and `-C linker-flavor=llbc`, which generates PTX. +The necessary components for this workflow are: + +- `rustup toolchain add nightly` +- `rustup component add llvm-tools --toolchain nightly` +- `rustup component add llvm-bitcode-linker --toolchain nightly` + +There are two options for using the core library: + +- `rustup component add rust-src --toolchain nightly` and build using `-Z build-std=core`. +- `rustup target add nvptx64-nvidia-cuda --toolchain nightly` + +### Target and features + +It is generally necessary to specify the target, such as `-C target-cpu=sm_89`, because the default is very old. This implies two target features: `sm_89` and `ptx78` (and all preceding features within `sm_*` and `ptx*`). Rust will default to using the oldest PTX version that supports the target processor (see [this table](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#release-notes-ptx-release-history)), which maximizes driver compatibility. +One can use `-C target-feature=+ptx80` to choose a later PTX version without changing the target (the default in this case, `ptx78`, requires CUDA driver version 11.8, while `ptx80` would require driver version 12.0). +Later PTX versions may allow more efficient code generation. + +Although Rust follows LLVM in representing `ptx*` and `sm_*` as target features, they should be thought of as having crate granularity, set via (either via `-Ctarget-cpu` and optionally `-Ctarget-feature`). +While the compiler accepts `#[target_feature(enable = "ptx80", enable = "sm_89")]`, it is not supported, may not behave as intended, and may become erroneous in the future. + +## Building Rust kernels + +A `no_std` crate containing one or more functions with `extern "ptx-kernel"` can be compiled to PTX using a command like the following. + +```console +$ RUSTFLAGS='-Ctarget-cpu=sm_89' cargo +nightly rustc --target=nvptx64-nvidia-cuda -Zbuild-std=core --crate-type=cdylib -- -Clinker-flavor=llbc -Zunstable-options +``` + +Intrinsics in `core::arch::nvptx` may use `#[cfg(target_feature = "...")]`, thus it's necessary to use `-Zbuild-std=core` with appropriate `RUSTFLAGS`. The following components are needed for this workflow: + +```console +$ rustup component add rust-src --toolchain nightly +$ rustup component add llvm-tools --toolchain nightly +$ rustup component add llvm-bitcode-linker --toolchain nightly +``` + + $DIR/gate.rs:29:18 + --> $DIR/gate.rs:30:18 | LL | #[target_feature(enable = "x87")] | ^^^^^^^^^^^^^^ From 35a485ddd86229101c4c17d9167f23cf75cae644 Mon Sep 17 00:00:00 2001 From: Jed Brown Date: Wed, 21 May 2025 22:08:51 -0600 Subject: [PATCH 0030/1134] target-feature: enable rust target features implied by target-cpu Normally LLVM and rustc agree about what features are implied by target-cpu, but for NVPTX, LLVM considers sm_* and ptx* features to be exclusive, which makes sense for codegen purposes. But in Rust, we want to think of them as: sm_{sver} means that the target supports the hardware features of sver ptx{pver} means the driver supports PTX ISA pver Intrinsics usually require a minimum sm_{sver} and ptx{pver}. Prior to this commit, -Ctarget-cpu=sm_70 would activate only sm_70 and ptx60 (the minimum PTX version that supports sm_70, which maximizes driver compatibility). With this commit, it also activates all the implied target features (sm_20, ..., sm_62; ptx32, ..., ptx50). --- compiler/rustc_codegen_llvm/src/llvm_util.rs | 9 ++---- .../rustc_codegen_ssa/src/target_features.rs | 15 ++++++++-- .../target-feature/implied-features-nvptx.rs | 28 +++++++++++++++++++ 3 files changed, 44 insertions(+), 8 deletions(-) create mode 100644 tests/ui/target-feature/implied-features-nvptx.rs diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 202b9641e567..2c1882e24bed 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -333,15 +333,12 @@ pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option TargetConfig { - // Add base features for the target. - // We do *not* add the -Ctarget-features there, and instead duplicate the logic for that below. - // The reason is that if LLVM considers a feature implied but we do not, we don't want that to - // show up in `cfg`. That way, `cfg` is entirely under our control -- except for the handling of - // the target CPU, that is still expanded to target features (with all their implied features) - // by LLVM. let target_machine = create_informational_target_machine(sess, true); let (unstable_target_features, target_features) = cfg_target_feature(sess, |feature| { + // This closure determines whether the target CPU has the feature according to LLVM. We do + // *not* consider the `-Ctarget-feature`s here, as that will be handled later in + // `cfg_target_feature`. if let Some(feat) = to_llvm_features(sess, feature) { // All the LLVM features this expands to must be enabled. for llvm_feature in feat { diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 67ac619091be..e291fb8649c1 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -224,7 +224,10 @@ fn parse_rust_feature_flag<'a>( /// 2nd component of the return value, respectively). /// /// `target_base_has_feature` should check whether the given feature (a Rust feature name!) is -/// enabled in the "base" target machine, i.e., without applying `-Ctarget-feature`. +/// enabled in the "base" target machine, i.e., without applying `-Ctarget-feature`. Note that LLVM +/// may consider features to be implied that we do not and vice-versa. We want `cfg` to be entirely +/// consistent with Rust feature implications, and thus only consult LLVM to expand the target CPU +/// to target features. /// /// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled elsewhere. pub fn cfg_target_feature( @@ -238,7 +241,15 @@ pub fn cfg_target_feature( .rust_target_features() .iter() .filter(|(feature, _, _)| target_base_has_feature(feature)) - .map(|(feature, _, _)| Symbol::intern(feature)) + .flat_map(|(base_feature, _, _)| { + // Expand the direct base feature into all transitively-implied features. Note that we + // cannot simply use the `implied` field of the tuple since that only contains + // directly-implied features. + // + // Iteration order is irrelevant because we're collecting into an `UnordSet`. + #[allow(rustc::potential_query_instability)] + sess.target.implied_target_features(base_feature).into_iter().map(|f| Symbol::intern(f)) + }) .collect(); // Add enabled and remove disabled features. diff --git a/tests/ui/target-feature/implied-features-nvptx.rs b/tests/ui/target-feature/implied-features-nvptx.rs new file mode 100644 index 000000000000..1550c99f67a8 --- /dev/null +++ b/tests/ui/target-feature/implied-features-nvptx.rs @@ -0,0 +1,28 @@ +//@ assembly-output: ptx-linker +//@ compile-flags: --crate-type cdylib -C target-cpu=sm_80 -Z unstable-options -Clinker-flavor=llbc +//@ only-nvptx64 +//@ build-pass +#![no_std] +#![allow(dead_code)] + +#[panic_handler] +pub fn panic(_info: &core::panic::PanicInfo) -> ! { + loop {} +} + +// -Ctarget-cpu=sm_80 directly enables sm_80 and ptx70 +#[cfg(not(all(target_feature = "sm_80", target_feature = "ptx70")))] +compile_error!("direct target features not enabled"); + +// -Ctarget-cpu=sm_80 implies all earlier sm_* and ptx* features. +#[cfg(not(all( + target_feature = "sm_60", + target_feature = "sm_70", + target_feature = "ptx50", + target_feature = "ptx60", +)))] +compile_error!("implied target features not enabled"); + +// -Ctarget-cpu=sm_80 implies all earlier sm_* and ptx* features. +#[cfg(target_feature = "ptx71")] +compile_error!("sm_80 requires only ptx70, but ptx71 enabled"); From 06ae1bee205c9f85cc89047568737a87c791a032 Mon Sep 17 00:00:00 2001 From: yukang Date: Sun, 22 Jun 2025 20:43:31 +0800 Subject: [PATCH 0031/1134] Make doc for transpose api better --- library/core/src/option.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index f2a1e901188f..2132376b3c57 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -2037,9 +2037,9 @@ impl Option<&mut T> { impl Option> { /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`. /// - /// [`None`] will be mapped to [Ok]\([None]). - /// [Some]\([Ok]\(\_)) and [Some]\([Err]\(\_)) will be mapped to - /// [Ok]\([Some]\(\_)) and [Err]\(\_). + /// [Some]\([Ok]\(\_)) is mapped to [Ok]\([Some]\(\_)), + /// [Some]\([Err]\(\_)) is mapped to [Err]\(\_), + /// and [`None`] will be mapped to [Ok]\([None]). /// /// # Examples /// @@ -2047,9 +2047,9 @@ impl Option> { /// #[derive(Debug, Eq, PartialEq)] /// struct SomeErr; /// - /// let x: Result, SomeErr> = Ok(Some(5)); - /// let y: Option> = Some(Ok(5)); - /// assert_eq!(x, y.transpose()); + /// let x: Option> = Some(Ok(5)); + /// let y: Result, SomeErr> = Ok(Some(5)); + /// assert_eq!(x.transpose(), y); /// ``` #[inline] #[stable(feature = "transpose_result", since = "1.33.0")] From fa5895ea8c39cb2d8f7078ccd4e78a41aeb2eb84 Mon Sep 17 00:00:00 2001 From: Boxy Date: Wed, 25 Jun 2025 12:29:04 +0100 Subject: [PATCH 0032/1134] Reviews --- compiler/rustc_hir/src/hir.rs | 27 ++++++--------------------- compiler/rustc_hir/src/intravisit.rs | 20 -------------------- 2 files changed, 6 insertions(+), 41 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index bd59ad613d63..380120ecfe28 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -408,7 +408,7 @@ impl<'hir> PathSegment<'hir> { /// versus const args that are literals or have arbitrary computations (e.g., `{ 1 + 3 }`). /// /// For an explanation of the `Unambig` generic parameter see the dev-guide: -/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html +/// #[derive(Clone, Copy, Debug, HashStable_Generic)] #[repr(C)] pub struct ConstArg<'hir, Unambig = ()> { @@ -420,16 +420,13 @@ pub struct ConstArg<'hir, Unambig = ()> { impl<'hir> ConstArg<'hir, AmbigArg> { /// Converts a `ConstArg` in an ambiguous position to one in an unambiguous position. /// - /// Functions accepting an unambiguous consts may expect the [`ConstArgKind::Infer`] variant + /// Functions accepting unambiguous consts may expect the [`ConstArgKind::Infer`] variant /// to be used. Care should be taken to separately handle infer consts when calling this /// function as it cannot be handled by downstream code making use of the returned const. /// /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or /// specifically matching on [`GenericArg::Infer`] when handling generic arguments. /// - /// For an explanation of what it means for a const arg to be ambig or unambig, see the dev-guide: - /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html - /// /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer] pub fn as_unambig_ct(&self) -> &ConstArg<'hir> { // SAFETY: `ConstArg` is `repr(C)` and `ConstArgKind` is marked `repr(u8)` so that the @@ -445,9 +442,6 @@ impl<'hir> ConstArg<'hir> { /// /// Functions accepting ambiguous consts will not handle the [`ConstArgKind::Infer`] variant, if /// infer consts are relevant to you then care should be taken to handle them separately. - /// - /// For an explanation of what it means for a const arg to be ambig or unambig, see the dev-guide: - /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn try_as_ambig_ct(&self) -> Option<&ConstArg<'hir, AmbigArg>> { if let ConstArgKind::Infer(_, ()) = self.kind { return None; @@ -479,9 +473,6 @@ impl<'hir, Unambig> ConstArg<'hir, Unambig> { } /// See [`ConstArg`]. -/// -/// For an explanation of the `Unambig` generic parameter see the dev-guide: -/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html #[derive(Clone, Copy, Debug, HashStable_Generic)] #[repr(u8, C)] pub enum ConstArgKind<'hir, Unambig = ()> { @@ -3305,12 +3296,12 @@ impl<'hir> AssocItemConstraintKind<'hir> { #[derive(Debug, Clone, Copy, HashStable_Generic)] pub enum AmbigArg {} -#[derive(Debug, Clone, Copy, HashStable_Generic)] -#[repr(C)] /// Represents a type in the `HIR`. /// /// For an explanation of the `Unambig` generic parameter see the dev-guide: -/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html +/// +#[derive(Debug, Clone, Copy, HashStable_Generic)] +#[repr(C)] pub struct Ty<'hir, Unambig = ()> { #[stable_hasher(ignore)] pub hir_id: HirId, @@ -3328,9 +3319,6 @@ impl<'hir> Ty<'hir, AmbigArg> { /// In practice this may mean overriding the [`Visitor::visit_infer`][visit_infer] method on hir visitors, or /// specifically matching on [`GenericArg::Infer`] when handling generic arguments. /// - /// For an explanation of what it means for a type to be ambig or unambig, see the dev-guide: - /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html - /// /// [visit_infer]: [rustc_hir::intravisit::Visitor::visit_infer] pub fn as_unambig_ty(&self) -> &Ty<'hir> { // SAFETY: `Ty` is `repr(C)` and `TyKind` is marked `repr(u8)` so that the layout is @@ -3346,9 +3334,6 @@ impl<'hir> Ty<'hir> { /// /// Functions accepting ambiguous types will not handle the [`TyKind::Infer`] variant, if /// infer types are relevant to you then care should be taken to handle them separately. - /// - /// For an explanation of what it means for a type to be ambig or unambig, see the dev-guide: - /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn try_as_ambig_ty(&self) -> Option<&Ty<'hir, AmbigArg>> { if let TyKind::Infer(()) = self.kind { return None; @@ -3653,7 +3638,7 @@ pub enum InferDelegationKind { /// The various kinds of types recognized by the compiler. /// /// For an explanation of the `Unambig` generic parameter see the dev-guide: -/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html +/// // SAFETY: `repr(u8)` is required so that `TyKind<()>` and `TyKind` are layout compatible #[repr(u8, C)] #[derive(Debug, Clone, Copy, HashStable_Generic)] diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index 95fee05a71b9..aa96ff1eb1af 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -364,9 +364,6 @@ pub trait Visitor<'v>: Sized { /// All types are treated as ambiguous types for the purposes of hir visiting in /// order to ensure that visitors can handle infer vars without it being too error-prone. /// - /// For an explanation of what it means for a type to be ambig, see the dev-guide: - /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html - /// /// The [`Visitor::visit_infer`] method should be overridden in order to handle infer vars. fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) -> Self::Result { walk_ty(self, t) @@ -375,9 +372,6 @@ pub trait Visitor<'v>: Sized { /// All consts are treated as ambiguous consts for the purposes of hir visiting in /// order to ensure that visitors can handle infer vars without it being too error-prone. /// - /// For an explanation of what it means for a const arg to be ambig, see the dev-guide: - /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html - /// /// The [`Visitor::visit_infer`] method should be overridden in order to handle infer vars. fn visit_const_arg(&mut self, c: &'v ConstArg<'v, AmbigArg>) -> Self::Result { walk_const_arg(self, c) @@ -516,9 +510,6 @@ pub trait VisitorExt<'v>: Visitor<'v> { /// /// Named `visit_ty_unambig` instead of `visit_unambig_ty` to aid in discovery /// by IDes when `v.visit_ty` is written. - /// - /// For an explanation of what it means for a type to be unambig, see the dev-guide: - /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html fn visit_ty_unambig(&mut self, t: &'v Ty<'v>) -> Self::Result { walk_unambig_ty(self, t) } @@ -527,9 +518,6 @@ pub trait VisitorExt<'v>: Visitor<'v> { /// /// Named `visit_const_arg_unambig` instead of `visit_unambig_const_arg` to aid in /// discovery by IDes when `v.visit_const_arg` is written. - /// - /// For an explanation of what it means for a const arg to be unambig, see the dev-guide: - /// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html fn visit_const_arg_unambig(&mut self, c: &'v ConstArg<'v>) -> Self::Result { walk_unambig_const_arg(self, c) } @@ -981,8 +969,6 @@ pub fn walk_generic_arg<'v, V: Visitor<'v>>( } } -/// For an explanation of what it means for a type to be unambig, see the dev-guide: -/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn walk_unambig_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) -> V::Result { match typ.try_as_ambig_ty() { Some(ambig_ty) => visitor.visit_ty(ambig_ty), @@ -993,8 +979,6 @@ pub fn walk_unambig_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) -> } } -/// For an explanation of what it means for a type to be ambig, see the dev-guide: -/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v, AmbigArg>) -> V::Result { let Ty { hir_id, span: _, kind } = typ; try_visit!(visitor.visit_id(*hir_id)); @@ -1047,8 +1031,6 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v, AmbigArg>) - V::Result::output() } -/// For an explanation of what it means for a const arg to be unambig, see the dev-guide: -/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn walk_unambig_const_arg<'v, V: Visitor<'v>>( visitor: &mut V, const_arg: &'v ConstArg<'v>, @@ -1062,8 +1044,6 @@ pub fn walk_unambig_const_arg<'v, V: Visitor<'v>>( } } -/// For an explanation of what it means for a const arg to be ambig, see the dev-guide: -/// https://rustc-dev-guide.rust-lang.org/hir/ambig-unambig-ty-and-consts.html pub fn walk_const_arg<'v, V: Visitor<'v>>( visitor: &mut V, const_arg: &'v ConstArg<'v, AmbigArg>, From c6a97d3c5939783c9df5ba876f0cc06d6fd0268c Mon Sep 17 00:00:00 2001 From: dianne Date: Wed, 25 Jun 2025 13:00:58 -0700 Subject: [PATCH 0033/1134] emit `StorageLive` and schedule `StorageDead` for `let`-`else` after matching --- compiler/rustc_mir_build/src/builder/block.rs | 12 +---- .../src/builder/matches/mod.rs | 52 +++---------------- .../issue_101867.main.built.after.mir | 3 +- ..._type_annotations.let_else.built.after.mir | 11 ++-- tests/ui/dropck/let-else-more-permissive.rs | 7 +-- .../ui/dropck/let-else-more-permissive.stderr | 20 ++++++- 6 files changed, 36 insertions(+), 69 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/block.rs b/compiler/rustc_mir_build/src/builder/block.rs index a71196f79d78..566d89f4269c 100644 --- a/compiler/rustc_mir_build/src/builder/block.rs +++ b/compiler/rustc_mir_build/src/builder/block.rs @@ -6,7 +6,7 @@ use rustc_span::Span; use tracing::debug; use crate::builder::ForGuard::OutsideGuard; -use crate::builder::matches::{DeclareLetBindings, EmitStorageLive, ScheduleDrops}; +use crate::builder::matches::{DeclareLetBindings, ScheduleDrops}; use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; impl<'a, 'tcx> Builder<'a, 'tcx> { @@ -199,15 +199,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { None, Some((Some(&destination), initializer_span)), ); - this.visit_primary_bindings(pattern, &mut |this, node, span| { - this.storage_live_binding( - block, - node, - span, - OutsideGuard, - ScheduleDrops::Yes, - ); - }); let else_block_span = this.thir[*else_block].span; let (matching, failure) = this.in_if_then_scope(last_remainder_scope, else_block_span, |this| { @@ -218,7 +209,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { None, initializer_span, DeclareLetBindings::No, - EmitStorageLive::No, ) }); matching.and(failure) diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 270a7d4b1543..78b81c14bd02 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -69,18 +69,6 @@ pub(crate) enum DeclareLetBindings { LetNotPermitted, } -/// Used by [`Builder::bind_matched_candidate_for_arm_body`] to determine -/// whether or not to call [`Builder::storage_live_binding`] to emit -/// [`StatementKind::StorageLive`]. -#[derive(Clone, Copy)] -pub(crate) enum EmitStorageLive { - /// Yes, emit `StorageLive` as normal. - Yes, - /// No, don't emit `StorageLive`. The caller has taken responsibility for - /// emitting `StorageLive` as appropriate. - No, -} - /// Used by [`Builder::storage_live_binding`] and [`Builder::bind_matched_candidate_for_arm_body`] /// to decide whether to schedule drops. #[derive(Clone, Copy, Debug)] @@ -207,7 +195,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { Some(args.variable_source_info.scope), args.variable_source_info.span, args.declare_let_bindings, - EmitStorageLive::Yes, ), _ => { let mut block = block; @@ -479,7 +466,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &built_match_tree.fake_borrow_temps, scrutinee_span, Some((arm, match_scope)), - EmitStorageLive::Yes, ); this.fixed_temps_scope = old_dedup_scope; @@ -533,7 +519,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { fake_borrow_temps: &[(Place<'tcx>, Local, FakeBorrowKind)], scrutinee_span: Span, arm_match_scope: Option<(&Arm<'tcx>, region::Scope)>, - emit_storage_live: EmitStorageLive, ) -> BasicBlock { if branch.sub_branches.len() == 1 { let [sub_branch] = branch.sub_branches.try_into().unwrap(); @@ -544,7 +529,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { scrutinee_span, arm_match_scope, ScheduleDrops::Yes, - emit_storage_live, ) } else { // It's helpful to avoid scheduling drops multiple times to save @@ -577,7 +561,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { scrutinee_span, arm_match_scope, schedule_drops, - emit_storage_live, ); if arm.is_none() { schedule_drops = ScheduleDrops::No; @@ -741,7 +724,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &[], irrefutable_pat.span, None, - EmitStorageLive::Yes, ) .unit() } @@ -2364,7 +2346,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { source_scope: Option, scope_span: Span, declare_let_bindings: DeclareLetBindings, - emit_storage_live: EmitStorageLive, ) -> BlockAnd<()> { let expr_span = self.thir[expr_id].span; let scrutinee = unpack!(block = self.lower_scrutinee(block, expr_id, expr_span)); @@ -2398,14 +2379,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - let success = self.bind_pattern( - self.source_info(pat.span), - branch, - &[], - expr_span, - None, - emit_storage_live, - ); + let success = self.bind_pattern(self.source_info(pat.span), branch, &[], expr_span, None); // If branch coverage is enabled, record this branch. self.visit_coverage_conditional_let(pat, success, built_tree.otherwise_block); @@ -2428,7 +2402,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { scrutinee_span: Span, arm_match_scope: Option<(&Arm<'tcx>, region::Scope)>, schedule_drops: ScheduleDrops, - emit_storage_live: EmitStorageLive, ) -> BasicBlock { debug!("bind_and_guard_matched_candidate(subbranch={:?})", sub_branch); @@ -2547,7 +2520,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { post_guard_block, ScheduleDrops::Yes, by_value_bindings, - emit_storage_live, ); post_guard_block @@ -2559,7 +2531,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { block, schedule_drops, sub_branch.bindings.iter(), - emit_storage_live, ); block } @@ -2730,7 +2701,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { block: BasicBlock, schedule_drops: ScheduleDrops, bindings: impl IntoIterator>, - emit_storage_live: EmitStorageLive, ) where 'tcx: 'b, { @@ -2740,19 +2710,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Assign each of the bindings. This may trigger moves out of the candidate. for binding in bindings { let source_info = self.source_info(binding.span); - let local = match emit_storage_live { - // Here storages are already alive, probably because this is a binding - // from let-else. - // We just need to schedule drop for the value. - EmitStorageLive::No => self.var_local_id(binding.var_id, OutsideGuard).into(), - EmitStorageLive::Yes => self.storage_live_binding( - block, - binding.var_id, - binding.span, - OutsideGuard, - schedule_drops, - ), - }; + let local = self.storage_live_binding( + block, + binding.var_id, + binding.span, + OutsideGuard, + schedule_drops, + ); if matches!(schedule_drops, ScheduleDrops::Yes) { self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard); } diff --git a/tests/mir-opt/building/issue_101867.main.built.after.mir b/tests/mir-opt/building/issue_101867.main.built.after.mir index dd1d093c4dba..35d22933afe9 100644 --- a/tests/mir-opt/building/issue_101867.main.built.after.mir +++ b/tests/mir-opt/building/issue_101867.main.built.after.mir @@ -24,7 +24,6 @@ fn main() -> () { _1 = Option::::Some(const 1_u8); FakeRead(ForLet(None), _1); AscribeUserType(_1, o, UserTypeProjection { base: UserType(1), projs: [] }); - StorageLive(_5); PlaceMention(_1); _6 = discriminant(_1); switchInt(move _6) -> [1: bb4, otherwise: bb3]; @@ -55,6 +54,7 @@ fn main() -> () { } bb6: { + StorageLive(_5); _5 = copy ((_1 as Some).0: u8); _0 = const (); StorageDead(_5); @@ -63,7 +63,6 @@ fn main() -> () { } bb7: { - StorageDead(_5); goto -> bb1; } diff --git a/tests/mir-opt/building/user_type_annotations.let_else.built.after.mir b/tests/mir-opt/building/user_type_annotations.let_else.built.after.mir index 3a515787c10b..2638da510118 100644 --- a/tests/mir-opt/building/user_type_annotations.let_else.built.after.mir +++ b/tests/mir-opt/building/user_type_annotations.let_else.built.after.mir @@ -21,9 +21,6 @@ fn let_else() -> () { } bb0: { - StorageLive(_2); - StorageLive(_3); - StorageLive(_4); StorageLive(_5); StorageLive(_6); StorageLive(_7); @@ -51,16 +48,19 @@ fn let_else() -> () { bb4: { AscribeUserType(_5, +, UserTypeProjection { base: UserType(1), projs: [] }); + StorageLive(_2); _2 = copy (_5.0: u32); + StorageLive(_3); _3 = copy (_5.1: u64); + StorageLive(_4); _4 = copy (_5.2: &char); StorageDead(_7); StorageDead(_5); _0 = const (); - StorageDead(_8); StorageDead(_4); StorageDead(_3); StorageDead(_2); + StorageDead(_8); return; } @@ -68,9 +68,6 @@ fn let_else() -> () { StorageDead(_7); StorageDead(_5); StorageDead(_8); - StorageDead(_4); - StorageDead(_3); - StorageDead(_2); goto -> bb1; } diff --git a/tests/ui/dropck/let-else-more-permissive.rs b/tests/ui/dropck/let-else-more-permissive.rs index 0020814aa81f..6247b0eb5e26 100644 --- a/tests/ui/dropck/let-else-more-permissive.rs +++ b/tests/ui/dropck/let-else-more-permissive.rs @@ -1,5 +1,5 @@ -//! The drop check is currently more permissive when `let` statements have an `else` block, due to -//! scheduling drops for bindings' storage before pattern-matching (#142056). +//! Regression test for #142056. The drop check used to be more permissive for `let` statements with +//! `else` blocks, due to scheduling drops for bindings' storage before pattern-matching. struct Struct(T); impl Drop for Struct { @@ -14,10 +14,11 @@ fn main() { //~^ ERROR `short1` does not live long enough } { - // This is OK: `short2`'s storage is live until after `long2`'s drop runs. + // This was OK: `short2`'s storage was live until after `long2`'s drop ran. #[expect(irrefutable_let_patterns)] let (mut long2, short2) = (Struct(&0), 1) else { unreachable!() }; long2.0 = &short2; + //~^ ERROR `short2` does not live long enough } { // Sanity check: `short3`'s drop is significant; it's dropped before `long3`: diff --git a/tests/ui/dropck/let-else-more-permissive.stderr b/tests/ui/dropck/let-else-more-permissive.stderr index 7c37e170afaf..4f0c193a78da 100644 --- a/tests/ui/dropck/let-else-more-permissive.stderr +++ b/tests/ui/dropck/let-else-more-permissive.stderr @@ -14,8 +14,24 @@ LL | } | = note: values in a scope are dropped in the opposite order they are defined +error[E0597]: `short2` does not live long enough + --> $DIR/let-else-more-permissive.rs:20:19 + | +LL | let (mut long2, short2) = (Struct(&0), 1) else { unreachable!() }; + | ------ binding `short2` declared here +LL | long2.0 = &short2; + | ^^^^^^^ borrowed value does not live long enough +LL | +LL | } + | - + | | + | `short2` dropped here while still borrowed + | borrow might be used here, when `long2` is dropped and runs the `Drop` code for type `Struct` + | + = note: values in a scope are dropped in the opposite order they are defined + error[E0597]: `short3` does not live long enough - --> $DIR/let-else-more-permissive.rs:27:19 + --> $DIR/let-else-more-permissive.rs:28:19 | LL | let (mut long3, short3) = (Struct(&tmp), Box::new(1)) else { unreachable!() }; | ------ binding `short3` declared here @@ -30,6 +46,6 @@ LL | } | = note: values in a scope are dropped in the opposite order they are defined -error: aborting due to 2 previous errors +error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0597`. From 1045b70304ab6a875fc9fbf10cb7e7c010edd3ab Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Thu, 26 Jun 2025 18:03:00 -0700 Subject: [PATCH 0034/1134] tests: add test for invalid interrupt signatures --- .../interrupt-invalid-signature.avr.stderr | 28 +++++ .../interrupt-invalid-signature.i686.stderr | 15 +++ .../interrupt-invalid-signature.msp430.stderr | 28 +++++ ...interrupt-invalid-signature.riscv32.stderr | 54 +++++++++ ...interrupt-invalid-signature.riscv64.stderr | 54 +++++++++ tests/ui/abi/interrupt-invalid-signature.rs | 110 ++++++++++++++++++ .../interrupt-invalid-signature.x64.stderr | 15 +++ 7 files changed, 304 insertions(+) create mode 100644 tests/ui/abi/interrupt-invalid-signature.avr.stderr create mode 100644 tests/ui/abi/interrupt-invalid-signature.i686.stderr create mode 100644 tests/ui/abi/interrupt-invalid-signature.msp430.stderr create mode 100644 tests/ui/abi/interrupt-invalid-signature.riscv32.stderr create mode 100644 tests/ui/abi/interrupt-invalid-signature.riscv64.stderr create mode 100644 tests/ui/abi/interrupt-invalid-signature.rs create mode 100644 tests/ui/abi/interrupt-invalid-signature.x64.stderr diff --git a/tests/ui/abi/interrupt-invalid-signature.avr.stderr b/tests/ui/abi/interrupt-invalid-signature.avr.stderr new file mode 100644 index 000000000000..91f5ca2022e3 --- /dev/null +++ b/tests/ui/abi/interrupt-invalid-signature.avr.stderr @@ -0,0 +1,28 @@ +error: invalid signature for `extern "avr-interrupt"` function + --> $DIR/interrupt-invalid-signature.rs:44:35 + | +LL | extern "avr-interrupt" fn avr_arg(_byte: u8) {} + | ^^^^^^^^^ + | + = note: functions with the "avr-interrupt" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "avr-interrupt" fn avr_arg(_byte: u8) {} +LL + extern "avr-interrupt" fn avr_arg() {} + | + +error: invalid signature for `extern "avr-interrupt"` function + --> $DIR/interrupt-invalid-signature.rs:59:40 + | +LL | extern "avr-interrupt" fn avr_ret() -> u8 { + | ^^ + | + = note: functions with the "avr-interrupt" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "avr-interrupt" fn avr_ret() -> u8 { +LL + extern "avr-interrupt" fn avr_ret() { + | + +error: aborting due to 2 previous errors + diff --git a/tests/ui/abi/interrupt-invalid-signature.i686.stderr b/tests/ui/abi/interrupt-invalid-signature.i686.stderr new file mode 100644 index 000000000000..06fd513df19e --- /dev/null +++ b/tests/ui/abi/interrupt-invalid-signature.i686.stderr @@ -0,0 +1,15 @@ +error: invalid signature for `extern "x86-interrupt"` function + --> $DIR/interrupt-invalid-signature.rs:83:40 + | +LL | extern "x86-interrupt" fn x86_ret() -> u8 { + | ^^ + | + = note: functions with the "custom" ABI cannot have a return type +help: remove the return type + --> $DIR/interrupt-invalid-signature.rs:83:40 + | +LL | extern "x86-interrupt" fn x86_ret() -> u8 { + | ^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/abi/interrupt-invalid-signature.msp430.stderr b/tests/ui/abi/interrupt-invalid-signature.msp430.stderr new file mode 100644 index 000000000000..38479f93de58 --- /dev/null +++ b/tests/ui/abi/interrupt-invalid-signature.msp430.stderr @@ -0,0 +1,28 @@ +error: invalid signature for `extern "msp430-interrupt"` function + --> $DIR/interrupt-invalid-signature.rs:40:41 + | +LL | extern "msp430-interrupt" fn msp430_arg(_byte: u8) {} + | ^^^^^^^^^ + | + = note: functions with the "msp430-interrupt" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "msp430-interrupt" fn msp430_arg(_byte: u8) {} +LL + extern "msp430-interrupt" fn msp430_arg() {} + | + +error: invalid signature for `extern "msp430-interrupt"` function + --> $DIR/interrupt-invalid-signature.rs:65:46 + | +LL | extern "msp430-interrupt" fn msp430_ret() -> u8 { + | ^^ + | + = note: functions with the "msp430-interrupt" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "msp430-interrupt" fn msp430_ret() -> u8 { +LL + extern "msp430-interrupt" fn msp430_ret() { + | + +error: aborting due to 2 previous errors + diff --git a/tests/ui/abi/interrupt-invalid-signature.riscv32.stderr b/tests/ui/abi/interrupt-invalid-signature.riscv32.stderr new file mode 100644 index 000000000000..d632b17ab83f --- /dev/null +++ b/tests/ui/abi/interrupt-invalid-signature.riscv32.stderr @@ -0,0 +1,54 @@ +error: invalid signature for `extern "riscv-interrupt-m"` function + --> $DIR/interrupt-invalid-signature.rs:48:43 + | +LL | extern "riscv-interrupt-m" fn riscv_m_arg(_byte: u8) {} + | ^^^^^^^^^ + | + = note: functions with the "riscv-interrupt-m" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "riscv-interrupt-m" fn riscv_m_arg(_byte: u8) {} +LL + extern "riscv-interrupt-m" fn riscv_m_arg() {} + | + +error: invalid signature for `extern "riscv-interrupt-s"` function + --> $DIR/interrupt-invalid-signature.rs:52:43 + | +LL | extern "riscv-interrupt-s" fn riscv_s_arg(_byte: u8) {} + | ^^^^^^^^^ + | + = note: functions with the "riscv-interrupt-s" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "riscv-interrupt-s" fn riscv_s_arg(_byte: u8) {} +LL + extern "riscv-interrupt-s" fn riscv_s_arg() {} + | + +error: invalid signature for `extern "riscv-interrupt-m"` function + --> $DIR/interrupt-invalid-signature.rs:71:48 + | +LL | extern "riscv-interrupt-m" fn riscv_m_ret() -> u8 { + | ^^ + | + = note: functions with the "riscv-interrupt-m" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "riscv-interrupt-m" fn riscv_m_ret() -> u8 { +LL + extern "riscv-interrupt-m" fn riscv_m_ret() { + | + +error: invalid signature for `extern "riscv-interrupt-s"` function + --> $DIR/interrupt-invalid-signature.rs:77:48 + | +LL | extern "riscv-interrupt-s" fn riscv_s_ret() -> u8 { + | ^^ + | + = note: functions with the "riscv-interrupt-s" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "riscv-interrupt-s" fn riscv_s_ret() -> u8 { +LL + extern "riscv-interrupt-s" fn riscv_s_ret() { + | + +error: aborting due to 4 previous errors + diff --git a/tests/ui/abi/interrupt-invalid-signature.riscv64.stderr b/tests/ui/abi/interrupt-invalid-signature.riscv64.stderr new file mode 100644 index 000000000000..d632b17ab83f --- /dev/null +++ b/tests/ui/abi/interrupt-invalid-signature.riscv64.stderr @@ -0,0 +1,54 @@ +error: invalid signature for `extern "riscv-interrupt-m"` function + --> $DIR/interrupt-invalid-signature.rs:48:43 + | +LL | extern "riscv-interrupt-m" fn riscv_m_arg(_byte: u8) {} + | ^^^^^^^^^ + | + = note: functions with the "riscv-interrupt-m" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "riscv-interrupt-m" fn riscv_m_arg(_byte: u8) {} +LL + extern "riscv-interrupt-m" fn riscv_m_arg() {} + | + +error: invalid signature for `extern "riscv-interrupt-s"` function + --> $DIR/interrupt-invalid-signature.rs:52:43 + | +LL | extern "riscv-interrupt-s" fn riscv_s_arg(_byte: u8) {} + | ^^^^^^^^^ + | + = note: functions with the "riscv-interrupt-s" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "riscv-interrupt-s" fn riscv_s_arg(_byte: u8) {} +LL + extern "riscv-interrupt-s" fn riscv_s_arg() {} + | + +error: invalid signature for `extern "riscv-interrupt-m"` function + --> $DIR/interrupt-invalid-signature.rs:71:48 + | +LL | extern "riscv-interrupt-m" fn riscv_m_ret() -> u8 { + | ^^ + | + = note: functions with the "riscv-interrupt-m" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "riscv-interrupt-m" fn riscv_m_ret() -> u8 { +LL + extern "riscv-interrupt-m" fn riscv_m_ret() { + | + +error: invalid signature for `extern "riscv-interrupt-s"` function + --> $DIR/interrupt-invalid-signature.rs:77:48 + | +LL | extern "riscv-interrupt-s" fn riscv_s_ret() -> u8 { + | ^^ + | + = note: functions with the "riscv-interrupt-s" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "riscv-interrupt-s" fn riscv_s_ret() -> u8 { +LL + extern "riscv-interrupt-s" fn riscv_s_ret() { + | + +error: aborting due to 4 previous errors + diff --git a/tests/ui/abi/interrupt-invalid-signature.rs b/tests/ui/abi/interrupt-invalid-signature.rs new file mode 100644 index 000000000000..e389285b0691 --- /dev/null +++ b/tests/ui/abi/interrupt-invalid-signature.rs @@ -0,0 +1,110 @@ +/*! Tests interrupt ABIs have a constricted signature + +Most interrupt ABIs share a similar restriction in terms of not allowing most signatures. +Specifically, they generally cannot have arguments or return types. +So we test that they error in essentially all of the same places. +A notable and interesting exception is x86. + +This test uses `cfg` because it is not testing whether these ABIs work on the platform. +*/ +//@ add-core-stubs +//@ revisions: x64 i686 riscv32 riscv64 avr msp430 +// +//@ [x64] needs-llvm-components: x86 +//@ [x64] compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=rlib +//@ [i686] needs-llvm-components: x86 +//@ [i686] compile-flags: --target=i686-unknown-linux-gnu --crate-type=rlib +//@ [riscv32] needs-llvm-components: riscv +//@ [riscv32] compile-flags: --target=riscv32i-unknown-none-elf --crate-type=rlib +//@ [riscv64] needs-llvm-components: riscv +//@ [riscv64] compile-flags: --target=riscv64gc-unknown-none-elf --crate-type=rlib +//@ [avr] needs-llvm-components: avr +//@ [avr] compile-flags: --target=avr-none -C target-cpu=atmega328p --crate-type=rlib +//@ [msp430] needs-llvm-components: msp430 +//@ [msp430] compile-flags: --target=msp430-none-elf --crate-type=rlib +#![no_core] +#![feature( + no_core, + abi_msp430_interrupt, + abi_avr_interrupt, + abi_x86_interrupt, + abi_riscv_interrupt +)] + +extern crate minicore; +use minicore::*; + +/* most extern "interrupt" definitions should not accept args */ + +#[cfg(msp430)] +extern "msp430-interrupt" fn msp430_arg(_byte: u8) {} +//[msp430]~^ ERROR invalid signature + +#[cfg(avr)] +extern "avr-interrupt" fn avr_arg(_byte: u8) {} +//[avr]~^ ERROR invalid signature + +#[cfg(any(riscv32,riscv64))] +extern "riscv-interrupt-m" fn riscv_m_arg(_byte: u8) {} +//[riscv32,riscv64]~^ ERROR invalid signature + +#[cfg(any(riscv32,riscv64))] +extern "riscv-interrupt-s" fn riscv_s_arg(_byte: u8) {} +//[riscv32,riscv64]~^ ERROR invalid signature + + +/* all extern "interrupt" definitions should not return non-1ZST values */ + +#[cfg(avr)] +extern "avr-interrupt" fn avr_ret() -> u8 { + //[avr]~^ ERROR invalid signature + 1 +} + +#[cfg(msp430)] +extern "msp430-interrupt" fn msp430_ret() -> u8 { + //[msp430]~^ ERROR invalid signature + 1 +} + +#[cfg(any(riscv32,riscv64))] +extern "riscv-interrupt-m" fn riscv_m_ret() -> u8 { + //[riscv32,riscv64]~^ ERROR invalid signature + 1 +} + +#[cfg(any(riscv32,riscv64))] +extern "riscv-interrupt-s" fn riscv_s_ret() -> u8 { + //[riscv32,riscv64]~^ ERROR invalid signature + 1 +} + +#[cfg(any(x64,i686))] +extern "x86-interrupt" fn x86_ret() -> u8 { + //[x64,i686]~^ ERROR invalid signature + 1 +} + + + +/* extern "interrupt" fnptrs with invalid signatures */ + +#[cfg(avr)] +fn avr_ptr(_f: extern "avr-interrupt" fn(u8) -> u8) { +} + +#[cfg(msp430)] +fn msp430_ptr(_f: extern "msp430-interrupt" fn(u8) -> u8) { +} + +#[cfg(any(riscv32,riscv64))] +fn riscv_m_ptr(_f: extern "riscv-interrupt-m" fn(u8) -> u8) { +} + +#[cfg(any(riscv32,riscv64))] +fn riscv_s_ptr(_f: extern "riscv-interrupt-s" fn(u8) -> u8) { +} + +#[cfg(any(x64,i686))] +fn x86_ptr(_f: extern "x86-interrupt" fn() -> u8) { +} diff --git a/tests/ui/abi/interrupt-invalid-signature.x64.stderr b/tests/ui/abi/interrupt-invalid-signature.x64.stderr new file mode 100644 index 000000000000..06fd513df19e --- /dev/null +++ b/tests/ui/abi/interrupt-invalid-signature.x64.stderr @@ -0,0 +1,15 @@ +error: invalid signature for `extern "x86-interrupt"` function + --> $DIR/interrupt-invalid-signature.rs:83:40 + | +LL | extern "x86-interrupt" fn x86_ret() -> u8 { + | ^^ + | + = note: functions with the "custom" ABI cannot have a return type +help: remove the return type + --> $DIR/interrupt-invalid-signature.rs:83:40 + | +LL | extern "x86-interrupt" fn x86_ret() -> u8 { + | ^^ + +error: aborting due to 1 previous error + From db33e98540fca8f3268cafc6276dbefd55681d55 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Thu, 26 Jun 2025 18:02:54 -0700 Subject: [PATCH 0035/1134] compiler: fixup error message for x86-interrupt invalid returns --- compiler/rustc_ast_passes/messages.ftl | 2 +- tests/ui/abi/interrupt-invalid-signature.i686.stderr | 2 +- tests/ui/abi/interrupt-invalid-signature.x64.stderr | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index 6eddce7b590a..869c3a58ae3d 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -17,7 +17,7 @@ ast_passes_abi_must_not_have_parameters_or_return_type= ast_passes_abi_must_not_have_return_type= invalid signature for `extern {$abi}` function - .note = functions with the "custom" ABI cannot have a return type + .note = functions with the {$abi} ABI cannot have a return type .help = remove the return type ast_passes_assoc_const_without_body = diff --git a/tests/ui/abi/interrupt-invalid-signature.i686.stderr b/tests/ui/abi/interrupt-invalid-signature.i686.stderr index 06fd513df19e..86f2e097c37e 100644 --- a/tests/ui/abi/interrupt-invalid-signature.i686.stderr +++ b/tests/ui/abi/interrupt-invalid-signature.i686.stderr @@ -4,7 +4,7 @@ error: invalid signature for `extern "x86-interrupt"` function LL | extern "x86-interrupt" fn x86_ret() -> u8 { | ^^ | - = note: functions with the "custom" ABI cannot have a return type + = note: functions with the "x86-interrupt" ABI cannot have a return type help: remove the return type --> $DIR/interrupt-invalid-signature.rs:83:40 | diff --git a/tests/ui/abi/interrupt-invalid-signature.x64.stderr b/tests/ui/abi/interrupt-invalid-signature.x64.stderr index 06fd513df19e..86f2e097c37e 100644 --- a/tests/ui/abi/interrupt-invalid-signature.x64.stderr +++ b/tests/ui/abi/interrupt-invalid-signature.x64.stderr @@ -4,7 +4,7 @@ error: invalid signature for `extern "x86-interrupt"` function LL | extern "x86-interrupt" fn x86_ret() -> u8 { | ^^ | - = note: functions with the "custom" ABI cannot have a return type + = note: functions with the "x86-interrupt" ABI cannot have a return type help: remove the return type --> $DIR/interrupt-invalid-signature.rs:83:40 | From d6b3314fb29cc688a968811b6a78dc8a5309cb7d Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Thu, 26 Jun 2025 19:35:28 -0700 Subject: [PATCH 0036/1134] compiler: allow interrupts to return () or ! --- .../rustc_ast_passes/src/ast_validation.rs | 16 ++- .../ui/abi/interrupt-returns-never-or-unit.rs | 110 ++++++++++++++++++ 2 files changed, 124 insertions(+), 2 deletions(-) create mode 100644 tests/ui/abi/interrupt-returns-never-or-unit.rs diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index da2482512037..478cec23fd57 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -396,7 +396,13 @@ impl<'a> AstValidator<'a> { if let InterruptKind::X86 = interrupt_kind { // "x86-interrupt" is special because it does have arguments. // FIXME(workingjubilee): properly lint on acceptable input types. - if let FnRetTy::Ty(ref ret_ty) = sig.decl.output { + if let FnRetTy::Ty(ref ret_ty) = sig.decl.output + && match &ret_ty.kind { + TyKind::Never => false, + TyKind::Tup(tup) if tup.is_empty() => false, + _ => true, + } + { self.dcx().emit_err(errors::AbiMustNotHaveReturnType { span: ret_ty.span, abi, @@ -455,7 +461,13 @@ impl<'a> AstValidator<'a> { fn reject_params_or_return(&self, abi: ExternAbi, ident: &Ident, sig: &FnSig) { let mut spans: Vec<_> = sig.decl.inputs.iter().map(|p| p.span).collect(); - if let FnRetTy::Ty(ref ret_ty) = sig.decl.output { + if let FnRetTy::Ty(ref ret_ty) = sig.decl.output + && match &ret_ty.kind { + TyKind::Never => false, + TyKind::Tup(tup) if tup.is_empty() => false, + _ => true, + } + { spans.push(ret_ty.span); } diff --git a/tests/ui/abi/interrupt-returns-never-or-unit.rs b/tests/ui/abi/interrupt-returns-never-or-unit.rs new file mode 100644 index 000000000000..34d509c83287 --- /dev/null +++ b/tests/ui/abi/interrupt-returns-never-or-unit.rs @@ -0,0 +1,110 @@ +/*! Tests interrupt ABIs can return ! + +Most interrupt ABIs share a similar restriction in terms of not allowing most signatures, +but it makes sense to allow them to return ! because they could indeed be divergent. + +This test uses `cfg` because it is not testing whether these ABIs work on the platform. +*/ +//@ add-core-stubs +//@ revisions: x64 i686 riscv32 riscv64 avr msp430 +//@ build-pass +// +//@ [x64] needs-llvm-components: x86 +//@ [x64] compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=rlib +//@ [i686] needs-llvm-components: x86 +//@ [i686] compile-flags: --target=i686-unknown-linux-gnu --crate-type=rlib +//@ [riscv32] needs-llvm-components: riscv +//@ [riscv32] compile-flags: --target=riscv32i-unknown-none-elf --crate-type=rlib +//@ [riscv64] needs-llvm-components: riscv +//@ [riscv64] compile-flags: --target=riscv64gc-unknown-none-elf --crate-type=rlib +//@ [avr] needs-llvm-components: avr +//@ [avr] compile-flags: --target=avr-none -C target-cpu=atmega328p --crate-type=rlib +//@ [msp430] needs-llvm-components: msp430 +//@ [msp430] compile-flags: --target=msp430-none-elf --crate-type=rlib +#![no_core] +#![feature( + no_core, + abi_msp430_interrupt, + abi_avr_interrupt, + abi_x86_interrupt, + abi_riscv_interrupt +)] + +extern crate minicore; +use minicore::*; + +/* interrupts can return never */ + +#[cfg(avr)] +extern "avr-interrupt" fn avr_ret_never() -> ! { + unsafe { hint::unreachable_unchecked() } +} + +#[cfg(msp430)] +extern "msp430-interrupt" fn msp430_ret_never() -> ! { + unsafe { hint::unreachable_unchecked() } +} + +#[cfg(any(riscv32,riscv64))] +extern "riscv-interrupt-m" fn riscv_m_ret_never() -> ! { + unsafe { hint::unreachable_unchecked() } +} + +#[cfg(any(riscv32,riscv64))] +extern "riscv-interrupt-s" fn riscv_s_ret_never() -> ! { + unsafe { hint::unreachable_unchecked() } +} + +#[cfg(any(x64,i686))] +extern "x86-interrupt" fn x86_ret_never() -> ! { + unsafe { hint::unreachable_unchecked() } +} + +/* interrupts can return explicit () */ + +#[cfg(avr)] +extern "avr-interrupt" fn avr_ret_unit() -> () { + unsafe { hint::unreachable_unchecked() } +} + +#[cfg(msp430)] +extern "msp430-interrupt" fn msp430_ret_unit() -> () { + unsafe { hint::unreachable_unchecked() } +} + +#[cfg(any(riscv32,riscv64))] +extern "riscv-interrupt-m" fn riscv_m_ret_unit() -> () { + unsafe { hint::unreachable_unchecked() } +} + +#[cfg(any(riscv32,riscv64))] +extern "riscv-interrupt-s" fn riscv_s_ret_unit() -> () { + unsafe { hint::unreachable_unchecked() } +} + +#[cfg(any(x64,i686))] +extern "x86-interrupt" fn x86_ret_unit() -> () { + unsafe { hint::unreachable_unchecked() } +} + +/* extern "interrupt" fnptrs can return ! too */ + +#[cfg(avr)] +fn avr_ptr(_f: extern "avr-interrupt" fn() -> !) { +} + +#[cfg(msp430)] +fn msp430_ptr(_f: extern "msp430-interrupt" fn() -> !) { +} + +#[cfg(any(riscv32,riscv64))] +fn riscv_m_ptr(_f: extern "riscv-interrupt-m" fn() -> !) { +} + +#[cfg(any(riscv32,riscv64))] +fn riscv_s_ptr(_f: extern "riscv-interrupt-s" fn() -> !) { +} + +#[cfg(any(x64,i686))] +fn x86_ptr(_f: extern "x86-interrupt" fn() -> !) { +} From b5ab966626e006172027e658fb1e43cf79f1c21a Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Fri, 27 Jun 2025 11:03:23 -0700 Subject: [PATCH 0037/1134] remember how to write never returns --- .../ui/abi/interrupt-returns-never-or-unit.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/ui/abi/interrupt-returns-never-or-unit.rs b/tests/ui/abi/interrupt-returns-never-or-unit.rs index 34d509c83287..8e224229a0b1 100644 --- a/tests/ui/abi/interrupt-returns-never-or-unit.rs +++ b/tests/ui/abi/interrupt-returns-never-or-unit.rs @@ -37,54 +37,54 @@ use minicore::*; #[cfg(avr)] extern "avr-interrupt" fn avr_ret_never() -> ! { - unsafe { hint::unreachable_unchecked() } + loop {} } #[cfg(msp430)] extern "msp430-interrupt" fn msp430_ret_never() -> ! { - unsafe { hint::unreachable_unchecked() } + loop {} } #[cfg(any(riscv32,riscv64))] extern "riscv-interrupt-m" fn riscv_m_ret_never() -> ! { - unsafe { hint::unreachable_unchecked() } + loop {} } #[cfg(any(riscv32,riscv64))] extern "riscv-interrupt-s" fn riscv_s_ret_never() -> ! { - unsafe { hint::unreachable_unchecked() } + loop {} } #[cfg(any(x64,i686))] extern "x86-interrupt" fn x86_ret_never() -> ! { - unsafe { hint::unreachable_unchecked() } + loop {} } /* interrupts can return explicit () */ #[cfg(avr)] extern "avr-interrupt" fn avr_ret_unit() -> () { - unsafe { hint::unreachable_unchecked() } + () } #[cfg(msp430)] extern "msp430-interrupt" fn msp430_ret_unit() -> () { - unsafe { hint::unreachable_unchecked() } + () } #[cfg(any(riscv32,riscv64))] extern "riscv-interrupt-m" fn riscv_m_ret_unit() -> () { - unsafe { hint::unreachable_unchecked() } + () } #[cfg(any(riscv32,riscv64))] extern "riscv-interrupt-s" fn riscv_s_ret_unit() -> () { - unsafe { hint::unreachable_unchecked() } + () } #[cfg(any(x64,i686))] extern "x86-interrupt" fn x86_ret_unit() -> () { - unsafe { hint::unreachable_unchecked() } + () } /* extern "interrupt" fnptrs can return ! too */ From 0920486fa6c0a3c08e23a867b1e6ca6a5563849b Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Sun, 29 Jun 2025 22:28:39 +0200 Subject: [PATCH 0038/1134] Do not autofix comments containing bare CR --- clippy_lints/src/four_forward_slashes.rs | 15 +++++++++++++++ tests/ui/four_forward_slashes_bare_cr.rs | 6 ++++++ tests/ui/four_forward_slashes_bare_cr.stderr | 14 ++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 tests/ui/four_forward_slashes_bare_cr.rs create mode 100644 tests/ui/four_forward_slashes_bare_cr.stderr diff --git a/clippy_lints/src/four_forward_slashes.rs b/clippy_lints/src/four_forward_slashes.rs index 8822b87f92f7..a7b0edeb7991 100644 --- a/clippy_lints/src/four_forward_slashes.rs +++ b/clippy_lints/src/four_forward_slashes.rs @@ -1,4 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::source::SpanRangeExt as _; +use itertools::Itertools; use rustc_errors::Applicability; use rustc_hir::Item; use rustc_lint::{LateContext, LateLintPass, LintContext}; @@ -81,6 +83,14 @@ impl<'tcx> LateLintPass<'tcx> for FourForwardSlashes { "turn these into doc comments by removing one `/`" }; + // If the comment contains a bare CR (not followed by a LF), do not propose an auto-fix + // as bare CR are not allowed in doc comments. + if span.check_source_text(cx, contains_bare_cr) { + diag.help(msg) + .note("bare CR characters are not allowed in doc comments"); + return; + } + diag.multipart_suggestion( msg, bad_comments @@ -97,3 +107,8 @@ impl<'tcx> LateLintPass<'tcx> for FourForwardSlashes { } } } + +/// Checks if `text` contains any CR not followed by a LF +fn contains_bare_cr(text: &str) -> bool { + text.bytes().tuple_windows().any(|(a, b)| a == b'\r' && b != b'\n') +} diff --git a/tests/ui/four_forward_slashes_bare_cr.rs b/tests/ui/four_forward_slashes_bare_cr.rs new file mode 100644 index 000000000000..19123cd206e3 --- /dev/null +++ b/tests/ui/four_forward_slashes_bare_cr.rs @@ -0,0 +1,6 @@ +//@no-rustfix +#![warn(clippy::four_forward_slashes)] + +//~v four_forward_slashes +//// nondoc comment with bare CR: ' ' +fn main() {} diff --git a/tests/ui/four_forward_slashes_bare_cr.stderr b/tests/ui/four_forward_slashes_bare_cr.stderr new file mode 100644 index 000000000000..64e70b97db9a --- /dev/null +++ b/tests/ui/four_forward_slashes_bare_cr.stderr @@ -0,0 +1,14 @@ +error: this item has comments with 4 forward slashes (`////`). These look like doc comments, but they aren't + --> tests/ui/four_forward_slashes_bare_cr.rs:5:1 + | +LL | / //// nondoc comment with bare CR: '␍' +LL | | fn main() {} + | |_^ + | + = help: make this a doc comment by removing one `/` + = note: bare CR characters are not allowed in doc comments + = note: `-D clippy::four-forward-slashes` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::four_forward_slashes)]` + +error: aborting due to 1 previous error + From 34ddd59e4544e77464fd6230bc354d0753987800 Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Wed, 2 Jul 2025 22:09:04 -0700 Subject: [PATCH 0039/1134] Improve settings tree title and descriptions - All settings are now phrased in the imperative form stating what the setting does rather than talking about what it controls. (E.g.: "Show `Debug` action." instead of "Whether to show `Debug` action" - Categories are now displayed in title case - Categories are now sorted lexicographically - General category is removed (and all the settings are moved to the top level) - Language for a few descriptions is made a bit less ambiguous --- .../crates/rust-analyzer/src/config.rs | 592 ++++++++++------ .../docs/book/src/configuration_generated.md | 292 ++++---- .../rust-analyzer/editors/code/package.json | 639 ++++++++++-------- 3 files changed, 899 insertions(+), 624 deletions(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs index e716d1407522..3f700862280f 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs @@ -61,233 +61,312 @@ pub enum MaxSubstitutionLength { Limit(usize), } -// Defines the server-side configuration of the rust-analyzer. We generate -// *parts* of VS Code's `package.json` config from this. Run `cargo test` to -// re-generate that file. +// Defines the server-side configuration of the rust-analyzer. We generate *parts* of VS Code's +// `package.json` config from this. Run `cargo test` to re-generate that file. // -// However, editor specific config, which the server doesn't know about, should -// be specified directly in `package.json`. +// However, editor specific config, which the server doesn't know about, should be specified +// directly in `package.json`. // -// To deprecate an option by replacing it with another name use `new_name` | `old_name` so that we keep -// parsing the old name. +// To deprecate an option by replacing it with another name use `new_name` | `old_name` so that we +// keep parsing the old name. config_data! { - /// Configs that apply on a workspace-wide scope. There are 2 levels on which a global configuration can be configured + /// Configs that apply on a workspace-wide scope. There are 2 levels on which a global + /// configuration can be configured /// - /// 1. `rust-analyzer.toml` file under user's config directory (e.g ~/.config/rust-analyzer/rust-analyzer.toml) + /// 1. `rust-analyzer.toml` file under user's config directory (e.g + /// ~/.config/rust-analyzer/rust-analyzer.toml) /// 2. Client's own configurations (e.g `settings.json` on VS Code) /// - /// A config is searched for by traversing a "config tree" in a bottom up fashion. It is chosen by the nearest first principle. + /// A config is searched for by traversing a "config tree" in a bottom up fashion. It is chosen + /// by the nearest first principle. global: struct GlobalDefaultConfigData <- GlobalConfigInput -> { /// Warm up caches on project load. cachePriming_enable: bool = true, - /// How many worker threads to handle priming caches. The default `0` means to pick automatically. + + /// How many worker threads to handle priming caches. The default `0` means to pick + /// automatically. cachePriming_numThreads: NumThreads = NumThreads::Physical, /// Custom completion snippets. - completion_snippets_custom: FxIndexMap = Config::completion_snippets_default(), - + completion_snippets_custom: FxIndexMap = + Config::completion_snippets_default(), - /// These paths (file/directories) will be ignored by rust-analyzer. They are - /// relative to the workspace root, and globs are not supported. You may - /// also need to add the folders to Code's `files.watcherExclude`. + /// List of files to ignore + /// + /// These paths (file/directories) will be ignored by rust-analyzer. They are relative to + /// the workspace root, and globs are not supported. You may also need to add the folders to + /// Code's `files.watcherExclude`. files_exclude | files_excludeDirs: Vec = vec![], - - - /// Enables highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`). + /// Highlight related return values while the cursor is on any `match`, `if`, or match arm + /// arrow (`=>`). highlightRelated_branchExitPoints_enable: bool = true, - /// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. + + /// Highlight related references while the cursor is on `break`, `loop`, `while`, or `for` + /// keywords. highlightRelated_breakPoints_enable: bool = true, - /// Enables highlighting of all captures of a closure while the cursor is on the `|` or move keyword of a closure. + + /// Highlight all captures of a closure while the cursor is on the `|` or move keyword of a closure. highlightRelated_closureCaptures_enable: bool = true, - /// Enables highlighting of all exit points while the cursor is on any `return`, `?`, `fn`, or return type arrow (`->`). + + /// Highlight all exit points while the cursor is on any `return`, `?`, `fn`, or return type + /// arrow (`->`). highlightRelated_exitPoints_enable: bool = true, - /// Enables highlighting of related references while the cursor is on any identifier. + + /// Highlight related references while the cursor is on any identifier. highlightRelated_references_enable: bool = true, - /// Enables highlighting of all break points for a loop or block context while the cursor is on any `async` or `await` keywords. + + /// Highlight all break points for a loop or block context while the cursor is on any + /// `async` or `await` keywords. highlightRelated_yieldPoints_enable: bool = true, - /// Whether to show `Debug` action. Only applies when - /// `#rust-analyzer.hover.actions.enable#` is set. - hover_actions_debug_enable: bool = true, - /// Whether to show HoverActions in Rust files. - hover_actions_enable: bool = true, - /// Whether to show `Go to Type Definition` action. Only applies when - /// `#rust-analyzer.hover.actions.enable#` is set. - hover_actions_gotoTypeDef_enable: bool = true, - /// Whether to show `Implementations` action. Only applies when + /// Show `Debug` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set. + hover_actions_debug_enable: bool = true, + + /// Show HoverActions in Rust files. + hover_actions_enable: bool = true, + + /// Show `Go to Type Definition` action. Only applies when /// `#rust-analyzer.hover.actions.enable#` is set. + hover_actions_gotoTypeDef_enable: bool = true, + + /// Show `Implementations` action. Only applies when `#rust-analyzer.hover.actions.enable#` + /// is set. hover_actions_implementations_enable: bool = true, - /// Whether to show `References` action. Only applies when - /// `#rust-analyzer.hover.actions.enable#` is set. - hover_actions_references_enable: bool = false, - /// Whether to show `Run` action. Only applies when - /// `#rust-analyzer.hover.actions.enable#` is set. - hover_actions_run_enable: bool = true, - /// Whether to show `Update Test` action. Only applies when - /// `#rust-analyzer.hover.actions.enable#` and `#rust-analyzer.hover.actions.run.enable#` are set. - hover_actions_updateTest_enable: bool = true, - - /// Whether to show documentation on hover. - hover_documentation_enable: bool = true, - /// Whether to show keyword hover popups. Only applies when + + /// Show `References` action. Only applies when `#rust-analyzer.hover.actions.enable#` is + /// set. + hover_actions_references_enable: bool = false, + + /// Show `Run` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set. + hover_actions_run_enable: bool = true, + + /// Show `Update Test` action. Only applies when `#rust-analyzer.hover.actions.enable#` and + /// `#rust-analyzer.hover.actions.run.enable#` are set. + hover_actions_updateTest_enable: bool = true, + + /// Show documentation on hover. + hover_documentation_enable: bool = true, + + /// Show keyword hover popups. Only applies when /// `#rust-analyzer.hover.documentation.enable#` is set. - hover_documentation_keywords_enable: bool = true, - /// Whether to show drop glue information on hover. - hover_dropGlue_enable: bool = true, + hover_documentation_keywords_enable: bool = true, + + /// Show drop glue information on hover. + hover_dropGlue_enable: bool = true, + /// Use markdown syntax for links on hover. hover_links_enable: bool = true, - /// Whether to show what types are used as generic arguments in calls etc. on hover, and what is their max length to show such types, beyond it they will be shown with ellipsis. + + /// Show what types are used as generic arguments in calls etc. on hover, and limit the max + /// length to show such types, beyond which they will be shown with ellipsis. /// - /// This can take three values: `null` means "unlimited", the string `"hide"` means to not show generic substitutions at all, and a number means to limit them to X characters. + /// This can take three values: `null` means "unlimited", the string `"hide"` means to not + /// show generic substitutions at all, and a number means to limit them to X characters. /// /// The default is 20 characters. - hover_maxSubstitutionLength: Option = Some(MaxSubstitutionLength::Limit(20)), + hover_maxSubstitutionLength: Option = + Some(MaxSubstitutionLength::Limit(20)), + /// How to render the align information in a memory layout hover. - hover_memoryLayout_alignment: Option = Some(MemoryLayoutHoverRenderKindDef::Hexadecimal), - /// Whether to show memory layout data on hover. + hover_memoryLayout_alignment: Option = + Some(MemoryLayoutHoverRenderKindDef::Hexadecimal), + + /// Show memory layout data on hover. hover_memoryLayout_enable: bool = true, + /// How to render the niche information in a memory layout hover. hover_memoryLayout_niches: Option = Some(false), + /// How to render the offset information in a memory layout hover. - hover_memoryLayout_offset: Option = Some(MemoryLayoutHoverRenderKindDef::Hexadecimal), + hover_memoryLayout_offset: Option = + Some(MemoryLayoutHoverRenderKindDef::Hexadecimal), + /// How to render the padding information in a memory layout hover. hover_memoryLayout_padding: Option = None, + /// How to render the size information in a memory layout hover. - hover_memoryLayout_size: Option = Some(MemoryLayoutHoverRenderKindDef::Both), + hover_memoryLayout_size: Option = + Some(MemoryLayoutHoverRenderKindDef::Both), /// How many variants of an enum to display when hovering on. Show none if empty. hover_show_enumVariants: Option = Some(5), - /// How many fields of a struct, variant or union to display when hovering on. Show none if empty. + + /// How many fields of a struct, variant or union to display when hovering on. Show none if + /// empty. hover_show_fields: Option = Some(5), + /// How many associated items of a trait to display when hovering a trait. hover_show_traitAssocItems: Option = None, - /// Whether to show inlay type hints for binding modes. - inlayHints_bindingModeHints_enable: bool = false, - /// Whether to show inlay type hints for method chains. - inlayHints_chainingHints_enable: bool = true, - /// Whether to show inlay hints after a closing `}` to indicate what item it belongs to. - inlayHints_closingBraceHints_enable: bool = true, + /// Show inlay type hints for binding modes. + inlayHints_bindingModeHints_enable: bool = false, + + /// Show inlay type hints for method chains. + inlayHints_chainingHints_enable: bool = true, + + /// Show inlay hints after a closing `}` to indicate what item it belongs to. + inlayHints_closingBraceHints_enable: bool = true, + /// Minimum number of lines required before the `}` until the hint is shown (set to 0 or 1 /// to always show them). - inlayHints_closingBraceHints_minLines: usize = 25, - /// Whether to show inlay hints for closure captures. - inlayHints_closureCaptureHints_enable: bool = false, - /// Whether to show inlay type hints for return types of closures. - inlayHints_closureReturnTypeHints_enable: ClosureReturnTypeHintsDef = ClosureReturnTypeHintsDef::Never, + inlayHints_closingBraceHints_minLines: usize = 25, + + /// Show inlay hints for closure captures. + inlayHints_closureCaptureHints_enable: bool = false, + + /// Show inlay type hints for return types of closures. + inlayHints_closureReturnTypeHints_enable: ClosureReturnTypeHintsDef = + ClosureReturnTypeHintsDef::Never, + /// Closure notation in type and chaining inlay hints. - inlayHints_closureStyle: ClosureStyle = ClosureStyle::ImplFn, - /// Whether to show enum variant discriminant hints. - inlayHints_discriminantHints_enable: DiscriminantHintsDef = DiscriminantHintsDef::Never, - /// Whether to show inlay hints for type adjustments. - inlayHints_expressionAdjustmentHints_enable: AdjustmentHintsDef = AdjustmentHintsDef::Never, - /// Whether to hide inlay hints for type adjustments outside of `unsafe` blocks. + inlayHints_closureStyle: ClosureStyle = ClosureStyle::ImplFn, + + /// Show enum variant discriminant hints. + inlayHints_discriminantHints_enable: DiscriminantHintsDef = + DiscriminantHintsDef::Never, + + /// Show inlay hints for type adjustments. + inlayHints_expressionAdjustmentHints_enable: AdjustmentHintsDef = + AdjustmentHintsDef::Never, + + /// Hide inlay hints for type adjustments outside of `unsafe` blocks. inlayHints_expressionAdjustmentHints_hideOutsideUnsafe: bool = false, - /// Whether to show inlay hints as postfix ops (`.*` instead of `*`, etc). - inlayHints_expressionAdjustmentHints_mode: AdjustmentHintsModeDef = AdjustmentHintsModeDef::Prefix, - /// Whether to show const generic parameter name inlay hints. - inlayHints_genericParameterHints_const_enable: bool= true, - /// Whether to show generic lifetime parameter name inlay hints. + + /// Show inlay hints as postfix ops (`.*` instead of `*`, etc). + inlayHints_expressionAdjustmentHints_mode: AdjustmentHintsModeDef = + AdjustmentHintsModeDef::Prefix, + + /// Show const generic parameter name inlay hints. + inlayHints_genericParameterHints_const_enable: bool = true, + + /// Show generic lifetime parameter name inlay hints. inlayHints_genericParameterHints_lifetime_enable: bool = false, - /// Whether to show generic type parameter name inlay hints. + + /// Show generic type parameter name inlay hints. inlayHints_genericParameterHints_type_enable: bool = false, - /// Whether to show implicit drop hints. - inlayHints_implicitDrops_enable: bool = false, - /// Whether to show inlay hints for the implied type parameter `Sized` bound. - inlayHints_implicitSizedBoundHints_enable: bool = false, - /// Whether to show inlay type hints for elided lifetimes in function signatures. + + /// Show implicit drop hints. + inlayHints_implicitDrops_enable: bool = false, + + /// Show inlay hints for the implied type parameter `Sized` bound. + inlayHints_implicitSizedBoundHints_enable: bool = false, + + /// Show inlay type hints for elided lifetimes in function signatures. inlayHints_lifetimeElisionHints_enable: LifetimeElisionDef = LifetimeElisionDef::Never, - /// Whether to prefer using parameter names as the name for elided lifetime hints if possible. - inlayHints_lifetimeElisionHints_useParameterNames: bool = false, + + /// Prefer using parameter names as the name for elided lifetime hints if possible. + inlayHints_lifetimeElisionHints_useParameterNames: bool = false, + /// Maximum length for inlay hints. Set to null to have an unlimited length. - inlayHints_maxLength: Option = Some(25), - /// Whether to show function parameter name inlay hints at the call - /// site. - inlayHints_parameterHints_enable: bool = true, - /// Whether to show exclusive range inlay hints. - inlayHints_rangeExclusiveHints_enable: bool = false, - /// Whether to show inlay hints for compiler inserted reborrows. - /// This setting is deprecated in favor of #rust-analyzer.inlayHints.expressionAdjustmentHints.enable#. - inlayHints_reborrowHints_enable: ReborrowHintsDef = ReborrowHintsDef::Never, + inlayHints_maxLength: Option = Some(25), + + /// Show function parameter name inlay hints at the call site. + inlayHints_parameterHints_enable: bool = true, + + /// Show exclusive range inlay hints. + inlayHints_rangeExclusiveHints_enable: bool = false, + + /// Show inlay hints for compiler inserted reborrows. + /// + /// This setting is deprecated in favor of + /// #rust-analyzer.inlayHints.expressionAdjustmentHints.enable#. + inlayHints_reborrowHints_enable: ReborrowHintsDef = ReborrowHintsDef::Never, + /// Whether to render leading colons for type hints, and trailing colons for parameter hints. - inlayHints_renderColons: bool = true, - /// Whether to show inlay type hints for variables. - inlayHints_typeHints_enable: bool = true, - /// Whether to hide inlay type hints for `let` statements that initialize to a closure. - /// Only applies to closures with blocks, same as `#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`. - inlayHints_typeHints_hideClosureInitialization: bool = false, - /// Whether to hide inlay parameter type hints for closures. - inlayHints_typeHints_hideClosureParameter:bool = false, - /// Whether to hide inlay type hints for constructors. - inlayHints_typeHints_hideNamedConstructor: bool = false, - - /// Enables the experimental support for interpreting tests. + inlayHints_renderColons: bool = true, + + /// Show inlay type hints for variables. + inlayHints_typeHints_enable: bool = true, + + /// Hide inlay type hints for `let` statements that initialize to a closure. + /// + /// Only applies to closures with blocks, same as + /// `#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`. + inlayHints_typeHints_hideClosureInitialization: bool = false, + + /// Hide inlay parameter type hints for closures. + inlayHints_typeHints_hideClosureParameter: bool = false, + + /// Hide inlay type hints for constructors. + inlayHints_typeHints_hideNamedConstructor: bool = false, + + /// Enable the experimental support for interpreting tests. interpret_tests: bool = false, /// Join lines merges consecutive declaration and initialization of an assignment. joinLines_joinAssignments: bool = true, + /// Join lines inserts else between consecutive ifs. joinLines_joinElseIf: bool = true, + /// Join lines removes trailing commas. joinLines_removeTrailingComma: bool = true, + /// Join lines unwraps trivial blocks. joinLines_unwrapTrivialBlock: bool = true, - /// Whether to show `Debug` lens. Only applies when - /// `#rust-analyzer.lens.enable#` is set. - lens_debug_enable: bool = true, - /// Whether to show CodeLens in Rust files. - lens_enable: bool = true, - /// Whether to show `Implementations` lens. Only applies when - /// `#rust-analyzer.lens.enable#` is set. - lens_implementations_enable: bool = true, + /// Show `Debug` lens. Only applies when `#rust-analyzer.lens.enable#` is set. + lens_debug_enable: bool = true, + + /// Show CodeLens in Rust files. + lens_enable: bool = true, + + /// Show `Implementations` lens. Only applies when `#rust-analyzer.lens.enable#` is set. + lens_implementations_enable: bool = true, + /// Where to render annotations. lens_location: AnnotationLocation = AnnotationLocation::AboveName, - /// Whether to show `References` lens for Struct, Enum, and Union. - /// Only applies when `#rust-analyzer.lens.enable#` is set. + + /// Show `References` lens for Struct, Enum, and Union. Only applies when + /// `#rust-analyzer.lens.enable#` is set. lens_references_adt_enable: bool = false, - /// Whether to show `References` lens for Enum Variants. - /// Only applies when `#rust-analyzer.lens.enable#` is set. - lens_references_enumVariant_enable: bool = false, - /// Whether to show `Method References` lens. Only applies when + + /// Show `References` lens for Enum Variants. Only applies when /// `#rust-analyzer.lens.enable#` is set. + lens_references_enumVariant_enable: bool = false, + + /// Show `Method References` lens. Only applies when `#rust-analyzer.lens.enable#` is set. lens_references_method_enable: bool = false, - /// Whether to show `References` lens for Trait. - /// Only applies when `#rust-analyzer.lens.enable#` is set. + + /// Show `References` lens for Trait. Only applies when `#rust-analyzer.lens.enable#` is + /// set. lens_references_trait_enable: bool = false, - /// Whether to show `Run` lens. Only applies when - /// `#rust-analyzer.lens.enable#` is set. - lens_run_enable: bool = true, - /// Whether to show `Update Test` lens. Only applies when - /// `#rust-analyzer.lens.enable#` and `#rust-analyzer.lens.run.enable#` are set. + + /// Show `Run` lens. Only applies when `#rust-analyzer.lens.enable#` is set. + lens_run_enable: bool = true, + + /// Show `Update Test` lens. Only applies when `#rust-analyzer.lens.enable#` and + /// `#rust-analyzer.lens.run.enable#` are set. lens_updateTest_enable: bool = true, - /// Disable project auto-discovery in favor of explicitly specified set - /// of projects. + /// Disable project auto-discovery in favor of explicitly specified set of projects. /// - /// Elements must be paths pointing to `Cargo.toml`, - /// `rust-project.json`, `.rs` files (which will be treated as standalone files) or JSON - /// objects in `rust-project.json` format. + /// Elements must be paths pointing to `Cargo.toml`, `rust-project.json`, `.rs` files (which + /// will be treated as standalone files) or JSON objects in `rust-project.json` format. linkedProjects: Vec = vec![], /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128. - lru_capacity: Option = None, - /// Sets the LRU capacity of the specified queries. + lru_capacity: Option = None, + + /// The LRU capacity of the specified queries. lru_query_capacities: FxHashMap, u16> = FxHashMap::default(), - /// Whether to show `can't find Cargo.toml` error message. - notifications_cargoTomlNotFound: bool = true, + /// Show `can't find Cargo.toml` error message. + notifications_cargoTomlNotFound: bool = true, - /// How many worker threads in the main loop. The default `null` means to pick automatically. + /// The number of worker threads in the main loop. The default `null` means to pick + /// automatically. numThreads: Option = None, /// Expand attribute macros. Requires `#rust-analyzer.procMacro.enable#` to be set. procMacro_attributes_enable: bool = true, + /// Enable support for procedural macros, implies `#rust-analyzer.cargo.buildScripts.enable#`. - procMacro_enable: bool = true, + procMacro_enable: bool = true, + /// Internal config, path to proc-macro server executable. - procMacro_server: Option = None, + procMacro_server: Option = None, /// Exclude imports from find-all-references. references_excludeImports: bool = false, @@ -300,31 +379,41 @@ config_data! { /// When enabled, rust-analyzer will highlight rust source in doc comments as well as intra /// doc links. semanticHighlighting_doc_comment_inject_enable: bool = true, - /// Whether the server is allowed to emit non-standard tokens and modifiers. + + /// Emit non-standard tokens and modifiers + /// + /// When enabled, rust-analyzer will emit tokens and modifiers that are not part of the + /// standard set of semantic tokens. semanticHighlighting_nonStandardTokens: bool = true, + /// Use semantic tokens for operators. /// /// When disabled, rust-analyzer will emit semantic tokens only for operator tokens when /// they are tagged with modifiers. semanticHighlighting_operator_enable: bool = true, + /// Use specialized semantic tokens for operators. /// /// When enabled, rust-analyzer will emit special token types for operator tokens instead /// of the generic `operator` token type. semanticHighlighting_operator_specialization_enable: bool = false, + /// Use semantic tokens for punctuation. /// /// When disabled, rust-analyzer will emit semantic tokens only for punctuation tokens when /// they are tagged with modifiers or have a special role. semanticHighlighting_punctuation_enable: bool = false, + /// When enabled, rust-analyzer will emit a punctuation semantic token for the `!` of macro /// calls. semanticHighlighting_punctuation_separate_macro_bang: bool = false, + /// Use specialized semantic tokens for punctuation. /// /// When enabled, rust-analyzer will emit special token types for punctuation tokens instead /// of the generic `punctuation` token type. semanticHighlighting_punctuation_specialization_enable: bool = false, + /// Use semantic tokens for strings. /// /// In some editors (e.g. vscode) semantic tokens override other highlighting grammars. @@ -333,16 +422,21 @@ config_data! { semanticHighlighting_strings_enable: bool = true, /// Show full signature of the callable. Only shows parameters if disabled. - signatureInfo_detail: SignatureDetail = SignatureDetail::Full, + signatureInfo_detail: SignatureDetail = SignatureDetail::Full, + /// Show documentation. - signatureInfo_documentation_enable: bool = true, + signatureInfo_documentation_enable: bool = true, /// Specify the characters allowed to invoke special on typing triggers. - /// - typing `=` after `let` tries to smartly add `;` if `=` is followed by an existing expression + /// + /// - typing `=` after `let` tries to smartly add `;` if `=` is followed by an existing + /// expression /// - typing `=` between two expressions adds `;` when in statement position - /// - typing `=` to turn an assignment into an equality comparison removes `;` when in expression position + /// - typing `=` to turn an assignment into an equality comparison removes `;` when in + /// expression position /// - typing `.` in a chain method call auto-indents - /// - typing `{` or `(` in front of an expression inserts a closing `}` or `)` after the expression + /// - typing `{` or `(` in front of an expression inserts a closing `}` or `)` after the + /// expression /// - typing `{` in a use item adds a closing `}` in the right place /// - typing `>` to complete a return type `->` will insert a whitespace after it /// - typing `<` in a path or type position inserts a closing `>` after the path or type. @@ -374,8 +468,8 @@ config_data! { /// /// **Warning**: This format is provisional and subject to change. /// - /// [`DiscoverWorkspaceConfig::command`] *must* return a JSON object - /// corresponding to `DiscoverProjectData::Finished`: + /// [`DiscoverWorkspaceConfig::command`] *must* return a JSON object corresponding to + /// `DiscoverProjectData::Finished`: /// /// ```norun /// #[derive(Debug, Clone, Deserialize, Serialize)] @@ -405,12 +499,11 @@ config_data! { /// } /// ``` /// - /// It is encouraged, but not required, to use the other variants on - /// `DiscoverProjectData` to provide a more polished end-user experience. + /// It is encouraged, but not required, to use the other variants on `DiscoverProjectData` + /// to provide a more polished end-user experience. /// - /// `DiscoverWorkspaceConfig::command` may *optionally* include an `{arg}`, - /// which will be substituted with the JSON-serialized form of the following - /// enum: + /// `DiscoverWorkspaceConfig::command` may *optionally* include an `{arg}`, which will be + /// substituted with the JSON-serialized form of the following enum: /// /// ```norun /// #[derive(PartialEq, Clone, Debug, Serialize)] @@ -437,11 +530,10 @@ config_data! { /// } /// ``` /// - /// `DiscoverArgument::Path` is used to find and generate a `rust-project.json`, - /// and therefore, a workspace, whereas `DiscoverArgument::buildfile` is used to - /// to update an existing workspace. As a reference for implementors, - /// buck2's `rust-project` will likely be useful: - /// https://github.com/facebook/buck2/tree/main/integrations/rust-project. + /// `DiscoverArgument::Path` is used to find and generate a `rust-project.json`, and + /// therefore, a workspace, whereas `DiscoverArgument::buildfile` is used to to update an + /// existing workspace. As a reference for implementors, buck2's `rust-project` will likely + /// be useful: https://github.com/facebook/buck2/tree/main/integrations/rust-project. workspace_discoverConfig: Option = None, } } @@ -449,109 +541,154 @@ config_data! { config_data! { /// Local configurations can be defined per `SourceRoot`. This almost always corresponds to a `Crate`. local: struct LocalDefaultConfigData <- LocalConfigInput -> { - /// Whether to insert #[must_use] when generating `as_` methods - /// for enum variants. - assist_emitMustUse: bool = false, + /// Insert #[must_use] when generating `as_` methods for enum variants. + assist_emitMustUse: bool = false, + /// Placeholder expression to use for missing expressions in assists. - assist_expressionFillDefault: ExprFillDefaultDef = ExprFillDefaultDef::Todo, - /// When inserting a type (e.g. in "fill match arms" assist), prefer to use `Self` over the type name where possible. + assist_expressionFillDefault: ExprFillDefaultDef = ExprFillDefaultDef::Todo, + + /// Prefer to use `Self` over the type name when inserting a type (e.g. in "fill match arms" assist). assist_preferSelf: bool = false, - /// Enable borrow checking for term search code assists. If set to false, also there will be more suggestions, but some of them may not borrow-check. + + /// Enable borrow checking for term search code assists. If set to false, also there will be + /// more suggestions, but some of them may not borrow-check. assist_termSearch_borrowcheck: bool = true, + /// Term search fuel in "units of work" for assists (Defaults to 1800). assist_termSearch_fuel: usize = 1800, - - /// Whether to automatically add a semicolon when completing unit-returning functions. + /// Automatically add a semicolon when completing unit-returning functions. /// /// In `match` arms it completes a comma instead. completion_addSemicolonToUnit: bool = true, - /// Toggles the additional completions that automatically show method calls and field accesses with `await` prefixed to them when completing on a future. - completion_autoAwait_enable: bool = true, - /// Toggles the additional completions that automatically show method calls with `iter()` or `into_iter()` prefixed to them when completing on a type that has them. - completion_autoIter_enable: bool = true, - /// Toggles the additional completions that automatically add imports when completed. - /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled. - completion_autoimport_enable: bool = true, + + /// Show method calls and field accesses completions with `await` prefixed to them when + /// completing on a future. + completion_autoAwait_enable: bool = true, + + /// Show method call completions with `iter()` or `into_iter()` prefixed to them when + /// completing on a type that has them. + completion_autoIter_enable: bool = true, + + /// Show completions that automatically add imports when completed. + /// + /// Note that your client must specify the `additionalTextEdits` LSP client capability to + /// truly have this feature enabled. + completion_autoimport_enable: bool = true, + /// A list of full paths to items to exclude from auto-importing completions. /// /// Traits in this list won't have their methods suggested in completions unless the trait /// is in scope. /// - /// You can either specify a string path which defaults to type "always" or use the more verbose - /// form `{ "path": "path::to::item", type: "always" }`. + /// You can either specify a string path which defaults to type "always" or use the more + /// verbose form `{ "path": "path::to::item", type: "always" }`. /// - /// For traits the type "methods" can be used to only exclude the methods but not the trait itself. + /// For traits the type "methods" can be used to only exclude the methods but not the trait + /// itself. /// /// This setting also inherits `#rust-analyzer.completion.excludeTraits#`. completion_autoimport_exclude: Vec = vec![ AutoImportExclusion::Verbose { path: "core::borrow::Borrow".to_owned(), r#type: AutoImportExclusionType::Methods }, AutoImportExclusion::Verbose { path: "core::borrow::BorrowMut".to_owned(), r#type: AutoImportExclusionType::Methods }, ], - /// Toggles the additional completions that automatically show method calls and field accesses - /// with `self` prefixed to them when inside a method. - completion_autoself_enable: bool = true, - /// Whether to add parenthesis and argument snippets when completing function. - completion_callable_snippets: CallableCompletionDef = CallableCompletionDef::FillArguments, + + /// Show method calls and field access completions with `self` prefixed to them when + /// inside a method. + completion_autoself_enable: bool = true, + + /// Add parenthesis and argument snippets when completing function. + completion_callable_snippets: CallableCompletionDef = CallableCompletionDef::FillArguments, + /// A list of full paths to traits whose methods to exclude from completion. /// - /// Methods from these traits won't be completed, even if the trait is in scope. However, they will still be suggested on expressions whose type is `dyn Trait`, `impl Trait` or `T where T: Trait`. + /// Methods from these traits won't be completed, even if the trait is in scope. However, + /// they will still be suggested on expressions whose type is `dyn Trait`, `impl Trait` or + /// `T where T: Trait`. /// /// Note that the trait themselves can still be completed. completion_excludeTraits: Vec = Vec::new(), - /// Whether to show full function/method signatures in completion docs. + + /// Show full function / method signatures in completion docs. completion_fullFunctionSignatures_enable: bool = false, - /// Whether to omit deprecated items from autocompletion. By default they are marked as deprecated but not hidden. + + /// Omit deprecated items from completions. By default they are marked as deprecated but not + /// hidden. completion_hideDeprecated: bool = false, + /// Maximum number of completions to return. If `None`, the limit is infinite. completion_limit: Option = None, - /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc. - completion_postfix_enable: bool = true, - /// Enables completions of private items and fields that are defined in the current workspace even if they are not visible at the current position. + + /// Show postfix snippets like `dbg`, `if`, `not`, etc. + completion_postfix_enable: bool = true, + + /// Show completions of private items and fields that are defined in the current workspace + /// even if they are not visible at the current position. completion_privateEditable_enable: bool = false, - /// Whether to enable term search based snippets like `Some(foo.bar().baz())`. + + /// Enable term search based snippets like `Some(foo.bar().baz())`. completion_termSearch_enable: bool = false, + /// Term search fuel in "units of work" for autocompletion (Defaults to 1000). completion_termSearch_fuel: usize = 1000, /// List of rust-analyzer diagnostics to disable. diagnostics_disabled: FxHashSet = FxHashSet::default(), - /// Whether to show native rust-analyzer diagnostics. - diagnostics_enable: bool = true, - /// Whether to show experimental rust-analyzer diagnostics that might - /// have more false positives than usual. - diagnostics_experimental_enable: bool = false, - /// Map of prefixes to be substituted when parsing diagnostic file paths. - /// This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`. + + /// Show native rust-analyzer diagnostics. + diagnostics_enable: bool = true, + + /// Show experimental rust-analyzer diagnostics that might have more false positives than + /// usual. + diagnostics_experimental_enable: bool = false, + + /// Map of prefixes to be substituted when parsing diagnostic file paths. This should be the + /// reverse mapping of what is passed to `rustc` as `--remap-path-prefix`. diagnostics_remapPrefix: FxHashMap = FxHashMap::default(), - /// Whether to run additional style lints. - diagnostics_styleLints_enable: bool = false, + + /// Run additional style lints. + diagnostics_styleLints_enable: bool = false, + /// List of warnings that should be displayed with hint severity. /// - /// The warnings will be indicated by faded text or three dots in code - /// and will not show up in the `Problems Panel`. + /// The warnings will be indicated by faded text or three dots in code and will not show up + /// in the `Problems Panel`. diagnostics_warningsAsHint: Vec = vec![], + /// List of warnings that should be displayed with info severity. /// - /// The warnings will be indicated by a blue squiggly underline in code - /// and a blue icon in the `Problems Panel`. + /// The warnings will be indicated by a blue squiggly underline in code and a blue icon in + /// the `Problems Panel`. diagnostics_warningsAsInfo: Vec = vec![], - /// Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file. - imports_granularity_enforce: bool = false, + /// Enforce the import granularity setting for all files. If set to false rust-analyzer will + /// try to keep import styles consistent per file. + imports_granularity_enforce: bool = false, + /// How imports should be grouped into use statements. - imports_granularity_group: ImportGranularityDef = ImportGranularityDef::Crate, - /// Group inserted imports by the [following order](https://rust-analyzer.github.io/book/features.html#auto-import). Groups are separated by newlines. - imports_group_enable: bool = true, - /// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`. - imports_merge_glob: bool = true, + imports_granularity_group: ImportGranularityDef = ImportGranularityDef::Crate, + + /// Group inserted imports by the [following + /// order](https://rust-analyzer.github.io/book/features.html#auto-import). Groups are + /// separated by newlines. + imports_group_enable: bool = true, + + /// Allow import insertion to merge new imports into single path glob imports like `use + /// std::fmt::*;`. + imports_merge_glob: bool = true, + /// Prefer to unconditionally use imports of the core and alloc crate, over the std crate. imports_preferNoStd | imports_prefer_no_std: bool = false, - /// Whether to prefer import paths containing a `prelude` module. - imports_preferPrelude: bool = false, + + /// Prefer import paths containing a `prelude` module. + imports_preferPrelude: bool = false, + /// The path structure for newly inserted paths to use. - imports_prefix: ImportPrefixDef = ImportPrefixDef::ByCrate, - /// Whether to prefix external (including std, core) crate imports with `::`. e.g. "use ::std::io::Read;". + imports_prefix: ImportPrefixDef = ImportPrefixDef::ByCrate, + + /// Prefix external (including std, core) crate imports with `::`. + /// + /// E.g. `use ::std::io::Read;`. imports_prefixExternPrelude: bool = false, } } @@ -3203,8 +3340,10 @@ fn schema(fields: &[SchemaField]) -> serde_json::Value { .iter() .map(|(field, ty, doc, default)| { let name = field.replace('_', "."); - let category = - name.find('.').map(|end| String::from(&name[..end])).unwrap_or("general".into()); + let category = name + .split_once(".") + .map(|(category, _name)| to_title_case(category)) + .unwrap_or("rust-analyzer".into()); let name = format!("rust-analyzer.{name}"); let props = field_props(field, ty, doc, default); serde_json::json!({ @@ -3218,6 +3357,29 @@ fn schema(fields: &[SchemaField]) -> serde_json::Value { map.into() } +/// Translate a field name to a title case string suitable for use in the category names on the +/// vscode settings page. +/// +/// First letter of word should be uppercase, if an uppercase letter is encountered, add a space +/// before it e.g. "fooBar" -> "Foo Bar", "fooBarBaz" -> "Foo Bar Baz", "foo" -> "Foo" +/// +/// This likely should be in stdx (or just use heck instead), but it doesn't handle any edge cases +/// and is intentionally simple. +fn to_title_case(s: &str) -> String { + let mut result = String::with_capacity(s.len()); + let mut chars = s.chars(); + if let Some(first) = chars.next() { + result.push(first.to_ascii_uppercase()); + for c in chars { + if c.is_uppercase() { + result.push(' '); + } + result.push(c); + } + } + result +} + fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value { let doc = doc_comment_to_string(doc); let doc = doc.trim_end_matches('\n'); diff --git a/src/tools/rust-analyzer/docs/book/src/configuration_generated.md b/src/tools/rust-analyzer/docs/book/src/configuration_generated.md index ebac26e1d60a..05299f1d017e 100644 --- a/src/tools/rust-analyzer/docs/book/src/configuration_generated.md +++ b/src/tools/rust-analyzer/docs/book/src/configuration_generated.md @@ -2,8 +2,7 @@ Default: `false` -Whether to insert #[must_use] when generating `as_` methods -for enum variants. +Insert #[must_use] when generating `as_` methods for enum variants. ## rust-analyzer.assist.expressionFillDefault {#assist.expressionFillDefault} @@ -17,14 +16,15 @@ Placeholder expression to use for missing expressions in assists. Default: `false` -When inserting a type (e.g. in "fill match arms" assist), prefer to use `Self` over the type name where possible. +Prefer to use `Self` over the type name when inserting a type (e.g. in "fill match arms" assist). ## rust-analyzer.assist.termSearch.borrowcheck {#assist.termSearch.borrowcheck} Default: `true` -Enable borrow checking for term search code assists. If set to false, also there will be more suggestions, but some of them may not borrow-check. +Enable borrow checking for term search code assists. If set to false, also there will be +more suggestions, but some of them may not borrow-check. ## rust-analyzer.assist.termSearch.fuel {#assist.termSearch.fuel} @@ -45,7 +45,8 @@ Warm up caches on project load. Default: `"physical"` -How many worker threads to handle priming caches. The default `0` means to pick automatically. +How many worker threads to handle priming caches. The default `0` means to pick +automatically. ## rust-analyzer.cargo.allTargets {#cargo.allTargets} @@ -358,7 +359,7 @@ check will be performed. Default: `true` -Whether to automatically add a semicolon when completing unit-returning functions. +Automatically add a semicolon when completing unit-returning functions. In `match` arms it completes a comma instead. @@ -367,22 +368,26 @@ In `match` arms it completes a comma instead. Default: `true` -Toggles the additional completions that automatically show method calls and field accesses with `await` prefixed to them when completing on a future. +Show method calls and field accesses completions with `await` prefixed to them when +completing on a future. ## rust-analyzer.completion.autoIter.enable {#completion.autoIter.enable} Default: `true` -Toggles the additional completions that automatically show method calls with `iter()` or `into_iter()` prefixed to them when completing on a type that has them. +Show method call completions with `iter()` or `into_iter()` prefixed to them when +completing on a type that has them. ## rust-analyzer.completion.autoimport.enable {#completion.autoimport.enable} Default: `true` -Toggles the additional completions that automatically add imports when completed. -Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled. +Show completions that automatically add imports when completed. + +Note that your client must specify the `additionalTextEdits` LSP client capability to +truly have this feature enabled. ## rust-analyzer.completion.autoimport.exclude {#completion.autoimport.exclude} @@ -406,10 +411,11 @@ A list of full paths to items to exclude from auto-importing completions. Traits in this list won't have their methods suggested in completions unless the trait is in scope. -You can either specify a string path which defaults to type "always" or use the more verbose -form `{ "path": "path::to::item", type: "always" }`. +You can either specify a string path which defaults to type "always" or use the more +verbose form `{ "path": "path::to::item", type: "always" }`. -For traits the type "methods" can be used to only exclude the methods but not the trait itself. +For traits the type "methods" can be used to only exclude the methods but not the trait +itself. This setting also inherits `#rust-analyzer.completion.excludeTraits#`. @@ -418,15 +424,15 @@ This setting also inherits `#rust-analyzer.completion.excludeTraits#`. Default: `true` -Toggles the additional completions that automatically show method calls and field accesses -with `self` prefixed to them when inside a method. +Show method calls and field access completions with `self` prefixed to them when +inside a method. ## rust-analyzer.completion.callable.snippets {#completion.callable.snippets} Default: `"fill_arguments"` -Whether to add parenthesis and argument snippets when completing function. +Add parenthesis and argument snippets when completing function. ## rust-analyzer.completion.excludeTraits {#completion.excludeTraits} @@ -435,7 +441,9 @@ Default: `[]` A list of full paths to traits whose methods to exclude from completion. -Methods from these traits won't be completed, even if the trait is in scope. However, they will still be suggested on expressions whose type is `dyn Trait`, `impl Trait` or `T where T: Trait`. +Methods from these traits won't be completed, even if the trait is in scope. However, +they will still be suggested on expressions whose type is `dyn Trait`, `impl Trait` or +`T where T: Trait`. Note that the trait themselves can still be completed. @@ -444,14 +452,15 @@ Note that the trait themselves can still be completed. Default: `false` -Whether to show full function/method signatures in completion docs. +Show full function / method signatures in completion docs. ## rust-analyzer.completion.hideDeprecated {#completion.hideDeprecated} Default: `false` -Whether to omit deprecated items from autocompletion. By default they are marked as deprecated but not hidden. +Omit deprecated items from completions. By default they are marked as deprecated but not +hidden. ## rust-analyzer.completion.limit {#completion.limit} @@ -465,14 +474,15 @@ Maximum number of completions to return. If `None`, the limit is infinite. Default: `true` -Whether to show postfix snippets like `dbg`, `if`, `not`, etc. +Show postfix snippets like `dbg`, `if`, `not`, etc. ## rust-analyzer.completion.privateEditable.enable {#completion.privateEditable.enable} Default: `false` -Enables completions of private items and fields that are defined in the current workspace even if they are not visible at the current position. +Show completions of private items and fields that are defined in the current workspace +even if they are not visible at the current position. ## rust-analyzer.completion.snippets.custom {#completion.snippets.custom} @@ -529,7 +539,7 @@ Custom completion snippets. Default: `false` -Whether to enable term search based snippets like `Some(foo.bar().baz())`. +Enable term search based snippets like `Some(foo.bar().baz())`. ## rust-analyzer.completion.termSearch.fuel {#completion.termSearch.fuel} @@ -550,30 +560,30 @@ List of rust-analyzer diagnostics to disable. Default: `true` -Whether to show native rust-analyzer diagnostics. +Show native rust-analyzer diagnostics. ## rust-analyzer.diagnostics.experimental.enable {#diagnostics.experimental.enable} Default: `false` -Whether to show experimental rust-analyzer diagnostics that might -have more false positives than usual. +Show experimental rust-analyzer diagnostics that might have more false positives than +usual. ## rust-analyzer.diagnostics.remapPrefix {#diagnostics.remapPrefix} Default: `{}` -Map of prefixes to be substituted when parsing diagnostic file paths. -This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`. +Map of prefixes to be substituted when parsing diagnostic file paths. This should be the +reverse mapping of what is passed to `rustc` as `--remap-path-prefix`. ## rust-analyzer.diagnostics.styleLints.enable {#diagnostics.styleLints.enable} Default: `false` -Whether to run additional style lints. +Run additional style lints. ## rust-analyzer.diagnostics.warningsAsHint {#diagnostics.warningsAsHint} @@ -582,8 +592,8 @@ Default: `[]` List of warnings that should be displayed with hint severity. -The warnings will be indicated by faded text or three dots in code -and will not show up in the `Problems Panel`. +The warnings will be indicated by faded text or three dots in code and will not show up +in the `Problems Panel`. ## rust-analyzer.diagnostics.warningsAsInfo {#diagnostics.warningsAsInfo} @@ -592,17 +602,19 @@ Default: `[]` List of warnings that should be displayed with info severity. -The warnings will be indicated by a blue squiggly underline in code -and a blue icon in the `Problems Panel`. +The warnings will be indicated by a blue squiggly underline in code and a blue icon in +the `Problems Panel`. ## rust-analyzer.files.exclude {#files.exclude} Default: `[]` -These paths (file/directories) will be ignored by rust-analyzer. They are -relative to the workspace root, and globs are not supported. You may -also need to add the folders to Code's `files.watcherExclude`. +List of files to ignore + +These paths (file/directories) will be ignored by rust-analyzer. They are relative to +the workspace root, and globs are not supported. You may also need to add the folders to +Code's `files.watcherExclude`. ## rust-analyzer.files.watcher {#files.watcher} @@ -616,64 +628,67 @@ Controls file watching implementation. Default: `true` -Enables highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`). +Highlight related return values while the cursor is on any `match`, `if`, or match arm +arrow (`=>`). ## rust-analyzer.highlightRelated.breakPoints.enable {#highlightRelated.breakPoints.enable} Default: `true` -Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. +Highlight related references while the cursor is on `break`, `loop`, `while`, or `for` +keywords. ## rust-analyzer.highlightRelated.closureCaptures.enable {#highlightRelated.closureCaptures.enable} Default: `true` -Enables highlighting of all captures of a closure while the cursor is on the `|` or move keyword of a closure. +Highlight all captures of a closure while the cursor is on the `|` or move keyword of a closure. ## rust-analyzer.highlightRelated.exitPoints.enable {#highlightRelated.exitPoints.enable} Default: `true` -Enables highlighting of all exit points while the cursor is on any `return`, `?`, `fn`, or return type arrow (`->`). +Highlight all exit points while the cursor is on any `return`, `?`, `fn`, or return type +arrow (`->`). ## rust-analyzer.highlightRelated.references.enable {#highlightRelated.references.enable} Default: `true` -Enables highlighting of related references while the cursor is on any identifier. +Highlight related references while the cursor is on any identifier. ## rust-analyzer.highlightRelated.yieldPoints.enable {#highlightRelated.yieldPoints.enable} Default: `true` -Enables highlighting of all break points for a loop or block context while the cursor is on any `async` or `await` keywords. +Highlight all break points for a loop or block context while the cursor is on any +`async` or `await` keywords. ## rust-analyzer.hover.actions.debug.enable {#hover.actions.debug.enable} Default: `true` -Whether to show `Debug` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. +Show `Debug` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set. ## rust-analyzer.hover.actions.enable {#hover.actions.enable} Default: `true` -Whether to show HoverActions in Rust files. +Show HoverActions in Rust files. ## rust-analyzer.hover.actions.gotoTypeDef.enable {#hover.actions.gotoTypeDef.enable} Default: `true` -Whether to show `Go to Type Definition` action. Only applies when +Show `Go to Type Definition` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set. @@ -681,46 +696,45 @@ Whether to show `Go to Type Definition` action. Only applies when Default: `true` -Whether to show `Implementations` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. +Show `Implementations` action. Only applies when `#rust-analyzer.hover.actions.enable#` +is set. ## rust-analyzer.hover.actions.references.enable {#hover.actions.references.enable} Default: `false` -Whether to show `References` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. +Show `References` action. Only applies when `#rust-analyzer.hover.actions.enable#` is +set. ## rust-analyzer.hover.actions.run.enable {#hover.actions.run.enable} Default: `true` -Whether to show `Run` action. Only applies when -`#rust-analyzer.hover.actions.enable#` is set. +Show `Run` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set. ## rust-analyzer.hover.actions.updateTest.enable {#hover.actions.updateTest.enable} Default: `true` -Whether to show `Update Test` action. Only applies when -`#rust-analyzer.hover.actions.enable#` and `#rust-analyzer.hover.actions.run.enable#` are set. +Show `Update Test` action. Only applies when `#rust-analyzer.hover.actions.enable#` and +`#rust-analyzer.hover.actions.run.enable#` are set. ## rust-analyzer.hover.documentation.enable {#hover.documentation.enable} Default: `true` -Whether to show documentation on hover. +Show documentation on hover. ## rust-analyzer.hover.documentation.keywords.enable {#hover.documentation.keywords.enable} Default: `true` -Whether to show keyword hover popups. Only applies when +Show keyword hover popups. Only applies when `#rust-analyzer.hover.documentation.enable#` is set. @@ -728,7 +742,7 @@ Whether to show keyword hover popups. Only applies when Default: `true` -Whether to show drop glue information on hover. +Show drop glue information on hover. ## rust-analyzer.hover.links.enable {#hover.links.enable} @@ -742,9 +756,11 @@ Use markdown syntax for links on hover. Default: `20` -Whether to show what types are used as generic arguments in calls etc. on hover, and what is their max length to show such types, beyond it they will be shown with ellipsis. +Show what types are used as generic arguments in calls etc. on hover, and limit the max +length to show such types, beyond which they will be shown with ellipsis. -This can take three values: `null` means "unlimited", the string `"hide"` means to not show generic substitutions at all, and a number means to limit them to X characters. +This can take three values: `null` means "unlimited", the string `"hide"` means to not +show generic substitutions at all, and a number means to limit them to X characters. The default is 20 characters. @@ -760,7 +776,7 @@ How to render the align information in a memory layout hover. Default: `true` -Whether to show memory layout data on hover. +Show memory layout data on hover. ## rust-analyzer.hover.memoryLayout.niches {#hover.memoryLayout.niches} @@ -802,7 +818,8 @@ How many variants of an enum to display when hovering on. Show none if empty. Default: `5` -How many fields of a struct, variant or union to display when hovering on. Show none if empty. +How many fields of a struct, variant or union to display when hovering on. Show none if +empty. ## rust-analyzer.hover.show.traitAssocItems {#hover.show.traitAssocItems} @@ -816,7 +833,8 @@ How many associated items of a trait to display when hovering a trait. Default: `false` -Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file. +Enforce the import granularity setting for all files. If set to false rust-analyzer will +try to keep import styles consistent per file. ## rust-analyzer.imports.granularity.group {#imports.granularity.group} @@ -830,14 +848,17 @@ How imports should be grouped into use statements. Default: `true` -Group inserted imports by the [following order](https://rust-analyzer.github.io/book/features.html#auto-import). Groups are separated by newlines. +Group inserted imports by the [following +order](https://rust-analyzer.github.io/book/features.html#auto-import). Groups are +separated by newlines. ## rust-analyzer.imports.merge.glob {#imports.merge.glob} Default: `true` -Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`. +Allow import insertion to merge new imports into single path glob imports like `use +std::fmt::*;`. ## rust-analyzer.imports.preferNoStd {#imports.preferNoStd} @@ -851,7 +872,7 @@ Prefer to unconditionally use imports of the core and alloc crate, over the std Default: `false` -Whether to prefer import paths containing a `prelude` module. +Prefer import paths containing a `prelude` module. ## rust-analyzer.imports.prefix {#imports.prefix} @@ -865,28 +886,30 @@ The path structure for newly inserted paths to use. Default: `false` -Whether to prefix external (including std, core) crate imports with `::`. e.g. "use ::std::io::Read;". +Prefix external (including std, core) crate imports with `::`. + +E.g. `use ::std::io::Read;`. ## rust-analyzer.inlayHints.bindingModeHints.enable {#inlayHints.bindingModeHints.enable} Default: `false` -Whether to show inlay type hints for binding modes. +Show inlay type hints for binding modes. ## rust-analyzer.inlayHints.chainingHints.enable {#inlayHints.chainingHints.enable} Default: `true` -Whether to show inlay type hints for method chains. +Show inlay type hints for method chains. ## rust-analyzer.inlayHints.closingBraceHints.enable {#inlayHints.closingBraceHints.enable} Default: `true` -Whether to show inlay hints after a closing `}` to indicate what item it belongs to. +Show inlay hints after a closing `}` to indicate what item it belongs to. ## rust-analyzer.inlayHints.closingBraceHints.minLines {#inlayHints.closingBraceHints.minLines} @@ -901,14 +924,14 @@ to always show them). Default: `false` -Whether to show inlay hints for closure captures. +Show inlay hints for closure captures. ## rust-analyzer.inlayHints.closureReturnTypeHints.enable {#inlayHints.closureReturnTypeHints.enable} Default: `"never"` -Whether to show inlay type hints for return types of closures. +Show inlay type hints for return types of closures. ## rust-analyzer.inlayHints.closureStyle {#inlayHints.closureStyle} @@ -922,77 +945,77 @@ Closure notation in type and chaining inlay hints. Default: `"never"` -Whether to show enum variant discriminant hints. +Show enum variant discriminant hints. ## rust-analyzer.inlayHints.expressionAdjustmentHints.enable {#inlayHints.expressionAdjustmentHints.enable} Default: `"never"` -Whether to show inlay hints for type adjustments. +Show inlay hints for type adjustments. ## rust-analyzer.inlayHints.expressionAdjustmentHints.hideOutsideUnsafe {#inlayHints.expressionAdjustmentHints.hideOutsideUnsafe} Default: `false` -Whether to hide inlay hints for type adjustments outside of `unsafe` blocks. +Hide inlay hints for type adjustments outside of `unsafe` blocks. ## rust-analyzer.inlayHints.expressionAdjustmentHints.mode {#inlayHints.expressionAdjustmentHints.mode} Default: `"prefix"` -Whether to show inlay hints as postfix ops (`.*` instead of `*`, etc). +Show inlay hints as postfix ops (`.*` instead of `*`, etc). ## rust-analyzer.inlayHints.genericParameterHints.const.enable {#inlayHints.genericParameterHints.const.enable} Default: `true` -Whether to show const generic parameter name inlay hints. +Show const generic parameter name inlay hints. ## rust-analyzer.inlayHints.genericParameterHints.lifetime.enable {#inlayHints.genericParameterHints.lifetime.enable} Default: `false` -Whether to show generic lifetime parameter name inlay hints. +Show generic lifetime parameter name inlay hints. ## rust-analyzer.inlayHints.genericParameterHints.type.enable {#inlayHints.genericParameterHints.type.enable} Default: `false` -Whether to show generic type parameter name inlay hints. +Show generic type parameter name inlay hints. ## rust-analyzer.inlayHints.implicitDrops.enable {#inlayHints.implicitDrops.enable} Default: `false` -Whether to show implicit drop hints. +Show implicit drop hints. ## rust-analyzer.inlayHints.implicitSizedBoundHints.enable {#inlayHints.implicitSizedBoundHints.enable} Default: `false` -Whether to show inlay hints for the implied type parameter `Sized` bound. +Show inlay hints for the implied type parameter `Sized` bound. ## rust-analyzer.inlayHints.lifetimeElisionHints.enable {#inlayHints.lifetimeElisionHints.enable} Default: `"never"` -Whether to show inlay type hints for elided lifetimes in function signatures. +Show inlay type hints for elided lifetimes in function signatures. ## rust-analyzer.inlayHints.lifetimeElisionHints.useParameterNames {#inlayHints.lifetimeElisionHints.useParameterNames} Default: `false` -Whether to prefer using parameter names as the name for elided lifetime hints if possible. +Prefer using parameter names as the name for elided lifetime hints if possible. ## rust-analyzer.inlayHints.maxLength {#inlayHints.maxLength} @@ -1006,23 +1029,24 @@ Maximum length for inlay hints. Set to null to have an unlimited length. Default: `true` -Whether to show function parameter name inlay hints at the call -site. +Show function parameter name inlay hints at the call site. ## rust-analyzer.inlayHints.rangeExclusiveHints.enable {#inlayHints.rangeExclusiveHints.enable} Default: `false` -Whether to show exclusive range inlay hints. +Show exclusive range inlay hints. ## rust-analyzer.inlayHints.reborrowHints.enable {#inlayHints.reborrowHints.enable} Default: `"never"` -Whether to show inlay hints for compiler inserted reborrows. -This setting is deprecated in favor of #rust-analyzer.inlayHints.expressionAdjustmentHints.enable#. +Show inlay hints for compiler inserted reborrows. + +This setting is deprecated in favor of +#rust-analyzer.inlayHints.expressionAdjustmentHints.enable#. ## rust-analyzer.inlayHints.renderColons {#inlayHints.renderColons} @@ -1036,36 +1060,38 @@ Whether to render leading colons for type hints, and trailing colons for paramet Default: `true` -Whether to show inlay type hints for variables. +Show inlay type hints for variables. ## rust-analyzer.inlayHints.typeHints.hideClosureInitialization {#inlayHints.typeHints.hideClosureInitialization} Default: `false` -Whether to hide inlay type hints for `let` statements that initialize to a closure. -Only applies to closures with blocks, same as `#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`. +Hide inlay type hints for `let` statements that initialize to a closure. + +Only applies to closures with blocks, same as +`#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`. ## rust-analyzer.inlayHints.typeHints.hideClosureParameter {#inlayHints.typeHints.hideClosureParameter} Default: `false` -Whether to hide inlay parameter type hints for closures. +Hide inlay parameter type hints for closures. ## rust-analyzer.inlayHints.typeHints.hideNamedConstructor {#inlayHints.typeHints.hideNamedConstructor} Default: `false` -Whether to hide inlay type hints for constructors. +Hide inlay type hints for constructors. ## rust-analyzer.interpret.tests {#interpret.tests} Default: `false` -Enables the experimental support for interpreting tests. +Enable the experimental support for interpreting tests. ## rust-analyzer.joinLines.joinAssignments {#joinLines.joinAssignments} @@ -1100,23 +1126,21 @@ Join lines unwraps trivial blocks. Default: `true` -Whether to show `Debug` lens. Only applies when -`#rust-analyzer.lens.enable#` is set. +Show `Debug` lens. Only applies when `#rust-analyzer.lens.enable#` is set. ## rust-analyzer.lens.enable {#lens.enable} Default: `true` -Whether to show CodeLens in Rust files. +Show CodeLens in Rust files. ## rust-analyzer.lens.implementations.enable {#lens.implementations.enable} Default: `true` -Whether to show `Implementations` lens. Only applies when -`#rust-analyzer.lens.enable#` is set. +Show `Implementations` lens. Only applies when `#rust-analyzer.lens.enable#` is set. ## rust-analyzer.lens.location {#lens.location} @@ -1130,60 +1154,56 @@ Where to render annotations. Default: `false` -Whether to show `References` lens for Struct, Enum, and Union. -Only applies when `#rust-analyzer.lens.enable#` is set. +Show `References` lens for Struct, Enum, and Union. Only applies when +`#rust-analyzer.lens.enable#` is set. ## rust-analyzer.lens.references.enumVariant.enable {#lens.references.enumVariant.enable} Default: `false` -Whether to show `References` lens for Enum Variants. -Only applies when `#rust-analyzer.lens.enable#` is set. +Show `References` lens for Enum Variants. Only applies when +`#rust-analyzer.lens.enable#` is set. ## rust-analyzer.lens.references.method.enable {#lens.references.method.enable} Default: `false` -Whether to show `Method References` lens. Only applies when -`#rust-analyzer.lens.enable#` is set. +Show `Method References` lens. Only applies when `#rust-analyzer.lens.enable#` is set. ## rust-analyzer.lens.references.trait.enable {#lens.references.trait.enable} Default: `false` -Whether to show `References` lens for Trait. -Only applies when `#rust-analyzer.lens.enable#` is set. +Show `References` lens for Trait. Only applies when `#rust-analyzer.lens.enable#` is +set. ## rust-analyzer.lens.run.enable {#lens.run.enable} Default: `true` -Whether to show `Run` lens. Only applies when -`#rust-analyzer.lens.enable#` is set. +Show `Run` lens. Only applies when `#rust-analyzer.lens.enable#` is set. ## rust-analyzer.lens.updateTest.enable {#lens.updateTest.enable} Default: `true` -Whether to show `Update Test` lens. Only applies when -`#rust-analyzer.lens.enable#` and `#rust-analyzer.lens.run.enable#` are set. +Show `Update Test` lens. Only applies when `#rust-analyzer.lens.enable#` and +`#rust-analyzer.lens.run.enable#` are set. ## rust-analyzer.linkedProjects {#linkedProjects} Default: `[]` -Disable project auto-discovery in favor of explicitly specified set -of projects. +Disable project auto-discovery in favor of explicitly specified set of projects. -Elements must be paths pointing to `Cargo.toml`, -`rust-project.json`, `.rs` files (which will be treated as standalone files) or JSON -objects in `rust-project.json` format. +Elements must be paths pointing to `Cargo.toml`, `rust-project.json`, `.rs` files (which +will be treated as standalone files) or JSON objects in `rust-project.json` format. ## rust-analyzer.lru.capacity {#lru.capacity} @@ -1197,21 +1217,22 @@ Number of syntax trees rust-analyzer keeps in memory. Defaults to 128. Default: `{}` -Sets the LRU capacity of the specified queries. +The LRU capacity of the specified queries. ## rust-analyzer.notifications.cargoTomlNotFound {#notifications.cargoTomlNotFound} Default: `true` -Whether to show `can't find Cargo.toml` error message. +Show `can't find Cargo.toml` error message. ## rust-analyzer.numThreads {#numThreads} Default: `null` -How many worker threads in the main loop. The default `null` means to pick automatically. +The number of worker threads in the main loop. The default `null` means to pick +automatically. ## rust-analyzer.procMacro.attributes.enable {#procMacro.attributes.enable} @@ -1346,7 +1367,10 @@ doc links. Default: `true` -Whether the server is allowed to emit non-standard tokens and modifiers. +Emit non-standard tokens and modifiers + +When enabled, rust-analyzer will emit tokens and modifiers that are not part of the +standard set of semantic tokens. ## rust-analyzer.semanticHighlighting.operator.enable {#semanticHighlighting.operator.enable} @@ -1427,11 +1451,15 @@ Show documentation. Default: `"=."` Specify the characters allowed to invoke special on typing triggers. -- typing `=` after `let` tries to smartly add `;` if `=` is followed by an existing expression + +- typing `=` after `let` tries to smartly add `;` if `=` is followed by an existing + expression - typing `=` between two expressions adds `;` when in statement position -- typing `=` to turn an assignment into an equality comparison removes `;` when in expression position +- typing `=` to turn an assignment into an equality comparison removes `;` when in + expression position - typing `.` in a chain method call auto-indents -- typing `{` or `(` in front of an expression inserts a closing `}` or `)` after the expression +- typing `{` or `(` in front of an expression inserts a closing `}` or `)` after the + expression - typing `{` in a use item adds a closing `}` in the right place - typing `>` to complete a return type `->` will insert a whitespace after it - typing `<` in a path or type position inserts a closing `>` after the path or type. @@ -1475,8 +1503,8 @@ Below is an example of a valid configuration: **Warning**: This format is provisional and subject to change. -[`DiscoverWorkspaceConfig::command`] *must* return a JSON object -corresponding to `DiscoverProjectData::Finished`: +[`DiscoverWorkspaceConfig::command`] *must* return a JSON object corresponding to +`DiscoverProjectData::Finished`: ```norun #[derive(Debug, Clone, Deserialize, Serialize)] @@ -1506,12 +1534,11 @@ As JSON, `DiscoverProjectData::Finished` is: } ``` -It is encouraged, but not required, to use the other variants on -`DiscoverProjectData` to provide a more polished end-user experience. +It is encouraged, but not required, to use the other variants on `DiscoverProjectData` +to provide a more polished end-user experience. -`DiscoverWorkspaceConfig::command` may *optionally* include an `{arg}`, -which will be substituted with the JSON-serialized form of the following -enum: +`DiscoverWorkspaceConfig::command` may *optionally* include an `{arg}`, which will be +substituted with the JSON-serialized form of the following enum: ```norun #[derive(PartialEq, Clone, Debug, Serialize)] @@ -1538,11 +1565,10 @@ Similarly, the JSON representation of `DiscoverArgument::Buildfile` is: } ``` -`DiscoverArgument::Path` is used to find and generate a `rust-project.json`, -and therefore, a workspace, whereas `DiscoverArgument::buildfile` is used to -to update an existing workspace. As a reference for implementors, -buck2's `rust-project` will likely be useful: -https://github.com/facebook/buck2/tree/main/integrations/rust-project. +`DiscoverArgument::Path` is used to find and generate a `rust-project.json`, and +therefore, a workspace, whereas `DiscoverArgument::buildfile` is used to to update an +existing workspace. As a reference for implementors, buck2's `rust-project` will likely +be useful: https://github.com/facebook/buck2/tree/main/integrations/rust-project. ## rust-analyzer.workspace.symbol.search.excludeImports {#workspace.symbol.search.excludeImports} diff --git a/src/tools/rust-analyzer/editors/code/package.json b/src/tools/rust-analyzer/editors/code/package.json index 3cb4c21ee1fb..8953a30dacb2 100644 --- a/src/tools/rust-analyzer/editors/code/package.json +++ b/src/tools/rust-analyzer/editors/code/package.json @@ -354,35 +354,122 @@ ], "configuration": [ { - "title": "general", + "title": "Rust Analyzer" + }, + { + "title": "Assist" + }, + { + "title": "Cache Priming" + }, + { + "title": "Cargo" + }, + { + "title": "Cfg" + }, + { + "title": "Check" + }, + { + "title": "Completion" + }, + { + "title": "Debug" + }, + { + "title": "Diagnostics" + }, + { + "title": "Files" + }, + { + "title": "Highlight Related" + }, + { + "title": "Hover" + }, + { + "title": "Imports" + }, + { + "title": "Inlay Hints" + }, + { + "title": "Interpret" + }, + { + "title": "Join Lines" + }, + { + "title": "Lens" + }, + { + "title": "Lru" + }, + { + "title": "Notifications" + }, + { + "title": "Proc Macro" + }, + { + "title": "References" + }, + { + "title": "Runnables" + }, + { + "title": "Rustc" + }, + { + "title": "Rustfmt" + }, + { + "title": "Semantic Highlighting" + }, + { + "title": "Signature Info" + }, + { + "title": "Typing" + }, + { + "title": "Vfs" + }, + { + "title": "Workspace" + }, + { + "title": "rust-analyzer", "properties": { "rust-analyzer.restartServerOnConfigChange": { - "markdownDescription": "Whether to restart the server automatically when certain settings that require a restart are changed.", + "description": "Restart the server automatically when settings that require a restart are changed.", "default": false, "type": "boolean" }, "rust-analyzer.showUnlinkedFileNotification": { - "markdownDescription": "Whether to show a notification for unlinked files asking the user to add the corresponding Cargo.toml to the linked projects setting.", + "description": "Show a notification for unlinked files, prompting the user to add the corresponding Cargo.toml to the linked projects setting.", "default": true, "type": "boolean" }, "rust-analyzer.showRequestFailedErrorNotification": { - "markdownDescription": "Whether to show error notifications for failing requests.", + "description": "Show error notifications when requests fail.", "default": true, "type": "boolean" }, "rust-analyzer.showDependenciesExplorer": { - "markdownDescription": "Whether to show the dependencies view.", + "description": "Show Rust Dependencies in the Explorer view.", "default": true, "type": "boolean" }, "rust-analyzer.showSyntaxTree": { - "markdownDescription": "Whether to show the syntax tree view.", + "description": "Show Syntax Tree in the Explorer view.", "default": false, "type": "boolean" }, "rust-analyzer.testExplorer": { - "markdownDescription": "Whether to show the test explorer.", + "description": "Show the Test Explorer view.", "default": false, "type": "boolean" }, @@ -394,7 +481,7 @@ } }, { - "title": "runnables", + "title": "Runnables", "properties": { "rust-analyzer.runnables.extraEnv": { "anyOf": [ @@ -452,7 +539,7 @@ } }, { - "title": "statusBar", + "title": "Status Bar", "properties": { "rust-analyzer.statusBar.clickAction": { "type": "string", @@ -524,7 +611,7 @@ } }, { - "title": "server", + "title": "Server", "properties": { "rust-analyzer.server.path": { "type": [ @@ -553,7 +640,7 @@ } }, { - "title": "trace", + "title": "Trace", "properties": { "rust-analyzer.trace.server": { "type": "string", @@ -580,7 +667,7 @@ } }, { - "title": "debug", + "title": "Debug", "properties": { "rust-analyzer.debug.engine": { "type": "string", @@ -625,7 +712,7 @@ } }, { - "title": "typing", + "title": "Typing", "properties": { "rust-analyzer.typing.continueCommentsOnNewline": { "markdownDescription": "Whether to prefix newlines after comments with the corresponding comment prefix.", @@ -635,7 +722,7 @@ } }, { - "title": "diagnostics", + "title": "Diagnostics", "properties": { "rust-analyzer.diagnostics.previewRustcOutput": { "markdownDescription": "Whether to show the main part of the rendered rustc output of a diagnostic message.", @@ -653,17 +740,17 @@ "title": "$generated-start" }, { - "title": "assist", + "title": "Assist", "properties": { "rust-analyzer.assist.emitMustUse": { - "markdownDescription": "Whether to insert #[must_use] when generating `as_` methods\nfor enum variants.", + "markdownDescription": "Insert #[must_use] when generating `as_` methods for enum variants.", "default": false, "type": "boolean" } } }, { - "title": "assist", + "title": "Assist", "properties": { "rust-analyzer.assist.expressionFillDefault": { "markdownDescription": "Placeholder expression to use for missing expressions in assists.", @@ -681,27 +768,27 @@ } }, { - "title": "assist", + "title": "Assist", "properties": { "rust-analyzer.assist.preferSelf": { - "markdownDescription": "When inserting a type (e.g. in \"fill match arms\" assist), prefer to use `Self` over the type name where possible.", + "markdownDescription": "Prefer to use `Self` over the type name when inserting a type (e.g. in \"fill match arms\" assist).", "default": false, "type": "boolean" } } }, { - "title": "assist", + "title": "Assist", "properties": { "rust-analyzer.assist.termSearch.borrowcheck": { - "markdownDescription": "Enable borrow checking for term search code assists. If set to false, also there will be more suggestions, but some of them may not borrow-check.", + "markdownDescription": "Enable borrow checking for term search code assists. If set to false, also there will be\nmore suggestions, but some of them may not borrow-check.", "default": true, "type": "boolean" } } }, { - "title": "assist", + "title": "Assist", "properties": { "rust-analyzer.assist.termSearch.fuel": { "markdownDescription": "Term search fuel in \"units of work\" for assists (Defaults to 1800).", @@ -712,7 +799,7 @@ } }, { - "title": "cachePriming", + "title": "Cache Priming", "properties": { "rust-analyzer.cachePriming.enable": { "markdownDescription": "Warm up caches on project load.", @@ -722,10 +809,10 @@ } }, { - "title": "cachePriming", + "title": "Cache Priming", "properties": { "rust-analyzer.cachePriming.numThreads": { - "markdownDescription": "How many worker threads to handle priming caches. The default `0` means to pick automatically.", + "markdownDescription": "How many worker threads to handle priming caches. The default `0` means to pick\nautomatically.", "default": "physical", "anyOf": [ { @@ -749,7 +836,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.allTargets": { "markdownDescription": "Pass `--all-targets` to cargo invocation.", @@ -759,7 +846,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.autoreload": { "markdownDescription": "Automatically refresh project info via `cargo metadata` on\n`Cargo.toml` or `.cargo/config.toml` changes.", @@ -769,7 +856,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.buildScripts.enable": { "markdownDescription": "Run build scripts (`build.rs`) for more precise code analysis.", @@ -779,7 +866,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.buildScripts.invocationStrategy": { "markdownDescription": "Specifies the invocation strategy to use when running the build scripts command.\nIf `per_workspace` is set, the command will be executed for each Rust workspace with the\nworkspace as the working directory.\nIf `once` is set, the command will be executed once with the opened project as the\nworking directory.\nThis config only has an effect when `#rust-analyzer.cargo.buildScripts.overrideCommand#`\nis set.", @@ -797,7 +884,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.buildScripts.overrideCommand": { "markdownDescription": "Override the command rust-analyzer uses to run build scripts and\nbuild procedural macros. The command is required to output json\nand should therefore include `--message-format=json` or a similar\noption.\n\nIf there are multiple linked projects/workspaces, this command is invoked for\neach of them, with the working directory being the workspace root\n(i.e., the folder containing the `Cargo.toml`). This can be overwritten\nby changing `#rust-analyzer.cargo.buildScripts.invocationStrategy#`.\n\nBy default, a cargo invocation will be constructed for the configured\ntargets and features, with the following base command line:\n\n```bash\ncargo check --quiet --workspace --message-format=json --all-targets --keep-going\n```\n.", @@ -813,7 +900,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.buildScripts.rebuildOnSave": { "markdownDescription": "Rerun proc-macros building/build-scripts running when proc-macro\nor build-script sources change and are saved.", @@ -823,7 +910,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.buildScripts.useRustcWrapper": { "markdownDescription": "Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to\navoid checking unnecessary things.", @@ -833,7 +920,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.cfgs": { "markdownDescription": "List of cfg options to enable with the given values.\n\nTo enable a name without a value, use `\"key\"`.\nTo enable a name with a value, use `\"key=value\"`.\nTo disable, prefix the entry with a `!`.", @@ -849,7 +936,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.extraArgs": { "markdownDescription": "Extra arguments that are passed to every cargo invocation.", @@ -862,7 +949,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.extraEnv": { "markdownDescription": "Extra environment variables that will be set when running cargo, rustc\nor other commands within the workspace. Useful for setting RUSTFLAGS.", @@ -872,7 +959,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.features": { "markdownDescription": "List of features to activate.\n\nSet this to `\"all\"` to pass `--all-features` to cargo.", @@ -898,7 +985,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.noDefaultFeatures": { "markdownDescription": "Whether to pass `--no-default-features` to cargo.", @@ -908,7 +995,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.noDeps": { "markdownDescription": "Whether to skip fetching dependencies. If set to \"true\", the analysis is performed\nentirely offline, and Cargo metadata for dependencies is not fetched.", @@ -918,7 +1005,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.sysroot": { "markdownDescription": "Relative path to the sysroot, or \"discover\" to try to automatically find it via\n\"rustc --print sysroot\".\n\nUnsetting this disables sysroot loading.\n\nThis option does not take effect until rust-analyzer is restarted.", @@ -931,7 +1018,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.sysrootSrc": { "markdownDescription": "Relative path to the sysroot library sources. If left unset, this will default to\n`{cargo.sysroot}/lib/rustlib/src/rust/library`.\n\nThis option does not take effect until rust-analyzer is restarted.", @@ -944,7 +1031,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.target": { "markdownDescription": "Compilation target override (target tuple).", @@ -957,7 +1044,7 @@ } }, { - "title": "cargo", + "title": "Cargo", "properties": { "rust-analyzer.cargo.targetDir": { "markdownDescription": "Optional path to a rust-analyzer specific target directory.\nThis prevents rust-analyzer's `cargo check` and initial build-script and proc-macro\nbuilding from locking the `Cargo.lock` at the expense of duplicating build artifacts.\n\nSet to `true` to use a subdirectory of the existing target directory or\nset to a path relative to the workspace to use that path.", @@ -977,7 +1064,7 @@ } }, { - "title": "cfg", + "title": "Cfg", "properties": { "rust-analyzer.cfg.setTest": { "markdownDescription": "Set `cfg(test)` for local crates. Defaults to true.", @@ -987,7 +1074,7 @@ } }, { - "title": "general", + "title": "rust-analyzer", "properties": { "rust-analyzer.checkOnSave": { "markdownDescription": "Run the check command for diagnostics on save.", @@ -997,7 +1084,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.allTargets": { "markdownDescription": "Check all targets and tests (`--all-targets`). Defaults to\n`#rust-analyzer.cargo.allTargets#`.", @@ -1010,7 +1097,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.command": { "markdownDescription": "Cargo command to use for `cargo check`.", @@ -1020,7 +1107,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.extraArgs": { "markdownDescription": "Extra arguments for `cargo check`.", @@ -1033,7 +1120,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.extraEnv": { "markdownDescription": "Extra environment variables that will be set when running `cargo check`.\nExtends `#rust-analyzer.cargo.extraEnv#`.", @@ -1043,7 +1130,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.features": { "markdownDescription": "List of features to activate. Defaults to\n`#rust-analyzer.cargo.features#`.\n\nSet to `\"all\"` to pass `--all-features` to Cargo.", @@ -1072,7 +1159,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.ignore": { "markdownDescription": "List of `cargo check` (or other command specified in `check.command`) diagnostics to ignore.\n\nFor example for `cargo check`: `dead_code`, `unused_imports`, `unused_variables`,...", @@ -1086,7 +1173,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.invocationStrategy": { "markdownDescription": "Specifies the invocation strategy to use when running the check command.\nIf `per_workspace` is set, the command will be executed for each workspace.\nIf `once` is set, the command will be executed once.\nThis config only has an effect when `#rust-analyzer.check.overrideCommand#`\nis set.", @@ -1104,7 +1191,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.noDefaultFeatures": { "markdownDescription": "Whether to pass `--no-default-features` to Cargo. Defaults to\n`#rust-analyzer.cargo.noDefaultFeatures#`.", @@ -1117,7 +1204,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.overrideCommand": { "markdownDescription": "Override the command rust-analyzer uses instead of `cargo check` for\ndiagnostics on save. The command is required to output json and\nshould therefore include `--message-format=json` or a similar option\n(if your client supports the `colorDiagnosticOutput` experimental\ncapability, you can use `--message-format=json-diagnostic-rendered-ansi`).\n\nIf you're changing this because you're using some tool wrapping\nCargo, you might also want to change\n`#rust-analyzer.cargo.buildScripts.overrideCommand#`.\n\nIf there are multiple linked projects/workspaces, this command is invoked for\neach of them, with the working directory being the workspace root\n(i.e., the folder containing the `Cargo.toml`). This can be overwritten\nby changing `#rust-analyzer.check.invocationStrategy#`.\n\nIf `$saved_file` is part of the command, rust-analyzer will pass\nthe absolute path of the saved file to the provided command. This is\nintended to be used with non-Cargo build systems.\nNote that `$saved_file` is experimental and may be removed in the future.\n\nAn example command would be:\n\n```bash\ncargo check --workspace --message-format=json --all-targets\n```\n.", @@ -1133,7 +1220,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.targets": { "markdownDescription": "Check for specific targets. Defaults to `#rust-analyzer.cargo.target#` if empty.\n\nCan be a single target, e.g. `\"x86_64-unknown-linux-gnu\"` or a list of targets, e.g.\n`[\"aarch64-apple-darwin\", \"x86_64-apple-darwin\"]`.\n\nAliased as `\"checkOnSave.targets\"`.", @@ -1156,7 +1243,7 @@ } }, { - "title": "check", + "title": "Check", "properties": { "rust-analyzer.check.workspace": { "markdownDescription": "Whether `--workspace` should be passed to `cargo check`.\nIf false, `-p ` will be passed instead if applicable. In case it is not, no\ncheck will be performed.", @@ -1166,50 +1253,50 @@ } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.addSemicolonToUnit": { - "markdownDescription": "Whether to automatically add a semicolon when completing unit-returning functions.\n\nIn `match` arms it completes a comma instead.", + "markdownDescription": "Automatically add a semicolon when completing unit-returning functions.\n\nIn `match` arms it completes a comma instead.", "default": true, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.autoAwait.enable": { - "markdownDescription": "Toggles the additional completions that automatically show method calls and field accesses with `await` prefixed to them when completing on a future.", + "markdownDescription": "Show method calls and field accesses completions with `await` prefixed to them when\ncompleting on a future.", "default": true, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.autoIter.enable": { - "markdownDescription": "Toggles the additional completions that automatically show method calls with `iter()` or `into_iter()` prefixed to them when completing on a type that has them.", + "markdownDescription": "Show method call completions with `iter()` or `into_iter()` prefixed to them when\ncompleting on a type that has them.", "default": true, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.autoimport.enable": { - "markdownDescription": "Toggles the additional completions that automatically add imports when completed.\nNote that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.", + "markdownDescription": "Show completions that automatically add imports when completed.\n\nNote that your client must specify the `additionalTextEdits` LSP client capability to\ntruly have this feature enabled.", "default": true, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.autoimport.exclude": { - "markdownDescription": "A list of full paths to items to exclude from auto-importing completions.\n\nTraits in this list won't have their methods suggested in completions unless the trait\nis in scope.\n\nYou can either specify a string path which defaults to type \"always\" or use the more verbose\nform `{ \"path\": \"path::to::item\", type: \"always\" }`.\n\nFor traits the type \"methods\" can be used to only exclude the methods but not the trait itself.\n\nThis setting also inherits `#rust-analyzer.completion.excludeTraits#`.", + "markdownDescription": "A list of full paths to items to exclude from auto-importing completions.\n\nTraits in this list won't have their methods suggested in completions unless the trait\nis in scope.\n\nYou can either specify a string path which defaults to type \"always\" or use the more\nverbose form `{ \"path\": \"path::to::item\", type: \"always\" }`.\n\nFor traits the type \"methods\" can be used to only exclude the methods but not the trait\nitself.\n\nThis setting also inherits `#rust-analyzer.completion.excludeTraits#`.", "default": [ { "path": "core::borrow::Borrow", @@ -1251,20 +1338,20 @@ } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.autoself.enable": { - "markdownDescription": "Toggles the additional completions that automatically show method calls and field accesses\nwith `self` prefixed to them when inside a method.", + "markdownDescription": "Show method calls and field access completions with `self` prefixed to them when\ninside a method.", "default": true, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.callable.snippets": { - "markdownDescription": "Whether to add parenthesis and argument snippets when completing function.", + "markdownDescription": "Add parenthesis and argument snippets when completing function.", "default": "fill_arguments", "type": "string", "enum": [ @@ -1281,10 +1368,10 @@ } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.excludeTraits": { - "markdownDescription": "A list of full paths to traits whose methods to exclude from completion.\n\nMethods from these traits won't be completed, even if the trait is in scope. However, they will still be suggested on expressions whose type is `dyn Trait`, `impl Trait` or `T where T: Trait`.\n\nNote that the trait themselves can still be completed.", + "markdownDescription": "A list of full paths to traits whose methods to exclude from completion.\n\nMethods from these traits won't be completed, even if the trait is in scope. However,\nthey will still be suggested on expressions whose type is `dyn Trait`, `impl Trait` or\n`T where T: Trait`.\n\nNote that the trait themselves can still be completed.", "default": [], "type": "array", "items": { @@ -1294,27 +1381,27 @@ } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.fullFunctionSignatures.enable": { - "markdownDescription": "Whether to show full function/method signatures in completion docs.", + "markdownDescription": "Show full function / method signatures in completion docs.", "default": false, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.hideDeprecated": { - "markdownDescription": "Whether to omit deprecated items from autocompletion. By default they are marked as deprecated but not hidden.", + "markdownDescription": "Omit deprecated items from completions. By default they are marked as deprecated but not\nhidden.", "default": false, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.limit": { "markdownDescription": "Maximum number of completions to return. If `None`, the limit is infinite.", @@ -1328,27 +1415,27 @@ } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.postfix.enable": { - "markdownDescription": "Whether to show postfix snippets like `dbg`, `if`, `not`, etc.", + "markdownDescription": "Show postfix snippets like `dbg`, `if`, `not`, etc.", "default": true, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.privateEditable.enable": { - "markdownDescription": "Enables completions of private items and fields that are defined in the current workspace even if they are not visible at the current position.", + "markdownDescription": "Show completions of private items and fields that are defined in the current workspace\neven if they are not visible at the current position.", "default": false, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.snippets.custom": { "markdownDescription": "Custom completion snippets.", @@ -1398,17 +1485,17 @@ } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.termSearch.enable": { - "markdownDescription": "Whether to enable term search based snippets like `Some(foo.bar().baz())`.", + "markdownDescription": "Enable term search based snippets like `Some(foo.bar().baz())`.", "default": false, "type": "boolean" } } }, { - "title": "completion", + "title": "Completion", "properties": { "rust-analyzer.completion.termSearch.fuel": { "markdownDescription": "Term search fuel in \"units of work\" for autocompletion (Defaults to 1000).", @@ -1419,7 +1506,7 @@ } }, { - "title": "diagnostics", + "title": "Diagnostics", "properties": { "rust-analyzer.diagnostics.disabled": { "markdownDescription": "List of rust-analyzer diagnostics to disable.", @@ -1433,50 +1520,50 @@ } }, { - "title": "diagnostics", + "title": "Diagnostics", "properties": { "rust-analyzer.diagnostics.enable": { - "markdownDescription": "Whether to show native rust-analyzer diagnostics.", + "markdownDescription": "Show native rust-analyzer diagnostics.", "default": true, "type": "boolean" } } }, { - "title": "diagnostics", + "title": "Diagnostics", "properties": { "rust-analyzer.diagnostics.experimental.enable": { - "markdownDescription": "Whether to show experimental rust-analyzer diagnostics that might\nhave more false positives than usual.", + "markdownDescription": "Show experimental rust-analyzer diagnostics that might have more false positives than\nusual.", "default": false, "type": "boolean" } } }, { - "title": "diagnostics", + "title": "Diagnostics", "properties": { "rust-analyzer.diagnostics.remapPrefix": { - "markdownDescription": "Map of prefixes to be substituted when parsing diagnostic file paths.\nThis should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.", + "markdownDescription": "Map of prefixes to be substituted when parsing diagnostic file paths. This should be the\nreverse mapping of what is passed to `rustc` as `--remap-path-prefix`.", "default": {}, "type": "object" } } }, { - "title": "diagnostics", + "title": "Diagnostics", "properties": { "rust-analyzer.diagnostics.styleLints.enable": { - "markdownDescription": "Whether to run additional style lints.", + "markdownDescription": "Run additional style lints.", "default": false, "type": "boolean" } } }, { - "title": "diagnostics", + "title": "Diagnostics", "properties": { "rust-analyzer.diagnostics.warningsAsHint": { - "markdownDescription": "List of warnings that should be displayed with hint severity.\n\nThe warnings will be indicated by faded text or three dots in code\nand will not show up in the `Problems Panel`.", + "markdownDescription": "List of warnings that should be displayed with hint severity.\n\nThe warnings will be indicated by faded text or three dots in code and will not show up\nin the `Problems Panel`.", "default": [], "type": "array", "items": { @@ -1486,10 +1573,10 @@ } }, { - "title": "diagnostics", + "title": "Diagnostics", "properties": { "rust-analyzer.diagnostics.warningsAsInfo": { - "markdownDescription": "List of warnings that should be displayed with info severity.\n\nThe warnings will be indicated by a blue squiggly underline in code\nand a blue icon in the `Problems Panel`.", + "markdownDescription": "List of warnings that should be displayed with info severity.\n\nThe warnings will be indicated by a blue squiggly underline in code and a blue icon in\nthe `Problems Panel`.", "default": [], "type": "array", "items": { @@ -1499,10 +1586,10 @@ } }, { - "title": "files", + "title": "Files", "properties": { "rust-analyzer.files.exclude": { - "markdownDescription": "These paths (file/directories) will be ignored by rust-analyzer. They are\nrelative to the workspace root, and globs are not supported. You may\nalso need to add the folders to Code's `files.watcherExclude`.", + "markdownDescription": "List of files to ignore\n\nThese paths (file/directories) will be ignored by rust-analyzer. They are relative to\nthe workspace root, and globs are not supported. You may also need to add the folders to\nCode's `files.watcherExclude`.", "default": [], "type": "array", "items": { @@ -1512,7 +1599,7 @@ } }, { - "title": "files", + "title": "Files", "properties": { "rust-analyzer.files.watcher": { "markdownDescription": "Controls file watching implementation.", @@ -1530,167 +1617,167 @@ } }, { - "title": "highlightRelated", + "title": "Highlight Related", "properties": { "rust-analyzer.highlightRelated.branchExitPoints.enable": { - "markdownDescription": "Enables highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`).", + "markdownDescription": "Highlight related return values while the cursor is on any `match`, `if`, or match arm\narrow (`=>`).", "default": true, "type": "boolean" } } }, { - "title": "highlightRelated", + "title": "Highlight Related", "properties": { "rust-analyzer.highlightRelated.breakPoints.enable": { - "markdownDescription": "Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords.", + "markdownDescription": "Highlight related references while the cursor is on `break`, `loop`, `while`, or `for`\nkeywords.", "default": true, "type": "boolean" } } }, { - "title": "highlightRelated", + "title": "Highlight Related", "properties": { "rust-analyzer.highlightRelated.closureCaptures.enable": { - "markdownDescription": "Enables highlighting of all captures of a closure while the cursor is on the `|` or move keyword of a closure.", + "markdownDescription": "Highlight all captures of a closure while the cursor is on the `|` or move keyword of a closure.", "default": true, "type": "boolean" } } }, { - "title": "highlightRelated", + "title": "Highlight Related", "properties": { "rust-analyzer.highlightRelated.exitPoints.enable": { - "markdownDescription": "Enables highlighting of all exit points while the cursor is on any `return`, `?`, `fn`, or return type arrow (`->`).", + "markdownDescription": "Highlight all exit points while the cursor is on any `return`, `?`, `fn`, or return type\narrow (`->`).", "default": true, "type": "boolean" } } }, { - "title": "highlightRelated", + "title": "Highlight Related", "properties": { "rust-analyzer.highlightRelated.references.enable": { - "markdownDescription": "Enables highlighting of related references while the cursor is on any identifier.", + "markdownDescription": "Highlight related references while the cursor is on any identifier.", "default": true, "type": "boolean" } } }, { - "title": "highlightRelated", + "title": "Highlight Related", "properties": { "rust-analyzer.highlightRelated.yieldPoints.enable": { - "markdownDescription": "Enables highlighting of all break points for a loop or block context while the cursor is on any `async` or `await` keywords.", + "markdownDescription": "Highlight all break points for a loop or block context while the cursor is on any\n`async` or `await` keywords.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.actions.debug.enable": { - "markdownDescription": "Whether to show `Debug` action. Only applies when\n`#rust-analyzer.hover.actions.enable#` is set.", + "markdownDescription": "Show `Debug` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.actions.enable": { - "markdownDescription": "Whether to show HoverActions in Rust files.", + "markdownDescription": "Show HoverActions in Rust files.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.actions.gotoTypeDef.enable": { - "markdownDescription": "Whether to show `Go to Type Definition` action. Only applies when\n`#rust-analyzer.hover.actions.enable#` is set.", + "markdownDescription": "Show `Go to Type Definition` action. Only applies when\n`#rust-analyzer.hover.actions.enable#` is set.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.actions.implementations.enable": { - "markdownDescription": "Whether to show `Implementations` action. Only applies when\n`#rust-analyzer.hover.actions.enable#` is set.", + "markdownDescription": "Show `Implementations` action. Only applies when `#rust-analyzer.hover.actions.enable#`\nis set.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.actions.references.enable": { - "markdownDescription": "Whether to show `References` action. Only applies when\n`#rust-analyzer.hover.actions.enable#` is set.", + "markdownDescription": "Show `References` action. Only applies when `#rust-analyzer.hover.actions.enable#` is\nset.", "default": false, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.actions.run.enable": { - "markdownDescription": "Whether to show `Run` action. Only applies when\n`#rust-analyzer.hover.actions.enable#` is set.", + "markdownDescription": "Show `Run` action. Only applies when `#rust-analyzer.hover.actions.enable#` is set.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.actions.updateTest.enable": { - "markdownDescription": "Whether to show `Update Test` action. Only applies when\n`#rust-analyzer.hover.actions.enable#` and `#rust-analyzer.hover.actions.run.enable#` are set.", + "markdownDescription": "Show `Update Test` action. Only applies when `#rust-analyzer.hover.actions.enable#` and\n`#rust-analyzer.hover.actions.run.enable#` are set.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.documentation.enable": { - "markdownDescription": "Whether to show documentation on hover.", + "markdownDescription": "Show documentation on hover.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.documentation.keywords.enable": { - "markdownDescription": "Whether to show keyword hover popups. Only applies when\n`#rust-analyzer.hover.documentation.enable#` is set.", + "markdownDescription": "Show keyword hover popups. Only applies when\n`#rust-analyzer.hover.documentation.enable#` is set.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.dropGlue.enable": { - "markdownDescription": "Whether to show drop glue information on hover.", + "markdownDescription": "Show drop glue information on hover.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.links.enable": { "markdownDescription": "Use markdown syntax for links on hover.", @@ -1700,10 +1787,10 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.maxSubstitutionLength": { - "markdownDescription": "Whether to show what types are used as generic arguments in calls etc. on hover, and what is their max length to show such types, beyond it they will be shown with ellipsis.\n\nThis can take three values: `null` means \"unlimited\", the string `\"hide\"` means to not show generic substitutions at all, and a number means to limit them to X characters.\n\nThe default is 20 characters.", + "markdownDescription": "Show what types are used as generic arguments in calls etc. on hover, and limit the max\nlength to show such types, beyond which they will be shown with ellipsis.\n\nThis can take three values: `null` means \"unlimited\", the string `\"hide\"` means to not\nshow generic substitutions at all, and a number means to limit them to X characters.\n\nThe default is 20 characters.", "default": 20, "anyOf": [ { @@ -1723,7 +1810,7 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.memoryLayout.alignment": { "markdownDescription": "How to render the align information in a memory layout hover.", @@ -1750,17 +1837,17 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.memoryLayout.enable": { - "markdownDescription": "Whether to show memory layout data on hover.", + "markdownDescription": "Show memory layout data on hover.", "default": true, "type": "boolean" } } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.memoryLayout.niches": { "markdownDescription": "How to render the niche information in a memory layout hover.", @@ -1773,7 +1860,7 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.memoryLayout.offset": { "markdownDescription": "How to render the offset information in a memory layout hover.", @@ -1800,7 +1887,7 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.memoryLayout.padding": { "markdownDescription": "How to render the padding information in a memory layout hover.", @@ -1827,7 +1914,7 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.memoryLayout.size": { "markdownDescription": "How to render the size information in a memory layout hover.", @@ -1854,7 +1941,7 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.show.enumVariants": { "markdownDescription": "How many variants of an enum to display when hovering on. Show none if empty.", @@ -1868,10 +1955,10 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.show.fields": { - "markdownDescription": "How many fields of a struct, variant or union to display when hovering on. Show none if empty.", + "markdownDescription": "How many fields of a struct, variant or union to display when hovering on. Show none if\nempty.", "default": 5, "type": [ "null", @@ -1882,7 +1969,7 @@ } }, { - "title": "hover", + "title": "Hover", "properties": { "rust-analyzer.hover.show.traitAssocItems": { "markdownDescription": "How many associated items of a trait to display when hovering a trait.", @@ -1896,17 +1983,17 @@ } }, { - "title": "imports", + "title": "Imports", "properties": { "rust-analyzer.imports.granularity.enforce": { - "markdownDescription": "Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file.", + "markdownDescription": "Enforce the import granularity setting for all files. If set to false rust-analyzer will\ntry to keep import styles consistent per file.", "default": false, "type": "boolean" } } }, { - "title": "imports", + "title": "Imports", "properties": { "rust-analyzer.imports.granularity.group": { "markdownDescription": "How imports should be grouped into use statements.", @@ -1930,27 +2017,27 @@ } }, { - "title": "imports", + "title": "Imports", "properties": { "rust-analyzer.imports.group.enable": { - "markdownDescription": "Group inserted imports by the [following order](https://rust-analyzer.github.io/book/features.html#auto-import). Groups are separated by newlines.", + "markdownDescription": "Group inserted imports by the [following\norder](https://rust-analyzer.github.io/book/features.html#auto-import). Groups are\nseparated by newlines.", "default": true, "type": "boolean" } } }, { - "title": "imports", + "title": "Imports", "properties": { "rust-analyzer.imports.merge.glob": { - "markdownDescription": "Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.", + "markdownDescription": "Allow import insertion to merge new imports into single path glob imports like `use\nstd::fmt::*;`.", "default": true, "type": "boolean" } } }, { - "title": "imports", + "title": "Imports", "properties": { "rust-analyzer.imports.preferNoStd": { "markdownDescription": "Prefer to unconditionally use imports of the core and alloc crate, over the std crate.", @@ -1960,17 +2047,17 @@ } }, { - "title": "imports", + "title": "Imports", "properties": { "rust-analyzer.imports.preferPrelude": { - "markdownDescription": "Whether to prefer import paths containing a `prelude` module.", + "markdownDescription": "Prefer import paths containing a `prelude` module.", "default": false, "type": "boolean" } } }, { - "title": "imports", + "title": "Imports", "properties": { "rust-analyzer.imports.prefix": { "markdownDescription": "The path structure for newly inserted paths to use.", @@ -1990,47 +2077,47 @@ } }, { - "title": "imports", + "title": "Imports", "properties": { "rust-analyzer.imports.prefixExternPrelude": { - "markdownDescription": "Whether to prefix external (including std, core) crate imports with `::`. e.g. \"use ::std::io::Read;\".", + "markdownDescription": "Prefix external (including std, core) crate imports with `::`.\n\nE.g. `use ::std::io::Read;`.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.bindingModeHints.enable": { - "markdownDescription": "Whether to show inlay type hints for binding modes.", + "markdownDescription": "Show inlay type hints for binding modes.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.chainingHints.enable": { - "markdownDescription": "Whether to show inlay type hints for method chains.", + "markdownDescription": "Show inlay type hints for method chains.", "default": true, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.closingBraceHints.enable": { - "markdownDescription": "Whether to show inlay hints after a closing `}` to indicate what item it belongs to.", + "markdownDescription": "Show inlay hints after a closing `}` to indicate what item it belongs to.", "default": true, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.closingBraceHints.minLines": { "markdownDescription": "Minimum number of lines required before the `}` until the hint is shown (set to 0 or 1\nto always show them).", @@ -2041,20 +2128,20 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.closureCaptureHints.enable": { - "markdownDescription": "Whether to show inlay hints for closure captures.", + "markdownDescription": "Show inlay hints for closure captures.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.closureReturnTypeHints.enable": { - "markdownDescription": "Whether to show inlay type hints for return types of closures.", + "markdownDescription": "Show inlay type hints for return types of closures.", "default": "never", "type": "string", "enum": [ @@ -2071,7 +2158,7 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.closureStyle": { "markdownDescription": "Closure notation in type and chaining inlay hints.", @@ -2093,10 +2180,10 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.discriminantHints.enable": { - "markdownDescription": "Whether to show enum variant discriminant hints.", + "markdownDescription": "Show enum variant discriminant hints.", "default": "never", "type": "string", "enum": [ @@ -2113,10 +2200,10 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.expressionAdjustmentHints.enable": { - "markdownDescription": "Whether to show inlay hints for type adjustments.", + "markdownDescription": "Show inlay hints for type adjustments.", "default": "never", "type": "string", "enum": [ @@ -2133,20 +2220,20 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.expressionAdjustmentHints.hideOutsideUnsafe": { - "markdownDescription": "Whether to hide inlay hints for type adjustments outside of `unsafe` blocks.", + "markdownDescription": "Hide inlay hints for type adjustments outside of `unsafe` blocks.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.expressionAdjustmentHints.mode": { - "markdownDescription": "Whether to show inlay hints as postfix ops (`.*` instead of `*`, etc).", + "markdownDescription": "Show inlay hints as postfix ops (`.*` instead of `*`, etc).", "default": "prefix", "type": "string", "enum": [ @@ -2165,60 +2252,60 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.genericParameterHints.const.enable": { - "markdownDescription": "Whether to show const generic parameter name inlay hints.", + "markdownDescription": "Show const generic parameter name inlay hints.", "default": true, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.genericParameterHints.lifetime.enable": { - "markdownDescription": "Whether to show generic lifetime parameter name inlay hints.", + "markdownDescription": "Show generic lifetime parameter name inlay hints.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.genericParameterHints.type.enable": { - "markdownDescription": "Whether to show generic type parameter name inlay hints.", + "markdownDescription": "Show generic type parameter name inlay hints.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.implicitDrops.enable": { - "markdownDescription": "Whether to show implicit drop hints.", + "markdownDescription": "Show implicit drop hints.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.implicitSizedBoundHints.enable": { - "markdownDescription": "Whether to show inlay hints for the implied type parameter `Sized` bound.", + "markdownDescription": "Show inlay hints for the implied type parameter `Sized` bound.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.lifetimeElisionHints.enable": { - "markdownDescription": "Whether to show inlay type hints for elided lifetimes in function signatures.", + "markdownDescription": "Show inlay type hints for elided lifetimes in function signatures.", "default": "never", "type": "string", "enum": [ @@ -2235,17 +2322,17 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.lifetimeElisionHints.useParameterNames": { - "markdownDescription": "Whether to prefer using parameter names as the name for elided lifetime hints if possible.", + "markdownDescription": "Prefer using parameter names as the name for elided lifetime hints if possible.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.maxLength": { "markdownDescription": "Maximum length for inlay hints. Set to null to have an unlimited length.", @@ -2259,30 +2346,30 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.parameterHints.enable": { - "markdownDescription": "Whether to show function parameter name inlay hints at the call\nsite.", + "markdownDescription": "Show function parameter name inlay hints at the call site.", "default": true, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.rangeExclusiveHints.enable": { - "markdownDescription": "Whether to show exclusive range inlay hints.", + "markdownDescription": "Show exclusive range inlay hints.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.reborrowHints.enable": { - "markdownDescription": "Whether to show inlay hints for compiler inserted reborrows.\nThis setting is deprecated in favor of #rust-analyzer.inlayHints.expressionAdjustmentHints.enable#.", + "markdownDescription": "Show inlay hints for compiler inserted reborrows.\n\nThis setting is deprecated in favor of\n#rust-analyzer.inlayHints.expressionAdjustmentHints.enable#.", "default": "never", "type": "string", "enum": [ @@ -2299,7 +2386,7 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.renderColons": { "markdownDescription": "Whether to render leading colons for type hints, and trailing colons for parameter hints.", @@ -2309,57 +2396,57 @@ } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.typeHints.enable": { - "markdownDescription": "Whether to show inlay type hints for variables.", + "markdownDescription": "Show inlay type hints for variables.", "default": true, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.typeHints.hideClosureInitialization": { - "markdownDescription": "Whether to hide inlay type hints for `let` statements that initialize to a closure.\nOnly applies to closures with blocks, same as `#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`.", + "markdownDescription": "Hide inlay type hints for `let` statements that initialize to a closure.\n\nOnly applies to closures with blocks, same as\n`#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.typeHints.hideClosureParameter": { - "markdownDescription": "Whether to hide inlay parameter type hints for closures.", + "markdownDescription": "Hide inlay parameter type hints for closures.", "default": false, "type": "boolean" } } }, { - "title": "inlayHints", + "title": "Inlay Hints", "properties": { "rust-analyzer.inlayHints.typeHints.hideNamedConstructor": { - "markdownDescription": "Whether to hide inlay type hints for constructors.", + "markdownDescription": "Hide inlay type hints for constructors.", "default": false, "type": "boolean" } } }, { - "title": "interpret", + "title": "Interpret", "properties": { "rust-analyzer.interpret.tests": { - "markdownDescription": "Enables the experimental support for interpreting tests.", + "markdownDescription": "Enable the experimental support for interpreting tests.", "default": false, "type": "boolean" } } }, { - "title": "joinLines", + "title": "Join Lines", "properties": { "rust-analyzer.joinLines.joinAssignments": { "markdownDescription": "Join lines merges consecutive declaration and initialization of an assignment.", @@ -2369,7 +2456,7 @@ } }, { - "title": "joinLines", + "title": "Join Lines", "properties": { "rust-analyzer.joinLines.joinElseIf": { "markdownDescription": "Join lines inserts else between consecutive ifs.", @@ -2379,7 +2466,7 @@ } }, { - "title": "joinLines", + "title": "Join Lines", "properties": { "rust-analyzer.joinLines.removeTrailingComma": { "markdownDescription": "Join lines removes trailing commas.", @@ -2389,7 +2476,7 @@ } }, { - "title": "joinLines", + "title": "Join Lines", "properties": { "rust-analyzer.joinLines.unwrapTrivialBlock": { "markdownDescription": "Join lines unwraps trivial blocks.", @@ -2399,37 +2486,37 @@ } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.debug.enable": { - "markdownDescription": "Whether to show `Debug` lens. Only applies when\n`#rust-analyzer.lens.enable#` is set.", + "markdownDescription": "Show `Debug` lens. Only applies when `#rust-analyzer.lens.enable#` is set.", "default": true, "type": "boolean" } } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.enable": { - "markdownDescription": "Whether to show CodeLens in Rust files.", + "markdownDescription": "Show CodeLens in Rust files.", "default": true, "type": "boolean" } } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.implementations.enable": { - "markdownDescription": "Whether to show `Implementations` lens. Only applies when\n`#rust-analyzer.lens.enable#` is set.", + "markdownDescription": "Show `Implementations` lens. Only applies when `#rust-analyzer.lens.enable#` is set.", "default": true, "type": "boolean" } } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.location": { "markdownDescription": "Where to render annotations.", @@ -2447,70 +2534,70 @@ } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.references.adt.enable": { - "markdownDescription": "Whether to show `References` lens for Struct, Enum, and Union.\nOnly applies when `#rust-analyzer.lens.enable#` is set.", + "markdownDescription": "Show `References` lens for Struct, Enum, and Union. Only applies when\n`#rust-analyzer.lens.enable#` is set.", "default": false, "type": "boolean" } } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.references.enumVariant.enable": { - "markdownDescription": "Whether to show `References` lens for Enum Variants.\nOnly applies when `#rust-analyzer.lens.enable#` is set.", + "markdownDescription": "Show `References` lens for Enum Variants. Only applies when\n`#rust-analyzer.lens.enable#` is set.", "default": false, "type": "boolean" } } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.references.method.enable": { - "markdownDescription": "Whether to show `Method References` lens. Only applies when\n`#rust-analyzer.lens.enable#` is set.", + "markdownDescription": "Show `Method References` lens. Only applies when `#rust-analyzer.lens.enable#` is set.", "default": false, "type": "boolean" } } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.references.trait.enable": { - "markdownDescription": "Whether to show `References` lens for Trait.\nOnly applies when `#rust-analyzer.lens.enable#` is set.", + "markdownDescription": "Show `References` lens for Trait. Only applies when `#rust-analyzer.lens.enable#` is\nset.", "default": false, "type": "boolean" } } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.run.enable": { - "markdownDescription": "Whether to show `Run` lens. Only applies when\n`#rust-analyzer.lens.enable#` is set.", + "markdownDescription": "Show `Run` lens. Only applies when `#rust-analyzer.lens.enable#` is set.", "default": true, "type": "boolean" } } }, { - "title": "lens", + "title": "Lens", "properties": { "rust-analyzer.lens.updateTest.enable": { - "markdownDescription": "Whether to show `Update Test` lens. Only applies when\n`#rust-analyzer.lens.enable#` and `#rust-analyzer.lens.run.enable#` are set.", + "markdownDescription": "Show `Update Test` lens. Only applies when `#rust-analyzer.lens.enable#` and\n`#rust-analyzer.lens.run.enable#` are set.", "default": true, "type": "boolean" } } }, { - "title": "general", + "title": "rust-analyzer", "properties": { "rust-analyzer.linkedProjects": { - "markdownDescription": "Disable project auto-discovery in favor of explicitly specified set\nof projects.\n\nElements must be paths pointing to `Cargo.toml`,\n`rust-project.json`, `.rs` files (which will be treated as standalone files) or JSON\nobjects in `rust-project.json` format.", + "markdownDescription": "Disable project auto-discovery in favor of explicitly specified set of projects.\n\nElements must be paths pointing to `Cargo.toml`, `rust-project.json`, `.rs` files (which\nwill be treated as standalone files) or JSON objects in `rust-project.json` format.", "default": [], "type": "array", "items": { @@ -2523,7 +2610,7 @@ } }, { - "title": "lru", + "title": "Lru", "properties": { "rust-analyzer.lru.capacity": { "markdownDescription": "Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.", @@ -2538,30 +2625,30 @@ } }, { - "title": "lru", + "title": "Lru", "properties": { "rust-analyzer.lru.query.capacities": { - "markdownDescription": "Sets the LRU capacity of the specified queries.", + "markdownDescription": "The LRU capacity of the specified queries.", "default": {}, "type": "object" } } }, { - "title": "notifications", + "title": "Notifications", "properties": { "rust-analyzer.notifications.cargoTomlNotFound": { - "markdownDescription": "Whether to show `can't find Cargo.toml` error message.", + "markdownDescription": "Show `can't find Cargo.toml` error message.", "default": true, "type": "boolean" } } }, { - "title": "general", + "title": "rust-analyzer", "properties": { "rust-analyzer.numThreads": { - "markdownDescription": "How many worker threads in the main loop. The default `null` means to pick automatically.", + "markdownDescription": "The number of worker threads in the main loop. The default `null` means to pick\nautomatically.", "default": null, "anyOf": [ { @@ -2588,7 +2675,7 @@ } }, { - "title": "procMacro", + "title": "Proc Macro", "properties": { "rust-analyzer.procMacro.attributes.enable": { "markdownDescription": "Expand attribute macros. Requires `#rust-analyzer.procMacro.enable#` to be set.", @@ -2598,7 +2685,7 @@ } }, { - "title": "procMacro", + "title": "Proc Macro", "properties": { "rust-analyzer.procMacro.enable": { "markdownDescription": "Enable support for procedural macros, implies `#rust-analyzer.cargo.buildScripts.enable#`.", @@ -2608,7 +2695,7 @@ } }, { - "title": "procMacro", + "title": "Proc Macro", "properties": { "rust-analyzer.procMacro.ignored": { "markdownDescription": "These proc-macros will be ignored when trying to expand them.\n\nThis config takes a map of crate names with the exported proc-macro names to ignore as values.", @@ -2618,7 +2705,7 @@ } }, { - "title": "procMacro", + "title": "Proc Macro", "properties": { "rust-analyzer.procMacro.server": { "markdownDescription": "Internal config, path to proc-macro server executable.", @@ -2631,7 +2718,7 @@ } }, { - "title": "references", + "title": "References", "properties": { "rust-analyzer.references.excludeImports": { "markdownDescription": "Exclude imports from find-all-references.", @@ -2641,7 +2728,7 @@ } }, { - "title": "references", + "title": "References", "properties": { "rust-analyzer.references.excludeTests": { "markdownDescription": "Exclude tests from find-all-references and call-hierarchy.", @@ -2651,7 +2738,7 @@ } }, { - "title": "runnables", + "title": "Runnables", "properties": { "rust-analyzer.runnables.command": { "markdownDescription": "Command to be executed instead of 'cargo' for runnables.", @@ -2664,7 +2751,7 @@ } }, { - "title": "runnables", + "title": "Runnables", "properties": { "rust-analyzer.runnables.extraArgs": { "markdownDescription": "Additional arguments to be passed to cargo for runnables such as\ntests or binaries. For example, it may be `--release`.", @@ -2677,7 +2764,7 @@ } }, { - "title": "runnables", + "title": "Runnables", "properties": { "rust-analyzer.runnables.extraTestBinaryArgs": { "markdownDescription": "Additional arguments to be passed through Cargo to launched tests, benchmarks, or\ndoc-tests.\n\nUnless the launched target uses a\n[custom test harness](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-harness-field),\nthey will end up being interpreted as options to\n[`rustc`’s built-in test harness (“libtest”)](https://doc.rust-lang.org/rustc/tests/index.html#cli-arguments).", @@ -2692,7 +2779,7 @@ } }, { - "title": "rustc", + "title": "Rustc", "properties": { "rust-analyzer.rustc.source": { "markdownDescription": "Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private\nprojects, or \"discover\" to try to automatically find it if the `rustc-dev` component\nis installed.\n\nAny project which uses rust-analyzer with the rustcPrivate\ncrates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.\n\nThis option does not take effect until rust-analyzer is restarted.", @@ -2705,7 +2792,7 @@ } }, { - "title": "rustfmt", + "title": "Rustfmt", "properties": { "rust-analyzer.rustfmt.extraArgs": { "markdownDescription": "Additional arguments to `rustfmt`.", @@ -2718,7 +2805,7 @@ } }, { - "title": "rustfmt", + "title": "Rustfmt", "properties": { "rust-analyzer.rustfmt.overrideCommand": { "markdownDescription": "Advanced option, fully override the command rust-analyzer uses for\nformatting. This should be the equivalent of `rustfmt` here, and\nnot that of `cargo fmt`. The file contents will be passed on the\nstandard input and the formatted result will be read from the\nstandard output.", @@ -2734,7 +2821,7 @@ } }, { - "title": "rustfmt", + "title": "Rustfmt", "properties": { "rust-analyzer.rustfmt.rangeFormatting.enable": { "markdownDescription": "Enables the use of rustfmt's unstable range formatting command for the\n`textDocument/rangeFormatting` request. The rustfmt option is unstable and only\navailable on a nightly build.", @@ -2744,7 +2831,7 @@ } }, { - "title": "semanticHighlighting", + "title": "Semantic Highlighting", "properties": { "rust-analyzer.semanticHighlighting.doc.comment.inject.enable": { "markdownDescription": "Inject additional highlighting into doc comments.\n\nWhen enabled, rust-analyzer will highlight rust source in doc comments as well as intra\ndoc links.", @@ -2754,17 +2841,17 @@ } }, { - "title": "semanticHighlighting", + "title": "Semantic Highlighting", "properties": { "rust-analyzer.semanticHighlighting.nonStandardTokens": { - "markdownDescription": "Whether the server is allowed to emit non-standard tokens and modifiers.", + "markdownDescription": "Emit non-standard tokens and modifiers\n\nWhen enabled, rust-analyzer will emit tokens and modifiers that are not part of the\nstandard set of semantic tokens.", "default": true, "type": "boolean" } } }, { - "title": "semanticHighlighting", + "title": "Semantic Highlighting", "properties": { "rust-analyzer.semanticHighlighting.operator.enable": { "markdownDescription": "Use semantic tokens for operators.\n\nWhen disabled, rust-analyzer will emit semantic tokens only for operator tokens when\nthey are tagged with modifiers.", @@ -2774,7 +2861,7 @@ } }, { - "title": "semanticHighlighting", + "title": "Semantic Highlighting", "properties": { "rust-analyzer.semanticHighlighting.operator.specialization.enable": { "markdownDescription": "Use specialized semantic tokens for operators.\n\nWhen enabled, rust-analyzer will emit special token types for operator tokens instead\nof the generic `operator` token type.", @@ -2784,7 +2871,7 @@ } }, { - "title": "semanticHighlighting", + "title": "Semantic Highlighting", "properties": { "rust-analyzer.semanticHighlighting.punctuation.enable": { "markdownDescription": "Use semantic tokens for punctuation.\n\nWhen disabled, rust-analyzer will emit semantic tokens only for punctuation tokens when\nthey are tagged with modifiers or have a special role.", @@ -2794,7 +2881,7 @@ } }, { - "title": "semanticHighlighting", + "title": "Semantic Highlighting", "properties": { "rust-analyzer.semanticHighlighting.punctuation.separate.macro.bang": { "markdownDescription": "When enabled, rust-analyzer will emit a punctuation semantic token for the `!` of macro\ncalls.", @@ -2804,7 +2891,7 @@ } }, { - "title": "semanticHighlighting", + "title": "Semantic Highlighting", "properties": { "rust-analyzer.semanticHighlighting.punctuation.specialization.enable": { "markdownDescription": "Use specialized semantic tokens for punctuation.\n\nWhen enabled, rust-analyzer will emit special token types for punctuation tokens instead\nof the generic `punctuation` token type.", @@ -2814,7 +2901,7 @@ } }, { - "title": "semanticHighlighting", + "title": "Semantic Highlighting", "properties": { "rust-analyzer.semanticHighlighting.strings.enable": { "markdownDescription": "Use semantic tokens for strings.\n\nIn some editors (e.g. vscode) semantic tokens override other highlighting grammars.\nBy disabling semantic tokens for strings, other grammars can be used to highlight\ntheir contents.", @@ -2824,7 +2911,7 @@ } }, { - "title": "signatureInfo", + "title": "Signature Info", "properties": { "rust-analyzer.signatureInfo.detail": { "markdownDescription": "Show full signature of the callable. Only shows parameters if disabled.", @@ -2842,7 +2929,7 @@ } }, { - "title": "signatureInfo", + "title": "Signature Info", "properties": { "rust-analyzer.signatureInfo.documentation.enable": { "markdownDescription": "Show documentation.", @@ -2852,10 +2939,10 @@ } }, { - "title": "typing", + "title": "Typing", "properties": { "rust-analyzer.typing.triggerChars": { - "markdownDescription": "Specify the characters allowed to invoke special on typing triggers.\n- typing `=` after `let` tries to smartly add `;` if `=` is followed by an existing expression\n- typing `=` between two expressions adds `;` when in statement position\n- typing `=` to turn an assignment into an equality comparison removes `;` when in expression position\n- typing `.` in a chain method call auto-indents\n- typing `{` or `(` in front of an expression inserts a closing `}` or `)` after the expression\n- typing `{` in a use item adds a closing `}` in the right place\n- typing `>` to complete a return type `->` will insert a whitespace after it\n- typing `<` in a path or type position inserts a closing `>` after the path or type.", + "markdownDescription": "Specify the characters allowed to invoke special on typing triggers.\n\n- typing `=` after `let` tries to smartly add `;` if `=` is followed by an existing\n expression\n- typing `=` between two expressions adds `;` when in statement position\n- typing `=` to turn an assignment into an equality comparison removes `;` when in\n expression position\n- typing `.` in a chain method call auto-indents\n- typing `{` or `(` in front of an expression inserts a closing `}` or `)` after the\n expression\n- typing `{` in a use item adds a closing `}` in the right place\n- typing `>` to complete a return type `->` will insert a whitespace after it\n- typing `<` in a path or type position inserts a closing `>` after the path or type.", "default": "=.", "type": [ "null", @@ -2865,7 +2952,7 @@ } }, { - "title": "vfs", + "title": "Vfs", "properties": { "rust-analyzer.vfs.extraIncludes": { "markdownDescription": "Additional paths to include in the VFS. Generally for code that is\ngenerated or otherwise managed by a build system outside of Cargo,\nthough Cargo might be the eventual consumer.", @@ -2878,10 +2965,10 @@ } }, { - "title": "workspace", + "title": "Workspace", "properties": { "rust-analyzer.workspace.discoverConfig": { - "markdownDescription": "Enables automatic discovery of projects using [`DiscoverWorkspaceConfig::command`].\n\n[`DiscoverWorkspaceConfig`] also requires setting `progress_label` and `files_to_watch`.\n`progress_label` is used for the title in progress indicators, whereas `files_to_watch`\nis used to determine which build system-specific files should be watched in order to\nreload rust-analyzer.\n\nBelow is an example of a valid configuration:\n```json\n\"rust-analyzer.workspace.discoverConfig\": {\n \"command\": [\n \"rust-project\",\n \"develop-json\"\n ],\n \"progressLabel\": \"rust-analyzer\",\n \"filesToWatch\": [\n \"BUCK\"\n ]\n}\n```\n\n## On `DiscoverWorkspaceConfig::command`\n\n**Warning**: This format is provisional and subject to change.\n\n[`DiscoverWorkspaceConfig::command`] *must* return a JSON object\ncorresponding to `DiscoverProjectData::Finished`:\n\n```norun\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(tag = \"kind\")]\n#[serde(rename_all = \"snake_case\")]\nenum DiscoverProjectData {\n Finished { buildfile: Utf8PathBuf, project: ProjectJsonData },\n Error { error: String, source: Option },\n Progress { message: String },\n}\n```\n\nAs JSON, `DiscoverProjectData::Finished` is:\n\n```json\n{\n // the internally-tagged representation of the enum.\n \"kind\": \"finished\",\n // the file used by a non-Cargo build system to define\n // a package or target.\n \"buildfile\": \"rust-analyzer/BUILD\",\n // the contents of a rust-project.json, elided for brevity\n \"project\": {\n \"sysroot\": \"foo\",\n \"crates\": []\n }\n}\n```\n\nIt is encouraged, but not required, to use the other variants on\n`DiscoverProjectData` to provide a more polished end-user experience.\n\n`DiscoverWorkspaceConfig::command` may *optionally* include an `{arg}`,\nwhich will be substituted with the JSON-serialized form of the following\nenum:\n\n```norun\n#[derive(PartialEq, Clone, Debug, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub enum DiscoverArgument {\n Path(AbsPathBuf),\n Buildfile(AbsPathBuf),\n}\n```\n\nThe JSON representation of `DiscoverArgument::Path` is:\n\n```json\n{\n \"path\": \"src/main.rs\"\n}\n```\n\nSimilarly, the JSON representation of `DiscoverArgument::Buildfile` is:\n\n```json\n{\n \"buildfile\": \"BUILD\"\n}\n```\n\n`DiscoverArgument::Path` is used to find and generate a `rust-project.json`,\nand therefore, a workspace, whereas `DiscoverArgument::buildfile` is used to\nto update an existing workspace. As a reference for implementors,\nbuck2's `rust-project` will likely be useful:\nhttps://github.com/facebook/buck2/tree/main/integrations/rust-project.", + "markdownDescription": "Enables automatic discovery of projects using [`DiscoverWorkspaceConfig::command`].\n\n[`DiscoverWorkspaceConfig`] also requires setting `progress_label` and `files_to_watch`.\n`progress_label` is used for the title in progress indicators, whereas `files_to_watch`\nis used to determine which build system-specific files should be watched in order to\nreload rust-analyzer.\n\nBelow is an example of a valid configuration:\n```json\n\"rust-analyzer.workspace.discoverConfig\": {\n \"command\": [\n \"rust-project\",\n \"develop-json\"\n ],\n \"progressLabel\": \"rust-analyzer\",\n \"filesToWatch\": [\n \"BUCK\"\n ]\n}\n```\n\n## On `DiscoverWorkspaceConfig::command`\n\n**Warning**: This format is provisional and subject to change.\n\n[`DiscoverWorkspaceConfig::command`] *must* return a JSON object corresponding to\n`DiscoverProjectData::Finished`:\n\n```norun\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(tag = \"kind\")]\n#[serde(rename_all = \"snake_case\")]\nenum DiscoverProjectData {\n Finished { buildfile: Utf8PathBuf, project: ProjectJsonData },\n Error { error: String, source: Option },\n Progress { message: String },\n}\n```\n\nAs JSON, `DiscoverProjectData::Finished` is:\n\n```json\n{\n // the internally-tagged representation of the enum.\n \"kind\": \"finished\",\n // the file used by a non-Cargo build system to define\n // a package or target.\n \"buildfile\": \"rust-analyzer/BUILD\",\n // the contents of a rust-project.json, elided for brevity\n \"project\": {\n \"sysroot\": \"foo\",\n \"crates\": []\n }\n}\n```\n\nIt is encouraged, but not required, to use the other variants on `DiscoverProjectData`\nto provide a more polished end-user experience.\n\n`DiscoverWorkspaceConfig::command` may *optionally* include an `{arg}`, which will be\nsubstituted with the JSON-serialized form of the following enum:\n\n```norun\n#[derive(PartialEq, Clone, Debug, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub enum DiscoverArgument {\n Path(AbsPathBuf),\n Buildfile(AbsPathBuf),\n}\n```\n\nThe JSON representation of `DiscoverArgument::Path` is:\n\n```json\n{\n \"path\": \"src/main.rs\"\n}\n```\n\nSimilarly, the JSON representation of `DiscoverArgument::Buildfile` is:\n\n```json\n{\n \"buildfile\": \"BUILD\"\n}\n```\n\n`DiscoverArgument::Path` is used to find and generate a `rust-project.json`, and\ntherefore, a workspace, whereas `DiscoverArgument::buildfile` is used to to update an\nexisting workspace. As a reference for implementors, buck2's `rust-project` will likely\nbe useful: https://github.com/facebook/buck2/tree/main/integrations/rust-project.", "default": null, "anyOf": [ { @@ -2912,7 +2999,7 @@ } }, { - "title": "workspace", + "title": "Workspace", "properties": { "rust-analyzer.workspace.symbol.search.excludeImports": { "markdownDescription": "Exclude all imports from workspace symbol search.\n\nIn addition to regular imports (which are always excluded),\nthis option removes public imports (better known as re-exports)\nand removes imports that rename the imported symbol.", @@ -2922,7 +3009,7 @@ } }, { - "title": "workspace", + "title": "Workspace", "properties": { "rust-analyzer.workspace.symbol.search.kind": { "markdownDescription": "Workspace symbol search kind.", @@ -2940,7 +3027,7 @@ } }, { - "title": "workspace", + "title": "Workspace", "properties": { "rust-analyzer.workspace.symbol.search.limit": { "markdownDescription": "Limits the number of items returned from a workspace symbol search (Defaults to 128).\nSome clients like vs-code issue new searches on result filtering and don't require all results to be returned in the initial search.\nOther clients requires all results upfront and might require a higher limit.", @@ -2951,7 +3038,7 @@ } }, { - "title": "workspace", + "title": "Workspace", "properties": { "rust-analyzer.workspace.symbol.search.scope": { "markdownDescription": "Workspace symbol search scope.", From 0e3d408c29c7e1b54ba514dfb728eb762719b15b Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 3 Jul 2025 14:24:58 +0000 Subject: [PATCH 0040/1134] Remove LtoModuleCodegen Most uses of it either contain a fat or thin lto module. Only WorkItem::LTO could contain both, but splitting that enum variant doesn't complicate things much. --- src/back/lto.rs | 15 +++++++-------- src/lib.rs | 6 +++--- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/back/lto.rs b/src/back/lto.rs index 10fce860b777..e554dd2500bd 100644 --- a/src/back/lto.rs +++ b/src/back/lto.rs @@ -24,7 +24,7 @@ use std::sync::Arc; use gccjit::{Context, OutputKind}; use object::read::archive::ArchiveFile; -use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule, ThinShared}; +use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared}; use rustc_codegen_ssa::back::symbol_export; use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput}; use rustc_codegen_ssa::traits::*; @@ -176,7 +176,7 @@ pub(crate) fn run_fat( cgcx: &CodegenContext, modules: Vec>, cached_modules: Vec<(SerializedModule, WorkProduct)>, -) -> Result, FatalError> { +) -> Result, FatalError> { let dcx = cgcx.create_dcx(); let dcx = dcx.handle(); let lto_data = prepare_lto(cgcx, dcx)?; @@ -201,7 +201,7 @@ fn fat_lto( mut serialized_modules: Vec<(SerializedModule, CString)>, tmp_path: TempDir, //symbols_below_threshold: &[String], -) -> Result, FatalError> { +) -> Result, FatalError> { let _timer = cgcx.prof.generic_activity("GCC_fat_lto_build_monolithic_module"); info!("going for a fat lto"); @@ -334,7 +334,7 @@ fn fat_lto( // of now. module.module_llvm.temp_dir = Some(tmp_path); - Ok(LtoModuleCodegen::Fat(module)) + Ok(module) } pub struct ModuleBuffer(PathBuf); @@ -358,7 +358,7 @@ pub(crate) fn run_thin( cgcx: &CodegenContext, modules: Vec<(String, ThinBuffer)>, cached_modules: Vec<(SerializedModule, WorkProduct)>, -) -> Result<(Vec>, Vec), FatalError> { +) -> Result<(Vec>, Vec), FatalError> { let dcx = cgcx.create_dcx(); let dcx = dcx.handle(); let lto_data = prepare_lto(cgcx, dcx)?; @@ -427,7 +427,7 @@ fn thin_lto( tmp_path: TempDir, cached_modules: Vec<(SerializedModule, WorkProduct)>, //_symbols_below_threshold: &[String], -) -> Result<(Vec>, Vec), FatalError> { +) -> Result<(Vec>, Vec), FatalError> { let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis"); info!("going for that thin, thin LTO"); @@ -573,8 +573,7 @@ fn thin_lto( }*/ info!(" - {}: re-compiled", module_name); - opt_jobs - .push(LtoModuleCodegen::Thin(ThinModule { shared: shared.clone(), idx: module_index })); + opt_jobs.push(ThinModule { shared: shared.clone(), idx: module_index }); } // Save the current ThinLTO import information for the next compilation diff --git a/src/lib.rs b/src/lib.rs index a912678ef2a1..a151a0ab7553 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -97,7 +97,7 @@ use gccjit::{CType, Context, OptimizationLevel}; use gccjit::{TargetInfo, Version}; use rustc_ast::expand::allocator::AllocatorKind; use rustc_ast::expand::autodiff_attrs::AutoDiffItem; -use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule}; +use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule}; use rustc_codegen_ssa::back::write::{ CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryFn, }; @@ -361,7 +361,7 @@ impl WriteBackendMethods for GccCodegenBackend { cgcx: &CodegenContext, modules: Vec>, cached_modules: Vec<(SerializedModule, WorkProduct)>, - ) -> Result, FatalError> { + ) -> Result, FatalError> { back::lto::run_fat(cgcx, modules, cached_modules) } @@ -369,7 +369,7 @@ impl WriteBackendMethods for GccCodegenBackend { cgcx: &CodegenContext, modules: Vec<(String, Self::ThinBuffer)>, cached_modules: Vec<(SerializedModule, WorkProduct)>, - ) -> Result<(Vec>, Vec), FatalError> { + ) -> Result<(Vec>, Vec), FatalError> { back::lto::run_thin(cgcx, modules, cached_modules) } From d9f9bcf18f7b8c997daad39ee726c50f1316fa60 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 3 Jul 2025 14:43:09 +0000 Subject: [PATCH 0041/1134] Move dcx creation into WriteBackendMethods::codegen --- src/back/write.rs | 4 +++- src/lib.rs | 3 +-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/back/write.rs b/src/back/write.rs index d03d063bdace..113abe70805b 100644 --- a/src/back/write.rs +++ b/src/back/write.rs @@ -16,10 +16,12 @@ use crate::{GccCodegenBackend, GccContext}; pub(crate) fn codegen( cgcx: &CodegenContext, - dcx: DiagCtxtHandle<'_>, module: ModuleCodegen, config: &ModuleConfig, ) -> Result { + let dcx = cgcx.create_dcx(); + let dcx = dcx.handle(); + let _timer = cgcx.prof.generic_activity_with_arg("GCC_module_codegen", &*module.name); { let context = &module.module_llvm.context; diff --git a/src/lib.rs b/src/lib.rs index a151a0ab7553..34452bdd2005 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -408,11 +408,10 @@ impl WriteBackendMethods for GccCodegenBackend { fn codegen( cgcx: &CodegenContext, - dcx: DiagCtxtHandle<'_>, module: ModuleCodegen, config: &ModuleConfig, ) -> Result { - back::write::codegen(cgcx, dcx, module, config) + back::write::codegen(cgcx, module, config) } fn prepare_thin( From 937044097b8fc23b387ab58fc233109551e8536f Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Thu, 3 Jul 2025 23:43:02 +0800 Subject: [PATCH 0042/1134] stabilize `const_array_each_ref` --- library/core/src/array/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index 5a46c04527b9..1739da105d1d 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -618,11 +618,11 @@ impl [T; N] { /// assert_eq!(strings.len(), 3); /// ``` #[stable(feature = "array_methods", since = "1.77.0")] - #[rustc_const_unstable(feature = "const_array_each_ref", issue = "133289")] + #[rustc_const_stable(feature = "const_array_each_ref", since = "CURRENT_RUSTC_VERSION")] pub const fn each_ref(&self) -> [&T; N] { let mut buf = [null::(); N]; - // FIXME(const-hack): We would like to simply use iterators for this (as in the original implementation), but this is not allowed in constant expressions. + // FIXME(const_trait_impl): We would like to simply use iterators for this (as in the original implementation), but this is not allowed in constant expressions. let mut i = 0; while i < N { buf[i] = &raw const self[i]; @@ -649,11 +649,11 @@ impl [T; N] { /// assert_eq!(floats, [0.0, 2.7, -1.0]); /// ``` #[stable(feature = "array_methods", since = "1.77.0")] - #[rustc_const_unstable(feature = "const_array_each_ref", issue = "133289")] + #[rustc_const_stable(feature = "const_array_each_ref", since = "CURRENT_RUSTC_VERSION")] pub const fn each_mut(&mut self) -> [&mut T; N] { let mut buf = [null_mut::(); N]; - // FIXME(const-hack): We would like to simply use iterators for this (as in the original implementation), but this is not allowed in constant expressions. + // FIXME(const_trait_impl): We would like to simply use iterators for this (as in the original implementation), but this is not allowed in constant expressions. let mut i = 0; while i < N { buf[i] = &raw mut self[i]; From 9404a1192421c29828167eb6962f5099793619d1 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 3 Jul 2025 16:09:10 +0000 Subject: [PATCH 0043/1134] Remove unused config param from WriteBackendMethods::autodiff --- src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 34452bdd2005..8e63ebc84940 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -437,7 +437,6 @@ impl WriteBackendMethods for GccCodegenBackend { _cgcx: &CodegenContext, _module: &ModuleCodegen, _diff_functions: Vec, - _config: &ModuleConfig, ) -> Result<(), FatalError> { unimplemented!() } From bf4daef80cab63ba6d2a0889927e9fce4828c6f9 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 3 Jul 2025 16:22:32 +0000 Subject: [PATCH 0044/1134] Merge run_fat_lto, optimize_fat and autodiff into run_and_optimize_fat_lto --- src/lib.rs | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 8e63ebc84940..75c36fffec98 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -357,11 +357,16 @@ impl WriteBackendMethods for GccCodegenBackend { type ThinData = ThinData; type ThinBuffer = ThinBuffer; - fn run_fat_lto( + fn run_and_optimize_fat_lto( cgcx: &CodegenContext, modules: Vec>, cached_modules: Vec<(SerializedModule, WorkProduct)>, + diff_fncs: Vec, ) -> Result, FatalError> { + if !diff_fncs.is_empty() { + unimplemented!(); + } + back::lto::run_fat(cgcx, modules, cached_modules) } @@ -391,14 +396,6 @@ impl WriteBackendMethods for GccCodegenBackend { Ok(()) } - fn optimize_fat( - _cgcx: &CodegenContext, - _module: &mut ModuleCodegen, - ) -> Result<(), FatalError> { - // TODO(antoyo) - Ok(()) - } - fn optimize_thin( cgcx: &CodegenContext, thin: ThinModule, @@ -432,14 +429,6 @@ impl WriteBackendMethods for GccCodegenBackend { ) -> Result, FatalError> { back::write::link(cgcx, dcx, modules) } - - fn autodiff( - _cgcx: &CodegenContext, - _module: &ModuleCodegen, - _diff_functions: Vec, - ) -> Result<(), FatalError> { - unimplemented!() - } } /// This is the entrypoint for a hot plugged rustc_codegen_gccjit From 7cce6aff07fa81c4a69deec899a1b87348f727de Mon Sep 17 00:00:00 2001 From: Daniel Paoliello Date: Thu, 3 Jul 2025 09:17:48 -0700 Subject: [PATCH 0045/1134] Make __rust_alloc_error_handler_should_panic a function --- src/allocator.rs | 44 +++++++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/src/allocator.rs b/src/allocator.rs index cf8aa500c778..0d8dc93274f9 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -1,6 +1,6 @@ -use gccjit::{Context, FunctionType, GlobalKind, ToRValue, Type}; #[cfg(feature = "master")] -use gccjit::{FnAttribute, VarAttribute}; +use gccjit::FnAttribute; +use gccjit::{Context, FunctionType, RValue, ToRValue, Type}; use rustc_ast::expand::allocator::{ ALLOCATOR_METHODS, AllocatorKind, AllocatorTy, NO_ALLOC_SHIM_IS_UNSTABLE, alloc_error_handler_name, default_fn_name, global_fn_name, @@ -71,15 +71,13 @@ pub(crate) unsafe fn codegen( None, ); - let name = mangle_internal_symbol(tcx, OomStrategy::SYMBOL); - let global = context.new_global(None, GlobalKind::Exported, i8, name); - #[cfg(feature = "master")] - global.add_attribute(VarAttribute::Visibility(symbol_visibility_to_gcc( - tcx.sess.default_visibility(), - ))); - let value = tcx.sess.opts.unstable_opts.oom.should_panic(); - let value = context.new_rvalue_from_int(i8, value as i32); - global.global_set_initializer_rvalue(value); + create_const_value_function( + tcx, + context, + &mangle_internal_symbol(tcx, OomStrategy::SYMBOL), + i8, + context.new_rvalue_from_int(i8, tcx.sess.opts.unstable_opts.oom.should_panic() as i32), + ); create_wrapper_function( tcx, @@ -91,6 +89,30 @@ pub(crate) unsafe fn codegen( ); } +fn create_const_value_function( + tcx: TyCtxt<'_>, + context: &Context<'_>, + name: &str, + output: Type<'_>, + value: RValue<'_>, +) { + let func = context.new_function(None, FunctionType::Exported, output, &[], name, false); + + #[cfg(feature = "master")] + func.add_attribute(FnAttribute::Visibility(symbol_visibility_to_gcc( + tcx.sess.default_visibility(), + ))); + + func.add_attribute(FnAttribute::AlwaysInline); + + if tcx.sess.must_emit_unwind_tables() { + // TODO(antoyo): emit unwind tables. + } + + let block = func.new_block("entry"); + block.end_with_return(None, value); +} + fn create_wrapper_function( tcx: TyCtxt<'_>, context: &Context<'_>, From 7b1674d5d0f395bd49434f0cec2f74c26b378362 Mon Sep 17 00:00:00 2001 From: Diggory Blake Date: Sat, 5 Jul 2025 15:58:04 +0100 Subject: [PATCH 0046/1134] Use `object` crate from crates.io to fix windows build error --- Cargo.lock | 10 ++++++++++ Cargo.toml | 1 + src/lib.rs | 1 - 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index b20c181a8cbf..7f35c1a80bda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -143,6 +143,15 @@ dependencies = [ "libc", ] +[[package]] +name = "object" +version = "0.37.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03fd943161069e1768b4b3d050890ba48730e590f57e56d4aa04e7e090e61b4a" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.20.2" @@ -179,6 +188,7 @@ dependencies = [ "boml", "gccjit", "lang_tester", + "object", "tempfile", ] diff --git a/Cargo.toml b/Cargo.toml index c284e3f060b8..05b0431b6ba9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ master = ["gccjit/master"] default = ["master"] [dependencies] +object = { version = "0.37.0", default-features = false, features = ["std", "read"] } gccjit = "2.7" #gccjit = { git = "https://github.com/rust-lang/gccjit.rs" } diff --git a/src/lib.rs b/src/lib.rs index a912678ef2a1..56afdd55bf99 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,7 +27,6 @@ #![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] // Some "regular" crates we want to share with rustc -extern crate object; extern crate smallvec; // FIXME(antoyo): clippy bug: remove the #[allow] when it's fixed. #[allow(unused_extern_crates)] From 214311beb05883c5d07200d28cc926e2acfbaaad Mon Sep 17 00:00:00 2001 From: Diggory Blake Date: Sat, 5 Jul 2025 17:23:39 +0100 Subject: [PATCH 0047/1134] Make tempfile a normal dependency --- Cargo.toml | 2 +- src/lib.rs | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 05b0431b6ba9..193348d1ef60 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ default = ["master"] [dependencies] object = { version = "0.37.0", default-features = false, features = ["std", "read"] } +tempfile = "3.20" gccjit = "2.7" #gccjit = { git = "https://github.com/rust-lang/gccjit.rs" } @@ -32,7 +33,6 @@ gccjit = "2.7" [dev-dependencies] boml = "0.3.1" lang_tester = "0.8.0" -tempfile = "3.20" [profile.dev] # By compiling dependencies with optimizations, performing tests gets much faster. diff --git a/src/lib.rs b/src/lib.rs index 56afdd55bf99..1a6eec0ed0bf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,11 +26,9 @@ #![deny(clippy::pattern_type_mismatch)] #![allow(clippy::needless_lifetimes, clippy::uninlined_format_args)] -// Some "regular" crates we want to share with rustc +// These crates are pulled from the sysroot because they are part of +// rustc's public API, so we need to ensure version compatibility. extern crate smallvec; -// FIXME(antoyo): clippy bug: remove the #[allow] when it's fixed. -#[allow(unused_extern_crates)] -extern crate tempfile; #[macro_use] extern crate tracing; From 303a795ac5d9e60c4524fadebd36d0a8f95d8e9c Mon Sep 17 00:00:00 2001 From: Edoardo Marangoni Date: Sun, 29 Jun 2025 12:11:51 +0200 Subject: [PATCH 0048/1134] compiler: Parse `p-` specs in datalayout string, allow definition of custom default data address space --- src/common.rs | 2 +- src/consts.rs | 4 ++-- src/intrinsic/mod.rs | 2 +- src/intrinsic/simd.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/common.rs b/src/common.rs index dd582834faca..32713eb56c6e 100644 --- a/src/common.rs +++ b/src/common.rs @@ -162,7 +162,7 @@ impl<'gcc, 'tcx> ConstCodegenMethods for CodegenCx<'gcc, 'tcx> { } fn const_usize(&self, i: u64) -> RValue<'gcc> { - let bit_size = self.data_layout().pointer_size.bits(); + let bit_size = self.data_layout().pointer_size().bits(); if bit_size < 64 { // make sure it doesn't overflow assert!(i < (1 << bit_size)); diff --git a/src/consts.rs b/src/consts.rs index b43f9b24c6a3..c04c75e1b11f 100644 --- a/src/consts.rs +++ b/src/consts.rs @@ -294,7 +294,7 @@ pub(crate) fn const_alloc_to_gcc_uncached<'gcc>( let alloc = alloc.inner(); let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1); let dl = cx.data_layout(); - let pointer_size = dl.pointer_size.bytes() as usize; + let pointer_size = dl.pointer_size().bytes() as usize; let mut next_offset = 0; for &(offset, prov) in alloc.provenance().ptrs().iter() { @@ -331,7 +331,7 @@ pub(crate) fn const_alloc_to_gcc_uncached<'gcc>( ), abi::Scalar::Initialized { value: Primitive::Pointer(address_space), - valid_range: WrappingRange::full(dl.pointer_size), + valid_range: WrappingRange::full(dl.pointer_size()), }, cx.type_i8p_ext(address_space), )); diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index 497605978fe2..0753ac1aeb84 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -541,7 +541,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc // For rusty ABIs, small aggregates are actually passed // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`), // so we re-use that same threshold here. - layout.size() <= self.data_layout().pointer_size * 2 + layout.size() <= self.data_layout().pointer_size() * 2 } }; diff --git a/src/intrinsic/simd.rs b/src/intrinsic/simd.rs index 2e508813fc3b..350915a277e3 100644 --- a/src/intrinsic/simd.rs +++ b/src/intrinsic/simd.rs @@ -1184,7 +1184,7 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let lhs = args[0].immediate(); let rhs = args[1].immediate(); let is_add = name == sym::simd_saturating_add; - let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _; + let ptr_bits = bx.tcx().data_layout.pointer_size().bits() as _; let (signed, elem_width, elem_ty) = match *in_elem.kind() { ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits) / 8, bx.cx.type_int_from_ty(i)), ty::Uint(i) => { From dffe77dbabf273e811929580825c6d474a5a605a Mon Sep 17 00:00:00 2001 From: Yotam Ofek Date: Sat, 28 Jun 2025 23:40:02 +0000 Subject: [PATCH 0049/1134] Remove unused allow attrs --- src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 1a6eec0ed0bf..d8fae1ca47d3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,7 +19,6 @@ #![doc(rust_logo)] #![feature(rustdoc_internals)] #![feature(rustc_private)] -#![allow(broken_intra_doc_links)] #![recursion_limit = "256"] #![warn(rust_2018_idioms)] #![warn(unused_lifetimes)] From 46836c352d86268ad88fb406337413539b48ca32 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 24 Jun 2025 16:58:46 +0200 Subject: [PATCH 0050/1134] Remove support for dynamic allocas --- src/builder.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index b1785af444a1..28d1ec7d8956 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -926,10 +926,6 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { .get_address(self.location) } - fn dynamic_alloca(&mut self, _len: RValue<'gcc>, _align: Align) -> RValue<'gcc> { - unimplemented!(); - } - fn load(&mut self, pointee_ty: Type<'gcc>, ptr: RValue<'gcc>, align: Align) -> RValue<'gcc> { let block = self.llbb(); let function = block.get_function(); From 3d5b1774db136b03a80279f2829e58863056ff3a Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Wed, 12 Mar 2025 10:26:37 +0000 Subject: [PATCH 0051/1134] Add opaque TypeId handles for CTFE --- src/common.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/common.rs b/src/common.rs index 32713eb56c6e..28848ca61845 100644 --- a/src/common.rs +++ b/src/common.rs @@ -1,7 +1,6 @@ use gccjit::{LValue, RValue, ToRValue, Type}; -use rustc_abi as abi; -use rustc_abi::HasDataLayout; use rustc_abi::Primitive::Pointer; +use rustc_abi::{self as abi, HasDataLayout}; use rustc_codegen_ssa::traits::{ BaseTypeCodegenMethods, ConstCodegenMethods, MiscCodegenMethods, StaticCodegenMethods, }; @@ -282,6 +281,13 @@ impl<'gcc, 'tcx> ConstCodegenMethods for CodegenCx<'gcc, 'tcx> { let init = self.const_data_from_alloc(alloc); self.static_addr_of(init, alloc.inner().align, None) } + GlobalAlloc::TypeId { .. } => { + let val = self.const_usize(offset.bytes()); + // This is still a variable of pointer type, even though we only use the provenance + // of that pointer in CTFE and Miri. But to make LLVM's type system happy, + // we need an int-to-ptr cast here (it doesn't matter at all which provenance that picks). + return self.context.new_cast(None, val, ty); + } GlobalAlloc::Static(def_id) => { assert!(self.tcx.is_static(def_id)); self.get_static(def_id).get_address(None) From f6bdffdcba7498fd3fe7b18bca966b23da6c463f Mon Sep 17 00:00:00 2001 From: Pavel Grigorenko Date: Mon, 20 Nov 2023 02:18:52 +0300 Subject: [PATCH 0052/1134] Add Ref/RefMut try_map method --- library/core/src/cell.rs | 93 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index c53a2b2beb4c..2f1a74fa2416 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -1573,6 +1573,47 @@ impl<'b, T: ?Sized> Ref<'b, T> { } } + /// Tries to makes a new `Ref` for a component of the borrowed data. + /// On failure, the original guard is returned alongside with the error + /// returned by the closure. + /// + /// The `RefCell` is already immutably borrowed, so this cannot fail. + /// + /// This is an associated function that needs to be used as + /// `Ref::try_map(...)`. A method would interfere with methods of the same + /// name on the contents of a `RefCell` used through `Deref`. + /// + /// # Examples + /// + /// ``` + /// #![feature(refcell_try_map)] + /// use std::cell::{RefCell, Ref}; + /// use std::str::{from_utf8, Utf8Error}; + /// + /// let c = RefCell::new(vec![0xF0, 0x9F, 0xA6 ,0x80]); + /// let b1: Ref<'_, Vec> = c.borrow(); + /// let b2: Result, _> = Ref::try_map(b1, |v| from_utf8(v)); + /// assert_eq!(&*b2.unwrap(), "🦀"); + /// + /// let c = RefCell::new(vec![0xF0, 0x9F, 0xA6]); + /// let b1: Ref<'_, Vec> = c.borrow(); + /// let b2: Result<_, (Ref<'_, Vec>, Utf8Error)> = Ref::try_map(b1, |v| from_utf8(v)); + /// let (b3, e) = b2.unwrap_err(); + /// assert_eq!(*b3, vec![0xF0, 0x9F, 0xA6]); + /// assert_eq!(e.valid_up_to(), 0); + /// ``` + #[unstable(feature = "refcell_try_map", issue = "143801")] + #[inline] + pub fn try_map( + orig: Ref<'b, T>, + f: impl FnOnce(&T) -> Result<&U, E>, + ) -> Result, (Self, E)> { + match f(&*orig) { + Ok(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }), + Err(e) => Err((orig, e)), + } + } + /// Splits a `Ref` into multiple `Ref`s for different components of the /// borrowed data. /// @@ -1734,6 +1775,58 @@ impl<'b, T: ?Sized> RefMut<'b, T> { } } + /// Tries to makes a new `RefMut` for a component of the borrowed data. + /// On failure, the original guard is returned alongside with the error + /// returned by the closure. + /// + /// The `RefCell` is already mutably borrowed, so this cannot fail. + /// + /// This is an associated function that needs to be used as + /// `RefMut::try_map(...)`. A method would interfere with methods of the same + /// name on the contents of a `RefCell` used through `Deref`. + /// + /// # Examples + /// + /// ``` + /// #![feature(refcell_try_map)] + /// use std::cell::{RefCell, RefMut}; + /// use std::str::{from_utf8_mut, Utf8Error}; + /// + /// let c = RefCell::new(vec![0x68, 0x65, 0x6C, 0x6C, 0x6F]); + /// { + /// let b1: RefMut<'_, Vec> = c.borrow_mut(); + /// let b2: Result, _> = RefMut::try_map(b1, |v| from_utf8_mut(v)); + /// let mut b2 = b2.unwrap(); + /// assert_eq!(&*b2, "hello"); + /// b2.make_ascii_uppercase(); + /// } + /// assert_eq!(*c.borrow(), "HELLO".as_bytes()); + /// + /// let c = RefCell::new(vec![0xFF]); + /// let b1: RefMut<'_, Vec> = c.borrow_mut(); + /// let b2: Result<_, (RefMut<'_, Vec>, Utf8Error)> = RefMut::try_map(b1, |v| from_utf8_mut(v)); + /// let (b3, e) = b2.unwrap_err(); + /// assert_eq!(*b3, vec![0xFF]); + /// assert_eq!(e.valid_up_to(), 0); + /// ``` + #[unstable(feature = "refcell_try_map", issue = "143801")] + #[inline] + pub fn try_map( + mut orig: RefMut<'b, T>, + f: impl FnOnce(&mut T) -> Result<&mut U, E>, + ) -> Result, (Self, E)> { + // SAFETY: function holds onto an exclusive reference for the duration + // of its call through `orig`, and the pointer is only de-referenced + // inside of the function call never allowing the exclusive reference to + // escape. + match f(&mut *orig) { + Ok(value) => { + Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData }) + } + Err(e) => Err((orig, e)), + } + } + /// Splits a `RefMut` into multiple `RefMut`s for different components of the /// borrowed data. /// From 222ebd0535bcaeda021702bef63e25cfcaa47e5b Mon Sep 17 00:00:00 2001 From: yanglsh Date: Wed, 25 Jun 2025 21:27:02 +0800 Subject: [PATCH 0053/1134] fix: `search_is_some` suggests wrongly inside macro --- clippy_utils/src/sugg.rs | 24 ++++++++++++++++++--- tests/ui/search_is_some.rs | 15 +++++++++++++ tests/ui/search_is_some.stderr | 17 ++++++++++++++- tests/ui/search_is_some_fixable_some.fixed | 7 ++++++ tests/ui/search_is_some_fixable_some.rs | 7 ++++++ tests/ui/search_is_some_fixable_some.stderr | 8 ++++++- 6 files changed, 73 insertions(+), 5 deletions(-) diff --git a/clippy_utils/src/sugg.rs b/clippy_utils/src/sugg.rs index 7a24d07fa1df..88f313c5f7e5 100644 --- a/clippy_utils/src/sugg.rs +++ b/clippy_utils/src/sugg.rs @@ -6,9 +6,9 @@ use crate::ty::expr_sig; use crate::{get_parent_expr_for_hir, higher}; use rustc_ast::ast; use rustc_ast::util::parser::AssocOp; +use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; -use rustc_hir as hir; -use rustc_hir::{Closure, ExprKind, HirId, MutTy, TyKind}; +use rustc_hir::{self as hir, Closure, ExprKind, HirId, MutTy, Node, TyKind}; use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; use rustc_lint::{EarlyContext, LateContext, LintContext}; use rustc_middle::hir::place::ProjectionKind; @@ -753,8 +753,10 @@ pub fn deref_closure_args(cx: &LateContext<'_>, closure: &hir::Expr<'_>) -> Opti let mut visitor = DerefDelegate { cx, closure_span: closure.span, + closure_arg_id: closure_body.params[0].pat.hir_id, closure_arg_is_type_annotated_double_ref, next_pos: closure.span.lo(), + checked_borrows: FxHashSet::default(), suggestion_start: String::new(), applicability: Applicability::MachineApplicable, }; @@ -780,10 +782,15 @@ struct DerefDelegate<'a, 'tcx> { cx: &'a LateContext<'tcx>, /// The span of the input closure to adapt closure_span: Span, + /// The `hir_id` of the closure argument being checked + closure_arg_id: HirId, /// Indicates if the arg of the closure is a type annotated double reference closure_arg_is_type_annotated_double_ref: bool, /// last position of the span to gradually build the suggestion next_pos: BytePos, + /// `hir_id`s that has been checked. This is used to avoid checking the same `hir_id` multiple + /// times when inside macro expansions. + checked_borrows: FxHashSet, /// starting part of the gradually built suggestion suggestion_start: String, /// confidence on the built suggestion @@ -847,9 +854,15 @@ impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> { fn use_cloned(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {} + #[expect(clippy::too_many_lines)] fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) { if let PlaceBase::Local(id) = cmt.place.base { let span = self.cx.tcx.hir_span(cmt.hir_id); + if !self.checked_borrows.insert(cmt.hir_id) { + // already checked this span and hir_id, skip + return; + } + let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None); let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability); @@ -858,7 +871,12 @@ impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> { // full identifier that includes projection (i.e.: `fp.field`) let ident_str_with_proj = snippet(self.cx, span, "..").to_string(); - if cmt.place.projections.is_empty() { + // Make sure to get in all projections if we're on a `matches!` + if let Node::Pat(pat) = self.cx.tcx.hir_node(id) + && pat.hir_id != self.closure_arg_id + { + let _ = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}"); + } else if cmt.place.projections.is_empty() { // handle item without any projection, that needs an explicit borrowing // i.e.: suggest `&x` instead of `x` let _: fmt::Result = write!(self.suggestion_start, "{start_snip}&{ident_str}"); diff --git a/tests/ui/search_is_some.rs b/tests/ui/search_is_some.rs index 4143b8bfba58..802d27449abf 100644 --- a/tests/ui/search_is_some.rs +++ b/tests/ui/search_is_some.rs @@ -87,3 +87,18 @@ fn is_none() { let _ = (0..1).find(some_closure).is_none(); //~^ search_is_some } + +#[allow(clippy::match_like_matches_macro)] +fn issue15102() { + let values = [None, Some(3)]; + let has_even = values + //~^ search_is_some + .iter() + .find(|v| match v { + Some(x) if x % 2 == 0 => true, + _ => false, + }) + .is_some(); + + println!("{has_even}"); +} diff --git a/tests/ui/search_is_some.stderr b/tests/ui/search_is_some.stderr index d9a43c8915e8..d5412f901110 100644 --- a/tests/ui/search_is_some.stderr +++ b/tests/ui/search_is_some.stderr @@ -90,5 +90,20 @@ error: called `is_none()` after searching an `Iterator` with `find` LL | let _ = (0..1).find(some_closure).is_none(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `!(0..1).any(some_closure)` -error: aborting due to 8 previous errors +error: called `is_some()` after searching an `Iterator` with `find` + --> tests/ui/search_is_some.rs:94:20 + | +LL | let has_even = values + | ____________________^ +LL | | +LL | | .iter() +LL | | .find(|v| match v { +... | +LL | | }) +LL | | .is_some(); + | |__________________^ + | + = help: this is more succinctly expressed by calling `any()` + +error: aborting due to 9 previous errors diff --git a/tests/ui/search_is_some_fixable_some.fixed b/tests/ui/search_is_some_fixable_some.fixed index 42b39b33b575..c7a4422f3737 100644 --- a/tests/ui/search_is_some_fixable_some.fixed +++ b/tests/ui/search_is_some_fixable_some.fixed @@ -289,3 +289,10 @@ mod issue9120 { //~^ search_is_some } } + +fn issue15102() { + let values = [None, Some(3)]; + let has_even = values.iter().any(|v| matches!(&v, Some(x) if x % 2 == 0)); + //~^ search_is_some + println!("{has_even}"); +} diff --git a/tests/ui/search_is_some_fixable_some.rs b/tests/ui/search_is_some_fixable_some.rs index ca4f4d941cb2..d6b1c67c9718 100644 --- a/tests/ui/search_is_some_fixable_some.rs +++ b/tests/ui/search_is_some_fixable_some.rs @@ -297,3 +297,10 @@ mod issue9120 { //~^ search_is_some } } + +fn issue15102() { + let values = [None, Some(3)]; + let has_even = values.iter().find(|v| matches!(v, Some(x) if x % 2 == 0)).is_some(); + //~^ search_is_some + println!("{has_even}"); +} diff --git a/tests/ui/search_is_some_fixable_some.stderr b/tests/ui/search_is_some_fixable_some.stderr index 8291f48d43c4..551a670d937f 100644 --- a/tests/ui/search_is_some_fixable_some.stderr +++ b/tests/ui/search_is_some_fixable_some.stderr @@ -289,5 +289,11 @@ error: called `is_some()` after searching an `Iterator` with `find` LL | let _ = v.iter().find(|x: &&u32| (*arg_no_deref_dyn)(x)).is_some(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `any(|x: &u32| (*arg_no_deref_dyn)(&x))` -error: aborting due to 46 previous errors +error: called `is_some()` after searching an `Iterator` with `find` + --> tests/ui/search_is_some_fixable_some.rs:303:34 + | +LL | let has_even = values.iter().find(|v| matches!(v, Some(x) if x % 2 == 0)).is_some(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `any(|v| matches!(&v, Some(x) if x % 2 == 0))` + +error: aborting due to 47 previous errors From ba6485d61c5dd6c106c5f93b6d581a88f630cbc2 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Sun, 15 Jun 2025 21:28:14 +0800 Subject: [PATCH 0054/1134] fix: `match_single_binding` wrongly handles scope --- .../src/matches/match_single_binding.rs | 222 +++++++++++++++--- clippy_utils/src/source.rs | 34 ++- tests/ui/match_single_binding.fixed | 53 +++++ tests/ui/match_single_binding.rs | 61 +++++ tests/ui/match_single_binding.stderr | 96 +++++++- 5 files changed, 429 insertions(+), 37 deletions(-) diff --git a/clippy_lints/src/matches/match_single_binding.rs b/clippy_lints/src/matches/match_single_binding.rs index 6a76c6cedd0d..9790e63821da 100644 --- a/clippy_lints/src/matches/match_single_binding.rs +++ b/clippy_lints/src/matches/match_single_binding.rs @@ -1,11 +1,18 @@ +use std::ops::ControlFlow; + use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::HirNode; -use clippy_utils::source::{indent_of, snippet, snippet_block_with_context, snippet_with_context}; +use clippy_utils::source::{ + RelativeIndent, indent_of, reindent_multiline_relative, snippet, snippet_block_with_context, snippet_with_context, +}; use clippy_utils::{is_refutable, peel_blocks}; +use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; -use rustc_hir::{Arm, Expr, ExprKind, Node, PatKind, StmtKind}; +use rustc_hir::def::Res; +use rustc_hir::intravisit::{Visitor, walk_block, walk_expr, walk_path, walk_stmt}; +use rustc_hir::{Arm, Block, Expr, ExprKind, HirId, Node, PatKind, Path, Stmt, StmtKind}; use rustc_lint::LateContext; -use rustc_span::Span; +use rustc_span::{Span, Symbol}; use super::MATCH_SINGLE_BINDING; @@ -50,10 +57,11 @@ pub(crate) fn check<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], e cx, (ex, expr), (bind_names, matched_vars), - &snippet_body, + snippet_body, &mut app, Some(span), true, + is_var_binding_used_later(cx, expr, &arms[0]), ); span_lint_and_sugg( @@ -83,10 +91,11 @@ pub(crate) fn check<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], e cx, (ex, expr), (bind_names, matched_vars), - &snippet_body, + snippet_body, &mut app, None, true, + is_var_binding_used_later(cx, expr, &arms[0]), ); (expr.span, sugg) }, @@ -108,10 +117,11 @@ pub(crate) fn check<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], e cx, (ex, expr), (bind_names, matched_vars), - &snippet_body, + snippet_body, &mut app, None, false, + true, ); span_lint_and_sugg( @@ -139,6 +149,125 @@ pub(crate) fn check<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], e } } +struct VarBindingVisitor<'a, 'tcx> { + cx: &'a LateContext<'tcx>, + identifiers: FxHashSet, +} + +impl<'tcx> Visitor<'tcx> for VarBindingVisitor<'_, 'tcx> { + type Result = ControlFlow<()>; + + fn visit_path(&mut self, path: &Path<'tcx>, _: HirId) -> Self::Result { + if let Res::Local(_) = path.res + && let [segment] = path.segments + && self.identifiers.contains(&segment.ident.name) + { + return ControlFlow::Break(()); + } + + walk_path(self, path) + } + + fn visit_block(&mut self, block: &'tcx Block<'tcx>) -> Self::Result { + let before = self.identifiers.clone(); + walk_block(self, block)?; + self.identifiers = before; + ControlFlow::Continue(()) + } + + fn visit_stmt(&mut self, stmt: &'tcx Stmt<'tcx>) -> Self::Result { + if let StmtKind::Let(let_stmt) = stmt.kind { + if let Some(init) = let_stmt.init { + self.visit_expr(init)?; + } + + let_stmt.pat.each_binding(|_, _, _, ident| { + self.identifiers.remove(&ident.name); + }); + } + walk_stmt(self, stmt) + } + + fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) -> Self::Result { + match expr.kind { + ExprKind::If( + Expr { + kind: ExprKind::Let(let_expr), + .. + }, + then, + else_, + ) => { + self.visit_expr(let_expr.init)?; + let before = self.identifiers.clone(); + let_expr.pat.each_binding(|_, _, _, ident| { + self.identifiers.remove(&ident.name); + }); + + self.visit_expr(then)?; + self.identifiers = before; + if let Some(else_) = else_ { + self.visit_expr(else_)?; + } + ControlFlow::Continue(()) + }, + ExprKind::Closure(closure) => { + let body = self.cx.tcx.hir_body(closure.body); + let before = self.identifiers.clone(); + for param in body.params { + param.pat.each_binding(|_, _, _, ident| { + self.identifiers.remove(&ident.name); + }); + } + self.visit_expr(body.value)?; + self.identifiers = before; + ControlFlow::Continue(()) + }, + ExprKind::Match(expr, arms, _) => { + self.visit_expr(expr)?; + for arm in arms { + let before = self.identifiers.clone(); + arm.pat.each_binding(|_, _, _, ident| { + self.identifiers.remove(&ident.name); + }); + if let Some(guard) = arm.guard { + self.visit_expr(guard)?; + } + self.visit_expr(arm.body)?; + self.identifiers = before; + } + ControlFlow::Continue(()) + }, + _ => walk_expr(self, expr), + } + } +} + +fn is_var_binding_used_later(cx: &LateContext<'_>, expr: &Expr<'_>, arm: &Arm<'_>) -> bool { + let Node::Stmt(stmt) = cx.tcx.parent_hir_node(expr.hir_id) else { + return false; + }; + let Node::Block(block) = cx.tcx.parent_hir_node(stmt.hir_id) else { + return false; + }; + + let mut identifiers = FxHashSet::default(); + arm.pat.each_binding(|_, _, _, ident| { + identifiers.insert(ident.name); + }); + + let mut visitor = VarBindingVisitor { cx, identifiers }; + block + .stmts + .iter() + .skip_while(|s| s.hir_id != stmt.hir_id) + .skip(1) + .any(|stmt| matches!(visitor.visit_stmt(stmt), ControlFlow::Break(()))) + || block + .expr + .is_some_and(|expr| matches!(visitor.visit_expr(expr), ControlFlow::Break(()))) +} + /// Returns true if the `ex` match expression is in a local (`let`) or assign expression fn opt_parent_assign_span<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option { if let Node::Expr(parent_arm_expr) = cx.tcx.parent_hir_node(ex.hir_id) { @@ -161,47 +290,58 @@ fn opt_parent_assign_span<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option(cx: &LateContext<'a>, match_expr: &Expr<'a>) -> bool { +fn expr_in_nested_block(cx: &LateContext<'_>, match_expr: &Expr<'_>) -> bool { + if let Node::Block(block) = cx.tcx.parent_hir_node(match_expr.hir_id) { + return block + .expr + .map_or_else(|| matches!(block.stmts, [_]), |_| block.stmts.is_empty()); + } + false +} + +fn expr_must_have_curlies(cx: &LateContext<'_>, match_expr: &Expr<'_>) -> bool { let parent = cx.tcx.parent_hir_node(match_expr.hir_id); - matches!( - parent, - Node::Expr(Expr { - kind: ExprKind::Closure { .. }, - .. - }) | Node::AnonConst(..) + if let Node::Expr(Expr { + kind: ExprKind::Closure { .. }, + .. + }) + | Node::AnonConst(..) = parent + { + return true; + } + + if let Node::Arm(arm) = &cx.tcx.parent_hir_node(match_expr.hir_id) + && let ExprKind::Match(..) = arm.body.kind + { + return true; + } + + false +} + +fn reindent_snippet_if_in_block(snippet_body: &str, has_assignment: bool) -> String { + if has_assignment || !snippet_body.starts_with('{') { + return reindent_multiline_relative(snippet_body, true, RelativeIndent::Add(0)); + } + + reindent_multiline_relative( + snippet_body.trim_start_matches('{').trim_end_matches('}').trim(), + false, + RelativeIndent::Sub(4), ) } +#[expect(clippy::too_many_arguments)] fn sugg_with_curlies<'a>( cx: &LateContext<'a>, (ex, match_expr): (&Expr<'a>, &Expr<'a>), (bind_names, matched_vars): (Span, Span), - snippet_body: &str, + mut snippet_body: String, applicability: &mut Applicability, assignment: Option, needs_var_binding: bool, + is_var_binding_used_later: bool, ) -> String { - let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0)); - - let (mut cbrace_start, mut cbrace_end) = (String::new(), String::new()); - if expr_parent_requires_curlies(cx, match_expr) { - cbrace_end = format!("\n{indent}}}"); - // Fix body indent due to the closure - indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0)); - cbrace_start = format!("{{\n{indent}"); - } - - // If the parent is already an arm, and the body is another match statement, - // we need curly braces around suggestion - if let Node::Arm(arm) = &cx.tcx.parent_hir_node(match_expr.hir_id) - && let ExprKind::Match(..) = arm.body.kind - { - cbrace_end = format!("\n{indent}}}"); - // Fix body indent due to the match - indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0)); - cbrace_start = format!("{{\n{indent}"); - } - let assignment_str = assignment.map_or_else(String::new, |span| { let mut s = snippet(cx, span, "..").to_string(); s.push_str(" = "); @@ -221,5 +361,17 @@ fn sugg_with_curlies<'a>( .to_string() }; + let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0)); + let (mut cbrace_start, mut cbrace_end) = (String::new(), String::new()); + if !expr_in_nested_block(cx, match_expr) + && ((needs_var_binding && is_var_binding_used_later) || expr_must_have_curlies(cx, match_expr)) + { + cbrace_end = format!("\n{indent}}}"); + // Fix body indent due to the closure + indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0)); + cbrace_start = format!("{{\n{indent}"); + snippet_body = reindent_snippet_if_in_block(&snippet_body, !assignment_str.is_empty()); + } + format!("{cbrace_start}{scrutinee};\n{indent}{assignment_str}{snippet_body}{cbrace_end}") } diff --git a/clippy_utils/src/source.rs b/clippy_utils/src/source.rs index 7f2bf99daff2..b490902429f5 100644 --- a/clippy_utils/src/source.rs +++ b/clippy_utils/src/source.rs @@ -18,7 +18,7 @@ use rustc_span::{ }; use std::borrow::Cow; use std::fmt; -use std::ops::{Deref, Index, Range}; +use std::ops::{Add, Deref, Index, Range}; pub trait HasSession { fn sess(&self) -> &Session; @@ -476,6 +476,38 @@ pub fn position_before_rarrow(s: &str) -> Option { }) } +pub enum RelativeIndent { + Add(usize), + Sub(usize), +} + +impl Add for usize { + type Output = usize; + + fn add(self, rhs: RelativeIndent) -> Self::Output { + match rhs { + RelativeIndent::Add(n) => self + n, + RelativeIndent::Sub(n) => self.saturating_sub(n), + } + } +} + +/// Reindents a multiline string with possibility of ignoring the first line and relative +/// indentation. +pub fn reindent_multiline_relative(s: &str, ignore_first: bool, relative_indent: RelativeIndent) -> String { + fn indent_of_string(s: &str) -> usize { + s.find(|c: char| !c.is_whitespace()).unwrap_or(0) + } + + let mut indent = 0; + if let Some(line) = s.lines().nth(usize::from(ignore_first)) { + let line_indent = indent_of_string(line); + indent = line_indent + relative_indent; + } + + reindent_multiline(s, ignore_first, Some(indent)) +} + /// Reindent a multiline string with possibility of ignoring the first line. pub fn reindent_multiline(s: &str, ignore_first: bool, indent: Option) -> String { let s_space = reindent_multiline_inner(s, ignore_first, indent, ' '); diff --git a/tests/ui/match_single_binding.fixed b/tests/ui/match_single_binding.fixed index e11dea352049..d8d865ee44cf 100644 --- a/tests/ui/match_single_binding.fixed +++ b/tests/ui/match_single_binding.fixed @@ -204,3 +204,56 @@ mod issue14991 { }], } } + +mod issue15018 { + fn used_later(a: i32, b: i32, c: i32) { + let x = 1; + { + let (x, y, z) = (a, b, c); + println!("{} {} {}", x, y, z); + } + println!("x = {x}"); + } + + fn not_used_later(a: i32, b: i32, c: i32) { + let (x, y, z) = (a, b, c); + println!("{} {} {}", x, y, z) + } + + #[allow(irrefutable_let_patterns)] + fn not_used_later_but_shadowed(a: i32, b: i32, c: i32) { + let (x, y, z) = (a, b, c); + println!("{} {} {}", x, y, z); + let x = 1; + println!("x = {x}"); + } + + #[allow(irrefutable_let_patterns)] + fn not_used_later_but_shadowed_nested(a: i32, b: i32, c: i32) { + let (x, y, z) = (a, b, c); + println!("{} {} {}", x, y, z); + if let (x, y, z) = (a, b, c) { + println!("{} {} {}", x, y, z) + } + + { + let x: i32 = 1; + { + let (x, y, z) = (a, b, c); + println!("{} {} {}", x, y, z); + } + if let (x, y, z) = (a, x, c) { + println!("{} {} {}", x, y, z) + } + } + + { + let (x, y, z) = (a, b, c); + println!("{} {} {}", x, y, z); + let fn_ = |y| { + println!("{} {} {}", a, b, y); + }; + fn_(c); + } + } +} diff --git a/tests/ui/match_single_binding.rs b/tests/ui/match_single_binding.rs index d498da30fc87..ecff945fb913 100644 --- a/tests/ui/match_single_binding.rs +++ b/tests/ui/match_single_binding.rs @@ -267,3 +267,64 @@ mod issue14991 { }], } } + +mod issue15018 { + fn used_later(a: i32, b: i32, c: i32) { + let x = 1; + match (a, b, c) { + //~^ match_single_binding + (x, y, z) => println!("{} {} {}", x, y, z), + } + println!("x = {x}"); + } + + fn not_used_later(a: i32, b: i32, c: i32) { + match (a, b, c) { + //~^ match_single_binding + (x, y, z) => println!("{} {} {}", x, y, z), + } + } + + #[allow(irrefutable_let_patterns)] + fn not_used_later_but_shadowed(a: i32, b: i32, c: i32) { + match (a, b, c) { + //~^ match_single_binding + (x, y, z) => println!("{} {} {}", x, y, z), + } + let x = 1; + println!("x = {x}"); + } + + #[allow(irrefutable_let_patterns)] + fn not_used_later_but_shadowed_nested(a: i32, b: i32, c: i32) { + match (a, b, c) { + //~^ match_single_binding + (x, y, z) => println!("{} {} {}", x, y, z), + } + if let (x, y, z) = (a, b, c) { + println!("{} {} {}", x, y, z) + } + + { + let x: i32 = 1; + match (a, b, c) { + //~^ match_single_binding + (x, y, z) => println!("{} {} {}", x, y, z), + } + if let (x, y, z) = (a, x, c) { + println!("{} {} {}", x, y, z) + } + } + + { + match (a, b, c) { + //~^ match_single_binding + (x, y, z) => println!("{} {} {}", x, y, z), + } + let fn_ = |y| { + println!("{} {} {}", a, b, y); + }; + fn_(c); + } + } +} diff --git a/tests/ui/match_single_binding.stderr b/tests/ui/match_single_binding.stderr index f274f80c81da..789626de6035 100644 --- a/tests/ui/match_single_binding.stderr +++ b/tests/ui/match_single_binding.stderr @@ -411,5 +411,99 @@ LL ~ let _n = 1; LL + 42 | -error: aborting due to 29 previous errors +error: this match could be written as a `let` statement + --> tests/ui/match_single_binding.rs:274:9 + | +LL | / match (a, b, c) { +LL | | +LL | | (x, y, z) => println!("{} {} {}", x, y, z), +LL | | } + | |_________^ + | +help: consider using a `let` statement + | +LL ~ { +LL + let (x, y, z) = (a, b, c); +LL + println!("{} {} {}", x, y, z); +LL + } + | + +error: this match could be written as a `let` statement + --> tests/ui/match_single_binding.rs:282:9 + | +LL | / match (a, b, c) { +LL | | +LL | | (x, y, z) => println!("{} {} {}", x, y, z), +LL | | } + | |_________^ + | +help: consider using a `let` statement + | +LL ~ let (x, y, z) = (a, b, c); +LL + println!("{} {} {}", x, y, z) + | + +error: this match could be written as a `let` statement + --> tests/ui/match_single_binding.rs:290:9 + | +LL | / match (a, b, c) { +LL | | +LL | | (x, y, z) => println!("{} {} {}", x, y, z), +LL | | } + | |_________^ + | +help: consider using a `let` statement + | +LL ~ let (x, y, z) = (a, b, c); +LL + println!("{} {} {}", x, y, z); + | + +error: this match could be written as a `let` statement + --> tests/ui/match_single_binding.rs:300:9 + | +LL | / match (a, b, c) { +LL | | +LL | | (x, y, z) => println!("{} {} {}", x, y, z), +LL | | } + | |_________^ + | +help: consider using a `let` statement + | +LL ~ let (x, y, z) = (a, b, c); +LL + println!("{} {} {}", x, y, z); + | + +error: this match could be written as a `let` statement + --> tests/ui/match_single_binding.rs:310:13 + | +LL | / match (a, b, c) { +LL | | +LL | | (x, y, z) => println!("{} {} {}", x, y, z), +LL | | } + | |_____________^ + | +help: consider using a `let` statement + | +LL ~ { +LL + let (x, y, z) = (a, b, c); +LL + println!("{} {} {}", x, y, z); +LL + } + | + +error: this match could be written as a `let` statement + --> tests/ui/match_single_binding.rs:320:13 + | +LL | / match (a, b, c) { +LL | | +LL | | (x, y, z) => println!("{} {} {}", x, y, z), +LL | | } + | |_____________^ + | +help: consider using a `let` statement + | +LL ~ let (x, y, z) = (a, b, c); +LL + println!("{} {} {}", x, y, z); + | + +error: aborting due to 35 previous errors From 87dd4695fe5fe2e76999d5040deb20a018e21942 Mon Sep 17 00:00:00 2001 From: Jules Bertholet Date: Tue, 15 Jul 2025 17:41:31 -0400 Subject: [PATCH 0055/1134] Add `Default` impls for `Pin`ned `Box`, `Rc`, `Arc` --- library/alloc/src/boxed.rs | 16 +++++++++++++++- library/alloc/src/rc.rs | 19 ++++++++++++++++--- library/alloc/src/sync.rs | 13 +++++++++++++ 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 3db37f1d16f3..fa12d379c8ca 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -1672,7 +1672,7 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box { #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl Default for Box { - /// Creates a `Box`, with the `Default` value for T. + /// Creates a `Box`, with the `Default` value for `T`. #[inline] fn default() -> Self { let mut x: Box> = Box::new_uninit(); @@ -1695,6 +1695,7 @@ impl Default for Box { #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl Default for Box<[T]> { + /// Creates an empty `[T]` inside a `Box`. #[inline] fn default() -> Self { let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling(); @@ -1716,6 +1717,19 @@ impl Default for Box { } } +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "pin_default_impls", since = "CURRENT_RUSTC_VERSION")] +impl Default for Pin> +where + T: ?Sized, + Box: Default, +{ + #[inline] + fn default() -> Self { + Box::into_pin(Box::::default()) + } +} + #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl Clone for Box { diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 5018ff4ad71f..529b583cdd2b 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -2357,7 +2357,7 @@ impl Default for Rc { /// assert_eq!(*x, 0); /// ``` #[inline] - fn default() -> Rc { + fn default() -> Self { unsafe { Self::from_inner( Box::leak(Box::write( @@ -2373,7 +2373,7 @@ impl Default for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "more_rc_default_impls", since = "1.80.0")] impl Default for Rc { - /// Creates an empty str inside an Rc + /// Creates an empty `str` inside an `Rc`. /// /// This may or may not share an allocation with other Rcs on the same thread. #[inline] @@ -2387,7 +2387,7 @@ impl Default for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "more_rc_default_impls", since = "1.80.0")] impl Default for Rc<[T]> { - /// Creates an empty `[T]` inside an Rc + /// Creates an empty `[T]` inside an `Rc`. /// /// This may or may not share an allocation with other Rcs on the same thread. #[inline] @@ -2397,6 +2397,19 @@ impl Default for Rc<[T]> { } } +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "pin_default_impls", since = "CURRENT_RUSTC_VERSION")] +impl Default for Pin> +where + T: ?Sized, + Rc: Default, +{ + #[inline] + fn default() -> Self { + unsafe { Pin::new_unchecked(Rc::::default()) } + } +} + #[stable(feature = "rust1", since = "1.0.0")] trait RcEqIdent { fn eq(&self, other: &Rc) -> bool; diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index b8925f4544f4..29caa7bc5393 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -3654,6 +3654,19 @@ impl Default for Arc<[T]> { } } +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "pin_default_impls", since = "CURRENT_RUSTC_VERSION")] +impl Default for Pin> +where + T: ?Sized, + Arc: Default, +{ + #[inline] + fn default() -> Self { + unsafe { Pin::new_unchecked(Arc::::default()) } + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl Hash for Arc { fn hash(&self, state: &mut H) { From e55baf9f7ada72ed9f661194065154a09aab3a9e Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 2 Jul 2025 11:12:54 +0200 Subject: [PATCH 0056/1134] use `codegen_instance_attrs` where an instance is (easily) available --- src/attributes.rs | 2 +- src/callee.rs | 2 +- src/mono_item.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/attributes.rs b/src/attributes.rs index bf0927dc590b..7a1ae6ca9c8b 100644 --- a/src/attributes.rs +++ b/src/attributes.rs @@ -87,7 +87,7 @@ pub fn from_fn_attrs<'gcc, 'tcx>( #[cfg_attr(not(feature = "master"), allow(unused_variables))] func: Function<'gcc>, instance: ty::Instance<'tcx>, ) { - let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id()); + let codegen_fn_attrs = cx.tcx.codegen_instance_attrs(instance.def); #[cfg(feature = "master")] { diff --git a/src/callee.rs b/src/callee.rs index 189ac7cd7792..e7ca95af594c 100644 --- a/src/callee.rs +++ b/src/callee.rs @@ -105,7 +105,7 @@ pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>) let is_hidden = if is_generic { // This is a monomorphization of a generic function. if !(cx.tcx.sess.opts.share_generics() - || tcx.codegen_fn_attrs(instance_def_id).inline + || tcx.codegen_instance_attrs(instance.def).inline == rustc_attr_data_structures::InlineAttr::Never) { // When not sharing generics, all instances are in the same diff --git a/src/mono_item.rs b/src/mono_item.rs index 539e3ac85076..51f35cbdee47 100644 --- a/src/mono_item.rs +++ b/src/mono_item.rs @@ -53,7 +53,7 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty()); self.linkage.set(base::linkage_to_gcc(linkage)); let decl = self.declare_fn(symbol_name, fn_abi); - //let attrs = self.tcx.codegen_fn_attrs(instance.def_id()); + //let attrs = self.tcx.codegen_instance_attrs(instance.def); attributes::from_fn_attrs(self, decl, instance); From 14c6e50d4740e13bf36b6c272485804ba9ad9117 Mon Sep 17 00:00:00 2001 From: Josh Simmons Date: Thu, 17 Jul 2025 09:11:44 +0200 Subject: [PATCH 0057/1134] Stabilize as_array_of_cells --- library/core/src/cell.rs | 4 ++-- tests/ui/rfcs/rfc-1789-as-cell/from-mut.rs | 2 -- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index d6d1bf2effae..583a3340c262 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -698,14 +698,14 @@ impl Cell<[T; N]> { /// # Examples /// /// ``` - /// #![feature(as_array_of_cells)] /// use std::cell::Cell; /// /// let mut array: [i32; 3] = [1, 2, 3]; /// let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array); /// let array_cell: &[Cell; 3] = cell_array.as_array_of_cells(); /// ``` - #[unstable(feature = "as_array_of_cells", issue = "88248")] + #[stable(feature = "as_array_of_cells", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "as_array_of_cells", since = "CURRENT_RUSTC_VERSION")] pub const fn as_array_of_cells(&self) -> &[Cell; N] { // SAFETY: `Cell` has the same memory layout as `T`. unsafe { &*(self as *const Cell<[T; N]> as *const [Cell; N]) } diff --git a/tests/ui/rfcs/rfc-1789-as-cell/from-mut.rs b/tests/ui/rfcs/rfc-1789-as-cell/from-mut.rs index d3b441fbe88f..700f875a4f63 100644 --- a/tests/ui/rfcs/rfc-1789-as-cell/from-mut.rs +++ b/tests/ui/rfcs/rfc-1789-as-cell/from-mut.rs @@ -1,7 +1,5 @@ //@ run-pass -#![feature(as_array_of_cells)] - use std::cell::Cell; fn main() { From 48df86f37ddf2904b60f31744e52f56234e4d95c Mon Sep 17 00:00:00 2001 From: yanglsh Date: Tue, 15 Jul 2025 22:55:41 +0800 Subject: [PATCH 0058/1134] fix: `match_single_binding` suggests wrongly inside binary expr --- .../src/matches/match_single_binding.rs | 36 ++++++--- clippy_utils/src/lib.rs | 80 +++++++++++-------- clippy_utils/src/source.rs | 34 +------- tests/ui/match_single_binding.fixed | 9 +++ tests/ui/match_single_binding.rs | 15 ++++ tests/ui/match_single_binding.stderr | 22 ++++- 6 files changed, 119 insertions(+), 77 deletions(-) diff --git a/clippy_lints/src/matches/match_single_binding.rs b/clippy_lints/src/matches/match_single_binding.rs index 9790e63821da..9bbc6042fe1a 100644 --- a/clippy_lints/src/matches/match_single_binding.rs +++ b/clippy_lints/src/matches/match_single_binding.rs @@ -2,10 +2,8 @@ use std::ops::ControlFlow; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::HirNode; -use clippy_utils::source::{ - RelativeIndent, indent_of, reindent_multiline_relative, snippet, snippet_block_with_context, snippet_with_context, -}; -use clippy_utils::{is_refutable, peel_blocks}; +use clippy_utils::source::{indent_of, reindent_multiline, snippet, snippet_block_with_context, snippet_with_context}; +use clippy_utils::{is_expr_identity_of_pat, is_refutable, peel_blocks}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def::Res; @@ -86,6 +84,18 @@ pub(crate) fn check<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], e snippet_with_context(cx, pat_span, ctxt, "..", &mut app).0 ), ), + None if is_expr_identity_of_pat(cx, arms[0].pat, ex, false) => { + span_lint_and_sugg( + cx, + MATCH_SINGLE_BINDING, + expr.span, + "this match could be replaced by its body itself", + "consider using the match body instead", + snippet_body, + Applicability::MachineApplicable, + ); + return; + }, None => { let sugg = sugg_with_curlies( cx, @@ -302,7 +312,7 @@ fn expr_in_nested_block(cx: &LateContext<'_>, match_expr: &Expr<'_>) -> bool { fn expr_must_have_curlies(cx: &LateContext<'_>, match_expr: &Expr<'_>) -> bool { let parent = cx.tcx.parent_hir_node(match_expr.hir_id); if let Node::Expr(Expr { - kind: ExprKind::Closure { .. }, + kind: ExprKind::Closure(..) | ExprKind::Binary(..), .. }) | Node::AnonConst(..) = parent @@ -319,15 +329,23 @@ fn expr_must_have_curlies(cx: &LateContext<'_>, match_expr: &Expr<'_>) -> bool { false } +fn indent_of_nth_line(snippet: &str, nth: usize) -> Option { + snippet + .lines() + .nth(nth) + .and_then(|s| s.find(|c: char| !c.is_whitespace())) +} + fn reindent_snippet_if_in_block(snippet_body: &str, has_assignment: bool) -> String { if has_assignment || !snippet_body.starts_with('{') { - return reindent_multiline_relative(snippet_body, true, RelativeIndent::Add(0)); + return reindent_multiline(snippet_body, true, indent_of_nth_line(snippet_body, 1)); } - reindent_multiline_relative( - snippet_body.trim_start_matches('{').trim_end_matches('}').trim(), + let snippet_body = snippet_body.trim_start_matches('{').trim_end_matches('}').trim(); + reindent_multiline( + snippet_body, false, - RelativeIndent::Sub(4), + indent_of_nth_line(snippet_body, 0).map(|indent| indent.saturating_sub(4)), ) } diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 8b9cd6a54dd6..febc13d89598 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -1900,39 +1900,6 @@ pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { /// /// Consider calling [`is_expr_untyped_identity_function`] or [`is_expr_identity_function`] instead. fn is_body_identity_function(cx: &LateContext<'_>, func: &Body<'_>) -> bool { - fn check_pat(cx: &LateContext<'_>, pat: &Pat<'_>, expr: &Expr<'_>) -> bool { - if cx - .typeck_results() - .pat_binding_modes() - .get(pat.hir_id) - .is_some_and(|mode| matches!(mode.0, ByRef::Yes(_))) - { - // If the parameter is `(x, y)` of type `&(T, T)`, or `[x, y]` of type `&[T; 2]`, then - // due to match ergonomics, the inner patterns become references. Don't consider this - // the identity function as that changes types. - return false; - } - - match (pat.kind, expr.kind) { - (PatKind::Binding(_, id, _, _), _) => { - path_to_local_id(expr, id) && cx.typeck_results().expr_adjustments(expr).is_empty() - }, - (PatKind::Tuple(pats, dotdot), ExprKind::Tup(tup)) - if dotdot.as_opt_usize().is_none() && pats.len() == tup.len() => - { - pats.iter().zip(tup).all(|(pat, expr)| check_pat(cx, pat, expr)) - }, - (PatKind::Slice(before, slice, after), ExprKind::Array(arr)) - if slice.is_none() && before.len() + after.len() == arr.len() => - { - (before.iter().chain(after)) - .zip(arr) - .all(|(pat, expr)| check_pat(cx, pat, expr)) - }, - _ => false, - } - } - let [param] = func.params else { return false; }; @@ -1965,11 +1932,56 @@ fn is_body_identity_function(cx: &LateContext<'_>, func: &Body<'_>) -> bool { return false; } }, - _ => return check_pat(cx, param.pat, expr), + _ => return is_expr_identity_of_pat(cx, param.pat, expr, true), } } } +/// Checks if the given expression is an identity representation of the given pattern: +/// * `x` is the identity representation of `x` +/// * `(x, y)` is the identity representation of `(x, y)` +/// * `[x, y]` is the identity representation of `[x, y]` +/// +/// Note that `by_hir` is used to determine bindings are checked by their `HirId` or by their name. +/// This can be useful when checking patterns in `let` bindings or `match` arms. +pub fn is_expr_identity_of_pat(cx: &LateContext<'_>, pat: &Pat<'_>, expr: &Expr<'_>, by_hir: bool) -> bool { + if cx + .typeck_results() + .pat_binding_modes() + .get(pat.hir_id) + .is_some_and(|mode| matches!(mode.0, ByRef::Yes(_))) + { + // If the parameter is `(x, y)` of type `&(T, T)`, or `[x, y]` of type `&[T; 2]`, then + // due to match ergonomics, the inner patterns become references. Don't consider this + // the identity function as that changes types. + return false; + } + + match (pat.kind, expr.kind) { + (PatKind::Binding(_, id, _, _), _) if by_hir => { + path_to_local_id(expr, id) && cx.typeck_results().expr_adjustments(expr).is_empty() + }, + (PatKind::Binding(_, _, ident, _), ExprKind::Path(QPath::Resolved(_, path))) => { + matches!(path.segments, [ segment] if segment.ident.name == ident.name) + }, + (PatKind::Tuple(pats, dotdot), ExprKind::Tup(tup)) + if dotdot.as_opt_usize().is_none() && pats.len() == tup.len() => + { + pats.iter() + .zip(tup) + .all(|(pat, expr)| is_expr_identity_of_pat(cx, pat, expr, by_hir)) + }, + (PatKind::Slice(before, slice, after), ExprKind::Array(arr)) + if slice.is_none() && before.len() + after.len() == arr.len() => + { + (before.iter().chain(after)) + .zip(arr) + .all(|(pat, expr)| is_expr_identity_of_pat(cx, pat, expr, by_hir)) + }, + _ => false, + } +} + /// This is the same as [`is_expr_identity_function`], but does not consider closures /// with type annotations for its bindings (or similar) as identity functions: /// * `|x: u8| x` diff --git a/clippy_utils/src/source.rs b/clippy_utils/src/source.rs index b490902429f5..7f2bf99daff2 100644 --- a/clippy_utils/src/source.rs +++ b/clippy_utils/src/source.rs @@ -18,7 +18,7 @@ use rustc_span::{ }; use std::borrow::Cow; use std::fmt; -use std::ops::{Add, Deref, Index, Range}; +use std::ops::{Deref, Index, Range}; pub trait HasSession { fn sess(&self) -> &Session; @@ -476,38 +476,6 @@ pub fn position_before_rarrow(s: &str) -> Option { }) } -pub enum RelativeIndent { - Add(usize), - Sub(usize), -} - -impl Add for usize { - type Output = usize; - - fn add(self, rhs: RelativeIndent) -> Self::Output { - match rhs { - RelativeIndent::Add(n) => self + n, - RelativeIndent::Sub(n) => self.saturating_sub(n), - } - } -} - -/// Reindents a multiline string with possibility of ignoring the first line and relative -/// indentation. -pub fn reindent_multiline_relative(s: &str, ignore_first: bool, relative_indent: RelativeIndent) -> String { - fn indent_of_string(s: &str) -> usize { - s.find(|c: char| !c.is_whitespace()).unwrap_or(0) - } - - let mut indent = 0; - if let Some(line) = s.lines().nth(usize::from(ignore_first)) { - let line_indent = indent_of_string(line); - indent = line_indent + relative_indent; - } - - reindent_multiline(s, ignore_first, Some(indent)) -} - /// Reindent a multiline string with possibility of ignoring the first line. pub fn reindent_multiline(s: &str, ignore_first: bool, indent: Option) -> String { let s_space = reindent_multiline_inner(s, ignore_first, indent, ' '); diff --git a/tests/ui/match_single_binding.fixed b/tests/ui/match_single_binding.fixed index d8d865ee44cf..e29fb87dbc30 100644 --- a/tests/ui/match_single_binding.fixed +++ b/tests/ui/match_single_binding.fixed @@ -257,3 +257,12 @@ mod issue15018 { } } } + +#[allow(clippy::short_circuit_statement)] +fn issue15269(a: usize, b: usize, c: usize) -> bool { + a < b + && b < c; + + a < b + && b < c +} diff --git a/tests/ui/match_single_binding.rs b/tests/ui/match_single_binding.rs index ecff945fb913..ede1ab32beb5 100644 --- a/tests/ui/match_single_binding.rs +++ b/tests/ui/match_single_binding.rs @@ -328,3 +328,18 @@ mod issue15018 { } } } + +#[allow(clippy::short_circuit_statement)] +fn issue15269(a: usize, b: usize, c: usize) -> bool { + a < b + && match b { + //~^ match_single_binding + b => b < c, + }; + + a < b + && match (a, b) { + //~^ match_single_binding + (a, b) => b < c, + } +} diff --git a/tests/ui/match_single_binding.stderr b/tests/ui/match_single_binding.stderr index 789626de6035..eea71777890e 100644 --- a/tests/ui/match_single_binding.stderr +++ b/tests/ui/match_single_binding.stderr @@ -505,5 +505,25 @@ LL ~ let (x, y, z) = (a, b, c); LL + println!("{} {} {}", x, y, z); | -error: aborting due to 35 previous errors +error: this match could be replaced by its body itself + --> tests/ui/match_single_binding.rs:335:12 + | +LL | && match b { + | ____________^ +LL | | +LL | | b => b < c, +LL | | }; + | |_________^ help: consider using the match body instead: `b < c` + +error: this match could be replaced by its body itself + --> tests/ui/match_single_binding.rs:341:12 + | +LL | && match (a, b) { + | ____________^ +LL | | +LL | | (a, b) => b < c, +LL | | } + | |_________^ help: consider using the match body instead: `b < c` + +error: aborting due to 37 previous errors From af19ff8cc89bb6a010faaf110eb63e1fbce49b1a Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Thu, 17 Jul 2025 19:16:39 +0200 Subject: [PATCH 0059/1134] fix `collapsable_if` when the inner `if` is in parens --- clippy_lints/src/collapsible_if.rs | 51 +++++++++++++++++++++++++++++- tests/ui/collapsible_if.fixed | 8 +++++ tests/ui/collapsible_if.rs | 9 ++++++ tests/ui/collapsible_if.stderr | 20 +++++++++++- 4 files changed, 86 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/collapsible_if.rs b/clippy_lints/src/collapsible_if.rs index 1854d86c53b2..da0f0b2f1be9 100644 --- a/clippy_lints/src/collapsible_if.rs +++ b/clippy_lints/src/collapsible_if.rs @@ -187,7 +187,8 @@ impl CollapsibleIf { .with_leading_whitespace(cx) .into_span() }; - let inner_if = inner.span.split_at(2).0; + let (paren_start, inner_if_span, paren_end) = peel_parens(cx.tcx.sess.source_map(), inner.span); + let inner_if = inner_if_span.split_at(2).0; let mut sugg = vec![ // Remove the outer then block `{` (then_open_bracket, String::new()), @@ -196,6 +197,17 @@ impl CollapsibleIf { // Replace inner `if` by `&&` (inner_if, String::from("&&")), ]; + + if !paren_start.is_empty() { + // Remove any leading parentheses '(' + sugg.push((paren_start, String::new())); + } + + if !paren_end.is_empty() { + // Remove any trailing parentheses ')' + sugg.push((paren_end, String::new())); + } + sugg.extend(parens_around(check)); sugg.extend(parens_around(check_inner)); @@ -285,3 +297,40 @@ fn span_extract_keyword(sm: &SourceMap, span: Span, keyword: &str) -> Option (Span, Span, Span) { + use crate::rustc_span::Pos; + use rustc_span::SpanData; + + let start = span.shrink_to_lo(); + let end = span.shrink_to_hi(); + + loop { + let data = span.data(); + let snippet = sm.span_to_snippet(span).unwrap(); + + let trim_start = snippet.len() - snippet.trim_start().len(); + let trim_end = snippet.len() - snippet.trim_end().len(); + + let trimmed = snippet.trim(); + + if trimmed.starts_with('(') && trimmed.ends_with(')') { + // Try to remove one layer of parens by adjusting the span + span = SpanData { + lo: data.lo + BytePos::from_usize(trim_start + 1), + hi: data.hi - BytePos::from_usize(trim_end + 1), + ctxt: data.ctxt, + parent: data.parent, + } + .span(); + + continue; + } + + break; + } + + (start.with_hi(span.lo()), + span, + end.with_lo(span.hi())) +} diff --git a/tests/ui/collapsible_if.fixed b/tests/ui/collapsible_if.fixed index 77bc791ea8e9..f7c840c4cc1e 100644 --- a/tests/ui/collapsible_if.fixed +++ b/tests/ui/collapsible_if.fixed @@ -163,3 +163,11 @@ fn issue14799() { if true {} }; } + +fn in_parens() { + if true + && true { + println!("In parens, linted"); + } + //~^^^^^ collapsible_if +} diff --git a/tests/ui/collapsible_if.rs b/tests/ui/collapsible_if.rs index d30df157d5eb..4faebcb0ca0d 100644 --- a/tests/ui/collapsible_if.rs +++ b/tests/ui/collapsible_if.rs @@ -173,3 +173,12 @@ fn issue14799() { if true {} }; } + +fn in_parens() { + if true { + (if true { + println!("In parens, linted"); + }) + } + //~^^^^^ collapsible_if +} diff --git a/tests/ui/collapsible_if.stderr b/tests/ui/collapsible_if.stderr index 32c6b0194030..a685cc2e9291 100644 --- a/tests/ui/collapsible_if.stderr +++ b/tests/ui/collapsible_if.stderr @@ -190,5 +190,23 @@ LL | // This is a comment, do not collapse code to it LL ~ ; 3 | -error: aborting due to 11 previous errors +error: this `if` statement can be collapsed + --> tests/ui/collapsible_if.rs:178:5 + | +LL | / if true { +LL | | (if true { +LL | | println!("In parens, linted"); +LL | | }) +LL | | } + | |_____^ + | +help: collapse nested if block + | +LL ~ if true +LL ~ && true { +LL | println!("In parens, linted"); +LL ~ } + | + +error: aborting due to 12 previous errors From d088fb739b40c083d3dd74185c4e1b05c86839ce Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 18 Jul 2025 18:31:20 +0200 Subject: [PATCH 0060/1134] Merge commit 'f682d09eefc6700b9e5851ef193847959acf4fac' into subtree-update_cg_gcc_2025-07-18 --- .github/workflows/m68k.yml | 40 +- .github/workflows/release.yml | 3 +- build_system/build_sysroot/Cargo.lock | 502 -------------------------- build_system/build_sysroot/Cargo.toml | 39 -- build_system/build_sysroot/lib.rs | 1 - build_system/src/build.rs | 38 +- build_system/src/config.rs | 5 - build_system/src/utils.rs | 13 - doc/tips.md | 6 +- example/mini_core_hello_world.rs | 16 +- rust-toolchain | 2 +- src/builder.rs | 6 +- src/lib.rs | 7 +- src/mono_item.rs | 2 +- tests/failing-ui-tests.txt | 2 + tests/run/asm.rs | 1 + tests/run/float.rs | 16 +- tests/run/int.rs | 2 - tests/run/volatile.rs | 3 +- tests/run/volatile2.rs | 6 +- 20 files changed, 85 insertions(+), 625 deletions(-) delete mode 100644 build_system/build_sysroot/Cargo.lock delete mode 100644 build_system/build_sysroot/Cargo.toml delete mode 100644 build_system/build_sysroot/lib.rs diff --git a/.github/workflows/m68k.yml b/.github/workflows/m68k.yml index 245bee7f2a3b..759d0d59e268 100644 --- a/.github/workflows/m68k.yml +++ b/.github/workflows/m68k.yml @@ -14,8 +14,6 @@ permissions: env: # Enable backtraces for easier debugging RUST_BACKTRACE: 1 - # TODO: remove when confish.sh is removed. - OVERWRITE_TARGET_TRIPLE: m68k-unknown-linux-gnu jobs: build: @@ -59,14 +57,12 @@ jobs: - name: Setup path to libgccjit run: | - sudo dpkg -i gcc-m68k-15.deb + sudo dpkg --force-overwrite -i gcc-m68k-15.deb echo 'gcc-path = "/usr/lib/"' > config.toml - name: Set env run: | echo "workspace="$GITHUB_WORKSPACE >> $GITHUB_ENV - - #- name: Cache rust repository ## We only clone the rust repository for rustc tests @@ -86,16 +82,20 @@ jobs: - name: Build sample project with target defined as JSON spec run: | ./y.sh prepare --only-libcore --cross - ./y.sh build --sysroot --features compiler_builtins/no-f16-f128 --target-triple m68k-unknown-linux-gnu --target ${{ github.workspace }}/target_specs/m68k-unknown-linux-gnu.json - ./y.sh cargo build --manifest-path=./tests/hello-world/Cargo.toml --target ${{ github.workspace }}/target_specs/m68k-unknown-linux-gnu.json + ./y.sh build --sysroot --features compiler-builtins-no-f16-f128 --target-triple m68k-unknown-linux-gnu --target ${{ github.workspace }}/target_specs/m68k-unknown-linux-gnu.json + CG_RUSTFLAGS="-Clinker=m68k-unknown-linux-gnu-gcc" ./y.sh cargo build --manifest-path=./tests/hello-world/Cargo.toml --target ${{ github.workspace }}/target_specs/m68k-unknown-linux-gnu.json ./y.sh clean all - name: Build run: | ./y.sh prepare --only-libcore --cross - ./y.sh build --sysroot --features compiler_builtins/no-f16-f128 --target-triple m68k-unknown-linux-gnu - ./y.sh test --mini-tests - CG_GCC_TEST_TARGET=m68k-unknown-linux-gnu ./y.sh test --cargo-tests + ./y.sh build --sysroot --features compiler-builtins-no-f16-f128 --target-triple m68k-unknown-linux-gnu + ./y.sh test --mini-tests --target-triple m68k-unknown-linux-gnu + # FIXME: since https://github.com/rust-lang/rust/pull/140809, we cannot run programs for architectures not + # supported by the object crate, since this adds a dependency on symbols.o for the panic runtime. + # And as such, a wrong order of the object files in the linker command now fails with an undefined reference + # to some symbols like __rustc::rust_panic. + #CG_GCC_TEST_TARGET=m68k-unknown-linux-gnu ./y.sh test --cargo-tests --target-triple m68k-unknown-linux-gnu ./y.sh clean all - name: Prepare dependencies @@ -104,9 +104,23 @@ jobs: git config --global user.name "User" ./y.sh prepare --cross - - name: Run tests - run: | - ./y.sh test --release --clean --build-sysroot --sysroot-features compiler_builtins/no-f16-f128 ${{ matrix.commands }} + # FIXME: We cannot run programs for architectures not supported by the object crate. See comment above. + #- name: Run tests + #run: | + #./y.sh test --target-triple m68k-unknown-linux-gnu --release --clean --build-sysroot --sysroot-features compiler-builtins-no-f16-f128 ${{ matrix.commands }} + + # FIXME: We cannot run programs for architectures not supported by the object crate. See comment above. + #- name: Run Hello World! + #run: | + #./y.sh build --target-triple m68k-unknown-linux-gnu + + #vm_dir=$(pwd)/vm + #cd tests/hello-world + #CG_RUSTFLAGS="-Clinker=m68k-unknown-linux-gnu-gcc" ../../y.sh cargo build --target m68k-unknown-linux-gnu + #sudo cp target/m68k-unknown-linux-gnu/debug/hello_world $vm_dir/home/ + #sudo chroot $vm_dir qemu-m68k-static /home/hello_world > hello_world_stdout + #expected_output="40" + #test $(cat hello_world_stdout) == $expected_output || (echo "Output differs. Actual output: $(cat hello_world_stdout)"; exit 1) # Summary job for the merge queue. # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1d8eaf9a141f..b7e2583aad39 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -78,7 +78,8 @@ jobs: - name: Run tests run: | # FIXME(antoyo): we cannot enable LTO for stdarch tests currently because of some failing LTO tests using proc-macros. - echo -n 'lto = "fat"' >> build_system/build_sysroot/Cargo.toml + # FIXME(antoyo): this should probably not be needed since we embed the LTO bitcode. + printf '[profile.release]\nlto = "fat"\n' >> build/build_sysroot/sysroot_src/library/Cargo.toml EMBED_LTO_BITCODE=1 ./y.sh test --release --clean --release-sysroot --build-sysroot --keep-lto-tests ${{ matrix.commands }} - name: Run y.sh cargo build diff --git a/build_system/build_sysroot/Cargo.lock b/build_system/build_sysroot/Cargo.lock deleted file mode 100644 index 0c75977ee798..000000000000 --- a/build_system/build_sysroot/Cargo.lock +++ /dev/null @@ -1,502 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" -dependencies = [ - "compiler_builtins", - "gimli", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "adler2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "alloc" -version = "0.0.0" -dependencies = [ - "compiler_builtins", - "core", -] - -[[package]] -name = "alloctests" -version = "0.0.0" -dependencies = [ - "rand", - "rand_xorshift", -] - -[[package]] -name = "cc" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aeb932158bd710538c73702db6945cb68a8fb08c519e6e12706b94263b36db8" -dependencies = [ - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "compiler_builtins" -version = "0.1.160" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6376049cfa92c0aa8b9ac95fae22184b981c658208d4ed8a1dc553cd83612895" -dependencies = [ - "cc", - "rustc-std-workspace-core", -] - -[[package]] -name = "core" -version = "0.0.0" - -[[package]] -name = "coretests" -version = "0.0.0" -dependencies = [ - "rand", - "rand_xorshift", -] - -[[package]] -name = "dlmalloc" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cff88b751e7a276c4ab0e222c3f355190adc6dde9ce39c851db39da34990df7" -dependencies = [ - "cfg-if", - "compiler_builtins", - "libc", - "rustc-std-workspace-core", - "windows-sys", -] - -[[package]] -name = "fortanix-sgx-abi" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57cafc2274c10fab234f176b25903ce17e690fca7597090d50880e047a0389c5" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "getopts" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" -dependencies = [ - "rustc-std-workspace-core", - "rustc-std-workspace-std", - "unicode-width", -] - -[[package]] -name = "gimli" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "hashbrown" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84b26c544d002229e640969970a2e74021aadf6e2f96372b9c58eff97de08eb3" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "hermit-abi" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f154ce46856750ed433c8649605bf7ed2de3bc35fd9d2a9f30cddd873c80cb08" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "libc" -version = "0.2.172" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" -dependencies = [ - "rustc-std-workspace-core", -] - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a" -dependencies = [ - "adler2", - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "object" -version = "0.36.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" -dependencies = [ - "compiler_builtins", - "memchr", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "panic_abort" -version = "0.0.0" -dependencies = [ - "alloc", - "compiler_builtins", - "core", - "libc", -] - -[[package]] -name = "panic_unwind" -version = "0.0.0" -dependencies = [ - "alloc", - "cfg-if", - "compiler_builtins", - "core", - "libc", - "unwind", -] - -[[package]] -name = "proc_macro" -version = "0.0.0" -dependencies = [ - "core", - "rustc-literal-escaper", - "std", -] - -[[package]] -name = "profiler_builtins" -version = "0.0.0" -dependencies = [ - "cc", -] - -[[package]] -name = "r-efi" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "r-efi-alloc" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e43c53ff1a01d423d1cb762fd991de07d32965ff0ca2e4f80444ac7804198203" -dependencies = [ - "compiler_builtins", - "r-efi", - "rustc-std-workspace-core", -] - -[[package]] -name = "rand" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" -dependencies = [ - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" - -[[package]] -name = "rand_xorshift" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" -dependencies = [ - "rand_core", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "rustc-literal-escaper" -version = "0.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0041b6238913c41fe704213a4a9329e2f685a156d1781998128b4149c230ad04" -dependencies = [ - "rustc-std-workspace-std", -] - -[[package]] -name = "rustc-std-workspace-alloc" -version = "1.99.0" -dependencies = [ - "alloc", -] - -[[package]] -name = "rustc-std-workspace-core" -version = "1.99.0" -dependencies = [ - "core", -] - -[[package]] -name = "rustc-std-workspace-std" -version = "1.99.0" -dependencies = [ - "std", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "std" -version = "0.0.0" -dependencies = [ - "addr2line", - "alloc", - "cfg-if", - "compiler_builtins", - "core", - "dlmalloc", - "fortanix-sgx-abi", - "hashbrown", - "hermit-abi", - "libc", - "miniz_oxide", - "object", - "panic_abort", - "panic_unwind", - "r-efi", - "r-efi-alloc", - "rand", - "rand_xorshift", - "rustc-demangle", - "std_detect", - "unwind", - "wasi", - "windows-targets 0.0.0", -] - -[[package]] -name = "std_detect" -version = "0.1.5" -dependencies = [ - "cfg-if", - "compiler_builtins", - "libc", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "sysroot" -version = "0.0.0" -dependencies = [ - "proc_macro", - "profiler_builtins", - "std", - "test", -] - -[[package]] -name = "test" -version = "0.0.0" -dependencies = [ - "core", - "getopts", - "libc", - "std", -] - -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", - "rustc-std-workspace-std", -] - -[[package]] -name = "unwind" -version = "0.0.0" -dependencies = [ - "cfg-if", - "compiler_builtins", - "core", - "libc", - "unwinding", -] - -[[package]] -name = "unwinding" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8393f2782b6060a807337ff353780c1ca15206f9ba2424df18cb6e733bd7b345" -dependencies = [ - "compiler_builtins", - "gimli", - "rustc-std-workspace-core", -] - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.0.0" - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" diff --git a/build_system/build_sysroot/Cargo.toml b/build_system/build_sysroot/Cargo.toml deleted file mode 100644 index 29a3bcec304c..000000000000 --- a/build_system/build_sysroot/Cargo.toml +++ /dev/null @@ -1,39 +0,0 @@ -[package] -authors = ["rustc_codegen_gcc devs"] -name = "sysroot" -version = "0.0.0" -resolver = "2" - -[dependencies] -core = { path = "./sysroot_src/library/core" } -compiler_builtins = { path = "./sysroot_src/library/compiler-builtins/compiler-builtins" } -alloc = { path = "./sysroot_src/library/alloc" } -std = { path = "./sysroot_src/library/std", features = ["panic_unwind", "backtrace"] } -test = { path = "./sysroot_src/library/test" } -proc_macro = { path = "./sysroot_src/library/proc_macro" } - -[patch.crates-io] -rustc-std-workspace-core = { path = "./sysroot_src/library/rustc-std-workspace-core" } -rustc-std-workspace-alloc = { path = "./sysroot_src/library/rustc-std-workspace-alloc" } -rustc-std-workspace-std = { path = "./sysroot_src/library/rustc-std-workspace-std" } -compiler_builtins = { path = "./sysroot_src/library/compiler-builtins/compiler-builtins" } - -# For compiler-builtins we always use a high number of codegen units. -# The goal here is to place every single intrinsic into its own object -# file to avoid symbol clashes with the system libgcc if possible. Note -# that this number doesn't actually produce this many object files, we -# just don't create more than this number of object files. -# -# It's a bit of a bummer that we have to pass this here, unfortunately. -# Ideally this would be specified through an env var to Cargo so Cargo -# knows how many CGUs are for this specific crate, but for now -# per-crate configuration isn't specifiable in the environment. -[profile.dev.package.compiler_builtins] -codegen-units = 10000 - -[profile.release.package.compiler_builtins] -codegen-units = 10000 - -[profile.release] -debug = "limited" -#lto = "fat" # TODO(antoyo): re-enable when the failing LTO tests regarding proc-macros are fixed. diff --git a/build_system/build_sysroot/lib.rs b/build_system/build_sysroot/lib.rs deleted file mode 100644 index 0c9ac1ac8e4b..000000000000 --- a/build_system/build_sysroot/lib.rs +++ /dev/null @@ -1 +0,0 @@ -#![no_std] diff --git a/build_system/src/build.rs b/build_system/src/build.rs index ecc4c1b2fe22..94b40319f4a7 100644 --- a/build_system/src/build.rs +++ b/build_system/src/build.rs @@ -5,7 +5,7 @@ use std::path::Path; use crate::config::{Channel, ConfigInfo}; use crate::utils::{ - copy_file, create_dir, get_sysroot_dir, run_command, run_command_with_output_and_env, walk_dir, + create_dir, get_sysroot_dir, run_command, run_command_with_output_and_env, walk_dir, }; #[derive(Default)] @@ -53,11 +53,11 @@ impl BuildArg { } } -fn cleanup_sysroot_previous_build(start_dir: &Path) { +fn cleanup_sysroot_previous_build(library_dir: &Path) { // Cleanup for previous run // Clean target dir except for build scripts and incremental cache let _ = walk_dir( - start_dir.join("target"), + library_dir.join("target"), &mut |dir: &Path| { for top in &["debug", "release"] { let _ = fs::remove_dir_all(dir.join(top).join("build")); @@ -95,31 +95,13 @@ fn cleanup_sysroot_previous_build(start_dir: &Path) { &mut |_| Ok(()), false, ); - - let _ = fs::remove_file(start_dir.join("Cargo.lock")); - let _ = fs::remove_file(start_dir.join("test_target/Cargo.lock")); - let _ = fs::remove_dir_all(start_dir.join("sysroot")); -} - -pub fn create_build_sysroot_content(start_dir: &Path) -> Result<(), String> { - if !start_dir.is_dir() { - create_dir(start_dir)?; - } - copy_file("build_system/build_sysroot/Cargo.toml", start_dir.join("Cargo.toml"))?; - copy_file("build_system/build_sysroot/Cargo.lock", start_dir.join("Cargo.lock"))?; - - let src_dir = start_dir.join("src"); - if !src_dir.is_dir() { - create_dir(&src_dir)?; - } - copy_file("build_system/build_sysroot/lib.rs", start_dir.join("src/lib.rs")) } pub fn build_sysroot(env: &HashMap, config: &ConfigInfo) -> Result<(), String> { let start_dir = get_sysroot_dir(); - cleanup_sysroot_previous_build(&start_dir); - create_build_sysroot_content(&start_dir)?; + let library_dir = start_dir.join("sysroot_src").join("library"); + cleanup_sysroot_previous_build(&library_dir); // Builds libs let mut rustflags = env.get("RUSTFLAGS").cloned().unwrap_or_default(); @@ -157,9 +139,13 @@ pub fn build_sysroot(env: &HashMap, config: &ConfigInfo) -> Resu rustflags.push_str(&cg_rustflags); } + args.push(&"--features"); + args.push(&"backtrace"); + let mut env = env.clone(); env.insert("RUSTFLAGS".to_string(), rustflags); - run_command_with_output_and_env(&args, Some(&start_dir), Some(&env))?; + let sysroot_dir = library_dir.join("sysroot"); + run_command_with_output_and_env(&args, Some(&sysroot_dir), Some(&env))?; // Copy files to sysroot let sysroot_path = start_dir.join(format!("sysroot/lib/rustlib/{}/lib/", config.target_triple)); @@ -169,7 +155,7 @@ pub fn build_sysroot(env: &HashMap, config: &ConfigInfo) -> Resu run_command(&[&"cp", &"-r", &dir_to_copy, &sysroot_path], None).map(|_| ()) }; walk_dir( - start_dir.join(format!("target/{}/{}/deps", config.target_triple, channel)), + library_dir.join(format!("target/{}/{}/deps", config.target_triple, channel)), &mut copier.clone(), &mut copier, false, @@ -178,7 +164,7 @@ pub fn build_sysroot(env: &HashMap, config: &ConfigInfo) -> Resu // Copy the source files to the sysroot (Rust for Linux needs this). let sysroot_src_path = start_dir.join("sysroot/lib/rustlib/src/rust"); create_dir(&sysroot_src_path)?; - run_command(&[&"cp", &"-r", &start_dir.join("sysroot_src/library/"), &sysroot_src_path], None)?; + run_command(&[&"cp", &"-r", &library_dir, &sysroot_src_path], None)?; Ok(()) } diff --git a/build_system/src/config.rs b/build_system/src/config.rs index 650c030ca539..a5f802e293a9 100644 --- a/build_system/src/config.rs +++ b/build_system/src/config.rs @@ -352,11 +352,6 @@ impl ConfigInfo { None => return Err("no host found".to_string()), }; - if self.target_triple.is_empty() - && let Some(overwrite) = env.get("OVERWRITE_TARGET_TRIPLE") - { - self.target_triple = overwrite.clone(); - } if self.target_triple.is_empty() { self.target_triple = self.host_triple.clone(); } diff --git a/build_system/src/utils.rs b/build_system/src/utils.rs index d77707d5f17a..fc948c54b24a 100644 --- a/build_system/src/utils.rs +++ b/build_system/src/utils.rs @@ -303,19 +303,6 @@ pub fn create_dir>(path: P) -> Result<(), String> { }) } -pub fn copy_file, T: AsRef>(from: F, to: T) -> Result<(), String> { - fs::copy(&from, &to) - .map_err(|error| { - format!( - "Failed to copy file `{}` into `{}`: {:?}", - from.as_ref().display(), - to.as_ref().display(), - error - ) - }) - .map(|_| ()) -} - /// This function differs from `git_clone` in how it handles *where* the repository will be cloned. /// In `git_clone`, it is cloned in the provided path. In this function, the path you provide is /// the parent folder. So if you pass "a" as folder and try to clone "b.git", it will be cloned into diff --git a/doc/tips.md b/doc/tips.md index 86c22db186e0..e62c3402a292 100644 --- a/doc/tips.md +++ b/doc/tips.md @@ -62,14 +62,14 @@ generate it in [gimple.md](./doc/gimple.md). * Run `./y.sh prepare --cross` so that the sysroot is patched for the cross-compiling case. * Set the path to the cross-compiling libgccjit in `gcc-path` (in `config.toml`). - * Make sure you have the linker for your target (for instance `m68k-unknown-linux-gnu-gcc`) in your `$PATH`. Currently, the linker name is hardcoded as being `$TARGET-gcc`. Specify the target when building the sysroot: `./y.sh build --sysroot --target-triple m68k-unknown-linux-gnu`. - * Build your project by specifying the target: `OVERWRITE_TARGET_TRIPLE=m68k-unknown-linux-gnu ../y.sh cargo build --target m68k-unknown-linux-gnu`. + * Make sure you have the linker for your target (for instance `m68k-unknown-linux-gnu-gcc`) in your `$PATH`. You can specify which linker to use via `CG_RUSTFLAGS="-Clinker="`, for instance: `CG_RUSTFLAGS="-Clinker=m68k-unknown-linux-gnu-gcc"`. Specify the target when building the sysroot: `./y.sh build --sysroot --target-triple m68k-unknown-linux-gnu`. + * Build your project by specifying the target and the linker to use: `CG_RUSTFLAGS="-Clinker=m68k-unknown-linux-gnu-gcc" ../y.sh cargo build --target m68k-unknown-linux-gnu`. If the target is not yet supported by the Rust compiler, create a [target specification file](https://docs.rust-embedded.org/embedonomicon/custom-target.html) (note that the `arch` specified in this file must be supported by the rust compiler). Then, you can use it the following way: * Add the target specification file using `--target` as an **absolute** path to build the sysroot: `./y.sh build --sysroot --target-triple m68k-unknown-linux-gnu --target $(pwd)/m68k-unknown-linux-gnu.json` - * Build your project by specifying the target specification file: `OVERWRITE_TARGET_TRIPLE=m68k-unknown-linux-gnu ../y.sh cargo build --target path/to/m68k-unknown-linux-gnu.json`. + * Build your project by specifying the target specification file: `../y.sh cargo build --target path/to/m68k-unknown-linux-gnu.json`. If you get the following error: diff --git a/example/mini_core_hello_world.rs b/example/mini_core_hello_world.rs index 6b6f71edaf8c..358f265a6b85 100644 --- a/example/mini_core_hello_world.rs +++ b/example/mini_core_hello_world.rs @@ -6,7 +6,7 @@ )] #![no_core] #![allow(dead_code, internal_features, non_camel_case_types)] -#![rustfmt::skip] +#![rustfmt_skip] extern crate mini_core; @@ -198,10 +198,24 @@ fn main() { assert_eq!(intrinsics::align_of::() as u8, 2); assert_eq!(intrinsics::align_of_val(&a) as u8, intrinsics::align_of::<&str>() as u8); +<<<<<<< HEAD assert!(!const { intrinsics::needs_drop::() }); assert!(!const { intrinsics::needs_drop::<[u8]>() }); assert!(const { intrinsics::needs_drop::() }); assert!(const { intrinsics::needs_drop::() }); +======= + /* + * TODO: re-enable in the next sync. + let u8_needs_drop = const { intrinsics::needs_drop::() }; + assert!(!u8_needs_drop); + let slice_needs_drop = const { intrinsics::needs_drop::<[u8]>() }; + assert!(!slice_needs_drop); + let noisy_drop = const { intrinsics::needs_drop::() }; + assert!(noisy_drop); + let noisy_unsized_drop = const { intrinsics::needs_drop::() }; + assert!(noisy_unsized_drop); + */ +>>>>>>> f682d09eefc6700b9e5851ef193847959acf4fac Unique { pointer: 0 as *const &str, diff --git a/rust-toolchain b/rust-toolchain index bccbc6cd2c5c..2fe8ec4647fa 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2025-06-28" +channel = "nightly-2025-07-04" components = ["rust-src", "rustc-dev", "llvm-tools-preview"] diff --git a/src/builder.rs b/src/builder.rs index 28d1ec7d8956..a4ec4bf8deac 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -971,7 +971,11 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn volatile_load(&mut self, ty: Type<'gcc>, ptr: RValue<'gcc>) -> RValue<'gcc> { let ptr = self.context.new_cast(self.location, ptr, ty.make_volatile().make_pointer()); - ptr.dereference(self.location).to_rvalue() + // (FractalFir): We insert a local here, to ensure this volatile load can't move across + // blocks. + let local = self.current_func().new_local(self.location, ty, "volatile_tmp"); + self.block.add_assignment(self.location, local, ptr.dereference(self.location).to_rvalue()); + local.to_rvalue() } fn atomic_load( diff --git a/src/lib.rs b/src/lib.rs index d81bcc597756..af416929ea73 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -273,6 +273,10 @@ fn new_context<'gcc, 'tcx>(tcx: TyCtxt<'tcx>) -> Context<'gcc> { } impl ExtraBackendMethods for GccCodegenBackend { + fn supports_parallel(&self) -> bool { + false + } + fn codegen_allocator( &self, tcx: TyCtxt<'_>, @@ -341,8 +345,7 @@ impl Deref for SyncContext { } unsafe impl Send for SyncContext {} -// FIXME(antoyo): that shouldn't be Sync. Parallel compilation is currently disabled with "-Zno-parallel-llvm". -// TODO: disable it here by returning false in CodegenBackend::supports_parallel(). +// FIXME(antoyo): that shouldn't be Sync. Parallel compilation is currently disabled with "CodegenBackend::supports_parallel()". unsafe impl Sync for SyncContext {} impl WriteBackendMethods for GccCodegenBackend { diff --git a/src/mono_item.rs b/src/mono_item.rs index 51f35cbdee47..ff188c437dae 100644 --- a/src/mono_item.rs +++ b/src/mono_item.rs @@ -64,7 +64,7 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) { #[cfg(feature = "master")] decl.add_attribute(FnAttribute::Visibility(gccjit::Visibility::Hidden)); - } else { + } else if visibility != Visibility::Default { #[cfg(feature = "master")] decl.add_attribute(FnAttribute::Visibility(base::visibility_to_gcc(visibility))); } diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index 544d0bfc7105..6979c04d5343 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -80,3 +80,5 @@ tests/ui/uninhabited/uninhabited-transparent-return-abi.rs tests/ui/coroutine/panic-drops-resume.rs tests/ui/coroutine/panic-drops.rs tests/ui/coroutine/panic-safe.rs +tests/ui/process/nofile-limit.rs +tests/ui/simd/intrinsic/generic-arithmetic-pass.rs diff --git a/tests/run/asm.rs b/tests/run/asm.rs index 2dbf43be664d..9b15a28d8298 100644 --- a/tests/run/asm.rs +++ b/tests/run/asm.rs @@ -16,6 +16,7 @@ add_asm: ret" ); +#[cfg(target_arch = "x86_64")] extern "C" { fn add_asm(a: i64, b: i64) -> i64; } diff --git a/tests/run/float.rs b/tests/run/float.rs index 424fa1cf4ad5..df555f383fe0 100644 --- a/tests/run/float.rs +++ b/tests/run/float.rs @@ -3,8 +3,6 @@ // Run-time: // status: 0 -#![feature(const_black_box)] - fn main() { use std::hint::black_box; @@ -15,14 +13,14 @@ fn main() { }}; } - check!(i32, (black_box(0.0f32) as i32)); + check!(i32, black_box(0.0f32) as i32); - check!(u64, (black_box(f32::NAN) as u64)); - check!(u128, (black_box(f32::NAN) as u128)); + check!(u64, black_box(f32::NAN) as u64); + check!(u128, black_box(f32::NAN) as u128); - check!(i64, (black_box(f64::NAN) as i64)); - check!(u64, (black_box(f64::NAN) as u64)); + check!(i64, black_box(f64::NAN) as i64); + check!(u64, black_box(f64::NAN) as u64); - check!(i16, (black_box(f32::MIN) as i16)); - check!(i16, (black_box(f32::MAX) as i16)); + check!(i16, black_box(f32::MIN) as i16); + check!(i16, black_box(f32::MAX) as i16); } diff --git a/tests/run/int.rs b/tests/run/int.rs index 47b5dea46f8d..e20ecc23679d 100644 --- a/tests/run/int.rs +++ b/tests/run/int.rs @@ -3,8 +3,6 @@ // Run-time: // status: 0 -#![feature(const_black_box)] - fn main() { use std::hint::black_box; diff --git a/tests/run/volatile.rs b/tests/run/volatile.rs index 8b0433125936..94a7bdc5c066 100644 --- a/tests/run/volatile.rs +++ b/tests/run/volatile.rs @@ -5,13 +5,14 @@ use std::mem::MaybeUninit; +#[allow(dead_code)] #[derive(Debug)] struct Struct { pointer: *const (), func: unsafe fn(*const ()), } -fn func(ptr: *const ()) { +fn func(_ptr: *const ()) { } fn main() { diff --git a/tests/run/volatile2.rs b/tests/run/volatile2.rs index a177b817ab35..bdcb82598789 100644 --- a/tests/run/volatile2.rs +++ b/tests/run/volatile2.rs @@ -6,8 +6,6 @@ mod libc { #[link(name = "c")] extern "C" { - pub fn puts(s: *const u8) -> i32; - pub fn sigaction(signum: i32, act: *const sigaction, oldact: *mut sigaction) -> i32; pub fn mmap(addr: *mut (), len: usize, prot: i32, flags: i32, fd: i32, offset: i64) -> *mut (); pub fn mprotect(addr: *mut (), len: usize, prot: i32) -> i32; @@ -61,7 +59,7 @@ fn main() { panic!("error: mmap failed"); } - let p_count = (&mut COUNT) as *mut u32; + let p_count = (&raw mut COUNT) as *mut u32; p_count.write_volatile(0); // Trigger segfaults @@ -94,7 +92,7 @@ fn main() { } unsafe extern "C" fn segv_handler(_: i32, _: *mut (), _: *mut ()) { - let p_count = (&mut COUNT) as *mut u32; + let p_count = (&raw mut COUNT) as *mut u32; p_count.write_volatile(p_count.read_volatile() + 1); let count = p_count.read_volatile(); From 4475b1c988aa94ad311fe83de9f0d0c9dbe08cb4 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 18 Jul 2025 22:35:30 +0200 Subject: [PATCH 0061/1134] Remove forgotten git annotations --- example/mini_core_hello_world.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/example/mini_core_hello_world.rs b/example/mini_core_hello_world.rs index 358f265a6b85..85489f850e24 100644 --- a/example/mini_core_hello_world.rs +++ b/example/mini_core_hello_world.rs @@ -198,12 +198,6 @@ fn main() { assert_eq!(intrinsics::align_of::() as u8, 2); assert_eq!(intrinsics::align_of_val(&a) as u8, intrinsics::align_of::<&str>() as u8); -<<<<<<< HEAD - assert!(!const { intrinsics::needs_drop::() }); - assert!(!const { intrinsics::needs_drop::<[u8]>() }); - assert!(const { intrinsics::needs_drop::() }); - assert!(const { intrinsics::needs_drop::() }); -======= /* * TODO: re-enable in the next sync. let u8_needs_drop = const { intrinsics::needs_drop::() }; @@ -215,7 +209,6 @@ fn main() { let noisy_unsized_drop = const { intrinsics::needs_drop::() }; assert!(noisy_unsized_drop); */ ->>>>>>> f682d09eefc6700b9e5851ef193847959acf4fac Unique { pointer: 0 as *const &str, From 215d8edfed6d8126d0c18ce8fc7721a807c3bcd0 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Fri, 11 Jul 2025 12:54:04 +0200 Subject: [PATCH 0062/1134] combine rust files into one compilation --- .../crates/intrinsic-test/src/arm/mod.rs | 64 +++-- .../intrinsic-test/src/common/argument.rs | 34 +-- .../intrinsic-test/src/common/compare.rs | 29 ++- .../intrinsic-test/src/common/gen_rust.rs | 232 +++++++++--------- .../crates/intrinsic-test/src/common/mod.rs | 1 - .../intrinsic-test/src/common/write_file.rs | 33 --- 6 files changed, 199 insertions(+), 194 deletions(-) delete mode 100644 library/stdarch/crates/intrinsic-test/src/common/write_file.rs diff --git a/library/stdarch/crates/intrinsic-test/src/arm/mod.rs b/library/stdarch/crates/intrinsic-test/src/arm/mod.rs index 0a64a24e7313..bd0bdf53015a 100644 --- a/library/stdarch/crates/intrinsic-test/src/arm/mod.rs +++ b/library/stdarch/crates/intrinsic-test/src/arm/mod.rs @@ -13,10 +13,9 @@ use crate::common::SupportedArchitectureTest; use crate::common::cli::ProcessedCli; use crate::common::compare::compare_outputs; use crate::common::gen_c::{write_main_cpp, write_mod_cpp}; -use crate::common::gen_rust::compile_rust_programs; -use crate::common::intrinsic::{Intrinsic, IntrinsicDefinition}; +use crate::common::gen_rust::{compile_rust_programs, write_cargo_toml, write_main_rs}; +use crate::common::intrinsic::Intrinsic; use crate::common::intrinsic_helpers::TypeKind; -use crate::common::write_file::write_rust_testfiles; use config::{AARCH_CONFIGURATIONS, F16_FORMATTING_DEF, build_notices}; use intrinsic::ArmIntrinsicType; use json_parser::get_neon_intrinsics; @@ -118,26 +117,61 @@ impl SupportedArchitectureTest for ArmArchitectureTest { } fn build_rust_file(&self) -> bool { - let rust_target = if self.cli_options.target.contains("v7") { + std::fs::create_dir_all("rust_programs/src").unwrap(); + + let architecture = if self.cli_options.target.contains("v7") { "arm" } else { "aarch64" }; + + let available_parallelism = std::thread::available_parallelism().unwrap().get(); + let chunk_size = self.intrinsics.len().div_ceil(available_parallelism); + + let mut cargo = File::create("rust_programs/Cargo.toml").unwrap(); + write_cargo_toml(&mut cargo, &[]).unwrap(); + + let mut main_rs = File::create("rust_programs/src/main.rs").unwrap(); + write_main_rs( + &mut main_rs, + available_parallelism, + architecture, + AARCH_CONFIGURATIONS, + F16_FORMATTING_DEF, + self.intrinsics.iter().map(|i| i.name.as_str()), + ) + .unwrap(); + let target = &self.cli_options.target; let toolchain = self.cli_options.toolchain.as_deref(); let linker = self.cli_options.linker.as_deref(); - let intrinsics_name_list = write_rust_testfiles( - self.intrinsics - .iter() - .map(|i| i as &dyn IntrinsicDefinition<_>) - .collect::>(), - rust_target, - &build_notices("// "), - F16_FORMATTING_DEF, - AARCH_CONFIGURATIONS, - ); - compile_rust_programs(intrinsics_name_list, toolchain, target, linker) + let notice = &build_notices("// "); + self.intrinsics + .par_chunks(chunk_size) + .enumerate() + .map(|(i, chunk)| { + use std::io::Write; + + let rust_filename = format!("rust_programs/src/mod_{i}.rs"); + trace!("generating `{rust_filename}`"); + let mut file = File::create(rust_filename).unwrap(); + + write!(file, "{notice}")?; + + writeln!(file, "use core_arch::arch::{architecture}::*;")?; + writeln!(file, "use crate::{{debug_simd_finish, debug_f16}};")?; + + for intrinsic in chunk { + crate::common::gen_rust::create_rust_test_module(&mut file, intrinsic)?; + } + + Ok(()) + }) + .collect::>() + .unwrap(); + + compile_rust_programs(toolchain, target, linker) } fn compare_outputs(&self) -> bool { diff --git a/library/stdarch/crates/intrinsic-test/src/common/argument.rs b/library/stdarch/crates/intrinsic-test/src/common/argument.rs index 1df4f55995e4..9cba8c90d9f5 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/argument.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/argument.rs @@ -146,21 +146,25 @@ where /// Creates a line for each argument that initializes an array for Rust from which `loads` argument /// values can be loaded as a sliding window, e.g `const A_VALS: [u32; 20] = [...];` - pub fn gen_arglists_rust(&self, indentation: Indentation, loads: u32) -> String { - self.iter() - .filter(|&arg| !arg.has_constraint()) - .map(|arg| { - format!( - "{indentation}{bind} {name}: [{ty}; {load_size}] = {values};", - bind = arg.rust_vals_array_binding(), - name = arg.rust_vals_array_name(), - ty = arg.ty.rust_scalar_type(), - load_size = arg.ty.num_lanes() * arg.ty.num_vectors() + loads - 1, - values = arg.ty.populate_random(indentation, loads, &Language::Rust) - ) - }) - .collect::>() - .join("\n") + pub fn gen_arglists_rust( + &self, + w: &mut impl std::io::Write, + indentation: Indentation, + loads: u32, + ) -> std::io::Result<()> { + for arg in self.iter().filter(|&arg| !arg.has_constraint()) { + writeln!( + w, + "{indentation}{bind} {name}: [{ty}; {load_size}] = {values};", + bind = arg.rust_vals_array_binding(), + name = arg.rust_vals_array_name(), + ty = arg.ty.rust_scalar_type(), + load_size = arg.ty.num_lanes() * arg.ty.num_vectors() + loads - 1, + values = arg.ty.populate_random(indentation, loads, &Language::Rust) + )? + } + + Ok(()) } /// Creates a line for each argument that initializes the argument from an array `[arg]_vals` at diff --git a/library/stdarch/crates/intrinsic-test/src/common/compare.rs b/library/stdarch/crates/intrinsic-test/src/common/compare.rs index cb55922eb199..183bb23ee0f4 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/compare.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/compare.rs @@ -2,25 +2,28 @@ use super::cli::FailureReason; use rayon::prelude::*; use std::process::Command; -pub fn compare_outputs(intrinsic_name_list: &Vec, runner: &str, target: &str) -> bool { - fn runner_command(runner: &str) -> Command { - let mut it = runner.split_whitespace(); - let mut cmd = Command::new(it.next().unwrap()); - cmd.args(it); +fn runner_command(runner: &str) -> Command { + let mut it = runner.split_whitespace(); + let mut cmd = Command::new(it.next().unwrap()); + cmd.args(it); - cmd - } + cmd +} +pub fn compare_outputs(intrinsic_name_list: &Vec, runner: &str, target: &str) -> bool { let intrinsics = intrinsic_name_list .par_iter() .filter_map(|intrinsic_name| { + let c = runner_command(runner) - .arg("./c_programs/intrinsic-test-programs") + .arg("intrinsic-test-programs") .arg(intrinsic_name) + .current_dir("c_programs") .output(); let rust = runner_command(runner) - .arg(format!("target/{target}/release/{intrinsic_name}")) + .arg(format!("target/{target}/release/intrinsic-test-programs")) + .arg(intrinsic_name) .output(); let (c, rust) = match (c, rust) { @@ -30,7 +33,7 @@ pub fn compare_outputs(intrinsic_name_list: &Vec, runner: &str, target: if !c.status.success() { error!( - "Failed to run C program for intrinsic {intrinsic_name}\nstdout: {stdout}\nstderr: {stderr}", + "Failed to run C program for intrinsic `{intrinsic_name}`\nstdout: {stdout}\nstderr: {stderr}", stdout = std::str::from_utf8(&c.stdout).unwrap_or(""), stderr = std::str::from_utf8(&c.stderr).unwrap_or(""), ); @@ -39,9 +42,9 @@ pub fn compare_outputs(intrinsic_name_list: &Vec, runner: &str, target: if !rust.status.success() { error!( - "Failed to run Rust program for intrinsic {intrinsic_name}\nstdout: {stdout}\nstderr: {stderr}", - stdout = String::from_utf8_lossy(&rust.stdout), - stderr = String::from_utf8_lossy(&rust.stderr), + "Failed to run Rust program for intrinsic `{intrinsic_name}`\nstdout: {stdout}\nstderr: {stderr}", + stdout = std::str::from_utf8(&rust.stdout).unwrap_or(""), + stderr = std::str::from_utf8(&rust.stderr).unwrap_or(""), ); return Some(FailureReason::RunRust(intrinsic_name.clone())); } diff --git a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs index 0e4a95ab528a..fb88e87d7e6a 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs @@ -1,7 +1,4 @@ use itertools::Itertools; -use rayon::prelude::*; -use std::collections::BTreeMap; -use std::fs::File; use std::process::Command; use super::argument::Argument; @@ -12,32 +9,7 @@ use super::intrinsic_helpers::IntrinsicTypeDefinition; // The number of times each intrinsic will be called. const PASSES: u32 = 20; -pub fn format_rust_main_template( - notices: &str, - definitions: &str, - configurations: &str, - arch_definition: &str, - arglists: &str, - passes: &str, -) -> String { - format!( - r#"{notices}#![feature(simd_ffi)] -#![feature(f16)] -#![allow(unused)] -{configurations} -{definitions} - -use core_arch::arch::{arch_definition}::*; - -fn main() {{ -{arglists} -{passes} -}} -"#, - ) -} - -fn write_cargo_toml(w: &mut impl std::io::Write, binaries: &[String]) -> std::io::Result<()> { +pub fn write_cargo_toml(w: &mut impl std::io::Write, binaries: &[String]) -> std::io::Result<()> { writeln!( w, concat!( @@ -73,25 +45,65 @@ fn write_cargo_toml(w: &mut impl std::io::Write, binaries: &[String]) -> std::io Ok(()) } -pub fn compile_rust_programs( - binaries: Vec, - toolchain: Option<&str>, - target: &str, - linker: Option<&str>, -) -> bool { - let mut cargo = File::create("rust_programs/Cargo.toml").unwrap(); - write_cargo_toml(&mut cargo, &binaries).unwrap(); +pub fn write_main_rs<'a>( + w: &mut impl std::io::Write, + available_parallelism: usize, + architecture: &str, + cfg: &str, + definitions: &str, + intrinsics: impl Iterator + Clone, +) -> std::io::Result<()> { + writeln!(w, "#![feature(simd_ffi)]")?; + writeln!(w, "#![feature(f16)]")?; + writeln!(w, "#![allow(unused)]")?; + + // Cargo will spam the logs if these warnings are not silenced. + writeln!(w, "#![allow(non_upper_case_globals)]")?; + writeln!(w, "#![allow(non_camel_case_types)]")?; + writeln!(w, "#![allow(non_snake_case)]")?; + + writeln!(w, "{cfg}")?; + writeln!(w, "{definitions}")?; + + writeln!(w, "use core_arch::arch::{architecture}::*;")?; + + for module in 0..Ord::min(available_parallelism, intrinsics.clone().count()) { + writeln!(w, "mod mod_{module};")?; + writeln!(w, "use mod_{module}::*;")?; + } + + writeln!(w, "fn main() {{")?; + + writeln!(w, " match std::env::args().nth(1).unwrap().as_str() {{")?; + + for binary in intrinsics { + writeln!(w, " \"{binary}\" => run_{binary}(),")?; + } + + writeln!( + w, + " other => panic!(\"unknown intrinsic `{{}}`\", other)," + )?; + + writeln!(w, " }}")?; + writeln!(w, "}}")?; + + Ok(()) +} +pub fn compile_rust_programs(toolchain: Option<&str>, target: &str, linker: Option<&str>) -> bool { /* If there has been a linker explicitly set from the command line then * we want to set it via setting it in the RUSTFLAGS*/ + trace!("Building cargo command"); + let mut cargo_command = Command::new("cargo"); cargo_command.current_dir("rust_programs"); - if let Some(toolchain) = toolchain { - if !toolchain.is_empty() { - cargo_command.arg(toolchain); - } + if let Some(toolchain) = toolchain + && !toolchain.is_empty() + { + cargo_command.arg(toolchain); } cargo_command.args(["build", "--target", target, "--release"]); @@ -105,7 +117,16 @@ pub fn compile_rust_programs( } cargo_command.env("RUSTFLAGS", rust_flags); + + trace!("running cargo"); + + if log::log_enabled!(log::Level::Trace) { + cargo_command.stdout(std::process::Stdio::inherit()); + cargo_command.stderr(std::process::Stdio::inherit()); + } + let output = cargo_command.output(); + trace!("cargo is done"); if let Ok(output) = output { if output.status.success() { @@ -124,26 +145,13 @@ pub fn compile_rust_programs( } } -// Creates directory structure and file path mappings -pub fn setup_rust_file_paths(identifiers: &Vec) -> BTreeMap<&String, String> { - identifiers - .par_iter() - .map(|identifier| { - let rust_dir = format!("rust_programs/{identifier}"); - let _ = std::fs::create_dir_all(&rust_dir); - let rust_filename = format!("{rust_dir}/main.rs"); - - (identifier, rust_filename) - }) - .collect::>() -} - pub fn generate_rust_test_loop( + w: &mut impl std::io::Write, intrinsic: &dyn IntrinsicDefinition, indentation: Indentation, additional: &str, passes: u32, -) -> String { +) -> std::io::Result<()> { let constraints = intrinsic.arguments().as_constraint_parameters_rust(); let constraints = if !constraints.is_empty() { format!("::<{constraints}>") @@ -154,7 +162,8 @@ pub fn generate_rust_test_loop( let return_value = format_f16_return_value(intrinsic); let indentation2 = indentation.nested(); let indentation3 = indentation2.nested(); - format!( + writeln!( + w, "{indentation}for i in 0..{passes} {{\n\ {indentation2}unsafe {{\n\ {loaded_args}\ @@ -169,74 +178,63 @@ pub fn generate_rust_test_loop( ) } -pub fn generate_rust_constraint_blocks( +fn generate_rust_constraint_blocks<'a, T: IntrinsicTypeDefinition + 'a>( + w: &mut impl std::io::Write, intrinsic: &dyn IntrinsicDefinition, indentation: Indentation, - constraints: &[&Argument], + constraints: &mut (impl Iterator> + Clone), name: String, -) -> String { - if let Some((current, constraints)) = constraints.split_last() { - let range = current - .constraint - .iter() - .map(|c| c.to_range()) - .flat_map(|r| r.into_iter()); - - let body_indentation = indentation.nested(); - range - .map(|i| { - format!( - "{indentation}{{\n\ - {body_indentation}const {name}: {ty} = {val};\n\ - {pass}\n\ - {indentation}}}", - name = current.name, - ty = current.ty.rust_type(), - val = i, - pass = generate_rust_constraint_blocks( - intrinsic, - body_indentation, - constraints, - format!("{name}-{i}") - ) - ) - }) - .join("\n") - } else { - generate_rust_test_loop(intrinsic, indentation, &name, PASSES) +) -> std::io::Result<()> { + let Some(current) = constraints.next() else { + return generate_rust_test_loop(w, intrinsic, indentation, &name, PASSES); + }; + + let body_indentation = indentation.nested(); + for i in current.constraint.iter().flat_map(|c| c.to_range()) { + let ty = current.ty.rust_type(); + + writeln!(w, "{indentation}{{")?; + + writeln!(w, "{body_indentation}const {}: {ty} = {i};", current.name)?; + + generate_rust_constraint_blocks( + w, + intrinsic, + body_indentation, + &mut constraints.clone(), + format!("{name}-{i}"), + )?; + + writeln!(w, "{indentation}}}")?; } + + Ok(()) } // Top-level function to create complete test program -pub fn create_rust_test_program( +pub fn create_rust_test_module( + w: &mut impl std::io::Write, intrinsic: &dyn IntrinsicDefinition, - target: &str, - notice: &str, - definitions: &str, - cfg: &str, -) -> String { +) -> std::io::Result<()> { + trace!("generating `{}`", intrinsic.name()); + let indentation = Indentation::default(); + + writeln!(w, "pub fn run_{}() {{", intrinsic.name())?; + + // Define the arrays of arguments. let arguments = intrinsic.arguments(); - let constraints = arguments - .iter() - .filter(|i| i.has_constraint()) - .collect_vec(); + arguments.gen_arglists_rust(w, indentation.nested(), PASSES)?; - let indentation = Indentation::default(); - format_rust_main_template( - notice, - definitions, - cfg, - target, - intrinsic - .arguments() - .gen_arglists_rust(indentation.nested(), PASSES) - .as_str(), - generate_rust_constraint_blocks( - intrinsic, - indentation.nested(), - &constraints, - Default::default(), - ) - .as_str(), - ) + // Define any const generics as `const` items, then generate the actual test loop. + generate_rust_constraint_blocks( + w, + intrinsic, + indentation.nested(), + &mut arguments.iter().rev().filter(|i| i.has_constraint()), + Default::default(), + )?; + + writeln!(w, "}}")?; + + Ok(()) } diff --git a/library/stdarch/crates/intrinsic-test/src/common/mod.rs b/library/stdarch/crates/intrinsic-test/src/common/mod.rs index 5d51d3460ecf..6c3154af385f 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/mod.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/mod.rs @@ -11,7 +11,6 @@ pub mod indentation; pub mod intrinsic; pub mod intrinsic_helpers; pub mod values; -pub mod write_file; /// Architectures must support this trait /// to be successfully tested. diff --git a/library/stdarch/crates/intrinsic-test/src/common/write_file.rs b/library/stdarch/crates/intrinsic-test/src/common/write_file.rs deleted file mode 100644 index 92dd70b7c578..000000000000 --- a/library/stdarch/crates/intrinsic-test/src/common/write_file.rs +++ /dev/null @@ -1,33 +0,0 @@ -use super::gen_rust::{create_rust_test_program, setup_rust_file_paths}; -use super::intrinsic::IntrinsicDefinition; -use super::intrinsic_helpers::IntrinsicTypeDefinition; -use std::fs::File; -use std::io::Write; - -pub fn write_file(filename: &String, code: String) { - let mut file = File::create(filename).unwrap(); - file.write_all(code.into_bytes().as_slice()).unwrap(); -} - -pub fn write_rust_testfiles( - intrinsics: Vec<&dyn IntrinsicDefinition>, - rust_target: &str, - notice: &str, - definitions: &str, - cfg: &str, -) -> Vec { - let intrinsics_name_list = intrinsics - .iter() - .map(|i| i.name().clone()) - .collect::>(); - let filename_mapping = setup_rust_file_paths(&intrinsics_name_list); - - intrinsics.iter().for_each(|&i| { - let rust_code = create_rust_test_program(i, rust_target, notice, definitions, cfg); - if let Some(filename) = filename_mapping.get(&i.name()) { - write_file(filename, rust_code) - } - }); - - intrinsics_name_list -} From 426091aed57f3b822be6d182c276bffeb4d67f9f Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Sat, 19 Jul 2025 02:00:17 +0200 Subject: [PATCH 0063/1134] update `Cargo.lock` --- library/stdarch/Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/stdarch/Cargo.lock b/library/stdarch/Cargo.lock index 4806682e6e0a..21d7d718fdf4 100644 --- a/library/stdarch/Cargo.lock +++ b/library/stdarch/Cargo.lock @@ -635,9 +635,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" dependencies = [ "itoa", "memchr", From 83804bf2ce8198c19144bc89e6e8e0f2c571b449 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Fri, 11 Jul 2025 20:49:54 +0200 Subject: [PATCH 0064/1134] split rust code into crates so that we get more parallelism out of cargo --- .../crates/intrinsic-test/src/arm/mod.rs | 33 ++++---- .../intrinsic-test/src/common/compare.rs | 1 + .../intrinsic-test/src/common/gen_rust.rs | 83 ++++++++++++++----- 3 files changed, 79 insertions(+), 38 deletions(-) diff --git a/library/stdarch/crates/intrinsic-test/src/arm/mod.rs b/library/stdarch/crates/intrinsic-test/src/arm/mod.rs index bd0bdf53015a..5d0320c4cdda 100644 --- a/library/stdarch/crates/intrinsic-test/src/arm/mod.rs +++ b/library/stdarch/crates/intrinsic-test/src/arm/mod.rs @@ -13,7 +13,9 @@ use crate::common::SupportedArchitectureTest; use crate::common::cli::ProcessedCli; use crate::common::compare::compare_outputs; use crate::common::gen_c::{write_main_cpp, write_mod_cpp}; -use crate::common::gen_rust::{compile_rust_programs, write_cargo_toml, write_main_rs}; +use crate::common::gen_rust::{ + compile_rust_programs, write_bin_cargo_toml, write_lib_cargo_toml, write_lib_rs, write_main_rs, +}; use crate::common::intrinsic::Intrinsic; use crate::common::intrinsic_helpers::TypeKind; use config::{AARCH_CONFIGURATIONS, F16_FORMATTING_DEF, build_notices}; @@ -125,19 +127,17 @@ impl SupportedArchitectureTest for ArmArchitectureTest { "aarch64" }; - let available_parallelism = std::thread::available_parallelism().unwrap().get(); - let chunk_size = self.intrinsics.len().div_ceil(available_parallelism); + let (chunk_size, chunk_count) = chunk_info(self.intrinsics.len()); let mut cargo = File::create("rust_programs/Cargo.toml").unwrap(); - write_cargo_toml(&mut cargo, &[]).unwrap(); + write_bin_cargo_toml(&mut cargo, chunk_count).unwrap(); let mut main_rs = File::create("rust_programs/src/main.rs").unwrap(); write_main_rs( &mut main_rs, - available_parallelism, - architecture, + chunk_count, AARCH_CONFIGURATIONS, - F16_FORMATTING_DEF, + "", self.intrinsics.iter().map(|i| i.name.as_str()), ) .unwrap(); @@ -151,20 +151,21 @@ impl SupportedArchitectureTest for ArmArchitectureTest { .par_chunks(chunk_size) .enumerate() .map(|(i, chunk)| { - use std::io::Write; + std::fs::create_dir_all(format!("rust_programs/mod_{i}/src"))?; - let rust_filename = format!("rust_programs/src/mod_{i}.rs"); + let rust_filename = format!("rust_programs/mod_{i}/src/lib.rs"); trace!("generating `{rust_filename}`"); - let mut file = File::create(rust_filename).unwrap(); + let mut file = File::create(rust_filename)?; - write!(file, "{notice}")?; + let cfg = AARCH_CONFIGURATIONS; + let definitions = F16_FORMATTING_DEF; + write_lib_rs(&mut file, architecture, notice, cfg, definitions, chunk)?; - writeln!(file, "use core_arch::arch::{architecture}::*;")?; - writeln!(file, "use crate::{{debug_simd_finish, debug_f16}};")?; + let toml_filename = format!("rust_programs/mod_{i}/Cargo.toml"); + trace!("generating `{toml_filename}`"); + let mut file = File::create(toml_filename).unwrap(); - for intrinsic in chunk { - crate::common::gen_rust::create_rust_test_module(&mut file, intrinsic)?; - } + write_lib_cargo_toml(&mut file, &format!("mod_{i}"))?; Ok(()) }) diff --git a/library/stdarch/crates/intrinsic-test/src/common/compare.rs b/library/stdarch/crates/intrinsic-test/src/common/compare.rs index 183bb23ee0f4..1ad00839ef02 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/compare.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/compare.rs @@ -24,6 +24,7 @@ pub fn compare_outputs(intrinsic_name_list: &Vec, runner: &str, target: let rust = runner_command(runner) .arg(format!("target/{target}/release/intrinsic-test-programs")) .arg(intrinsic_name) + .current_dir("rust_programs") .output(); let (c, rust) = match (c, rust) { diff --git a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs index fb88e87d7e6a..96b09b09f312 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs @@ -9,46 +9,53 @@ use super::intrinsic_helpers::IntrinsicTypeDefinition; // The number of times each intrinsic will be called. const PASSES: u32 = 20; -pub fn write_cargo_toml(w: &mut impl std::io::Write, binaries: &[String]) -> std::io::Result<()> { +fn write_cargo_toml_header(w: &mut impl std::io::Write, name: &str) -> std::io::Result<()> { writeln!( w, concat!( "[package]\n", - "name = \"intrinsic-test-programs\"\n", + "name = \"{name}\"\n", "version = \"{version}\"\n", "authors = [{authors}]\n", "license = \"{license}\"\n", "edition = \"2018\"\n", - "[workspace]\n", - "[dependencies]\n", - "core_arch = {{ path = \"../crates/core_arch\" }}", ), + name = name, version = env!("CARGO_PKG_VERSION"), authors = env!("CARGO_PKG_AUTHORS") .split(":") .format_with(", ", |author, fmt| fmt(&format_args!("\"{author}\""))), license = env!("CARGO_PKG_LICENSE"), - )?; + ) +} - for binary in binaries { - writeln!( - w, - concat!( - "[[bin]]\n", - "name = \"{binary}\"\n", - "path = \"{binary}/main.rs\"\n", - ), - binary = binary, - )?; +pub fn write_bin_cargo_toml( + w: &mut impl std::io::Write, + module_count: usize, +) -> std::io::Result<()> { + write_cargo_toml_header(w, "intrinsic-test-programs")?; + + writeln!(w, "[dependencies]")?; + + for i in 0..module_count { + writeln!(w, "mod_{i} = {{ path = \"mod_{i}/\" }}")?; } Ok(()) } +pub fn write_lib_cargo_toml(w: &mut impl std::io::Write, name: &str) -> std::io::Result<()> { + write_cargo_toml_header(w, name)?; + + writeln!(w, "[dependencies]")?; + writeln!(w, "core_arch = {{ path = \"../../crates/core_arch\" }}")?; + + Ok(()) +} + pub fn write_main_rs<'a>( w: &mut impl std::io::Write, - available_parallelism: usize, - architecture: &str, + chunk_count: usize, cfg: &str, definitions: &str, intrinsics: impl Iterator + Clone, @@ -65,10 +72,7 @@ pub fn write_main_rs<'a>( writeln!(w, "{cfg}")?; writeln!(w, "{definitions}")?; - writeln!(w, "use core_arch::arch::{architecture}::*;")?; - - for module in 0..Ord::min(available_parallelism, intrinsics.clone().count()) { - writeln!(w, "mod mod_{module};")?; + for module in 0..chunk_count { writeln!(w, "use mod_{module}::*;")?; } @@ -91,6 +95,38 @@ pub fn write_main_rs<'a>( Ok(()) } +pub fn write_lib_rs( + w: &mut impl std::io::Write, + architecture: &str, + notice: &str, + cfg: &str, + definitions: &str, + intrinsics: &[impl IntrinsicDefinition], +) -> std::io::Result<()> { + write!(w, "{notice}")?; + + writeln!(w, "#![feature(simd_ffi)]")?; + writeln!(w, "#![feature(f16)]")?; + writeln!(w, "#![allow(unused)]")?; + + // Cargo will spam the logs if these warnings are not silenced. + writeln!(w, "#![allow(non_upper_case_globals)]")?; + writeln!(w, "#![allow(non_camel_case_types)]")?; + writeln!(w, "#![allow(non_snake_case)]")?; + + writeln!(w, "{cfg}")?; + + writeln!(w, "use core_arch::arch::{architecture}::*;")?; + + writeln!(w, "{definitions}")?; + + for intrinsic in intrinsics { + crate::common::gen_rust::create_rust_test_module(w, intrinsic)?; + } + + Ok(()) +} + pub fn compile_rust_programs(toolchain: Option<&str>, target: &str, linker: Option<&str>) -> bool { /* If there has been a linker explicitly set from the command line then * we want to set it via setting it in the RUSTFLAGS*/ @@ -100,6 +136,9 @@ pub fn compile_rust_programs(toolchain: Option<&str>, target: &str, linker: Opti let mut cargo_command = Command::new("cargo"); cargo_command.current_dir("rust_programs"); + // Do not use the target directory of the workspace please. + cargo_command.env("CARGO_TARGET_DIR", "target"); + if let Some(toolchain) = toolchain && !toolchain.is_empty() { From 3051039b945f77a55e2fbbd1aceabfd147542746 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Fri, 11 Jul 2025 22:10:56 +0200 Subject: [PATCH 0065/1134] generate arrays of type-erased function pointers --- .../crates/intrinsic-test/src/arm/types.rs | 19 --- .../intrinsic-test/src/common/argument.rs | 8 -- .../intrinsic-test/src/common/gen_rust.rs | 126 ++++++++++-------- .../src/common/intrinsic_helpers.rs | 3 - 4 files changed, 73 insertions(+), 83 deletions(-) diff --git a/library/stdarch/crates/intrinsic-test/src/arm/types.rs b/library/stdarch/crates/intrinsic-test/src/arm/types.rs index 77f5e8d0e560..c06e9355c440 100644 --- a/library/stdarch/crates/intrinsic-test/src/arm/types.rs +++ b/library/stdarch/crates/intrinsic-test/src/arm/types.rs @@ -33,25 +33,6 @@ impl IntrinsicTypeDefinition for ArmIntrinsicType { } } - fn rust_type(&self) -> String { - let rust_prefix = self.0.kind.rust_prefix(); - let c_prefix = self.0.kind.c_prefix(); - if self.0.ptr_constant { - self.c_type() - } else if let (Some(bit_len), simd_len, vec_len) = - (self.0.bit_len, self.0.simd_len, self.0.vec_len) - { - match (simd_len, vec_len) { - (None, None) => format!("{rust_prefix}{bit_len}"), - (Some(simd), None) => format!("{c_prefix}{bit_len}x{simd}_t"), - (Some(simd), Some(vec)) => format!("{c_prefix}{bit_len}x{simd}x{vec}_t"), - (None, Some(_)) => todo!("{:#?}", self), // Likely an invalid case - } - } else { - todo!("{:#?}", self) - } - } - /// Determines the load function for this type. fn get_load_function(&self, language: Language) -> String { if let IntrinsicType { diff --git a/library/stdarch/crates/intrinsic-test/src/common/argument.rs b/library/stdarch/crates/intrinsic-test/src/common/argument.rs index 9cba8c90d9f5..1550cbd97f58 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/argument.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/argument.rs @@ -114,14 +114,6 @@ where .join(", ") } - pub fn as_constraint_parameters_rust(&self) -> String { - self.iter() - .filter(|a| a.has_constraint()) - .map(|arg| arg.name.clone()) - .collect::>() - .join(", ") - } - /// Creates a line for each argument that initializes an array for C from which `loads` argument /// values can be loaded as a sliding window. /// e.g `const int32x2_t a_vals = {0x3effffff, 0x3effffff, 0x3f7fffff}`, if loads=2. diff --git a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs index 96b09b09f312..60bb577a80c9 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs @@ -1,7 +1,6 @@ use itertools::Itertools; use std::process::Command; -use super::argument::Argument; use super::indentation::Indentation; use super::intrinsic::{IntrinsicDefinition, format_f16_return_value}; use super::intrinsic_helpers::IntrinsicTypeDefinition; @@ -188,66 +187,87 @@ pub fn generate_rust_test_loop( w: &mut impl std::io::Write, intrinsic: &dyn IntrinsicDefinition, indentation: Indentation, - additional: &str, + specializations: &[Vec], passes: u32, ) -> std::io::Result<()> { - let constraints = intrinsic.arguments().as_constraint_parameters_rust(); - let constraints = if !constraints.is_empty() { - format!("::<{constraints}>") - } else { - constraints - }; + let intrinsic_name = intrinsic.name(); + + // Each function (and each specialization) has its own type. Erase that type with a cast. + let mut coerce = String::from("unsafe fn("); + for _ in intrinsic.arguments().iter().filter(|a| !a.has_constraint()) { + coerce += "_, "; + } + coerce += ") -> _"; + + match specializations { + [] => { + writeln!(w, " let specializations = [(\"\", {intrinsic_name})];")?; + } + [const_args] if const_args.is_empty() => { + writeln!(w, " let specializations = [(\"\", {intrinsic_name})];")?; + } + _ => { + writeln!(w, " let specializations = [")?; + + for specialization in specializations { + let mut specialization: Vec<_> = + specialization.iter().map(|d| d.to_string()).collect(); + + let const_args = specialization.join(","); + + // The identifier is reversed. + specialization.reverse(); + let id = specialization.join("-"); + + writeln!( + w, + " (\"-{id}\", {intrinsic_name}::<{const_args}> as {coerce})," + )?; + } + + writeln!(w, " ];")?; + } + } let return_value = format_f16_return_value(intrinsic); let indentation2 = indentation.nested(); let indentation3 = indentation2.nested(); writeln!( w, - "{indentation}for i in 0..{passes} {{\n\ - {indentation2}unsafe {{\n\ - {loaded_args}\ - {indentation3}let __return_value = {intrinsic_call}{const}({args});\n\ - {indentation3}println!(\"Result {additional}-{{}}: {{:?}}\", i + 1, {return_value});\n\ - {indentation2}}}\n\ - {indentation}}}", + "\ + for (id, f) in specializations {{\n\ + for i in 0..{passes} {{\n\ + unsafe {{\n\ + {loaded_args}\ + let __return_value = f({args});\n\ + println!(\"Result {{id}}-{{}}: {{:?}}\", i + 1, {return_value});\n\ + }}\n\ + }}\n\ + }}", loaded_args = intrinsic.arguments().load_values_rust(indentation3), - intrinsic_call = intrinsic.name(), - const = constraints, args = intrinsic.arguments().as_call_param_rust(), ) } -fn generate_rust_constraint_blocks<'a, T: IntrinsicTypeDefinition + 'a>( - w: &mut impl std::io::Write, - intrinsic: &dyn IntrinsicDefinition, - indentation: Indentation, - constraints: &mut (impl Iterator> + Clone), - name: String, -) -> std::io::Result<()> { - let Some(current) = constraints.next() else { - return generate_rust_test_loop(w, intrinsic, indentation, &name, PASSES); - }; - - let body_indentation = indentation.nested(); - for i in current.constraint.iter().flat_map(|c| c.to_range()) { - let ty = current.ty.rust_type(); - - writeln!(w, "{indentation}{{")?; - - writeln!(w, "{body_indentation}const {}: {ty} = {i};", current.name)?; - - generate_rust_constraint_blocks( - w, - intrinsic, - body_indentation, - &mut constraints.clone(), - format!("{name}-{i}"), - )?; - - writeln!(w, "{indentation}}}")?; +/// Generate the specializations (unique sequences of const-generic arguments) for this intrinsic. +fn generate_rust_specializations<'a>( + constraints: &mut impl Iterator>, +) -> Vec> { + let mut specializations = vec![vec![]]; + + for constraint in constraints { + specializations = constraint + .flat_map(|right| { + specializations.iter().map(move |left| { + let mut left = left.clone(); + left.push(u8::try_from(right).unwrap()); + left + }) + }) + .collect(); } - Ok(()) + specializations } // Top-level function to create complete test program @@ -265,13 +285,13 @@ pub fn create_rust_test_module( arguments.gen_arglists_rust(w, indentation.nested(), PASSES)?; // Define any const generics as `const` items, then generate the actual test loop. - generate_rust_constraint_blocks( - w, - intrinsic, - indentation.nested(), - &mut arguments.iter().rev().filter(|i| i.has_constraint()), - Default::default(), - )?; + let specializations = generate_rust_specializations( + &mut arguments + .iter() + .filter_map(|i| i.constraint.as_ref().map(|v| v.to_range())), + ); + + generate_rust_test_loop(w, intrinsic, indentation, &specializations, PASSES)?; writeln!(w, "}}")?; diff --git a/library/stdarch/crates/intrinsic-test/src/common/intrinsic_helpers.rs b/library/stdarch/crates/intrinsic-test/src/common/intrinsic_helpers.rs index 697f9c8754da..b53047b2d38b 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/intrinsic_helpers.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/intrinsic_helpers.rs @@ -332,7 +332,4 @@ pub trait IntrinsicTypeDefinition: Deref { /// can be directly defined in `impl` blocks fn c_single_vector_type(&self) -> String; - - /// can be defined in `impl` blocks - fn rust_type(&self) -> String; } From 5a5027aba07400b337b8a56ae0dc4b4e7fbfd6a8 Mon Sep 17 00:00:00 2001 From: LorrensP-2158466 Date: Mon, 7 Jul 2025 12:44:48 +0200 Subject: [PATCH 0066/1134] Move float non determinism helpers to math.rs --- src/tools/miri/src/intrinsics/mod.rs | 195 +++++---------------------- src/tools/miri/src/math.rs | 114 +++++++++++++++- 2 files changed, 145 insertions(+), 164 deletions(-) diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index 4efa7dd4dcf8..22fcd998cedb 100644 --- a/src/tools/miri/src/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -3,20 +3,17 @@ mod atomic; mod simd; -use std::ops::Neg; - use rand::Rng; use rustc_abi::Size; -use rustc_apfloat::ieee::{IeeeFloat, Semantics}; use rustc_apfloat::{self, Float, Round}; use rustc_middle::mir; -use rustc_middle::ty::{self, FloatTy, ScalarInt}; +use rustc_middle::ty::{self, FloatTy}; use rustc_span::{Symbol, sym}; use self::atomic::EvalContextExt as _; use self::helpers::{ToHost, ToSoft, check_intrinsic_arg_count}; use self::simd::EvalContextExt as _; -use crate::math::{IeeeExt, apply_random_float_error_ulp}; +use crate::math::apply_random_float_error_ulp; use crate::*; impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} @@ -191,7 +188,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let [f] = check_intrinsic_arg_count(args)?; let f = this.read_scalar(f)?.to_f32()?; - let res = fixed_float_value(this, intrinsic_name, &[f]).unwrap_or_else(|| { + let res = math::fixed_float_value(this, intrinsic_name, &[f]).unwrap_or_else(|| { // Using host floats (but it's fine, these operations do not have // guaranteed precision). let host = f.to_host(); @@ -209,7 +206,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Apply a relative error of 4ULP to introduce some non-determinism // simulating imprecise implementations and optimizations. - let res = apply_random_float_error_ulp( + let res = math::apply_random_float_error_ulp( this, res, 2, // log2(4) @@ -217,7 +214,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Clamp the result to the guaranteed range of this function according to the C standard, // if any. - clamp_float_value(intrinsic_name, res) + math::clamp_float_value(intrinsic_name, res) }); let res = this.adjust_nan(res, &[f]); this.write_scalar(res, dest)?; @@ -235,7 +232,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let [f] = check_intrinsic_arg_count(args)?; let f = this.read_scalar(f)?.to_f64()?; - let res = fixed_float_value(this, intrinsic_name, &[f]).unwrap_or_else(|| { + let res = math::fixed_float_value(this, intrinsic_name, &[f]).unwrap_or_else(|| { // Using host floats (but it's fine, these operations do not have // guaranteed precision). let host = f.to_host(); @@ -253,7 +250,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Apply a relative error of 4ULP to introduce some non-determinism // simulating imprecise implementations and optimizations. - let res = apply_random_float_error_ulp( + let res = math::apply_random_float_error_ulp( this, res, 2, // log2(4) @@ -261,7 +258,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Clamp the result to the guaranteed range of this function according to the C standard, // if any. - clamp_float_value(intrinsic_name, res) + math::clamp_float_value(intrinsic_name, res) }); let res = this.adjust_nan(res, &[f]); this.write_scalar(res, dest)?; @@ -312,16 +309,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let f1 = this.read_scalar(f1)?.to_f32()?; let f2 = this.read_scalar(f2)?.to_f32()?; - let res = fixed_float_value(this, intrinsic_name, &[f1, f2]).unwrap_or_else(|| { - // Using host floats (but it's fine, this operation does not have guaranteed precision). - let res = f1.to_host().powf(f2.to_host()).to_soft(); + let res = + math::fixed_float_value(this, intrinsic_name, &[f1, f2]).unwrap_or_else(|| { + // Using host floats (but it's fine, this operation does not have guaranteed precision). + let res = f1.to_host().powf(f2.to_host()).to_soft(); - // Apply a relative error of 4ULP to introduce some non-determinism - // simulating imprecise implementations and optimizations. - apply_random_float_error_ulp( - this, res, 2, // log2(4) - ) - }); + // Apply a relative error of 4ULP to introduce some non-determinism + // simulating imprecise implementations and optimizations. + math::apply_random_float_error_ulp( + this, res, 2, // log2(4) + ) + }); let res = this.adjust_nan(res, &[f1, f2]); this.write_scalar(res, dest)?; } @@ -330,16 +328,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let f1 = this.read_scalar(f1)?.to_f64()?; let f2 = this.read_scalar(f2)?.to_f64()?; - let res = fixed_float_value(this, intrinsic_name, &[f1, f2]).unwrap_or_else(|| { - // Using host floats (but it's fine, this operation does not have guaranteed precision). - let res = f1.to_host().powf(f2.to_host()).to_soft(); + let res = + math::fixed_float_value(this, intrinsic_name, &[f1, f2]).unwrap_or_else(|| { + // Using host floats (but it's fine, this operation does not have guaranteed precision). + let res = f1.to_host().powf(f2.to_host()).to_soft(); - // Apply a relative error of 4ULP to introduce some non-determinism - // simulating imprecise implementations and optimizations. - apply_random_float_error_ulp( - this, res, 2, // log2(4) - ) - }); + // Apply a relative error of 4ULP to introduce some non-determinism + // simulating imprecise implementations and optimizations. + math::apply_random_float_error_ulp( + this, res, 2, // log2(4) + ) + }); let res = this.adjust_nan(res, &[f1, f2]); this.write_scalar(res, dest)?; } @@ -349,7 +348,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let f = this.read_scalar(f)?.to_f32()?; let i = this.read_scalar(i)?.to_i32()?; - let res = fixed_powi_float_value(this, f, i).unwrap_or_else(|| { + let res = math::fixed_powi_float_value(this, f, i).unwrap_or_else(|| { // Using host floats (but it's fine, this operation does not have guaranteed precision). let res = f.to_host().powi(i).to_soft(); @@ -367,13 +366,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let f = this.read_scalar(f)?.to_f64()?; let i = this.read_scalar(i)?.to_i32()?; - let res = fixed_powi_float_value(this, f, i).unwrap_or_else(|| { + let res = math::fixed_powi_float_value(this, f, i).unwrap_or_else(|| { // Using host floats (but it's fine, this operation does not have guaranteed precision). let res = f.to_host().powi(i).to_soft(); // Apply a relative error of 4ULP to introduce some non-determinism // simulating imprecise implementations and optimizations. - apply_random_float_error_ulp( + math::apply_random_float_error_ulp( this, res, 2, // log2(4) ) }); @@ -430,7 +429,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Apply a relative error of 4ULP to simulate non-deterministic precision loss // due to optimizations. - let res = apply_random_float_error_to_imm(this, res, 2 /* log2(4) */)?; + let res = math::apply_random_float_error_to_imm(this, res, 2 /* log2(4) */)?; this.write_immediate(*res, dest)?; } @@ -467,133 +466,3 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { interp_ok(EmulateItemResult::NeedsReturn) } } - -/// Applies a random ULP floating point error to `val` and returns the new value. -/// So if you want an X ULP error, `ulp_exponent` should be log2(X). -/// -/// Will fail if `val` is not a floating point number. -fn apply_random_float_error_to_imm<'tcx>( - ecx: &mut MiriInterpCx<'tcx>, - val: ImmTy<'tcx>, - ulp_exponent: u32, -) -> InterpResult<'tcx, ImmTy<'tcx>> { - let scalar = val.to_scalar_int()?; - let res: ScalarInt = match val.layout.ty.kind() { - ty::Float(FloatTy::F16) => - apply_random_float_error_ulp(ecx, scalar.to_f16(), ulp_exponent).into(), - ty::Float(FloatTy::F32) => - apply_random_float_error_ulp(ecx, scalar.to_f32(), ulp_exponent).into(), - ty::Float(FloatTy::F64) => - apply_random_float_error_ulp(ecx, scalar.to_f64(), ulp_exponent).into(), - ty::Float(FloatTy::F128) => - apply_random_float_error_ulp(ecx, scalar.to_f128(), ulp_exponent).into(), - _ => bug!("intrinsic called with non-float input type"), - }; - - interp_ok(ImmTy::from_scalar_int(res, val.layout)) -} - -/// For the intrinsics: -/// - sinf32, sinf64 -/// - cosf32, cosf64 -/// - expf32, expf64, exp2f32, exp2f64 -/// - logf32, logf64, log2f32, log2f64, log10f32, log10f64 -/// - powf32, powf64 -/// -/// # Return -/// -/// Returns `Some(output)` if the `intrinsic` results in a defined fixed `output` specified in the C standard -/// (specifically, C23 annex F.10) when given `args` as arguments. Outputs that are unaffected by a relative error -/// (such as INF and zero) are not handled here, they are assumed to be handled by the underlying -/// implementation. Returns `None` if no specific value is guaranteed. -/// -/// # Note -/// -/// For `powf*` operations of the form: -/// -/// - `(SNaN)^(±0)` -/// - `1^(SNaN)` -/// -/// The result is implementation-defined: -/// - musl returns for both `1.0` -/// - glibc returns for both `NaN` -/// -/// This discrepancy exists because SNaN handling is not consistently defined across platforms, -/// and the C standard leaves behavior for SNaNs unspecified. -/// -/// Miri chooses to adhere to both implementations and returns either one of them non-deterministically. -fn fixed_float_value( - ecx: &mut MiriInterpCx<'_>, - intrinsic_name: &str, - args: &[IeeeFloat], -) -> Option> { - let one = IeeeFloat::::one(); - Some(match (intrinsic_name, args) { - // cos(+- 0) = 1 - ("cosf32" | "cosf64", [input]) if input.is_zero() => one, - - // e^0 = 1 - ("expf32" | "expf64" | "exp2f32" | "exp2f64", [input]) if input.is_zero() => one, - - // (-1)^(±INF) = 1 - ("powf32" | "powf64", [base, exp]) if *base == -one && exp.is_infinite() => one, - - // 1^y = 1 for any y, even a NaN - ("powf32" | "powf64", [base, exp]) if *base == one => { - let rng = ecx.machine.rng.get_mut(); - // SNaN exponents get special treatment: they might return 1, or a NaN. - let return_nan = exp.is_signaling() && ecx.machine.float_nondet && rng.random(); - // Handle both the musl and glibc cases non-deterministically. - if return_nan { ecx.generate_nan(args) } else { one } - } - - // x^(±0) = 1 for any x, even a NaN - ("powf32" | "powf64", [base, exp]) if exp.is_zero() => { - let rng = ecx.machine.rng.get_mut(); - // SNaN bases get special treatment: they might return 1, or a NaN. - let return_nan = base.is_signaling() && ecx.machine.float_nondet && rng.random(); - // Handle both the musl and glibc cases non-deterministically. - if return_nan { ecx.generate_nan(args) } else { one } - } - - // There are a lot of cases for fixed outputs according to the C Standard, but these are - // mainly INF or zero which are not affected by the applied error. - _ => return None, - }) -} - -/// Returns `Some(output)` if `powi` (called `pown` in C) results in a fixed value specified in the -/// C standard (specifically, C23 annex F.10.4.6) when doing `base^exp`. Otherwise, returns `None`. -fn fixed_powi_float_value( - ecx: &mut MiriInterpCx<'_>, - base: IeeeFloat, - exp: i32, -) -> Option> { - Some(match exp { - 0 => { - let one = IeeeFloat::::one(); - let rng = ecx.machine.rng.get_mut(); - let return_nan = ecx.machine.float_nondet && rng.random() && base.is_signaling(); - // For SNaN treatment, we are consistent with `powf`above. - // (We wouldn't have two, unlike powf all implementations seem to agree for powi, - // but for now we are maximally conservative.) - if return_nan { ecx.generate_nan(&[base]) } else { one } - } - - _ => return None, - }) -} - -/// Given an floating-point operation and a floating-point value, clamps the result to the output -/// range of the given operation. -fn clamp_float_value(intrinsic_name: &str, val: IeeeFloat) -> IeeeFloat { - match intrinsic_name { - // sin and cos: [-1, 1] - "sinf32" | "cosf32" | "sinf64" | "cosf64" => - val.clamp(IeeeFloat::::one().neg(), IeeeFloat::::one()), - // exp: [0, +INF] - "expf32" | "exp2f32" | "expf64" | "exp2f64" => - IeeeFloat::::maximum(val, IeeeFloat::::ZERO), - _ => val, - } -} diff --git a/src/tools/miri/src/math.rs b/src/tools/miri/src/math.rs index cf16a5676d68..7713e1d31568 100644 --- a/src/tools/miri/src/math.rs +++ b/src/tools/miri/src/math.rs @@ -1,6 +1,8 @@ +use std::ops::Neg; + use rand::Rng as _; use rustc_apfloat::Float as _; -use rustc_apfloat::ieee::IeeeFloat; +use rustc_apfloat::ieee::{IeeeFloat, Semantics}; use rustc_middle::ty::{self, FloatTy, ScalarInt}; use crate::*; @@ -73,6 +75,116 @@ pub(crate) fn apply_random_float_error_to_imm<'tcx>( interp_ok(ImmTy::from_scalar_int(res, val.layout)) } +/// Given an floating-point operation and a floating-point value, clamps the result to the output +/// range of the given operation. +pub(crate) fn clamp_float_value( + intrinsic_name: &str, + val: IeeeFloat, +) -> IeeeFloat { + match intrinsic_name { + // sin and cos: [-1, 1] + "sinf32" | "cosf32" | "sinf64" | "cosf64" => + val.clamp(IeeeFloat::::one().neg(), IeeeFloat::::one()), + // exp: [0, +INF] + "expf32" | "exp2f32" | "expf64" | "exp2f64" => + IeeeFloat::::maximum(val, IeeeFloat::::ZERO), + _ => val, + } +} + +/// For the intrinsics: +/// - sinf32, sinf64 +/// - cosf32, cosf64 +/// - expf32, expf64, exp2f32, exp2f64 +/// - logf32, logf64, log2f32, log2f64, log10f32, log10f64 +/// - powf32, powf64 +/// +/// # Return +/// +/// Returns `Some(output)` if the `intrinsic` results in a defined fixed `output` specified in the C standard +/// (specifically, C23 annex F.10) when given `args` as arguments. Outputs that are unaffected by a relative error +/// (such as INF and zero) are not handled here, they are assumed to be handled by the underlying +/// implementation. Returns `None` if no specific value is guaranteed. +/// +/// # Note +/// +/// For `powf*` operations of the form: +/// +/// - `(SNaN)^(±0)` +/// - `1^(SNaN)` +/// +/// The result is implementation-defined: +/// - musl returns for both `1.0` +/// - glibc returns for both `NaN` +/// +/// This discrepancy exists because SNaN handling is not consistently defined across platforms, +/// and the C standard leaves behavior for SNaNs unspecified. +/// +/// Miri chooses to adhere to both implementations and returns either one of them non-deterministically. +pub(crate) fn fixed_float_value( + ecx: &mut MiriInterpCx<'_>, + intrinsic_name: &str, + args: &[IeeeFloat], +) -> Option> { + let this = ecx.eval_context_mut(); + let one = IeeeFloat::::one(); + Some(match (intrinsic_name, args) { + // cos(+- 0) = 1 + ("cosf32" | "cosf64", [input]) if input.is_zero() => one, + + // e^0 = 1 + ("expf32" | "expf64" | "exp2f32" | "exp2f64", [input]) if input.is_zero() => one, + + // (-1)^(±INF) = 1 + ("powf32" | "powf64", [base, exp]) if *base == -one && exp.is_infinite() => one, + + // 1^y = 1 for any y, even a NaN + ("powf32" | "powf64", [base, exp]) if *base == one => { + let rng = this.machine.rng.get_mut(); + // SNaN exponents get special treatment: they might return 1, or a NaN. + let return_nan = exp.is_signaling() && this.machine.float_nondet && rng.random(); + // Handle both the musl and glibc cases non-deterministically. + if return_nan { this.generate_nan(args) } else { one } + } + + // x^(±0) = 1 for any x, even a NaN + ("powf32" | "powf64", [base, exp]) if exp.is_zero() => { + let rng = this.machine.rng.get_mut(); + // SNaN bases get special treatment: they might return 1, or a NaN. + let return_nan = base.is_signaling() && this.machine.float_nondet && rng.random(); + // Handle both the musl and glibc cases non-deterministically. + if return_nan { this.generate_nan(args) } else { one } + } + + // There are a lot of cases for fixed outputs according to the C Standard, but these are + // mainly INF or zero which are not affected by the applied error. + _ => return None, + }) +} + +/// Returns `Some(output)` if `powi` (called `pown` in C) results in a fixed value specified in the +/// C standard (specifically, C23 annex F.10.4.6) when doing `base^exp`. Otherwise, returns `None`. +pub(crate) fn fixed_powi_float_value( + ecx: &mut MiriInterpCx<'_>, + base: IeeeFloat, + exp: i32, +) -> Option> { + let this = ecx.eval_context_mut(); + Some(match exp { + 0 => { + let one = IeeeFloat::::one(); + let rng = this.machine.rng.get_mut(); + let return_nan = this.machine.float_nondet && rng.random() && base.is_signaling(); + // For SNaN treatment, we are consistent with `powf`above. + // (We wouldn't have two, unlike powf all implementations seem to agree for powi, + // but for now we are maximally conservative.) + if return_nan { this.generate_nan(&[base]) } else { one } + } + + _ => return None, + }) +} + pub(crate) fn sqrt(x: IeeeFloat) -> IeeeFloat { match x.category() { // preserve zero sign From 58c00f3b7139a689492a48ee45b45b951aeb2427 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Thu, 17 Jul 2025 19:41:40 +0200 Subject: [PATCH 0067/1134] fix `collapsable_else_if` when the inner `if` is in parens --- clippy_lints/src/collapsible_if.rs | 52 ++++++++++++++--------------- tests/ui/collapsible_else_if.fixed | 22 ++++++++++++ tests/ui/collapsible_else_if.rs | 24 +++++++++++++ tests/ui/collapsible_else_if.stderr | 11 +++++- tests/ui/collapsible_if.fixed | 10 ++++++ tests/ui/collapsible_if.rs | 10 ++++++ 6 files changed, 102 insertions(+), 27 deletions(-) diff --git a/clippy_lints/src/collapsible_if.rs b/clippy_lints/src/collapsible_if.rs index da0f0b2f1be9..e3103e2d3016 100644 --- a/clippy_lints/src/collapsible_if.rs +++ b/clippy_lints/src/collapsible_if.rs @@ -136,6 +136,9 @@ impl CollapsibleIf { return; } + // Peel off any parentheses. + let (_, else_block_span, _) = peel_parens(cx.tcx.sess.source_map(), else_.span); + // Prevent "elseif" // Check that the "else" is followed by whitespace let requires_space = if let Some(c) = snippet(cx, up_to_else, "..").chars().last() { @@ -152,7 +155,7 @@ impl CollapsibleIf { if requires_space { " " } else { "" }, snippet_block_with_applicability( cx, - else_.span, + else_block_span, "..", Some(else_block.span), &mut applicability @@ -298,39 +301,36 @@ fn span_extract_keyword(sm: &SourceMap, span: Span, keyword: &str) -> Option (Span, Span, Span) { use crate::rustc_span::Pos; - use rustc_span::SpanData; let start = span.shrink_to_lo(); let end = span.shrink_to_hi(); - loop { - let data = span.data(); - let snippet = sm.span_to_snippet(span).unwrap(); - - let trim_start = snippet.len() - snippet.trim_start().len(); - let trim_end = snippet.len() - snippet.trim_end().len(); - - let trimmed = snippet.trim(); - - if trimmed.starts_with('(') && trimmed.ends_with(')') { - // Try to remove one layer of parens by adjusting the span - span = SpanData { - lo: data.lo + BytePos::from_usize(trim_start + 1), - hi: data.hi - BytePos::from_usize(trim_end + 1), - ctxt: data.ctxt, - parent: data.parent, - } - .span(); + let snippet = sm.span_to_snippet(span).unwrap(); + if let Some((trim_start, _, trim_end)) = peel_parens_str(&snippet) { + let mut data = span.data(); + data.lo = data.lo + BytePos::from_usize(trim_start); + data.hi = data.hi - BytePos::from_usize(trim_end); + span = data.span(); + } - continue; - } + (start.with_hi(span.lo()), span, end.with_lo(span.hi())) +} - break; +fn peel_parens_str(snippet: &str) -> Option<(usize, &str, usize)> { + let trimmed = snippet.trim(); + if !(trimmed.starts_with('(') && trimmed.ends_with(')')) { + return None; } - (start.with_hi(span.lo()), - span, - end.with_lo(span.hi())) + let trim_start = (snippet.len() - snippet.trim_start().len()) + 1; + let trim_end = (snippet.len() - snippet.trim_end().len()) + 1; + + let inner = snippet.get(trim_start..snippet.len() - trim_end)?; + Some(match peel_parens_str(inner) { + None => (trim_start, inner, trim_end), + Some((start, inner, end)) => (trim_start + start, inner, trim_end + end), + }) } diff --git a/tests/ui/collapsible_else_if.fixed b/tests/ui/collapsible_else_if.fixed index fed75244c6f7..3d709fe9b8e0 100644 --- a/tests/ui/collapsible_else_if.fixed +++ b/tests/ui/collapsible_else_if.fixed @@ -104,3 +104,25 @@ fn issue14799() { } } } + +fn in_parens() { + let x = "hello"; + let y = "world"; + + if x == "hello" { + print!("Hello "); + } else if y == "world" { println!("world") } else { println!("!") } + //~^^^ collapsible_else_if +} + +fn in_brackets() { + let x = "hello"; + let y = "world"; + + // There is no lint when the inner `if` is in a block. + if x == "hello" { + print!("Hello "); + } else { + { if y == "world" { println!("world") } else { println!("!") } } + } +} diff --git a/tests/ui/collapsible_else_if.rs b/tests/ui/collapsible_else_if.rs index e50e781fb698..51868e039086 100644 --- a/tests/ui/collapsible_else_if.rs +++ b/tests/ui/collapsible_else_if.rs @@ -120,3 +120,27 @@ fn issue14799() { } } } + +fn in_parens() { + let x = "hello"; + let y = "world"; + + if x == "hello" { + print!("Hello "); + } else { + (if y == "world" { println!("world") } else { println!("!") }) + } + //~^^^ collapsible_else_if +} + +fn in_brackets() { + let x = "hello"; + let y = "world"; + + // There is no lint when the inner `if` is in a block. + if x == "hello" { + print!("Hello "); + } else { + { if y == "world" { println!("world") } else { println!("!") } } + } +} diff --git a/tests/ui/collapsible_else_if.stderr b/tests/ui/collapsible_else_if.stderr index 7d80894cadbb..1a7bcec7fd5d 100644 --- a/tests/ui/collapsible_else_if.stderr +++ b/tests/ui/collapsible_else_if.stderr @@ -150,5 +150,14 @@ LL | | if false {} LL | | } | |_____^ help: collapse nested if block: `if false {}` -error: aborting due to 8 previous errors +error: this `else { if .. }` block can be collapsed + --> tests/ui/collapsible_else_if.rs:130:12 + | +LL | } else { + | ____________^ +LL | | (if y == "world" { println!("world") } else { println!("!") }) +LL | | } + | |_____^ help: collapse nested if block: `if y == "world" { println!("world") } else { println!("!") }` + +error: aborting due to 9 previous errors diff --git a/tests/ui/collapsible_if.fixed b/tests/ui/collapsible_if.fixed index f7c840c4cc1e..78354c2d7cf8 100644 --- a/tests/ui/collapsible_if.fixed +++ b/tests/ui/collapsible_if.fixed @@ -171,3 +171,13 @@ fn in_parens() { } //~^^^^^ collapsible_if } + +fn in_brackets() { + if true { + { + if true { + println!("In brackets, not linted"); + } + } + } +} diff --git a/tests/ui/collapsible_if.rs b/tests/ui/collapsible_if.rs index 4faebcb0ca0d..5d9afa109569 100644 --- a/tests/ui/collapsible_if.rs +++ b/tests/ui/collapsible_if.rs @@ -182,3 +182,13 @@ fn in_parens() { } //~^^^^^ collapsible_if } + +fn in_brackets() { + if true { + { + if true { + println!("In brackets, not linted"); + } + } + } +} From 5b2c61edbe508163ad11cde0f35278417d7c26b3 Mon Sep 17 00:00:00 2001 From: Alisa Sireneva Date: Sat, 19 Jul 2025 18:18:01 +0300 Subject: [PATCH 0068/1134] Document guarantees of poisoning This mostly documents the current behavior of `Mutex` and `RwLock` as imperfect. It's unlikely that the situation improves significantly in the future, and even if it does, the rules will probably be more complicated than "poisoning is completely reliable", so this is a conservative guarantee. We also explicitly specify that `OnceLock` never poisons, even though it has an API similar to mutexes. --- library/std/src/sync/once_lock.rs | 2 ++ library/std/src/sync/poison.rs | 24 +++++++------ library/std/src/sync/poison/mutex.rs | 52 ++++++++++++++++++++++----- library/std/src/sync/poison/once.rs | 6 +++- library/std/src/sync/poison/rwlock.rs | 8 ++--- 5 files changed, 67 insertions(+), 25 deletions(-) diff --git a/library/std/src/sync/once_lock.rs b/library/std/src/sync/once_lock.rs index a5c3a6c46a43..b224044cbe09 100644 --- a/library/std/src/sync/once_lock.rs +++ b/library/std/src/sync/once_lock.rs @@ -16,6 +16,8 @@ use crate::sync::Once; /// A `OnceLock` can be thought of as a safe abstraction over uninitialized data that becomes /// initialized once written. /// +/// Unlike [`Mutex`](crate::sync::Mutex), `OnceLock` is never poisoned on panic. +/// /// [`OnceCell`]: crate::cell::OnceCell /// [`LazyLock`]: crate::sync::LazyLock /// [`LazyLock::new(|| ...)`]: crate::sync::LazyLock::new diff --git a/library/std/src/sync/poison.rs b/library/std/src/sync/poison.rs index 0c05f152ef84..e928b6772cc8 100644 --- a/library/std/src/sync/poison.rs +++ b/library/std/src/sync/poison.rs @@ -2,15 +2,16 @@ //! //! # Poisoning //! -//! All synchronization objects in this module implement a strategy called "poisoning" -//! where if a thread panics while holding the exclusive access granted by the primitive, -//! the state of the primitive is set to "poisoned". -//! This information is then propagated to all other threads +//! All synchronization objects in this module implement a strategy called +//! "poisoning" where a primitive becomes poisoned if it recognizes that some +//! thread has panicked while holding the exclusive access granted by the +//! primitive. This information is then propagated to all other threads //! to signify that the data protected by this primitive is likely tainted //! (some invariant is not being upheld). //! -//! The specifics of how this "poisoned" state affects other threads -//! depend on the primitive. See [#Overview] below. +//! The specifics of how this "poisoned" state affects other threads and whether +//! the panics are recognized reliably or on a best-effort basis depend on the +//! primitive. See [#Overview] below. //! //! For the alternative implementations that do not employ poisoning, //! see `std::sync::nonpoisoning`. @@ -34,14 +35,15 @@ //! - [`Mutex`]: Mutual Exclusion mechanism, which ensures that at //! most one thread at a time is able to access some data. //! -//! [`Mutex::lock()`] returns a [`LockResult`], -//! providing a way to deal with the poisoned state. -//! See [`Mutex`'s documentation](Mutex#poisoning) for more. +//! Panicking while holding the lock typically poisons the mutex, but it is +//! not guaranteed to detect this condition in all circumstances. +//! [`Mutex::lock()`] returns a [`LockResult`], providing a way to deal with +//! the poisoned state. See [`Mutex`'s documentation](Mutex#poisoning) for more. //! //! - [`Once`]: A thread-safe way to run a piece of code only once. //! Mostly useful for implementing one-time global initialization. //! -//! [`Once`] is poisoned if the piece of code passed to +//! [`Once`] is reliably poisoned if the piece of code passed to //! [`Once::call_once()`] or [`Once::call_once_force()`] panics. //! When in poisoned state, subsequent calls to [`Once::call_once()`] will panic too. //! [`Once::call_once_force()`] can be used to clear the poisoned state. @@ -51,7 +53,7 @@ //! writer at a time. In some cases, this can be more efficient than //! a mutex. //! -//! This implementation, like [`Mutex`], will become poisoned on a panic. +//! This implementation, like [`Mutex`], usually becomes poisoned on a panic. //! Note, however, that an `RwLock` may only be poisoned if a panic occurs //! while it is locked exclusively (write mode). If a panic occurs in any reader, //! then the lock will not be poisoned. diff --git a/library/std/src/sync/poison/mutex.rs b/library/std/src/sync/poison/mutex.rs index 30325be685c3..15dfe116133b 100644 --- a/library/std/src/sync/poison/mutex.rs +++ b/library/std/src/sync/poison/mutex.rs @@ -18,20 +18,54 @@ use crate::sys::sync as sys; /// # Poisoning /// /// The mutexes in this module implement a strategy called "poisoning" where a -/// mutex is considered poisoned whenever a thread panics while holding the -/// mutex. Once a mutex is poisoned, all other threads are unable to access the -/// data by default as it is likely tainted (some invariant is not being -/// upheld). +/// mutex becomes poisoned if it recognizes that the thread holding it has +/// panicked. /// -/// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a +/// Once a mutex is poisoned, all other threads are unable to access the data by +/// default as it is likely tainted (some invariant is not being upheld). For a +/// mutex, this means that the [`lock`] and [`try_lock`] methods return a /// [`Result`] which indicates whether a mutex has been poisoned or not. Most /// usage of a mutex will simply [`unwrap()`] these results, propagating panics /// among threads to ensure that a possibly invalid invariant is not witnessed. /// -/// A poisoned mutex, however, does not prevent all access to the underlying -/// data. The [`PoisonError`] type has an [`into_inner`] method which will return -/// the guard that would have otherwise been returned on a successful lock. This -/// allows access to the data, despite the lock being poisoned. +/// Poisoning is only advisory: the [`PoisonError`] type has an [`into_inner`] +/// method which will return the guard that would have otherwise been returned +/// on a successful lock. This allows access to the data, despite the lock being +/// poisoned. +/// +/// In addition, the panic detection is not ideal, so even unpoisoned mutexes +/// need to be handled with care, since certain panics may have been skipped. +/// Therefore, `unsafe` code cannot rely on poisoning for soundness. Here's an +/// example of **incorrect** use of poisoning: +/// +/// ```rust +/// use std::sync::Mutex; +/// +/// struct MutexBox { +/// data: Mutex<*mut T>, +/// } +/// +/// impl MutexBox { +/// pub fn new(value: T) -> Self { +/// Self { +/// data: Mutex::new(Box::into_raw(Box::new(value))), +/// } +/// } +/// +/// pub fn replace_with(&self, f: impl FnOnce(T) -> T) { +/// let ptr = self.data.lock().expect("poisoned"); +/// // While `f` is running, the data is moved out of `*ptr`. If `f` +/// // panics, `*ptr` keeps pointing at a dropped value. The intention +/// // is that this will poison the mutex, so the following calls to +/// // `replace_with` will panic without reading `*ptr`. But since +/// // poisoning is not guaranteed to occur, this can lead to +/// // use-after-free. +/// unsafe { +/// (*ptr).write(f((*ptr).read())); +/// } +/// } +/// } +/// ``` /// /// [`new`]: Self::new /// [`lock`]: Self::lock diff --git a/library/std/src/sync/poison/once.rs b/library/std/src/sync/poison/once.rs index 103e51954079..faf2913c5473 100644 --- a/library/std/src/sync/poison/once.rs +++ b/library/std/src/sync/poison/once.rs @@ -136,7 +136,8 @@ impl Once { /// it will *poison* this [`Once`] instance, causing all future invocations of /// `call_once` to also panic. /// - /// This is similar to [poisoning with mutexes][poison]. + /// This is similar to [poisoning with mutexes][poison], but this mechanism + /// is guaranteed to never skip panics within `f`. /// /// [poison]: struct.Mutex.html#poisoning #[inline] @@ -293,6 +294,9 @@ impl Once { /// Blocks the current thread until initialization has completed, ignoring /// poisoning. + /// + /// If this [`Once`] has been poisoned, this function blocks until it + /// becomes completed, unlike [`Once::wait()`], which panics in this case. #[stable(feature = "once_wait", since = "1.86.0")] pub fn wait_force(&self) { if !self.inner.is_completed() { diff --git a/library/std/src/sync/poison/rwlock.rs b/library/std/src/sync/poison/rwlock.rs index 934a173425a8..0a50b6c2d8f1 100644 --- a/library/std/src/sync/poison/rwlock.rs +++ b/library/std/src/sync/poison/rwlock.rs @@ -46,10 +46,10 @@ use crate::sys::sync as sys; /// /// # Poisoning /// -/// An `RwLock`, like [`Mutex`], will become poisoned on a panic. Note, however, -/// that an `RwLock` may only be poisoned if a panic occurs while it is locked -/// exclusively (write mode). If a panic occurs in any reader, then the lock -/// will not be poisoned. +/// An `RwLock`, like [`Mutex`], will usually become poisoned on a panic. Note, +/// however, that an `RwLock` may only be poisoned if a panic occurs while it is +/// locked exclusively (write mode). If a panic occurs in any reader, then the +/// lock will not be poisoned. /// /// # Examples /// From 41199f39d89135408763eee492fd2a5270828030 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Sat, 19 Jul 2025 11:17:38 -0700 Subject: [PATCH 0069/1134] `available_parallelism`: Add documentation for why we don't look at `ulimit` --- library/std/src/thread/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 6075173db47f..c80ea9cf4f00 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -2012,6 +2012,9 @@ fn _assert_sync_and_send() { /// which may take time on systems with large numbers of mountpoints. /// (This does not apply to cgroup v2, or to processes not in a /// cgroup.) +/// - It does not attempt to take `ulimit` into account. If there is a limit set on the number of +/// threads, `available_parallelism` cannot know how much of that limit a Rust program should +/// take, or know in a reliable and race-free way how much of that limit is already taken. /// /// On all targets: /// - It may overcount the amount of parallelism available when running in a VM From 788fb08bdb375eb811d682b4f24566d0aad1baca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Fri, 18 Jul 2025 12:51:44 +0200 Subject: [PATCH 0070/1134] Reject relaxed bounds inside associated type bounds --- compiler/rustc_ast_lowering/src/lib.rs | 12 ++++++++---- .../src/hir_ty_lowering/bounds.rs | 8 +++----- tests/ui/trait-bounds/more_maybe_bounds.rs | 8 ++++++-- tests/ui/trait-bounds/more_maybe_bounds.stderr | 6 +++--- .../unsized/relaxed-bounds-invalid-places.rs | 4 ++++ .../relaxed-bounds-invalid-places.stderr | 18 +++++++++++++----- 6 files changed, 37 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 533ee9bff54f..d3e8f62618f8 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -296,6 +296,7 @@ enum RelaxedBoundPolicy<'a> { enum RelaxedBoundForbiddenReason { TraitObjectTy, SuperTrait, + AssocTyBounds, LateBoundVarsInScope, } @@ -1102,9 +1103,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar))); hir::AssocItemConstraintKind::Equality { term: err_ty.into() } } else { - // FIXME(#135229): These should be forbidden! - let bounds = - self.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx); + let bounds = self.lower_param_bounds( + bounds, + RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds), + itctx, + ); hir::AssocItemConstraintKind::Bound { bounds } } } @@ -2117,7 +2120,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { diag.emit(); return; } - RelaxedBoundForbiddenReason::LateBoundVarsInScope => {} + RelaxedBoundForbiddenReason::AssocTyBounds + | RelaxedBoundForbiddenReason::LateBoundVarsInScope => {} }; } } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index d7a827c649dd..bd0d0d7c1062 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -199,12 +199,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // However, this can easily get out of sync! Ideally, we would perform this step // where we are guaranteed to catch *all* bounds like in // `Self::lower_poly_trait_ref`. List of concrete issues: - // FIXME(more_maybe_bounds): We don't call this for e.g., trait object tys or - // supertrait bounds! + // FIXME(more_maybe_bounds): We don't call this for trait object tys, supertrait + // bounds or associated type bounds (ATB)! // FIXME(trait_alias, #143122): We don't call it for the RHS. Arguably however, - // AST lowering should reject them outright. - // FIXME(associated_type_bounds): We don't call this for them. However, AST - // lowering should reject them outright (#135229). + // AST lowering should reject them outright. let bounds = collect_relaxed_bounds(hir_bounds, self_ty_where_predicates); self.check_and_report_invalid_relaxed_bounds(bounds); } diff --git a/tests/ui/trait-bounds/more_maybe_bounds.rs b/tests/ui/trait-bounds/more_maybe_bounds.rs index 47348b0a0dd7..d367dd5b299d 100644 --- a/tests/ui/trait-bounds/more_maybe_bounds.rs +++ b/tests/ui/trait-bounds/more_maybe_bounds.rs @@ -1,7 +1,7 @@ // FIXME(more_maybe_bounds): Even under `more_maybe_bounds` / `-Zexperimental-default-bounds`, // trying to relax non-default bounds should still be an error in all contexts! As you can see -// there are places like supertrait bounds and trait object types where we currently don't perform -// this check. +// there are places like supertrait bounds, trait object types or associated type bounds (ATB) +// where we currently don't perform this check. #![feature(auto_traits, more_maybe_bounds, negative_impls)] trait Trait1 {} @@ -13,11 +13,15 @@ trait Trait4 where Self: Trait1 {} // FIXME: `?Trait2` should be rejected, `Trait2` isn't marked `#[lang = "default_traitN"]`. fn foo(_: Box<(dyn Trait3 + ?Trait2)>) {} + fn bar(_: &T) {} //~^ ERROR bound modifier `?` can only be applied to default traits like `Sized` //~| ERROR bound modifier `?` can only be applied to default traits like `Sized` //~| ERROR bound modifier `?` can only be applied to default traits like `Sized` +// FIXME: `?Trait1` should be rejected, `Trait1` isn't marked `#[lang = "default_traitN"]`. +fn baz() where T: Iterator {} + struct S; impl !Trait2 for S {} impl Trait1 for S {} diff --git a/tests/ui/trait-bounds/more_maybe_bounds.stderr b/tests/ui/trait-bounds/more_maybe_bounds.stderr index 09c9fc311657..8dd83fc7728a 100644 --- a/tests/ui/trait-bounds/more_maybe_bounds.stderr +++ b/tests/ui/trait-bounds/more_maybe_bounds.stderr @@ -1,17 +1,17 @@ error: bound modifier `?` can only be applied to default traits like `Sized` - --> $DIR/more_maybe_bounds.rs:16:20 + --> $DIR/more_maybe_bounds.rs:17:20 | LL | fn bar(_: &T) {} | ^^^^^^^ error: bound modifier `?` can only be applied to default traits like `Sized` - --> $DIR/more_maybe_bounds.rs:16:30 + --> $DIR/more_maybe_bounds.rs:17:30 | LL | fn bar(_: &T) {} | ^^^^^^^ error: bound modifier `?` can only be applied to default traits like `Sized` - --> $DIR/more_maybe_bounds.rs:16:40 + --> $DIR/more_maybe_bounds.rs:17:40 | LL | fn bar(_: &T) {} | ^^^^^^^ diff --git a/tests/ui/unsized/relaxed-bounds-invalid-places.rs b/tests/ui/unsized/relaxed-bounds-invalid-places.rs index b8eda1e7786b..4c1f242a01ce 100644 --- a/tests/ui/unsized/relaxed-bounds-invalid-places.rs +++ b/tests/ui/unsized/relaxed-bounds-invalid-places.rs @@ -22,6 +22,10 @@ impl S1 { fn f() where T: ?Sized {} //~ ERROR this relaxed bound is not permitted here } +// Test associated type bounds (ATB). +// issue: +struct S6(T) where T: Iterator; //~ ERROR this relaxed bound is not permitted here + trait Tr: ?Sized {} //~ ERROR relaxed bounds are not permitted in supertrait bounds // Test that relaxed `Sized` bounds are rejected in trait object types: diff --git a/tests/ui/unsized/relaxed-bounds-invalid-places.stderr b/tests/ui/unsized/relaxed-bounds-invalid-places.stderr index 30285d626936..d3f0535e2f0c 100644 --- a/tests/ui/unsized/relaxed-bounds-invalid-places.stderr +++ b/tests/ui/unsized/relaxed-bounds-invalid-places.stderr @@ -38,8 +38,16 @@ LL | fn f() where T: ?Sized {} | = note: in this context, relaxed bounds are only allowed on type parameters defined by the closest item +error: this relaxed bound is not permitted here + --> $DIR/relaxed-bounds-invalid-places.rs:27:41 + | +LL | struct S6(T) where T: Iterator; + | ^^^^^^ + | + = note: in this context, relaxed bounds are only allowed on type parameters defined by the closest item + error: relaxed bounds are not permitted in supertrait bounds - --> $DIR/relaxed-bounds-invalid-places.rs:25:11 + --> $DIR/relaxed-bounds-invalid-places.rs:29:11 | LL | trait Tr: ?Sized {} | ^^^^^^ @@ -47,19 +55,19 @@ LL | trait Tr: ?Sized {} = note: traits are `?Sized` by default error: relaxed bounds are not permitted in trait object types - --> $DIR/relaxed-bounds-invalid-places.rs:29:20 + --> $DIR/relaxed-bounds-invalid-places.rs:33:20 | LL | type O1 = dyn Tr + ?Sized; | ^^^^^^ error: relaxed bounds are not permitted in trait object types - --> $DIR/relaxed-bounds-invalid-places.rs:30:15 + --> $DIR/relaxed-bounds-invalid-places.rs:34:15 | LL | type O2 = dyn ?Sized + ?Sized + Tr; | ^^^^^^ error: relaxed bounds are not permitted in trait object types - --> $DIR/relaxed-bounds-invalid-places.rs:30:24 + --> $DIR/relaxed-bounds-invalid-places.rs:34:24 | LL | type O2 = dyn ?Sized + ?Sized + Tr; | ^^^^^^ @@ -76,5 +84,5 @@ error: bound modifier `?` can only be applied to `Sized` LL | struct S5(*const T) where T: ?Trait<'static> + ?Sized; | ^^^^^^^^^^^^^^^ -error: aborting due to 11 previous errors +error: aborting due to 12 previous errors From 9e50049157eb783ad7bf40c3f4e0cff1f8f2d3bf Mon Sep 17 00:00:00 2001 From: Jason Newcomb Date: Sun, 20 Jul 2025 09:43:45 -0400 Subject: [PATCH 0071/1134] Split `possible_missing_else` from `suspicious_else_formatting`. --- CHANGELOG.md | 1 + clippy_lints/src/declared_lints.rs | 1 + clippy_lints/src/formatting.rs | 28 +++++++++++++++++++++- tests/ui/suspicious_else_formatting.rs | 10 ++++---- tests/ui/suspicious_else_formatting.stderr | 6 +++-- 5 files changed, 38 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a92fbdc767bd..8e0f76ddf759 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6260,6 +6260,7 @@ Released 2018-09-13 [`pointers_in_nomem_asm_block`]: https://rust-lang.github.io/rust-clippy/master/index.html#pointers_in_nomem_asm_block [`positional_named_format_parameters`]: https://rust-lang.github.io/rust-clippy/master/index.html#positional_named_format_parameters [`possible_missing_comma`]: https://rust-lang.github.io/rust-clippy/master/index.html#possible_missing_comma +[`possible_missing_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#possible_missing_else [`precedence`]: https://rust-lang.github.io/rust-clippy/master/index.html#precedence [`precedence_bits`]: https://rust-lang.github.io/rust-clippy/master/index.html#precedence_bits [`print_in_format_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_in_format_impl diff --git a/clippy_lints/src/declared_lints.rs b/clippy_lints/src/declared_lints.rs index c3f8e02b4c06..c0e7ffc77ba9 100644 --- a/clippy_lints/src/declared_lints.rs +++ b/clippy_lints/src/declared_lints.rs @@ -178,6 +178,7 @@ pub static LINTS: &[&::declare_clippy_lint::LintInfo] = &[ crate::format_impl::RECURSIVE_FORMAT_IMPL_INFO, crate::format_push_string::FORMAT_PUSH_STRING_INFO, crate::formatting::POSSIBLE_MISSING_COMMA_INFO, + crate::formatting::POSSIBLE_MISSING_ELSE_INFO, crate::formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING_INFO, crate::formatting::SUSPICIOUS_ELSE_FORMATTING_INFO, crate::formatting::SUSPICIOUS_UNARY_OP_FORMATTING_INFO, diff --git a/clippy_lints/src/formatting.rs b/clippy_lints/src/formatting.rs index 4b482f7b233b..1c751643becb 100644 --- a/clippy_lints/src/formatting.rs +++ b/clippy_lints/src/formatting.rs @@ -91,6 +91,31 @@ declare_clippy_lint! { "suspicious formatting of `else`" } +declare_clippy_lint! { + /// ### What it does + /// Checks for an `if` expression followed by either a block or another `if` that + /// looks like it should have an `else` between them. + /// + /// ### Why is this bad? + /// This is probably some refactoring remnant, even if the code is correct, it + /// might look confusing. + /// + /// ### Example + /// ```rust,ignore + /// if foo { + /// } { // looks like an `else` is missing here + /// } + /// + /// if foo { + /// } if bar { // looks like an `else` is missing here + /// } + /// ``` + #[clippy::version = "1.90.0"] + pub POSSIBLE_MISSING_ELSE, + suspicious, + "possibly missing `else`" +} + declare_clippy_lint! { /// ### What it does /// Checks for possible missing comma in an array. It lints if @@ -116,6 +141,7 @@ declare_lint_pass!(Formatting => [ SUSPICIOUS_ASSIGNMENT_FORMATTING, SUSPICIOUS_UNARY_OP_FORMATTING, SUSPICIOUS_ELSE_FORMATTING, + POSSIBLE_MISSING_ELSE, POSSIBLE_MISSING_COMMA ]); @@ -307,7 +333,7 @@ fn check_missing_else(cx: &EarlyContext<'_>, first: &Expr, second: &Expr) { span_lint_and_note( cx, - SUSPICIOUS_ELSE_FORMATTING, + POSSIBLE_MISSING_ELSE, else_span, format!("this looks like {looks_like} but the `else` is missing"), None, diff --git a/tests/ui/suspicious_else_formatting.rs b/tests/ui/suspicious_else_formatting.rs index 28a3b551116d..072e7b27b0d0 100644 --- a/tests/ui/suspicious_else_formatting.rs +++ b/tests/ui/suspicious_else_formatting.rs @@ -1,6 +1,6 @@ //@aux-build:proc_macro_suspicious_else_formatting.rs -#![warn(clippy::suspicious_else_formatting)] +#![warn(clippy::suspicious_else_formatting, clippy::possible_missing_else)] #![allow( clippy::if_same_then_else, clippy::let_unit_value, @@ -20,12 +20,12 @@ fn main() { // weird `else` formatting: if foo() { } { - //~^ suspicious_else_formatting + //~^ possible_missing_else } if foo() { } if foo() { - //~^ suspicious_else_formatting + //~^ possible_missing_else } let _ = { // if as the last expression @@ -33,7 +33,7 @@ fn main() { if foo() { } if foo() { - //~^ suspicious_else_formatting + //~^ possible_missing_else } else { } @@ -42,7 +42,7 @@ fn main() { let _ = { // if in the middle of a block if foo() { } if foo() { - //~^ suspicious_else_formatting + //~^ possible_missing_else } else { } diff --git a/tests/ui/suspicious_else_formatting.stderr b/tests/ui/suspicious_else_formatting.stderr index affd20b22d9c..04555c6edbd3 100644 --- a/tests/ui/suspicious_else_formatting.stderr +++ b/tests/ui/suspicious_else_formatting.stderr @@ -5,8 +5,8 @@ LL | } { | ^ | = note: to remove this lint, add the missing `else` or add a new line before the next block - = note: `-D clippy::suspicious-else-formatting` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::suspicious_else_formatting)]` + = note: `-D clippy::possible-missing-else` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::possible_missing_else)]` error: this looks like an `else if` but the `else` is missing --> tests/ui/suspicious_else_formatting.rs:27:6 @@ -41,6 +41,8 @@ LL | | { | |____^ | = note: to remove this lint, remove the `else` or remove the new line between `else` and `{..}` + = note: `-D clippy::suspicious-else-formatting` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::suspicious_else_formatting)]` error: this is an `else if` but the formatting might hide it --> tests/ui/suspicious_else_formatting.rs:67:6 From 8b8ffa8b4e58c2c451a53ae428718edf111922e0 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 4 Jul 2025 07:42:28 +0000 Subject: [PATCH 0072/1134] Merge modules and cached_modules for fat LTO The modules vec can already contain serialized modules and there is no need to distinguish between cached and non-cached cgus at LTO time. --- src/back/lto.rs | 12 ------------ src/lib.rs | 3 +-- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/src/back/lto.rs b/src/back/lto.rs index e554dd2500bd..9f2842d7abc8 100644 --- a/src/back/lto.rs +++ b/src/back/lto.rs @@ -175,7 +175,6 @@ fn save_as_file(obj: &[u8], path: &Path) -> Result<(), LtoBitcodeFromRlib> { pub(crate) fn run_fat( cgcx: &CodegenContext, modules: Vec>, - cached_modules: Vec<(SerializedModule, WorkProduct)>, ) -> Result, FatalError> { let dcx = cgcx.create_dcx(); let dcx = dcx.handle(); @@ -186,7 +185,6 @@ pub(crate) fn run_fat( cgcx, dcx, modules, - cached_modules, lto_data.upstream_modules, lto_data.tmp_path, //<o_data.symbols_below_threshold, @@ -197,7 +195,6 @@ fn fat_lto( cgcx: &CodegenContext, _dcx: DiagCtxtHandle<'_>, modules: Vec>, - cached_modules: Vec<(SerializedModule, WorkProduct)>, mut serialized_modules: Vec<(SerializedModule, CString)>, tmp_path: TempDir, //symbols_below_threshold: &[String], @@ -211,21 +208,12 @@ fn fat_lto( // modules that are serialized in-memory. // * `in_memory` contains modules which are already parsed and in-memory, // such as from multi-CGU builds. - // - // All of `cached_modules` (cached from previous incremental builds) can - // immediately go onto the `serialized_modules` modules list and then we can - // split the `modules` array into these two lists. let mut in_memory = Vec::new(); - serialized_modules.extend(cached_modules.into_iter().map(|(buffer, wp)| { - info!("pushing cached module {:?}", wp.cgu_name); - (buffer, CString::new(wp.cgu_name).unwrap()) - })); for module in modules { match module { FatLtoInput::InMemory(m) => in_memory.push(m), FatLtoInput::Serialized { name, buffer } => { info!("pushing serialized module {:?}", name); - let buffer = SerializedModule::Local(buffer); serialized_modules.push((buffer, CString::new(name).unwrap())); } } diff --git a/src/lib.rs b/src/lib.rs index af416929ea73..3fbbaacf1bbb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -359,14 +359,13 @@ impl WriteBackendMethods for GccCodegenBackend { fn run_and_optimize_fat_lto( cgcx: &CodegenContext, modules: Vec>, - cached_modules: Vec<(SerializedModule, WorkProduct)>, diff_fncs: Vec, ) -> Result, FatalError> { if !diff_fncs.is_empty() { unimplemented!(); } - back::lto::run_fat(cgcx, modules, cached_modules) + back::lto::run_fat(cgcx, modules) } fn run_thin_lto( From 803ada77a5104911ca972926610d2d4b9f3f511e Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 4 Jul 2025 14:59:53 +0000 Subject: [PATCH 0073/1134] Move LTO symbol export calculation from backends to cg_ssa --- messages.ftl | 8 ------ src/back/lto.rs | 74 ++++++------------------------------------------- src/errors.rs | 13 --------- 3 files changed, 8 insertions(+), 87 deletions(-) diff --git a/messages.ftl b/messages.ftl index 55a28bc9493e..a70ac08f01ae 100644 --- a/messages.ftl +++ b/messages.ftl @@ -3,12 +3,4 @@ codegen_gcc_unwinding_inline_asm = codegen_gcc_copy_bitcode = failed to copy bitcode to object file: {$err} -codegen_gcc_dynamic_linking_with_lto = - cannot prefer dynamic linking when performing LTO - .note = only 'staticlib', 'bin', and 'cdylib' outputs are supported with LTO - -codegen_gcc_lto_disallowed = lto can only be run for executables, cdylibs and static library outputs - -codegen_gcc_lto_dylib = lto cannot be used for `dylib` crate type without `-Zdylib-lto` - codegen_gcc_lto_bitcode_from_rlib = failed to get bitcode from object file for LTO ({$gcc_err}) diff --git a/src/back/lto.rs b/src/back/lto.rs index 9f2842d7abc8..e075aa8480aa 100644 --- a/src/back/lto.rs +++ b/src/back/lto.rs @@ -24,36 +24,24 @@ use std::sync::Arc; use gccjit::{Context, OutputKind}; use object::read::archive::ArchiveFile; -use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared}; -use rustc_codegen_ssa::back::symbol_export; +use rustc_codegen_ssa::back::lto::{ + SerializedModule, ThinModule, ThinShared, exported_symbols_for_lto, +}; use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput}; use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::{ModuleCodegen, ModuleKind, looks_like_rust_object_file}; use rustc_data_structures::memmap::Mmap; use rustc_errors::{DiagCtxtHandle, FatalError}; -use rustc_hir::def_id::LOCAL_CRATE; use rustc_middle::bug; use rustc_middle::dep_graph::WorkProduct; -use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel}; -use rustc_session::config::{CrateType, Lto}; +use rustc_session::config::Lto; use rustc_target::spec::RelocModel; use tempfile::{TempDir, tempdir}; use crate::back::write::save_temp_bitcode; -use crate::errors::{DynamicLinkingWithLTO, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib}; +use crate::errors::LtoBitcodeFromRlib; use crate::{GccCodegenBackend, GccContext, SyncContext, to_gcc_opt_level}; -pub fn crate_type_allows_lto(crate_type: CrateType) -> bool { - match crate_type { - CrateType::Executable - | CrateType::Dylib - | CrateType::Staticlib - | CrateType::Cdylib - | CrateType::Sdylib => true, - CrateType::Rlib | CrateType::ProcMacro => false, - } -} - struct LtoData { // TODO(antoyo): use symbols_below_threshold. //symbols_below_threshold: Vec, @@ -65,15 +53,8 @@ fn prepare_lto( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, ) -> Result { - let export_threshold = match cgcx.lto { - // We're just doing LTO for our one crate - Lto::ThinLocal => SymbolExportLevel::Rust, - - // We're doing LTO for the entire crate graph - Lto::Fat | Lto::Thin => symbol_export::crates_export_threshold(&cgcx.crate_types), - - Lto::No => panic!("didn't request LTO but we're doing LTO"), - }; + // FIXME(bjorn3): Limit LTO exports to these symbols + let _symbols_below_threshold = exported_symbols_for_lto(cgcx, dcx)?; let tmp_path = match tempdir() { Ok(tmp_path) => tmp_path, @@ -83,20 +64,6 @@ fn prepare_lto( } }; - let symbol_filter = &|&(ref name, info): &(String, SymbolExportInfo)| { - if info.level.is_below_threshold(export_threshold) || info.used { - Some(name.clone()) - } else { - None - } - }; - let exported_symbols = cgcx.exported_symbols.as_ref().expect("needs exported symbols for LTO"); - let mut symbols_below_threshold = { - let _timer = cgcx.prof.generic_activity("GCC_lto_generate_symbols_below_threshold"); - exported_symbols[&LOCAL_CRATE].iter().filter_map(symbol_filter).collect::>() - }; - info!("{} symbols to preserve in this crate", symbols_below_threshold.len()); - // If we're performing LTO for the entire crate graph, then for each of our // upstream dependencies, find the corresponding rlib and load the bitcode // from the archive. @@ -105,32 +72,7 @@ fn prepare_lto( // with either fat or thin LTO let mut upstream_modules = Vec::new(); if cgcx.lto != Lto::ThinLocal { - // Make sure we actually can run LTO - for crate_type in cgcx.crate_types.iter() { - if !crate_type_allows_lto(*crate_type) { - dcx.emit_err(LtoDisallowed); - return Err(FatalError); - } - if *crate_type == CrateType::Dylib && !cgcx.opts.unstable_opts.dylib_lto { - dcx.emit_err(LtoDylib); - return Err(FatalError); - } - } - - if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto { - dcx.emit_err(DynamicLinkingWithLTO); - return Err(FatalError); - } - - for &(cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() { - let exported_symbols = - cgcx.exported_symbols.as_ref().expect("needs exported symbols for LTO"); - { - let _timer = cgcx.prof.generic_activity("GCC_lto_generate_symbols_below_threshold"); - symbols_below_threshold - .extend(exported_symbols[&cnum].iter().filter_map(symbol_filter)); - } - + for &(_cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() { let archive_data = unsafe { Mmap::map(File::open(path).expect("couldn't open rlib")).expect("couldn't map rlib") }; diff --git a/src/errors.rs b/src/errors.rs index b7e7343460fb..0aa16bd88b43 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -14,19 +14,6 @@ pub(crate) struct CopyBitcode { pub err: std::io::Error, } -#[derive(Diagnostic)] -#[diag(codegen_gcc_dynamic_linking_with_lto)] -#[note] -pub(crate) struct DynamicLinkingWithLTO; - -#[derive(Diagnostic)] -#[diag(codegen_gcc_lto_disallowed)] -pub(crate) struct LtoDisallowed; - -#[derive(Diagnostic)] -#[diag(codegen_gcc_lto_dylib)] -pub(crate) struct LtoDylib; - #[derive(Diagnostic)] #[diag(codegen_gcc_lto_bitcode_from_rlib)] pub(crate) struct LtoBitcodeFromRlib { From df5367810bb1af76f82f9dff4a727bee8e54f3bc Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sun, 6 Jul 2025 15:57:20 +0000 Subject: [PATCH 0074/1134] Merge exported_symbols computation into exported_symbols_for_lto And move exported_symbols_for_lto call from backends to cg_ssa. --- src/back/lto.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/back/lto.rs b/src/back/lto.rs index e075aa8480aa..f957bb7f101b 100644 --- a/src/back/lto.rs +++ b/src/back/lto.rs @@ -24,9 +24,7 @@ use std::sync::Arc; use gccjit::{Context, OutputKind}; use object::read::archive::ArchiveFile; -use rustc_codegen_ssa::back::lto::{ - SerializedModule, ThinModule, ThinShared, exported_symbols_for_lto, -}; +use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared}; use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput}; use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::{ModuleCodegen, ModuleKind, looks_like_rust_object_file}; @@ -54,7 +52,7 @@ fn prepare_lto( dcx: DiagCtxtHandle<'_>, ) -> Result { // FIXME(bjorn3): Limit LTO exports to these symbols - let _symbols_below_threshold = exported_symbols_for_lto(cgcx, dcx)?; + let _symbols_below_threshold = &cgcx.exported_symbols_for_lto; let tmp_path = match tempdir() { Ok(tmp_path) => tmp_path, From ecab766c2cc08d22205c01b6ad6c903389ea480d Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sun, 6 Jul 2025 16:06:10 +0000 Subject: [PATCH 0075/1134] Move exported_symbols_for_lto out of CodegenContext --- src/back/lto.rs | 3 --- src/lib.rs | 4 ++++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/back/lto.rs b/src/back/lto.rs index f957bb7f101b..d107e56fa35a 100644 --- a/src/back/lto.rs +++ b/src/back/lto.rs @@ -51,9 +51,6 @@ fn prepare_lto( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, ) -> Result { - // FIXME(bjorn3): Limit LTO exports to these symbols - let _symbols_below_threshold = &cgcx.exported_symbols_for_lto; - let tmp_path = match tempdir() { Ok(tmp_path) => tmp_path, Err(error) => { diff --git a/src/lib.rs b/src/lib.rs index 3fbbaacf1bbb..c8bf5bd8f67b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -358,6 +358,8 @@ impl WriteBackendMethods for GccCodegenBackend { fn run_and_optimize_fat_lto( cgcx: &CodegenContext, + // FIXME(bjorn3): Limit LTO exports to these symbols + _exported_symbols_for_lto: &[String], modules: Vec>, diff_fncs: Vec, ) -> Result, FatalError> { @@ -370,6 +372,8 @@ impl WriteBackendMethods for GccCodegenBackend { fn run_thin_lto( cgcx: &CodegenContext, + // FIXME(bjorn3): Limit LTO exports to these symbols + _exported_symbols_for_lto: &[String], modules: Vec<(String, Self::ThinBuffer)>, cached_modules: Vec<(SerializedModule, WorkProduct)>, ) -> Result<(Vec>, Vec), FatalError> { From 28ccfad3a8478c4bf160d9ab30671eb1a4429590 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sun, 6 Jul 2025 16:59:30 +0000 Subject: [PATCH 0076/1134] Remove each_linked_rlib_for_lto from CodegenContext --- src/back/lto.rs | 9 ++++++--- src/lib.rs | 7 +++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/back/lto.rs b/src/back/lto.rs index d107e56fa35a..d558dfbc1c45 100644 --- a/src/back/lto.rs +++ b/src/back/lto.rs @@ -49,6 +49,7 @@ struct LtoData { fn prepare_lto( cgcx: &CodegenContext, + each_linked_rlib_for_lto: &[PathBuf], dcx: DiagCtxtHandle<'_>, ) -> Result { let tmp_path = match tempdir() { @@ -67,7 +68,7 @@ fn prepare_lto( // with either fat or thin LTO let mut upstream_modules = Vec::new(); if cgcx.lto != Lto::ThinLocal { - for &(_cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() { + for path in each_linked_rlib_for_lto { let archive_data = unsafe { Mmap::map(File::open(path).expect("couldn't open rlib")).expect("couldn't map rlib") }; @@ -111,11 +112,12 @@ fn save_as_file(obj: &[u8], path: &Path) -> Result<(), LtoBitcodeFromRlib> { /// for further optimization. pub(crate) fn run_fat( cgcx: &CodegenContext, + each_linked_rlib_for_lto: &[PathBuf], modules: Vec>, ) -> Result, FatalError> { let dcx = cgcx.create_dcx(); let dcx = dcx.handle(); - let lto_data = prepare_lto(cgcx, dcx)?; + let lto_data = prepare_lto(cgcx, each_linked_rlib_for_lto, dcx)?; /*let symbols_below_threshold = lto_data.symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::>();*/ fat_lto( @@ -281,12 +283,13 @@ impl ModuleBufferMethods for ModuleBuffer { /// can simply be copied over from the incr. comp. cache. pub(crate) fn run_thin( cgcx: &CodegenContext, + each_linked_rlib_for_lto: &[PathBuf], modules: Vec<(String, ThinBuffer)>, cached_modules: Vec<(SerializedModule, WorkProduct)>, ) -> Result<(Vec>, Vec), FatalError> { let dcx = cgcx.create_dcx(); let dcx = dcx.handle(); - let lto_data = prepare_lto(cgcx, dcx)?; + let lto_data = prepare_lto(cgcx, each_linked_rlib_for_lto, dcx)?; if cgcx.opts.cg.linker_plugin_lto.enabled() { unreachable!( "We should never reach this case if the LTO step \ diff --git a/src/lib.rs b/src/lib.rs index c8bf5bd8f67b..71765c511381 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -81,6 +81,7 @@ mod type_of; use std::any::Any; use std::fmt::Debug; use std::ops::Deref; +use std::path::PathBuf; #[cfg(not(feature = "master"))] use std::sync::atomic::AtomicBool; #[cfg(not(feature = "master"))] @@ -360,6 +361,7 @@ impl WriteBackendMethods for GccCodegenBackend { cgcx: &CodegenContext, // FIXME(bjorn3): Limit LTO exports to these symbols _exported_symbols_for_lto: &[String], + each_linked_rlib_for_lto: &[PathBuf], modules: Vec>, diff_fncs: Vec, ) -> Result, FatalError> { @@ -367,17 +369,18 @@ impl WriteBackendMethods for GccCodegenBackend { unimplemented!(); } - back::lto::run_fat(cgcx, modules) + back::lto::run_fat(cgcx, each_linked_rlib_for_lto, modules) } fn run_thin_lto( cgcx: &CodegenContext, // FIXME(bjorn3): Limit LTO exports to these symbols _exported_symbols_for_lto: &[String], + each_linked_rlib_for_lto: &[PathBuf], modules: Vec<(String, Self::ThinBuffer)>, cached_modules: Vec<(SerializedModule, WorkProduct)>, ) -> Result<(Vec>, Vec), FatalError> { - back::lto::run_thin(cgcx, modules, cached_modules) + back::lto::run_thin(cgcx, each_linked_rlib_for_lto, modules, cached_modules) } fn print_pass_timings(&self) { From 4653b7acbdd50f14d35f5b2f95c3af765c0799ec Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Fri, 18 Jul 2025 13:18:56 +0000 Subject: [PATCH 0077/1134] Stabilize const `TypeId::of` --- library/core/src/any.rs | 4 ++-- tests/ui/const-generics/issues/issue-90318.rs | 1 - tests/ui/const-generics/issues/issue-90318.stderr | 4 ++-- tests/ui/consts/const-typeid-of-rpass.rs | 2 -- tests/ui/consts/const_cmp_type_id.rs | 2 +- tests/ui/consts/const_transmute_type_id.rs | 2 +- tests/ui/consts/const_transmute_type_id2.rs | 2 +- tests/ui/consts/const_transmute_type_id3.rs | 2 +- tests/ui/consts/const_transmute_type_id4.rs | 2 +- tests/ui/consts/const_transmute_type_id5.rs | 2 +- tests/ui/consts/issue-102117.rs | 2 -- tests/ui/consts/issue-102117.stderr | 4 ++-- tests/ui/consts/issue-73976-monomorphic.rs | 1 - tests/ui/consts/issue-73976-polymorphic.rs | 1 - tests/ui/consts/issue-73976-polymorphic.stderr | 4 ++-- 15 files changed, 14 insertions(+), 21 deletions(-) diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 38393379a78a..ceb9748e7feb 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -725,7 +725,7 @@ unsafe impl Send for TypeId {} unsafe impl Sync for TypeId {} #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_type_id", issue = "77125")] +#[rustc_const_unstable(feature = "const_cmp", issue = "143800")] impl const PartialEq for TypeId { #[inline] fn eq(&self, other: &Self) -> bool { @@ -773,7 +773,7 @@ impl TypeId { /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_type_id", issue = "77125")] + #[rustc_const_stable(feature = "const_type_id", since = "CURRENT_RUSTC_VERSION")] pub const fn of() -> TypeId { const { intrinsics::type_id::() } } diff --git a/tests/ui/const-generics/issues/issue-90318.rs b/tests/ui/const-generics/issues/issue-90318.rs index 239171217eba..35b0dd216a1a 100644 --- a/tests/ui/const-generics/issues/issue-90318.rs +++ b/tests/ui/const-generics/issues/issue-90318.rs @@ -1,4 +1,3 @@ -#![feature(const_type_id)] #![feature(generic_const_exprs)] #![feature(const_trait_impl, const_cmp)] #![feature(core_intrinsics)] diff --git a/tests/ui/const-generics/issues/issue-90318.stderr b/tests/ui/const-generics/issues/issue-90318.stderr index 7031230db91c..f13fd795d7a1 100644 --- a/tests/ui/const-generics/issues/issue-90318.stderr +++ b/tests/ui/const-generics/issues/issue-90318.stderr @@ -1,5 +1,5 @@ error: overly complex generic constant - --> $DIR/issue-90318.rs:15:8 + --> $DIR/issue-90318.rs:14:8 | LL | If<{ TypeId::of::() != TypeId::of::<()>() }>: True, | ^^-----------------^^^^^^^^^^^^^^^^^^^^^^^^ @@ -10,7 +10,7 @@ LL | If<{ TypeId::of::() != TypeId::of::<()>() }>: True, = note: this operation may be supported in the future error: overly complex generic constant - --> $DIR/issue-90318.rs:22:8 + --> $DIR/issue-90318.rs:21:8 | LL | If<{ TypeId::of::() != TypeId::of::<()>() }>: True, | ^^-----------------^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/consts/const-typeid-of-rpass.rs b/tests/ui/consts/const-typeid-of-rpass.rs index 15ffdd1e83a2..30f410708933 100644 --- a/tests/ui/consts/const-typeid-of-rpass.rs +++ b/tests/ui/consts/const-typeid-of-rpass.rs @@ -1,6 +1,4 @@ //@ run-pass -#![feature(const_type_id)] -#![feature(core_intrinsics)] use std::any::TypeId; diff --git a/tests/ui/consts/const_cmp_type_id.rs b/tests/ui/consts/const_cmp_type_id.rs index db2d50f4d22c..e312c0b75d52 100644 --- a/tests/ui/consts/const_cmp_type_id.rs +++ b/tests/ui/consts/const_cmp_type_id.rs @@ -1,5 +1,5 @@ //@ compile-flags: -Znext-solver -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature(const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id.rs b/tests/ui/consts/const_transmute_type_id.rs index a2d4cf378309..98783ad5b81b 100644 --- a/tests/ui/consts/const_transmute_type_id.rs +++ b/tests/ui/consts/const_transmute_type_id.rs @@ -1,4 +1,4 @@ -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature(const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id2.rs b/tests/ui/consts/const_transmute_type_id2.rs index 3ceb2b942b04..7e09947b768d 100644 --- a/tests/ui/consts/const_transmute_type_id2.rs +++ b/tests/ui/consts/const_transmute_type_id2.rs @@ -1,6 +1,6 @@ //@ normalize-stderr: "0x(ff)+" -> "" -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature( const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id3.rs b/tests/ui/consts/const_transmute_type_id3.rs index f1bb8cddf774..77c469d42f50 100644 --- a/tests/ui/consts/const_transmute_type_id3.rs +++ b/tests/ui/consts/const_transmute_type_id3.rs @@ -1,7 +1,7 @@ //! Test that all bytes of a TypeId must have the //! TypeId marker provenance. -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature( const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id4.rs b/tests/ui/consts/const_transmute_type_id4.rs index 0ea75f2a2f4d..bedd6084a16b 100644 --- a/tests/ui/consts/const_transmute_type_id4.rs +++ b/tests/ui/consts/const_transmute_type_id4.rs @@ -1,4 +1,4 @@ -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature(const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/const_transmute_type_id5.rs b/tests/ui/consts/const_transmute_type_id5.rs index ae0429f8dbb6..7f9a34104a35 100644 --- a/tests/ui/consts/const_transmute_type_id5.rs +++ b/tests/ui/consts/const_transmute_type_id5.rs @@ -1,7 +1,7 @@ //! Test that we require an equal TypeId to have an integer part that properly //! reflects the type id hash. -#![feature(const_type_id, const_trait_impl, const_cmp)] +#![feature(const_trait_impl, const_cmp)] use std::any::TypeId; diff --git a/tests/ui/consts/issue-102117.rs b/tests/ui/consts/issue-102117.rs index 6cb9832bcd81..b7955283a8d8 100644 --- a/tests/ui/consts/issue-102117.rs +++ b/tests/ui/consts/issue-102117.rs @@ -1,5 +1,3 @@ -#![feature(const_type_id)] - use std::alloc::Layout; use std::any::TypeId; use std::mem::transmute; diff --git a/tests/ui/consts/issue-102117.stderr b/tests/ui/consts/issue-102117.stderr index da92db87f182..cea355d01d7b 100644 --- a/tests/ui/consts/issue-102117.stderr +++ b/tests/ui/consts/issue-102117.stderr @@ -1,5 +1,5 @@ error[E0310]: the parameter type `T` may not live long enough - --> $DIR/issue-102117.rs:19:26 + --> $DIR/issue-102117.rs:17:26 | LL | type_id: TypeId::of::(), | ^^^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL | pub fn new() -> &'static Self { | +++++++++ error[E0310]: the parameter type `T` may not live long enough - --> $DIR/issue-102117.rs:19:26 + --> $DIR/issue-102117.rs:17:26 | LL | type_id: TypeId::of::(), | ^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/consts/issue-73976-monomorphic.rs b/tests/ui/consts/issue-73976-monomorphic.rs index 5f364cd995e0..2867b836f482 100644 --- a/tests/ui/consts/issue-73976-monomorphic.rs +++ b/tests/ui/consts/issue-73976-monomorphic.rs @@ -5,7 +5,6 @@ // will be properly rejected. This test will ensure that monomorphic use of these // would not be wrongly rejected in patterns. -#![feature(const_type_id)] #![feature(const_type_name)] #![feature(const_trait_impl)] #![feature(const_cmp)] diff --git a/tests/ui/consts/issue-73976-polymorphic.rs b/tests/ui/consts/issue-73976-polymorphic.rs index 98b4005792db..db06706a970c 100644 --- a/tests/ui/consts/issue-73976-polymorphic.rs +++ b/tests/ui/consts/issue-73976-polymorphic.rs @@ -5,7 +5,6 @@ // This test case should either run-pass or be rejected at compile time. // Currently we just disallow this usage and require pattern is monomorphic. -#![feature(const_type_id)] #![feature(const_type_name)] use std::any::{self, TypeId}; diff --git a/tests/ui/consts/issue-73976-polymorphic.stderr b/tests/ui/consts/issue-73976-polymorphic.stderr index ec9512a26163..41a5e804c676 100644 --- a/tests/ui/consts/issue-73976-polymorphic.stderr +++ b/tests/ui/consts/issue-73976-polymorphic.stderr @@ -1,5 +1,5 @@ error[E0158]: constant pattern cannot depend on generic parameters - --> $DIR/issue-73976-polymorphic.rs:20:37 + --> $DIR/issue-73976-polymorphic.rs:19:37 | LL | impl GetTypeId { | ----------------------------- @@ -12,7 +12,7 @@ LL | matches!(GetTypeId::::VALUE, GetTypeId::::VALUE) | ^^^^^^^^^^^^^^^^^^^^^ `const` depends on a generic parameter error[E0158]: constant pattern cannot depend on generic parameters - --> $DIR/issue-73976-polymorphic.rs:31:42 + --> $DIR/issue-73976-polymorphic.rs:30:42 | LL | impl GetTypeNameLen { | ---------------------------------- From ed50029b925e07ad92b8eaa6e563a4a494ed42a4 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Mon, 21 Jul 2025 12:18:07 -0500 Subject: [PATCH 0078/1134] ci: Switch to nightly rustfmt We are getting warnings in CI about unsupported features. There isn't any reason to use stable rustfmt so switch the channel here. --- library/compiler-builtins/.github/workflows/main.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/compiler-builtins/.github/workflows/main.yaml b/library/compiler-builtins/.github/workflows/main.yaml index 541c99c828dc..972f1b89878a 100644 --- a/library/compiler-builtins/.github/workflows/main.yaml +++ b/library/compiler-builtins/.github/workflows/main.yaml @@ -311,8 +311,8 @@ jobs: timeout-minutes: 10 steps: - uses: actions/checkout@v4 - - name: Install stable `rustfmt` - run: rustup set profile minimal && rustup default stable && rustup component add rustfmt + - name: Install nightly `rustfmt` + run: rustup set profile minimal && rustup default nightly && rustup component add rustfmt - run: cargo fmt -- --check extensive: From c1be95ca0c2be04060da7a01f6892e5e6f2ef9dc Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Mon, 21 Jul 2025 14:16:43 -0400 Subject: [PATCH 0079/1134] Add missing inline attribute --- src/allocator.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/allocator.rs b/src/allocator.rs index 0d8dc93274f9..66258390d909 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -99,11 +99,14 @@ fn create_const_value_function( let func = context.new_function(None, FunctionType::Exported, output, &[], name, false); #[cfg(feature = "master")] - func.add_attribute(FnAttribute::Visibility(symbol_visibility_to_gcc( - tcx.sess.default_visibility(), - ))); + { + func.add_attribute(FnAttribute::Visibility(symbol_visibility_to_gcc( + tcx.sess.default_visibility(), + ))); - func.add_attribute(FnAttribute::AlwaysInline); + func.add_attribute(FnAttribute::AlwaysInline); + func.add_attribute(FnAttribute::Inline); + } if tcx.sess.must_emit_unwind_tables() { // TODO(antoyo): emit unwind tables. From cf80eeec1650add1e24f114841154484fa051b70 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Mon, 21 Jul 2025 14:42:45 -0400 Subject: [PATCH 0080/1134] Fix clippy warnings --- build_system/src/abi_test.rs | 2 +- build_system/src/fuzz.rs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/build_system/src/abi_test.rs b/build_system/src/abi_test.rs index 3c1531be27a5..a85886d87f36 100644 --- a/build_system/src/abi_test.rs +++ b/build_system/src/abi_test.rs @@ -31,7 +31,7 @@ pub fn run() -> Result<(), String> { Some("clones/abi-cafe".as_ref()), true, ) - .map_err(|err| (format!("Git clone failed with message: {err:?}!")))?; + .map_err(|err| format!("Git clone failed with message: {err:?}!"))?; // Configure abi-cafe to use the exact same rustc version we use - this is crucial. // Otherwise, the concept of ABI compatibility becomes meanignless. std::fs::copy("rust-toolchain", "clones/abi-cafe/rust-toolchain") diff --git a/build_system/src/fuzz.rs b/build_system/src/fuzz.rs index 453211366b31..9714ce29af90 100644 --- a/build_system/src/fuzz.rs +++ b/build_system/src/fuzz.rs @@ -43,18 +43,18 @@ pub fn run() -> Result<(), String> { "--start" => { start = str::parse(&args.next().ok_or_else(|| "Fuzz start not provided!".to_string())?) - .map_err(|err| (format!("Fuzz start not a number {err:?}!")))?; + .map_err(|err| format!("Fuzz start not a number {err:?}!"))?; } "--count" => { count = str::parse(&args.next().ok_or_else(|| "Fuzz count not provided!".to_string())?) - .map_err(|err| (format!("Fuzz count not a number {err:?}!")))?; + .map_err(|err| format!("Fuzz count not a number {err:?}!"))?; } "-j" | "--jobs" => { threads = str::parse( &args.next().ok_or_else(|| "Fuzz thread count not provided!".to_string())?, ) - .map_err(|err| (format!("Fuzz thread count not a number {err:?}!")))?; + .map_err(|err| format!("Fuzz thread count not a number {err:?}!"))?; } _ => return Err(format!("Unknown option {arg}")), } @@ -66,7 +66,7 @@ pub fn run() -> Result<(), String> { Some("clones/rustlantis".as_ref()), true, ) - .map_err(|err| (format!("Git clone failed with message: {err:?}!")))?; + .map_err(|err| format!("Git clone failed with message: {err:?}!"))?; // Ensure that we are on the newest rustlantis commit. let cmd: &[&dyn AsRef] = &[&"git", &"pull", &"origin"]; From 18cc4f06a5252f0868be4ea620076247da68077c Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Mon, 21 Jul 2025 14:45:00 -0400 Subject: [PATCH 0081/1134] Fix spelling mistakes --- src/lib.rs | 4 ++-- tools/cspell_dicts/rustc_codegen_gcc.txt | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index af416929ea73..5e65a36f2737 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -360,9 +360,9 @@ impl WriteBackendMethods for GccCodegenBackend { cgcx: &CodegenContext, modules: Vec>, cached_modules: Vec<(SerializedModule, WorkProduct)>, - diff_fncs: Vec, + diff_functions: Vec, ) -> Result, FatalError> { - if !diff_fncs.is_empty() { + if !diff_functions.is_empty() { unimplemented!(); } diff --git a/tools/cspell_dicts/rustc_codegen_gcc.txt b/tools/cspell_dicts/rustc_codegen_gcc.txt index 31023e50ffa1..b19d7f67eab3 100644 --- a/tools/cspell_dicts/rustc_codegen_gcc.txt +++ b/tools/cspell_dicts/rustc_codegen_gcc.txt @@ -8,6 +8,7 @@ clzll cmse codegened csky +ctfe ctlz ctpop cttz @@ -47,6 +48,7 @@ mavx mcmodel minimumf minnumf +miri monomorphization monomorphizations monomorphized From f391acb9a9ee4db9aa72315bb80e94692c759602 Mon Sep 17 00:00:00 2001 From: LorrensP-2158466 Date: Mon, 7 Jul 2025 15:16:59 +0200 Subject: [PATCH 0082/1134] Implement nondet behaviour and change/add tests. --- src/tools/miri/src/intrinsics/mod.rs | 7 +- src/tools/miri/src/lib.rs | 2 + src/tools/miri/src/math.rs | 188 ++++++++++++++++--- src/tools/miri/src/shims/foreign_items.rs | 217 ++++++++++++---------- src/tools/miri/tests/pass/float.rs | 154 ++++++++++----- 5 files changed, 394 insertions(+), 174 deletions(-) diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index 22fcd998cedb..1ffba2726a2a 100644 --- a/src/tools/miri/src/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -13,7 +13,6 @@ use rustc_span::{Symbol, sym}; use self::atomic::EvalContextExt as _; use self::helpers::{ToHost, ToSoft, check_intrinsic_arg_count}; use self::simd::EvalContextExt as _; -use crate::math::apply_random_float_error_ulp; use crate::*; impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} @@ -348,13 +347,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let f = this.read_scalar(f)?.to_f32()?; let i = this.read_scalar(i)?.to_i32()?; - let res = math::fixed_powi_float_value(this, f, i).unwrap_or_else(|| { + let res = math::fixed_powi_value(this, f, i).unwrap_or_else(|| { // Using host floats (but it's fine, this operation does not have guaranteed precision). let res = f.to_host().powi(i).to_soft(); // Apply a relative error of 4ULP to introduce some non-determinism // simulating imprecise implementations and optimizations. - apply_random_float_error_ulp( + math::apply_random_float_error_ulp( this, res, 2, // log2(4) ) }); @@ -366,7 +365,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let f = this.read_scalar(f)?.to_f64()?; let i = this.read_scalar(i)?.to_i32()?; - let res = math::fixed_powi_float_value(this, f, i).unwrap_or_else(|| { + let res = math::fixed_powi_value(this, f, i).unwrap_or_else(|| { // Using host floats (but it's fine, this operation does not have guaranteed precision). let res = f.to_host().powi(i).to_soft(); diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index a591d21071db..c9086922a51f 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -16,6 +16,8 @@ #![feature(derive_coerce_pointee)] #![feature(arbitrary_self_types)] #![feature(iter_advance_by)] +#![feature(f16)] +#![feature(f128)] // Configure clippy and other lints #![allow( clippy::collapsible_else_if, diff --git a/src/tools/miri/src/math.rs b/src/tools/miri/src/math.rs index 7713e1d31568..f576bed9e50a 100644 --- a/src/tools/miri/src/math.rs +++ b/src/tools/miri/src/math.rs @@ -1,8 +1,9 @@ use std::ops::Neg; +use std::{f16, f32, f64, f128}; use rand::Rng as _; use rustc_apfloat::Float as _; -use rustc_apfloat::ieee::{IeeeFloat, Semantics}; +use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, Semantics, SingleS}; use rustc_middle::ty::{self, FloatTy, ScalarInt}; use crate::*; @@ -52,52 +53,95 @@ pub(crate) fn apply_random_float_error_ulp( apply_random_float_error(ecx, val, err_scale) } -/// Applies a random 16ULP floating point error to `val` and returns the new value. +/// Applies a random ULP floating point error to `val` and returns the new value. +/// So if you want an X ULP error, `ulp_exponent` should be log2(X). +/// /// Will fail if `val` is not a floating point number. pub(crate) fn apply_random_float_error_to_imm<'tcx>( ecx: &mut MiriInterpCx<'tcx>, val: ImmTy<'tcx>, ulp_exponent: u32, ) -> InterpResult<'tcx, ImmTy<'tcx>> { + let this = ecx.eval_context_mut(); let scalar = val.to_scalar_int()?; let res: ScalarInt = match val.layout.ty.kind() { ty::Float(FloatTy::F16) => - apply_random_float_error_ulp(ecx, scalar.to_f16(), ulp_exponent).into(), + apply_random_float_error_ulp(this, scalar.to_f16(), ulp_exponent).into(), ty::Float(FloatTy::F32) => - apply_random_float_error_ulp(ecx, scalar.to_f32(), ulp_exponent).into(), + apply_random_float_error_ulp(this, scalar.to_f32(), ulp_exponent).into(), ty::Float(FloatTy::F64) => - apply_random_float_error_ulp(ecx, scalar.to_f64(), ulp_exponent).into(), + apply_random_float_error_ulp(this, scalar.to_f64(), ulp_exponent).into(), ty::Float(FloatTy::F128) => - apply_random_float_error_ulp(ecx, scalar.to_f128(), ulp_exponent).into(), + apply_random_float_error_ulp(this, scalar.to_f128(), ulp_exponent).into(), _ => bug!("intrinsic called with non-float input type"), }; interp_ok(ImmTy::from_scalar_int(res, val.layout)) } -/// Given an floating-point operation and a floating-point value, clamps the result to the output -/// range of the given operation. +/// Given a floating-point operation and a floating-point value, clamps the result to the output +/// range of the given operation according to the C standard, if any. pub(crate) fn clamp_float_value( intrinsic_name: &str, val: IeeeFloat, -) -> IeeeFloat { +) -> IeeeFloat +where + IeeeFloat: IeeeExt, +{ + let zero = IeeeFloat::::ZERO; + let one = IeeeFloat::::one(); + let two = IeeeFloat::::two(); + let pi = IeeeFloat::::pi(); + let pi_over_2 = (pi / two).value; + match intrinsic_name { - // sin and cos: [-1, 1] - "sinf32" | "cosf32" | "sinf64" | "cosf64" => - val.clamp(IeeeFloat::::one().neg(), IeeeFloat::::one()), - // exp: [0, +INF] - "expf32" | "exp2f32" | "expf64" | "exp2f64" => - IeeeFloat::::maximum(val, IeeeFloat::::ZERO), + // sin, cos, tanh: [-1, 1] + #[rustfmt::skip] + | "sinf32" + | "sinf64" + | "cosf32" + | "cosf64" + | "tanhf" + | "tanh" + => val.clamp(one.neg(), one), + + // exp: [0, +INF) + "expf32" | "exp2f32" | "expf64" | "exp2f64" => val.maximum(zero), + + // cosh: [1, +INF) + "coshf" | "cosh" => val.maximum(one), + + // acos: [0, π] + "acosf" | "acos" => val.clamp(zero, pi), + + // asin: [-π, +π] + "asinf" | "asin" => val.clamp(pi.neg(), pi), + + // atan: (-π/2, +π/2) + "atanf" | "atan" => val.clamp(pi_over_2.neg(), pi_over_2), + + // erfc: (-1, 1) + "erff" | "erf" => val.clamp(one.neg(), one), + + // erfc: (0, 2) + "erfcf" | "erfc" => val.clamp(zero, two), + + // atan2(y, x): arctan(y/x) in [−π, +π] + "atan2f" | "atan2" => val.clamp(pi.neg(), pi), + _ => val, } } /// For the intrinsics: -/// - sinf32, sinf64 -/// - cosf32, cosf64 +/// - sinf32, sinf64, sinhf, sinh +/// - cosf32, cosf64, coshf, cosh +/// - tanhf, tanh, atanf, atan, atan2f, atan2 /// - expf32, expf64, exp2f32, exp2f64 /// - logf32, logf64, log2f32, log2f64, log10f32, log10f64 /// - powf32, powf64 +/// - erff, erf, erfcf, erfc +/// - hypotf, hypot /// /// # Return /// @@ -125,16 +169,68 @@ pub(crate) fn fixed_float_value( ecx: &mut MiriInterpCx<'_>, intrinsic_name: &str, args: &[IeeeFloat], -) -> Option> { +) -> Option> +where + IeeeFloat: IeeeExt, +{ let this = ecx.eval_context_mut(); let one = IeeeFloat::::one(); + let two = IeeeFloat::::two(); + let three = IeeeFloat::::three(); + let pi = IeeeFloat::::pi(); + let pi_over_2 = (pi / two).value; + let pi_over_4 = (pi_over_2 / two).value; + Some(match (intrinsic_name, args) { - // cos(+- 0) = 1 - ("cosf32" | "cosf64", [input]) if input.is_zero() => one, + // cos(±0) and cosh(±0)= 1 + ("cosf32" | "cosf64" | "coshf" | "cosh", [input]) if input.is_zero() => one, // e^0 = 1 ("expf32" | "expf64" | "exp2f32" | "exp2f64", [input]) if input.is_zero() => one, + // tanh(±INF) = ±1 + ("tanhf" | "tanh", [input]) if input.is_infinite() => one.copy_sign(*input), + + // atan(±INF) = ±π/2 + ("atanf" | "atan", [input]) if input.is_infinite() => pi_over_2.copy_sign(*input), + + // erf(±INF) = ±1 + ("erff" | "erf", [input]) if input.is_infinite() => one.copy_sign(*input), + + // erfc(-INF) = 2 + ("erfcf" | "erfc", [input]) if input.is_neg_infinity() => (one + one).value, + + // hypot(x, ±0) = abs(x), if x is not a NaN. + ("_hypotf" | "hypotf" | "_hypot" | "hypot", [x, y]) if !x.is_nan() && y.is_zero() => + x.abs(), + + // atan2(±0,−0) = ±π. + // atan2(±0, y) = ±π for y < 0. + // Must check for non NaN because `y.is_negative()` also applies to NaN. + ("atan2f" | "atan2", [x, y]) if (x.is_zero() && (y.is_negative() && !y.is_nan())) => + pi.copy_sign(*x), + + // atan2(±x,−∞) = ±π for finite x > 0. + ("atan2f" | "atan2", [x, y]) + if (!x.is_zero() && !x.is_infinite()) && y.is_neg_infinity() => + pi.copy_sign(*x), + + // atan2(x, ±0) = −π/2 for x < 0. + // atan2(x, ±0) = π/2 for x > 0. + ("atan2f" | "atan2", [x, y]) if !x.is_zero() && y.is_zero() => pi_over_2.copy_sign(*x), + + //atan2(±∞, −∞) = ±3π/4 + ("atan2f" | "atan2", [x, y]) if x.is_infinite() && y.is_neg_infinity() => + (pi_over_4 * three).value.copy_sign(*x), + + //atan2(±∞, +∞) = ±π/4 + ("atan2f" | "atan2", [x, y]) if x.is_infinite() && y.is_pos_infinity() => + pi_over_4.copy_sign(*x), + + // atan2(±∞, y) returns ±π/2 for finite y. + ("atan2f" | "atan2", [x, y]) if x.is_infinite() && (!y.is_infinite() && !y.is_nan()) => + pi_over_2.copy_sign(*x), + // (-1)^(±INF) = 1 ("powf32" | "powf64", [base, exp]) if *base == -one && exp.is_infinite() => one, @@ -164,25 +260,27 @@ pub(crate) fn fixed_float_value( /// Returns `Some(output)` if `powi` (called `pown` in C) results in a fixed value specified in the /// C standard (specifically, C23 annex F.10.4.6) when doing `base^exp`. Otherwise, returns `None`. -pub(crate) fn fixed_powi_float_value( +pub(crate) fn fixed_powi_value( ecx: &mut MiriInterpCx<'_>, base: IeeeFloat, exp: i32, -) -> Option> { - let this = ecx.eval_context_mut(); - Some(match exp { +) -> Option> +where + IeeeFloat: IeeeExt, +{ + match exp { 0 => { let one = IeeeFloat::::one(); - let rng = this.machine.rng.get_mut(); - let return_nan = this.machine.float_nondet && rng.random() && base.is_signaling(); + let rng = ecx.machine.rng.get_mut(); + let return_nan = ecx.machine.float_nondet && rng.random() && base.is_signaling(); // For SNaN treatment, we are consistent with `powf`above. // (We wouldn't have two, unlike powf all implementations seem to agree for powi, // but for now we are maximally conservative.) - if return_nan { this.generate_nan(&[base]) } else { one } + Some(if return_nan { ecx.generate_nan(&[base]) } else { one }) } _ => return None, - }) + } } pub(crate) fn sqrt(x: IeeeFloat) -> IeeeFloat { @@ -267,19 +365,49 @@ pub(crate) fn sqrt(x: IeeeFloat) -> IeeeFl } } -/// Extend functionality of rustc_apfloat softfloats +/// Extend functionality of `rustc_apfloat` softfloats for IEEE float types. pub trait IeeeExt: rustc_apfloat::Float { + // Some values we use: + #[inline] fn one() -> Self { Self::from_u128(1).value } + #[inline] + fn two() -> Self { + Self::from_u128(2).value + } + + #[inline] + fn three() -> Self { + Self::from_u128(3).value + } + + fn pi() -> Self; + #[inline] fn clamp(self, min: Self, max: Self) -> Self { self.maximum(min).minimum(max) } } -impl IeeeExt for IeeeFloat {} + +macro_rules! impl_ieee_pi { + ($float_ty:ident, $semantic:ty) => { + impl IeeeExt for IeeeFloat<$semantic> { + #[inline] + fn pi() -> Self { + // We take the value from the standard library as the most reasonable source for an exact π here. + Self::from_bits($float_ty::consts::PI.to_bits() as _) + } + } + }; +} + +impl_ieee_pi!(f16, HalfS); +impl_ieee_pi!(f32, SingleS); +impl_ieee_pi!(f64, DoubleS); +impl_ieee_pi!(f128, QuadS); #[cfg(test)] mod tests { diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs index 9ddba8c2b48d..c57790278315 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -17,6 +17,7 @@ use rustc_target::callconv::FnAbi; use self::helpers::{ToHost, ToSoft}; use super::alloc::EvalContextExt as _; use super::backtrace::EvalContextExt as _; +use crate::helpers::EvalContextExt as _; use crate::*; /// Type of dynamic symbols (for `dlsym` et al) @@ -766,33 +767,38 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { => { let [f] = this.check_shim(abi, CanonAbi::C , link_name, args)?; let f = this.read_scalar(f)?.to_f32()?; - // Using host floats (but it's fine, these operations do not have guaranteed precision). - let f_host = f.to_host(); - let res = match link_name.as_str() { - "cbrtf" => f_host.cbrt(), - "coshf" => f_host.cosh(), - "sinhf" => f_host.sinh(), - "tanf" => f_host.tan(), - "tanhf" => f_host.tanh(), - "acosf" => f_host.acos(), - "asinf" => f_host.asin(), - "atanf" => f_host.atan(), - "log1pf" => f_host.ln_1p(), - "expm1f" => f_host.exp_m1(), - "tgammaf" => f_host.gamma(), - "erff" => f_host.erf(), - "erfcf" => f_host.erfc(), - _ => bug!(), - }; - let res = res.to_soft(); - // Apply a relative error of 16ULP to introduce some non-determinism - // simulating imprecise implementations and optimizations. - // FIXME: temporarily disabled as it breaks std tests. - // let res = math::apply_random_float_error_ulp( - // this, - // res, - // 4, // log2(16) - // ); + + let res = math::fixed_float_value(this, link_name.as_str(), &[f]).unwrap_or_else(|| { + // Using host floats (but it's fine, these operations do not have + // guaranteed precision). + let f_host = f.to_host(); + let res = match link_name.as_str() { + "cbrtf" => f_host.cbrt(), + "coshf" => f_host.cosh(), + "sinhf" => f_host.sinh(), + "tanf" => f_host.tan(), + "tanhf" => f_host.tanh(), + "acosf" => f_host.acos(), + "asinf" => f_host.asin(), + "atanf" => f_host.atan(), + "log1pf" => f_host.ln_1p(), + "expm1f" => f_host.exp_m1(), + "tgammaf" => f_host.gamma(), + "erff" => f_host.erf(), + "erfcf" => f_host.erfc(), + _ => bug!(), + }; + let res = res.to_soft(); + // Apply a relative error of 4ULP to introduce some non-determinism + // simulating imprecise implementations and optimizations. + let res = math::apply_random_float_error_ulp( + this, res, 2, // log2(4) + ); + + // Clamp the result to the guaranteed range of this function according to the C standard, + // if any. + math::clamp_float_value(link_name.as_str(), res) + }); let res = this.adjust_nan(res, &[f]); this.write_scalar(res, dest)?; } @@ -805,24 +811,28 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { let [f1, f2] = this.check_shim(abi, CanonAbi::C , link_name, args)?; let f1 = this.read_scalar(f1)?.to_f32()?; let f2 = this.read_scalar(f2)?.to_f32()?; - // underscore case for windows, here and below - // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019) - // Using host floats (but it's fine, these operations do not have guaranteed precision). - let res = match link_name.as_str() { - "_hypotf" | "hypotf" => f1.to_host().hypot(f2.to_host()).to_soft(), - "atan2f" => f1.to_host().atan2(f2.to_host()).to_soft(), - #[allow(deprecated)] - "fdimf" => f1.to_host().abs_sub(f2.to_host()).to_soft(), - _ => bug!(), - }; - // Apply a relative error of 16ULP to introduce some non-determinism - // simulating imprecise implementations and optimizations. - // FIXME: temporarily disabled as it breaks std tests. - // let res = math::apply_random_float_error_ulp( - // this, - // res, - // 4, // log2(16) - // ); + + let res = math::fixed_float_value(this, link_name.as_str(), &[f1, f2]).unwrap_or_else(|| { + let res = match link_name.as_str() { + // underscore case for windows, here and below + // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019) + // Using host floats (but it's fine, these operations do not have guaranteed precision). + "_hypotf" | "hypotf" => f1.to_host().hypot(f2.to_host()).to_soft(), + "atan2f" => f1.to_host().atan2(f2.to_host()).to_soft(), + #[allow(deprecated)] + "fdimf" => f1.to_host().abs_sub(f2.to_host()).to_soft(), + _ => bug!(), + }; + // Apply a relative error of 4ULP to introduce some non-determinism + // simulating imprecise implementations and optimizations. + let res = math::apply_random_float_error_ulp( + this, res, 2, // log2(4) + ); + + // Clamp the result to the guaranteed range of this function according to the C standard, + // if any. + math::clamp_float_value(link_name.as_str(), res) + }); let res = this.adjust_nan(res, &[f1, f2]); this.write_scalar(res, dest)?; } @@ -843,33 +853,38 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { => { let [f] = this.check_shim(abi, CanonAbi::C , link_name, args)?; let f = this.read_scalar(f)?.to_f64()?; - // Using host floats (but it's fine, these operations do not have guaranteed precision). - let f_host = f.to_host(); - let res = match link_name.as_str() { - "cbrt" => f_host.cbrt(), - "cosh" => f_host.cosh(), - "sinh" => f_host.sinh(), - "tan" => f_host.tan(), - "tanh" => f_host.tanh(), - "acos" => f_host.acos(), - "asin" => f_host.asin(), - "atan" => f_host.atan(), - "log1p" => f_host.ln_1p(), - "expm1" => f_host.exp_m1(), - "tgamma" => f_host.gamma(), - "erf" => f_host.erf(), - "erfc" => f_host.erfc(), - _ => bug!(), - }; - let res = res.to_soft(); - // Apply a relative error of 16ULP to introduce some non-determinism - // simulating imprecise implementations and optimizations. - // FIXME: temporarily disabled as it breaks std tests. - // let res = math::apply_random_float_error_ulp( - // this, - // res.to_soft(), - // 4, // log2(16) - // ); + + let res = math::fixed_float_value(this, link_name.as_str(), &[f]).unwrap_or_else(|| { + // Using host floats (but it's fine, these operations do not have + // guaranteed precision). + let f_host = f.to_host(); + let res = match link_name.as_str() { + "cbrt" => f_host.cbrt(), + "cosh" => f_host.cosh(), + "sinh" => f_host.sinh(), + "tan" => f_host.tan(), + "tanh" => f_host.tanh(), + "acos" => f_host.acos(), + "asin" => f_host.asin(), + "atan" => f_host.atan(), + "log1p" => f_host.ln_1p(), + "expm1" => f_host.exp_m1(), + "tgamma" => f_host.gamma(), + "erf" => f_host.erf(), + "erfc" => f_host.erfc(), + _ => bug!(), + }; + let res = res.to_soft(); + // Apply a relative error of 4ULP to introduce some non-determinism + // simulating imprecise implementations and optimizations. + let res = math::apply_random_float_error_ulp( + this, res, 2, // log2(4) + ); + + // Clamp the result to the guaranteed range of this function according to the C standard, + // if any. + math::clamp_float_value(link_name.as_str(), res) + }); let res = this.adjust_nan(res, &[f]); this.write_scalar(res, dest)?; } @@ -882,24 +897,28 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { let [f1, f2] = this.check_shim(abi, CanonAbi::C , link_name, args)?; let f1 = this.read_scalar(f1)?.to_f64()?; let f2 = this.read_scalar(f2)?.to_f64()?; - // underscore case for windows, here and below - // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019) - // Using host floats (but it's fine, these operations do not have guaranteed precision). - let res = match link_name.as_str() { - "_hypot" | "hypot" => f1.to_host().hypot(f2.to_host()).to_soft(), - "atan2" => f1.to_host().atan2(f2.to_host()).to_soft(), - #[allow(deprecated)] - "fdim" => f1.to_host().abs_sub(f2.to_host()).to_soft(), - _ => bug!(), - }; - // Apply a relative error of 16ULP to introduce some non-determinism - // simulating imprecise implementations and optimizations. - // FIXME: temporarily disabled as it breaks std tests. - // let res = math::apply_random_float_error_ulp( - // this, - // res, - // 4, // log2(16) - // ); + + let res = math::fixed_float_value(this, link_name.as_str(), &[f1, f2]).unwrap_or_else(|| { + let res = match link_name.as_str() { + // underscore case for windows, here and below + // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019) + // Using host floats (but it's fine, these operations do not have guaranteed precision). + "_hypot" | "hypot" => f1.to_host().hypot(f2.to_host()).to_soft(), + "atan2" => f1.to_host().atan2(f2.to_host()).to_soft(), + #[allow(deprecated)] + "fdim" => f1.to_host().abs_sub(f2.to_host()).to_soft(), + _ => bug!(), + }; + // Apply a relative error of 4ULP to introduce some non-determinism + // simulating imprecise implementations and optimizations. + let res = math::apply_random_float_error_ulp( + this, res, 2, // log2(4) + ); + + // Clamp the result to the guaranteed range of this function according to the C standard, + // if any. + math::clamp_float_value(link_name.as_str(), res) + }); let res = this.adjust_nan(res, &[f1, f2]); this.write_scalar(res, dest)?; } @@ -925,11 +944,14 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // Using host floats (but it's fine, these operations do not have guaranteed precision). let (res, sign) = x.to_host().ln_gamma(); this.write_int(sign, &signp)?; + let res = res.to_soft(); - // Apply a relative error of 16ULP to introduce some non-determinism + // Apply a relative error of 4ULP to introduce some non-determinism // simulating imprecise implementations and optimizations. - // FIXME: temporarily disabled as it breaks std tests. - // let res = math::apply_random_float_error_ulp(this, res, 4 /* log2(16) */); + let res = math::apply_random_float_error_ulp(this, res, 2 /* log2(4) */); + // Clamp the result to the guaranteed range of this function according to the C standard, + // if any. + let res = math::clamp_float_value(link_name.as_str(), res); let res = this.adjust_nan(res, &[x]); this.write_scalar(res, dest)?; } @@ -941,11 +963,14 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // Using host floats (but it's fine, these operations do not have guaranteed precision). let (res, sign) = x.to_host().ln_gamma(); this.write_int(sign, &signp)?; + let res = res.to_soft(); - // Apply a relative error of 16ULP to introduce some non-determinism + // Apply a relative error of 4ULP to introduce some non-determinism // simulating imprecise implementations and optimizations. - // FIXME: temporarily disabled as it breaks std tests. - // let res = math::apply_random_float_error_ulp(this, res, 4 /* log2(16) */); + let res = math::apply_random_float_error_ulp(this, res, 2 /* log2(4) */); + // Clamp the result to the guaranteed range of this function according to the C standard, + // if any. + let res = math::clamp_float_value(link_name.as_str(), res); let res = this.adjust_nan(res, &[x]); this.write_scalar(res, dest)?; } diff --git a/src/tools/miri/tests/pass/float.rs b/src/tools/miri/tests/pass/float.rs index fe7316c6680d..96590b4bf2be 100644 --- a/src/tools/miri/tests/pass/float.rs +++ b/src/tools/miri/tests/pass/float.rs @@ -1088,6 +1088,8 @@ pub fn libm() { assert_approx_eq!(1f32.exp_m1(), f32::consts::E - 1.0); assert_approx_eq!(1f64.exp_m1(), f64::consts::E - 1.0); + assert_approx_eq!(f32::NEG_INFINITY.exp_m1(), -1.0); + assert_approx_eq!(f64::NEG_INFINITY.exp_m1(), -1.0); assert_approx_eq!(10f32.exp2(), 1024f32); assert_approx_eq!(50f64.exp2(), 1125899906842624f64); @@ -1123,6 +1125,7 @@ pub fn libm() { assert_eq!(ldexp(0.65f64, 3i32), 5.2f64); assert_eq!(ldexp(1.42, 0xFFFF), f64::INFINITY); assert_eq!(ldexp(1.42, -0xFFFF), 0f64); + assert_eq!(ldexp(42.0, 0), 42.0); // Trigonometric functions. @@ -1131,8 +1134,14 @@ pub fn libm() { assert_approx_eq!((f64::consts::PI / 2f64).sin(), 1f64); assert_approx_eq!(f32::consts::FRAC_PI_6.sin(), 0.5); assert_approx_eq!(f64::consts::FRAC_PI_6.sin(), 0.5); - assert_approx_eq!(f32::consts::FRAC_PI_4.sin().asin(), f32::consts::FRAC_PI_4); - assert_approx_eq!(f64::consts::FRAC_PI_4.sin().asin(), f64::consts::FRAC_PI_4); + // Increase error tolerance from 12ULP to 16ULP because of the extra operation. + assert_approx_eq!(f32::consts::FRAC_PI_4.sin().asin(), f32::consts::FRAC_PI_4, 16); + assert_approx_eq!(f64::consts::FRAC_PI_4.sin().asin(), f64::consts::FRAC_PI_4, 16); + assert_biteq(0.0f32.asin(), 0.0f32, "asin(+0) = +0"); + assert_biteq((-0.0f32).asin(), -0.0, "asin(-0) = -0"); + assert_biteq(0.0f64.asin(), 0.0, "asin(+0) = +0"); + assert_biteq((-0.0f64).asin(), -0.0, "asin(-0) = -0"); + assert_approx_eq!(1.0f32.sinh(), 1.1752012f32); assert_approx_eq!(1.0f64.sinh(), 1.1752011936438014f64); @@ -1159,11 +1168,18 @@ pub fn libm() { assert_approx_eq!((f64::consts::PI * 2f64).cos(), 1f64); assert_approx_eq!(f32::consts::FRAC_PI_3.cos(), 0.5); assert_approx_eq!(f64::consts::FRAC_PI_3.cos(), 0.5); - assert_approx_eq!(f32::consts::FRAC_PI_4.cos().acos(), f32::consts::FRAC_PI_4); - assert_approx_eq!(f64::consts::FRAC_PI_4.cos().acos(), f64::consts::FRAC_PI_4); + // Increase error tolerance from 12ULP to 16ULP because of the extra operation. + assert_approx_eq!(f32::consts::FRAC_PI_4.cos().acos(), f32::consts::FRAC_PI_4, 16); + assert_approx_eq!(f64::consts::FRAC_PI_4.cos().acos(), f64::consts::FRAC_PI_4, 16); + assert_biteq(1.0f32.acos(), 0.0, "acos(1) = 0"); + assert_biteq(1.0f64.acos(), 0.0, "acos(1) = 0"); assert_approx_eq!(1.0f32.cosh(), 1.54308f32); assert_approx_eq!(1.0f64.cosh(), 1.5430806348152437f64); + assert_eq!(0.0f32.cosh(), 1.0); + assert_eq!(0.0f64.cosh(), 1.0); + assert_eq!((-0.0f32).cosh(), 1.0); + assert_eq!((-0.0f64).cosh(), 1.0); assert_approx_eq!(2.0f32.acosh(), 1.31695789692481670862504634730796844f32); assert_approx_eq!(3.0f64.acosh(), 1.76274717403908605046521864995958461f64); @@ -1173,6 +1189,47 @@ pub fn libm() { assert_approx_eq!(1.0_f64, 1.0_f64.tan().atan()); assert_approx_eq!(1.0f32.atan2(2.0f32), 0.46364761f32); assert_approx_eq!(1.0f32.atan2(2.0f32), 0.46364761f32); + // C standard defines a bunch of fixed outputs for atan2 + macro_rules! fixed_atan2_cases{ + ($float_type:ident) => {{ + use std::$float_type::consts::{PI, FRAC_PI_2, FRAC_PI_4}; + use $float_type::{INFINITY, NEG_INFINITY}; + + // atan2(±0,−0) = ±π. + assert_eq!($float_type::atan2(0.0, -0.0), PI, "atan2(0,−0) = π"); + assert_eq!($float_type::atan2(-0.0, -0.0), -PI, "atan2(-0,−0) = -π"); + + // atan2(±0, y) = ±π for y < 0. + assert_eq!($float_type::atan2(0.0, -1.0), PI, "atan2(0, y) = π for y < 0."); + assert_eq!($float_type::atan2(-0.0, -1.0), -PI, "atan2(-0, y) = -π for y < 0."); + + // atan2(x, ±0) = −π/2 for x < 0. + assert_eq!($float_type::atan2(-1.0, 0.0), -FRAC_PI_2, "atan2(x, 0) = −π/2 for x < 0"); + assert_eq!($float_type::atan2(-1.0, -0.0), -FRAC_PI_2, "atan2(x, -0) = −π/2 for x < 0"); + + // atan2(x, ±0) = π/2 for x > 0. + assert_eq!($float_type::atan2(1.0, 0.0), FRAC_PI_2, "atan2(x, 0) = π/2 for x > 0."); + assert_eq!($float_type::atan2(1.0, -0.0), FRAC_PI_2, "atan2(x, -0) = π/2 for x > 0."); + + // atan2(±x,−∞) = ±π for finite x > 0. + assert_eq!($float_type::atan2(1.0, NEG_INFINITY), PI, "atan2(x, −∞) = π for finite x > 0"); + assert_eq!($float_type::atan2(-1.0, NEG_INFINITY), -PI, "atan2(-x, −∞) = -π for finite x > 0"); + + // atan2(±∞, y) returns ±π/2 for finite y. + assert_eq!($float_type::atan2(INFINITY, 1.0), FRAC_PI_2, "atan2(+∞, y) returns π/2 for finite y"); + assert_eq!($float_type::atan2(NEG_INFINITY, 1.0), -FRAC_PI_2, "atan2(-∞, y) returns -π/2 for finite y"); + + // atan2(±∞, −∞) = ±3π/4 + assert_eq!($float_type::atan2(INFINITY, NEG_INFINITY), 3.0 * FRAC_PI_4, "atan2(+∞, −∞) = 3π/4"); + assert_eq!($float_type::atan2(NEG_INFINITY, NEG_INFINITY), -3.0 * FRAC_PI_4, "atan2(-∞, −∞) = -3π/4"); + + // atan2(±∞, +∞) = ±π/4 + assert_eq!($float_type::atan2(INFINITY, INFINITY), FRAC_PI_4, "atan2(+∞, +∞) = π/4"); + assert_eq!($float_type::atan2(NEG_INFINITY, INFINITY), -FRAC_PI_4, "atan2(-∞, +∞) = -π/4"); + }} + } + fixed_atan2_cases!(f32); + fixed_atan2_cases!(f64); assert_approx_eq!( 1.0f32.tanh(), @@ -1182,6 +1239,11 @@ pub fn libm() { 1.0f64.tanh(), (1.0 - f64::consts::E.powi(-2)) / (1.0 + f64::consts::E.powi(-2)) ); + assert_eq!(f32::INFINITY.tanh(), 1.0); + assert_eq!(f32::NEG_INFINITY.tanh(), -1.0); + assert_eq!(f64::INFINITY.tanh(), 1.0); + assert_eq!(f64::NEG_INFINITY.tanh(), -1.0); + assert_approx_eq!(0.5f32.atanh(), 0.54930614433405484569762261846126285f32); assert_approx_eq!(0.5f64.atanh(), 0.54930614433405484569762261846126285f64); @@ -1202,8 +1264,14 @@ pub fn libm() { assert_approx_eq!(1.0f32.erf(), 0.84270079294971486934122063508260926f32); assert_approx_eq!(1.0f64.erf(), 0.84270079294971486934122063508260926f64); + assert_eq!(f32::INFINITY.erf(), 1.0); + assert_eq!(f64::INFINITY.erf(), 1.0); assert_approx_eq!(1.0f32.erfc(), 0.15729920705028513065877936491739074f32); assert_approx_eq!(1.0f64.erfc(), 0.15729920705028513065877936491739074f64); + assert_eq!(f32::NEG_INFINITY.erfc(), 2.0); + assert_eq!(f64::NEG_INFINITY.erfc(), 2.0); + assert_eq!(f32::INFINITY.erfc(), 0.0); + assert_eq!(f64::INFINITY.erfc(), 0.0); } fn test_fast() { @@ -1413,7 +1481,6 @@ fn test_non_determinism() { } pub fn test_operations_f32(a: f32, b: f32) { test_operations_f!(a, b); - // FIXME: some are temporarily disabled as it breaks std tests. ensure_nondet(|| a.powf(b)); ensure_nondet(|| a.powi(2)); ensure_nondet(|| a.log(b)); @@ -1422,35 +1489,34 @@ fn test_non_determinism() { ensure_nondet(|| f32::consts::E.ln()); ensure_nondet(|| 10f32.log10()); ensure_nondet(|| 8f32.log2()); - // ensure_nondet(|| 1f32.ln_1p()); - // ensure_nondet(|| 27.0f32.cbrt()); - // ensure_nondet(|| 3.0f32.hypot(4.0f32)); + ensure_nondet(|| 1f32.ln_1p()); + ensure_nondet(|| 27.0f32.cbrt()); + ensure_nondet(|| 3.0f32.hypot(4.0f32)); ensure_nondet(|| 1f32.sin()); ensure_nondet(|| 1f32.cos()); // On i686-pc-windows-msvc , these functions are implemented by calling the `f64` version, // which means the little rounding errors Miri introduces are discarded by the cast down to // `f32`. Just skip the test for them. - // if !cfg!(all(target_os = "windows", target_env = "msvc", target_arch = "x86")) { - // ensure_nondet(|| 1.0f32.tan()); - // ensure_nondet(|| 1.0f32.asin()); - // ensure_nondet(|| 5.0f32.acos()); - // ensure_nondet(|| 1.0f32.atan()); - // ensure_nondet(|| 1.0f32.atan2(2.0f32)); - // ensure_nondet(|| 1.0f32.sinh()); - // ensure_nondet(|| 1.0f32.cosh()); - // ensure_nondet(|| 1.0f32.tanh()); - // } - // ensure_nondet(|| 1.0f32.asinh()); - // ensure_nondet(|| 2.0f32.acosh()); - // ensure_nondet(|| 0.5f32.atanh()); - // ensure_nondet(|| 5.0f32.gamma()); - // ensure_nondet(|| 5.0f32.ln_gamma()); - // ensure_nondet(|| 5.0f32.erf()); - // ensure_nondet(|| 5.0f32.erfc()); + if !cfg!(all(target_os = "windows", target_env = "msvc", target_arch = "x86")) { + ensure_nondet(|| 1.0f32.tan()); + ensure_nondet(|| 1.0f32.asin()); + ensure_nondet(|| 5.0f32.acos()); + ensure_nondet(|| 1.0f32.atan()); + ensure_nondet(|| 1.0f32.atan2(2.0f32)); + ensure_nondet(|| 1.0f32.sinh()); + ensure_nondet(|| 1.0f32.cosh()); + ensure_nondet(|| 1.0f32.tanh()); + } + ensure_nondet(|| 1.0f32.asinh()); + ensure_nondet(|| 2.0f32.acosh()); + ensure_nondet(|| 0.5f32.atanh()); + ensure_nondet(|| 5.0f32.gamma()); + ensure_nondet(|| 5.0f32.ln_gamma()); + ensure_nondet(|| 5.0f32.erf()); + ensure_nondet(|| 5.0f32.erfc()); } pub fn test_operations_f64(a: f64, b: f64) { test_operations_f!(a, b); - // FIXME: some are temporarily disabled as it breaks std tests. ensure_nondet(|| a.powf(b)); ensure_nondet(|| a.powi(2)); ensure_nondet(|| a.log(b)); @@ -1459,26 +1525,26 @@ fn test_non_determinism() { ensure_nondet(|| 3f64.ln()); ensure_nondet(|| f64::consts::E.log10()); ensure_nondet(|| f64::consts::E.log2()); - // ensure_nondet(|| 1f64.ln_1p()); - // ensure_nondet(|| 27.0f64.cbrt()); - // ensure_nondet(|| 3.0f64.hypot(4.0f64)); + ensure_nondet(|| 1f64.ln_1p()); + ensure_nondet(|| 27.0f64.cbrt()); + ensure_nondet(|| 3.0f64.hypot(4.0f64)); ensure_nondet(|| 1f64.sin()); ensure_nondet(|| 1f64.cos()); - // ensure_nondet(|| 1.0f64.tan()); - // ensure_nondet(|| 1.0f64.asin()); - // ensure_nondet(|| 5.0f64.acos()); - // ensure_nondet(|| 1.0f64.atan()); - // ensure_nondet(|| 1.0f64.atan2(2.0f64)); - // ensure_nondet(|| 1.0f64.sinh()); - // ensure_nondet(|| 1.0f64.cosh()); - // ensure_nondet(|| 1.0f64.tanh()); - // ensure_nondet(|| 1.0f64.asinh()); - // ensure_nondet(|| 3.0f64.acosh()); - // ensure_nondet(|| 0.5f64.atanh()); - // ensure_nondet(|| 5.0f64.gamma()); - // ensure_nondet(|| 5.0f64.ln_gamma()); - // ensure_nondet(|| 5.0f64.erf()); - // ensure_nondet(|| 5.0f64.erfc()); + ensure_nondet(|| 1.0f64.tan()); + ensure_nondet(|| 1.0f64.asin()); + ensure_nondet(|| 5.0f64.acos()); + ensure_nondet(|| 1.0f64.atan()); + ensure_nondet(|| 1.0f64.atan2(2.0f64)); + ensure_nondet(|| 1.0f64.sinh()); + ensure_nondet(|| 1.0f64.cosh()); + ensure_nondet(|| 1.0f64.tanh()); + ensure_nondet(|| 1.0f64.asinh()); + ensure_nondet(|| 3.0f64.acosh()); + ensure_nondet(|| 0.5f64.atanh()); + ensure_nondet(|| 5.0f64.gamma()); + ensure_nondet(|| 5.0f64.ln_gamma()); + ensure_nondet(|| 5.0f64.erf()); + ensure_nondet(|| 5.0f64.erfc()); } pub fn test_operations_f128(a: f128, b: f128) { test_operations_f!(a, b); From af8cb1da142645c1d546e7c9ad66b17b50e16ffe Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 21 Jul 2025 14:22:51 +0200 Subject: [PATCH 0083/1134] Rename `tests/assembly` into `tests/assembly-llvm` --- build_system/src/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build_system/src/test.rs b/build_system/src/test.rs index cbb0f9493838..bc0fdd40b6e8 100644 --- a/build_system/src/test.rs +++ b/build_system/src/test.rs @@ -588,7 +588,7 @@ fn asm_tests(env: &Env, args: &TestArg) -> Result<(), String> { &"always", &"--stage", &"0", - &"tests/assembly/asm", + &"tests/assembly-llvm/asm", &"--compiletest-rustc-args", &rustc_args, ], From d466953088a41ce98acfcd53961ef07b887f074a Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:03:49 -0400 Subject: [PATCH 0084/1134] Fix failing UI tests --- tests/failing-ui-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index 6979c04d5343..f7040055874e 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -10,7 +10,7 @@ tests/ui/iterators/iter-sum-overflow-overflow-checks.rs tests/ui/mir/mir_drop_order.rs tests/ui/mir/mir_let_chains_drop_order.rs tests/ui/mir/mir_match_guard_let_chains_drop_order.rs -tests/ui/oom_unwind.rs +tests/ui/panics/oom-panic-unwind.rs tests/ui/panic-runtime/abort-link-to-unwinding-crates.rs tests/ui/panic-runtime/abort.rs tests/ui/panic-runtime/link-to-abort.rs From a4fb5794e60883625fed8d25e9e55c649f9fb70c Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:14:31 -0400 Subject: [PATCH 0085/1134] Fix compilation of overflow addition --- src/int.rs | 30 +++++++++++++++++++++++++++++- src/lib.rs | 1 + 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/int.rs b/src/int.rs index 6f21ce9352b5..53e49e71e2bf 100644 --- a/src/int.rs +++ b/src/int.rs @@ -4,12 +4,15 @@ // cSpell:words cmpti divti modti mulodi muloti udivti umodti -use gccjit::{BinaryOp, ComparisonOp, FunctionType, Location, RValue, ToRValue, Type, UnaryOp}; +use gccjit::{ + BinaryOp, CType, ComparisonOp, FunctionType, Location, RValue, ToRValue, Type, UnaryOp, +}; use rustc_abi::{CanonAbi, Endian, ExternAbi}; use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeCodegenMethods, BuilderMethods, OverflowOp}; use rustc_middle::ty::{self, Ty}; use rustc_target::callconv::{ArgAbi, ArgAttributes, FnAbi, PassMode}; +use rustc_type_ir::{Interner, TyKind}; use crate::builder::{Builder, ToGccComp}; use crate::common::{SignType, TypeReflection}; @@ -351,6 +354,9 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { // TODO(antoyo): is it correct to use rhs type instead of the parameter typ? .new_local(self.location, rhs.get_type(), "binopResult") .get_address(self.location); + let new_type = type_kind_to_gcc_type(new_kind); + let new_type = self.context.new_c_type(new_type); + let lhs = self.context.new_cast(self.location, lhs, new_type); let overflow = self.overflow_call(intrinsic, &[lhs, rhs, res], None); (res.dereference(self.location).to_rvalue(), overflow) } @@ -1042,3 +1048,25 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { self.context.new_array_constructor(None, typ, &values) } } + +fn type_kind_to_gcc_type(kind: TyKind) -> CType { + use rustc_middle::ty::IntTy::*; + use rustc_middle::ty::UintTy::*; + use rustc_middle::ty::{Int, Uint}; + + match kind { + Int(I8) => CType::Int8t, + Int(I16) => CType::Int16t, + Int(I32) => CType::Int32t, + Int(I64) => CType::Int64t, + Int(I128) => CType::Int128t, + + Uint(U8) => CType::UInt8t, + Uint(U16) => CType::UInt16t, + Uint(U32) => CType::UInt32t, + Uint(U64) => CType::UInt64t, + Uint(U128) => CType::UInt128t, + + _ => unimplemented!("Kind: {:?}", kind), + } +} diff --git a/src/lib.rs b/src/lib.rs index 5e65a36f2737..92808123d6a9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,6 +51,7 @@ extern crate rustc_session; extern crate rustc_span; extern crate rustc_symbol_mangling; extern crate rustc_target; +extern crate rustc_type_ir; // This prevents duplicating functions and statics that are already part of the host rustc process. #[allow(unused_extern_crates)] From 27f3a97747cd46676c4fe2a4afd77009f3b98a46 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:16:06 -0400 Subject: [PATCH 0086/1134] Use a bitcast in Builder::ret to support non-native integers --- src/builder.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index a4ec4bf8deac..3cd464b61e14 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -540,8 +540,8 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn ret(&mut self, mut value: RValue<'gcc>) { let expected_return_type = self.current_func().get_return_type(); if !expected_return_type.is_compatible_with(value.get_type()) { - // NOTE: due to opaque pointers now being used, we need to cast here. - value = self.context.new_cast(self.location, value, expected_return_type); + // NOTE: due to opaque pointers now being used, we need to bitcast here. + value = self.context.new_bitcast(self.location, value, expected_return_type); } self.llbb().end_with_return(self.location, value); } From a5bd9d6635831b09457ce39b1eacdc30ec306cd4 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:17:43 -0400 Subject: [PATCH 0087/1134] Fix spelling mistake --- tools/cspell_dicts/rustc_codegen_gcc.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/cspell_dicts/rustc_codegen_gcc.txt b/tools/cspell_dicts/rustc_codegen_gcc.txt index b19d7f67eab3..4fb018b3ecd8 100644 --- a/tools/cspell_dicts/rustc_codegen_gcc.txt +++ b/tools/cspell_dicts/rustc_codegen_gcc.txt @@ -26,6 +26,7 @@ fwrapv gimple hrtb immediates +interner liblto llbb llcx From 9ea18272eceae790619661b421dcec7fe1f0e41b Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:26:31 -0400 Subject: [PATCH 0088/1134] Fix sysroot compilation in release mode --- src/int.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/int.rs b/src/int.rs index 53e49e71e2bf..5180f1e6d3ed 100644 --- a/src/int.rs +++ b/src/int.rs @@ -170,9 +170,9 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { if a_type.is_vector() { // Vector types need to be bitcast. // TODO(antoyo): perhaps use __builtin_convertvector for vector casting. - b = self.context.new_bitcast(self.location, b, a.get_type()); + b = self.context.new_bitcast(self.location, b, a_type); } else { - b = self.context.new_cast(self.location, b, a.get_type()); + b = self.context.new_cast(self.location, b, a_type); } } self.context.new_binary_op(self.location, operation, a_type, a, b) @@ -219,13 +219,22 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { operation_name: &str, signed: bool, a: RValue<'gcc>, - b: RValue<'gcc>, + mut b: RValue<'gcc>, ) -> RValue<'gcc> { let a_type = a.get_type(); let b_type = b.get_type(); if (self.is_native_int_type_or_bool(a_type) && self.is_native_int_type_or_bool(b_type)) || (a_type.is_vector() && b_type.is_vector()) { + if !a_type.is_compatible_with(b_type) { + if a_type.is_vector() { + // Vector types need to be bitcast. + // TODO(antoyo): perhaps use __builtin_convertvector for vector casting. + b = self.context.new_bitcast(self.location, b, a_type); + } else { + b = self.context.new_cast(self.location, b, a_type); + } + } self.context.new_binary_op(self.location, operation, a_type, a, b) } else { debug_assert!(a_type.dyncast_array().is_some()); @@ -626,7 +635,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { } } - pub fn gcc_xor(&self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { + pub fn gcc_xor(&self, a: RValue<'gcc>, mut b: RValue<'gcc>) -> RValue<'gcc> { let a_type = a.get_type(); let b_type = b.get_type(); if a_type.is_vector() && b_type.is_vector() { @@ -634,6 +643,9 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { a ^ b } else if self.is_native_int_type_or_bool(a_type) && self.is_native_int_type_or_bool(b_type) { + if !a_type.is_compatible_with(b_type) { + b = self.context.new_cast(self.location, b, a_type); + } a ^ b } else { self.concat_low_high_rvalues( From de5cf685461967da8351a4d54ba96c5da5349eae Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:27:07 -0400 Subject: [PATCH 0089/1134] Remove failing UI test --- tests/failing-ui-tests.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index f7040055874e..9a806e5ba522 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -14,7 +14,6 @@ tests/ui/panics/oom-panic-unwind.rs tests/ui/panic-runtime/abort-link-to-unwinding-crates.rs tests/ui/panic-runtime/abort.rs tests/ui/panic-runtime/link-to-abort.rs -tests/ui/unwind-no-uwtable.rs tests/ui/parser/unclosed-delimiter-in-dep.rs tests/ui/consts/missing_span_in_backtrace.rs tests/ui/drop/dynamic-drop.rs From ba18e20501d18c05859534b93796c4ca5100ad8f Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:28:44 -0400 Subject: [PATCH 0090/1134] Remove failing run-make test --- tests/failing-run-make-tests.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/failing-run-make-tests.txt b/tests/failing-run-make-tests.txt index 842533cd3c62..29032b321fa7 100644 --- a/tests/failing-run-make-tests.txt +++ b/tests/failing-run-make-tests.txt @@ -6,7 +6,6 @@ tests/run-make/doctests-keep-binaries/ tests/run-make/doctests-runtool/ tests/run-make/emit-shared-files/ tests/run-make/exit-code/ -tests/run-make/issue-22131/ tests/run-make/issue-64153/ tests/run-make/llvm-ident/ tests/run-make/native-link-modifier-bundle/ From 041be62e5f365434741195e5870ba355103a44d0 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:44:42 -0400 Subject: [PATCH 0091/1134] Add failing UI tests --- tests/failing-ui-tests.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index 9a806e5ba522..4dc9507f28f1 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -81,3 +81,6 @@ tests/ui/coroutine/panic-drops.rs tests/ui/coroutine/panic-safe.rs tests/ui/process/nofile-limit.rs tests/ui/simd/intrinsic/generic-arithmetic-pass.rs +tests/ui/linking/no-gc-encapsulation-symbols.rs +tests/ui/panics/unwind-force-no-unwind-tables.rs +tests/ui/attributes/fn-align-dyn.rs From 3c35d9b3eb46e6fa5645f93a6d04d13374f58b67 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:44:52 -0400 Subject: [PATCH 0092/1134] Add missing cast in gcc_checked_binop --- src/int.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/int.rs b/src/int.rs index 5180f1e6d3ed..64b612553cfc 100644 --- a/src/int.rs +++ b/src/int.rs @@ -366,6 +366,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let new_type = type_kind_to_gcc_type(new_kind); let new_type = self.context.new_c_type(new_type); let lhs = self.context.new_cast(self.location, lhs, new_type); + let rhs = self.context.new_cast(self.location, rhs, new_type); let overflow = self.overflow_call(intrinsic, &[lhs, rhs, res], None); (res.dereference(self.location).to_rvalue(), overflow) } From d3a61f88e87b69574b691405024eacaa0d134518 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 13:06:52 -0400 Subject: [PATCH 0093/1134] Remove failing UI test --- tests/failing-lto-tests.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/failing-lto-tests.txt b/tests/failing-lto-tests.txt index b9126fb73a77..b1ae1e91078b 100644 --- a/tests/failing-lto-tests.txt +++ b/tests/failing-lto-tests.txt @@ -28,6 +28,5 @@ tests/ui/macros/macro-comma-behavior-rpass.rs tests/ui/macros/rfc-2011-nicer-assert-messages/assert-with-custom-errors-does-not-create-unnecessary-code.rs tests/ui/macros/rfc-2011-nicer-assert-messages/feature-gate-generic_assert.rs tests/ui/macros/stringify.rs -tests/ui/reexport-test-harness-main.rs tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-in-test.rs tests/ui/binding/fn-arg-incomplete-pattern-drop-order.rs From d05542af7a07de7e58dc9a695125a3b50146ea82 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 13:07:12 -0400 Subject: [PATCH 0094/1134] Add missing cast in gcc_checked_binop --- src/int.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/int.rs b/src/int.rs index 64b612553cfc..9dc1fcf5fc8b 100644 --- a/src/int.rs +++ b/src/int.rs @@ -367,6 +367,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let new_type = self.context.new_c_type(new_type); let lhs = self.context.new_cast(self.location, lhs, new_type); let rhs = self.context.new_cast(self.location, rhs, new_type); + let res = self.context.new_cast(self.location, res, new_type.make_pointer()); let overflow = self.overflow_call(intrinsic, &[lhs, rhs, res], None); (res.dereference(self.location).to_rvalue(), overflow) } From b658b3d251a7776ff35807c1a49ab1c57c9ca6c2 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Tue, 22 Jul 2025 19:32:09 +0200 Subject: [PATCH 0095/1134] work around not being able to project out of SIMD values any more --- .../stdarch/crates/core_arch/src/s390x/vector.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/library/stdarch/crates/core_arch/src/s390x/vector.rs b/library/stdarch/crates/core_arch/src/s390x/vector.rs index a09a27a029c1..0ce720a9244c 100644 --- a/library/stdarch/crates/core_arch/src/s390x/vector.rs +++ b/library/stdarch/crates/core_arch/src/s390x/vector.rs @@ -5831,24 +5831,30 @@ mod tests { use crate::core_arch::simd::*; use stdarch_test::simd_test; + impl ShuffleMask { + fn as_array(&self) -> &[u32; N] { + unsafe { std::mem::transmute(self) } + } + } + #[test] fn reverse_mask() { - assert_eq!(ShuffleMask::<4>::reverse().0, [3, 2, 1, 0]); + assert_eq!(ShuffleMask::<4>::reverse().as_array(), &[3, 2, 1, 0]); } #[test] fn mergel_mask() { - assert_eq!(ShuffleMask::<4>::merge_low().0, [2, 6, 3, 7]); + assert_eq!(ShuffleMask::<4>::merge_low().as_array(), &[2, 6, 3, 7]); } #[test] fn mergeh_mask() { - assert_eq!(ShuffleMask::<4>::merge_high().0, [0, 4, 1, 5]); + assert_eq!(ShuffleMask::<4>::merge_high().as_array(), &[0, 4, 1, 5]); } #[test] fn pack_mask() { - assert_eq!(ShuffleMask::<4>::pack().0, [1, 3, 5, 7]); + assert_eq!(ShuffleMask::<4>::pack().as_array(), &[1, 3, 5, 7]); } #[test] From aaa5d91a0242d3c90bc9df063115eeb32f505313 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Tue, 22 Jul 2025 15:19:09 +0200 Subject: [PATCH 0096/1134] remove `lazy_static` dependency from `intrinsic-test` we use `std::sync::LazyLock` now. --- library/stdarch/Cargo.lock | 11 ++--------- library/stdarch/crates/intrinsic-test/Cargo.toml | 1 - 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/library/stdarch/Cargo.lock b/library/stdarch/Cargo.lock index 4806682e6e0a..2eba81399885 100644 --- a/library/stdarch/Cargo.lock +++ b/library/stdarch/Cargo.lock @@ -360,7 +360,6 @@ dependencies = [ "csv", "diff", "itertools", - "lazy_static", "log", "pretty_env_logger", "rayon", @@ -401,12 +400,6 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - [[package]] name = "libc" version = "0.2.174" @@ -635,9 +628,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" dependencies = [ "itoa", "memchr", diff --git a/library/stdarch/crates/intrinsic-test/Cargo.toml b/library/stdarch/crates/intrinsic-test/Cargo.toml index 06051abc8d0d..2b2df2dacca6 100644 --- a/library/stdarch/crates/intrinsic-test/Cargo.toml +++ b/library/stdarch/crates/intrinsic-test/Cargo.toml @@ -11,7 +11,6 @@ license = "MIT OR Apache-2.0" edition = "2024" [dependencies] -lazy_static = "1.4.0" serde = { version = "1", features = ["derive"] } serde_json = "1.0" csv = "1.1" From 30033b45bb2fcbc0f267acaf9fab22411422e166 Mon Sep 17 00:00:00 2001 From: gewitternacht <60887951+gewitternacht@users.noreply.github.com> Date: Tue, 22 Jul 2025 23:16:49 +0200 Subject: [PATCH 0097/1134] document assumptions about `Clone` and `Eq` traits --- library/core/src/clone.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index a34d1b4a0649..7afdf50ce51d 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -139,6 +139,30 @@ mod uninit; /// // Note: With the manual implementations the above line will compile. /// ``` /// +/// ## `Clone` and `PartialEq`/`Eq` +/// `Clone` is intended for the duplication of objects. Consequently, when implementing +/// both `Clone` and [`PartialEq`], the following property is expected to hold: +/// ```text +/// x == x -> x.clone() == x +/// ``` +/// In other words, if an object compares equal to itself, +/// its clone must also compare equal to the original. +/// +/// For types that also implement [`Eq`] – for which `x == x` always holds – +/// this implies that `x.clone() == x` must always be true. +/// Standard library collections such as +/// [`HashMap`], [`HashSet`], [`BTreeMap`], [`BTreeSet`] and [`BinaryHeap`] +/// rely on their keys respecting this property for correct behavior. +/// +/// This property is automatically satisfied when deriving both `Clone` and [`PartialEq`] +/// using `#[derive(Clone, PartialEq)]` or when additionally deriving [`Eq`] +/// using `#[derive(Clone, PartialEq, Eq)]`. +/// +/// Violating this property is a logic error. The behavior resulting from a logic error is not +/// specified, but users of the trait must ensure that such logic errors do *not* result in +/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these +/// methods. +/// /// ## Additional implementors /// /// In addition to the [implementors listed below][impls], From cdbcd72f341c949e4fa11f58d76a094bd435d18f Mon Sep 17 00:00:00 2001 From: gewitternacht <60887951+gewitternacht@users.noreply.github.com> Date: Wed, 23 Jul 2025 00:41:48 +0200 Subject: [PATCH 0098/1134] remove trailing whitespace --- library/core/src/clone.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index 7afdf50ce51d..64916f49f3a5 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -155,7 +155,7 @@ mod uninit; /// rely on their keys respecting this property for correct behavior. /// /// This property is automatically satisfied when deriving both `Clone` and [`PartialEq`] -/// using `#[derive(Clone, PartialEq)]` or when additionally deriving [`Eq`] +/// using `#[derive(Clone, PartialEq)]` or when additionally deriving [`Eq`] /// using `#[derive(Clone, PartialEq, Eq)]`. /// /// Violating this property is a logic error. The behavior resulting from a logic error is not From 623317eb5e2bf73b53a5cd52d693ac032cf5aa32 Mon Sep 17 00:00:00 2001 From: gewitternacht <60887951+gewitternacht@users.noreply.github.com> Date: Wed, 23 Jul 2025 01:44:18 +0200 Subject: [PATCH 0099/1134] add links to collections --- library/core/src/clone.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index 64916f49f3a5..c4778edf0fcc 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -176,6 +176,11 @@ mod uninit; /// (even if the referent doesn't), /// while variables captured by mutable reference never implement `Clone`. /// +/// [`HashMap`]: ../../std/collections/struct.HashMap.html +/// [`HashSet`]: ../../std/collections/struct.HashSet.html +/// [`BTreeMap`]: ../../std/collections/struct.BTreeMap.html +/// [`BTreeSet`]: ../../std/collections/struct.BTreeSet.html +/// [`BinaryHeap`]: ../../std/collections/struct.BinaryHeap.html /// [impls]: #implementors #[stable(feature = "rust1", since = "1.0.0")] #[lang = "clone"] From 45231fa599583edc95843aaa4f23b12f762e01e7 Mon Sep 17 00:00:00 2001 From: Predrag Gruevski Date: Wed, 23 Jul 2025 00:00:01 +0000 Subject: [PATCH 0100/1134] [rustdoc] Display unsafe attrs with edition 2024 `unsafe()` wrappers. --- src/librustdoc/clean/types.rs | 6 +++--- tests/rustdoc/attribute-rendering.rs | 6 +++--- tests/rustdoc/attributes-2021-edition.rs | 14 ++++++++++++++ tests/rustdoc/attributes-re-export-2021-edition.rs | 13 +++++++++++++ tests/rustdoc/attributes-re-export.rs | 2 +- tests/rustdoc/attributes.rs | 13 +++++++++---- tests/rustdoc/reexport/reexport-attrs.rs | 6 +++--- 7 files changed, 46 insertions(+), 14 deletions(-) create mode 100644 tests/rustdoc/attributes-2021-edition.rs create mode 100644 tests/rustdoc/attributes-re-export-2021-edition.rs diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 5ac5da24299f..64e707ad9d36 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -768,13 +768,13 @@ impl Item { .iter() .filter_map(|attr| match attr { hir::Attribute::Parsed(AttributeKind::LinkSection { name, .. }) => { - Some(format!("#[link_section = \"{name}\"]")) + Some(format!("#[unsafe(link_section = \"{name}\")]")) } hir::Attribute::Parsed(AttributeKind::NoMangle(..)) => { - Some("#[no_mangle]".to_string()) + Some("#[unsafe(no_mangle)]".to_string()) } hir::Attribute::Parsed(AttributeKind::ExportName { name, .. }) => { - Some(format!("#[export_name = \"{name}\"]")) + Some(format!("#[unsafe(export_name = \"{name}\")]")) } hir::Attribute::Parsed(AttributeKind::NonExhaustive(..)) => { Some("#[non_exhaustive]".to_string()) diff --git a/tests/rustdoc/attribute-rendering.rs b/tests/rustdoc/attribute-rendering.rs index 841533814c38..bf9b81077f35 100644 --- a/tests/rustdoc/attribute-rendering.rs +++ b/tests/rustdoc/attribute-rendering.rs @@ -1,7 +1,7 @@ #![crate_name = "foo"] //@ has 'foo/fn.f.html' -//@ has - //*[@'class="rust item-decl"]' '#[export_name = "f"] pub fn f()' -#[export_name = "\ -f"] +//@ has - //*[@'class="rust item-decl"]' '#[unsafe(export_name = "f")] pub fn f()' +#[unsafe(export_name = "\ +f")] pub fn f() {} diff --git a/tests/rustdoc/attributes-2021-edition.rs b/tests/rustdoc/attributes-2021-edition.rs new file mode 100644 index 000000000000..b5028d8c8525 --- /dev/null +++ b/tests/rustdoc/attributes-2021-edition.rs @@ -0,0 +1,14 @@ +//@ edition: 2021 +#![crate_name = "foo"] + +//@ has foo/fn.f.html '//pre[@class="rust item-decl"]' '#[unsafe(no_mangle)]' +#[no_mangle] +pub extern "C" fn f() {} + +//@ has foo/fn.g.html '//pre[@class="rust item-decl"]' '#[unsafe(export_name = "bar")]' +#[export_name = "bar"] +pub extern "C" fn g() {} + +//@ has foo/fn.example.html '//pre[@class="rust item-decl"]' '#[unsafe(link_section = ".text")]' +#[link_section = ".text"] +pub extern "C" fn example() {} diff --git a/tests/rustdoc/attributes-re-export-2021-edition.rs b/tests/rustdoc/attributes-re-export-2021-edition.rs new file mode 100644 index 000000000000..04ee6c273dd6 --- /dev/null +++ b/tests/rustdoc/attributes-re-export-2021-edition.rs @@ -0,0 +1,13 @@ +// Tests that attributes are correctly copied onto a re-exported item. +//@ edition:2024 +#![crate_name = "re_export"] + +//@ has 're_export/fn.thingy2.html' '//pre[@class="rust item-decl"]' '#[unsafe(no_mangle)]' +pub use thingymod::thingy as thingy2; + +mod thingymod { + #[unsafe(no_mangle)] + pub fn thingy() { + + } +} diff --git a/tests/rustdoc/attributes-re-export.rs b/tests/rustdoc/attributes-re-export.rs index 458826ea8a35..820276f83c09 100644 --- a/tests/rustdoc/attributes-re-export.rs +++ b/tests/rustdoc/attributes-re-export.rs @@ -2,7 +2,7 @@ //@ edition:2021 #![crate_name = "re_export"] -//@ has 're_export/fn.thingy2.html' '//pre[@class="rust item-decl"]' '#[no_mangle]' +//@ has 're_export/fn.thingy2.html' '//pre[@class="rust item-decl"]' '#[unsafe(no_mangle)]' pub use thingymod::thingy as thingy2; mod thingymod { diff --git a/tests/rustdoc/attributes.rs b/tests/rustdoc/attributes.rs index e34468a88b11..34487a891277 100644 --- a/tests/rustdoc/attributes.rs +++ b/tests/rustdoc/attributes.rs @@ -1,13 +1,18 @@ +//@ edition: 2024 #![crate_name = "foo"] -//@ has foo/fn.f.html '//pre[@class="rust item-decl"]' '#[no_mangle]' -#[no_mangle] +//@ has foo/fn.f.html '//pre[@class="rust item-decl"]' '#[unsafe(no_mangle)]' +#[unsafe(no_mangle)] pub extern "C" fn f() {} -//@ has foo/fn.g.html '//pre[@class="rust item-decl"]' '#[export_name = "bar"]' -#[export_name = "bar"] +//@ has foo/fn.g.html '//pre[@class="rust item-decl"]' '#[unsafe(export_name = "bar")]' +#[unsafe(export_name = "bar")] pub extern "C" fn g() {} +//@ has foo/fn.example.html '//pre[@class="rust item-decl"]' '#[unsafe(link_section = ".text")]' +#[unsafe(link_section = ".text")] +pub extern "C" fn example() {} + //@ has foo/struct.Repr.html '//pre[@class="rust item-decl"]' '#[repr(C, align(8))]' #[repr(C, align(8))] pub struct Repr; diff --git a/tests/rustdoc/reexport/reexport-attrs.rs b/tests/rustdoc/reexport/reexport-attrs.rs index 0ec645841f0b..aec0a11c0c6a 100644 --- a/tests/rustdoc/reexport/reexport-attrs.rs +++ b/tests/rustdoc/reexport/reexport-attrs.rs @@ -4,13 +4,13 @@ extern crate reexports_attrs; -//@ has 'foo/fn.f0.html' '//pre[@class="rust item-decl"]' '#[no_mangle]' +//@ has 'foo/fn.f0.html' '//pre[@class="rust item-decl"]' '#[unsafe(no_mangle)]' pub use reexports_attrs::f0; -//@ has 'foo/fn.f1.html' '//pre[@class="rust item-decl"]' '#[link_section = ".here"]' +//@ has 'foo/fn.f1.html' '//pre[@class="rust item-decl"]' '#[unsafe(link_section = ".here")]' pub use reexports_attrs::f1; -//@ has 'foo/fn.f2.html' '//pre[@class="rust item-decl"]' '#[export_name = "f2export"]' +//@ has 'foo/fn.f2.html' '//pre[@class="rust item-decl"]' '#[unsafe(export_name = "f2export")]' pub use reexports_attrs::f2; //@ has 'foo/enum.T0.html' '//pre[@class="rust item-decl"]' '#[repr(u8)]' From efcae7d31d30ba8d8c806fbb8dea634e78d7b969 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 19 Jul 2025 22:38:57 +0200 Subject: [PATCH 0101/1134] properly use caller-side panic location for some GenericArgs methods --- compiler/rustc_middle/src/ty/generic_args.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 7d34d8df3f3b..a5fd4d7a262c 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -536,21 +536,28 @@ impl<'tcx> GenericArgs<'tcx> { #[inline] #[track_caller] pub fn type_at(&self, i: usize) -> Ty<'tcx> { - self[i].as_type().unwrap_or_else(|| bug!("expected type for param #{} in {:?}", i, self)) + self[i].as_type().unwrap_or_else( + #[track_caller] + || bug!("expected type for param #{} in {:?}", i, self), + ) } #[inline] #[track_caller] pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { - self[i] - .as_region() - .unwrap_or_else(|| bug!("expected region for param #{} in {:?}", i, self)) + self[i].as_region().unwrap_or_else( + #[track_caller] + || bug!("expected region for param #{} in {:?}", i, self), + ) } #[inline] #[track_caller] pub fn const_at(&self, i: usize) -> ty::Const<'tcx> { - self[i].as_const().unwrap_or_else(|| bug!("expected const for param #{} in {:?}", i, self)) + self[i].as_const().unwrap_or_else( + #[track_caller] + || bug!("expected const for param #{} in {:?}", i, self), + ) } #[inline] From de1b999ff6c981475e4491ea2fff1851655587e5 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 19 Jul 2025 23:23:40 +0200 Subject: [PATCH 0102/1134] atomicrmw on pointers: move integer-pointer cast hacks into backend --- .../src/intrinsics/mod.rs | 24 ++--- compiler/rustc_codegen_gcc/src/builder.rs | 7 +- compiler/rustc_codegen_llvm/src/builder.rs | 14 ++- compiler/rustc_codegen_ssa/messages.ftl | 2 + compiler/rustc_codegen_ssa/src/errors.rs | 8 ++ .../rustc_codegen_ssa/src/mir/intrinsic.rs | 82 +++++++++++++---- .../rustc_codegen_ssa/src/traits/builder.rs | 3 + .../rustc_hir_analysis/src/check/intrinsic.rs | 12 +-- library/core/src/intrinsics/mod.rs | 30 +++---- library/core/src/sync/atomic.rs | 89 ++++++++++--------- src/tools/miri/src/intrinsics/atomic.rs | 19 ++-- src/tools/miri/src/operator.rs | 8 +- tests/codegen-llvm/atomicptr.rs | 6 +- .../atomic-lock-free/atomic_lock_free.rs | 39 +++++--- tests/ui/intrinsics/intrinsic-atomics.rs | 12 +-- tests/ui/intrinsics/non-integer-atomic.rs | 32 +++---- tests/ui/intrinsics/non-integer-atomic.stderr | 32 +++---- 17 files changed, 243 insertions(+), 176 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 4ff5773a06cb..ed40901ac9b8 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -969,7 +969,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = amount.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Uint(_) | ty::Int(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -982,7 +982,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Add, ptr, amount); - let old = CValue::by_val(old, layout); + let old = CValue::by_val(old, ret.layout()); ret.write_cvalue(fx, old); } sym::atomic_xsub => { @@ -991,7 +991,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = amount.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Uint(_) | ty::Int(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -1004,7 +1004,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Sub, ptr, amount); - let old = CValue::by_val(old, layout); + let old = CValue::by_val(old, ret.layout()); ret.write_cvalue(fx, old); } sym::atomic_and => { @@ -1013,7 +1013,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = src.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Uint(_) | ty::Int(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -1025,7 +1025,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::And, ptr, src); - let old = CValue::by_val(old, layout); + let old = CValue::by_val(old, ret.layout()); ret.write_cvalue(fx, old); } sym::atomic_or => { @@ -1034,7 +1034,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = src.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Uint(_) | ty::Int(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -1046,7 +1046,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Or, ptr, src); - let old = CValue::by_val(old, layout); + let old = CValue::by_val(old, ret.layout()); ret.write_cvalue(fx, old); } sym::atomic_xor => { @@ -1055,7 +1055,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = src.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Uint(_) | ty::Int(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -1067,7 +1067,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Xor, ptr, src); - let old = CValue::by_val(old, layout); + let old = CValue::by_val(old, ret.layout()); ret.write_cvalue(fx, old); } sym::atomic_nand => { @@ -1076,7 +1076,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = src.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Uint(_) | ty::Int(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -1088,7 +1088,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Nand, ptr, src); - let old = CValue::by_val(old, layout); + let old = CValue::by_val(old, ret.layout()); ret.write_cvalue(fx, old); } sym::atomic_max => { diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index a4ec4bf8deac..032f5d0a622d 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -1656,6 +1656,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { dst: RValue<'gcc>, src: RValue<'gcc>, order: AtomicOrdering, + ret_ptr: bool, ) -> RValue<'gcc> { let size = get_maybe_pointer_size(src); let name = match op { @@ -1683,6 +1684,9 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { let atomic_function = self.context.get_builtin_function(name); let order = self.context.new_rvalue_from_int(self.i32_type, order.to_gcc()); + // FIXME: If `ret_ptr` is true and `src` is an integer, we should really tell GCC + // that this is a pointer operation that needs to preserve provenance -- but like LLVM, + // GCC does not currently seems to support that. let void_ptr_type = self.context.new_type::<*mut ()>(); let volatile_void_ptr_type = void_ptr_type.make_volatile(); let dst = self.context.new_cast(self.location, dst, volatile_void_ptr_type); @@ -1690,7 +1694,8 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { let new_src_type = atomic_function.get_param(1).to_rvalue().get_type(); let src = self.context.new_bitcast(self.location, src, new_src_type); let res = self.context.new_call(self.location, atomic_function, &[dst, src, order]); - self.context.new_cast(self.location, res, src.get_type()) + let res_type = if ret_ptr { void_ptr_type } else { src.get_type() }; + self.context.new_cast(self.location, res, res_type) } fn atomic_fence(&mut self, order: AtomicOrdering, scope: SynchronizationScope) { diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 0ade9edb0d2e..51593f3f065f 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -1326,15 +1326,13 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { &mut self, op: rustc_codegen_ssa::common::AtomicRmwBinOp, dst: &'ll Value, - mut src: &'ll Value, + src: &'ll Value, order: rustc_middle::ty::AtomicOrdering, + ret_ptr: bool, ) -> &'ll Value { - // The only RMW operation that LLVM supports on pointers is compare-exchange. - let requires_cast_to_int = self.val_ty(src) == self.type_ptr() - && op != rustc_codegen_ssa::common::AtomicRmwBinOp::AtomicXchg; - if requires_cast_to_int { - src = self.ptrtoint(src, self.type_isize()); - } + // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the + // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not + // currently support that (https://github.com/llvm/llvm-project/issues/120837). let mut res = unsafe { llvm::LLVMBuildAtomicRMW( self.llbuilder, @@ -1345,7 +1343,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { llvm::False, // SingleThreaded ) }; - if requires_cast_to_int { + if ret_ptr && self.val_ty(res) != self.type_ptr() { res = self.inttoptr(res, self.type_ptr()); } res diff --git a/compiler/rustc_codegen_ssa/messages.ftl b/compiler/rustc_codegen_ssa/messages.ftl index c7bd6ffd1f27..42310a8b8c77 100644 --- a/compiler/rustc_codegen_ssa/messages.ftl +++ b/compiler/rustc_codegen_ssa/messages.ftl @@ -97,6 +97,8 @@ codegen_ssa_invalid_monomorphization_basic_float_type = invalid monomorphization codegen_ssa_invalid_monomorphization_basic_integer_type = invalid monomorphization of `{$name}` intrinsic: expected basic integer type, found `{$ty}` +codegen_ssa_invalid_monomorphization_basic_integer_or_ptr_type = invalid monomorphization of `{$name}` intrinsic: expected basic integer or pointer type, found `{$ty}` + codegen_ssa_invalid_monomorphization_cannot_return = invalid monomorphization of `{$name}` intrinsic: cannot return `{$ret_ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` codegen_ssa_invalid_monomorphization_cast_wide_pointer = invalid monomorphization of `{$name}` intrinsic: cannot cast wide pointer `{$ty}` diff --git a/compiler/rustc_codegen_ssa/src/errors.rs b/compiler/rustc_codegen_ssa/src/errors.rs index 9040915b6af3..751e7c8a6cb1 100644 --- a/compiler/rustc_codegen_ssa/src/errors.rs +++ b/compiler/rustc_codegen_ssa/src/errors.rs @@ -764,6 +764,14 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, + #[diag(codegen_ssa_invalid_monomorphization_basic_integer_or_ptr_type, code = E0511)] + BasicIntegerOrPtrType { + #[primary_span] + span: Span, + name: Symbol, + ty: Ty<'tcx>, + }, + #[diag(codegen_ssa_invalid_monomorphization_basic_float_type, code = E0511)] BasicFloatType { #[primary_span] diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index fc95f62b4a43..3c667b8e8820 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -92,6 +92,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let invalid_monomorphization_int_type = |ty| { bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType { span, name, ty }); }; + let invalid_monomorphization_int_or_ptr_type = |ty| { + bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerOrPtrType { + span, + name, + ty, + }); + }; let parse_atomic_ordering = |ord: ty::Value<'tcx>| { let discr = ord.valtree.unwrap_branch()[0].unwrap_leaf(); @@ -351,7 +358,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { sym::atomic_load => { let ty = fn_args.type_at(0); if !(int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr()) { - invalid_monomorphization_int_type(ty); + invalid_monomorphization_int_or_ptr_type(ty); return Ok(()); } let ordering = fn_args.const_at(1).to_value(); @@ -367,7 +374,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { sym::atomic_store => { let ty = fn_args.type_at(0); if !(int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr()) { - invalid_monomorphization_int_type(ty); + invalid_monomorphization_int_or_ptr_type(ty); return Ok(()); } let ordering = fn_args.const_at(1).to_value(); @@ -377,10 +384,11 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx.atomic_store(val, ptr, parse_atomic_ordering(ordering), size); return Ok(()); } + // These are all AtomicRMW ops sym::atomic_cxchg | sym::atomic_cxchgweak => { let ty = fn_args.type_at(0); if !(int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr()) { - invalid_monomorphization_int_type(ty); + invalid_monomorphization_int_or_ptr_type(ty); return Ok(()); } let succ_ordering = fn_args.const_at(1).to_value(); @@ -407,7 +415,6 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { return Ok(()); } - // These are all AtomicRMW ops sym::atomic_max | sym::atomic_min => { let atom_op = if name == sym::atomic_max { AtomicRmwBinOp::AtomicMax @@ -420,7 +427,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let ordering = fn_args.const_at(1).to_value(); let ptr = args[0].immediate(); let val = args[1].immediate(); - bx.atomic_rmw(atom_op, ptr, val, parse_atomic_ordering(ordering)) + bx.atomic_rmw( + atom_op, + ptr, + val, + parse_atomic_ordering(ordering), + /* ret_ptr */ false, + ) } else { invalid_monomorphization_int_type(ty); return Ok(()); @@ -438,21 +451,44 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let ordering = fn_args.const_at(1).to_value(); let ptr = args[0].immediate(); let val = args[1].immediate(); - bx.atomic_rmw(atom_op, ptr, val, parse_atomic_ordering(ordering)) + bx.atomic_rmw( + atom_op, + ptr, + val, + parse_atomic_ordering(ordering), + /* ret_ptr */ false, + ) } else { invalid_monomorphization_int_type(ty); return Ok(()); } } - sym::atomic_xchg - | sym::atomic_xadd + sym::atomic_xchg => { + let ty = fn_args.type_at(0); + let ordering = fn_args.const_at(1).to_value(); + if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr() { + let ptr = args[0].immediate(); + let val = args[1].immediate(); + let atomic_op = AtomicRmwBinOp::AtomicXchg; + bx.atomic_rmw( + atomic_op, + ptr, + val, + parse_atomic_ordering(ordering), + /* ret_ptr */ ty.is_raw_ptr(), + ) + } else { + invalid_monomorphization_int_or_ptr_type(ty); + return Ok(()); + } + } + sym::atomic_xadd | sym::atomic_xsub | sym::atomic_and | sym::atomic_nand | sym::atomic_or | sym::atomic_xor => { let atom_op = match name { - sym::atomic_xchg => AtomicRmwBinOp::AtomicXchg, sym::atomic_xadd => AtomicRmwBinOp::AtomicAdd, sym::atomic_xsub => AtomicRmwBinOp::AtomicSub, sym::atomic_and => AtomicRmwBinOp::AtomicAnd, @@ -462,14 +498,28 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { _ => unreachable!(), }; - let ty = fn_args.type_at(0); - if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr() { - let ordering = fn_args.const_at(1).to_value(); - let ptr = args[0].immediate(); - let val = args[1].immediate(); - bx.atomic_rmw(atom_op, ptr, val, parse_atomic_ordering(ordering)) + // The type of the in-memory data. + let ty_mem = fn_args.type_at(0); + // The type of the 2nd operand, given by-value. + let ty_op = fn_args.type_at(1); + + let ordering = fn_args.const_at(2).to_value(); + // We require either both arguments to have the same integer type, or the first to + // be a pointer and the second to be `usize`. + if (int_type_width_signed(ty_mem, bx.tcx()).is_some() && ty_op == ty_mem) + || (ty_mem.is_raw_ptr() && ty_op == bx.tcx().types.usize) + { + let ptr = args[0].immediate(); // of type "pointer to `ty_mem`" + let val = args[1].immediate(); // of type `ty_op` + bx.atomic_rmw( + atom_op, + ptr, + val, + parse_atomic_ordering(ordering), + /* ret_ptr */ ty_mem.is_raw_ptr(), + ) } else { - invalid_monomorphization_int_type(ty); + invalid_monomorphization_int_or_ptr_type(ty_mem); return Ok(()); } } diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 979456a6ba70..fc17b30d6572 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -548,12 +548,15 @@ pub trait BuilderMethods<'a, 'tcx>: failure_order: AtomicOrdering, weak: bool, ) -> (Self::Value, Self::Value); + /// `ret_ptr` indicates whether the return type (which is also the type `dst` points to) + /// is a pointer or the same type as `src`. fn atomic_rmw( &mut self, op: AtomicRmwBinOp, dst: Self::Value, src: Self::Value, order: AtomicOrdering, + ret_ptr: bool, ) -> Self::Value; fn atomic_fence(&mut self, order: AtomicOrdering, scope: SynchronizationScope); fn set_invariant_load(&mut self, load: Self::Value); diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 6e5fe3823ab5..4441dd6ebd66 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -652,16 +652,16 @@ pub(crate) fn check_intrinsic_type( sym::atomic_store => (1, 1, vec![Ty::new_mut_ptr(tcx, param(0)), param(0)], tcx.types.unit), sym::atomic_xchg - | sym::atomic_xadd - | sym::atomic_xsub - | sym::atomic_and - | sym::atomic_nand - | sym::atomic_or - | sym::atomic_xor | sym::atomic_max | sym::atomic_min | sym::atomic_umax | sym::atomic_umin => (1, 1, vec![Ty::new_mut_ptr(tcx, param(0)), param(0)], param(0)), + sym::atomic_xadd + | sym::atomic_xsub + | sym::atomic_and + | sym::atomic_nand + | sym::atomic_or + | sym::atomic_xor => (2, 1, vec![Ty::new_mut_ptr(tcx, param(0)), param(1)], param(0)), sym::atomic_fence | sym::atomic_singlethreadfence => (0, 1, Vec::new(), tcx.types.unit), other => { diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 106cc725fee2..9bf695e30258 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -150,69 +150,63 @@ pub unsafe fn atomic_xchg(dst: *mut T, src: /// Adds to the current value, returning the previous value. /// `T` must be an integer or pointer type. -/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new -/// value stored at `*dst` will have the provenance of the old value stored there. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_add` method. For example, [`AtomicIsize::fetch_add`]. #[rustc_intrinsic] #[rustc_nounwind] -pub unsafe fn atomic_xadd(dst: *mut T, src: T) -> T; +pub unsafe fn atomic_xadd(dst: *mut T, src: U) -> T; /// Subtract from the current value, returning the previous value. /// `T` must be an integer or pointer type. -/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new -/// value stored at `*dst` will have the provenance of the old value stored there. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_sub` method. For example, [`AtomicIsize::fetch_sub`]. #[rustc_intrinsic] #[rustc_nounwind] -pub unsafe fn atomic_xsub(dst: *mut T, src: T) -> T; +pub unsafe fn atomic_xsub(dst: *mut T, src: U) -> T; /// Bitwise and with the current value, returning the previous value. /// `T` must be an integer or pointer type. -/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new -/// value stored at `*dst` will have the provenance of the old value stored there. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_and` method. For example, [`AtomicBool::fetch_and`]. #[rustc_intrinsic] #[rustc_nounwind] -pub unsafe fn atomic_and(dst: *mut T, src: T) -> T; +pub unsafe fn atomic_and(dst: *mut T, src: U) -> T; /// Bitwise nand with the current value, returning the previous value. /// `T` must be an integer or pointer type. -/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new -/// value stored at `*dst` will have the provenance of the old value stored there. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`AtomicBool`] type via the `fetch_nand` method. For example, [`AtomicBool::fetch_nand`]. #[rustc_intrinsic] #[rustc_nounwind] -pub unsafe fn atomic_nand(dst: *mut T, src: T) -> T; +pub unsafe fn atomic_nand(dst: *mut T, src: U) -> T; /// Bitwise or with the current value, returning the previous value. /// `T` must be an integer or pointer type. -/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new -/// value stored at `*dst` will have the provenance of the old value stored there. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_or` method. For example, [`AtomicBool::fetch_or`]. #[rustc_intrinsic] #[rustc_nounwind] -pub unsafe fn atomic_or(dst: *mut T, src: T) -> T; +pub unsafe fn atomic_or(dst: *mut T, src: U) -> T; /// Bitwise xor with the current value, returning the previous value. /// `T` must be an integer or pointer type. -/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new -/// value stored at `*dst` will have the provenance of the old value stored there. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_xor` method. For example, [`AtomicBool::fetch_xor`]. #[rustc_intrinsic] #[rustc_nounwind] -pub unsafe fn atomic_xor(dst: *mut T, src: T) -> T; +pub unsafe fn atomic_xor(dst: *mut T, src: U) -> T; /// Maximum with the current value using a signed comparison. /// `T` must be a signed integer type. diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 546f3d91a809..bf07b18f3e73 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -2291,7 +2291,7 @@ impl AtomicPtr { #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. - unsafe { atomic_add(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() } + unsafe { atomic_add(self.p.get(), val, order).cast() } } /// Offsets the pointer's address by subtracting `val` *bytes*, returning the @@ -2316,9 +2316,10 @@ impl AtomicPtr { /// #![feature(strict_provenance_atomic_ptr)] /// use core::sync::atomic::{AtomicPtr, Ordering}; /// - /// let atom = AtomicPtr::::new(core::ptr::without_provenance_mut(1)); - /// assert_eq!(atom.fetch_byte_sub(1, Ordering::Relaxed).addr(), 1); - /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 0); + /// let mut arr = [0i64, 1]; + /// let atom = AtomicPtr::::new(&raw mut arr[1]); + /// assert_eq!(atom.fetch_byte_sub(8, Ordering::Relaxed).addr(), (&raw const arr[1]).addr()); + /// assert_eq!(atom.load(Ordering::Relaxed).addr(), (&raw const arr[0]).addr()); /// ``` #[inline] #[cfg(target_has_atomic = "ptr")] @@ -2326,7 +2327,7 @@ impl AtomicPtr { #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. - unsafe { atomic_sub(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() } + unsafe { atomic_sub(self.p.get(), val, order).cast() } } /// Performs a bitwise "or" operation on the address of the current pointer, @@ -2377,7 +2378,7 @@ impl AtomicPtr { #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. - unsafe { atomic_or(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() } + unsafe { atomic_or(self.p.get(), val, order).cast() } } /// Performs a bitwise "and" operation on the address of the current @@ -2427,7 +2428,7 @@ impl AtomicPtr { #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. - unsafe { atomic_and(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() } + unsafe { atomic_and(self.p.get(), val, order).cast() } } /// Performs a bitwise "xor" operation on the address of the current @@ -2475,7 +2476,7 @@ impl AtomicPtr { #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. - unsafe { atomic_xor(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() } + unsafe { atomic_xor(self.p.get(), val, order).cast() } } /// Returns a mutable pointer to the underlying pointer. @@ -3975,15 +3976,15 @@ unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -unsafe fn atomic_add(dst: *mut T, val: T, order: Ordering) -> T { +unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_add`. unsafe { match order { - Relaxed => intrinsics::atomic_xadd::(dst, val), - Acquire => intrinsics::atomic_xadd::(dst, val), - Release => intrinsics::atomic_xadd::(dst, val), - AcqRel => intrinsics::atomic_xadd::(dst, val), - SeqCst => intrinsics::atomic_xadd::(dst, val), + Relaxed => intrinsics::atomic_xadd::(dst, val), + Acquire => intrinsics::atomic_xadd::(dst, val), + Release => intrinsics::atomic_xadd::(dst, val), + AcqRel => intrinsics::atomic_xadd::(dst, val), + SeqCst => intrinsics::atomic_xadd::(dst, val), } } } @@ -3992,15 +3993,15 @@ unsafe fn atomic_add(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -unsafe fn atomic_sub(dst: *mut T, val: T, order: Ordering) -> T { +unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_sub`. unsafe { match order { - Relaxed => intrinsics::atomic_xsub::(dst, val), - Acquire => intrinsics::atomic_xsub::(dst, val), - Release => intrinsics::atomic_xsub::(dst, val), - AcqRel => intrinsics::atomic_xsub::(dst, val), - SeqCst => intrinsics::atomic_xsub::(dst, val), + Relaxed => intrinsics::atomic_xsub::(dst, val), + Acquire => intrinsics::atomic_xsub::(dst, val), + Release => intrinsics::atomic_xsub::(dst, val), + AcqRel => intrinsics::atomic_xsub::(dst, val), + SeqCst => intrinsics::atomic_xsub::(dst, val), } } } @@ -4141,15 +4142,15 @@ unsafe fn atomic_compare_exchange_weak( #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -unsafe fn atomic_and(dst: *mut T, val: T, order: Ordering) -> T { +unsafe fn atomic_and(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_and` unsafe { match order { - Relaxed => intrinsics::atomic_and::(dst, val), - Acquire => intrinsics::atomic_and::(dst, val), - Release => intrinsics::atomic_and::(dst, val), - AcqRel => intrinsics::atomic_and::(dst, val), - SeqCst => intrinsics::atomic_and::(dst, val), + Relaxed => intrinsics::atomic_and::(dst, val), + Acquire => intrinsics::atomic_and::(dst, val), + Release => intrinsics::atomic_and::(dst, val), + AcqRel => intrinsics::atomic_and::(dst, val), + SeqCst => intrinsics::atomic_and::(dst, val), } } } @@ -4157,15 +4158,15 @@ unsafe fn atomic_and(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -unsafe fn atomic_nand(dst: *mut T, val: T, order: Ordering) -> T { +unsafe fn atomic_nand(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_nand` unsafe { match order { - Relaxed => intrinsics::atomic_nand::(dst, val), - Acquire => intrinsics::atomic_nand::(dst, val), - Release => intrinsics::atomic_nand::(dst, val), - AcqRel => intrinsics::atomic_nand::(dst, val), - SeqCst => intrinsics::atomic_nand::(dst, val), + Relaxed => intrinsics::atomic_nand::(dst, val), + Acquire => intrinsics::atomic_nand::(dst, val), + Release => intrinsics::atomic_nand::(dst, val), + AcqRel => intrinsics::atomic_nand::(dst, val), + SeqCst => intrinsics::atomic_nand::(dst, val), } } } @@ -4173,15 +4174,15 @@ unsafe fn atomic_nand(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -unsafe fn atomic_or(dst: *mut T, val: T, order: Ordering) -> T { +unsafe fn atomic_or(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_or` unsafe { match order { - SeqCst => intrinsics::atomic_or::(dst, val), - Acquire => intrinsics::atomic_or::(dst, val), - Release => intrinsics::atomic_or::(dst, val), - AcqRel => intrinsics::atomic_or::(dst, val), - Relaxed => intrinsics::atomic_or::(dst, val), + SeqCst => intrinsics::atomic_or::(dst, val), + Acquire => intrinsics::atomic_or::(dst, val), + Release => intrinsics::atomic_or::(dst, val), + AcqRel => intrinsics::atomic_or::(dst, val), + Relaxed => intrinsics::atomic_or::(dst, val), } } } @@ -4189,15 +4190,15 @@ unsafe fn atomic_or(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -unsafe fn atomic_xor(dst: *mut T, val: T, order: Ordering) -> T { +unsafe fn atomic_xor(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_xor` unsafe { match order { - SeqCst => intrinsics::atomic_xor::(dst, val), - Acquire => intrinsics::atomic_xor::(dst, val), - Release => intrinsics::atomic_xor::(dst, val), - AcqRel => intrinsics::atomic_xor::(dst, val), - Relaxed => intrinsics::atomic_xor::(dst, val), + SeqCst => intrinsics::atomic_xor::(dst, val), + Acquire => intrinsics::atomic_xor::(dst, val), + Release => intrinsics::atomic_xor::(dst, val), + AcqRel => intrinsics::atomic_xor::(dst, val), + Relaxed => intrinsics::atomic_xor::(dst, val), } } } diff --git a/src/tools/miri/src/intrinsics/atomic.rs b/src/tools/miri/src/intrinsics/atomic.rs index 0a59a707a101..341a00a30aec 100644 --- a/src/tools/miri/src/intrinsics/atomic.rs +++ b/src/tools/miri/src/intrinsics/atomic.rs @@ -105,27 +105,27 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "or" => { - let ord = get_ord_at(1); + let ord = get_ord_at(2); this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitOr, false), rw_ord(ord))?; } "xor" => { - let ord = get_ord_at(1); + let ord = get_ord_at(2); this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitXor, false), rw_ord(ord))?; } "and" => { - let ord = get_ord_at(1); + let ord = get_ord_at(2); this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitAnd, false), rw_ord(ord))?; } "nand" => { - let ord = get_ord_at(1); + let ord = get_ord_at(2); this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitAnd, true), rw_ord(ord))?; } "xadd" => { - let ord = get_ord_at(1); + let ord = get_ord_at(2); this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::Add, false), rw_ord(ord))?; } "xsub" => { - let ord = get_ord_at(1); + let ord = get_ord_at(2); this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::Sub, false), rw_ord(ord))?; } "min" => { @@ -231,15 +231,14 @@ trait EvalContextPrivExt<'tcx>: MiriInterpCxExt<'tcx> { let place = this.deref_pointer(place)?; let rhs = this.read_immediate(rhs)?; - if !place.layout.ty.is_integral() && !place.layout.ty.is_raw_ptr() { + if !(place.layout.ty.is_integral() || place.layout.ty.is_raw_ptr()) + || !(rhs.layout.ty.is_integral() || rhs.layout.ty.is_raw_ptr()) + { span_bug!( this.cur_span(), "atomic arithmetic operations only work on integer and raw pointer types", ); } - if rhs.layout.ty != place.layout.ty { - span_bug!(this.cur_span(), "atomic arithmetic operation type mismatch"); - } let old = match atomic_op { AtomicOp::Min => diff --git a/src/tools/miri/src/operator.rs b/src/tools/miri/src/operator.rs index 73d671121f65..3c3f2c285358 100644 --- a/src/tools/miri/src/operator.rs +++ b/src/tools/miri/src/operator.rs @@ -50,17 +50,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Some more operations are possible with atomics. - // The return value always has the provenance of the *left* operand. + // The RHS must be `usize`. Add | Sub | BitOr | BitAnd | BitXor => { assert!(left.layout.ty.is_raw_ptr()); - assert!(right.layout.ty.is_raw_ptr()); + assert_eq!(right.layout.ty, this.tcx.types.usize); let ptr = left.to_scalar().to_pointer(this)?; // We do the actual operation with usize-typed scalars. let left = ImmTy::from_uint(ptr.addr().bytes(), this.machine.layouts.usize); - let right = ImmTy::from_uint( - right.to_scalar().to_target_usize(this)?, - this.machine.layouts.usize, - ); let result = this.binary_op(bin_op, &left, &right)?; // Construct a new pointer with the provenance of `ptr` (the LHS). let result_ptr = Pointer::new( diff --git a/tests/codegen-llvm/atomicptr.rs b/tests/codegen-llvm/atomicptr.rs index 4819af40ca2d..ce6c4aa0d2b8 100644 --- a/tests/codegen-llvm/atomicptr.rs +++ b/tests/codegen-llvm/atomicptr.rs @@ -1,5 +1,5 @@ // LLVM does not support some atomic RMW operations on pointers, so inside codegen we lower those -// to integer atomics, surrounded by casts to and from integer type. +// to integer atomics, followed by an inttoptr cast. // This test ensures that we do the round-trip correctly for AtomicPtr::fetch_byte_add, and also // ensures that we do not have such a round-trip for AtomicPtr::swap, because LLVM supports pointer // arguments to `atomicrmw xchg`. @@ -20,8 +20,8 @@ pub fn helper(_: usize) {} // CHECK-LABEL: @atomicptr_fetch_byte_add #[no_mangle] pub fn atomicptr_fetch_byte_add(a: &AtomicPtr, v: usize) -> *mut u8 { - // CHECK: %[[INTPTR:.*]] = ptrtoint ptr %{{.*}} to [[USIZE]] - // CHECK-NEXT: %[[RET:.*]] = atomicrmw add ptr %{{.*}}, [[USIZE]] %[[INTPTR]] + // CHECK: llvm.lifetime.start + // CHECK-NEXT: %[[RET:.*]] = atomicrmw add ptr %{{.*}}, [[USIZE]] %v // CHECK-NEXT: inttoptr [[USIZE]] %[[RET]] to ptr a.fetch_byte_add(v, Relaxed) } diff --git a/tests/run-make/atomic-lock-free/atomic_lock_free.rs b/tests/run-make/atomic-lock-free/atomic_lock_free.rs index f5c3b360ee81..92ffd111ce8b 100644 --- a/tests/run-make/atomic-lock-free/atomic_lock_free.rs +++ b/tests/run-make/atomic-lock-free/atomic_lock_free.rs @@ -14,7 +14,7 @@ pub enum AtomicOrdering { } #[rustc_intrinsic] -unsafe fn atomic_xadd(dst: *mut T, src: T) -> T; +unsafe fn atomic_xadd(dst: *mut T, src: U) -> T; #[lang = "pointee_sized"] pub trait PointeeSized {} @@ -35,51 +35,62 @@ impl Copy for *mut T {} impl ConstParamTy for AtomicOrdering {} #[cfg(target_has_atomic = "8")] +#[unsafe(no_mangle)] // let's make sure we actually generate a symbol to check pub unsafe fn atomic_u8(x: *mut u8) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1u8); } #[cfg(target_has_atomic = "8")] +#[unsafe(no_mangle)] pub unsafe fn atomic_i8(x: *mut i8) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1i8); } #[cfg(target_has_atomic = "16")] +#[unsafe(no_mangle)] pub unsafe fn atomic_u16(x: *mut u16) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1u16); } #[cfg(target_has_atomic = "16")] +#[unsafe(no_mangle)] pub unsafe fn atomic_i16(x: *mut i16) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1i16); } #[cfg(target_has_atomic = "32")] +#[unsafe(no_mangle)] pub unsafe fn atomic_u32(x: *mut u32) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1u32); } #[cfg(target_has_atomic = "32")] +#[unsafe(no_mangle)] pub unsafe fn atomic_i32(x: *mut i32) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1i32); } #[cfg(target_has_atomic = "64")] +#[unsafe(no_mangle)] pub unsafe fn atomic_u64(x: *mut u64) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1u64); } #[cfg(target_has_atomic = "64")] +#[unsafe(no_mangle)] pub unsafe fn atomic_i64(x: *mut i64) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1i64); } #[cfg(target_has_atomic = "128")] +#[unsafe(no_mangle)] pub unsafe fn atomic_u128(x: *mut u128) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1u128); } #[cfg(target_has_atomic = "128")] +#[unsafe(no_mangle)] pub unsafe fn atomic_i128(x: *mut i128) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1i128); } #[cfg(target_has_atomic = "ptr")] +#[unsafe(no_mangle)] pub unsafe fn atomic_usize(x: *mut usize) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1usize); } #[cfg(target_has_atomic = "ptr")] +#[unsafe(no_mangle)] pub unsafe fn atomic_isize(x: *mut isize) { - atomic_xadd::<_, { AtomicOrdering::SeqCst }>(x, 1); + atomic_xadd::<_, _, { AtomicOrdering::SeqCst }>(x, 1isize); } diff --git a/tests/ui/intrinsics/intrinsic-atomics.rs b/tests/ui/intrinsics/intrinsic-atomics.rs index 2275aafff833..c19948137db0 100644 --- a/tests/ui/intrinsics/intrinsic-atomics.rs +++ b/tests/ui/intrinsics/intrinsic-atomics.rs @@ -33,14 +33,14 @@ pub fn main() { assert_eq!(rusti::atomic_xchg::<_, { Release }>(&mut *x, 0), 1); assert_eq!(*x, 0); - assert_eq!(rusti::atomic_xadd::<_, { SeqCst }>(&mut *x, 1), 0); - assert_eq!(rusti::atomic_xadd::<_, { Acquire }>(&mut *x, 1), 1); - assert_eq!(rusti::atomic_xadd::<_, { Release }>(&mut *x, 1), 2); + assert_eq!(rusti::atomic_xadd::<_, _, { SeqCst }>(&mut *x, 1), 0); + assert_eq!(rusti::atomic_xadd::<_, _, { Acquire }>(&mut *x, 1), 1); + assert_eq!(rusti::atomic_xadd::<_, _, { Release }>(&mut *x, 1), 2); assert_eq!(*x, 3); - assert_eq!(rusti::atomic_xsub::<_, { SeqCst }>(&mut *x, 1), 3); - assert_eq!(rusti::atomic_xsub::<_, { Acquire }>(&mut *x, 1), 2); - assert_eq!(rusti::atomic_xsub::<_, { Release }>(&mut *x, 1), 1); + assert_eq!(rusti::atomic_xsub::<_, _, { SeqCst }>(&mut *x, 1), 3); + assert_eq!(rusti::atomic_xsub::<_, _, { Acquire }>(&mut *x, 1), 2); + assert_eq!(rusti::atomic_xsub::<_, _, { Release }>(&mut *x, 1), 1); assert_eq!(*x, 0); loop { diff --git a/tests/ui/intrinsics/non-integer-atomic.rs b/tests/ui/intrinsics/non-integer-atomic.rs index 853c163710fc..30f713f12412 100644 --- a/tests/ui/intrinsics/non-integer-atomic.rs +++ b/tests/ui/intrinsics/non-integer-atomic.rs @@ -13,80 +13,80 @@ pub type Quux = [u8; 100]; pub unsafe fn test_bool_load(p: &mut bool, v: bool) { intrinsics::atomic_load::<_, { SeqCst }>(p); - //~^ ERROR `atomic_load` intrinsic: expected basic integer type, found `bool` + //~^ ERROR `atomic_load` intrinsic: expected basic integer or pointer type, found `bool` } pub unsafe fn test_bool_store(p: &mut bool, v: bool) { intrinsics::atomic_store::<_, { SeqCst }>(p, v); - //~^ ERROR `atomic_store` intrinsic: expected basic integer type, found `bool` + //~^ ERROR `atomic_store` intrinsic: expected basic integer or pointer type, found `bool` } pub unsafe fn test_bool_xchg(p: &mut bool, v: bool) { intrinsics::atomic_xchg::<_, { SeqCst }>(p, v); - //~^ ERROR `atomic_xchg` intrinsic: expected basic integer type, found `bool` + //~^ ERROR `atomic_xchg` intrinsic: expected basic integer or pointer type, found `bool` } pub unsafe fn test_bool_cxchg(p: &mut bool, v: bool) { intrinsics::atomic_cxchg::<_, { SeqCst }, { SeqCst }>(p, v, v); - //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer type, found `bool` + //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer or pointer type, found `bool` } pub unsafe fn test_Foo_load(p: &mut Foo, v: Foo) { intrinsics::atomic_load::<_, { SeqCst }>(p); - //~^ ERROR `atomic_load` intrinsic: expected basic integer type, found `Foo` + //~^ ERROR `atomic_load` intrinsic: expected basic integer or pointer type, found `Foo` } pub unsafe fn test_Foo_store(p: &mut Foo, v: Foo) { intrinsics::atomic_store::<_, { SeqCst }>(p, v); - //~^ ERROR `atomic_store` intrinsic: expected basic integer type, found `Foo` + //~^ ERROR `atomic_store` intrinsic: expected basic integer or pointer type, found `Foo` } pub unsafe fn test_Foo_xchg(p: &mut Foo, v: Foo) { intrinsics::atomic_xchg::<_, { SeqCst }>(p, v); - //~^ ERROR `atomic_xchg` intrinsic: expected basic integer type, found `Foo` + //~^ ERROR `atomic_xchg` intrinsic: expected basic integer or pointer type, found `Foo` } pub unsafe fn test_Foo_cxchg(p: &mut Foo, v: Foo) { intrinsics::atomic_cxchg::<_, { SeqCst }, { SeqCst }>(p, v, v); - //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer type, found `Foo` + //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer or pointer type, found `Foo` } pub unsafe fn test_Bar_load(p: &mut Bar, v: Bar) { intrinsics::atomic_load::<_, { SeqCst }>(p); - //~^ ERROR expected basic integer type, found `&dyn Fn()` + //~^ ERROR expected basic integer or pointer type, found `&dyn Fn()` } pub unsafe fn test_Bar_store(p: &mut Bar, v: Bar) { intrinsics::atomic_store::<_, { SeqCst }>(p, v); - //~^ ERROR expected basic integer type, found `&dyn Fn()` + //~^ ERROR expected basic integer or pointer type, found `&dyn Fn()` } pub unsafe fn test_Bar_xchg(p: &mut Bar, v: Bar) { intrinsics::atomic_xchg::<_, { SeqCst }>(p, v); - //~^ ERROR expected basic integer type, found `&dyn Fn()` + //~^ ERROR expected basic integer or pointer type, found `&dyn Fn()` } pub unsafe fn test_Bar_cxchg(p: &mut Bar, v: Bar) { intrinsics::atomic_cxchg::<_, { SeqCst }, { SeqCst }>(p, v, v); - //~^ ERROR expected basic integer type, found `&dyn Fn()` + //~^ ERROR expected basic integer or pointer type, found `&dyn Fn()` } pub unsafe fn test_Quux_load(p: &mut Quux, v: Quux) { intrinsics::atomic_load::<_, { SeqCst }>(p); - //~^ ERROR `atomic_load` intrinsic: expected basic integer type, found `[u8; 100]` + //~^ ERROR `atomic_load` intrinsic: expected basic integer or pointer type, found `[u8; 100]` } pub unsafe fn test_Quux_store(p: &mut Quux, v: Quux) { intrinsics::atomic_store::<_, { SeqCst }>(p, v); - //~^ ERROR `atomic_store` intrinsic: expected basic integer type, found `[u8; 100]` + //~^ ERROR `atomic_store` intrinsic: expected basic integer or pointer type, found `[u8; 100]` } pub unsafe fn test_Quux_xchg(p: &mut Quux, v: Quux) { intrinsics::atomic_xchg::<_, { SeqCst }>(p, v); - //~^ ERROR `atomic_xchg` intrinsic: expected basic integer type, found `[u8; 100]` + //~^ ERROR `atomic_xchg` intrinsic: expected basic integer or pointer type, found `[u8; 100]` } pub unsafe fn test_Quux_cxchg(p: &mut Quux, v: Quux) { intrinsics::atomic_cxchg::<_, { SeqCst }, { SeqCst }>(p, v, v); - //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer type, found `[u8; 100]` + //~^ ERROR `atomic_cxchg` intrinsic: expected basic integer or pointer type, found `[u8; 100]` } diff --git a/tests/ui/intrinsics/non-integer-atomic.stderr b/tests/ui/intrinsics/non-integer-atomic.stderr index e539d99b8aeb..b96ee7ba8468 100644 --- a/tests/ui/intrinsics/non-integer-atomic.stderr +++ b/tests/ui/intrinsics/non-integer-atomic.stderr @@ -1,94 +1,94 @@ -error[E0511]: invalid monomorphization of `atomic_load` intrinsic: expected basic integer type, found `bool` +error[E0511]: invalid monomorphization of `atomic_load` intrinsic: expected basic integer or pointer type, found `bool` --> $DIR/non-integer-atomic.rs:15:5 | LL | intrinsics::atomic_load::<_, { SeqCst }>(p); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_store` intrinsic: expected basic integer type, found `bool` +error[E0511]: invalid monomorphization of `atomic_store` intrinsic: expected basic integer or pointer type, found `bool` --> $DIR/non-integer-atomic.rs:20:5 | LL | intrinsics::atomic_store::<_, { SeqCst }>(p, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_xchg` intrinsic: expected basic integer type, found `bool` +error[E0511]: invalid monomorphization of `atomic_xchg` intrinsic: expected basic integer or pointer type, found `bool` --> $DIR/non-integer-atomic.rs:25:5 | LL | intrinsics::atomic_xchg::<_, { SeqCst }>(p, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_cxchg` intrinsic: expected basic integer type, found `bool` +error[E0511]: invalid monomorphization of `atomic_cxchg` intrinsic: expected basic integer or pointer type, found `bool` --> $DIR/non-integer-atomic.rs:30:5 | LL | intrinsics::atomic_cxchg::<_, { SeqCst }, { SeqCst }>(p, v, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_load` intrinsic: expected basic integer type, found `Foo` +error[E0511]: invalid monomorphization of `atomic_load` intrinsic: expected basic integer or pointer type, found `Foo` --> $DIR/non-integer-atomic.rs:35:5 | LL | intrinsics::atomic_load::<_, { SeqCst }>(p); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_store` intrinsic: expected basic integer type, found `Foo` +error[E0511]: invalid monomorphization of `atomic_store` intrinsic: expected basic integer or pointer type, found `Foo` --> $DIR/non-integer-atomic.rs:40:5 | LL | intrinsics::atomic_store::<_, { SeqCst }>(p, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_xchg` intrinsic: expected basic integer type, found `Foo` +error[E0511]: invalid monomorphization of `atomic_xchg` intrinsic: expected basic integer or pointer type, found `Foo` --> $DIR/non-integer-atomic.rs:45:5 | LL | intrinsics::atomic_xchg::<_, { SeqCst }>(p, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_cxchg` intrinsic: expected basic integer type, found `Foo` +error[E0511]: invalid monomorphization of `atomic_cxchg` intrinsic: expected basic integer or pointer type, found `Foo` --> $DIR/non-integer-atomic.rs:50:5 | LL | intrinsics::atomic_cxchg::<_, { SeqCst }, { SeqCst }>(p, v, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_load` intrinsic: expected basic integer type, found `&dyn Fn()` +error[E0511]: invalid monomorphization of `atomic_load` intrinsic: expected basic integer or pointer type, found `&dyn Fn()` --> $DIR/non-integer-atomic.rs:55:5 | LL | intrinsics::atomic_load::<_, { SeqCst }>(p); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_store` intrinsic: expected basic integer type, found `&dyn Fn()` +error[E0511]: invalid monomorphization of `atomic_store` intrinsic: expected basic integer or pointer type, found `&dyn Fn()` --> $DIR/non-integer-atomic.rs:60:5 | LL | intrinsics::atomic_store::<_, { SeqCst }>(p, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_xchg` intrinsic: expected basic integer type, found `&dyn Fn()` +error[E0511]: invalid monomorphization of `atomic_xchg` intrinsic: expected basic integer or pointer type, found `&dyn Fn()` --> $DIR/non-integer-atomic.rs:65:5 | LL | intrinsics::atomic_xchg::<_, { SeqCst }>(p, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_cxchg` intrinsic: expected basic integer type, found `&dyn Fn()` +error[E0511]: invalid monomorphization of `atomic_cxchg` intrinsic: expected basic integer or pointer type, found `&dyn Fn()` --> $DIR/non-integer-atomic.rs:70:5 | LL | intrinsics::atomic_cxchg::<_, { SeqCst }, { SeqCst }>(p, v, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_load` intrinsic: expected basic integer type, found `[u8; 100]` +error[E0511]: invalid monomorphization of `atomic_load` intrinsic: expected basic integer or pointer type, found `[u8; 100]` --> $DIR/non-integer-atomic.rs:75:5 | LL | intrinsics::atomic_load::<_, { SeqCst }>(p); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_store` intrinsic: expected basic integer type, found `[u8; 100]` +error[E0511]: invalid monomorphization of `atomic_store` intrinsic: expected basic integer or pointer type, found `[u8; 100]` --> $DIR/non-integer-atomic.rs:80:5 | LL | intrinsics::atomic_store::<_, { SeqCst }>(p, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_xchg` intrinsic: expected basic integer type, found `[u8; 100]` +error[E0511]: invalid monomorphization of `atomic_xchg` intrinsic: expected basic integer or pointer type, found `[u8; 100]` --> $DIR/non-integer-atomic.rs:85:5 | LL | intrinsics::atomic_xchg::<_, { SeqCst }>(p, v); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0511]: invalid monomorphization of `atomic_cxchg` intrinsic: expected basic integer type, found `[u8; 100]` +error[E0511]: invalid monomorphization of `atomic_cxchg` intrinsic: expected basic integer or pointer type, found `[u8; 100]` --> $DIR/non-integer-atomic.rs:90:5 | LL | intrinsics::atomic_cxchg::<_, { SeqCst }, { SeqCst }>(p, v, v); From cb27ff0715723d174e244b1465b7386c20910f5b Mon Sep 17 00:00:00 2001 From: klensy Date: Wed, 23 Jul 2025 11:40:44 +0300 Subject: [PATCH 0103/1134] remove unused deps --- library/stdarch/Cargo.lock | 23 ------------------- .../stdarch/crates/intrinsic-test/Cargo.toml | 2 -- 2 files changed, 25 deletions(-) diff --git a/library/stdarch/Cargo.lock b/library/stdarch/Cargo.lock index 2eba81399885..9b3255312d27 100644 --- a/library/stdarch/Cargo.lock +++ b/library/stdarch/Cargo.lock @@ -182,27 +182,6 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" -[[package]] -name = "csv" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acdc4883a9c96732e4733212c01447ebd805833b7275a73ca3ee080fd77afdaf" -dependencies = [ - "csv-core", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "csv-core" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d02f3b0da4c6504f86e9cd789d8dbafab48c2321be74e9987593de5a894d93d" -dependencies = [ - "memchr", -] - [[package]] name = "darling" version = "0.13.4" @@ -357,13 +336,11 @@ name = "intrinsic-test" version = "0.1.0" dependencies = [ "clap", - "csv", "diff", "itertools", "log", "pretty_env_logger", "rayon", - "regex", "serde", "serde_json", ] diff --git a/library/stdarch/crates/intrinsic-test/Cargo.toml b/library/stdarch/crates/intrinsic-test/Cargo.toml index 2b2df2dacca6..fbbf90e1400a 100644 --- a/library/stdarch/crates/intrinsic-test/Cargo.toml +++ b/library/stdarch/crates/intrinsic-test/Cargo.toml @@ -13,9 +13,7 @@ edition = "2024" [dependencies] serde = { version = "1", features = ["derive"] } serde_json = "1.0" -csv = "1.1" clap = { version = "4.4", features = ["derive"] } -regex = "1.4.2" log = "0.4.11" pretty_env_logger = "0.5.0" rayon = "1.5.0" From d8bf6c48a4143b82b35b37cbb2799fb2388a190e Mon Sep 17 00:00:00 2001 From: klensy Date: Wed, 23 Jul 2025 12:22:33 +0300 Subject: [PATCH 0104/1134] bump serde_with. Weird that it works without std feature, but --- library/stdarch/Cargo.lock | 60 +++++++------------ .../stdarch/crates/stdarch-gen-arm/Cargo.toml | 2 +- 2 files changed, 23 insertions(+), 39 deletions(-) diff --git a/library/stdarch/Cargo.lock b/library/stdarch/Cargo.lock index 9b3255312d27..fe3b33a453fe 100644 --- a/library/stdarch/Cargo.lock +++ b/library/stdarch/Cargo.lock @@ -73,7 +73,7 @@ version = "0.1.0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn", ] [[package]] @@ -122,7 +122,7 @@ dependencies = [ "anstream", "anstyle", "clap_lex", - "strsim 0.11.1", + "strsim", ] [[package]] @@ -134,7 +134,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.104", + "syn", ] [[package]] @@ -184,9 +184,9 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "darling" -version = "0.13.4" +version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ "darling_core", "darling_macro", @@ -194,27 +194,27 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.13.4" +version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", - "strsim 0.10.0", - "syn 1.0.109", + "strsim", + "syn", ] [[package]] name = "darling_macro" -version = "0.13.4" +version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core", "quote", - "syn 1.0.109", + "syn", ] [[package]] @@ -600,7 +600,7 @@ checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn", ] [[package]] @@ -617,24 +617,25 @@ dependencies = [ [[package]] name = "serde_with" -version = "1.14.0" +version = "3.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678b5a069e50bf00ecd22d0cd8ddf7c236f68581b03db652061ed5eb13a312ff" +checksum = "f2c45cd61fefa9db6f254525d46e392b852e0e61d9a1fd36e5bd183450a556d5" dependencies = [ "serde", + "serde_derive", "serde_with_macros", ] [[package]] name = "serde_with_macros" -version = "1.5.2" +version = "3.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e182d6ec6f05393cc0e5ed1bf81ad6db3a8feedf8ee515ecdd369809bcce8082" +checksum = "de90945e6565ce0d9a25098082ed4ee4002e047cb59892c318d66821e14bb30f" dependencies = [ "darling", "proc-macro2", "quote", - "syn 1.0.109", + "syn", ] [[package]] @@ -661,7 +662,7 @@ version = "0.1.0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn", ] [[package]] @@ -716,7 +717,7 @@ dependencies = [ "quote", "serde", "serde_json", - "syn 2.0.104", + "syn", ] [[package]] @@ -729,29 +730,12 @@ dependencies = [ "std_detect", ] -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - [[package]] name = "syn" version = "2.0.104" @@ -936,5 +920,5 @@ checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn", ] diff --git a/library/stdarch/crates/stdarch-gen-arm/Cargo.toml b/library/stdarch/crates/stdarch-gen-arm/Cargo.toml index 312019f454cb..de24335a52e8 100644 --- a/library/stdarch/crates/stdarch-gen-arm/Cargo.toml +++ b/library/stdarch/crates/stdarch-gen-arm/Cargo.toml @@ -17,6 +17,6 @@ proc-macro2 = "1.0" quote = "1.0" regex = "1.5" serde = { version = "1.0", features = ["derive"] } -serde_with = "1.14" +serde_with = { version = "3.2.0", default-features = false, features = ["macros"] } serde_yaml = "0.8" walkdir = "2.3.2" From 08bca4d6a24660c13ce1af3247638e9cf9d4dd50 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 23 Jul 2025 04:50:41 -0500 Subject: [PATCH 0105/1134] ci: Add native PowerPC64LE and s390x jobs We now have access to native runners, so make use of them for these architectures. The existing ppc64le Docker job is kept for now. --- .../.github/workflows/main.yaml | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/library/compiler-builtins/.github/workflows/main.yaml b/library/compiler-builtins/.github/workflows/main.yaml index 972f1b89878a..6c98a60d25b5 100644 --- a/library/compiler-builtins/.github/workflows/main.yaml +++ b/library/compiler-builtins/.github/workflows/main.yaml @@ -70,8 +70,12 @@ jobs: os: ubuntu-24.04 - target: powerpc64le-unknown-linux-gnu os: ubuntu-24.04 + - target: powerpc64le-unknown-linux-gnu + os: ubuntu-24.04-ppc64le - target: riscv64gc-unknown-linux-gnu os: ubuntu-24.04 + - target: s390x-unknown-linux-gnu + os: ubuntu-24.04-s390x - target: thumbv6m-none-eabi os: ubuntu-24.04 - target: thumbv7em-none-eabi @@ -105,8 +109,21 @@ jobs: TEST_VERBATIM: ${{ matrix.test_verbatim }} MAY_SKIP_LIBM_CI: ${{ needs.calculate_vars.outputs.may_skip_libm_ci }} steps: + - name: Print $HOME + shell: bash + run: | + set -x + echo "${HOME:-not found}" + pwd + printenv - name: Print runner information run: uname -a + + # Native ppc and s390x runners don't have rustup by default + - name: Install rustup + if: matrix.os == 'ubuntu-24.04-ppc64le' || matrix.os == 'ubuntu-24.04-s390x' + run: sudo apt-get update && sudo apt-get install -y rustup + - uses: actions/checkout@v4 - name: Install Rust (rustup) shell: bash @@ -117,7 +134,12 @@ jobs: rustup update "$channel" --no-self-update rustup default "$channel" rustup target add "${{ matrix.target }}" + + # Our scripts use nextest if possible. This is skipped on the native ppc + # and s390x runners since install-action doesn't support them. - uses: taiki-e/install-action@nextest + if: "!(matrix.os == 'ubuntu-24.04-ppc64le' || matrix.os == 'ubuntu-24.04-s390x')" + - uses: Swatinem/rust-cache@v2 with: key: ${{ matrix.target }} From a343926954a525f491756c3c9714417ae9ccc121 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 23 Jul 2025 14:58:49 +0200 Subject: [PATCH 0106/1134] Prepare for merging from rust-lang/rust This updates the rust-version file to 5a30e4307f0506bed87eeecd171f8366fdbda1dc. --- library/stdarch/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/stdarch/rust-version b/library/stdarch/rust-version index 5102178848e7..622dce1c1215 100644 --- a/library/stdarch/rust-version +++ b/library/stdarch/rust-version @@ -1 +1 @@ -040e2f8b9ff2d76fbe2146d6003e297ed4532088 +5a30e4307f0506bed87eeecd171f8366fdbda1dc From 8f0ffa8125f00af923098b30f390f6597b89d80d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 23 Jul 2025 15:01:42 +0200 Subject: [PATCH 0107/1134] Reformat code --- library/stdarch/examples/connect5.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/library/stdarch/examples/connect5.rs b/library/stdarch/examples/connect5.rs index 371b28552b32..f24657b14839 100644 --- a/library/stdarch/examples/connect5.rs +++ b/library/stdarch/examples/connect5.rs @@ -563,11 +563,7 @@ fn search(pos: &Pos, alpha: i32, beta: i32, depth: i32, _ply: i32) -> i32 { assert!(bs >= -EVAL_INF && bs <= EVAL_INF); //best move at the root node, best score elsewhere - if _ply == 0 { - bm - } else { - bs - } + if _ply == 0 { bm } else { bs } } /// Evaluation function: give different scores to different patterns after a fixed depth. From 2b640216aea9527c67c82cfc781d979247ac6028 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Wed, 23 Jul 2025 09:56:54 -0400 Subject: [PATCH 0108/1134] Fix gcc_icmp with non-native integers --- src/int.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/int.rs b/src/int.rs index 9dc1fcf5fc8b..9fb7f6bad684 100644 --- a/src/int.rs +++ b/src/int.rs @@ -494,11 +494,27 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let lhs_low = self.context.new_cast(self.location, self.low(lhs), unsigned_type); let rhs_low = self.context.new_cast(self.location, self.low(rhs), unsigned_type); + let mut lhs_high = self.high(lhs); + let mut rhs_high = self.high(rhs); + + match op { + IntPredicate::IntUGT + | IntPredicate::IntUGE + | IntPredicate::IntULT + | IntPredicate::IntULE => { + lhs_high = self.context.new_cast(self.location, lhs_high, unsigned_type); + rhs_high = self.context.new_cast(self.location, rhs_high, unsigned_type); + } + // TODO(antoyo): we probably need to handle signed comparison for unsigned + // integers. + _ => (), + } + let condition = self.context.new_comparison( self.location, ComparisonOp::LessThan, - self.high(lhs), - self.high(rhs), + lhs_high, + rhs_high, ); self.llbb().end_with_conditional(self.location, condition, block1, block2); @@ -512,8 +528,8 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let condition = self.context.new_comparison( self.location, ComparisonOp::GreaterThan, - self.high(lhs), - self.high(rhs), + lhs_high, + rhs_high, ); block2.end_with_conditional(self.location, condition, block3, block4); From 288a5654514938b973a75e0e1de64ee702170661 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Wed, 23 Jul 2025 09:14:12 -0700 Subject: [PATCH 0109/1134] Upgrade semicolon_in_expressions_from_macros from warn to deny This is already warn-by-default, and a future compatibility warning (FCW) that warns in dependencies. Upgrade it to deny-by-default, as the next step towards hard error. --- compiler/rustc_lint_defs/src/builtin.rs | 2 +- ...arn-semicolon-in-expressions-from-macros.rs | 5 ++--- ...semicolon-in-expressions-from-macros.stderr | 18 +++++++++--------- tests/ui/macros/lint-trailing-macro-call.rs | 4 +--- .../ui/macros/lint-trailing-macro-call.stderr | 18 +++++++++--------- tests/ui/macros/macro-context.rs | 2 +- tests/ui/macros/macro-context.stderr | 14 +++++++------- .../macros/macro-in-expression-context.fixed | 4 ++-- tests/ui/macros/macro-in-expression-context.rs | 4 ++-- .../macros/macro-in-expression-context.stderr | 14 +++++++------- 10 files changed, 41 insertions(+), 44 deletions(-) diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index a08d68e2d153..277a87f9bfc0 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -2838,7 +2838,7 @@ declare_lint! { /// [issue #79813]: https://github.com/rust-lang/rust/issues/79813 /// [future-incompatible]: ../index.md#future-incompatible-lints pub SEMICOLON_IN_EXPRESSIONS_FROM_MACROS, - Warn, + Deny, "trailing semicolon in macro body used as expression", @future_incompatible = FutureIncompatibleInfo { reason: FutureIncompatibilityReason::FutureReleaseError, diff --git a/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.rs b/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.rs index 05fbfec2ae57..8ec70a17864a 100644 --- a/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.rs +++ b/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.rs @@ -1,9 +1,8 @@ -//@ check-pass -// Ensure that trailing semicolons cause warnings by default +// Ensure that trailing semicolons cause errors by default macro_rules! foo { () => { - true; //~ WARN trailing semicolon in macro + true; //~ ERROR trailing semicolon in macro //~| WARN this was previously } } diff --git a/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.stderr b/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.stderr index 0fec4996f1a0..99cdcafab39a 100644 --- a/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.stderr +++ b/tests/ui/lint/semicolon-in-expressions-from-macros/warn-semicolon-in-expressions-from-macros.stderr @@ -1,5 +1,5 @@ -warning: trailing semicolon in macro used in expression position - --> $DIR/warn-semicolon-in-expressions-from-macros.rs:6:13 +error: trailing semicolon in macro used in expression position + --> $DIR/warn-semicolon-in-expressions-from-macros.rs:5:13 | LL | true; | ^ @@ -9,14 +9,14 @@ LL | _ => foo!() | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) -warning: 1 warning emitted +error: aborting due to 1 previous error Future incompatibility report: Future breakage diagnostic: -warning: trailing semicolon in macro used in expression position - --> $DIR/warn-semicolon-in-expressions-from-macros.rs:6:13 +error: trailing semicolon in macro used in expression position + --> $DIR/warn-semicolon-in-expressions-from-macros.rs:5:13 | LL | true; | ^ @@ -26,6 +26,6 @@ LL | _ => foo!() | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/macros/lint-trailing-macro-call.rs b/tests/ui/macros/lint-trailing-macro-call.rs index 78b861f1df17..25fa91062c43 100644 --- a/tests/ui/macros/lint-trailing-macro-call.rs +++ b/tests/ui/macros/lint-trailing-macro-call.rs @@ -1,12 +1,10 @@ -//@ check-pass -// // Ensures that we properly lint // a removed 'expression' resulting from a macro // in trailing expression position macro_rules! expand_it { () => { - #[cfg(false)] 25; //~ WARN trailing semicolon in macro + #[cfg(false)] 25; //~ ERROR trailing semicolon in macro //~| WARN this was previously } } diff --git a/tests/ui/macros/lint-trailing-macro-call.stderr b/tests/ui/macros/lint-trailing-macro-call.stderr index 223b85e112ed..3fd1ea813459 100644 --- a/tests/ui/macros/lint-trailing-macro-call.stderr +++ b/tests/ui/macros/lint-trailing-macro-call.stderr @@ -1,5 +1,5 @@ -warning: trailing semicolon in macro used in expression position - --> $DIR/lint-trailing-macro-call.rs:9:25 +error: trailing semicolon in macro used in expression position + --> $DIR/lint-trailing-macro-call.rs:7:25 | LL | #[cfg(false)] 25; | ^ @@ -11,14 +11,14 @@ LL | expand_it!() = note: for more information, see issue #79813 = note: macro invocations at the end of a block are treated as expressions = note: to ignore the value produced by the macro, add a semicolon after the invocation of `expand_it` - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `expand_it` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `expand_it` (in Nightly builds, run with -Z macro-backtrace for more info) -warning: 1 warning emitted +error: aborting due to 1 previous error Future incompatibility report: Future breakage diagnostic: -warning: trailing semicolon in macro used in expression position - --> $DIR/lint-trailing-macro-call.rs:9:25 +error: trailing semicolon in macro used in expression position + --> $DIR/lint-trailing-macro-call.rs:7:25 | LL | #[cfg(false)] 25; | ^ @@ -30,6 +30,6 @@ LL | expand_it!() = note: for more information, see issue #79813 = note: macro invocations at the end of a block are treated as expressions = note: to ignore the value produced by the macro, add a semicolon after the invocation of `expand_it` - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `expand_it` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `expand_it` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/macros/macro-context.rs b/tests/ui/macros/macro-context.rs index a31470263a0a..e1c24ba8b570 100644 --- a/tests/ui/macros/macro-context.rs +++ b/tests/ui/macros/macro-context.rs @@ -6,7 +6,7 @@ macro_rules! m { //~| ERROR macro expansion ignores `;` //~| ERROR cannot find type `i` in this scope //~| ERROR cannot find value `i` in this scope - //~| WARN trailing semicolon in macro + //~| ERROR trailing semicolon in macro //~| WARN this was previously } diff --git a/tests/ui/macros/macro-context.stderr b/tests/ui/macros/macro-context.stderr index 4820a43f00c7..6b49c05f360d 100644 --- a/tests/ui/macros/macro-context.stderr +++ b/tests/ui/macros/macro-context.stderr @@ -64,7 +64,7 @@ LL | let i = m!(); | = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) -warning: trailing semicolon in macro used in expression position +error: trailing semicolon in macro used in expression position --> $DIR/macro-context.rs:3:15 | LL | () => ( i ; typeof ); @@ -75,15 +75,15 @@ LL | let i = m!(); | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 6 previous errors; 1 warning emitted +error: aborting due to 7 previous errors Some errors have detailed explanations: E0412, E0425. For more information about an error, try `rustc --explain E0412`. Future incompatibility report: Future breakage diagnostic: -warning: trailing semicolon in macro used in expression position +error: trailing semicolon in macro used in expression position --> $DIR/macro-context.rs:3:15 | LL | () => ( i ; typeof ); @@ -94,6 +94,6 @@ LL | let i = m!(); | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #79813 - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/macros/macro-in-expression-context.fixed b/tests/ui/macros/macro-in-expression-context.fixed index 7c830707ffd9..52e1b429e48a 100644 --- a/tests/ui/macros/macro-in-expression-context.fixed +++ b/tests/ui/macros/macro-in-expression-context.fixed @@ -3,12 +3,12 @@ macro_rules! foo { () => { assert_eq!("A", "A"); - //~^ WARN trailing semicolon in macro + //~^ ERROR trailing semicolon in macro //~| WARN this was previously //~| NOTE macro invocations at the end of a block //~| NOTE to ignore the value produced by the macro //~| NOTE for more information - //~| NOTE `#[warn(semicolon_in_expressions_from_macros)]` on by default + //~| NOTE `#[deny(semicolon_in_expressions_from_macros)]` on by default assert_eq!("B", "B"); } //~^^ ERROR macro expansion ignores `assert_eq` and any tokens following diff --git a/tests/ui/macros/macro-in-expression-context.rs b/tests/ui/macros/macro-in-expression-context.rs index da95017aa5f7..5c560e78dad4 100644 --- a/tests/ui/macros/macro-in-expression-context.rs +++ b/tests/ui/macros/macro-in-expression-context.rs @@ -3,12 +3,12 @@ macro_rules! foo { () => { assert_eq!("A", "A"); - //~^ WARN trailing semicolon in macro + //~^ ERROR trailing semicolon in macro //~| WARN this was previously //~| NOTE macro invocations at the end of a block //~| NOTE to ignore the value produced by the macro //~| NOTE for more information - //~| NOTE `#[warn(semicolon_in_expressions_from_macros)]` on by default + //~| NOTE `#[deny(semicolon_in_expressions_from_macros)]` on by default assert_eq!("B", "B"); } //~^^ ERROR macro expansion ignores `assert_eq` and any tokens following diff --git a/tests/ui/macros/macro-in-expression-context.stderr b/tests/ui/macros/macro-in-expression-context.stderr index 43419f2678c2..b04348d70108 100644 --- a/tests/ui/macros/macro-in-expression-context.stderr +++ b/tests/ui/macros/macro-in-expression-context.stderr @@ -13,7 +13,7 @@ help: you might be missing a semicolon here LL | foo!(); | + -warning: trailing semicolon in macro used in expression position +error: trailing semicolon in macro used in expression position --> $DIR/macro-in-expression-context.rs:5:29 | LL | assert_eq!("A", "A"); @@ -26,13 +26,13 @@ LL | foo!() = note: for more information, see issue #79813 = note: macro invocations at the end of a block are treated as expressions = note: to ignore the value produced by the macro, add a semicolon after the invocation of `foo` - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 2 previous errors Future incompatibility report: Future breakage diagnostic: -warning: trailing semicolon in macro used in expression position +error: trailing semicolon in macro used in expression position --> $DIR/macro-in-expression-context.rs:5:29 | LL | assert_eq!("A", "A"); @@ -45,6 +45,6 @@ LL | foo!() = note: for more information, see issue #79813 = note: macro invocations at the end of a block are treated as expressions = note: to ignore the value produced by the macro, add a semicolon after the invocation of `foo` - = note: `#[warn(semicolon_in_expressions_from_macros)]` on by default - = note: this warning originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: `#[deny(semicolon_in_expressions_from_macros)]` on by default + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) From fcc7824b883bd9bba8e588fbe61d45dc427ea18e Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 01:20:55 -0500 Subject: [PATCH 0110/1134] ci: Update to the latest ubuntu:25.04 Docker images This includes a qemu update from 8.2.2 to 9.2.1 which should hopefully fix some bugs we have encountered. PowerPC64LE is skipped for now because the new version seems to cause a number of new SIGILLs. --- .../ci/docker/aarch64-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/arm-unknown-linux-gnueabi/Dockerfile | 2 +- .../ci/docker/arm-unknown-linux-gnueabihf/Dockerfile | 2 +- .../ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile | 2 +- .../ci/docker/i586-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/i686-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/loongarch64-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/mips-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile | 2 +- .../ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile | 2 +- .../ci/docker/mipsel-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/powerpc-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/powerpc64-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile | 1 + .../ci/docker/riscv64gc-unknown-linux-gnu/Dockerfile | 2 +- .../compiler-builtins/ci/docker/thumbv6m-none-eabi/Dockerfile | 2 +- .../compiler-builtins/ci/docker/thumbv7em-none-eabi/Dockerfile | 2 +- .../ci/docker/thumbv7em-none-eabihf/Dockerfile | 2 +- .../compiler-builtins/ci/docker/thumbv7m-none-eabi/Dockerfile | 2 +- .../ci/docker/x86_64-unknown-linux-gnu/Dockerfile | 2 +- library/compiler-builtins/ci/run-docker.sh | 2 +- 21 files changed, 21 insertions(+), 20 deletions(-) diff --git a/library/compiler-builtins/ci/docker/aarch64-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/aarch64-unknown-linux-gnu/Dockerfile index df71804ba235..69b99f5b6b32 100644 --- a/library/compiler-builtins/ci/docker/aarch64-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/aarch64-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/arm-unknown-linux-gnueabi/Dockerfile b/library/compiler-builtins/ci/docker/arm-unknown-linux-gnueabi/Dockerfile index 38ad1a136236..2fa6f8520520 100644 --- a/library/compiler-builtins/ci/docker/arm-unknown-linux-gnueabi/Dockerfile +++ b/library/compiler-builtins/ci/docker/arm-unknown-linux-gnueabi/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile b/library/compiler-builtins/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile index ffead05d5f22..85f7335f5a85 100644 --- a/library/compiler-builtins/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile +++ b/library/compiler-builtins/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile b/library/compiler-builtins/ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile index 9ab49e46ee3a..42511479f36f 100644 --- a/library/compiler-builtins/ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile +++ b/library/compiler-builtins/ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/i586-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/i586-unknown-linux-gnu/Dockerfile index d12ced3257fe..35488c477493 100644 --- a/library/compiler-builtins/ci/docker/i586-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/i586-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/i686-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/i686-unknown-linux-gnu/Dockerfile index d12ced3257fe..35488c477493 100644 --- a/library/compiler-builtins/ci/docker/i686-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/i686-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/loongarch64-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/loongarch64-unknown-linux-gnu/Dockerfile index 62b43da9e70d..e95a1b9163ff 100644 --- a/library/compiler-builtins/ci/docker/loongarch64-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/loongarch64-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/mips-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/mips-unknown-linux-gnu/Dockerfile index c02a94672340..fd1877603100 100644 --- a/library/compiler-builtins/ci/docker/mips-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/mips-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile b/library/compiler-builtins/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile index 6d8b96069bed..4e542ce6858c 100644 --- a/library/compiler-builtins/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile +++ b/library/compiler-builtins/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile b/library/compiler-builtins/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile index 7e6ac7c3b8aa..528dfd8940d5 100644 --- a/library/compiler-builtins/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile +++ b/library/compiler-builtins/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/mipsel-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/mipsel-unknown-linux-gnu/Dockerfile index 9feadc7b5ce1..2572180238e2 100644 --- a/library/compiler-builtins/ci/docker/mipsel-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/mipsel-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/powerpc-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/powerpc-unknown-linux-gnu/Dockerfile index 84dcaf47ed5d..cac1f23610aa 100644 --- a/library/compiler-builtins/ci/docker/powerpc-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/powerpc-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile index b90fd5ec5456..76127b7dbb8c 100644 --- a/library/compiler-builtins/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile index e6d1d1cd0b53..c95adecf04a9 100644 --- a/library/compiler-builtins/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile @@ -1,3 +1,4 @@ +# FIXME(ppc): We want 25.04 but get SIGILLs ARG IMAGE=ubuntu:24.04 FROM $IMAGE diff --git a/library/compiler-builtins/ci/docker/riscv64gc-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/riscv64gc-unknown-linux-gnu/Dockerfile index eeb4ed0193e2..513efacd6d96 100644 --- a/library/compiler-builtins/ci/docker/riscv64gc-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/riscv64gc-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/thumbv6m-none-eabi/Dockerfile b/library/compiler-builtins/ci/docker/thumbv6m-none-eabi/Dockerfile index ad0d4351ea65..a9a172a21137 100644 --- a/library/compiler-builtins/ci/docker/thumbv6m-none-eabi/Dockerfile +++ b/library/compiler-builtins/ci/docker/thumbv6m-none-eabi/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/thumbv7em-none-eabi/Dockerfile b/library/compiler-builtins/ci/docker/thumbv7em-none-eabi/Dockerfile index ad0d4351ea65..a9a172a21137 100644 --- a/library/compiler-builtins/ci/docker/thumbv7em-none-eabi/Dockerfile +++ b/library/compiler-builtins/ci/docker/thumbv7em-none-eabi/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/thumbv7em-none-eabihf/Dockerfile b/library/compiler-builtins/ci/docker/thumbv7em-none-eabihf/Dockerfile index ad0d4351ea65..a9a172a21137 100644 --- a/library/compiler-builtins/ci/docker/thumbv7em-none-eabihf/Dockerfile +++ b/library/compiler-builtins/ci/docker/thumbv7em-none-eabihf/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/thumbv7m-none-eabi/Dockerfile b/library/compiler-builtins/ci/docker/thumbv7m-none-eabi/Dockerfile index ad0d4351ea65..a9a172a21137 100644 --- a/library/compiler-builtins/ci/docker/thumbv7m-none-eabi/Dockerfile +++ b/library/compiler-builtins/ci/docker/thumbv7m-none-eabi/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/docker/x86_64-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/x86_64-unknown-linux-gnu/Dockerfile index c590adcddf64..2ef800129d67 100644 --- a/library/compiler-builtins/ci/docker/x86_64-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/x86_64-unknown-linux-gnu/Dockerfile @@ -1,4 +1,4 @@ -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ diff --git a/library/compiler-builtins/ci/run-docker.sh b/library/compiler-builtins/ci/run-docker.sh index d0122dee5c89..4c1fe0fe2644 100755 --- a/library/compiler-builtins/ci/run-docker.sh +++ b/library/compiler-builtins/ci/run-docker.sh @@ -97,7 +97,7 @@ if [ "${1:-}" = "--help" ] || [ "$#" -gt 1 ]; then usage: ./ci/run-docker.sh [target] you can also set DOCKER_BASE_IMAGE to use something other than the default - ubuntu:24.04 (or rustlang/rust:nightly). + ubuntu:25.04 (or rustlang/rust:nightly). " exit fi From 95c42630eb7fb234dfd369d2c1ce671c7b304f9e Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 03:26:32 -0500 Subject: [PATCH 0111/1134] symcheck: Switch the `object` dependency from git to crates.io Wasm support has since been released, so we no longer need to depend on a git version of `object`. --- library/compiler-builtins/crates/symbol-check/Cargo.toml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/library/compiler-builtins/crates/symbol-check/Cargo.toml b/library/compiler-builtins/crates/symbol-check/Cargo.toml index 30969ee406ab..e2218b491720 100644 --- a/library/compiler-builtins/crates/symbol-check/Cargo.toml +++ b/library/compiler-builtins/crates/symbol-check/Cargo.toml @@ -5,8 +5,7 @@ edition = "2024" publish = false [dependencies] -# FIXME: used as a git dependency since the latest release does not support wasm -object = { git = "https://github.com/gimli-rs/object.git", rev = "013fac75da56a684377af4151b8164b78c1790e0" } +object = "0.37.1" serde_json = "1.0.140" [features] From 83aea652e444bd246600bb1b7a39b92482366bd2 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 04:05:41 -0500 Subject: [PATCH 0112/1134] ci: Use a mirror for musl We pretty often get at least one job failed because of failure to pull the musl git repo. Switch this to the unofficial mirror [1] which should be more reliable. Link: https://github.com/kraj/musl [1] --- library/compiler-builtins/ci/update-musl.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/compiler-builtins/ci/update-musl.sh b/library/compiler-builtins/ci/update-musl.sh index b71cf5778300..637ab1394855 100755 --- a/library/compiler-builtins/ci/update-musl.sh +++ b/library/compiler-builtins/ci/update-musl.sh @@ -3,7 +3,7 @@ set -eux -url=git://git.musl-libc.org/musl +url=https://github.com/kraj/musl.git ref=c47ad25ea3b484e10326f933e927c0bc8cded3da dst=crates/musl-math-sys/musl From 5c4abe9ca022cff5fa8d334423a34a8cdc356f05 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 04:49:46 -0500 Subject: [PATCH 0113/1134] ci: Upgrade ubuntu:25.04 for the PowerPC64LE test Update the last remaining image. For this to work, the `QEMU_CPU=POWER8` configuration needed to be dropped to avoid a new SIGILL. Doing some debugging locally, the crash comes from an `extswsli` (per `powerpc:common64` in gdb-multiarch) in the `ld64.so` available with PowerPC, which qemu rejects when set to power8. Testing a build with `+crt-static` hits the same issue at a `maddld` in `__libc_start_main_impl`. Rust isn't needed to reproduce this: $ cat a.c #include int main() { printf("Hello, world!\n"); } $ powerpc64le-linux-gnu-gcc a.c $ QEMU_CPU=power8 QEMU_LD_PREFIX=/usr/powerpc64le-linux-gnu/ ./a.out qemu: uncaught target signal 4 (Illegal instruction) - core dumped Illegal instruction So the cross toolchain provided by Debian must have a power9 baseline rather than rustc's power8. Alternatively, qemu may be incorrectly rejecting these instructions (I can't find a source on whether or not they should be available for power8). Testing instead with the `-musl` toolchain and ppc linker from musl.cc works correctly. In any case, things work with the default qemu config so it seems fine to drop. The env was originally added in 5d164a4edafb ("fix the powerpc64le target") but whatever the problem was there appears to no longer be relevant. --- .../ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/library/compiler-builtins/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile b/library/compiler-builtins/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile index c95adecf04a9..da1d56ca66f2 100644 --- a/library/compiler-builtins/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile +++ b/library/compiler-builtins/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile @@ -1,5 +1,4 @@ -# FIXME(ppc): We want 25.04 but get SIGILLs -ARG IMAGE=ubuntu:24.04 +ARG IMAGE=ubuntu:25.04 FROM $IMAGE RUN apt-get update && \ @@ -13,6 +12,5 @@ ENV CARGO_TARGET_POWERPC64LE_UNKNOWN_LINUX_GNU_LINKER="$TOOLCHAIN_PREFIX"gcc \ CARGO_TARGET_POWERPC64LE_UNKNOWN_LINUX_GNU_RUNNER=qemu-ppc64le-static \ AR_powerpc64le_unknown_linux_gnu="$TOOLCHAIN_PREFIX"ar \ CC_powerpc64le_unknown_linux_gnu="$TOOLCHAIN_PREFIX"gcc \ - QEMU_CPU=POWER8 \ QEMU_LD_PREFIX=/usr/powerpc64le-linux-gnu \ RUST_TEST_THREADS=1 From 43c3e1bb97186d598dc7066706bd66cf5a383cfb Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 01:18:46 -0500 Subject: [PATCH 0114/1134] Enable tests that were skipped on PowerPC Most of these were skipped because of a bug with the platform implementation, or some kind of crash unwinding. Since the upgrade to Ubuntu 25.04, these all seem to be resolved with the exception of a bug in the host `__floatundisf` [1]. [1] https://github.com/rust-lang/compiler-builtins/pull/384#issuecomment-740413334 --- .../builtins-test-intrinsics/src/main.rs | 84 ++++--------------- .../builtins-test/benches/float_conv.rs | 9 -- .../builtins-test/benches/float_extend.rs | 2 - .../builtins-test/benches/float_trunc.rs | 5 -- .../builtins-test/src/bench.rs | 11 --- .../builtins-test/tests/conv.rs | 38 ++++----- .../crates/musl-math-sys/src/lib.rs | 2 - .../compiler-builtins/libm/src/math/j1f.rs | 3 +- 8 files changed, 34 insertions(+), 120 deletions(-) diff --git a/library/compiler-builtins/builtins-test-intrinsics/src/main.rs b/library/compiler-builtins/builtins-test-intrinsics/src/main.rs index 66744a0817fe..b9d19ea77256 100644 --- a/library/compiler-builtins/builtins-test-intrinsics/src/main.rs +++ b/library/compiler-builtins/builtins-test-intrinsics/src/main.rs @@ -40,11 +40,7 @@ mod intrinsics { x as f64 } - #[cfg(all( - f16_enabled, - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(all(f16_enabled, f128_enabled))] pub fn extendhftf(x: f16) -> f128 { x as f128 } @@ -201,11 +197,7 @@ mod intrinsics { /* f128 operations */ - #[cfg(all( - f16_enabled, - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(all(f16_enabled, f128_enabled))] pub fn trunctfhf(x: f128) -> f16 { x as f16 } @@ -220,50 +212,32 @@ mod intrinsics { x as f64 } - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] pub fn fixtfsi(x: f128) -> i32 { x as i32 } - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] pub fn fixtfdi(x: f128) -> i64 { x as i64 } - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] pub fn fixtfti(x: f128) -> i128 { x as i128 } - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] pub fn fixunstfsi(x: f128) -> u32 { x as u32 } - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] pub fn fixunstfdi(x: f128) -> u64 { x as u64 } - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] pub fn fixunstfti(x: f128) -> u128 { x as u128 } @@ -540,47 +514,25 @@ fn run() { bb(extendhfdf(bb(2.))); #[cfg(f16_enabled)] bb(extendhfsf(bb(2.))); - #[cfg(all( - f16_enabled, - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(all(f16_enabled, f128_enabled))] bb(extendhftf(bb(2.))); #[cfg(f128_enabled)] bb(extendsftf(bb(2.))); bb(fixdfti(bb(2.))); bb(fixsfti(bb(2.))); - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] bb(fixtfdi(bb(2.))); - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] bb(fixtfsi(bb(2.))); - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] bb(fixtfti(bb(2.))); bb(fixunsdfti(bb(2.))); bb(fixunssfti(bb(2.))); - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] bb(fixunstfdi(bb(2.))); - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] bb(fixunstfsi(bb(2.))); - #[cfg(all( - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(f128_enabled)] bb(fixunstfti(bb(2.))); #[cfg(f128_enabled)] bb(floatditf(bb(2))); @@ -616,11 +568,7 @@ fn run() { bb(truncsfhf(bb(2.))); #[cfg(f128_enabled)] bb(trunctfdf(bb(2.))); - #[cfg(all( - f16_enabled, - f128_enabled, - not(any(target_arch = "powerpc", target_arch = "powerpc64")) - ))] + #[cfg(all(f16_enabled, f128_enabled))] bb(trunctfhf(bb(2.))); #[cfg(f128_enabled)] bb(trunctfsf(bb(2.))); diff --git a/library/compiler-builtins/builtins-test/benches/float_conv.rs b/library/compiler-builtins/builtins-test/benches/float_conv.rs index d4a7346d1d58..e0f488eb6855 100644 --- a/library/compiler-builtins/builtins-test/benches/float_conv.rs +++ b/library/compiler-builtins/builtins-test/benches/float_conv.rs @@ -365,7 +365,6 @@ float_bench! { /* float -> unsigned int */ -#[cfg(not(all(target_arch = "powerpc64", target_endian = "little")))] float_bench! { name: conv_f32_u32, sig: (a: f32) -> u32, @@ -387,7 +386,6 @@ float_bench! { ], } -#[cfg(not(all(target_arch = "powerpc64", target_endian = "little")))] float_bench! { name: conv_f32_u64, sig: (a: f32) -> u64, @@ -409,7 +407,6 @@ float_bench! { ], } -#[cfg(not(all(target_arch = "powerpc64", target_endian = "little")))] float_bench! { name: conv_f32_u128, sig: (a: f32) -> u128, @@ -505,7 +502,6 @@ float_bench! { /* float -> signed int */ -#[cfg(not(all(target_arch = "powerpc64", target_endian = "little")))] float_bench! { name: conv_f32_i32, sig: (a: f32) -> i32, @@ -527,7 +523,6 @@ float_bench! { ], } -#[cfg(not(all(target_arch = "powerpc64", target_endian = "little")))] float_bench! { name: conv_f32_i64, sig: (a: f32) -> i64, @@ -549,7 +544,6 @@ float_bench! { ], } -#[cfg(not(all(target_arch = "powerpc64", target_endian = "little")))] float_bench! { name: conv_f32_i128, sig: (a: f32) -> i128, @@ -666,9 +660,6 @@ pub fn float_conv() { conv_f64_i128(&mut criterion); #[cfg(f128_enabled)] - // FIXME: ppc64le has a sporadic overflow panic in the crate functions - // - #[cfg(not(all(target_arch = "powerpc64", target_endian = "little")))] { conv_u32_f128(&mut criterion); conv_u64_f128(&mut criterion); diff --git a/library/compiler-builtins/builtins-test/benches/float_extend.rs b/library/compiler-builtins/builtins-test/benches/float_extend.rs index fc44e80c9e14..939dc60f95f4 100644 --- a/library/compiler-builtins/builtins-test/benches/float_extend.rs +++ b/library/compiler-builtins/builtins-test/benches/float_extend.rs @@ -110,9 +110,7 @@ float_bench! { pub fn float_extend() { let mut criterion = Criterion::default().configure_from_args(); - // FIXME(#655): `f16` tests disabled until we can bootstrap symbols #[cfg(f16_enabled)] - #[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))] { extend_f16_f32(&mut criterion); extend_f16_f64(&mut criterion); diff --git a/library/compiler-builtins/builtins-test/benches/float_trunc.rs b/library/compiler-builtins/builtins-test/benches/float_trunc.rs index 43310c7cfc82..9373f945bb2b 100644 --- a/library/compiler-builtins/builtins-test/benches/float_trunc.rs +++ b/library/compiler-builtins/builtins-test/benches/float_trunc.rs @@ -121,9 +121,7 @@ float_bench! { pub fn float_trunc() { let mut criterion = Criterion::default().configure_from_args(); - // FIXME(#655): `f16` tests disabled until we can bootstrap symbols #[cfg(f16_enabled)] - #[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))] { trunc_f32_f16(&mut criterion); trunc_f64_f16(&mut criterion); @@ -133,11 +131,8 @@ pub fn float_trunc() { #[cfg(f128_enabled)] { - // FIXME(#655): `f16` tests disabled until we can bootstrap symbols #[cfg(f16_enabled)] - #[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))] trunc_f128_f16(&mut criterion); - trunc_f128_f32(&mut criterion); trunc_f128_f64(&mut criterion); } diff --git a/library/compiler-builtins/builtins-test/src/bench.rs b/library/compiler-builtins/builtins-test/src/bench.rs index 0987185670ee..8a513ad67a4b 100644 --- a/library/compiler-builtins/builtins-test/src/bench.rs +++ b/library/compiler-builtins/builtins-test/src/bench.rs @@ -23,11 +23,6 @@ pub fn skip_sys_checks(test_name: &str) -> bool { "mul_f64", ]; - // FIXME(f16_f128): error on LE ppc64. There are more tests that are cfg-ed out completely - // in their benchmark modules due to runtime panics. - // - const PPC64LE_SKIPPED: &[&str] = &["extend_f32_f128"]; - // FIXME(f16_f128): system symbols have incorrect results // const X86_NO_SSE_SKIPPED: &[&str] = &[ @@ -57,12 +52,6 @@ pub fn skip_sys_checks(test_name: &str) -> bool { return true; } - if cfg!(all(target_arch = "powerpc64", target_endian = "little")) - && PPC64LE_SKIPPED.contains(&test_name) - { - return true; - } - if cfg!(all(target_arch = "x86", not(target_feature = "sse"))) && X86_NO_SSE_SKIPPED.contains(&test_name) { diff --git a/library/compiler-builtins/builtins-test/tests/conv.rs b/library/compiler-builtins/builtins-test/tests/conv.rs index 7d729364faef..9b04295d2efe 100644 --- a/library/compiler-builtins/builtins-test/tests/conv.rs +++ b/library/compiler-builtins/builtins-test/tests/conv.rs @@ -59,32 +59,28 @@ mod i_to_f { || ((error_minus == error || error_plus == error) && ((f0.to_bits() & 1) != 0)) { - if !cfg!(any( - target_arch = "powerpc", - target_arch = "powerpc64" - )) { - panic!( - "incorrect rounding by {}({}): {}, ({}, {}, {}), errors ({}, {}, {})", - stringify!($fn), - x, - f1.to_bits(), - y_minus_ulp, - y, - y_plus_ulp, - error_minus, - error, - error_plus, - ); - } + panic!( + "incorrect rounding by {}({}): {}, ({}, {}, {}), errors ({}, {}, {})", + stringify!($fn), + x, + f1.to_bits(), + y_minus_ulp, + y, + y_plus_ulp, + error_minus, + error, + error_plus, + ); } } - // Test against native conversion. We disable testing on all `x86` because of - // rounding bugs with `i686`. `powerpc` also has the same rounding bug. + // Test against native conversion. + // FIXME(x86,ppc): the platform version has rounding bugs on i686 and + // PowerPC64le (for PPC this only shows up in Docker, not the native runner). + // https://github.com/rust-lang/compiler-builtins/pull/384#issuecomment-740413334 if !Float::eq_repr(f0, f1) && !cfg!(any( target_arch = "x86", - target_arch = "powerpc", - target_arch = "powerpc64" + all(target_arch = "powerpc64", target_endian = "little") )) { panic!( "{}({}): std: {:?}, builtins: {:?}", diff --git a/library/compiler-builtins/crates/musl-math-sys/src/lib.rs b/library/compiler-builtins/crates/musl-math-sys/src/lib.rs index 6a4bf4859d93..9cab8deefdef 100644 --- a/library/compiler-builtins/crates/musl-math-sys/src/lib.rs +++ b/library/compiler-builtins/crates/musl-math-sys/src/lib.rs @@ -40,8 +40,6 @@ macro_rules! functions { ) => { // Run a simple check to ensure we can link and call the function without crashing. #[test] - // FIXME(#309): LE PPC crashes calling some musl functions - #[cfg_attr(all(target_arch = "powerpc64", target_endian = "little"), ignore)] fn $name() { $rty>::check(super::$name); } diff --git a/library/compiler-builtins/libm/src/math/j1f.rs b/library/compiler-builtins/libm/src/math/j1f.rs index a47472401ee2..da5413ac2f5b 100644 --- a/library/compiler-builtins/libm/src/math/j1f.rs +++ b/library/compiler-builtins/libm/src/math/j1f.rs @@ -361,8 +361,6 @@ fn qonef(x: f32) -> f32 { return (0.375 + r / s) / x; } -// PowerPC tests are failing on LLVM 13: https://github.com/rust-lang/rust/issues/88520 -#[cfg(not(target_arch = "powerpc64"))] #[cfg(test)] mod tests { use super::{j1f, y1f}; @@ -371,6 +369,7 @@ mod tests { // 0x401F3E49 assert_eq!(j1f(2.4881766_f32), 0.49999475_f32); } + #[test] fn test_y1f_2002() { //allow slightly different result on x87 From be947d4d2ba7acc99010c5e41f5bb5e517bcfee1 Mon Sep 17 00:00:00 2001 From: Aurelia Molzer <5550310+197g@users.noreply.github.com> Date: Thu, 24 Jul 2025 14:41:07 +0200 Subject: [PATCH 0115/1134] Add non-temporal note for maskmoveu_si128 Like any other non-temporal instructions this has additional safety requirements due to the mismatch with the Rust memory model. It is vital to know when using this instruction. --- library/stdarch/crates/core_arch/src/x86/sse2.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/library/stdarch/crates/core_arch/src/x86/sse2.rs b/library/stdarch/crates/core_arch/src/x86/sse2.rs index 3dabcde18ce9..1eaa89663b2c 100644 --- a/library/stdarch/crates/core_arch/src/x86/sse2.rs +++ b/library/stdarch/crates/core_arch/src/x86/sse2.rs @@ -1272,7 +1272,7 @@ pub unsafe fn _mm_loadu_si128(mem_addr: *const __m128i) -> __m128i { } /// Conditionally store 8-bit integer elements from `a` into memory using -/// `mask`. +/// `mask` flagged as non-temporal (unlikely to be used again soon). /// /// Elements are not stored when the highest bit is not set in the /// corresponding element. @@ -1281,6 +1281,15 @@ pub unsafe fn _mm_loadu_si128(mem_addr: *const __m128i) -> __m128i { /// to be aligned on any particular boundary. /// /// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_maskmoveu_si128) +/// +/// # Safety of non-temporal stores +/// +/// After using this intrinsic, but before any other access to the memory that this intrinsic +/// mutates, a call to [`_mm_sfence`] must be performed by the thread that used the intrinsic. In +/// particular, functions that call this intrinsic should generally call `_mm_sfence` before they +/// return. +/// +/// See [`_mm_sfence`] for details. #[inline] #[target_feature(enable = "sse2")] #[cfg_attr(test, assert_instr(maskmovdqu))] From a383fb0c738967ea8c6af200d8f4a37c751427c1 Mon Sep 17 00:00:00 2001 From: WANG Rui Date: Thu, 9 Jan 2025 20:35:49 +0800 Subject: [PATCH 0116/1134] asm: Stabilize loongarch32 --- compiler/rustc_ast_lowering/src/asm.rs | 1 + .../asm-experimental-arch.md | 5 -- tests/assembly-llvm/asm/loongarch-type.rs | 51 +++++++++------ .../bad-reg.loongarch32_ilp32d.stderr | 38 ++++++++++++ .../bad-reg.loongarch32_ilp32s.stderr | 62 +++++++++++++++++++ .../bad-reg.loongarch64_lp64d.stderr | 12 ++-- .../bad-reg.loongarch64_lp64s.stderr | 20 +++--- tests/ui/asm/loongarch/bad-reg.rs | 15 +++-- 8 files changed, 158 insertions(+), 46 deletions(-) create mode 100644 tests/ui/asm/loongarch/bad-reg.loongarch32_ilp32d.stderr create mode 100644 tests/ui/asm/loongarch/bad-reg.loongarch32_ilp32s.stderr diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index af279e07acc6..d44faad017ee 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -48,6 +48,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { | asm::InlineAsmArch::Arm64EC | asm::InlineAsmArch::RiscV32 | asm::InlineAsmArch::RiscV64 + | asm::InlineAsmArch::LoongArch32 | asm::InlineAsmArch::LoongArch64 | asm::InlineAsmArch::S390x ); diff --git a/src/doc/unstable-book/src/language-features/asm-experimental-arch.md b/src/doc/unstable-book/src/language-features/asm-experimental-arch.md index 121f94934359..d9566c9f55c5 100644 --- a/src/doc/unstable-book/src/language-features/asm-experimental-arch.md +++ b/src/doc/unstable-book/src/language-features/asm-experimental-arch.md @@ -19,7 +19,6 @@ This feature tracks `asm!` and `global_asm!` support for the following architect - M68k - CSKY - SPARC -- LoongArch32 ## Register classes @@ -54,8 +53,6 @@ This feature tracks `asm!` and `global_asm!` support for the following architect | CSKY | `freg` | `f[0-31]` | `f` | | SPARC | `reg` | `r[2-29]` | `r` | | SPARC | `yreg` | `y` | Only clobbers | -| LoongArch32 | `reg` | `$r1`, `$r[4-20]`, `$r[23,30]` | `r` | -| LoongArch32 | `freg` | `$f[0-31]` | `f` | > **Notes**: > - NVPTX doesn't have a fixed register set, so named registers are not supported. @@ -94,8 +91,6 @@ This feature tracks `asm!` and `global_asm!` support for the following architect | CSKY | `freg` | None | `f32`, | | SPARC | `reg` | None | `i8`, `i16`, `i32`, `i64` (SPARC64 only) | | SPARC | `yreg` | N/A | Only clobbers | -| LoongArch32 | `reg` | None | `i8`, `i16`, `i32`, `f32` | -| LoongArch32 | `freg` | None | `f32`, `f64` | ## Register aliases diff --git a/tests/assembly-llvm/asm/loongarch-type.rs b/tests/assembly-llvm/asm/loongarch-type.rs index c782be19f1d2..95d811a6bd0a 100644 --- a/tests/assembly-llvm/asm/loongarch-type.rs +++ b/tests/assembly-llvm/asm/loongarch-type.rs @@ -1,8 +1,15 @@ //@ add-core-stubs +//@ revisions: loongarch32 loongarch64 + //@ assembly-output: emit-asm -//@ compile-flags: --target loongarch64-unknown-linux-gnu + +//@[loongarch32] compile-flags: --target loongarch32-unknown-none +//@[loongarch32] needs-llvm-components: loongarch + +//@[loongarch64] compile-flags: --target loongarch64-unknown-none +//@[loongarch64] needs-llvm-components: loongarch + //@ compile-flags: -Zmerge-functions=disabled -//@ needs-llvm-components: loongarch #![feature(no_core, f16)] #![crate_type = "rlib"] @@ -22,7 +29,7 @@ extern "C" { // CHECK-LABEL: sym_fn: // CHECK: #APP // CHECK: pcalau12i $t0, %got_pc_hi20(extern_func) -// CHECK: ld.d $t0, $t0, %got_pc_lo12(extern_func) +// CHECK: ld.{{[wd]}} $t0, $t0, %got_pc_lo12(extern_func) // CHECK: #NO_APP #[no_mangle] pub unsafe fn sym_fn() { @@ -32,7 +39,7 @@ pub unsafe fn sym_fn() { // CHECK-LABEL: sym_static: // CHECK: #APP // CHECK: pcalau12i $t0, %got_pc_hi20(extern_static) -// CHECK: ld.d $t0, $t0, %got_pc_lo12(extern_static) +// CHECK: ld.{{[wd]}} $t0, $t0, %got_pc_lo12(extern_static) // CHECK: #NO_APP #[no_mangle] pub unsafe fn sym_static() { @@ -87,16 +94,18 @@ check!(reg_i32, i32, reg, "move"); // CHECK: #NO_APP check!(reg_f32, f32, reg, "move"); -// CHECK-LABEL: reg_i64: -// CHECK: #APP -// CHECK: move ${{[a-z0-9]+}}, ${{[a-z0-9]+}} -// CHECK: #NO_APP +// loongarch64-LABEL: reg_i64: +// loongarch64: #APP +// loongarch64: move ${{[a-z0-9]+}}, ${{[a-z0-9]+}} +// loongarch64: #NO_APP +#[cfg(loongarch64)] check!(reg_i64, i64, reg, "move"); -// CHECK-LABEL: reg_f64: -// CHECK: #APP -// CHECK: move ${{[a-z0-9]+}}, ${{[a-z0-9]+}} -// CHECK: #NO_APP +// loongarch64-LABEL: reg_f64: +// loongarch64: #APP +// loongarch64: move ${{[a-z0-9]+}}, ${{[a-z0-9]+}} +// loongarch64: #NO_APP +#[cfg(loongarch64)] check!(reg_f64, f64, reg, "move"); // CHECK-LABEL: reg_ptr: @@ -153,16 +162,18 @@ check_reg!(r4_i32, i32, "$r4", "move"); // CHECK: #NO_APP check_reg!(r4_f32, f32, "$r4", "move"); -// CHECK-LABEL: r4_i64: -// CHECK: #APP -// CHECK: move $a0, $a0 -// CHECK: #NO_APP +// loongarch64-LABEL: r4_i64: +// loongarch64: #APP +// loongarch64: move $a0, $a0 +// loongarch64: #NO_APP +#[cfg(loongarch64)] check_reg!(r4_i64, i64, "$r4", "move"); -// CHECK-LABEL: r4_f64: -// CHECK: #APP -// CHECK: move $a0, $a0 -// CHECK: #NO_APP +// loongarch64-LABEL: r4_f64: +// loongarch64: #APP +// loongarch64: move $a0, $a0 +// loongarch64: #NO_APP +#[cfg(loongarch64)] check_reg!(r4_f64, f64, "$r4", "move"); // CHECK-LABEL: r4_ptr: diff --git a/tests/ui/asm/loongarch/bad-reg.loongarch32_ilp32d.stderr b/tests/ui/asm/loongarch/bad-reg.loongarch32_ilp32d.stderr new file mode 100644 index 000000000000..8742d4bd82cd --- /dev/null +++ b/tests/ui/asm/loongarch/bad-reg.loongarch32_ilp32d.stderr @@ -0,0 +1,38 @@ +error: invalid register `$r0`: constant zero cannot be used as an operand for inline asm + --> $DIR/bad-reg.rs:27:18 + | +LL | asm!("", out("$r0") _); + | ^^^^^^^^^^^^ + +error: invalid register `$tp`: reserved for TLS + --> $DIR/bad-reg.rs:29:18 + | +LL | asm!("", out("$tp") _); + | ^^^^^^^^^^^^ + +error: invalid register `$sp`: the stack pointer cannot be used as an operand for inline asm + --> $DIR/bad-reg.rs:31:18 + | +LL | asm!("", out("$sp") _); + | ^^^^^^^^^^^^ + +error: invalid register `$r21`: reserved by the ABI + --> $DIR/bad-reg.rs:33:18 + | +LL | asm!("", out("$r21") _); + | ^^^^^^^^^^^^^ + +error: invalid register `$fp`: the frame pointer cannot be used as an operand for inline asm + --> $DIR/bad-reg.rs:35:18 + | +LL | asm!("", out("$fp") _); + | ^^^^^^^^^^^^ + +error: invalid register `$r31`: $r31 is used internally by LLVM and cannot be used as an operand for inline asm + --> $DIR/bad-reg.rs:37:18 + | +LL | asm!("", out("$r31") _); + | ^^^^^^^^^^^^^ + +error: aborting due to 6 previous errors + diff --git a/tests/ui/asm/loongarch/bad-reg.loongarch32_ilp32s.stderr b/tests/ui/asm/loongarch/bad-reg.loongarch32_ilp32s.stderr new file mode 100644 index 000000000000..e6cb6e40c701 --- /dev/null +++ b/tests/ui/asm/loongarch/bad-reg.loongarch32_ilp32s.stderr @@ -0,0 +1,62 @@ +error: invalid register `$r0`: constant zero cannot be used as an operand for inline asm + --> $DIR/bad-reg.rs:27:18 + | +LL | asm!("", out("$r0") _); + | ^^^^^^^^^^^^ + +error: invalid register `$tp`: reserved for TLS + --> $DIR/bad-reg.rs:29:18 + | +LL | asm!("", out("$tp") _); + | ^^^^^^^^^^^^ + +error: invalid register `$sp`: the stack pointer cannot be used as an operand for inline asm + --> $DIR/bad-reg.rs:31:18 + | +LL | asm!("", out("$sp") _); + | ^^^^^^^^^^^^ + +error: invalid register `$r21`: reserved by the ABI + --> $DIR/bad-reg.rs:33:18 + | +LL | asm!("", out("$r21") _); + | ^^^^^^^^^^^^^ + +error: invalid register `$fp`: the frame pointer cannot be used as an operand for inline asm + --> $DIR/bad-reg.rs:35:18 + | +LL | asm!("", out("$fp") _); + | ^^^^^^^^^^^^ + +error: invalid register `$r31`: $r31 is used internally by LLVM and cannot be used as an operand for inline asm + --> $DIR/bad-reg.rs:37:18 + | +LL | asm!("", out("$r31") _); + | ^^^^^^^^^^^^^ + +error: register class `freg` requires at least one of the following target features: d, f + --> $DIR/bad-reg.rs:41:26 + | +LL | asm!("/* {} */", in(freg) f); + | ^^^^^^^^^^ + +error: register class `freg` requires at least one of the following target features: d, f + --> $DIR/bad-reg.rs:43:26 + | +LL | asm!("/* {} */", out(freg) _); + | ^^^^^^^^^^^ + +error: register class `freg` requires at least one of the following target features: d, f + --> $DIR/bad-reg.rs:45:26 + | +LL | asm!("/* {} */", in(freg) d); + | ^^^^^^^^^^ + +error: register class `freg` requires at least one of the following target features: d, f + --> $DIR/bad-reg.rs:47:26 + | +LL | asm!("/* {} */", out(freg) d); + | ^^^^^^^^^^^ + +error: aborting due to 10 previous errors + diff --git a/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64d.stderr b/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64d.stderr index 0e5441196501..8742d4bd82cd 100644 --- a/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64d.stderr +++ b/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64d.stderr @@ -1,35 +1,35 @@ error: invalid register `$r0`: constant zero cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:22:18 + --> $DIR/bad-reg.rs:27:18 | LL | asm!("", out("$r0") _); | ^^^^^^^^^^^^ error: invalid register `$tp`: reserved for TLS - --> $DIR/bad-reg.rs:24:18 + --> $DIR/bad-reg.rs:29:18 | LL | asm!("", out("$tp") _); | ^^^^^^^^^^^^ error: invalid register `$sp`: the stack pointer cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:26:18 + --> $DIR/bad-reg.rs:31:18 | LL | asm!("", out("$sp") _); | ^^^^^^^^^^^^ error: invalid register `$r21`: reserved by the ABI - --> $DIR/bad-reg.rs:28:18 + --> $DIR/bad-reg.rs:33:18 | LL | asm!("", out("$r21") _); | ^^^^^^^^^^^^^ error: invalid register `$fp`: the frame pointer cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:30:18 + --> $DIR/bad-reg.rs:35:18 | LL | asm!("", out("$fp") _); | ^^^^^^^^^^^^ error: invalid register `$r31`: $r31 is used internally by LLVM and cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:32:18 + --> $DIR/bad-reg.rs:37:18 | LL | asm!("", out("$r31") _); | ^^^^^^^^^^^^^ diff --git a/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64s.stderr b/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64s.stderr index 6d0410dc6a13..e6cb6e40c701 100644 --- a/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64s.stderr +++ b/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64s.stderr @@ -1,59 +1,59 @@ error: invalid register `$r0`: constant zero cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:22:18 + --> $DIR/bad-reg.rs:27:18 | LL | asm!("", out("$r0") _); | ^^^^^^^^^^^^ error: invalid register `$tp`: reserved for TLS - --> $DIR/bad-reg.rs:24:18 + --> $DIR/bad-reg.rs:29:18 | LL | asm!("", out("$tp") _); | ^^^^^^^^^^^^ error: invalid register `$sp`: the stack pointer cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:26:18 + --> $DIR/bad-reg.rs:31:18 | LL | asm!("", out("$sp") _); | ^^^^^^^^^^^^ error: invalid register `$r21`: reserved by the ABI - --> $DIR/bad-reg.rs:28:18 + --> $DIR/bad-reg.rs:33:18 | LL | asm!("", out("$r21") _); | ^^^^^^^^^^^^^ error: invalid register `$fp`: the frame pointer cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:30:18 + --> $DIR/bad-reg.rs:35:18 | LL | asm!("", out("$fp") _); | ^^^^^^^^^^^^ error: invalid register `$r31`: $r31 is used internally by LLVM and cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:32:18 + --> $DIR/bad-reg.rs:37:18 | LL | asm!("", out("$r31") _); | ^^^^^^^^^^^^^ error: register class `freg` requires at least one of the following target features: d, f - --> $DIR/bad-reg.rs:36:26 + --> $DIR/bad-reg.rs:41:26 | LL | asm!("/* {} */", in(freg) f); | ^^^^^^^^^^ error: register class `freg` requires at least one of the following target features: d, f - --> $DIR/bad-reg.rs:38:26 + --> $DIR/bad-reg.rs:43:26 | LL | asm!("/* {} */", out(freg) _); | ^^^^^^^^^^^ error: register class `freg` requires at least one of the following target features: d, f - --> $DIR/bad-reg.rs:40:26 + --> $DIR/bad-reg.rs:45:26 | LL | asm!("/* {} */", in(freg) d); | ^^^^^^^^^^ error: register class `freg` requires at least one of the following target features: d, f - --> $DIR/bad-reg.rs:42:26 + --> $DIR/bad-reg.rs:47:26 | LL | asm!("/* {} */", out(freg) d); | ^^^^^^^^^^^ diff --git a/tests/ui/asm/loongarch/bad-reg.rs b/tests/ui/asm/loongarch/bad-reg.rs index 685b460bc922..0d3eba07f14d 100644 --- a/tests/ui/asm/loongarch/bad-reg.rs +++ b/tests/ui/asm/loongarch/bad-reg.rs @@ -1,6 +1,11 @@ //@ add-core-stubs //@ needs-asm-support -//@ revisions: loongarch64_lp64d loongarch64_lp64s +//@ revisions: loongarch32_ilp32d loongarch32_ilp32s loongarch64_lp64d loongarch64_lp64s +//@ min-llvm-version: 20 +//@[loongarch32_ilp32d] compile-flags: --target loongarch32-unknown-none +//@[loongarch32_ilp32d] needs-llvm-components: loongarch +//@[loongarch32_ilp32s] compile-flags: --target loongarch32-unknown-none-softfloat +//@[loongarch32_ilp32s] needs-llvm-components: loongarch //@[loongarch64_lp64d] compile-flags: --target loongarch64-unknown-linux-gnu //@[loongarch64_lp64d] needs-llvm-components: loongarch //@[loongarch64_lp64s] compile-flags: --target loongarch64-unknown-none-softfloat @@ -34,12 +39,12 @@ fn f() { asm!("", out("$f0") _); // ok asm!("/* {} */", in(freg) f); - //[loongarch64_lp64s]~^ ERROR register class `freg` requires at least one of the following target features: d, f + //[loongarch32_ilp32s,loongarch64_lp64s]~^ ERROR register class `freg` requires at least one of the following target features: d, f asm!("/* {} */", out(freg) _); - //[loongarch64_lp64s]~^ ERROR register class `freg` requires at least one of the following target features: d, f + //[loongarch32_ilp32s,loongarch64_lp64s]~^ ERROR register class `freg` requires at least one of the following target features: d, f asm!("/* {} */", in(freg) d); - //[loongarch64_lp64s]~^ ERROR register class `freg` requires at least one of the following target features: d, f + //[loongarch32_ilp32s,loongarch64_lp64s]~^ ERROR register class `freg` requires at least one of the following target features: d, f asm!("/* {} */", out(freg) d); - //[loongarch64_lp64s]~^ ERROR register class `freg` requires at least one of the following target features: d, f + //[loongarch32_ilp32s,loongarch64_lp64s]~^ ERROR register class `freg` requires at least one of the following target features: d, f } } From 5ae2d42a8c80807c7e3ae7e8aff165fb4d8e046f Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 7 Nov 2024 15:33:45 -0600 Subject: [PATCH 0117/1134] get rid of some false negatives in rustdoc::broken_intra_doc_links rustdoc will not try to do intra-doc linking if the "path" of a link looks too much like a "real url". however, only inline links ([text](url)) can actually contain a url, other types of links (reference links, shortcut links) contain a *reference* which is later resolved to an actual url. the "path" in this case cannot be a url, and therefore it should not be skipped due to looking like a url. Co-authored-by: Michael Howell --- .../passes/collect_intra_doc_links.rs | 13 ++++++-- tests/rustdoc-ui/bad-intra-doc.rs | 13 ++++++++ tests/rustdoc-ui/bad-intra-doc.stderr | 31 +++++++++++++++++++ 3 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 tests/rustdoc-ui/bad-intra-doc.rs create mode 100644 tests/rustdoc-ui/bad-intra-doc.stderr diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 5a9aa2a94c8b..97f8a2be10b2 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -941,13 +941,20 @@ fn preprocess_link( ori_link: &MarkdownLink, dox: &str, ) -> Option> { + // certain link kinds cannot have their path be urls, + // so they should not be ignored, no matter how much they look like urls. + // e.g. [https://example.com/] is not a link to example.com. + let can_be_url = ori_link.kind != LinkType::ShortcutUnknown + && ori_link.kind != LinkType::CollapsedUnknown + && ori_link.kind != LinkType::ReferenceUnknown; + // [] is mostly likely not supposed to be a link if ori_link.link.is_empty() { return None; } // Bail early for real links. - if ori_link.link.contains('/') { + if can_be_url && ori_link.link.contains('/') { return None; } @@ -972,7 +979,7 @@ fn preprocess_link( Ok(None) => (None, link, link), Err((err_msg, relative_range)) => { // Only report error if we would not have ignored this link. See issue #83859. - if !should_ignore_link_with_disambiguators(link) { + if !(can_be_url && should_ignore_link_with_disambiguators(link)) { let disambiguator_range = match range_between_backticks(&ori_link.range, dox) { MarkdownLinkRange::Destination(no_backticks_range) => { MarkdownLinkRange::Destination( @@ -989,7 +996,7 @@ fn preprocess_link( } }; - if should_ignore_link(path_str) { + if can_be_url && should_ignore_link(path_str) { return None; } diff --git a/tests/rustdoc-ui/bad-intra-doc.rs b/tests/rustdoc-ui/bad-intra-doc.rs new file mode 100644 index 000000000000..7bc55756e670 --- /dev/null +++ b/tests/rustdoc-ui/bad-intra-doc.rs @@ -0,0 +1,13 @@ +#![no_std] +#![deny(rustdoc::broken_intra_doc_links)] + +// regression test for https://github.com/rust-lang/rust/issues/54191 + +/// this is not a link to [`example.com`] //~ERROR unresolved link +/// +/// this link [`has spaces in it`]. +/// +/// attempted link to method: [`Foo.bar()`] //~ERROR unresolved link +/// +/// classic broken intra-doc link: [`Bar`] //~ERROR unresolved link +pub struct Foo; diff --git a/tests/rustdoc-ui/bad-intra-doc.stderr b/tests/rustdoc-ui/bad-intra-doc.stderr new file mode 100644 index 000000000000..9533792b35b6 --- /dev/null +++ b/tests/rustdoc-ui/bad-intra-doc.stderr @@ -0,0 +1,31 @@ +error: unresolved link to `example.com` + --> $DIR/bad-intra-doc.rs:6:29 + | +LL | /// this is not a link to [`example.com`] + | ^^^^^^^^^^^ no item named `example.com` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` +note: the lint level is defined here + --> $DIR/bad-intra-doc.rs:2:9 + | +LL | #![deny(rustdoc::broken_intra_doc_links)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: unresolved link to `Foo.bar` + --> $DIR/bad-intra-doc.rs:10:33 + | +LL | /// attempted link to method: [`Foo.bar()`] + | ^^^^^^^^^ no item named `Foo.bar` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + +error: unresolved link to `Bar` + --> $DIR/bad-intra-doc.rs:12:38 + | +LL | /// classic broken intra-doc link: [`Bar`] + | ^^^ no item named `Bar` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + +error: aborting due to 3 previous errors + From 87d7d80cec060690c9055fa93cb29dfe5eb79ce9 Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 8 Nov 2024 13:59:56 -0600 Subject: [PATCH 0118/1134] adjust more unit tests to reflect more aggressive intra-doc linting --- .../disambiguator-endswith-named-suffix.rs | 30 ++--- ...disambiguator-endswith-named-suffix.stderr | 122 +++++++++++++++++- tests/rustdoc-ui/intra-doc/weird-syntax.rs | 2 +- .../rustdoc-ui/intra-doc/weird-syntax.stderr | 24 ++++ .../lints/redundant_explicit_links-utf8.rs | 14 +- .../redundant_explicit_links-utf8.stderr | 59 +++++++++ 6 files changed, 230 insertions(+), 21 deletions(-) create mode 100644 tests/rustdoc-ui/lints/redundant_explicit_links-utf8.stderr diff --git a/tests/rustdoc-ui/disambiguator-endswith-named-suffix.rs b/tests/rustdoc-ui/disambiguator-endswith-named-suffix.rs index 1174e16dd53f..cb277d529ce7 100644 --- a/tests/rustdoc-ui/disambiguator-endswith-named-suffix.rs +++ b/tests/rustdoc-ui/disambiguator-endswith-named-suffix.rs @@ -2,67 +2,67 @@ //@ normalize-stderr: "nightly|beta|1\.[0-9][0-9]\.[0-9]" -> "$$CHANNEL" //! [struct@m!()] //~ WARN: unmatched disambiguator `struct` and suffix `!()` -//! [struct@m!{}] +//! [struct@m!{}] //~ WARN: unmatched disambiguator `struct` and suffix `!{}` //! [struct@m![]] //! [struct@f()] //~ WARN: unmatched disambiguator `struct` and suffix `()` //! [struct@m!] //~ WARN: unmatched disambiguator `struct` and suffix `!` //! //! [enum@m!()] //~ WARN: unmatched disambiguator `enum` and suffix `!()` -//! [enum@m!{}] +//! [enum@m!{}] //~ WARN: unmatched disambiguator `enum` and suffix `!{}` //! [enum@m![]] //! [enum@f()] //~ WARN: unmatched disambiguator `enum` and suffix `()` //! [enum@m!] //~ WARN: unmatched disambiguator `enum` and suffix `!` //! //! [trait@m!()] //~ WARN: unmatched disambiguator `trait` and suffix `!()` -//! [trait@m!{}] +//! [trait@m!{}] //~ WARN: unmatched disambiguator `trait` and suffix `!{}` //! [trait@m![]] //! [trait@f()] //~ WARN: unmatched disambiguator `trait` and suffix `()` //! [trait@m!] //~ WARN: unmatched disambiguator `trait` and suffix `!` //! //! [module@m!()] //~ WARN: unmatched disambiguator `module` and suffix `!()` -//! [module@m!{}] +//! [module@m!{}] //~ WARN: unmatched disambiguator `module` and suffix `!{}` //! [module@m![]] //! [module@f()] //~ WARN: unmatched disambiguator `module` and suffix `()` //! [module@m!] //~ WARN: unmatched disambiguator `module` and suffix `!` //! //! [mod@m!()] //~ WARN: unmatched disambiguator `mod` and suffix `!()` -//! [mod@m!{}] +//! [mod@m!{}] //~ WARN: unmatched disambiguator `mod` and suffix `!{}` //! [mod@m![]] //! [mod@f()] //~ WARN: unmatched disambiguator `mod` and suffix `()` //! [mod@m!] //~ WARN: unmatched disambiguator `mod` and suffix `!` //! //! [const@m!()] //~ WARN: unmatched disambiguator `const` and suffix `!()` -//! [const@m!{}] +//! [const@m!{}] //~ WARN: unmatched disambiguator `const` and suffix `!{}` //! [const@m![]] //! [const@f()] //~ WARN: incompatible link kind for `f` //! [const@m!] //~ WARN: unmatched disambiguator `const` and suffix `!` //! //! [constant@m!()] //~ WARN: unmatched disambiguator `constant` and suffix `!()` -//! [constant@m!{}] +//! [constant@m!{}] //~ WARN: unmatched disambiguator `constant` and suffix `!{}` //! [constant@m![]] //! [constant@f()] //~ WARN: incompatible link kind for `f` //! [constant@m!] //~ WARN: unmatched disambiguator `constant` and suffix `!` //! //! [static@m!()] //~ WARN: unmatched disambiguator `static` and suffix `!()` -//! [static@m!{}] +//! [static@m!{}] //~ WARN: unmatched disambiguator `static` and suffix `!{}` //! [static@m![]] //! [static@f()] //~ WARN: incompatible link kind for `f` //! [static@m!] //~ WARN: unmatched disambiguator `static` and suffix `!` //! //! [function@m!()] //~ WARN: unmatched disambiguator `function` and suffix `!()` -//! [function@m!{}] +//! [function@m!{}] //~ WARN: unmatched disambiguator `function` and suffix `!{}` //! [function@m![]] //! [function@f()] //! [function@m!] //~ WARN: unmatched disambiguator `function` and suffix `!` //! //! [fn@m!()] //~ WARN: unmatched disambiguator `fn` and suffix `!()` -//! [fn@m!{}] +//! [fn@m!{}] //~ WARN: unmatched disambiguator `fn` and suffix `!{}` //! [fn@m![]] //! [fn@f()] //! [fn@m!] //~ WARN: unmatched disambiguator `fn` and suffix `!` //! //! [method@m!()] //~ WARN: unmatched disambiguator `method` and suffix `!()` -//! [method@m!{}] +//! [method@m!{}] //~ WARN: unmatched disambiguator `method` and suffix `!{}` //! [method@m![]] //! [method@f()] //! [method@m!] //~ WARN: unmatched disambiguator `method` and suffix `!` @@ -74,13 +74,13 @@ //! [derive@m!] //~ WARN: incompatible link kind for `m` //! //! [type@m!()] //~ WARN: unmatched disambiguator `type` and suffix `!()` -//! [type@m!{}] +//! [type@m!{}] //~ WARN: unmatched disambiguator `type` and suffix `!{}` //! [type@m![]] //! [type@f()] //~ WARN: unmatched disambiguator `type` and suffix `()` //! [type@m!] //~ WARN: unmatched disambiguator `type` and suffix `!` //! //! [value@m!()] //~ WARN: unmatched disambiguator `value` and suffix `!()` -//! [value@m!{}] +//! [value@m!{}] //~ WARN: unmatched disambiguator `value` and suffix `!{}` //! [value@m![]] //! [value@f()] //! [value@m!] //~ WARN: unmatched disambiguator `value` and suffix `!` @@ -92,13 +92,13 @@ //! [macro@m!] //! //! [prim@m!()] //~ WARN: unmatched disambiguator `prim` and suffix `!()` -//! [prim@m!{}] +//! [prim@m!{}] //~ WARN: unmatched disambiguator `prim` and suffix `!{}` //! [prim@m![]] //! [prim@f()] //~ WARN: unmatched disambiguator `prim` and suffix `()` //! [prim@m!] //~ WARN: unmatched disambiguator `prim` and suffix `!` //! //! [primitive@m!()] //~ WARN: unmatched disambiguator `primitive` and suffix `!()` -//! [primitive@m!{}] +//! [primitive@m!{}] //~ WARN: unmatched disambiguator `primitive` and suffix `!{}` //! [primitive@m![]] //! [primitive@f()] //~ WARN: unmatched disambiguator `primitive` and suffix `()` //! [primitive@m!] //~ WARN: unmatched disambiguator `primitive` and suffix `!` diff --git a/tests/rustdoc-ui/disambiguator-endswith-named-suffix.stderr b/tests/rustdoc-ui/disambiguator-endswith-named-suffix.stderr index f4e40a488738..184033859688 100644 --- a/tests/rustdoc-ui/disambiguator-endswith-named-suffix.stderr +++ b/tests/rustdoc-ui/disambiguator-endswith-named-suffix.stderr @@ -7,6 +7,14 @@ LL | //! [struct@m!()] = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default +warning: unmatched disambiguator `struct` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:5:6 + | +LL | //! [struct@m!{}] + | ^^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `struct` and suffix `()` --> $DIR/disambiguator-endswith-named-suffix.rs:7:6 | @@ -31,6 +39,14 @@ LL | //! [enum@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `enum` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:11:6 + | +LL | //! [enum@m!{}] + | ^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `enum` and suffix `()` --> $DIR/disambiguator-endswith-named-suffix.rs:13:6 | @@ -55,6 +71,14 @@ LL | //! [trait@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `trait` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:17:6 + | +LL | //! [trait@m!{}] + | ^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `trait` and suffix `()` --> $DIR/disambiguator-endswith-named-suffix.rs:19:6 | @@ -79,6 +103,14 @@ LL | //! [module@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `module` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:23:6 + | +LL | //! [module@m!{}] + | ^^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `module` and suffix `()` --> $DIR/disambiguator-endswith-named-suffix.rs:25:6 | @@ -103,6 +135,14 @@ LL | //! [mod@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `mod` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:29:6 + | +LL | //! [mod@m!{}] + | ^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `mod` and suffix `()` --> $DIR/disambiguator-endswith-named-suffix.rs:31:6 | @@ -127,6 +167,14 @@ LL | //! [const@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `const` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:35:6 + | +LL | //! [const@m!{}] + | ^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: incompatible link kind for `f` --> $DIR/disambiguator-endswith-named-suffix.rs:37:6 | @@ -155,6 +203,14 @@ LL | //! [constant@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `constant` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:41:6 + | +LL | //! [constant@m!{}] + | ^^^^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: incompatible link kind for `f` --> $DIR/disambiguator-endswith-named-suffix.rs:43:6 | @@ -183,6 +239,14 @@ LL | //! [static@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `static` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:47:6 + | +LL | //! [static@m!{}] + | ^^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: incompatible link kind for `f` --> $DIR/disambiguator-endswith-named-suffix.rs:49:6 | @@ -211,6 +275,14 @@ LL | //! [function@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `function` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:53:6 + | +LL | //! [function@m!{}] + | ^^^^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `function` and suffix `!` --> $DIR/disambiguator-endswith-named-suffix.rs:56:6 | @@ -227,6 +299,14 @@ LL | //! [fn@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `fn` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:59:6 + | +LL | //! [fn@m!{}] + | ^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `fn` and suffix `!` --> $DIR/disambiguator-endswith-named-suffix.rs:62:6 | @@ -243,6 +323,14 @@ LL | //! [method@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `method` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:65:6 + | +LL | //! [method@m!{}] + | ^^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `method` and suffix `!` --> $DIR/disambiguator-endswith-named-suffix.rs:68:6 | @@ -303,6 +391,14 @@ LL | //! [type@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `type` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:77:6 + | +LL | //! [type@m!{}] + | ^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `type` and suffix `()` --> $DIR/disambiguator-endswith-named-suffix.rs:79:6 | @@ -327,6 +423,14 @@ LL | //! [value@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `value` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:83:6 + | +LL | //! [value@m!{}] + | ^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `value` and suffix `!` --> $DIR/disambiguator-endswith-named-suffix.rs:86:6 | @@ -351,6 +455,14 @@ LL | //! [prim@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `prim` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:95:6 + | +LL | //! [prim@m!{}] + | ^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `prim` and suffix `()` --> $DIR/disambiguator-endswith-named-suffix.rs:97:6 | @@ -375,6 +487,14 @@ LL | //! [primitive@m!()] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators +warning: unmatched disambiguator `primitive` and suffix `!{}` + --> $DIR/disambiguator-endswith-named-suffix.rs:101:6 + | +LL | //! [primitive@m!{}] + | ^^^^^^^^^ + | + = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators + warning: unmatched disambiguator `primitive` and suffix `()` --> $DIR/disambiguator-endswith-named-suffix.rs:103:6 | @@ -391,5 +511,5 @@ LL | //! [primitive@m!] | = note: see https://doc.rust-lang.org/$CHANNEL/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators -warning: 46 warnings emitted +warning: 61 warnings emitted diff --git a/tests/rustdoc-ui/intra-doc/weird-syntax.rs b/tests/rustdoc-ui/intra-doc/weird-syntax.rs index d2a922b2b624..1c5977b1bc33 100644 --- a/tests/rustdoc-ui/intra-doc/weird-syntax.rs +++ b/tests/rustdoc-ui/intra-doc/weird-syntax.rs @@ -65,7 +65,7 @@ pub struct XLinkToCloneWithStartSpace; /// [x][struct@Clone ] //~ERROR link pub struct XLinkToCloneWithEndSpace; -/// [x][Clone\(\)] not URL-shaped enough +/// [x][Clone\(\)] //~ERROR link pub struct XLinkToCloneWithEscapedParens; /// [x][`Clone`] not URL-shaped enough diff --git a/tests/rustdoc-ui/intra-doc/weird-syntax.stderr b/tests/rustdoc-ui/intra-doc/weird-syntax.stderr index ad813f0f9b62..3a567e409eff 100644 --- a/tests/rustdoc-ui/intra-doc/weird-syntax.stderr +++ b/tests/rustdoc-ui/intra-doc/weird-syntax.stderr @@ -123,6 +123,14 @@ LL - /// [x][struct@Clone ] LL + /// [x][trait@Clone ] | +error: unresolved link to `Clone\(\)` + --> $DIR/weird-syntax.rs:68:9 + | +LL | /// [x][Clone\(\)] + | ^^^^^^^^^ no item named `Clone\(\)` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + error: unresolved link to `Clone` --> $DIR/weird-syntax.rs:74:9 | @@ -299,5 +307,21 @@ LL | /// - [`SDL_PROP_WINDOW_CREATE_COCOA_WINDOW_POINTER`]: the | = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` +error: unresolved link to `Clone` + --> $DIR/weird-syntax.rs:132:9 + | +LL | /// The [cln][] link here will produce a plain text suggestion + | ^^^^^ this link resolves to the trait `Clone`, which is not a function + | + = help: to link to the trait, prefix with `trait@`: trait@Clone + +error: incompatible link kind for `Clone` + --> $DIR/weird-syntax.rs:137:9 + | +LL | /// The [cln][] link here will produce a plain text suggestion + | ^^^^^ this link resolved to a trait, which is not a struct + | + = help: to link to the trait, prefix with `trait@`: trait@Clone + error: aborting due to 27 previous errors diff --git a/tests/rustdoc-ui/lints/redundant_explicit_links-utf8.rs b/tests/rustdoc-ui/lints/redundant_explicit_links-utf8.rs index 4f4590d45fc8..81cd6c73d1c1 100644 --- a/tests/rustdoc-ui/lints/redundant_explicit_links-utf8.rs +++ b/tests/rustdoc-ui/lints/redundant_explicit_links-utf8.rs @@ -1,18 +1,24 @@ //@ check-pass -/// [`…foo`] [`…bar`] [`Err`] +/// [`…foo`] //~ WARN: unresolved link +/// [`…bar`] //~ WARN: unresolved link +/// [`Err`] pub struct Broken {} -/// [`…`] [`…`] [`Err`] +/// [`…`] //~ WARN: unresolved link +/// [`…`] //~ WARN: unresolved link +/// [`Err`] pub struct Broken2 {} -/// [`…`][…] [`…`][…] [`Err`] +/// [`…`][…] //~ WARN: unresolved link +/// [`…`][…] //~ WARN: unresolved link +/// [`Err`] pub struct Broken3 {} /// […………………………][Broken3] pub struct Broken4 {} -/// [Broken3][…………………………] +/// [Broken3][…………………………] //~ WARN: unresolved link pub struct Broken5 {} pub struct Err; diff --git a/tests/rustdoc-ui/lints/redundant_explicit_links-utf8.stderr b/tests/rustdoc-ui/lints/redundant_explicit_links-utf8.stderr new file mode 100644 index 000000000000..0a5ff68b9081 --- /dev/null +++ b/tests/rustdoc-ui/lints/redundant_explicit_links-utf8.stderr @@ -0,0 +1,59 @@ +warning: unresolved link to `…foo` + --> $DIR/redundant_explicit_links-utf8.rs:3:7 + | +LL | /// [`…foo`] + | ^^^^ no item named `…foo` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default + +warning: unresolved link to `…bar` + --> $DIR/redundant_explicit_links-utf8.rs:4:7 + | +LL | /// [`…bar`] + | ^^^^ no item named `…bar` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + +warning: unresolved link to `…` + --> $DIR/redundant_explicit_links-utf8.rs:8:7 + | +LL | /// [`…`] + | ^ no item named `…` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + +warning: unresolved link to `…` + --> $DIR/redundant_explicit_links-utf8.rs:9:7 + | +LL | /// [`…`] + | ^ no item named `…` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + +warning: unresolved link to `…` + --> $DIR/redundant_explicit_links-utf8.rs:13:11 + | +LL | /// [`…`][…] + | ^ no item named `…` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + +warning: unresolved link to `…` + --> $DIR/redundant_explicit_links-utf8.rs:14:11 + | +LL | /// [`…`][…] + | ^ no item named `…` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + +warning: unresolved link to `…………………………` + --> $DIR/redundant_explicit_links-utf8.rs:21:15 + | +LL | /// [Broken3][…………………………] + | ^^^^^^^^^^ no item named `…………………………` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + +warning: 7 warnings emitted + From a7da4b829d328f129e342917908b70c5f4b98abc Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 18 Apr 2025 15:32:56 -0500 Subject: [PATCH 0119/1134] rustdoc::broken_intra_doc_links: no backticks = use old behavior this is in an effort to reduce the amount of code churn caused by this lint triggering on text that was never meant to be a link. a more principled hierustic for ignoring lints is not possible without extensive changes, due to the lint emitting code being so far away from the link collecting code, and the fact that only the link collecting code has access to details about how the link appears in the unnormalized markdown. --- src/librustdoc/passes/collect_intra_doc_links.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 97f8a2be10b2..08f0d4015fca 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -996,7 +996,9 @@ fn preprocess_link( } }; - if can_be_url && should_ignore_link(path_str) { + // If there's no backticks, be lenient revert to old behavior. + // This is to prevent churn by linting on stuff that isn't meant to be a link. + if (can_be_url || !ori_link.link.contains('`')) && should_ignore_link(path_str) { return None; } From 041348110e2e526a80efd5adfc2909c716cbb37f Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 18 Apr 2025 17:15:11 -0500 Subject: [PATCH 0120/1134] rustdoc: update tests to match new lint behavior --- tests/rustdoc-ui/bad-intra-doc.rs | 2 ++ tests/rustdoc-ui/intra-doc/weird-syntax.rs | 2 +- .../rustdoc-ui/intra-doc/weird-syntax.stderr | 24 ------------------- 3 files changed, 3 insertions(+), 25 deletions(-) diff --git a/tests/rustdoc-ui/bad-intra-doc.rs b/tests/rustdoc-ui/bad-intra-doc.rs index 7bc55756e670..c24a848d8985 100644 --- a/tests/rustdoc-ui/bad-intra-doc.rs +++ b/tests/rustdoc-ui/bad-intra-doc.rs @@ -10,4 +10,6 @@ /// attempted link to method: [`Foo.bar()`] //~ERROR unresolved link /// /// classic broken intra-doc link: [`Bar`] //~ERROR unresolved link +/// +/// no backticks, so we let this one slide: [Foo.bar()] pub struct Foo; diff --git a/tests/rustdoc-ui/intra-doc/weird-syntax.rs b/tests/rustdoc-ui/intra-doc/weird-syntax.rs index 1c5977b1bc33..9f18f67fc44a 100644 --- a/tests/rustdoc-ui/intra-doc/weird-syntax.rs +++ b/tests/rustdoc-ui/intra-doc/weird-syntax.rs @@ -65,7 +65,7 @@ pub struct XLinkToCloneWithStartSpace; /// [x][struct@Clone ] //~ERROR link pub struct XLinkToCloneWithEndSpace; -/// [x][Clone\(\)] //~ERROR link +/// [x][Clone\(\)] pub struct XLinkToCloneWithEscapedParens; /// [x][`Clone`] not URL-shaped enough diff --git a/tests/rustdoc-ui/intra-doc/weird-syntax.stderr b/tests/rustdoc-ui/intra-doc/weird-syntax.stderr index 3a567e409eff..ad813f0f9b62 100644 --- a/tests/rustdoc-ui/intra-doc/weird-syntax.stderr +++ b/tests/rustdoc-ui/intra-doc/weird-syntax.stderr @@ -123,14 +123,6 @@ LL - /// [x][struct@Clone ] LL + /// [x][trait@Clone ] | -error: unresolved link to `Clone\(\)` - --> $DIR/weird-syntax.rs:68:9 - | -LL | /// [x][Clone\(\)] - | ^^^^^^^^^ no item named `Clone\(\)` in scope - | - = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` - error: unresolved link to `Clone` --> $DIR/weird-syntax.rs:74:9 | @@ -307,21 +299,5 @@ LL | /// - [`SDL_PROP_WINDOW_CREATE_COCOA_WINDOW_POINTER`]: the | = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` -error: unresolved link to `Clone` - --> $DIR/weird-syntax.rs:132:9 - | -LL | /// The [cln][] link here will produce a plain text suggestion - | ^^^^^ this link resolves to the trait `Clone`, which is not a function - | - = help: to link to the trait, prefix with `trait@`: trait@Clone - -error: incompatible link kind for `Clone` - --> $DIR/weird-syntax.rs:137:9 - | -LL | /// The [cln][] link here will produce a plain text suggestion - | ^^^^^ this link resolved to a trait, which is not a struct - | - = help: to link to the trait, prefix with `trait@`: trait@Clone - error: aborting due to 27 previous errors From 6a7d4882a207890c75ca09ce19810d90ac9cfde6 Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 18 Apr 2025 20:23:05 -0500 Subject: [PATCH 0121/1134] rustdoc::broken_intra_doc_links: only be lenient with shortcut links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit collapsed links and reference links have a pretty particular syntax, it seems unlikely they would show up on accident. Co-authored-by: León Orell Valerian Liehr --- .../passes/collect_intra_doc_links.rs | 27 +++++++++++++++---- tests/rustdoc-ui/intra-doc/weird-syntax.rs | 2 +- .../rustdoc-ui/intra-doc/weird-syntax.stderr | 10 ++++++- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 08f0d4015fca..c9fa3a4837f2 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -944,9 +944,10 @@ fn preprocess_link( // certain link kinds cannot have their path be urls, // so they should not be ignored, no matter how much they look like urls. // e.g. [https://example.com/] is not a link to example.com. - let can_be_url = ori_link.kind != LinkType::ShortcutUnknown - && ori_link.kind != LinkType::CollapsedUnknown - && ori_link.kind != LinkType::ReferenceUnknown; + let can_be_url = !matches!( + ori_link.kind, + LinkType::ShortcutUnknown | LinkType::CollapsedUnknown | LinkType::ReferenceUnknown + ); // [] is mostly likely not supposed to be a link if ori_link.link.is_empty() { @@ -996,9 +997,25 @@ fn preprocess_link( } }; - // If there's no backticks, be lenient revert to old behavior. + // If there's no backticks, be lenient and revert to the old behavior. // This is to prevent churn by linting on stuff that isn't meant to be a link. - if (can_be_url || !ori_link.link.contains('`')) && should_ignore_link(path_str) { + // only shortcut links have simple enough syntax that they + // are likely to be written accidentally, collapsed and reference links + // need 4 metachars, and reference links will not usually use + // backticks in the reference name. + // therefore, only shortcut syntax gets the lenient behavior. + // + // here's a truth table for how link kinds that cannot be urls are handled: + // + // |-------------------------------------------------------| + // | | is shortcut link | not shortcut link | + // |--------------|--------------------|-------------------| + // | has backtick | never ignore | never ignore | + // | no backtick | ignore if url-like | never ignore | + // |-------------------------------------------------------| + let ignore_urllike = + can_be_url || (ori_link.kind == LinkType::ShortcutUnknown && !ori_link.link.contains('`')); + if ignore_urllike && should_ignore_link(path_str) { return None; } diff --git a/tests/rustdoc-ui/intra-doc/weird-syntax.rs b/tests/rustdoc-ui/intra-doc/weird-syntax.rs index 9f18f67fc44a..1c5977b1bc33 100644 --- a/tests/rustdoc-ui/intra-doc/weird-syntax.rs +++ b/tests/rustdoc-ui/intra-doc/weird-syntax.rs @@ -65,7 +65,7 @@ pub struct XLinkToCloneWithStartSpace; /// [x][struct@Clone ] //~ERROR link pub struct XLinkToCloneWithEndSpace; -/// [x][Clone\(\)] +/// [x][Clone\(\)] //~ERROR link pub struct XLinkToCloneWithEscapedParens; /// [x][`Clone`] not URL-shaped enough diff --git a/tests/rustdoc-ui/intra-doc/weird-syntax.stderr b/tests/rustdoc-ui/intra-doc/weird-syntax.stderr index ad813f0f9b62..7f2fc1fe6256 100644 --- a/tests/rustdoc-ui/intra-doc/weird-syntax.stderr +++ b/tests/rustdoc-ui/intra-doc/weird-syntax.stderr @@ -123,6 +123,14 @@ LL - /// [x][struct@Clone ] LL + /// [x][trait@Clone ] | +error: unresolved link to `Clone\(\)` + --> $DIR/weird-syntax.rs:68:9 + | +LL | /// [x][Clone\(\)] + | ^^^^^^^^^ no item named `Clone\(\)` in scope + | + = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` + error: unresolved link to `Clone` --> $DIR/weird-syntax.rs:74:9 | @@ -299,5 +307,5 @@ LL | /// - [`SDL_PROP_WINDOW_CREATE_COCOA_WINDOW_POINTER`]: the | = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]` -error: aborting due to 27 previous errors +error: aborting due to 28 previous errors From bd85df192d07660511b711cd7d4cae5b5a85577a Mon Sep 17 00:00:00 2001 From: binarycat Date: Sat, 19 Apr 2025 10:51:40 -0500 Subject: [PATCH 0122/1134] move bad-intra-doc test into intra-doc dir --- tests/rustdoc-ui/{ => intra-doc}/bad-intra-doc.rs | 0 tests/rustdoc-ui/{ => intra-doc}/bad-intra-doc.stderr | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename tests/rustdoc-ui/{ => intra-doc}/bad-intra-doc.rs (100%) rename tests/rustdoc-ui/{ => intra-doc}/bad-intra-doc.stderr (100%) diff --git a/tests/rustdoc-ui/bad-intra-doc.rs b/tests/rustdoc-ui/intra-doc/bad-intra-doc.rs similarity index 100% rename from tests/rustdoc-ui/bad-intra-doc.rs rename to tests/rustdoc-ui/intra-doc/bad-intra-doc.rs diff --git a/tests/rustdoc-ui/bad-intra-doc.stderr b/tests/rustdoc-ui/intra-doc/bad-intra-doc.stderr similarity index 100% rename from tests/rustdoc-ui/bad-intra-doc.stderr rename to tests/rustdoc-ui/intra-doc/bad-intra-doc.stderr From 6017fe65968cbe044e1f9a0638376e788829736b Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 24 Jul 2025 12:27:00 -0500 Subject: [PATCH 0123/1134] expand the issue template for new lints When I first tried contributing to clippy, I encountered the problem that a lot of lint suggestions overlapped with existing lints, so I would spend a bunch of time implementing something only to figure out it wasn't actually needed. The "comparison with existing lints" field should hopefully reduce this somewhat, while not incresing the burden of requesting a new lint too much due to not being mandatory. --- .github/ISSUE_TEMPLATE/new_lint.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/.github/ISSUE_TEMPLATE/new_lint.yml b/.github/ISSUE_TEMPLATE/new_lint.yml index 464740640e0c..49a616d94f81 100644 --- a/.github/ISSUE_TEMPLATE/new_lint.yml +++ b/.github/ISSUE_TEMPLATE/new_lint.yml @@ -48,3 +48,24 @@ body: ``` validations: required: true + - type: textarea + id: comparison + attributes: + label: Comparision with existing lints + description: | + What makes this lint different from any existing lints that are similar, and how are those differences useful? + + You can [use this playground template to see what existing lints are triggered by the bad code][playground] + (make sure to use "Tools > Clippy" and not "Build"). + You can also look through the list of [rustc's allowed-by-default lints][allowed-by-default], + as those won't show up in the playground above. + + [allowed-by-default](https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html) + + [playground]: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&code=%23%21%5Bwarn%28clippy%3A%3Apedantic%29%5D%0A%23%21%5Bwarn%28clippy%3A%3Anursery%29%5D%0A%23%21%5Bwarn%28clippy%3A%3Arestriction%29%5D%0A%23%21%5Bwarn%28clippy%3A%3Aall%29%5D%0A%23%21%5Ballow%28clippy%3A%3Ablanket_clippy_restriction_lints%2C+reason+%3D+%22testing+to+see+if+any+restriction+lints+match+given+code%22%29%5D%0A%0A%2F%2F%21+Template+that+can+be+used+to+see+what+clippy+lints+a+given+piece+of+code+would+trigger + placeholder: Unlike `clippy::...`, the proposed lint would... + - type: textarea + id: context + attributes: + label: Additional Context + description: Any additional context that you believe may be relevant. From a73d7e3ab9cc29cb427c1463d1a02b89dd7728b6 Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 24 Jul 2025 12:37:46 -0500 Subject: [PATCH 0124/1134] fix up issues with internal compiler docs revealed by stricter lint --- compiler/rustc_mir_transform/src/elaborate_drop.rs | 4 ++++ compiler/rustc_thread_pool/src/sleep/mod.rs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_mir_transform/src/elaborate_drop.rs b/compiler/rustc_mir_transform/src/elaborate_drop.rs index de96b1f255a6..de60772b17ea 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drop.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drop.rs @@ -611,6 +611,7 @@ where /// /// For example, with 3 fields, the drop ladder is /// + /// ```text /// .d0: /// ELAB(drop location.0 [target=.d1, unwind=.c1]) /// .d1: @@ -621,8 +622,10 @@ where /// ELAB(drop location.1 [target=.c2]) /// .c2: /// ELAB(drop location.2 [target=`self.unwind`]) + /// ``` /// /// For possible-async drops in coroutines we also need dropline ladder + /// ```text /// .d0 (mainline): /// ELAB(drop location.0 [target=.d1, unwind=.c1, drop=.e1]) /// .d1 (mainline): @@ -637,6 +640,7 @@ where /// ELAB(drop location.1 [target=.e2, unwind=.c2]) /// .e2 (dropline): /// ELAB(drop location.2 [target=`self.drop`, unwind=`self.unwind`]) + /// ``` /// /// NOTE: this does not clear the master drop flag, so you need /// to point succ/unwind on a `drop_ladder_bottom`. diff --git a/compiler/rustc_thread_pool/src/sleep/mod.rs b/compiler/rustc_thread_pool/src/sleep/mod.rs index 31bf7184b42d..aa6666092147 100644 --- a/compiler/rustc_thread_pool/src/sleep/mod.rs +++ b/compiler/rustc_thread_pool/src/sleep/mod.rs @@ -44,7 +44,7 @@ impl SleepData { /// jobs are published, and it either blocks threads or wakes them in response to these /// events. See the [`README.md`] in this module for more details. /// -/// [`README.md`] README.md +/// [`README.md`]: README.md pub(super) struct Sleep { /// One "sleep state" per worker. Used to track if a worker is sleeping and to have /// them block. From b16879304602614a89dd7bd0bd67f0e05204f279 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 07:28:38 -0500 Subject: [PATCH 0125/1134] Enable tests that were skipped on aarch64 The LLVM issue was resolved a while ago, these should no longer be a problem. --- library/compiler-builtins/builtins-test/src/bench.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/library/compiler-builtins/builtins-test/src/bench.rs b/library/compiler-builtins/builtins-test/src/bench.rs index 8a513ad67a4b..9ba6742949df 100644 --- a/library/compiler-builtins/builtins-test/src/bench.rs +++ b/library/compiler-builtins/builtins-test/src/bench.rs @@ -29,11 +29,6 @@ pub fn skip_sys_checks(test_name: &str) -> bool { "add_f128", "sub_f128", "mul_f128", "div_f128", "powi_f32", "powi_f64", ]; - // FIXME(f16_f128): Wide multiply carry bug in `compiler-rt`, re-enable when nightly no longer - // uses `compiler-rt` version. - // - const AARCH64_SKIPPED: &[&str] = &["mul_f128", "div_f128"]; - // FIXME(llvm): system symbols have incorrect results on Windows // const WINDOWS_SKIPPED: &[&str] = &[ @@ -58,10 +53,6 @@ pub fn skip_sys_checks(test_name: &str) -> bool { return true; } - if cfg!(target_arch = "aarch64") && AARCH64_SKIPPED.contains(&test_name) { - return true; - } - if cfg!(target_family = "windows") && WINDOWS_SKIPPED.contains(&test_name) { return true; } From 0b6c1d38618d1f694541621d97712afaabde01f4 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 07:31:49 -0500 Subject: [PATCH 0126/1134] Enable skipped `f32` and `f64` multiplication tests The fix has since made it to nightly, so the skips here can be removed. --- library/compiler-builtins/builtins-test/src/bench.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/library/compiler-builtins/builtins-test/src/bench.rs b/library/compiler-builtins/builtins-test/src/bench.rs index 9ba6742949df..bca9f8418b58 100644 --- a/library/compiler-builtins/builtins-test/src/bench.rs +++ b/library/compiler-builtins/builtins-test/src/bench.rs @@ -17,10 +17,6 @@ pub fn skip_sys_checks(test_name: &str) -> bool { "extend_f16_f32", "trunc_f32_f16", "trunc_f64_f16", - // FIXME(#616): re-enable once fix is in nightly - // - "mul_f32", - "mul_f64", ]; // FIXME(f16_f128): system symbols have incorrect results From a19b46d745cc2ef4d6fbff32119a3a9331bda8e1 Mon Sep 17 00:00:00 2001 From: lolbinarycat Date: Thu, 24 Jul 2025 14:10:12 -0500 Subject: [PATCH 0127/1134] fix markdown Co-authored-by: Philipp Krones --- .github/ISSUE_TEMPLATE/new_lint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/new_lint.yml b/.github/ISSUE_TEMPLATE/new_lint.yml index 49a616d94f81..4c9e18b2b913 100644 --- a/.github/ISSUE_TEMPLATE/new_lint.yml +++ b/.github/ISSUE_TEMPLATE/new_lint.yml @@ -60,7 +60,7 @@ body: You can also look through the list of [rustc's allowed-by-default lints][allowed-by-default], as those won't show up in the playground above. - [allowed-by-default](https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html) + [allowed-by-default]: https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html [playground]: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&code=%23%21%5Bwarn%28clippy%3A%3Apedantic%29%5D%0A%23%21%5Bwarn%28clippy%3A%3Anursery%29%5D%0A%23%21%5Bwarn%28clippy%3A%3Arestriction%29%5D%0A%23%21%5Bwarn%28clippy%3A%3Aall%29%5D%0A%23%21%5Ballow%28clippy%3A%3Ablanket_clippy_restriction_lints%2C+reason+%3D+%22testing+to+see+if+any+restriction+lints+match+given+code%22%29%5D%0A%0A%2F%2F%21+Template+that+can+be+used+to+see+what+clippy+lints+a+given+piece+of+code+would+trigger placeholder: Unlike `clippy::...`, the proposed lint would... From 9dad77f337745e1aeed4337dcc25549be053eeb5 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 18:55:27 +0000 Subject: [PATCH 0128/1134] Use `x86_no_sse` configuration in more places Emit `x86_no_sse` in the compiler-builtins (and builtins-test) build script, and use it to simplify `all(target_arch = "x86", not(target_fefature = "sse))` configuration. --- library/compiler-builtins/builtins-test/src/bench.rs | 4 +--- library/compiler-builtins/builtins-test/tests/addsub.rs | 4 ++-- library/compiler-builtins/builtins-test/tests/div_rem.rs | 2 +- library/compiler-builtins/builtins-test/tests/float_pow.rs | 3 ++- library/compiler-builtins/builtins-test/tests/mul.rs | 4 ++-- library/compiler-builtins/compiler-builtins/build.rs | 7 ------- library/compiler-builtins/compiler-builtins/configure.rs | 7 +++++++ library/compiler-builtins/libm/src/math/rem_pio2.rs | 2 +- 8 files changed, 16 insertions(+), 17 deletions(-) diff --git a/library/compiler-builtins/builtins-test/src/bench.rs b/library/compiler-builtins/builtins-test/src/bench.rs index bca9f8418b58..4bdcf482cd61 100644 --- a/library/compiler-builtins/builtins-test/src/bench.rs +++ b/library/compiler-builtins/builtins-test/src/bench.rs @@ -43,9 +43,7 @@ pub fn skip_sys_checks(test_name: &str) -> bool { return true; } - if cfg!(all(target_arch = "x86", not(target_feature = "sse"))) - && X86_NO_SSE_SKIPPED.contains(&test_name) - { + if cfg!(x86_no_sse) && X86_NO_SSE_SKIPPED.contains(&test_name) { return true; } diff --git a/library/compiler-builtins/builtins-test/tests/addsub.rs b/library/compiler-builtins/builtins-test/tests/addsub.rs index 865b9e472ab4..abe7dde645e0 100644 --- a/library/compiler-builtins/builtins-test/tests/addsub.rs +++ b/library/compiler-builtins/builtins-test/tests/addsub.rs @@ -111,7 +111,7 @@ macro_rules! float_sum { } } -#[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] +#[cfg(not(x86_no_sse))] mod float_addsub { use super::*; @@ -122,7 +122,7 @@ mod float_addsub { } #[cfg(f128_enabled)] -#[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] +#[cfg(not(x86_no_sse))] #[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))] mod float_addsub_f128 { use super::*; diff --git a/library/compiler-builtins/builtins-test/tests/div_rem.rs b/library/compiler-builtins/builtins-test/tests/div_rem.rs index e8327f9b4b86..caee4166c995 100644 --- a/library/compiler-builtins/builtins-test/tests/div_rem.rs +++ b/library/compiler-builtins/builtins-test/tests/div_rem.rs @@ -138,7 +138,7 @@ macro_rules! float { }; } -#[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] +#[cfg(not(x86_no_sse))] mod float_div { use super::*; diff --git a/library/compiler-builtins/builtins-test/tests/float_pow.rs b/library/compiler-builtins/builtins-test/tests/float_pow.rs index 0e8ae88e83ef..a17dff27c105 100644 --- a/library/compiler-builtins/builtins-test/tests/float_pow.rs +++ b/library/compiler-builtins/builtins-test/tests/float_pow.rs @@ -1,7 +1,7 @@ #![allow(unused_macros)] #![cfg_attr(f128_enabled, feature(f128))] -#![cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] +#[cfg_attr(x86_no_sse, allow(unused))] use builtins_test::*; // This is approximate because of issues related to @@ -52,6 +52,7 @@ macro_rules! pow { }; } +#[cfg(not(x86_no_sse))] // FIXME(i586): failure for powidf2 pow! { f32, 1e-4, __powisf2, all(); f64, 1e-12, __powidf2, all(); diff --git a/library/compiler-builtins/builtins-test/tests/mul.rs b/library/compiler-builtins/builtins-test/tests/mul.rs index 58bc9ab4ac95..3072b45dca03 100644 --- a/library/compiler-builtins/builtins-test/tests/mul.rs +++ b/library/compiler-builtins/builtins-test/tests/mul.rs @@ -113,7 +113,7 @@ macro_rules! float_mul { }; } -#[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] +#[cfg(not(x86_no_sse))] mod float_mul { use super::*; @@ -126,7 +126,7 @@ mod float_mul { } #[cfg(f128_enabled)] -#[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] +#[cfg(not(x86_no_sse))] #[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))] mod float_mul_f128 { use super::*; diff --git a/library/compiler-builtins/compiler-builtins/build.rs b/library/compiler-builtins/compiler-builtins/build.rs index 8f51c12b535d..43b978606e5f 100644 --- a/library/compiler-builtins/compiler-builtins/build.rs +++ b/library/compiler-builtins/compiler-builtins/build.rs @@ -106,13 +106,6 @@ fn configure_libm(target: &Target) { println!("cargo:rustc-cfg=optimizations_enabled"); } - // Config shorthands - println!("cargo:rustc-check-cfg=cfg(x86_no_sse)"); - if target.arch == "x86" && !target.features.iter().any(|f| f == "sse") { - // Shorthand to detect i586 targets - println!("cargo:rustc-cfg=x86_no_sse"); - } - println!( "cargo:rustc-env=CFG_CARGO_FEATURES={:?}", target.cargo_features diff --git a/library/compiler-builtins/compiler-builtins/configure.rs b/library/compiler-builtins/compiler-builtins/configure.rs index 9721ddf090c6..caedc034da68 100644 --- a/library/compiler-builtins/compiler-builtins/configure.rs +++ b/library/compiler-builtins/compiler-builtins/configure.rs @@ -100,6 +100,13 @@ pub fn configure_aliases(target: &Target) { println!("cargo:rustc-cfg=thumb_1") } + // Config shorthands + println!("cargo:rustc-check-cfg=cfg(x86_no_sse)"); + if target.arch == "x86" && !target.features.iter().any(|f| f == "sse") { + // Shorthand to detect i586 targets + println!("cargo:rustc-cfg=x86_no_sse"); + } + /* Not all backends support `f16` and `f128` to the same level on all architectures, so we * need to disable things if the compiler may crash. See configuration at: * * https://github.com/rust-lang/rust/blob/c65dccabacdfd6c8a7f7439eba13422fdd89b91e/compiler/rustc_codegen_llvm/src/llvm_util.rs#L367-L432 diff --git a/library/compiler-builtins/libm/src/math/rem_pio2.rs b/library/compiler-builtins/libm/src/math/rem_pio2.rs index d677fd9dcb30..648dca170ec4 100644 --- a/library/compiler-builtins/libm/src/math/rem_pio2.rs +++ b/library/compiler-builtins/libm/src/math/rem_pio2.rs @@ -195,7 +195,7 @@ mod tests { #[test] // FIXME(correctness): inaccurate results on i586 - #[cfg_attr(all(target_arch = "x86", not(target_feature = "sse")), ignore)] + #[cfg_attr(x86_no_sse, ignore)] fn test_near_pi() { let arg = 3.141592025756836; let arg = force_eval!(arg); From 0aa92fdba699a3227d9d1f7ed8121785d7b3b502 Mon Sep 17 00:00:00 2001 From: Dan Johnson Date: Tue, 17 Jun 2025 17:21:44 -0700 Subject: [PATCH 0129/1134] fix ip_constant when call wrapped in extra parens --- clippy_lints/src/methods/ip_constant.rs | 25 ++++---- tests/ui/ip_constant.fixed | 14 +++++ tests/ui/ip_constant.rs | 14 +++++ tests/ui/ip_constant.stderr | 80 +++++++++++++++++++++---- 4 files changed, 109 insertions(+), 24 deletions(-) diff --git a/clippy_lints/src/methods/ip_constant.rs b/clippy_lints/src/methods/ip_constant.rs index 83803fba6a13..a2ac4e54334e 100644 --- a/clippy_lints/src/methods/ip_constant.rs +++ b/clippy_lints/src/methods/ip_constant.rs @@ -1,7 +1,7 @@ use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint_and_then; use rustc_errors::Applicability; -use rustc_hir::{Expr, ExprKind, QPath, Ty, TyKind}; +use rustc_hir::{Expr, ExprKind, QPath, TyKind}; use rustc_lint::LateContext; use rustc_span::sym; use smallvec::SmallVec; @@ -9,13 +9,8 @@ use smallvec::SmallVec; use super::IP_CONSTANT; pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, func: &Expr<'_>, args: &[Expr<'_>]) { - if let ExprKind::Path(QPath::TypeRelative( - Ty { - kind: TyKind::Path(QPath::Resolved(_, func_path)), - .. - }, - p, - )) = func.kind + if let ExprKind::Path(QPath::TypeRelative(ty, p)) = func.kind + && let TyKind::Path(QPath::Resolved(_, func_path)) = ty.kind && p.ident.name == sym::new && let Some(func_def_id) = func_path.res.opt_def_id() && matches!( @@ -40,13 +35,15 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, func: &Expr<'_>, args _ => return, }; + let mut sugg = vec![(expr.span.with_lo(p.ident.span.lo()), constant_name.to_owned())]; + let before_span = expr.span.shrink_to_lo().until(ty.span); + if !before_span.is_empty() { + // Remove everything before the type name + sugg.push((before_span, String::new())); + } + span_lint_and_then(cx, IP_CONSTANT, expr.span, "hand-coded well-known IP address", |diag| { - diag.span_suggestion_verbose( - expr.span.with_lo(p.ident.span.lo()), - "use", - constant_name, - Applicability::MachineApplicable, - ); + diag.multipart_suggestion_verbose("use", sugg, Applicability::MachineApplicable); }); } } diff --git a/tests/ui/ip_constant.fixed b/tests/ui/ip_constant.fixed index 2e3389c11938..c94796821394 100644 --- a/tests/ui/ip_constant.fixed +++ b/tests/ui/ip_constant.fixed @@ -48,6 +48,20 @@ fn literal_test3() { //~^ ip_constant } +fn wrapped_in_parens() { + let _ = std::net::Ipv4Addr::LOCALHOST; + //~^ ip_constant + let _ = std::net::Ipv4Addr::BROADCAST; + //~^ ip_constant + let _ = std::net::Ipv4Addr::UNSPECIFIED; + //~^ ip_constant + + let _ = std::net::Ipv6Addr::LOCALHOST; + //~^ ip_constant + let _ = std::net::Ipv6Addr::UNSPECIFIED; + //~^ ip_constant +} + const CONST_U8_0: u8 = 0; const CONST_U8_1: u8 = 1; const CONST_U8_127: u8 = 127; diff --git a/tests/ui/ip_constant.rs b/tests/ui/ip_constant.rs index 15e0b0551bab..69a5c3b4e923 100644 --- a/tests/ui/ip_constant.rs +++ b/tests/ui/ip_constant.rs @@ -48,6 +48,20 @@ fn literal_test3() { //~^ ip_constant } +fn wrapped_in_parens() { + let _ = (std::net::Ipv4Addr::new(127, 0, 0, 1)); + //~^ ip_constant + let _ = (std::net::Ipv4Addr::new(255, 255, 255, 255)); + //~^ ip_constant + let _ = (std::net::Ipv4Addr::new(0, 0, 0, 0)); + //~^ ip_constant + + let _ = (std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); + //~^ ip_constant + let _ = (std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)); + //~^ ip_constant +} + const CONST_U8_0: u8 = 0; const CONST_U8_1: u8 = 1; const CONST_U8_127: u8 = 127; diff --git a/tests/ui/ip_constant.stderr b/tests/ui/ip_constant.stderr index 3e984c6cb3bb..07d912b18a57 100644 --- a/tests/ui/ip_constant.stderr +++ b/tests/ui/ip_constant.stderr @@ -180,9 +180,69 @@ LL - let _ = std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0); LL + let _ = std::net::Ipv6Addr::UNSPECIFIED; | +error: hand-coded well-known IP address + --> tests/ui/ip_constant.rs:52:13 + | +LL | let _ = (std::net::Ipv4Addr::new(127, 0, 0, 1)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use + | +LL - let _ = (std::net::Ipv4Addr::new(127, 0, 0, 1)); +LL + let _ = std::net::Ipv4Addr::LOCALHOST; + | + +error: hand-coded well-known IP address + --> tests/ui/ip_constant.rs:54:13 + | +LL | let _ = (std::net::Ipv4Addr::new(255, 255, 255, 255)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use + | +LL - let _ = (std::net::Ipv4Addr::new(255, 255, 255, 255)); +LL + let _ = std::net::Ipv4Addr::BROADCAST; + | + +error: hand-coded well-known IP address + --> tests/ui/ip_constant.rs:56:13 + | +LL | let _ = (std::net::Ipv4Addr::new(0, 0, 0, 0)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use + | +LL - let _ = (std::net::Ipv4Addr::new(0, 0, 0, 0)); +LL + let _ = std::net::Ipv4Addr::UNSPECIFIED; + | + +error: hand-coded well-known IP address + --> tests/ui/ip_constant.rs:59:13 + | +LL | let _ = (std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use + | +LL - let _ = (std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); +LL + let _ = std::net::Ipv6Addr::LOCALHOST; + | + error: hand-coded well-known IP address --> tests/ui/ip_constant.rs:61:13 | +LL | let _ = (std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use + | +LL - let _ = (std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)); +LL + let _ = std::net::Ipv6Addr::UNSPECIFIED; + | + +error: hand-coded well-known IP address + --> tests/ui/ip_constant.rs:75:13 + | LL | let _ = Ipv4Addr::new(CONST_U8_127, CONST_U8_0, CONST_U8_0, CONST_U8_1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | @@ -193,7 +253,7 @@ LL + let _ = Ipv4Addr::LOCALHOST; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:63:13 + --> tests/ui/ip_constant.rs:77:13 | LL | let _ = Ipv4Addr::new(CONST_U8_255, CONST_U8_255, CONST_U8_255, CONST_U8_255); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -205,7 +265,7 @@ LL + let _ = Ipv4Addr::BROADCAST; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:65:13 + --> tests/ui/ip_constant.rs:79:13 | LL | let _ = Ipv4Addr::new(CONST_U8_0, CONST_U8_0, CONST_U8_0, CONST_U8_0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -217,7 +277,7 @@ LL + let _ = Ipv4Addr::UNSPECIFIED; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:69:13 + --> tests/ui/ip_constant.rs:83:13 | LL | let _ = Ipv6Addr::new( | _____________^ @@ -246,7 +306,7 @@ LL + let _ = Ipv6Addr::LOCALHOST; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:81:13 + --> tests/ui/ip_constant.rs:95:13 | LL | let _ = Ipv6Addr::new( | _____________^ @@ -275,7 +335,7 @@ LL + let _ = Ipv6Addr::UNSPECIFIED; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:96:13 + --> tests/ui/ip_constant.rs:110:13 | LL | let _ = Ipv4Addr::new(126 + 1, 0, 0, 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -287,7 +347,7 @@ LL + let _ = Ipv4Addr::LOCALHOST; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:98:13 + --> tests/ui/ip_constant.rs:112:13 | LL | let _ = Ipv4Addr::new(254 + CONST_U8_1, 255, { 255 - CONST_U8_0 }, CONST_U8_255); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -299,7 +359,7 @@ LL + let _ = Ipv4Addr::BROADCAST; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:100:13 + --> tests/ui/ip_constant.rs:114:13 | LL | let _ = Ipv4Addr::new(0, CONST_U8_255 - 255, 0, { 1 + 0 - 1 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -311,7 +371,7 @@ LL + let _ = Ipv4Addr::UNSPECIFIED; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:104:13 + --> tests/ui/ip_constant.rs:118:13 | LL | let _ = Ipv6Addr::new(0 + CONST_U16_0, 0, 0, 0, 0, 0, 0, 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -323,7 +383,7 @@ LL + let _ = Ipv6Addr::LOCALHOST; | error: hand-coded well-known IP address - --> tests/ui/ip_constant.rs:106:13 + --> tests/ui/ip_constant.rs:120:13 | LL | let _ = Ipv6Addr::new(0 + 0, 0, 0, 0, 0, { 2 - 1 - CONST_U16_1 }, 0, 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -334,5 +394,5 @@ LL - let _ = Ipv6Addr::new(0 + 0, 0, 0, 0, 0, { 2 - 1 - CONST_U16_1 }, 0, 1) LL + let _ = Ipv6Addr::LOCALHOST; | -error: aborting due to 25 previous errors +error: aborting due to 30 previous errors From da6618097f9dea0baf5950b588d38fefa0544a07 Mon Sep 17 00:00:00 2001 From: newt Date: Fri, 25 Jul 2025 00:34:01 +0100 Subject: [PATCH 0130/1134] Detect prefixed attributes as duplicated --- .../src/attrs/duplicated_attributes.rs | 44 ++++++++++-------- tests/ui/duplicated_attributes.rs | 2 +- tests/ui/duplicated_attributes.stderr | 23 ++++++++-- tests/ui/indexing_slicing_slice.rs | 1 - tests/ui/indexing_slicing_slice.stderr | 38 +++++++-------- tests/ui/needless_collect_indirect.rs | 3 +- tests/ui/needless_collect_indirect.stderr | 32 ++++++------- tests/ui/unnecessary_clippy_cfg.rs | 3 +- tests/ui/unnecessary_clippy_cfg.stderr | 46 ++----------------- 9 files changed, 89 insertions(+), 103 deletions(-) diff --git a/clippy_lints/src/attrs/duplicated_attributes.rs b/clippy_lints/src/attrs/duplicated_attributes.rs index c2406bcfb647..c956738edf0e 100644 --- a/clippy_lints/src/attrs/duplicated_attributes.rs +++ b/clippy_lints/src/attrs/duplicated_attributes.rs @@ -2,6 +2,7 @@ use super::DUPLICATED_ATTRIBUTES; use clippy_utils::diagnostics::span_lint_and_then; use itertools::Itertools; use rustc_ast::{Attribute, MetaItem}; +use rustc_ast_pretty::pprust::path_to_string; use rustc_data_structures::fx::FxHashMap; use rustc_lint::EarlyContext; use rustc_span::{Span, Symbol, sym}; @@ -35,31 +36,38 @@ fn check_duplicated_attr( if attr.span.from_expansion() { return; } - let Some(ident) = attr.ident() else { return }; - let name = ident.name; - if name == sym::doc || name == sym::cfg_attr_trace || name == sym::rustc_on_unimplemented || name == sym::reason { - // FIXME: Would be nice to handle `cfg_attr` as well. Only problem is to check that cfg - // conditions are the same. - // `#[rustc_on_unimplemented]` contains duplicated subattributes, that's expected. - return; - } - if let Some(direct_parent) = parent.last() - && *direct_parent == sym::cfg_trace - && [sym::all, sym::not, sym::any].contains(&name) - { - // FIXME: We don't correctly check `cfg`s for now, so if it's more complex than just a one - // level `cfg`, we leave. - return; + let attr_path = if let Some(ident) = attr.ident() { + ident.name + } else { + Symbol::intern(&path_to_string(&attr.path)) + }; + if let Some(ident) = attr.ident() { + let name = ident.name; + if name == sym::doc || name == sym::cfg_attr_trace || name == sym::rustc_on_unimplemented || name == sym::reason + { + // FIXME: Would be nice to handle `cfg_attr` as well. Only problem is to check that cfg + // conditions are the same. + // `#[rustc_on_unimplemented]` contains duplicated subattributes, that's expected. + return; + } + if let Some(direct_parent) = parent.last() + && *direct_parent == sym::cfg_trace + && [sym::all, sym::not, sym::any].contains(&name) + { + // FIXME: We don't correctly check `cfg`s for now, so if it's more complex than just a one + // level `cfg`, we leave. + return; + } } if let Some(value) = attr.value_str() { emit_if_duplicated( cx, attr, attr_paths, - format!("{}:{name}={value}", parent.iter().join(":")), + format!("{}:{attr_path}={value}", parent.iter().join(":")), ); } else if let Some(sub_attrs) = attr.meta_item_list() { - parent.push(name); + parent.push(attr_path); for sub_attr in sub_attrs { if let Some(meta) = sub_attr.meta_item() { check_duplicated_attr(cx, meta, attr_paths, parent); @@ -67,7 +75,7 @@ fn check_duplicated_attr( } parent.pop(); } else { - emit_if_duplicated(cx, attr, attr_paths, format!("{}:{name}", parent.iter().join(":"))); + emit_if_duplicated(cx, attr, attr_paths, format!("{}:{attr_path}", parent.iter().join(":"))); } } diff --git a/tests/ui/duplicated_attributes.rs b/tests/ui/duplicated_attributes.rs index 3ca91d6f1829..9a6714995059 100644 --- a/tests/ui/duplicated_attributes.rs +++ b/tests/ui/duplicated_attributes.rs @@ -1,6 +1,6 @@ //@aux-build:proc_macro_attr.rs +#![warn(clippy::duplicated_attributes, clippy::duplicated_attributes)] //~ ERROR: duplicated attribute #![feature(rustc_attrs)] -#![warn(clippy::duplicated_attributes)] #![cfg(any(unix, windows))] #![allow(dead_code)] #![allow(dead_code)] //~ ERROR: duplicated attribute diff --git a/tests/ui/duplicated_attributes.stderr b/tests/ui/duplicated_attributes.stderr index 0903617a8d1f..922939d60dd6 100644 --- a/tests/ui/duplicated_attributes.stderr +++ b/tests/ui/duplicated_attributes.stderr @@ -1,3 +1,22 @@ +error: duplicated attribute + --> tests/ui/duplicated_attributes.rs:2:40 + | +LL | #![warn(clippy::duplicated_attributes, clippy::duplicated_attributes)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: first defined here + --> tests/ui/duplicated_attributes.rs:2:9 + | +LL | #![warn(clippy::duplicated_attributes, clippy::duplicated_attributes)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +help: remove this attribute + --> tests/ui/duplicated_attributes.rs:2:40 + | +LL | #![warn(clippy::duplicated_attributes, clippy::duplicated_attributes)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `-D clippy::duplicated-attributes` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::duplicated_attributes)]` + error: duplicated attribute --> tests/ui/duplicated_attributes.rs:6:10 | @@ -14,8 +33,6 @@ help: remove this attribute | LL | #![allow(dead_code)] | ^^^^^^^^^ - = note: `-D clippy::duplicated-attributes` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::duplicated_attributes)]` error: duplicated attribute --> tests/ui/duplicated_attributes.rs:14:9 @@ -34,5 +51,5 @@ help: remove this attribute LL | #[allow(dead_code)] | ^^^^^^^^^ -error: aborting due to 2 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/indexing_slicing_slice.rs b/tests/ui/indexing_slicing_slice.rs index cad77f56d03a..dea31530a0b6 100644 --- a/tests/ui/indexing_slicing_slice.rs +++ b/tests/ui/indexing_slicing_slice.rs @@ -1,6 +1,5 @@ //@aux-build: proc_macros.rs -#![warn(clippy::indexing_slicing)] // We also check the out_of_bounds_indexing lint here, because it lints similar things and // we want to avoid false positives. #![warn(clippy::out_of_bounds_indexing)] diff --git a/tests/ui/indexing_slicing_slice.stderr b/tests/ui/indexing_slicing_slice.stderr index e3ef89823e3d..e3d6086544de 100644 --- a/tests/ui/indexing_slicing_slice.stderr +++ b/tests/ui/indexing_slicing_slice.stderr @@ -1,5 +1,5 @@ error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:115:6 + --> tests/ui/indexing_slicing_slice.rs:114:6 | LL | &x[index..]; | ^^^^^^^^^^ @@ -9,7 +9,7 @@ LL | &x[index..]; = help: to override `-D warnings` add `#[allow(clippy::indexing_slicing)]` error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:117:6 + --> tests/ui/indexing_slicing_slice.rs:116:6 | LL | &x[..index]; | ^^^^^^^^^^ @@ -17,7 +17,7 @@ LL | &x[..index]; = help: consider using `.get(..n)`or `.get_mut(..n)` instead error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:119:6 + --> tests/ui/indexing_slicing_slice.rs:118:6 | LL | &x[index_from..index_to]; | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL | &x[index_from..index_to]; = help: consider using `.get(n..m)` or `.get_mut(n..m)` instead error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:121:6 + --> tests/ui/indexing_slicing_slice.rs:120:6 | LL | &x[index_from..][..index_to]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -33,7 +33,7 @@ LL | &x[index_from..][..index_to]; = help: consider using `.get(..n)`or `.get_mut(..n)` instead error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:121:6 + --> tests/ui/indexing_slicing_slice.rs:120:6 | LL | &x[index_from..][..index_to]; | ^^^^^^^^^^^^^^^ @@ -41,7 +41,7 @@ LL | &x[index_from..][..index_to]; = help: consider using `.get(n..)` or .get_mut(n..)` instead error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:124:6 + --> tests/ui/indexing_slicing_slice.rs:123:6 | LL | &x[5..][..10]; | ^^^^^^^^^^^^ @@ -49,7 +49,7 @@ LL | &x[5..][..10]; = help: consider using `.get(..n)`or `.get_mut(..n)` instead error: range is out of bounds - --> tests/ui/indexing_slicing_slice.rs:124:8 + --> tests/ui/indexing_slicing_slice.rs:123:8 | LL | &x[5..][..10]; | ^ @@ -58,7 +58,7 @@ LL | &x[5..][..10]; = help: to override `-D warnings` add `#[allow(clippy::out_of_bounds_indexing)]` error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:127:6 + --> tests/ui/indexing_slicing_slice.rs:126:6 | LL | &x[0..][..3]; | ^^^^^^^^^^^ @@ -66,7 +66,7 @@ LL | &x[0..][..3]; = help: consider using `.get(..n)`or `.get_mut(..n)` instead error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:129:6 + --> tests/ui/indexing_slicing_slice.rs:128:6 | LL | &x[1..][..5]; | ^^^^^^^^^^^ @@ -74,19 +74,19 @@ LL | &x[1..][..5]; = help: consider using `.get(..n)`or `.get_mut(..n)` instead error: range is out of bounds - --> tests/ui/indexing_slicing_slice.rs:137:12 + --> tests/ui/indexing_slicing_slice.rs:136:12 | LL | &y[0..=4]; | ^ error: range is out of bounds - --> tests/ui/indexing_slicing_slice.rs:139:11 + --> tests/ui/indexing_slicing_slice.rs:138:11 | LL | &y[..=4]; | ^ error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:145:6 + --> tests/ui/indexing_slicing_slice.rs:144:6 | LL | &v[10..100]; | ^^^^^^^^^^ @@ -94,7 +94,7 @@ LL | &v[10..100]; = help: consider using `.get(n..m)` or `.get_mut(n..m)` instead error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:147:6 + --> tests/ui/indexing_slicing_slice.rs:146:6 | LL | &x[10..][..100]; | ^^^^^^^^^^^^^^ @@ -102,13 +102,13 @@ LL | &x[10..][..100]; = help: consider using `.get(..n)`or `.get_mut(..n)` instead error: range is out of bounds - --> tests/ui/indexing_slicing_slice.rs:147:8 + --> tests/ui/indexing_slicing_slice.rs:146:8 | LL | &x[10..][..100]; | ^^ error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:150:6 + --> tests/ui/indexing_slicing_slice.rs:149:6 | LL | &v[10..]; | ^^^^^^^ @@ -116,7 +116,7 @@ LL | &v[10..]; = help: consider using `.get(n..)` or .get_mut(n..)` instead error: slicing may panic - --> tests/ui/indexing_slicing_slice.rs:152:6 + --> tests/ui/indexing_slicing_slice.rs:151:6 | LL | &v[..100]; | ^^^^^^^^ @@ -124,7 +124,7 @@ LL | &v[..100]; = help: consider using `.get(..n)`or `.get_mut(..n)` instead error: indexing may panic - --> tests/ui/indexing_slicing_slice.rs:170:5 + --> tests/ui/indexing_slicing_slice.rs:169:5 | LL | map_with_get[true]; | ^^^^^^^^^^^^^^^^^^ @@ -132,7 +132,7 @@ LL | map_with_get[true]; = help: consider using `.get(n)` or `.get_mut(n)` instead error: indexing may panic - --> tests/ui/indexing_slicing_slice.rs:174:5 + --> tests/ui/indexing_slicing_slice.rs:173:5 | LL | s[0]; | ^^^^ @@ -140,7 +140,7 @@ LL | s[0]; = help: consider using `.get(n)` or `.get_mut(n)` instead error: indexing may panic - --> tests/ui/indexing_slicing_slice.rs:178:5 + --> tests/ui/indexing_slicing_slice.rs:177:5 | LL | y[0]; | ^^^^ diff --git a/tests/ui/needless_collect_indirect.rs b/tests/ui/needless_collect_indirect.rs index 57d0f2b99480..fff6d2f34b8e 100644 --- a/tests/ui/needless_collect_indirect.rs +++ b/tests/ui/needless_collect_indirect.rs @@ -1,5 +1,4 @@ -#![allow(clippy::uninlined_format_args, clippy::useless_vec)] -#![allow(clippy::needless_if, clippy::uninlined_format_args)] +#![allow(clippy::uninlined_format_args, clippy::useless_vec, clippy::needless_if)] #![warn(clippy::needless_collect)] //@no-rustfix use std::collections::{BinaryHeap, HashMap, HashSet, LinkedList, VecDeque}; diff --git a/tests/ui/needless_collect_indirect.stderr b/tests/ui/needless_collect_indirect.stderr index c7bf1b14df80..24523c9f97b0 100644 --- a/tests/ui/needless_collect_indirect.stderr +++ b/tests/ui/needless_collect_indirect.stderr @@ -1,5 +1,5 @@ error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:9:39 + --> tests/ui/needless_collect_indirect.rs:8:39 | LL | let indirect_iter = sample.iter().collect::>(); | ^^^^^^^ @@ -18,7 +18,7 @@ LL ~ sample.iter().map(|x| (x, x + 1)).collect::>(); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:13:38 + --> tests/ui/needless_collect_indirect.rs:12:38 | LL | let indirect_len = sample.iter().collect::>(); | ^^^^^^^ @@ -35,7 +35,7 @@ LL ~ sample.iter().count(); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:17:40 + --> tests/ui/needless_collect_indirect.rs:16:40 | LL | let indirect_empty = sample.iter().collect::>(); | ^^^^^^^ @@ -52,7 +52,7 @@ LL ~ sample.iter().next().is_none(); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:21:43 + --> tests/ui/needless_collect_indirect.rs:20:43 | LL | let indirect_contains = sample.iter().collect::>(); | ^^^^^^^ @@ -69,7 +69,7 @@ LL ~ sample.iter().any(|x| x == &5); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:35:48 + --> tests/ui/needless_collect_indirect.rs:34:48 | LL | let non_copy_contains = sample.into_iter().collect::>(); | ^^^^^^^ @@ -86,7 +86,7 @@ LL ~ sample.into_iter().any(|x| x == a); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:66:51 + --> tests/ui/needless_collect_indirect.rs:65:51 | LL | let buffer: Vec<&str> = string.split('/').collect(); | ^^^^^^^ @@ -103,7 +103,7 @@ LL ~ string.split('/').count() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:73:55 + --> tests/ui/needless_collect_indirect.rs:72:55 | LL | let indirect_len: VecDeque<_> = sample.iter().collect(); | ^^^^^^^ @@ -120,7 +120,7 @@ LL ~ sample.iter().count() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:80:57 + --> tests/ui/needless_collect_indirect.rs:79:57 | LL | let indirect_len: LinkedList<_> = sample.iter().collect(); | ^^^^^^^ @@ -137,7 +137,7 @@ LL ~ sample.iter().count() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:87:57 + --> tests/ui/needless_collect_indirect.rs:86:57 | LL | let indirect_len: BinaryHeap<_> = sample.iter().collect(); | ^^^^^^^ @@ -154,7 +154,7 @@ LL ~ sample.iter().count() | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:149:59 + --> tests/ui/needless_collect_indirect.rs:148:59 | LL | let y: Vec = vec.iter().map(|k| k * k).collect(); | ^^^^^^^ @@ -172,7 +172,7 @@ LL ~ vec.iter().map(|k| k * k).any(|x| x == i); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:176:59 + --> tests/ui/needless_collect_indirect.rs:175:59 | LL | let y: Vec = vec.iter().map(|k| k * k).collect(); | ^^^^^^^ @@ -190,7 +190,7 @@ LL ~ vec.iter().map(|k| k * k).any(|x| x == n); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:207:63 + --> tests/ui/needless_collect_indirect.rs:206:63 | LL | let y: Vec = vec.iter().map(|k| k * k).collect(); | ^^^^^^^ @@ -208,7 +208,7 @@ LL ~ vec.iter().map(|k| k * k).any(|x| x == n); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:245:59 + --> tests/ui/needless_collect_indirect.rs:244:59 | LL | let y: Vec = vec.iter().map(|k| k * k).collect(); | ^^^^^^^ @@ -226,7 +226,7 @@ LL ~ vec.iter().map(|k| k * k).any(|x| x == n); | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:272:26 + --> tests/ui/needless_collect_indirect.rs:271:26 | LL | let w = v.iter().collect::>(); | ^^^^^^^ @@ -244,7 +244,7 @@ LL ~ for _ in 0..v.iter().count() { | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:296:30 + --> tests/ui/needless_collect_indirect.rs:295:30 | LL | let mut w = v.iter().collect::>(); | ^^^^^^^ @@ -262,7 +262,7 @@ LL ~ while 1 == v.iter().count() { | error: avoid using `collect()` when not needed - --> tests/ui/needless_collect_indirect.rs:320:30 + --> tests/ui/needless_collect_indirect.rs:319:30 | LL | let mut w = v.iter().collect::>(); | ^^^^^^^ diff --git a/tests/ui/unnecessary_clippy_cfg.rs b/tests/ui/unnecessary_clippy_cfg.rs index e7e01248dfbe..65f67df79131 100644 --- a/tests/ui/unnecessary_clippy_cfg.rs +++ b/tests/ui/unnecessary_clippy_cfg.rs @@ -1,5 +1,6 @@ //@no-rustfix +#![allow(clippy::duplicated_attributes)] #![warn(clippy::unnecessary_clippy_cfg)] #![cfg_attr(clippy, deny(clippy::non_minimal_cfg))] //~^ unnecessary_clippy_cfg @@ -7,7 +8,6 @@ //~^ unnecessary_clippy_cfg #![cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] //~^ unnecessary_clippy_cfg -//~| duplicated_attributes #![cfg_attr(clippy, deny(clippy::non_minimal_cfg))] //~^ unnecessary_clippy_cfg @@ -17,7 +17,6 @@ //~^ unnecessary_clippy_cfg #[cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] //~^ unnecessary_clippy_cfg -//~| duplicated_attributes #[cfg_attr(clippy, deny(clippy::non_minimal_cfg))] //~^ unnecessary_clippy_cfg diff --git a/tests/ui/unnecessary_clippy_cfg.stderr b/tests/ui/unnecessary_clippy_cfg.stderr index f66c68949548..4f638d5c513c 100644 --- a/tests/ui/unnecessary_clippy_cfg.stderr +++ b/tests/ui/unnecessary_clippy_cfg.stderr @@ -1,5 +1,5 @@ error: no need to put clippy lints behind a `clippy` cfg - --> tests/ui/unnecessary_clippy_cfg.rs:4:1 + --> tests/ui/unnecessary_clippy_cfg.rs:5:1 | LL | #![cfg_attr(clippy, deny(clippy::non_minimal_cfg))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `#![deny(clippy::non_minimal_cfg)]` @@ -8,7 +8,7 @@ LL | #![cfg_attr(clippy, deny(clippy::non_minimal_cfg))] = help: to override `-D warnings` add `#[allow(clippy::unnecessary_clippy_cfg)]` error: no need to put clippy lints behind a `clippy` cfg - --> tests/ui/unnecessary_clippy_cfg.rs:6:37 + --> tests/ui/unnecessary_clippy_cfg.rs:7:37 | LL | #![cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -16,7 +16,7 @@ LL | #![cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] = note: write instead: `#![deny(clippy::non_minimal_cfg)]` error: no need to put clippy lints behind a `clippy` cfg - --> tests/ui/unnecessary_clippy_cfg.rs:8:37 + --> tests/ui/unnecessary_clippy_cfg.rs:9:37 | LL | #![cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -52,46 +52,10 @@ LL | #[cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] = note: write instead: `#[deny(clippy::non_minimal_cfg)]` error: no need to put clippy lints behind a `clippy` cfg - --> tests/ui/unnecessary_clippy_cfg.rs:21:1 + --> tests/ui/unnecessary_clippy_cfg.rs:20:1 | LL | #[cfg_attr(clippy, deny(clippy::non_minimal_cfg))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `#[deny(clippy::non_minimal_cfg)]` -error: duplicated attribute - --> tests/ui/unnecessary_clippy_cfg.rs:8:26 - | -LL | #![cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] - | ^^^^^^^^^ - | -note: first defined here - --> tests/ui/unnecessary_clippy_cfg.rs:6:26 - | -LL | #![cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] - | ^^^^^^^^^ -help: remove this attribute - --> tests/ui/unnecessary_clippy_cfg.rs:8:26 - | -LL | #![cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] - | ^^^^^^^^^ - = note: `-D clippy::duplicated-attributes` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::duplicated_attributes)]` - -error: duplicated attribute - --> tests/ui/unnecessary_clippy_cfg.rs:18:25 - | -LL | #[cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] - | ^^^^^^^^^ - | -note: first defined here - --> tests/ui/unnecessary_clippy_cfg.rs:16:25 - | -LL | #[cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] - | ^^^^^^^^^ -help: remove this attribute - --> tests/ui/unnecessary_clippy_cfg.rs:18:25 - | -LL | #[cfg_attr(clippy, deny(dead_code, clippy::non_minimal_cfg))] - | ^^^^^^^^^ - -error: aborting due to 10 previous errors +error: aborting due to 8 previous errors From 49ea48d952db3e9825508699e81d3d8af837b09e Mon Sep 17 00:00:00 2001 From: WANG Rui Date: Sat, 19 Jul 2025 10:36:45 +0800 Subject: [PATCH 0131/1134] loongarch: Use unified data types for SIMD intrinsics --- .../src/loongarch64/lasx/generated.rs | 4441 +++++++++-------- .../core_arch/src/loongarch64/lasx/types.rs | 157 +- .../src/loongarch64/lsx/generated.rs | 4321 ++++++++-------- .../core_arch/src/loongarch64/lsx/types.rs | 159 +- .../crates/stdarch-gen-loongarch/src/main.rs | 224 +- 5 files changed, 4780 insertions(+), 4522 deletions(-) diff --git a/library/stdarch/crates/core_arch/src/loongarch64/lasx/generated.rs b/library/stdarch/crates/core_arch/src/loongarch64/lasx/generated.rs index 4361acdc1fcc..cda0ebec6779 100644 --- a/library/stdarch/crates/core_arch/src/loongarch64/lasx/generated.rs +++ b/library/stdarch/crates/core_arch/src/loongarch64/lasx/generated.rs @@ -6,7058 +6,7059 @@ // OUT_DIR=`pwd`/crates/core_arch cargo run -p stdarch-gen-loongarch -- crates/stdarch-gen-loongarch/lasx.spec // ``` +use crate::mem::transmute; use super::types::*; #[allow(improper_ctypes)] unsafe extern "unadjusted" { #[link_name = "llvm.loongarch.lasx.xvsll.b"] - fn __lasx_xvsll_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsll_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsll.h"] - fn __lasx_xvsll_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsll_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsll.w"] - fn __lasx_xvsll_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsll_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsll.d"] - fn __lasx_xvsll_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsll_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvslli.b"] - fn __lasx_xvslli_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvslli_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvslli.h"] - fn __lasx_xvslli_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvslli_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvslli.w"] - fn __lasx_xvslli_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvslli_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvslli.d"] - fn __lasx_xvslli_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvslli_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsra.b"] - fn __lasx_xvsra_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsra_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsra.h"] - fn __lasx_xvsra_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsra_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsra.w"] - fn __lasx_xvsra_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsra_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsra.d"] - fn __lasx_xvsra_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsra_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrai.b"] - fn __lasx_xvsrai_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvsrai_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrai.h"] - fn __lasx_xvsrai_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvsrai_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrai.w"] - fn __lasx_xvsrai_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvsrai_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrai.d"] - fn __lasx_xvsrai_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvsrai_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrar.b"] - fn __lasx_xvsrar_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsrar_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrar.h"] - fn __lasx_xvsrar_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsrar_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrar.w"] - fn __lasx_xvsrar_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsrar_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrar.d"] - fn __lasx_xvsrar_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsrar_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrari.b"] - fn __lasx_xvsrari_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvsrari_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrari.h"] - fn __lasx_xvsrari_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvsrari_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrari.w"] - fn __lasx_xvsrari_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvsrari_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrari.d"] - fn __lasx_xvsrari_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvsrari_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrl.b"] - fn __lasx_xvsrl_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsrl_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrl.h"] - fn __lasx_xvsrl_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsrl_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrl.w"] - fn __lasx_xvsrl_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsrl_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrl.d"] - fn __lasx_xvsrl_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsrl_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrli.b"] - fn __lasx_xvsrli_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvsrli_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrli.h"] - fn __lasx_xvsrli_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvsrli_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrli.w"] - fn __lasx_xvsrli_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvsrli_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrli.d"] - fn __lasx_xvsrli_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvsrli_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrlr.b"] - fn __lasx_xvsrlr_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsrlr_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrlr.h"] - fn __lasx_xvsrlr_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsrlr_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrlr.w"] - fn __lasx_xvsrlr_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsrlr_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrlr.d"] - fn __lasx_xvsrlr_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsrlr_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrlri.b"] - fn __lasx_xvsrlri_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvsrlri_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrlri.h"] - fn __lasx_xvsrlri_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvsrlri_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrlri.w"] - fn __lasx_xvsrlri_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvsrlri_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrlri.d"] - fn __lasx_xvsrlri_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvsrlri_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvbitclr.b"] - fn __lasx_xvbitclr_b(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvbitclr_b(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvbitclr.h"] - fn __lasx_xvbitclr_h(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvbitclr_h(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvbitclr.w"] - fn __lasx_xvbitclr_w(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvbitclr_w(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvbitclr.d"] - fn __lasx_xvbitclr_d(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvbitclr_d(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvbitclri.b"] - fn __lasx_xvbitclri_b(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvbitclri_b(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvbitclri.h"] - fn __lasx_xvbitclri_h(a: v16u16, b: u32) -> v16u16; + fn __lasx_xvbitclri_h(a: __v16u16, b: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvbitclri.w"] - fn __lasx_xvbitclri_w(a: v8u32, b: u32) -> v8u32; + fn __lasx_xvbitclri_w(a: __v8u32, b: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvbitclri.d"] - fn __lasx_xvbitclri_d(a: v4u64, b: u32) -> v4u64; + fn __lasx_xvbitclri_d(a: __v4u64, b: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvbitset.b"] - fn __lasx_xvbitset_b(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvbitset_b(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvbitset.h"] - fn __lasx_xvbitset_h(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvbitset_h(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvbitset.w"] - fn __lasx_xvbitset_w(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvbitset_w(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvbitset.d"] - fn __lasx_xvbitset_d(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvbitset_d(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvbitseti.b"] - fn __lasx_xvbitseti_b(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvbitseti_b(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvbitseti.h"] - fn __lasx_xvbitseti_h(a: v16u16, b: u32) -> v16u16; + fn __lasx_xvbitseti_h(a: __v16u16, b: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvbitseti.w"] - fn __lasx_xvbitseti_w(a: v8u32, b: u32) -> v8u32; + fn __lasx_xvbitseti_w(a: __v8u32, b: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvbitseti.d"] - fn __lasx_xvbitseti_d(a: v4u64, b: u32) -> v4u64; + fn __lasx_xvbitseti_d(a: __v4u64, b: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvbitrev.b"] - fn __lasx_xvbitrev_b(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvbitrev_b(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvbitrev.h"] - fn __lasx_xvbitrev_h(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvbitrev_h(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvbitrev.w"] - fn __lasx_xvbitrev_w(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvbitrev_w(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvbitrev.d"] - fn __lasx_xvbitrev_d(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvbitrev_d(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvbitrevi.b"] - fn __lasx_xvbitrevi_b(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvbitrevi_b(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvbitrevi.h"] - fn __lasx_xvbitrevi_h(a: v16u16, b: u32) -> v16u16; + fn __lasx_xvbitrevi_h(a: __v16u16, b: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvbitrevi.w"] - fn __lasx_xvbitrevi_w(a: v8u32, b: u32) -> v8u32; + fn __lasx_xvbitrevi_w(a: __v8u32, b: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvbitrevi.d"] - fn __lasx_xvbitrevi_d(a: v4u64, b: u32) -> v4u64; + fn __lasx_xvbitrevi_d(a: __v4u64, b: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvadd.b"] - fn __lasx_xvadd_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvadd_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvadd.h"] - fn __lasx_xvadd_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvadd_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvadd.w"] - fn __lasx_xvadd_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvadd_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvadd.d"] - fn __lasx_xvadd_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvadd_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddi.bu"] - fn __lasx_xvaddi_bu(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvaddi_bu(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvaddi.hu"] - fn __lasx_xvaddi_hu(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvaddi_hu(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvaddi.wu"] - fn __lasx_xvaddi_wu(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvaddi_wu(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvaddi.du"] - fn __lasx_xvaddi_du(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvaddi_du(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsub.b"] - fn __lasx_xvsub_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsub_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsub.h"] - fn __lasx_xvsub_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsub_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsub.w"] - fn __lasx_xvsub_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsub_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsub.d"] - fn __lasx_xvsub_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsub_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubi.bu"] - fn __lasx_xvsubi_bu(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvsubi_bu(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsubi.hu"] - fn __lasx_xvsubi_hu(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvsubi_hu(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsubi.wu"] - fn __lasx_xvsubi_wu(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvsubi_wu(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsubi.du"] - fn __lasx_xvsubi_du(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvsubi_du(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmax.b"] - fn __lasx_xvmax_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvmax_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmax.h"] - fn __lasx_xvmax_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvmax_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmax.w"] - fn __lasx_xvmax_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvmax_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmax.d"] - fn __lasx_xvmax_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvmax_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaxi.b"] - fn __lasx_xvmaxi_b(a: v32i8, b: i32) -> v32i8; + fn __lasx_xvmaxi_b(a: __v32i8, b: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmaxi.h"] - fn __lasx_xvmaxi_h(a: v16i16, b: i32) -> v16i16; + fn __lasx_xvmaxi_h(a: __v16i16, b: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmaxi.w"] - fn __lasx_xvmaxi_w(a: v8i32, b: i32) -> v8i32; + fn __lasx_xvmaxi_w(a: __v8i32, b: i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmaxi.d"] - fn __lasx_xvmaxi_d(a: v4i64, b: i32) -> v4i64; + fn __lasx_xvmaxi_d(a: __v4i64, b: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmax.bu"] - fn __lasx_xvmax_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvmax_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvmax.hu"] - fn __lasx_xvmax_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvmax_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvmax.wu"] - fn __lasx_xvmax_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvmax_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvmax.du"] - fn __lasx_xvmax_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvmax_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmaxi.bu"] - fn __lasx_xvmaxi_bu(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvmaxi_bu(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvmaxi.hu"] - fn __lasx_xvmaxi_hu(a: v16u16, b: u32) -> v16u16; + fn __lasx_xvmaxi_hu(a: __v16u16, b: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvmaxi.wu"] - fn __lasx_xvmaxi_wu(a: v8u32, b: u32) -> v8u32; + fn __lasx_xvmaxi_wu(a: __v8u32, b: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvmaxi.du"] - fn __lasx_xvmaxi_du(a: v4u64, b: u32) -> v4u64; + fn __lasx_xvmaxi_du(a: __v4u64, b: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmin.b"] - fn __lasx_xvmin_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvmin_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmin.h"] - fn __lasx_xvmin_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvmin_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmin.w"] - fn __lasx_xvmin_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvmin_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmin.d"] - fn __lasx_xvmin_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvmin_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmini.b"] - fn __lasx_xvmini_b(a: v32i8, b: i32) -> v32i8; + fn __lasx_xvmini_b(a: __v32i8, b: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmini.h"] - fn __lasx_xvmini_h(a: v16i16, b: i32) -> v16i16; + fn __lasx_xvmini_h(a: __v16i16, b: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmini.w"] - fn __lasx_xvmini_w(a: v8i32, b: i32) -> v8i32; + fn __lasx_xvmini_w(a: __v8i32, b: i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmini.d"] - fn __lasx_xvmini_d(a: v4i64, b: i32) -> v4i64; + fn __lasx_xvmini_d(a: __v4i64, b: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmin.bu"] - fn __lasx_xvmin_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvmin_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvmin.hu"] - fn __lasx_xvmin_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvmin_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvmin.wu"] - fn __lasx_xvmin_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvmin_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvmin.du"] - fn __lasx_xvmin_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvmin_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmini.bu"] - fn __lasx_xvmini_bu(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvmini_bu(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvmini.hu"] - fn __lasx_xvmini_hu(a: v16u16, b: u32) -> v16u16; + fn __lasx_xvmini_hu(a: __v16u16, b: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvmini.wu"] - fn __lasx_xvmini_wu(a: v8u32, b: u32) -> v8u32; + fn __lasx_xvmini_wu(a: __v8u32, b: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvmini.du"] - fn __lasx_xvmini_du(a: v4u64, b: u32) -> v4u64; + fn __lasx_xvmini_du(a: __v4u64, b: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvseq.b"] - fn __lasx_xvseq_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvseq_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvseq.h"] - fn __lasx_xvseq_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvseq_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvseq.w"] - fn __lasx_xvseq_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvseq_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvseq.d"] - fn __lasx_xvseq_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvseq_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvseqi.b"] - fn __lasx_xvseqi_b(a: v32i8, b: i32) -> v32i8; + fn __lasx_xvseqi_b(a: __v32i8, b: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvseqi.h"] - fn __lasx_xvseqi_h(a: v16i16, b: i32) -> v16i16; + fn __lasx_xvseqi_h(a: __v16i16, b: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvseqi.w"] - fn __lasx_xvseqi_w(a: v8i32, b: i32) -> v8i32; + fn __lasx_xvseqi_w(a: __v8i32, b: i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvseqi.d"] - fn __lasx_xvseqi_d(a: v4i64, b: i32) -> v4i64; + fn __lasx_xvseqi_d(a: __v4i64, b: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvslt.b"] - fn __lasx_xvslt_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvslt_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvslt.h"] - fn __lasx_xvslt_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvslt_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvslt.w"] - fn __lasx_xvslt_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvslt_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvslt.d"] - fn __lasx_xvslt_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvslt_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvslti.b"] - fn __lasx_xvslti_b(a: v32i8, b: i32) -> v32i8; + fn __lasx_xvslti_b(a: __v32i8, b: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvslti.h"] - fn __lasx_xvslti_h(a: v16i16, b: i32) -> v16i16; + fn __lasx_xvslti_h(a: __v16i16, b: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvslti.w"] - fn __lasx_xvslti_w(a: v8i32, b: i32) -> v8i32; + fn __lasx_xvslti_w(a: __v8i32, b: i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvslti.d"] - fn __lasx_xvslti_d(a: v4i64, b: i32) -> v4i64; + fn __lasx_xvslti_d(a: __v4i64, b: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvslt.bu"] - fn __lasx_xvslt_bu(a: v32u8, b: v32u8) -> v32i8; + fn __lasx_xvslt_bu(a: __v32u8, b: __v32u8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvslt.hu"] - fn __lasx_xvslt_hu(a: v16u16, b: v16u16) -> v16i16; + fn __lasx_xvslt_hu(a: __v16u16, b: __v16u16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvslt.wu"] - fn __lasx_xvslt_wu(a: v8u32, b: v8u32) -> v8i32; + fn __lasx_xvslt_wu(a: __v8u32, b: __v8u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvslt.du"] - fn __lasx_xvslt_du(a: v4u64, b: v4u64) -> v4i64; + fn __lasx_xvslt_du(a: __v4u64, b: __v4u64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvslti.bu"] - fn __lasx_xvslti_bu(a: v32u8, b: u32) -> v32i8; + fn __lasx_xvslti_bu(a: __v32u8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvslti.hu"] - fn __lasx_xvslti_hu(a: v16u16, b: u32) -> v16i16; + fn __lasx_xvslti_hu(a: __v16u16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvslti.wu"] - fn __lasx_xvslti_wu(a: v8u32, b: u32) -> v8i32; + fn __lasx_xvslti_wu(a: __v8u32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvslti.du"] - fn __lasx_xvslti_du(a: v4u64, b: u32) -> v4i64; + fn __lasx_xvslti_du(a: __v4u64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsle.b"] - fn __lasx_xvsle_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsle_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsle.h"] - fn __lasx_xvsle_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsle_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsle.w"] - fn __lasx_xvsle_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsle_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsle.d"] - fn __lasx_xvsle_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsle_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvslei.b"] - fn __lasx_xvslei_b(a: v32i8, b: i32) -> v32i8; + fn __lasx_xvslei_b(a: __v32i8, b: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvslei.h"] - fn __lasx_xvslei_h(a: v16i16, b: i32) -> v16i16; + fn __lasx_xvslei_h(a: __v16i16, b: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvslei.w"] - fn __lasx_xvslei_w(a: v8i32, b: i32) -> v8i32; + fn __lasx_xvslei_w(a: __v8i32, b: i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvslei.d"] - fn __lasx_xvslei_d(a: v4i64, b: i32) -> v4i64; + fn __lasx_xvslei_d(a: __v4i64, b: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsle.bu"] - fn __lasx_xvsle_bu(a: v32u8, b: v32u8) -> v32i8; + fn __lasx_xvsle_bu(a: __v32u8, b: __v32u8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsle.hu"] - fn __lasx_xvsle_hu(a: v16u16, b: v16u16) -> v16i16; + fn __lasx_xvsle_hu(a: __v16u16, b: __v16u16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsle.wu"] - fn __lasx_xvsle_wu(a: v8u32, b: v8u32) -> v8i32; + fn __lasx_xvsle_wu(a: __v8u32, b: __v8u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsle.du"] - fn __lasx_xvsle_du(a: v4u64, b: v4u64) -> v4i64; + fn __lasx_xvsle_du(a: __v4u64, b: __v4u64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvslei.bu"] - fn __lasx_xvslei_bu(a: v32u8, b: u32) -> v32i8; + fn __lasx_xvslei_bu(a: __v32u8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvslei.hu"] - fn __lasx_xvslei_hu(a: v16u16, b: u32) -> v16i16; + fn __lasx_xvslei_hu(a: __v16u16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvslei.wu"] - fn __lasx_xvslei_wu(a: v8u32, b: u32) -> v8i32; + fn __lasx_xvslei_wu(a: __v8u32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvslei.du"] - fn __lasx_xvslei_du(a: v4u64, b: u32) -> v4i64; + fn __lasx_xvslei_du(a: __v4u64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsat.b"] - fn __lasx_xvsat_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvsat_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsat.h"] - fn __lasx_xvsat_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvsat_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsat.w"] - fn __lasx_xvsat_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvsat_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsat.d"] - fn __lasx_xvsat_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvsat_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsat.bu"] - fn __lasx_xvsat_bu(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvsat_bu(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvsat.hu"] - fn __lasx_xvsat_hu(a: v16u16, b: u32) -> v16u16; + fn __lasx_xvsat_hu(a: __v16u16, b: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvsat.wu"] - fn __lasx_xvsat_wu(a: v8u32, b: u32) -> v8u32; + fn __lasx_xvsat_wu(a: __v8u32, b: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvsat.du"] - fn __lasx_xvsat_du(a: v4u64, b: u32) -> v4u64; + fn __lasx_xvsat_du(a: __v4u64, b: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvadda.b"] - fn __lasx_xvadda_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvadda_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvadda.h"] - fn __lasx_xvadda_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvadda_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvadda.w"] - fn __lasx_xvadda_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvadda_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvadda.d"] - fn __lasx_xvadda_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvadda_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsadd.b"] - fn __lasx_xvsadd_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsadd_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsadd.h"] - fn __lasx_xvsadd_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsadd_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsadd.w"] - fn __lasx_xvsadd_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsadd_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsadd.d"] - fn __lasx_xvsadd_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsadd_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsadd.bu"] - fn __lasx_xvsadd_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvsadd_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvsadd.hu"] - fn __lasx_xvsadd_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvsadd_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvsadd.wu"] - fn __lasx_xvsadd_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvsadd_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvsadd.du"] - fn __lasx_xvsadd_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvsadd_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvavg.b"] - fn __lasx_xvavg_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvavg_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvavg.h"] - fn __lasx_xvavg_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvavg_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvavg.w"] - fn __lasx_xvavg_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvavg_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvavg.d"] - fn __lasx_xvavg_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvavg_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvavg.bu"] - fn __lasx_xvavg_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvavg_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvavg.hu"] - fn __lasx_xvavg_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvavg_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvavg.wu"] - fn __lasx_xvavg_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvavg_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvavg.du"] - fn __lasx_xvavg_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvavg_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvavgr.b"] - fn __lasx_xvavgr_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvavgr_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvavgr.h"] - fn __lasx_xvavgr_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvavgr_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvavgr.w"] - fn __lasx_xvavgr_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvavgr_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvavgr.d"] - fn __lasx_xvavgr_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvavgr_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvavgr.bu"] - fn __lasx_xvavgr_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvavgr_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvavgr.hu"] - fn __lasx_xvavgr_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvavgr_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvavgr.wu"] - fn __lasx_xvavgr_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvavgr_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvavgr.du"] - fn __lasx_xvavgr_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvavgr_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvssub.b"] - fn __lasx_xvssub_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvssub_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssub.h"] - fn __lasx_xvssub_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvssub_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssub.w"] - fn __lasx_xvssub_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvssub_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssub.d"] - fn __lasx_xvssub_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvssub_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvssub.bu"] - fn __lasx_xvssub_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvssub_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssub.hu"] - fn __lasx_xvssub_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvssub_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssub.wu"] - fn __lasx_xvssub_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvssub_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvssub.du"] - fn __lasx_xvssub_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvssub_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvabsd.b"] - fn __lasx_xvabsd_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvabsd_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvabsd.h"] - fn __lasx_xvabsd_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvabsd_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvabsd.w"] - fn __lasx_xvabsd_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvabsd_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvabsd.d"] - fn __lasx_xvabsd_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvabsd_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvabsd.bu"] - fn __lasx_xvabsd_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvabsd_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvabsd.hu"] - fn __lasx_xvabsd_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvabsd_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvabsd.wu"] - fn __lasx_xvabsd_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvabsd_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvabsd.du"] - fn __lasx_xvabsd_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvabsd_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmul.b"] - fn __lasx_xvmul_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvmul_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmul.h"] - fn __lasx_xvmul_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvmul_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmul.w"] - fn __lasx_xvmul_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvmul_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmul.d"] - fn __lasx_xvmul_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvmul_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmadd.b"] - fn __lasx_xvmadd_b(a: v32i8, b: v32i8, c: v32i8) -> v32i8; + fn __lasx_xvmadd_b(a: __v32i8, b: __v32i8, c: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmadd.h"] - fn __lasx_xvmadd_h(a: v16i16, b: v16i16, c: v16i16) -> v16i16; + fn __lasx_xvmadd_h(a: __v16i16, b: __v16i16, c: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmadd.w"] - fn __lasx_xvmadd_w(a: v8i32, b: v8i32, c: v8i32) -> v8i32; + fn __lasx_xvmadd_w(a: __v8i32, b: __v8i32, c: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmadd.d"] - fn __lasx_xvmadd_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64; + fn __lasx_xvmadd_d(a: __v4i64, b: __v4i64, c: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmsub.b"] - fn __lasx_xvmsub_b(a: v32i8, b: v32i8, c: v32i8) -> v32i8; + fn __lasx_xvmsub_b(a: __v32i8, b: __v32i8, c: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmsub.h"] - fn __lasx_xvmsub_h(a: v16i16, b: v16i16, c: v16i16) -> v16i16; + fn __lasx_xvmsub_h(a: __v16i16, b: __v16i16, c: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmsub.w"] - fn __lasx_xvmsub_w(a: v8i32, b: v8i32, c: v8i32) -> v8i32; + fn __lasx_xvmsub_w(a: __v8i32, b: __v8i32, c: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmsub.d"] - fn __lasx_xvmsub_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64; + fn __lasx_xvmsub_d(a: __v4i64, b: __v4i64, c: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvdiv.b"] - fn __lasx_xvdiv_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvdiv_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvdiv.h"] - fn __lasx_xvdiv_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvdiv_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvdiv.w"] - fn __lasx_xvdiv_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvdiv_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvdiv.d"] - fn __lasx_xvdiv_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvdiv_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvdiv.bu"] - fn __lasx_xvdiv_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvdiv_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvdiv.hu"] - fn __lasx_xvdiv_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvdiv_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvdiv.wu"] - fn __lasx_xvdiv_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvdiv_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvdiv.du"] - fn __lasx_xvdiv_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvdiv_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvhaddw.h.b"] - fn __lasx_xvhaddw_h_b(a: v32i8, b: v32i8) -> v16i16; + fn __lasx_xvhaddw_h_b(a: __v32i8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvhaddw.w.h"] - fn __lasx_xvhaddw_w_h(a: v16i16, b: v16i16) -> v8i32; + fn __lasx_xvhaddw_w_h(a: __v16i16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvhaddw.d.w"] - fn __lasx_xvhaddw_d_w(a: v8i32, b: v8i32) -> v4i64; + fn __lasx_xvhaddw_d_w(a: __v8i32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvhaddw.hu.bu"] - fn __lasx_xvhaddw_hu_bu(a: v32u8, b: v32u8) -> v16u16; + fn __lasx_xvhaddw_hu_bu(a: __v32u8, b: __v32u8) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvhaddw.wu.hu"] - fn __lasx_xvhaddw_wu_hu(a: v16u16, b: v16u16) -> v8u32; + fn __lasx_xvhaddw_wu_hu(a: __v16u16, b: __v16u16) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvhaddw.du.wu"] - fn __lasx_xvhaddw_du_wu(a: v8u32, b: v8u32) -> v4u64; + fn __lasx_xvhaddw_du_wu(a: __v8u32, b: __v8u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvhsubw.h.b"] - fn __lasx_xvhsubw_h_b(a: v32i8, b: v32i8) -> v16i16; + fn __lasx_xvhsubw_h_b(a: __v32i8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvhsubw.w.h"] - fn __lasx_xvhsubw_w_h(a: v16i16, b: v16i16) -> v8i32; + fn __lasx_xvhsubw_w_h(a: __v16i16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvhsubw.d.w"] - fn __lasx_xvhsubw_d_w(a: v8i32, b: v8i32) -> v4i64; + fn __lasx_xvhsubw_d_w(a: __v8i32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvhsubw.hu.bu"] - fn __lasx_xvhsubw_hu_bu(a: v32u8, b: v32u8) -> v16i16; + fn __lasx_xvhsubw_hu_bu(a: __v32u8, b: __v32u8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvhsubw.wu.hu"] - fn __lasx_xvhsubw_wu_hu(a: v16u16, b: v16u16) -> v8i32; + fn __lasx_xvhsubw_wu_hu(a: __v16u16, b: __v16u16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvhsubw.du.wu"] - fn __lasx_xvhsubw_du_wu(a: v8u32, b: v8u32) -> v4i64; + fn __lasx_xvhsubw_du_wu(a: __v8u32, b: __v8u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmod.b"] - fn __lasx_xvmod_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvmod_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmod.h"] - fn __lasx_xvmod_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvmod_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmod.w"] - fn __lasx_xvmod_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvmod_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmod.d"] - fn __lasx_xvmod_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvmod_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmod.bu"] - fn __lasx_xvmod_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvmod_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvmod.hu"] - fn __lasx_xvmod_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvmod_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvmod.wu"] - fn __lasx_xvmod_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvmod_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvmod.du"] - fn __lasx_xvmod_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvmod_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvrepl128vei.b"] - fn __lasx_xvrepl128vei_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvrepl128vei_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvrepl128vei.h"] - fn __lasx_xvrepl128vei_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvrepl128vei_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvrepl128vei.w"] - fn __lasx_xvrepl128vei_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvrepl128vei_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvrepl128vei.d"] - fn __lasx_xvrepl128vei_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvrepl128vei_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpickev.b"] - fn __lasx_xvpickev_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvpickev_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvpickev.h"] - fn __lasx_xvpickev_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvpickev_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvpickev.w"] - fn __lasx_xvpickev_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvpickev_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvpickev.d"] - fn __lasx_xvpickev_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvpickev_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpickod.b"] - fn __lasx_xvpickod_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvpickod_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvpickod.h"] - fn __lasx_xvpickod_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvpickod_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvpickod.w"] - fn __lasx_xvpickod_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvpickod_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvpickod.d"] - fn __lasx_xvpickod_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvpickod_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvilvh.b"] - fn __lasx_xvilvh_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvilvh_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvilvh.h"] - fn __lasx_xvilvh_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvilvh_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvilvh.w"] - fn __lasx_xvilvh_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvilvh_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvilvh.d"] - fn __lasx_xvilvh_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvilvh_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvilvl.b"] - fn __lasx_xvilvl_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvilvl_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvilvl.h"] - fn __lasx_xvilvl_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvilvl_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvilvl.w"] - fn __lasx_xvilvl_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvilvl_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvilvl.d"] - fn __lasx_xvilvl_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvilvl_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpackev.b"] - fn __lasx_xvpackev_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvpackev_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvpackev.h"] - fn __lasx_xvpackev_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvpackev_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvpackev.w"] - fn __lasx_xvpackev_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvpackev_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvpackev.d"] - fn __lasx_xvpackev_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvpackev_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpackod.b"] - fn __lasx_xvpackod_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvpackod_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvpackod.h"] - fn __lasx_xvpackod_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvpackod_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvpackod.w"] - fn __lasx_xvpackod_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvpackod_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvpackod.d"] - fn __lasx_xvpackod_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvpackod_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvshuf.b"] - fn __lasx_xvshuf_b(a: v32i8, b: v32i8, c: v32i8) -> v32i8; + fn __lasx_xvshuf_b(a: __v32i8, b: __v32i8, c: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvshuf.h"] - fn __lasx_xvshuf_h(a: v16i16, b: v16i16, c: v16i16) -> v16i16; + fn __lasx_xvshuf_h(a: __v16i16, b: __v16i16, c: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvshuf.w"] - fn __lasx_xvshuf_w(a: v8i32, b: v8i32, c: v8i32) -> v8i32; + fn __lasx_xvshuf_w(a: __v8i32, b: __v8i32, c: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvshuf.d"] - fn __lasx_xvshuf_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64; + fn __lasx_xvshuf_d(a: __v4i64, b: __v4i64, c: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvand.v"] - fn __lasx_xvand_v(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvand_v(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvandi.b"] - fn __lasx_xvandi_b(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvandi_b(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvor.v"] - fn __lasx_xvor_v(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvor_v(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvori.b"] - fn __lasx_xvori_b(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvori_b(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvnor.v"] - fn __lasx_xvnor_v(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvnor_v(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvnori.b"] - fn __lasx_xvnori_b(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvnori_b(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvxor.v"] - fn __lasx_xvxor_v(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvxor_v(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvxori.b"] - fn __lasx_xvxori_b(a: v32u8, b: u32) -> v32u8; + fn __lasx_xvxori_b(a: __v32u8, b: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvbitsel.v"] - fn __lasx_xvbitsel_v(a: v32u8, b: v32u8, c: v32u8) -> v32u8; + fn __lasx_xvbitsel_v(a: __v32u8, b: __v32u8, c: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvbitseli.b"] - fn __lasx_xvbitseli_b(a: v32u8, b: v32u8, c: u32) -> v32u8; + fn __lasx_xvbitseli_b(a: __v32u8, b: __v32u8, c: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvshuf4i.b"] - fn __lasx_xvshuf4i_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvshuf4i_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvshuf4i.h"] - fn __lasx_xvshuf4i_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvshuf4i_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvshuf4i.w"] - fn __lasx_xvshuf4i_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvshuf4i_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvreplgr2vr.b"] - fn __lasx_xvreplgr2vr_b(a: i32) -> v32i8; + fn __lasx_xvreplgr2vr_b(a: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvreplgr2vr.h"] - fn __lasx_xvreplgr2vr_h(a: i32) -> v16i16; + fn __lasx_xvreplgr2vr_h(a: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvreplgr2vr.w"] - fn __lasx_xvreplgr2vr_w(a: i32) -> v8i32; + fn __lasx_xvreplgr2vr_w(a: i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvreplgr2vr.d"] - fn __lasx_xvreplgr2vr_d(a: i64) -> v4i64; + fn __lasx_xvreplgr2vr_d(a: i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpcnt.b"] - fn __lasx_xvpcnt_b(a: v32i8) -> v32i8; + fn __lasx_xvpcnt_b(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvpcnt.h"] - fn __lasx_xvpcnt_h(a: v16i16) -> v16i16; + fn __lasx_xvpcnt_h(a: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvpcnt.w"] - fn __lasx_xvpcnt_w(a: v8i32) -> v8i32; + fn __lasx_xvpcnt_w(a: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvpcnt.d"] - fn __lasx_xvpcnt_d(a: v4i64) -> v4i64; + fn __lasx_xvpcnt_d(a: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvclo.b"] - fn __lasx_xvclo_b(a: v32i8) -> v32i8; + fn __lasx_xvclo_b(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvclo.h"] - fn __lasx_xvclo_h(a: v16i16) -> v16i16; + fn __lasx_xvclo_h(a: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvclo.w"] - fn __lasx_xvclo_w(a: v8i32) -> v8i32; + fn __lasx_xvclo_w(a: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvclo.d"] - fn __lasx_xvclo_d(a: v4i64) -> v4i64; + fn __lasx_xvclo_d(a: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvclz.b"] - fn __lasx_xvclz_b(a: v32i8) -> v32i8; + fn __lasx_xvclz_b(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvclz.h"] - fn __lasx_xvclz_h(a: v16i16) -> v16i16; + fn __lasx_xvclz_h(a: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvclz.w"] - fn __lasx_xvclz_w(a: v8i32) -> v8i32; + fn __lasx_xvclz_w(a: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvclz.d"] - fn __lasx_xvclz_d(a: v4i64) -> v4i64; + fn __lasx_xvclz_d(a: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfadd.s"] - fn __lasx_xvfadd_s(a: v8f32, b: v8f32) -> v8f32; + fn __lasx_xvfadd_s(a: __v8f32, b: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfadd.d"] - fn __lasx_xvfadd_d(a: v4f64, b: v4f64) -> v4f64; + fn __lasx_xvfadd_d(a: __v4f64, b: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfsub.s"] - fn __lasx_xvfsub_s(a: v8f32, b: v8f32) -> v8f32; + fn __lasx_xvfsub_s(a: __v8f32, b: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfsub.d"] - fn __lasx_xvfsub_d(a: v4f64, b: v4f64) -> v4f64; + fn __lasx_xvfsub_d(a: __v4f64, b: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfmul.s"] - fn __lasx_xvfmul_s(a: v8f32, b: v8f32) -> v8f32; + fn __lasx_xvfmul_s(a: __v8f32, b: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfmul.d"] - fn __lasx_xvfmul_d(a: v4f64, b: v4f64) -> v4f64; + fn __lasx_xvfmul_d(a: __v4f64, b: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfdiv.s"] - fn __lasx_xvfdiv_s(a: v8f32, b: v8f32) -> v8f32; + fn __lasx_xvfdiv_s(a: __v8f32, b: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfdiv.d"] - fn __lasx_xvfdiv_d(a: v4f64, b: v4f64) -> v4f64; + fn __lasx_xvfdiv_d(a: __v4f64, b: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfcvt.h.s"] - fn __lasx_xvfcvt_h_s(a: v8f32, b: v8f32) -> v16i16; + fn __lasx_xvfcvt_h_s(a: __v8f32, b: __v8f32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvfcvt.s.d"] - fn __lasx_xvfcvt_s_d(a: v4f64, b: v4f64) -> v8f32; + fn __lasx_xvfcvt_s_d(a: __v4f64, b: __v4f64) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfmin.s"] - fn __lasx_xvfmin_s(a: v8f32, b: v8f32) -> v8f32; + fn __lasx_xvfmin_s(a: __v8f32, b: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfmin.d"] - fn __lasx_xvfmin_d(a: v4f64, b: v4f64) -> v4f64; + fn __lasx_xvfmin_d(a: __v4f64, b: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfmina.s"] - fn __lasx_xvfmina_s(a: v8f32, b: v8f32) -> v8f32; + fn __lasx_xvfmina_s(a: __v8f32, b: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfmina.d"] - fn __lasx_xvfmina_d(a: v4f64, b: v4f64) -> v4f64; + fn __lasx_xvfmina_d(a: __v4f64, b: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfmax.s"] - fn __lasx_xvfmax_s(a: v8f32, b: v8f32) -> v8f32; + fn __lasx_xvfmax_s(a: __v8f32, b: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfmax.d"] - fn __lasx_xvfmax_d(a: v4f64, b: v4f64) -> v4f64; + fn __lasx_xvfmax_d(a: __v4f64, b: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfmaxa.s"] - fn __lasx_xvfmaxa_s(a: v8f32, b: v8f32) -> v8f32; + fn __lasx_xvfmaxa_s(a: __v8f32, b: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfmaxa.d"] - fn __lasx_xvfmaxa_d(a: v4f64, b: v4f64) -> v4f64; + fn __lasx_xvfmaxa_d(a: __v4f64, b: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfclass.s"] - fn __lasx_xvfclass_s(a: v8f32) -> v8i32; + fn __lasx_xvfclass_s(a: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfclass.d"] - fn __lasx_xvfclass_d(a: v4f64) -> v4i64; + fn __lasx_xvfclass_d(a: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfsqrt.s"] - fn __lasx_xvfsqrt_s(a: v8f32) -> v8f32; + fn __lasx_xvfsqrt_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfsqrt.d"] - fn __lasx_xvfsqrt_d(a: v4f64) -> v4f64; + fn __lasx_xvfsqrt_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfrecip.s"] - fn __lasx_xvfrecip_s(a: v8f32) -> v8f32; + fn __lasx_xvfrecip_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrecip.d"] - fn __lasx_xvfrecip_d(a: v4f64) -> v4f64; + fn __lasx_xvfrecip_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfrecipe.s"] - fn __lasx_xvfrecipe_s(a: v8f32) -> v8f32; + fn __lasx_xvfrecipe_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrecipe.d"] - fn __lasx_xvfrecipe_d(a: v4f64) -> v4f64; + fn __lasx_xvfrecipe_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfrsqrte.s"] - fn __lasx_xvfrsqrte_s(a: v8f32) -> v8f32; + fn __lasx_xvfrsqrte_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrsqrte.d"] - fn __lasx_xvfrsqrte_d(a: v4f64) -> v4f64; + fn __lasx_xvfrsqrte_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfrint.s"] - fn __lasx_xvfrint_s(a: v8f32) -> v8f32; + fn __lasx_xvfrint_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrint.d"] - fn __lasx_xvfrint_d(a: v4f64) -> v4f64; + fn __lasx_xvfrint_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfrsqrt.s"] - fn __lasx_xvfrsqrt_s(a: v8f32) -> v8f32; + fn __lasx_xvfrsqrt_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrsqrt.d"] - fn __lasx_xvfrsqrt_d(a: v4f64) -> v4f64; + fn __lasx_xvfrsqrt_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvflogb.s"] - fn __lasx_xvflogb_s(a: v8f32) -> v8f32; + fn __lasx_xvflogb_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvflogb.d"] - fn __lasx_xvflogb_d(a: v4f64) -> v4f64; + fn __lasx_xvflogb_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfcvth.s.h"] - fn __lasx_xvfcvth_s_h(a: v16i16) -> v8f32; + fn __lasx_xvfcvth_s_h(a: __v16i16) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfcvth.d.s"] - fn __lasx_xvfcvth_d_s(a: v8f32) -> v4f64; + fn __lasx_xvfcvth_d_s(a: __v8f32) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfcvtl.s.h"] - fn __lasx_xvfcvtl_s_h(a: v16i16) -> v8f32; + fn __lasx_xvfcvtl_s_h(a: __v16i16) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfcvtl.d.s"] - fn __lasx_xvfcvtl_d_s(a: v8f32) -> v4f64; + fn __lasx_xvfcvtl_d_s(a: __v8f32) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvftint.w.s"] - fn __lasx_xvftint_w_s(a: v8f32) -> v8i32; + fn __lasx_xvftint_w_s(a: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftint.l.d"] - fn __lasx_xvftint_l_d(a: v4f64) -> v4i64; + fn __lasx_xvftint_l_d(a: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftint.wu.s"] - fn __lasx_xvftint_wu_s(a: v8f32) -> v8u32; + fn __lasx_xvftint_wu_s(a: __v8f32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvftint.lu.d"] - fn __lasx_xvftint_lu_d(a: v4f64) -> v4u64; + fn __lasx_xvftint_lu_d(a: __v4f64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvftintrz.w.s"] - fn __lasx_xvftintrz_w_s(a: v8f32) -> v8i32; + fn __lasx_xvftintrz_w_s(a: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftintrz.l.d"] - fn __lasx_xvftintrz_l_d(a: v4f64) -> v4i64; + fn __lasx_xvftintrz_l_d(a: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrz.wu.s"] - fn __lasx_xvftintrz_wu_s(a: v8f32) -> v8u32; + fn __lasx_xvftintrz_wu_s(a: __v8f32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvftintrz.lu.d"] - fn __lasx_xvftintrz_lu_d(a: v4f64) -> v4u64; + fn __lasx_xvftintrz_lu_d(a: __v4f64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvffint.s.w"] - fn __lasx_xvffint_s_w(a: v8i32) -> v8f32; + fn __lasx_xvffint_s_w(a: __v8i32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvffint.d.l"] - fn __lasx_xvffint_d_l(a: v4i64) -> v4f64; + fn __lasx_xvffint_d_l(a: __v4i64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvffint.s.wu"] - fn __lasx_xvffint_s_wu(a: v8u32) -> v8f32; + fn __lasx_xvffint_s_wu(a: __v8u32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvffint.d.lu"] - fn __lasx_xvffint_d_lu(a: v4u64) -> v4f64; + fn __lasx_xvffint_d_lu(a: __v4u64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvreplve.b"] - fn __lasx_xvreplve_b(a: v32i8, b: i32) -> v32i8; + fn __lasx_xvreplve_b(a: __v32i8, b: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvreplve.h"] - fn __lasx_xvreplve_h(a: v16i16, b: i32) -> v16i16; + fn __lasx_xvreplve_h(a: __v16i16, b: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvreplve.w"] - fn __lasx_xvreplve_w(a: v8i32, b: i32) -> v8i32; + fn __lasx_xvreplve_w(a: __v8i32, b: i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvreplve.d"] - fn __lasx_xvreplve_d(a: v4i64, b: i32) -> v4i64; + fn __lasx_xvreplve_d(a: __v4i64, b: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpermi.w"] - fn __lasx_xvpermi_w(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvpermi_w(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvandn.v"] - fn __lasx_xvandn_v(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvandn_v(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvneg.b"] - fn __lasx_xvneg_b(a: v32i8) -> v32i8; + fn __lasx_xvneg_b(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvneg.h"] - fn __lasx_xvneg_h(a: v16i16) -> v16i16; + fn __lasx_xvneg_h(a: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvneg.w"] - fn __lasx_xvneg_w(a: v8i32) -> v8i32; + fn __lasx_xvneg_w(a: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvneg.d"] - fn __lasx_xvneg_d(a: v4i64) -> v4i64; + fn __lasx_xvneg_d(a: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmuh.b"] - fn __lasx_xvmuh_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvmuh_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmuh.h"] - fn __lasx_xvmuh_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvmuh_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmuh.w"] - fn __lasx_xvmuh_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvmuh_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmuh.d"] - fn __lasx_xvmuh_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvmuh_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmuh.bu"] - fn __lasx_xvmuh_bu(a: v32u8, b: v32u8) -> v32u8; + fn __lasx_xvmuh_bu(a: __v32u8, b: __v32u8) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvmuh.hu"] - fn __lasx_xvmuh_hu(a: v16u16, b: v16u16) -> v16u16; + fn __lasx_xvmuh_hu(a: __v16u16, b: __v16u16) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvmuh.wu"] - fn __lasx_xvmuh_wu(a: v8u32, b: v8u32) -> v8u32; + fn __lasx_xvmuh_wu(a: __v8u32, b: __v8u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvmuh.du"] - fn __lasx_xvmuh_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvmuh_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvsllwil.h.b"] - fn __lasx_xvsllwil_h_b(a: v32i8, b: u32) -> v16i16; + fn __lasx_xvsllwil_h_b(a: __v32i8, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsllwil.w.h"] - fn __lasx_xvsllwil_w_h(a: v16i16, b: u32) -> v8i32; + fn __lasx_xvsllwil_w_h(a: __v16i16, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsllwil.d.w"] - fn __lasx_xvsllwil_d_w(a: v8i32, b: u32) -> v4i64; + fn __lasx_xvsllwil_d_w(a: __v8i32, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsllwil.hu.bu"] - fn __lasx_xvsllwil_hu_bu(a: v32u8, b: u32) -> v16u16; + fn __lasx_xvsllwil_hu_bu(a: __v32u8, b: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvsllwil.wu.hu"] - fn __lasx_xvsllwil_wu_hu(a: v16u16, b: u32) -> v8u32; + fn __lasx_xvsllwil_wu_hu(a: __v16u16, b: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvsllwil.du.wu"] - fn __lasx_xvsllwil_du_wu(a: v8u32, b: u32) -> v4u64; + fn __lasx_xvsllwil_du_wu(a: __v8u32, b: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvsran.b.h"] - fn __lasx_xvsran_b_h(a: v16i16, b: v16i16) -> v32i8; + fn __lasx_xvsran_b_h(a: __v16i16, b: __v16i16) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsran.h.w"] - fn __lasx_xvsran_h_w(a: v8i32, b: v8i32) -> v16i16; + fn __lasx_xvsran_h_w(a: __v8i32, b: __v8i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsran.w.d"] - fn __lasx_xvsran_w_d(a: v4i64, b: v4i64) -> v8i32; + fn __lasx_xvsran_w_d(a: __v4i64, b: __v4i64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssran.b.h"] - fn __lasx_xvssran_b_h(a: v16i16, b: v16i16) -> v32i8; + fn __lasx_xvssran_b_h(a: __v16i16, b: __v16i16) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssran.h.w"] - fn __lasx_xvssran_h_w(a: v8i32, b: v8i32) -> v16i16; + fn __lasx_xvssran_h_w(a: __v8i32, b: __v8i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssran.w.d"] - fn __lasx_xvssran_w_d(a: v4i64, b: v4i64) -> v8i32; + fn __lasx_xvssran_w_d(a: __v4i64, b: __v4i64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssran.bu.h"] - fn __lasx_xvssran_bu_h(a: v16u16, b: v16u16) -> v32u8; + fn __lasx_xvssran_bu_h(a: __v16u16, b: __v16u16) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssran.hu.w"] - fn __lasx_xvssran_hu_w(a: v8u32, b: v8u32) -> v16u16; + fn __lasx_xvssran_hu_w(a: __v8u32, b: __v8u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssran.wu.d"] - fn __lasx_xvssran_wu_d(a: v4u64, b: v4u64) -> v8u32; + fn __lasx_xvssran_wu_d(a: __v4u64, b: __v4u64) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvsrarn.b.h"] - fn __lasx_xvsrarn_b_h(a: v16i16, b: v16i16) -> v32i8; + fn __lasx_xvsrarn_b_h(a: __v16i16, b: __v16i16) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrarn.h.w"] - fn __lasx_xvsrarn_h_w(a: v8i32, b: v8i32) -> v16i16; + fn __lasx_xvsrarn_h_w(a: __v8i32, b: __v8i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrarn.w.d"] - fn __lasx_xvsrarn_w_d(a: v4i64, b: v4i64) -> v8i32; + fn __lasx_xvsrarn_w_d(a: __v4i64, b: __v4i64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrarn.b.h"] - fn __lasx_xvssrarn_b_h(a: v16i16, b: v16i16) -> v32i8; + fn __lasx_xvssrarn_b_h(a: __v16i16, b: __v16i16) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssrarn.h.w"] - fn __lasx_xvssrarn_h_w(a: v8i32, b: v8i32) -> v16i16; + fn __lasx_xvssrarn_h_w(a: __v8i32, b: __v8i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssrarn.w.d"] - fn __lasx_xvssrarn_w_d(a: v4i64, b: v4i64) -> v8i32; + fn __lasx_xvssrarn_w_d(a: __v4i64, b: __v4i64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrarn.bu.h"] - fn __lasx_xvssrarn_bu_h(a: v16u16, b: v16u16) -> v32u8; + fn __lasx_xvssrarn_bu_h(a: __v16u16, b: __v16u16) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssrarn.hu.w"] - fn __lasx_xvssrarn_hu_w(a: v8u32, b: v8u32) -> v16u16; + fn __lasx_xvssrarn_hu_w(a: __v8u32, b: __v8u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssrarn.wu.d"] - fn __lasx_xvssrarn_wu_d(a: v4u64, b: v4u64) -> v8u32; + fn __lasx_xvssrarn_wu_d(a: __v4u64, b: __v4u64) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvsrln.b.h"] - fn __lasx_xvsrln_b_h(a: v16i16, b: v16i16) -> v32i8; + fn __lasx_xvsrln_b_h(a: __v16i16, b: __v16i16) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrln.h.w"] - fn __lasx_xvsrln_h_w(a: v8i32, b: v8i32) -> v16i16; + fn __lasx_xvsrln_h_w(a: __v8i32, b: __v8i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrln.w.d"] - fn __lasx_xvsrln_w_d(a: v4i64, b: v4i64) -> v8i32; + fn __lasx_xvsrln_w_d(a: __v4i64, b: __v4i64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrln.bu.h"] - fn __lasx_xvssrln_bu_h(a: v16u16, b: v16u16) -> v32u8; + fn __lasx_xvssrln_bu_h(a: __v16u16, b: __v16u16) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssrln.hu.w"] - fn __lasx_xvssrln_hu_w(a: v8u32, b: v8u32) -> v16u16; + fn __lasx_xvssrln_hu_w(a: __v8u32, b: __v8u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssrln.wu.d"] - fn __lasx_xvssrln_wu_d(a: v4u64, b: v4u64) -> v8u32; + fn __lasx_xvssrln_wu_d(a: __v4u64, b: __v4u64) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvsrlrn.b.h"] - fn __lasx_xvsrlrn_b_h(a: v16i16, b: v16i16) -> v32i8; + fn __lasx_xvsrlrn_b_h(a: __v16i16, b: __v16i16) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrlrn.h.w"] - fn __lasx_xvsrlrn_h_w(a: v8i32, b: v8i32) -> v16i16; + fn __lasx_xvsrlrn_h_w(a: __v8i32, b: __v8i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrlrn.w.d"] - fn __lasx_xvsrlrn_w_d(a: v4i64, b: v4i64) -> v8i32; + fn __lasx_xvsrlrn_w_d(a: __v4i64, b: __v4i64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrlrn.bu.h"] - fn __lasx_xvssrlrn_bu_h(a: v16u16, b: v16u16) -> v32u8; + fn __lasx_xvssrlrn_bu_h(a: __v16u16, b: __v16u16) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssrlrn.hu.w"] - fn __lasx_xvssrlrn_hu_w(a: v8u32, b: v8u32) -> v16u16; + fn __lasx_xvssrlrn_hu_w(a: __v8u32, b: __v8u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssrlrn.wu.d"] - fn __lasx_xvssrlrn_wu_d(a: v4u64, b: v4u64) -> v8u32; + fn __lasx_xvssrlrn_wu_d(a: __v4u64, b: __v4u64) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvfrstpi.b"] - fn __lasx_xvfrstpi_b(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvfrstpi_b(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvfrstpi.h"] - fn __lasx_xvfrstpi_h(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvfrstpi_h(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvfrstp.b"] - fn __lasx_xvfrstp_b(a: v32i8, b: v32i8, c: v32i8) -> v32i8; + fn __lasx_xvfrstp_b(a: __v32i8, b: __v32i8, c: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvfrstp.h"] - fn __lasx_xvfrstp_h(a: v16i16, b: v16i16, c: v16i16) -> v16i16; + fn __lasx_xvfrstp_h(a: __v16i16, b: __v16i16, c: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvshuf4i.d"] - fn __lasx_xvshuf4i_d(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvshuf4i_d(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvbsrl.v"] - fn __lasx_xvbsrl_v(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvbsrl_v(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvbsll.v"] - fn __lasx_xvbsll_v(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvbsll_v(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvextrins.b"] - fn __lasx_xvextrins_b(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvextrins_b(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvextrins.h"] - fn __lasx_xvextrins_h(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvextrins_h(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvextrins.w"] - fn __lasx_xvextrins_w(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvextrins_w(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvextrins.d"] - fn __lasx_xvextrins_d(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvextrins_d(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmskltz.b"] - fn __lasx_xvmskltz_b(a: v32i8) -> v32i8; + fn __lasx_xvmskltz_b(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmskltz.h"] - fn __lasx_xvmskltz_h(a: v16i16) -> v16i16; + fn __lasx_xvmskltz_h(a: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmskltz.w"] - fn __lasx_xvmskltz_w(a: v8i32) -> v8i32; + fn __lasx_xvmskltz_w(a: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmskltz.d"] - fn __lasx_xvmskltz_d(a: v4i64) -> v4i64; + fn __lasx_xvmskltz_d(a: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsigncov.b"] - fn __lasx_xvsigncov_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvsigncov_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsigncov.h"] - fn __lasx_xvsigncov_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvsigncov_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsigncov.w"] - fn __lasx_xvsigncov_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvsigncov_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsigncov.d"] - fn __lasx_xvsigncov_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsigncov_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfmadd.s"] - fn __lasx_xvfmadd_s(a: v8f32, b: v8f32, c: v8f32) -> v8f32; + fn __lasx_xvfmadd_s(a: __v8f32, b: __v8f32, c: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfmadd.d"] - fn __lasx_xvfmadd_d(a: v4f64, b: v4f64, c: v4f64) -> v4f64; + fn __lasx_xvfmadd_d(a: __v4f64, b: __v4f64, c: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfmsub.s"] - fn __lasx_xvfmsub_s(a: v8f32, b: v8f32, c: v8f32) -> v8f32; + fn __lasx_xvfmsub_s(a: __v8f32, b: __v8f32, c: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfmsub.d"] - fn __lasx_xvfmsub_d(a: v4f64, b: v4f64, c: v4f64) -> v4f64; + fn __lasx_xvfmsub_d(a: __v4f64, b: __v4f64, c: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfnmadd.s"] - fn __lasx_xvfnmadd_s(a: v8f32, b: v8f32, c: v8f32) -> v8f32; + fn __lasx_xvfnmadd_s(a: __v8f32, b: __v8f32, c: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfnmadd.d"] - fn __lasx_xvfnmadd_d(a: v4f64, b: v4f64, c: v4f64) -> v4f64; + fn __lasx_xvfnmadd_d(a: __v4f64, b: __v4f64, c: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfnmsub.s"] - fn __lasx_xvfnmsub_s(a: v8f32, b: v8f32, c: v8f32) -> v8f32; + fn __lasx_xvfnmsub_s(a: __v8f32, b: __v8f32, c: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfnmsub.d"] - fn __lasx_xvfnmsub_d(a: v4f64, b: v4f64, c: v4f64) -> v4f64; + fn __lasx_xvfnmsub_d(a: __v4f64, b: __v4f64, c: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvftintrne.w.s"] - fn __lasx_xvftintrne_w_s(a: v8f32) -> v8i32; + fn __lasx_xvftintrne_w_s(a: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftintrne.l.d"] - fn __lasx_xvftintrne_l_d(a: v4f64) -> v4i64; + fn __lasx_xvftintrne_l_d(a: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrp.w.s"] - fn __lasx_xvftintrp_w_s(a: v8f32) -> v8i32; + fn __lasx_xvftintrp_w_s(a: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftintrp.l.d"] - fn __lasx_xvftintrp_l_d(a: v4f64) -> v4i64; + fn __lasx_xvftintrp_l_d(a: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrm.w.s"] - fn __lasx_xvftintrm_w_s(a: v8f32) -> v8i32; + fn __lasx_xvftintrm_w_s(a: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftintrm.l.d"] - fn __lasx_xvftintrm_l_d(a: v4f64) -> v4i64; + fn __lasx_xvftintrm_l_d(a: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftint.w.d"] - fn __lasx_xvftint_w_d(a: v4f64, b: v4f64) -> v8i32; + fn __lasx_xvftint_w_d(a: __v4f64, b: __v4f64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvffint.s.l"] - fn __lasx_xvffint_s_l(a: v4i64, b: v4i64) -> v8f32; + fn __lasx_xvffint_s_l(a: __v4i64, b: __v4i64) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvftintrz.w.d"] - fn __lasx_xvftintrz_w_d(a: v4f64, b: v4f64) -> v8i32; + fn __lasx_xvftintrz_w_d(a: __v4f64, b: __v4f64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftintrp.w.d"] - fn __lasx_xvftintrp_w_d(a: v4f64, b: v4f64) -> v8i32; + fn __lasx_xvftintrp_w_d(a: __v4f64, b: __v4f64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftintrm.w.d"] - fn __lasx_xvftintrm_w_d(a: v4f64, b: v4f64) -> v8i32; + fn __lasx_xvftintrm_w_d(a: __v4f64, b: __v4f64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftintrne.w.d"] - fn __lasx_xvftintrne_w_d(a: v4f64, b: v4f64) -> v8i32; + fn __lasx_xvftintrne_w_d(a: __v4f64, b: __v4f64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvftinth.l.s"] - fn __lasx_xvftinth_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftinth_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintl.l.s"] - fn __lasx_xvftintl_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintl_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvffinth.d.w"] - fn __lasx_xvffinth_d_w(a: v8i32) -> v4f64; + fn __lasx_xvffinth_d_w(a: __v8i32) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvffintl.d.w"] - fn __lasx_xvffintl_d_w(a: v8i32) -> v4f64; + fn __lasx_xvffintl_d_w(a: __v8i32) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvftintrzh.l.s"] - fn __lasx_xvftintrzh_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintrzh_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrzl.l.s"] - fn __lasx_xvftintrzl_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintrzl_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrph.l.s"] - fn __lasx_xvftintrph_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintrph_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrpl.l.s"] - fn __lasx_xvftintrpl_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintrpl_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrmh.l.s"] - fn __lasx_xvftintrmh_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintrmh_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrml.l.s"] - fn __lasx_xvftintrml_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintrml_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrneh.l.s"] - fn __lasx_xvftintrneh_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintrneh_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvftintrnel.l.s"] - fn __lasx_xvftintrnel_l_s(a: v8f32) -> v4i64; + fn __lasx_xvftintrnel_l_s(a: __v8f32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfrintrne.s"] - fn __lasx_xvfrintrne_s(a: v8f32) -> v8f32; + fn __lasx_xvfrintrne_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrintrne.d"] - fn __lasx_xvfrintrne_d(a: v4f64) -> v4f64; + fn __lasx_xvfrintrne_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfrintrz.s"] - fn __lasx_xvfrintrz_s(a: v8f32) -> v8f32; + fn __lasx_xvfrintrz_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrintrz.d"] - fn __lasx_xvfrintrz_d(a: v4f64) -> v4f64; + fn __lasx_xvfrintrz_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfrintrp.s"] - fn __lasx_xvfrintrp_s(a: v8f32) -> v8f32; + fn __lasx_xvfrintrp_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrintrp.d"] - fn __lasx_xvfrintrp_d(a: v4f64) -> v4f64; + fn __lasx_xvfrintrp_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvfrintrm.s"] - fn __lasx_xvfrintrm_s(a: v8f32) -> v8f32; + fn __lasx_xvfrintrm_s(a: __v8f32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvfrintrm.d"] - fn __lasx_xvfrintrm_d(a: v4f64) -> v4f64; + fn __lasx_xvfrintrm_d(a: __v4f64) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvld"] - fn __lasx_xvld(a: *const i8, b: i32) -> v32i8; + fn __lasx_xvld(a: *const i8, b: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvst"] - fn __lasx_xvst(a: v32i8, b: *mut i8, c: i32); + fn __lasx_xvst(a: __v32i8, b: *mut i8, c: i32); #[link_name = "llvm.loongarch.lasx.xvstelm.b"] - fn __lasx_xvstelm_b(a: v32i8, b: *mut i8, c: i32, d: u32); + fn __lasx_xvstelm_b(a: __v32i8, b: *mut i8, c: i32, d: u32); #[link_name = "llvm.loongarch.lasx.xvstelm.h"] - fn __lasx_xvstelm_h(a: v16i16, b: *mut i8, c: i32, d: u32); + fn __lasx_xvstelm_h(a: __v16i16, b: *mut i8, c: i32, d: u32); #[link_name = "llvm.loongarch.lasx.xvstelm.w"] - fn __lasx_xvstelm_w(a: v8i32, b: *mut i8, c: i32, d: u32); + fn __lasx_xvstelm_w(a: __v8i32, b: *mut i8, c: i32, d: u32); #[link_name = "llvm.loongarch.lasx.xvstelm.d"] - fn __lasx_xvstelm_d(a: v4i64, b: *mut i8, c: i32, d: u32); + fn __lasx_xvstelm_d(a: __v4i64, b: *mut i8, c: i32, d: u32); #[link_name = "llvm.loongarch.lasx.xvinsve0.w"] - fn __lasx_xvinsve0_w(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvinsve0_w(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvinsve0.d"] - fn __lasx_xvinsve0_d(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvinsve0_d(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpickve.w"] - fn __lasx_xvpickve_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvpickve_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvpickve.d"] - fn __lasx_xvpickve_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvpickve_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvssrlrn.b.h"] - fn __lasx_xvssrlrn_b_h(a: v16i16, b: v16i16) -> v32i8; + fn __lasx_xvssrlrn_b_h(a: __v16i16, b: __v16i16) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssrlrn.h.w"] - fn __lasx_xvssrlrn_h_w(a: v8i32, b: v8i32) -> v16i16; + fn __lasx_xvssrlrn_h_w(a: __v8i32, b: __v8i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssrlrn.w.d"] - fn __lasx_xvssrlrn_w_d(a: v4i64, b: v4i64) -> v8i32; + fn __lasx_xvssrlrn_w_d(a: __v4i64, b: __v4i64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrln.b.h"] - fn __lasx_xvssrln_b_h(a: v16i16, b: v16i16) -> v32i8; + fn __lasx_xvssrln_b_h(a: __v16i16, b: __v16i16) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssrln.h.w"] - fn __lasx_xvssrln_h_w(a: v8i32, b: v8i32) -> v16i16; + fn __lasx_xvssrln_h_w(a: __v8i32, b: __v8i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssrln.w.d"] - fn __lasx_xvssrln_w_d(a: v4i64, b: v4i64) -> v8i32; + fn __lasx_xvssrln_w_d(a: __v4i64, b: __v4i64) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvorn.v"] - fn __lasx_xvorn_v(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvorn_v(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvldi"] - fn __lasx_xvldi(a: i32) -> v4i64; + fn __lasx_xvldi(a: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvldx"] - fn __lasx_xvldx(a: *const i8, b: i64) -> v32i8; + fn __lasx_xvldx(a: *const i8, b: i64) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvstx"] - fn __lasx_xvstx(a: v32i8, b: *mut i8, c: i64); + fn __lasx_xvstx(a: __v32i8, b: *mut i8, c: i64); #[link_name = "llvm.loongarch.lasx.xvextl.qu.du"] - fn __lasx_xvextl_qu_du(a: v4u64) -> v4u64; + fn __lasx_xvextl_qu_du(a: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvinsgr2vr.w"] - fn __lasx_xvinsgr2vr_w(a: v8i32, b: i32, c: u32) -> v8i32; + fn __lasx_xvinsgr2vr_w(a: __v8i32, b: i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvinsgr2vr.d"] - fn __lasx_xvinsgr2vr_d(a: v4i64, b: i64, c: u32) -> v4i64; + fn __lasx_xvinsgr2vr_d(a: __v4i64, b: i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvreplve0.b"] - fn __lasx_xvreplve0_b(a: v32i8) -> v32i8; + fn __lasx_xvreplve0_b(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvreplve0.h"] - fn __lasx_xvreplve0_h(a: v16i16) -> v16i16; + fn __lasx_xvreplve0_h(a: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvreplve0.w"] - fn __lasx_xvreplve0_w(a: v8i32) -> v8i32; + fn __lasx_xvreplve0_w(a: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvreplve0.d"] - fn __lasx_xvreplve0_d(a: v4i64) -> v4i64; + fn __lasx_xvreplve0_d(a: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvreplve0.q"] - fn __lasx_xvreplve0_q(a: v32i8) -> v32i8; + fn __lasx_xvreplve0_q(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.vext2xv.h.b"] - fn __lasx_vext2xv_h_b(a: v32i8) -> v16i16; + fn __lasx_vext2xv_h_b(a: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.vext2xv.w.h"] - fn __lasx_vext2xv_w_h(a: v16i16) -> v8i32; + fn __lasx_vext2xv_w_h(a: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.vext2xv.d.w"] - fn __lasx_vext2xv_d_w(a: v8i32) -> v4i64; + fn __lasx_vext2xv_d_w(a: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.vext2xv.w.b"] - fn __lasx_vext2xv_w_b(a: v32i8) -> v8i32; + fn __lasx_vext2xv_w_b(a: __v32i8) -> __v8i32; #[link_name = "llvm.loongarch.lasx.vext2xv.d.h"] - fn __lasx_vext2xv_d_h(a: v16i16) -> v4i64; + fn __lasx_vext2xv_d_h(a: __v16i16) -> __v4i64; #[link_name = "llvm.loongarch.lasx.vext2xv.d.b"] - fn __lasx_vext2xv_d_b(a: v32i8) -> v4i64; + fn __lasx_vext2xv_d_b(a: __v32i8) -> __v4i64; #[link_name = "llvm.loongarch.lasx.vext2xv.hu.bu"] - fn __lasx_vext2xv_hu_bu(a: v32i8) -> v16i16; + fn __lasx_vext2xv_hu_bu(a: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.vext2xv.wu.hu"] - fn __lasx_vext2xv_wu_hu(a: v16i16) -> v8i32; + fn __lasx_vext2xv_wu_hu(a: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.vext2xv.du.wu"] - fn __lasx_vext2xv_du_wu(a: v8i32) -> v4i64; + fn __lasx_vext2xv_du_wu(a: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.vext2xv.wu.bu"] - fn __lasx_vext2xv_wu_bu(a: v32i8) -> v8i32; + fn __lasx_vext2xv_wu_bu(a: __v32i8) -> __v8i32; #[link_name = "llvm.loongarch.lasx.vext2xv.du.hu"] - fn __lasx_vext2xv_du_hu(a: v16i16) -> v4i64; + fn __lasx_vext2xv_du_hu(a: __v16i16) -> __v4i64; #[link_name = "llvm.loongarch.lasx.vext2xv.du.bu"] - fn __lasx_vext2xv_du_bu(a: v32i8) -> v4i64; + fn __lasx_vext2xv_du_bu(a: __v32i8) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpermi.q"] - fn __lasx_xvpermi_q(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvpermi_q(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvpermi.d"] - fn __lasx_xvpermi_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvpermi_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvperm.w"] - fn __lasx_xvperm_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvperm_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvldrepl.b"] - fn __lasx_xvldrepl_b(a: *const i8, b: i32) -> v32i8; + fn __lasx_xvldrepl_b(a: *const i8, b: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvldrepl.h"] - fn __lasx_xvldrepl_h(a: *const i8, b: i32) -> v16i16; + fn __lasx_xvldrepl_h(a: *const i8, b: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvldrepl.w"] - fn __lasx_xvldrepl_w(a: *const i8, b: i32) -> v8i32; + fn __lasx_xvldrepl_w(a: *const i8, b: i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvldrepl.d"] - fn __lasx_xvldrepl_d(a: *const i8, b: i32) -> v4i64; + fn __lasx_xvldrepl_d(a: *const i8, b: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvpickve2gr.w"] - fn __lasx_xvpickve2gr_w(a: v8i32, b: u32) -> i32; + fn __lasx_xvpickve2gr_w(a: __v8i32, b: u32) -> i32; #[link_name = "llvm.loongarch.lasx.xvpickve2gr.wu"] - fn __lasx_xvpickve2gr_wu(a: v8i32, b: u32) -> u32; + fn __lasx_xvpickve2gr_wu(a: __v8i32, b: u32) -> u32; #[link_name = "llvm.loongarch.lasx.xvpickve2gr.d"] - fn __lasx_xvpickve2gr_d(a: v4i64, b: u32) -> i64; + fn __lasx_xvpickve2gr_d(a: __v4i64, b: u32) -> i64; #[link_name = "llvm.loongarch.lasx.xvpickve2gr.du"] - fn __lasx_xvpickve2gr_du(a: v4i64, b: u32) -> u64; + fn __lasx_xvpickve2gr_du(a: __v4i64, b: u32) -> u64; #[link_name = "llvm.loongarch.lasx.xvaddwev.q.d"] - fn __lasx_xvaddwev_q_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvaddwev_q_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwev.d.w"] - fn __lasx_xvaddwev_d_w(a: v8i32, b: v8i32) -> v4i64; + fn __lasx_xvaddwev_d_w(a: __v8i32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwev.w.h"] - fn __lasx_xvaddwev_w_h(a: v16i16, b: v16i16) -> v8i32; + fn __lasx_xvaddwev_w_h(a: __v16i16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvaddwev.h.b"] - fn __lasx_xvaddwev_h_b(a: v32i8, b: v32i8) -> v16i16; + fn __lasx_xvaddwev_h_b(a: __v32i8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvaddwev.q.du"] - fn __lasx_xvaddwev_q_du(a: v4u64, b: v4u64) -> v4i64; + fn __lasx_xvaddwev_q_du(a: __v4u64, b: __v4u64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwev.d.wu"] - fn __lasx_xvaddwev_d_wu(a: v8u32, b: v8u32) -> v4i64; + fn __lasx_xvaddwev_d_wu(a: __v8u32, b: __v8u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwev.w.hu"] - fn __lasx_xvaddwev_w_hu(a: v16u16, b: v16u16) -> v8i32; + fn __lasx_xvaddwev_w_hu(a: __v16u16, b: __v16u16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvaddwev.h.bu"] - fn __lasx_xvaddwev_h_bu(a: v32u8, b: v32u8) -> v16i16; + fn __lasx_xvaddwev_h_bu(a: __v32u8, b: __v32u8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsubwev.q.d"] - fn __lasx_xvsubwev_q_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsubwev_q_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubwev.d.w"] - fn __lasx_xvsubwev_d_w(a: v8i32, b: v8i32) -> v4i64; + fn __lasx_xvsubwev_d_w(a: __v8i32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubwev.w.h"] - fn __lasx_xvsubwev_w_h(a: v16i16, b: v16i16) -> v8i32; + fn __lasx_xvsubwev_w_h(a: __v16i16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsubwev.h.b"] - fn __lasx_xvsubwev_h_b(a: v32i8, b: v32i8) -> v16i16; + fn __lasx_xvsubwev_h_b(a: __v32i8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsubwev.q.du"] - fn __lasx_xvsubwev_q_du(a: v4u64, b: v4u64) -> v4i64; + fn __lasx_xvsubwev_q_du(a: __v4u64, b: __v4u64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubwev.d.wu"] - fn __lasx_xvsubwev_d_wu(a: v8u32, b: v8u32) -> v4i64; + fn __lasx_xvsubwev_d_wu(a: __v8u32, b: __v8u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubwev.w.hu"] - fn __lasx_xvsubwev_w_hu(a: v16u16, b: v16u16) -> v8i32; + fn __lasx_xvsubwev_w_hu(a: __v16u16, b: __v16u16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsubwev.h.bu"] - fn __lasx_xvsubwev_h_bu(a: v32u8, b: v32u8) -> v16i16; + fn __lasx_xvsubwev_h_bu(a: __v32u8, b: __v32u8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmulwev.q.d"] - fn __lasx_xvmulwev_q_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvmulwev_q_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwev.d.w"] - fn __lasx_xvmulwev_d_w(a: v8i32, b: v8i32) -> v4i64; + fn __lasx_xvmulwev_d_w(a: __v8i32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwev.w.h"] - fn __lasx_xvmulwev_w_h(a: v16i16, b: v16i16) -> v8i32; + fn __lasx_xvmulwev_w_h(a: __v16i16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmulwev.h.b"] - fn __lasx_xvmulwev_h_b(a: v32i8, b: v32i8) -> v16i16; + fn __lasx_xvmulwev_h_b(a: __v32i8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmulwev.q.du"] - fn __lasx_xvmulwev_q_du(a: v4u64, b: v4u64) -> v4i64; + fn __lasx_xvmulwev_q_du(a: __v4u64, b: __v4u64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwev.d.wu"] - fn __lasx_xvmulwev_d_wu(a: v8u32, b: v8u32) -> v4i64; + fn __lasx_xvmulwev_d_wu(a: __v8u32, b: __v8u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwev.w.hu"] - fn __lasx_xvmulwev_w_hu(a: v16u16, b: v16u16) -> v8i32; + fn __lasx_xvmulwev_w_hu(a: __v16u16, b: __v16u16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmulwev.h.bu"] - fn __lasx_xvmulwev_h_bu(a: v32u8, b: v32u8) -> v16i16; + fn __lasx_xvmulwev_h_bu(a: __v32u8, b: __v32u8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvaddwod.q.d"] - fn __lasx_xvaddwod_q_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvaddwod_q_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwod.d.w"] - fn __lasx_xvaddwod_d_w(a: v8i32, b: v8i32) -> v4i64; + fn __lasx_xvaddwod_d_w(a: __v8i32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwod.w.h"] - fn __lasx_xvaddwod_w_h(a: v16i16, b: v16i16) -> v8i32; + fn __lasx_xvaddwod_w_h(a: __v16i16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvaddwod.h.b"] - fn __lasx_xvaddwod_h_b(a: v32i8, b: v32i8) -> v16i16; + fn __lasx_xvaddwod_h_b(a: __v32i8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvaddwod.q.du"] - fn __lasx_xvaddwod_q_du(a: v4u64, b: v4u64) -> v4i64; + fn __lasx_xvaddwod_q_du(a: __v4u64, b: __v4u64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwod.d.wu"] - fn __lasx_xvaddwod_d_wu(a: v8u32, b: v8u32) -> v4i64; + fn __lasx_xvaddwod_d_wu(a: __v8u32, b: __v8u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwod.w.hu"] - fn __lasx_xvaddwod_w_hu(a: v16u16, b: v16u16) -> v8i32; + fn __lasx_xvaddwod_w_hu(a: __v16u16, b: __v16u16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvaddwod.h.bu"] - fn __lasx_xvaddwod_h_bu(a: v32u8, b: v32u8) -> v16i16; + fn __lasx_xvaddwod_h_bu(a: __v32u8, b: __v32u8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsubwod.q.d"] - fn __lasx_xvsubwod_q_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsubwod_q_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubwod.d.w"] - fn __lasx_xvsubwod_d_w(a: v8i32, b: v8i32) -> v4i64; + fn __lasx_xvsubwod_d_w(a: __v8i32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubwod.w.h"] - fn __lasx_xvsubwod_w_h(a: v16i16, b: v16i16) -> v8i32; + fn __lasx_xvsubwod_w_h(a: __v16i16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsubwod.h.b"] - fn __lasx_xvsubwod_h_b(a: v32i8, b: v32i8) -> v16i16; + fn __lasx_xvsubwod_h_b(a: __v32i8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsubwod.q.du"] - fn __lasx_xvsubwod_q_du(a: v4u64, b: v4u64) -> v4i64; + fn __lasx_xvsubwod_q_du(a: __v4u64, b: __v4u64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubwod.d.wu"] - fn __lasx_xvsubwod_d_wu(a: v8u32, b: v8u32) -> v4i64; + fn __lasx_xvsubwod_d_wu(a: __v8u32, b: __v8u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsubwod.w.hu"] - fn __lasx_xvsubwod_w_hu(a: v16u16, b: v16u16) -> v8i32; + fn __lasx_xvsubwod_w_hu(a: __v16u16, b: __v16u16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsubwod.h.bu"] - fn __lasx_xvsubwod_h_bu(a: v32u8, b: v32u8) -> v16i16; + fn __lasx_xvsubwod_h_bu(a: __v32u8, b: __v32u8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmulwod.q.d"] - fn __lasx_xvmulwod_q_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvmulwod_q_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwod.d.w"] - fn __lasx_xvmulwod_d_w(a: v8i32, b: v8i32) -> v4i64; + fn __lasx_xvmulwod_d_w(a: __v8i32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwod.w.h"] - fn __lasx_xvmulwod_w_h(a: v16i16, b: v16i16) -> v8i32; + fn __lasx_xvmulwod_w_h(a: __v16i16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmulwod.h.b"] - fn __lasx_xvmulwod_h_b(a: v32i8, b: v32i8) -> v16i16; + fn __lasx_xvmulwod_h_b(a: __v32i8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmulwod.q.du"] - fn __lasx_xvmulwod_q_du(a: v4u64, b: v4u64) -> v4i64; + fn __lasx_xvmulwod_q_du(a: __v4u64, b: __v4u64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwod.d.wu"] - fn __lasx_xvmulwod_d_wu(a: v8u32, b: v8u32) -> v4i64; + fn __lasx_xvmulwod_d_wu(a: __v8u32, b: __v8u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwod.w.hu"] - fn __lasx_xvmulwod_w_hu(a: v16u16, b: v16u16) -> v8i32; + fn __lasx_xvmulwod_w_hu(a: __v16u16, b: __v16u16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmulwod.h.bu"] - fn __lasx_xvmulwod_h_bu(a: v32u8, b: v32u8) -> v16i16; + fn __lasx_xvmulwod_h_bu(a: __v32u8, b: __v32u8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvaddwev.d.wu.w"] - fn __lasx_xvaddwev_d_wu_w(a: v8u32, b: v8i32) -> v4i64; + fn __lasx_xvaddwev_d_wu_w(a: __v8u32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwev.w.hu.h"] - fn __lasx_xvaddwev_w_hu_h(a: v16u16, b: v16i16) -> v8i32; + fn __lasx_xvaddwev_w_hu_h(a: __v16u16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvaddwev.h.bu.b"] - fn __lasx_xvaddwev_h_bu_b(a: v32u8, b: v32i8) -> v16i16; + fn __lasx_xvaddwev_h_bu_b(a: __v32u8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmulwev.d.wu.w"] - fn __lasx_xvmulwev_d_wu_w(a: v8u32, b: v8i32) -> v4i64; + fn __lasx_xvmulwev_d_wu_w(a: __v8u32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwev.w.hu.h"] - fn __lasx_xvmulwev_w_hu_h(a: v16u16, b: v16i16) -> v8i32; + fn __lasx_xvmulwev_w_hu_h(a: __v16u16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmulwev.h.bu.b"] - fn __lasx_xvmulwev_h_bu_b(a: v32u8, b: v32i8) -> v16i16; + fn __lasx_xvmulwev_h_bu_b(a: __v32u8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvaddwod.d.wu.w"] - fn __lasx_xvaddwod_d_wu_w(a: v8u32, b: v8i32) -> v4i64; + fn __lasx_xvaddwod_d_wu_w(a: __v8u32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwod.w.hu.h"] - fn __lasx_xvaddwod_w_hu_h(a: v16u16, b: v16i16) -> v8i32; + fn __lasx_xvaddwod_w_hu_h(a: __v16u16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvaddwod.h.bu.b"] - fn __lasx_xvaddwod_h_bu_b(a: v32u8, b: v32i8) -> v16i16; + fn __lasx_xvaddwod_h_bu_b(a: __v32u8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmulwod.d.wu.w"] - fn __lasx_xvmulwod_d_wu_w(a: v8u32, b: v8i32) -> v4i64; + fn __lasx_xvmulwod_d_wu_w(a: __v8u32, b: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwod.w.hu.h"] - fn __lasx_xvmulwod_w_hu_h(a: v16u16, b: v16i16) -> v8i32; + fn __lasx_xvmulwod_w_hu_h(a: __v16u16, b: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmulwod.h.bu.b"] - fn __lasx_xvmulwod_h_bu_b(a: v32u8, b: v32i8) -> v16i16; + fn __lasx_xvmulwod_h_bu_b(a: __v32u8, b: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvhaddw.q.d"] - fn __lasx_xvhaddw_q_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvhaddw_q_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvhaddw.qu.du"] - fn __lasx_xvhaddw_qu_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvhaddw_qu_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvhsubw.q.d"] - fn __lasx_xvhsubw_q_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvhsubw_q_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvhsubw.qu.du"] - fn __lasx_xvhsubw_qu_du(a: v4u64, b: v4u64) -> v4u64; + fn __lasx_xvhsubw_qu_du(a: __v4u64, b: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmaddwev.q.d"] - fn __lasx_xvmaddwev_q_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64; + fn __lasx_xvmaddwev_q_d(a: __v4i64, b: __v4i64, c: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaddwev.d.w"] - fn __lasx_xvmaddwev_d_w(a: v4i64, b: v8i32, c: v8i32) -> v4i64; + fn __lasx_xvmaddwev_d_w(a: __v4i64, b: __v8i32, c: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaddwev.w.h"] - fn __lasx_xvmaddwev_w_h(a: v8i32, b: v16i16, c: v16i16) -> v8i32; + fn __lasx_xvmaddwev_w_h(a: __v8i32, b: __v16i16, c: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmaddwev.h.b"] - fn __lasx_xvmaddwev_h_b(a: v16i16, b: v32i8, c: v32i8) -> v16i16; + fn __lasx_xvmaddwev_h_b(a: __v16i16, b: __v32i8, c: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmaddwev.q.du"] - fn __lasx_xvmaddwev_q_du(a: v4u64, b: v4u64, c: v4u64) -> v4u64; + fn __lasx_xvmaddwev_q_du(a: __v4u64, b: __v4u64, c: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmaddwev.d.wu"] - fn __lasx_xvmaddwev_d_wu(a: v4u64, b: v8u32, c: v8u32) -> v4u64; + fn __lasx_xvmaddwev_d_wu(a: __v4u64, b: __v8u32, c: __v8u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmaddwev.w.hu"] - fn __lasx_xvmaddwev_w_hu(a: v8u32, b: v16u16, c: v16u16) -> v8u32; + fn __lasx_xvmaddwev_w_hu(a: __v8u32, b: __v16u16, c: __v16u16) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvmaddwev.h.bu"] - fn __lasx_xvmaddwev_h_bu(a: v16u16, b: v32u8, c: v32u8) -> v16u16; + fn __lasx_xvmaddwev_h_bu(a: __v16u16, b: __v32u8, c: __v32u8) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvmaddwod.q.d"] - fn __lasx_xvmaddwod_q_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64; + fn __lasx_xvmaddwod_q_d(a: __v4i64, b: __v4i64, c: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaddwod.d.w"] - fn __lasx_xvmaddwod_d_w(a: v4i64, b: v8i32, c: v8i32) -> v4i64; + fn __lasx_xvmaddwod_d_w(a: __v4i64, b: __v8i32, c: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaddwod.w.h"] - fn __lasx_xvmaddwod_w_h(a: v8i32, b: v16i16, c: v16i16) -> v8i32; + fn __lasx_xvmaddwod_w_h(a: __v8i32, b: __v16i16, c: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmaddwod.h.b"] - fn __lasx_xvmaddwod_h_b(a: v16i16, b: v32i8, c: v32i8) -> v16i16; + fn __lasx_xvmaddwod_h_b(a: __v16i16, b: __v32i8, c: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmaddwod.q.du"] - fn __lasx_xvmaddwod_q_du(a: v4u64, b: v4u64, c: v4u64) -> v4u64; + fn __lasx_xvmaddwod_q_du(a: __v4u64, b: __v4u64, c: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmaddwod.d.wu"] - fn __lasx_xvmaddwod_d_wu(a: v4u64, b: v8u32, c: v8u32) -> v4u64; + fn __lasx_xvmaddwod_d_wu(a: __v4u64, b: __v8u32, c: __v8u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvmaddwod.w.hu"] - fn __lasx_xvmaddwod_w_hu(a: v8u32, b: v16u16, c: v16u16) -> v8u32; + fn __lasx_xvmaddwod_w_hu(a: __v8u32, b: __v16u16, c: __v16u16) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvmaddwod.h.bu"] - fn __lasx_xvmaddwod_h_bu(a: v16u16, b: v32u8, c: v32u8) -> v16u16; + fn __lasx_xvmaddwod_h_bu(a: __v16u16, b: __v32u8, c: __v32u8) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvmaddwev.q.du.d"] - fn __lasx_xvmaddwev_q_du_d(a: v4i64, b: v4u64, c: v4i64) -> v4i64; + fn __lasx_xvmaddwev_q_du_d(a: __v4i64, b: __v4u64, c: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaddwev.d.wu.w"] - fn __lasx_xvmaddwev_d_wu_w(a: v4i64, b: v8u32, c: v8i32) -> v4i64; + fn __lasx_xvmaddwev_d_wu_w(a: __v4i64, b: __v8u32, c: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaddwev.w.hu.h"] - fn __lasx_xvmaddwev_w_hu_h(a: v8i32, b: v16u16, c: v16i16) -> v8i32; + fn __lasx_xvmaddwev_w_hu_h(a: __v8i32, b: __v16u16, c: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmaddwev.h.bu.b"] - fn __lasx_xvmaddwev_h_bu_b(a: v16i16, b: v32u8, c: v32i8) -> v16i16; + fn __lasx_xvmaddwev_h_bu_b(a: __v16i16, b: __v32u8, c: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvmaddwod.q.du.d"] - fn __lasx_xvmaddwod_q_du_d(a: v4i64, b: v4u64, c: v4i64) -> v4i64; + fn __lasx_xvmaddwod_q_du_d(a: __v4i64, b: __v4u64, c: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaddwod.d.wu.w"] - fn __lasx_xvmaddwod_d_wu_w(a: v4i64, b: v8u32, c: v8i32) -> v4i64; + fn __lasx_xvmaddwod_d_wu_w(a: __v4i64, b: __v8u32, c: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmaddwod.w.hu.h"] - fn __lasx_xvmaddwod_w_hu_h(a: v8i32, b: v16u16, c: v16i16) -> v8i32; + fn __lasx_xvmaddwod_w_hu_h(a: __v8i32, b: __v16u16, c: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvmaddwod.h.bu.b"] - fn __lasx_xvmaddwod_h_bu_b(a: v16i16, b: v32u8, c: v32i8) -> v16i16; + fn __lasx_xvmaddwod_h_bu_b(a: __v16i16, b: __v32u8, c: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvrotr.b"] - fn __lasx_xvrotr_b(a: v32i8, b: v32i8) -> v32i8; + fn __lasx_xvrotr_b(a: __v32i8, b: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvrotr.h"] - fn __lasx_xvrotr_h(a: v16i16, b: v16i16) -> v16i16; + fn __lasx_xvrotr_h(a: __v16i16, b: __v16i16) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvrotr.w"] - fn __lasx_xvrotr_w(a: v8i32, b: v8i32) -> v8i32; + fn __lasx_xvrotr_w(a: __v8i32, b: __v8i32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvrotr.d"] - fn __lasx_xvrotr_d(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvrotr_d(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvadd.q"] - fn __lasx_xvadd_q(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvadd_q(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsub.q"] - fn __lasx_xvsub_q(a: v4i64, b: v4i64) -> v4i64; + fn __lasx_xvsub_q(a: __v4i64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwev.q.du.d"] - fn __lasx_xvaddwev_q_du_d(a: v4u64, b: v4i64) -> v4i64; + fn __lasx_xvaddwev_q_du_d(a: __v4u64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvaddwod.q.du.d"] - fn __lasx_xvaddwod_q_du_d(a: v4u64, b: v4i64) -> v4i64; + fn __lasx_xvaddwod_q_du_d(a: __v4u64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwev.q.du.d"] - fn __lasx_xvmulwev_q_du_d(a: v4u64, b: v4i64) -> v4i64; + fn __lasx_xvmulwev_q_du_d(a: __v4u64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmulwod.q.du.d"] - fn __lasx_xvmulwod_q_du_d(a: v4u64, b: v4i64) -> v4i64; + fn __lasx_xvmulwod_q_du_d(a: __v4u64, b: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvmskgez.b"] - fn __lasx_xvmskgez_b(a: v32i8) -> v32i8; + fn __lasx_xvmskgez_b(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvmsknz.b"] - fn __lasx_xvmsknz_b(a: v32i8) -> v32i8; + fn __lasx_xvmsknz_b(a: __v32i8) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvexth.h.b"] - fn __lasx_xvexth_h_b(a: v32i8) -> v16i16; + fn __lasx_xvexth_h_b(a: __v32i8) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvexth.w.h"] - fn __lasx_xvexth_w_h(a: v16i16) -> v8i32; + fn __lasx_xvexth_w_h(a: __v16i16) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvexth.d.w"] - fn __lasx_xvexth_d_w(a: v8i32) -> v4i64; + fn __lasx_xvexth_d_w(a: __v8i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvexth.q.d"] - fn __lasx_xvexth_q_d(a: v4i64) -> v4i64; + fn __lasx_xvexth_q_d(a: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvexth.hu.bu"] - fn __lasx_xvexth_hu_bu(a: v32u8) -> v16u16; + fn __lasx_xvexth_hu_bu(a: __v32u8) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvexth.wu.hu"] - fn __lasx_xvexth_wu_hu(a: v16u16) -> v8u32; + fn __lasx_xvexth_wu_hu(a: __v16u16) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvexth.du.wu"] - fn __lasx_xvexth_du_wu(a: v8u32) -> v4u64; + fn __lasx_xvexth_du_wu(a: __v8u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvexth.qu.du"] - fn __lasx_xvexth_qu_du(a: v4u64) -> v4u64; + fn __lasx_xvexth_qu_du(a: __v4u64) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvrotri.b"] - fn __lasx_xvrotri_b(a: v32i8, b: u32) -> v32i8; + fn __lasx_xvrotri_b(a: __v32i8, b: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvrotri.h"] - fn __lasx_xvrotri_h(a: v16i16, b: u32) -> v16i16; + fn __lasx_xvrotri_h(a: __v16i16, b: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvrotri.w"] - fn __lasx_xvrotri_w(a: v8i32, b: u32) -> v8i32; + fn __lasx_xvrotri_w(a: __v8i32, b: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvrotri.d"] - fn __lasx_xvrotri_d(a: v4i64, b: u32) -> v4i64; + fn __lasx_xvrotri_d(a: __v4i64, b: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvextl.q.d"] - fn __lasx_xvextl_q_d(a: v4i64) -> v4i64; + fn __lasx_xvextl_q_d(a: __v4i64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrlni.b.h"] - fn __lasx_xvsrlni_b_h(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvsrlni_b_h(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrlni.h.w"] - fn __lasx_xvsrlni_h_w(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvsrlni_h_w(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrlni.w.d"] - fn __lasx_xvsrlni_w_d(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvsrlni_w_d(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrlni.d.q"] - fn __lasx_xvsrlni_d_q(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvsrlni_d_q(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrlrni.b.h"] - fn __lasx_xvsrlrni_b_h(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvsrlrni_b_h(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrlrni.h.w"] - fn __lasx_xvsrlrni_h_w(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvsrlrni_h_w(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrlrni.w.d"] - fn __lasx_xvsrlrni_w_d(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvsrlrni_w_d(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrlrni.d.q"] - fn __lasx_xvsrlrni_d_q(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvsrlrni_d_q(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvssrlni.b.h"] - fn __lasx_xvssrlni_b_h(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvssrlni_b_h(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssrlni.h.w"] - fn __lasx_xvssrlni_h_w(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvssrlni_h_w(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssrlni.w.d"] - fn __lasx_xvssrlni_w_d(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvssrlni_w_d(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrlni.d.q"] - fn __lasx_xvssrlni_d_q(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvssrlni_d_q(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvssrlni.bu.h"] - fn __lasx_xvssrlni_bu_h(a: v32u8, b: v32i8, c: u32) -> v32u8; + fn __lasx_xvssrlni_bu_h(a: __v32u8, b: __v32i8, c: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssrlni.hu.w"] - fn __lasx_xvssrlni_hu_w(a: v16u16, b: v16i16, c: u32) -> v16u16; + fn __lasx_xvssrlni_hu_w(a: __v16u16, b: __v16i16, c: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssrlni.wu.d"] - fn __lasx_xvssrlni_wu_d(a: v8u32, b: v8i32, c: u32) -> v8u32; + fn __lasx_xvssrlni_wu_d(a: __v8u32, b: __v8i32, c: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvssrlni.du.q"] - fn __lasx_xvssrlni_du_q(a: v4u64, b: v4i64, c: u32) -> v4u64; + fn __lasx_xvssrlni_du_q(a: __v4u64, b: __v4i64, c: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvssrlrni.b.h"] - fn __lasx_xvssrlrni_b_h(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvssrlrni_b_h(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssrlrni.h.w"] - fn __lasx_xvssrlrni_h_w(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvssrlrni_h_w(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssrlrni.w.d"] - fn __lasx_xvssrlrni_w_d(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvssrlrni_w_d(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrlrni.d.q"] - fn __lasx_xvssrlrni_d_q(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvssrlrni_d_q(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvssrlrni.bu.h"] - fn __lasx_xvssrlrni_bu_h(a: v32u8, b: v32i8, c: u32) -> v32u8; + fn __lasx_xvssrlrni_bu_h(a: __v32u8, b: __v32i8, c: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssrlrni.hu.w"] - fn __lasx_xvssrlrni_hu_w(a: v16u16, b: v16i16, c: u32) -> v16u16; + fn __lasx_xvssrlrni_hu_w(a: __v16u16, b: __v16i16, c: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssrlrni.wu.d"] - fn __lasx_xvssrlrni_wu_d(a: v8u32, b: v8i32, c: u32) -> v8u32; + fn __lasx_xvssrlrni_wu_d(a: __v8u32, b: __v8i32, c: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvssrlrni.du.q"] - fn __lasx_xvssrlrni_du_q(a: v4u64, b: v4i64, c: u32) -> v4u64; + fn __lasx_xvssrlrni_du_q(a: __v4u64, b: __v4i64, c: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvsrani.b.h"] - fn __lasx_xvsrani_b_h(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvsrani_b_h(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrani.h.w"] - fn __lasx_xvsrani_h_w(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvsrani_h_w(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrani.w.d"] - fn __lasx_xvsrani_w_d(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvsrani_w_d(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrani.d.q"] - fn __lasx_xvsrani_d_q(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvsrani_d_q(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvsrarni.b.h"] - fn __lasx_xvsrarni_b_h(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvsrarni_b_h(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvsrarni.h.w"] - fn __lasx_xvsrarni_h_w(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvsrarni_h_w(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvsrarni.w.d"] - fn __lasx_xvsrarni_w_d(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvsrarni_w_d(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvsrarni.d.q"] - fn __lasx_xvsrarni_d_q(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvsrarni_d_q(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvssrani.b.h"] - fn __lasx_xvssrani_b_h(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvssrani_b_h(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssrani.h.w"] - fn __lasx_xvssrani_h_w(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvssrani_h_w(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssrani.w.d"] - fn __lasx_xvssrani_w_d(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvssrani_w_d(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrani.d.q"] - fn __lasx_xvssrani_d_q(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvssrani_d_q(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvssrani.bu.h"] - fn __lasx_xvssrani_bu_h(a: v32u8, b: v32i8, c: u32) -> v32u8; + fn __lasx_xvssrani_bu_h(a: __v32u8, b: __v32i8, c: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssrani.hu.w"] - fn __lasx_xvssrani_hu_w(a: v16u16, b: v16i16, c: u32) -> v16u16; + fn __lasx_xvssrani_hu_w(a: __v16u16, b: __v16i16, c: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssrani.wu.d"] - fn __lasx_xvssrani_wu_d(a: v8u32, b: v8i32, c: u32) -> v8u32; + fn __lasx_xvssrani_wu_d(a: __v8u32, b: __v8i32, c: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvssrani.du.q"] - fn __lasx_xvssrani_du_q(a: v4u64, b: v4i64, c: u32) -> v4u64; + fn __lasx_xvssrani_du_q(a: __v4u64, b: __v4i64, c: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xvssrarni.b.h"] - fn __lasx_xvssrarni_b_h(a: v32i8, b: v32i8, c: u32) -> v32i8; + fn __lasx_xvssrarni_b_h(a: __v32i8, b: __v32i8, c: u32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvssrarni.h.w"] - fn __lasx_xvssrarni_h_w(a: v16i16, b: v16i16, c: u32) -> v16i16; + fn __lasx_xvssrarni_h_w(a: __v16i16, b: __v16i16, c: u32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvssrarni.w.d"] - fn __lasx_xvssrarni_w_d(a: v8i32, b: v8i32, c: u32) -> v8i32; + fn __lasx_xvssrarni_w_d(a: __v8i32, b: __v8i32, c: u32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvssrarni.d.q"] - fn __lasx_xvssrarni_d_q(a: v4i64, b: v4i64, c: u32) -> v4i64; + fn __lasx_xvssrarni_d_q(a: __v4i64, b: __v4i64, c: u32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvssrarni.bu.h"] - fn __lasx_xvssrarni_bu_h(a: v32u8, b: v32i8, c: u32) -> v32u8; + fn __lasx_xvssrarni_bu_h(a: __v32u8, b: __v32i8, c: u32) -> __v32u8; #[link_name = "llvm.loongarch.lasx.xvssrarni.hu.w"] - fn __lasx_xvssrarni_hu_w(a: v16u16, b: v16i16, c: u32) -> v16u16; + fn __lasx_xvssrarni_hu_w(a: __v16u16, b: __v16i16, c: u32) -> __v16u16; #[link_name = "llvm.loongarch.lasx.xvssrarni.wu.d"] - fn __lasx_xvssrarni_wu_d(a: v8u32, b: v8i32, c: u32) -> v8u32; + fn __lasx_xvssrarni_wu_d(a: __v8u32, b: __v8i32, c: u32) -> __v8u32; #[link_name = "llvm.loongarch.lasx.xvssrarni.du.q"] - fn __lasx_xvssrarni_du_q(a: v4u64, b: v4i64, c: u32) -> v4u64; + fn __lasx_xvssrarni_du_q(a: __v4u64, b: __v4i64, c: u32) -> __v4u64; #[link_name = "llvm.loongarch.lasx.xbnz.b"] - fn __lasx_xbnz_b(a: v32u8) -> i32; + fn __lasx_xbnz_b(a: __v32u8) -> i32; #[link_name = "llvm.loongarch.lasx.xbnz.d"] - fn __lasx_xbnz_d(a: v4u64) -> i32; + fn __lasx_xbnz_d(a: __v4u64) -> i32; #[link_name = "llvm.loongarch.lasx.xbnz.h"] - fn __lasx_xbnz_h(a: v16u16) -> i32; + fn __lasx_xbnz_h(a: __v16u16) -> i32; #[link_name = "llvm.loongarch.lasx.xbnz.v"] - fn __lasx_xbnz_v(a: v32u8) -> i32; + fn __lasx_xbnz_v(a: __v32u8) -> i32; #[link_name = "llvm.loongarch.lasx.xbnz.w"] - fn __lasx_xbnz_w(a: v8u32) -> i32; + fn __lasx_xbnz_w(a: __v8u32) -> i32; #[link_name = "llvm.loongarch.lasx.xbz.b"] - fn __lasx_xbz_b(a: v32u8) -> i32; + fn __lasx_xbz_b(a: __v32u8) -> i32; #[link_name = "llvm.loongarch.lasx.xbz.d"] - fn __lasx_xbz_d(a: v4u64) -> i32; + fn __lasx_xbz_d(a: __v4u64) -> i32; #[link_name = "llvm.loongarch.lasx.xbz.h"] - fn __lasx_xbz_h(a: v16u16) -> i32; + fn __lasx_xbz_h(a: __v16u16) -> i32; #[link_name = "llvm.loongarch.lasx.xbz.v"] - fn __lasx_xbz_v(a: v32u8) -> i32; + fn __lasx_xbz_v(a: __v32u8) -> i32; #[link_name = "llvm.loongarch.lasx.xbz.w"] - fn __lasx_xbz_w(a: v8u32) -> i32; + fn __lasx_xbz_w(a: __v8u32) -> i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.caf.d"] - fn __lasx_xvfcmp_caf_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_caf_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.caf.s"] - fn __lasx_xvfcmp_caf_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_caf_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.ceq.d"] - fn __lasx_xvfcmp_ceq_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_ceq_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.ceq.s"] - fn __lasx_xvfcmp_ceq_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_ceq_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.cle.d"] - fn __lasx_xvfcmp_cle_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_cle_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.cle.s"] - fn __lasx_xvfcmp_cle_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_cle_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.clt.d"] - fn __lasx_xvfcmp_clt_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_clt_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.clt.s"] - fn __lasx_xvfcmp_clt_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_clt_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.cne.d"] - fn __lasx_xvfcmp_cne_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_cne_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.cne.s"] - fn __lasx_xvfcmp_cne_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_cne_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.cor.d"] - fn __lasx_xvfcmp_cor_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_cor_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.cor.s"] - fn __lasx_xvfcmp_cor_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_cor_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.cueq.d"] - fn __lasx_xvfcmp_cueq_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_cueq_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.cueq.s"] - fn __lasx_xvfcmp_cueq_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_cueq_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.cule.d"] - fn __lasx_xvfcmp_cule_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_cule_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.cule.s"] - fn __lasx_xvfcmp_cule_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_cule_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.cult.d"] - fn __lasx_xvfcmp_cult_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_cult_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.cult.s"] - fn __lasx_xvfcmp_cult_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_cult_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.cun.d"] - fn __lasx_xvfcmp_cun_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_cun_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.cune.d"] - fn __lasx_xvfcmp_cune_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_cune_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.cune.s"] - fn __lasx_xvfcmp_cune_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_cune_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.cun.s"] - fn __lasx_xvfcmp_cun_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_cun_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.saf.d"] - fn __lasx_xvfcmp_saf_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_saf_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.saf.s"] - fn __lasx_xvfcmp_saf_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_saf_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.seq.d"] - fn __lasx_xvfcmp_seq_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_seq_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.seq.s"] - fn __lasx_xvfcmp_seq_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_seq_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.sle.d"] - fn __lasx_xvfcmp_sle_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_sle_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.sle.s"] - fn __lasx_xvfcmp_sle_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_sle_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.slt.d"] - fn __lasx_xvfcmp_slt_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_slt_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.slt.s"] - fn __lasx_xvfcmp_slt_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_slt_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.sne.d"] - fn __lasx_xvfcmp_sne_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_sne_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.sne.s"] - fn __lasx_xvfcmp_sne_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_sne_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.sor.d"] - fn __lasx_xvfcmp_sor_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_sor_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.sor.s"] - fn __lasx_xvfcmp_sor_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_sor_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.sueq.d"] - fn __lasx_xvfcmp_sueq_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_sueq_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.sueq.s"] - fn __lasx_xvfcmp_sueq_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_sueq_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.sule.d"] - fn __lasx_xvfcmp_sule_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_sule_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.sule.s"] - fn __lasx_xvfcmp_sule_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_sule_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.sult.d"] - fn __lasx_xvfcmp_sult_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_sult_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.sult.s"] - fn __lasx_xvfcmp_sult_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_sult_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.sun.d"] - fn __lasx_xvfcmp_sun_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_sun_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.sune.d"] - fn __lasx_xvfcmp_sune_d(a: v4f64, b: v4f64) -> v4i64; + fn __lasx_xvfcmp_sune_d(a: __v4f64, b: __v4f64) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvfcmp.sune.s"] - fn __lasx_xvfcmp_sune_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_sune_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvfcmp.sun.s"] - fn __lasx_xvfcmp_sun_s(a: v8f32, b: v8f32) -> v8i32; + fn __lasx_xvfcmp_sun_s(a: __v8f32, b: __v8f32) -> __v8i32; #[link_name = "llvm.loongarch.lasx.xvpickve.d.f"] - fn __lasx_xvpickve_d_f(a: v4f64, b: u32) -> v4f64; + fn __lasx_xvpickve_d_f(a: __v4f64, b: u32) -> __v4f64; #[link_name = "llvm.loongarch.lasx.xvpickve.w.f"] - fn __lasx_xvpickve_w_f(a: v8f32, b: u32) -> v8f32; + fn __lasx_xvpickve_w_f(a: __v8f32, b: u32) -> __v8f32; #[link_name = "llvm.loongarch.lasx.xvrepli.b"] - fn __lasx_xvrepli_b(a: i32) -> v32i8; + fn __lasx_xvrepli_b(a: i32) -> __v32i8; #[link_name = "llvm.loongarch.lasx.xvrepli.d"] - fn __lasx_xvrepli_d(a: i32) -> v4i64; + fn __lasx_xvrepli_d(a: i32) -> __v4i64; #[link_name = "llvm.loongarch.lasx.xvrepli.h"] - fn __lasx_xvrepli_h(a: i32) -> v16i16; + fn __lasx_xvrepli_h(a: i32) -> __v16i16; #[link_name = "llvm.loongarch.lasx.xvrepli.w"] - fn __lasx_xvrepli_w(a: i32) -> v8i32; + fn __lasx_xvrepli_w(a: i32) -> __v8i32; } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsll_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsll_b(a, b) } +pub fn lasx_xvsll_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsll_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsll_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsll_h(a, b) } +pub fn lasx_xvsll_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsll_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsll_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsll_w(a, b) } +pub fn lasx_xvsll_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsll_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsll_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsll_d(a, b) } +pub fn lasx_xvsll_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsll_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslli_b(a: v32i8) -> v32i8 { +pub fn lasx_xvslli_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvslli_b(a, IMM3) } + unsafe { transmute(__lasx_xvslli_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslli_h(a: v16i16) -> v16i16 { +pub fn lasx_xvslli_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvslli_h(a, IMM4) } + unsafe { transmute(__lasx_xvslli_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslli_w(a: v8i32) -> v8i32 { +pub fn lasx_xvslli_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslli_w(a, IMM5) } + unsafe { transmute(__lasx_xvslli_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslli_d(a: v4i64) -> v4i64 { +pub fn lasx_xvslli_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvslli_d(a, IMM6) } + unsafe { transmute(__lasx_xvslli_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsra_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsra_b(a, b) } +pub fn lasx_xvsra_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsra_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsra_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsra_h(a, b) } +pub fn lasx_xvsra_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsra_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsra_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsra_w(a, b) } +pub fn lasx_xvsra_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsra_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsra_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsra_d(a, b) } +pub fn lasx_xvsra_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsra_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrai_b(a: v32i8) -> v32i8 { +pub fn lasx_xvsrai_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvsrai_b(a, IMM3) } + unsafe { transmute(__lasx_xvsrai_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrai_h(a: v16i16) -> v16i16 { +pub fn lasx_xvsrai_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsrai_h(a, IMM4) } + unsafe { transmute(__lasx_xvsrai_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrai_w(a: v8i32) -> v8i32 { +pub fn lasx_xvsrai_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsrai_w(a, IMM5) } + unsafe { transmute(__lasx_xvsrai_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrai_d(a: v4i64) -> v4i64 { +pub fn lasx_xvsrai_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsrai_d(a, IMM6) } + unsafe { transmute(__lasx_xvsrai_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrar_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsrar_b(a, b) } +pub fn lasx_xvsrar_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrar_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrar_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsrar_h(a, b) } +pub fn lasx_xvsrar_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrar_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrar_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsrar_w(a, b) } +pub fn lasx_xvsrar_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrar_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrar_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsrar_d(a, b) } +pub fn lasx_xvsrar_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrar_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrari_b(a: v32i8) -> v32i8 { +pub fn lasx_xvsrari_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvsrari_b(a, IMM3) } + unsafe { transmute(__lasx_xvsrari_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrari_h(a: v16i16) -> v16i16 { +pub fn lasx_xvsrari_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsrari_h(a, IMM4) } + unsafe { transmute(__lasx_xvsrari_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrari_w(a: v8i32) -> v8i32 { +pub fn lasx_xvsrari_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsrari_w(a, IMM5) } + unsafe { transmute(__lasx_xvsrari_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrari_d(a: v4i64) -> v4i64 { +pub fn lasx_xvsrari_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsrari_d(a, IMM6) } + unsafe { transmute(__lasx_xvsrari_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrl_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsrl_b(a, b) } +pub fn lasx_xvsrl_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrl_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrl_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsrl_h(a, b) } +pub fn lasx_xvsrl_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrl_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrl_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsrl_w(a, b) } +pub fn lasx_xvsrl_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrl_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrl_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsrl_d(a, b) } +pub fn lasx_xvsrl_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrl_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrli_b(a: v32i8) -> v32i8 { +pub fn lasx_xvsrli_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvsrli_b(a, IMM3) } + unsafe { transmute(__lasx_xvsrli_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrli_h(a: v16i16) -> v16i16 { +pub fn lasx_xvsrli_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsrli_h(a, IMM4) } + unsafe { transmute(__lasx_xvsrli_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrli_w(a: v8i32) -> v8i32 { +pub fn lasx_xvsrli_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsrli_w(a, IMM5) } + unsafe { transmute(__lasx_xvsrli_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrli_d(a: v4i64) -> v4i64 { +pub fn lasx_xvsrli_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsrli_d(a, IMM6) } + unsafe { transmute(__lasx_xvsrli_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlr_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsrlr_b(a, b) } +pub fn lasx_xvsrlr_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrlr_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlr_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsrlr_h(a, b) } +pub fn lasx_xvsrlr_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrlr_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlr_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsrlr_w(a, b) } +pub fn lasx_xvsrlr_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrlr_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlr_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsrlr_d(a, b) } +pub fn lasx_xvsrlr_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrlr_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlri_b(a: v32i8) -> v32i8 { +pub fn lasx_xvsrlri_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvsrlri_b(a, IMM3) } + unsafe { transmute(__lasx_xvsrlri_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlri_h(a: v16i16) -> v16i16 { +pub fn lasx_xvsrlri_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsrlri_h(a, IMM4) } + unsafe { transmute(__lasx_xvsrlri_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlri_w(a: v8i32) -> v8i32 { +pub fn lasx_xvsrlri_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsrlri_w(a, IMM5) } + unsafe { transmute(__lasx_xvsrlri_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlri_d(a: v4i64) -> v4i64 { +pub fn lasx_xvsrlri_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsrlri_d(a, IMM6) } + unsafe { transmute(__lasx_xvsrlri_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitclr_b(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvbitclr_b(a, b) } +pub fn lasx_xvbitclr_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitclr_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitclr_h(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvbitclr_h(a, b) } +pub fn lasx_xvbitclr_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitclr_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitclr_w(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvbitclr_w(a, b) } +pub fn lasx_xvbitclr_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitclr_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitclr_d(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvbitclr_d(a, b) } +pub fn lasx_xvbitclr_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitclr_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitclri_b(a: v32u8) -> v32u8 { +pub fn lasx_xvbitclri_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvbitclri_b(a, IMM3) } + unsafe { transmute(__lasx_xvbitclri_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitclri_h(a: v16u16) -> v16u16 { +pub fn lasx_xvbitclri_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvbitclri_h(a, IMM4) } + unsafe { transmute(__lasx_xvbitclri_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitclri_w(a: v8u32) -> v8u32 { +pub fn lasx_xvbitclri_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvbitclri_w(a, IMM5) } + unsafe { transmute(__lasx_xvbitclri_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitclri_d(a: v4u64) -> v4u64 { +pub fn lasx_xvbitclri_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvbitclri_d(a, IMM6) } + unsafe { transmute(__lasx_xvbitclri_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitset_b(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvbitset_b(a, b) } +pub fn lasx_xvbitset_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitset_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitset_h(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvbitset_h(a, b) } +pub fn lasx_xvbitset_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitset_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitset_w(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvbitset_w(a, b) } +pub fn lasx_xvbitset_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitset_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitset_d(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvbitset_d(a, b) } +pub fn lasx_xvbitset_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitset_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitseti_b(a: v32u8) -> v32u8 { +pub fn lasx_xvbitseti_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvbitseti_b(a, IMM3) } + unsafe { transmute(__lasx_xvbitseti_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitseti_h(a: v16u16) -> v16u16 { +pub fn lasx_xvbitseti_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvbitseti_h(a, IMM4) } + unsafe { transmute(__lasx_xvbitseti_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitseti_w(a: v8u32) -> v8u32 { +pub fn lasx_xvbitseti_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvbitseti_w(a, IMM5) } + unsafe { transmute(__lasx_xvbitseti_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitseti_d(a: v4u64) -> v4u64 { +pub fn lasx_xvbitseti_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvbitseti_d(a, IMM6) } + unsafe { transmute(__lasx_xvbitseti_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitrev_b(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvbitrev_b(a, b) } +pub fn lasx_xvbitrev_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitrev_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitrev_h(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvbitrev_h(a, b) } +pub fn lasx_xvbitrev_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitrev_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitrev_w(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvbitrev_w(a, b) } +pub fn lasx_xvbitrev_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitrev_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitrev_d(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvbitrev_d(a, b) } +pub fn lasx_xvbitrev_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitrev_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitrevi_b(a: v32u8) -> v32u8 { +pub fn lasx_xvbitrevi_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvbitrevi_b(a, IMM3) } + unsafe { transmute(__lasx_xvbitrevi_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitrevi_h(a: v16u16) -> v16u16 { +pub fn lasx_xvbitrevi_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvbitrevi_h(a, IMM4) } + unsafe { transmute(__lasx_xvbitrevi_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitrevi_w(a: v8u32) -> v8u32 { +pub fn lasx_xvbitrevi_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvbitrevi_w(a, IMM5) } + unsafe { transmute(__lasx_xvbitrevi_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitrevi_d(a: v4u64) -> v4u64 { +pub fn lasx_xvbitrevi_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvbitrevi_d(a, IMM6) } + unsafe { transmute(__lasx_xvbitrevi_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadd_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvadd_b(a, b) } +pub fn lasx_xvadd_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadd_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadd_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvadd_h(a, b) } +pub fn lasx_xvadd_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadd_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadd_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvadd_w(a, b) } +pub fn lasx_xvadd_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadd_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadd_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvadd_d(a, b) } +pub fn lasx_xvadd_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadd_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddi_bu(a: v32i8) -> v32i8 { +pub fn lasx_xvaddi_bu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvaddi_bu(a, IMM5) } + unsafe { transmute(__lasx_xvaddi_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddi_hu(a: v16i16) -> v16i16 { +pub fn lasx_xvaddi_hu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvaddi_hu(a, IMM5) } + unsafe { transmute(__lasx_xvaddi_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddi_wu(a: v8i32) -> v8i32 { +pub fn lasx_xvaddi_wu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvaddi_wu(a, IMM5) } + unsafe { transmute(__lasx_xvaddi_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddi_du(a: v4i64) -> v4i64 { +pub fn lasx_xvaddi_du(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvaddi_du(a, IMM5) } + unsafe { transmute(__lasx_xvaddi_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsub_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsub_b(a, b) } +pub fn lasx_xvsub_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsub_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsub_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsub_h(a, b) } +pub fn lasx_xvsub_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsub_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsub_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsub_w(a, b) } +pub fn lasx_xvsub_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsub_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsub_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsub_d(a, b) } +pub fn lasx_xvsub_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsub_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubi_bu(a: v32i8) -> v32i8 { +pub fn lasx_xvsubi_bu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsubi_bu(a, IMM5) } + unsafe { transmute(__lasx_xvsubi_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubi_hu(a: v16i16) -> v16i16 { +pub fn lasx_xvsubi_hu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsubi_hu(a, IMM5) } + unsafe { transmute(__lasx_xvsubi_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubi_wu(a: v8i32) -> v8i32 { +pub fn lasx_xvsubi_wu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsubi_wu(a, IMM5) } + unsafe { transmute(__lasx_xvsubi_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubi_du(a: v4i64) -> v4i64 { +pub fn lasx_xvsubi_du(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsubi_du(a, IMM5) } + unsafe { transmute(__lasx_xvsubi_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmax_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvmax_b(a, b) } +pub fn lasx_xvmax_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmax_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmax_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvmax_h(a, b) } +pub fn lasx_xvmax_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmax_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmax_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvmax_w(a, b) } +pub fn lasx_xvmax_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmax_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmax_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmax_d(a, b) } +pub fn lasx_xvmax_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmax_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaxi_b(a: v32i8) -> v32i8 { +pub fn lasx_xvmaxi_b(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvmaxi_b(a, IMM_S5) } + unsafe { transmute(__lasx_xvmaxi_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaxi_h(a: v16i16) -> v16i16 { +pub fn lasx_xvmaxi_h(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvmaxi_h(a, IMM_S5) } + unsafe { transmute(__lasx_xvmaxi_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaxi_w(a: v8i32) -> v8i32 { +pub fn lasx_xvmaxi_w(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvmaxi_w(a, IMM_S5) } + unsafe { transmute(__lasx_xvmaxi_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaxi_d(a: v4i64) -> v4i64 { +pub fn lasx_xvmaxi_d(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvmaxi_d(a, IMM_S5) } + unsafe { transmute(__lasx_xvmaxi_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmax_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvmax_bu(a, b) } +pub fn lasx_xvmax_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmax_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmax_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvmax_hu(a, b) } +pub fn lasx_xvmax_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmax_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmax_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvmax_wu(a, b) } +pub fn lasx_xvmax_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmax_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmax_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvmax_du(a, b) } +pub fn lasx_xvmax_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmax_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaxi_bu(a: v32u8) -> v32u8 { +pub fn lasx_xvmaxi_bu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvmaxi_bu(a, IMM5) } + unsafe { transmute(__lasx_xvmaxi_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaxi_hu(a: v16u16) -> v16u16 { +pub fn lasx_xvmaxi_hu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvmaxi_hu(a, IMM5) } + unsafe { transmute(__lasx_xvmaxi_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaxi_wu(a: v8u32) -> v8u32 { +pub fn lasx_xvmaxi_wu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvmaxi_wu(a, IMM5) } + unsafe { transmute(__lasx_xvmaxi_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaxi_du(a: v4u64) -> v4u64 { +pub fn lasx_xvmaxi_du(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvmaxi_du(a, IMM5) } + unsafe { transmute(__lasx_xvmaxi_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmin_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvmin_b(a, b) } +pub fn lasx_xvmin_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmin_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmin_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvmin_h(a, b) } +pub fn lasx_xvmin_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmin_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmin_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvmin_w(a, b) } +pub fn lasx_xvmin_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmin_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmin_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmin_d(a, b) } +pub fn lasx_xvmin_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmin_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmini_b(a: v32i8) -> v32i8 { +pub fn lasx_xvmini_b(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvmini_b(a, IMM_S5) } + unsafe { transmute(__lasx_xvmini_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmini_h(a: v16i16) -> v16i16 { +pub fn lasx_xvmini_h(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvmini_h(a, IMM_S5) } + unsafe { transmute(__lasx_xvmini_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmini_w(a: v8i32) -> v8i32 { +pub fn lasx_xvmini_w(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvmini_w(a, IMM_S5) } + unsafe { transmute(__lasx_xvmini_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmini_d(a: v4i64) -> v4i64 { +pub fn lasx_xvmini_d(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvmini_d(a, IMM_S5) } + unsafe { transmute(__lasx_xvmini_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmin_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvmin_bu(a, b) } +pub fn lasx_xvmin_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmin_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmin_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvmin_hu(a, b) } +pub fn lasx_xvmin_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmin_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmin_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvmin_wu(a, b) } +pub fn lasx_xvmin_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmin_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmin_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvmin_du(a, b) } +pub fn lasx_xvmin_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmin_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmini_bu(a: v32u8) -> v32u8 { +pub fn lasx_xvmini_bu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvmini_bu(a, IMM5) } + unsafe { transmute(__lasx_xvmini_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmini_hu(a: v16u16) -> v16u16 { +pub fn lasx_xvmini_hu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvmini_hu(a, IMM5) } + unsafe { transmute(__lasx_xvmini_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmini_wu(a: v8u32) -> v8u32 { +pub fn lasx_xvmini_wu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvmini_wu(a, IMM5) } + unsafe { transmute(__lasx_xvmini_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmini_du(a: v4u64) -> v4u64 { +pub fn lasx_xvmini_du(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvmini_du(a, IMM5) } + unsafe { transmute(__lasx_xvmini_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvseq_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvseq_b(a, b) } +pub fn lasx_xvseq_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvseq_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvseq_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvseq_h(a, b) } +pub fn lasx_xvseq_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvseq_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvseq_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvseq_w(a, b) } +pub fn lasx_xvseq_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvseq_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvseq_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvseq_d(a, b) } +pub fn lasx_xvseq_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvseq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvseqi_b(a: v32i8) -> v32i8 { +pub fn lasx_xvseqi_b(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvseqi_b(a, IMM_S5) } + unsafe { transmute(__lasx_xvseqi_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvseqi_h(a: v16i16) -> v16i16 { +pub fn lasx_xvseqi_h(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvseqi_h(a, IMM_S5) } + unsafe { transmute(__lasx_xvseqi_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvseqi_w(a: v8i32) -> v8i32 { +pub fn lasx_xvseqi_w(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvseqi_w(a, IMM_S5) } + unsafe { transmute(__lasx_xvseqi_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvseqi_d(a: v4i64) -> v4i64 { +pub fn lasx_xvseqi_d(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvseqi_d(a, IMM_S5) } + unsafe { transmute(__lasx_xvseqi_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslt_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvslt_b(a, b) } +pub fn lasx_xvslt_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvslt_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslt_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvslt_h(a, b) } +pub fn lasx_xvslt_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvslt_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslt_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvslt_w(a, b) } +pub fn lasx_xvslt_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvslt_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslt_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvslt_d(a, b) } +pub fn lasx_xvslt_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvslt_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslti_b(a: v32i8) -> v32i8 { +pub fn lasx_xvslti_b(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvslti_b(a, IMM_S5) } + unsafe { transmute(__lasx_xvslti_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslti_h(a: v16i16) -> v16i16 { +pub fn lasx_xvslti_h(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvslti_h(a, IMM_S5) } + unsafe { transmute(__lasx_xvslti_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslti_w(a: v8i32) -> v8i32 { +pub fn lasx_xvslti_w(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvslti_w(a, IMM_S5) } + unsafe { transmute(__lasx_xvslti_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslti_d(a: v4i64) -> v4i64 { +pub fn lasx_xvslti_d(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvslti_d(a, IMM_S5) } + unsafe { transmute(__lasx_xvslti_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslt_bu(a: v32u8, b: v32u8) -> v32i8 { - unsafe { __lasx_xvslt_bu(a, b) } +pub fn lasx_xvslt_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvslt_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslt_hu(a: v16u16, b: v16u16) -> v16i16 { - unsafe { __lasx_xvslt_hu(a, b) } +pub fn lasx_xvslt_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvslt_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslt_wu(a: v8u32, b: v8u32) -> v8i32 { - unsafe { __lasx_xvslt_wu(a, b) } +pub fn lasx_xvslt_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvslt_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslt_du(a: v4u64, b: v4u64) -> v4i64 { - unsafe { __lasx_xvslt_du(a, b) } +pub fn lasx_xvslt_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvslt_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslti_bu(a: v32u8) -> v32i8 { +pub fn lasx_xvslti_bu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslti_bu(a, IMM5) } + unsafe { transmute(__lasx_xvslti_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslti_hu(a: v16u16) -> v16i16 { +pub fn lasx_xvslti_hu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslti_hu(a, IMM5) } + unsafe { transmute(__lasx_xvslti_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslti_wu(a: v8u32) -> v8i32 { +pub fn lasx_xvslti_wu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslti_wu(a, IMM5) } + unsafe { transmute(__lasx_xvslti_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslti_du(a: v4u64) -> v4i64 { +pub fn lasx_xvslti_du(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslti_du(a, IMM5) } + unsafe { transmute(__lasx_xvslti_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsle_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsle_b(a, b) } +pub fn lasx_xvsle_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsle_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsle_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsle_h(a, b) } +pub fn lasx_xvsle_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsle_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsle_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsle_w(a, b) } +pub fn lasx_xvsle_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsle_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsle_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsle_d(a, b) } +pub fn lasx_xvsle_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsle_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslei_b(a: v32i8) -> v32i8 { +pub fn lasx_xvslei_b(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvslei_b(a, IMM_S5) } + unsafe { transmute(__lasx_xvslei_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslei_h(a: v16i16) -> v16i16 { +pub fn lasx_xvslei_h(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvslei_h(a, IMM_S5) } + unsafe { transmute(__lasx_xvslei_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslei_w(a: v8i32) -> v8i32 { +pub fn lasx_xvslei_w(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvslei_w(a, IMM_S5) } + unsafe { transmute(__lasx_xvslei_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslei_d(a: v4i64) -> v4i64 { +pub fn lasx_xvslei_d(a: m256i) -> m256i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lasx_xvslei_d(a, IMM_S5) } + unsafe { transmute(__lasx_xvslei_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsle_bu(a: v32u8, b: v32u8) -> v32i8 { - unsafe { __lasx_xvsle_bu(a, b) } +pub fn lasx_xvsle_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsle_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsle_hu(a: v16u16, b: v16u16) -> v16i16 { - unsafe { __lasx_xvsle_hu(a, b) } +pub fn lasx_xvsle_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsle_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsle_wu(a: v8u32, b: v8u32) -> v8i32 { - unsafe { __lasx_xvsle_wu(a, b) } +pub fn lasx_xvsle_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsle_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsle_du(a: v4u64, b: v4u64) -> v4i64 { - unsafe { __lasx_xvsle_du(a, b) } +pub fn lasx_xvsle_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsle_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslei_bu(a: v32u8) -> v32i8 { +pub fn lasx_xvslei_bu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslei_bu(a, IMM5) } + unsafe { transmute(__lasx_xvslei_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslei_hu(a: v16u16) -> v16i16 { +pub fn lasx_xvslei_hu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslei_hu(a, IMM5) } + unsafe { transmute(__lasx_xvslei_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslei_wu(a: v8u32) -> v8i32 { +pub fn lasx_xvslei_wu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslei_wu(a, IMM5) } + unsafe { transmute(__lasx_xvslei_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvslei_du(a: v4u64) -> v4i64 { +pub fn lasx_xvslei_du(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvslei_du(a, IMM5) } + unsafe { transmute(__lasx_xvslei_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsat_b(a: v32i8) -> v32i8 { +pub fn lasx_xvsat_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvsat_b(a, IMM3) } + unsafe { transmute(__lasx_xvsat_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsat_h(a: v16i16) -> v16i16 { +pub fn lasx_xvsat_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsat_h(a, IMM4) } + unsafe { transmute(__lasx_xvsat_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsat_w(a: v8i32) -> v8i32 { +pub fn lasx_xvsat_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsat_w(a, IMM5) } + unsafe { transmute(__lasx_xvsat_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsat_d(a: v4i64) -> v4i64 { +pub fn lasx_xvsat_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsat_d(a, IMM6) } + unsafe { transmute(__lasx_xvsat_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsat_bu(a: v32u8) -> v32u8 { +pub fn lasx_xvsat_bu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvsat_bu(a, IMM3) } + unsafe { transmute(__lasx_xvsat_bu(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsat_hu(a: v16u16) -> v16u16 { +pub fn lasx_xvsat_hu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsat_hu(a, IMM4) } + unsafe { transmute(__lasx_xvsat_hu(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsat_wu(a: v8u32) -> v8u32 { +pub fn lasx_xvsat_wu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsat_wu(a, IMM5) } + unsafe { transmute(__lasx_xvsat_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsat_du(a: v4u64) -> v4u64 { +pub fn lasx_xvsat_du(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsat_du(a, IMM6) } + unsafe { transmute(__lasx_xvsat_du(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadda_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvadda_b(a, b) } +pub fn lasx_xvadda_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadda_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadda_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvadda_h(a, b) } +pub fn lasx_xvadda_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadda_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadda_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvadda_w(a, b) } +pub fn lasx_xvadda_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadda_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadda_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvadda_d(a, b) } +pub fn lasx_xvadda_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadda_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsadd_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsadd_b(a, b) } +pub fn lasx_xvsadd_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsadd_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsadd_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsadd_h(a, b) } +pub fn lasx_xvsadd_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsadd_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsadd_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsadd_w(a, b) } +pub fn lasx_xvsadd_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsadd_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsadd_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsadd_d(a, b) } +pub fn lasx_xvsadd_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsadd_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsadd_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvsadd_bu(a, b) } +pub fn lasx_xvsadd_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsadd_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsadd_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvsadd_hu(a, b) } +pub fn lasx_xvsadd_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsadd_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsadd_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvsadd_wu(a, b) } +pub fn lasx_xvsadd_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsadd_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsadd_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvsadd_du(a, b) } +pub fn lasx_xvsadd_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsadd_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavg_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvavg_b(a, b) } +pub fn lasx_xvavg_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavg_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavg_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvavg_h(a, b) } +pub fn lasx_xvavg_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavg_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavg_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvavg_w(a, b) } +pub fn lasx_xvavg_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavg_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavg_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvavg_d(a, b) } +pub fn lasx_xvavg_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavg_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavg_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvavg_bu(a, b) } +pub fn lasx_xvavg_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavg_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavg_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvavg_hu(a, b) } +pub fn lasx_xvavg_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavg_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavg_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvavg_wu(a, b) } +pub fn lasx_xvavg_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavg_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavg_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvavg_du(a, b) } +pub fn lasx_xvavg_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavg_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavgr_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvavgr_b(a, b) } +pub fn lasx_xvavgr_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavgr_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavgr_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvavgr_h(a, b) } +pub fn lasx_xvavgr_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavgr_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavgr_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvavgr_w(a, b) } +pub fn lasx_xvavgr_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavgr_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavgr_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvavgr_d(a, b) } +pub fn lasx_xvavgr_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavgr_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavgr_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvavgr_bu(a, b) } +pub fn lasx_xvavgr_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavgr_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavgr_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvavgr_hu(a, b) } +pub fn lasx_xvavgr_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavgr_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavgr_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvavgr_wu(a, b) } +pub fn lasx_xvavgr_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavgr_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvavgr_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvavgr_du(a, b) } +pub fn lasx_xvavgr_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvavgr_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssub_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvssub_b(a, b) } +pub fn lasx_xvssub_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssub_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssub_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvssub_h(a, b) } +pub fn lasx_xvssub_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssub_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssub_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvssub_w(a, b) } +pub fn lasx_xvssub_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssub_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssub_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvssub_d(a, b) } +pub fn lasx_xvssub_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssub_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssub_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvssub_bu(a, b) } +pub fn lasx_xvssub_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssub_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssub_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvssub_hu(a, b) } +pub fn lasx_xvssub_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssub_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssub_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvssub_wu(a, b) } +pub fn lasx_xvssub_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssub_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssub_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvssub_du(a, b) } +pub fn lasx_xvssub_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssub_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvabsd_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvabsd_b(a, b) } +pub fn lasx_xvabsd_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvabsd_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvabsd_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvabsd_h(a, b) } +pub fn lasx_xvabsd_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvabsd_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvabsd_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvabsd_w(a, b) } +pub fn lasx_xvabsd_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvabsd_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvabsd_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvabsd_d(a, b) } +pub fn lasx_xvabsd_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvabsd_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvabsd_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvabsd_bu(a, b) } +pub fn lasx_xvabsd_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvabsd_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvabsd_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvabsd_hu(a, b) } +pub fn lasx_xvabsd_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvabsd_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvabsd_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvabsd_wu(a, b) } +pub fn lasx_xvabsd_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvabsd_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvabsd_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvabsd_du(a, b) } +pub fn lasx_xvabsd_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvabsd_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmul_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvmul_b(a, b) } +pub fn lasx_xvmul_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmul_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmul_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvmul_h(a, b) } +pub fn lasx_xvmul_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmul_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmul_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvmul_w(a, b) } +pub fn lasx_xvmul_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmul_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmul_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmul_d(a, b) } +pub fn lasx_xvmul_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmul_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmadd_b(a: v32i8, b: v32i8, c: v32i8) -> v32i8 { - unsafe { __lasx_xvmadd_b(a, b, c) } +pub fn lasx_xvmadd_b(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmadd_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmadd_h(a: v16i16, b: v16i16, c: v16i16) -> v16i16 { - unsafe { __lasx_xvmadd_h(a, b, c) } +pub fn lasx_xvmadd_h(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmadd_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmadd_w(a: v8i32, b: v8i32, c: v8i32) -> v8i32 { - unsafe { __lasx_xvmadd_w(a, b, c) } +pub fn lasx_xvmadd_w(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmadd_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmadd_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64 { - unsafe { __lasx_xvmadd_d(a, b, c) } +pub fn lasx_xvmadd_d(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmadd_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmsub_b(a: v32i8, b: v32i8, c: v32i8) -> v32i8 { - unsafe { __lasx_xvmsub_b(a, b, c) } +pub fn lasx_xvmsub_b(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmsub_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmsub_h(a: v16i16, b: v16i16, c: v16i16) -> v16i16 { - unsafe { __lasx_xvmsub_h(a, b, c) } +pub fn lasx_xvmsub_h(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmsub_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmsub_w(a: v8i32, b: v8i32, c: v8i32) -> v8i32 { - unsafe { __lasx_xvmsub_w(a, b, c) } +pub fn lasx_xvmsub_w(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmsub_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmsub_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64 { - unsafe { __lasx_xvmsub_d(a, b, c) } +pub fn lasx_xvmsub_d(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmsub_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvdiv_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvdiv_b(a, b) } +pub fn lasx_xvdiv_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvdiv_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvdiv_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvdiv_h(a, b) } +pub fn lasx_xvdiv_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvdiv_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvdiv_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvdiv_w(a, b) } +pub fn lasx_xvdiv_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvdiv_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvdiv_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvdiv_d(a, b) } +pub fn lasx_xvdiv_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvdiv_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvdiv_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvdiv_bu(a, b) } +pub fn lasx_xvdiv_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvdiv_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvdiv_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvdiv_hu(a, b) } +pub fn lasx_xvdiv_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvdiv_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvdiv_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvdiv_wu(a, b) } +pub fn lasx_xvdiv_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvdiv_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvdiv_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvdiv_du(a, b) } +pub fn lasx_xvdiv_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvdiv_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhaddw_h_b(a: v32i8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvhaddw_h_b(a, b) } +pub fn lasx_xvhaddw_h_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhaddw_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhaddw_w_h(a: v16i16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvhaddw_w_h(a, b) } +pub fn lasx_xvhaddw_w_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhaddw_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhaddw_d_w(a: v8i32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvhaddw_d_w(a, b) } +pub fn lasx_xvhaddw_d_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhaddw_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhaddw_hu_bu(a: v32u8, b: v32u8) -> v16u16 { - unsafe { __lasx_xvhaddw_hu_bu(a, b) } +pub fn lasx_xvhaddw_hu_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhaddw_hu_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhaddw_wu_hu(a: v16u16, b: v16u16) -> v8u32 { - unsafe { __lasx_xvhaddw_wu_hu(a, b) } +pub fn lasx_xvhaddw_wu_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhaddw_wu_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhaddw_du_wu(a: v8u32, b: v8u32) -> v4u64 { - unsafe { __lasx_xvhaddw_du_wu(a, b) } +pub fn lasx_xvhaddw_du_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhaddw_du_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhsubw_h_b(a: v32i8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvhsubw_h_b(a, b) } +pub fn lasx_xvhsubw_h_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhsubw_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhsubw_w_h(a: v16i16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvhsubw_w_h(a, b) } +pub fn lasx_xvhsubw_w_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhsubw_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhsubw_d_w(a: v8i32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvhsubw_d_w(a, b) } +pub fn lasx_xvhsubw_d_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhsubw_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhsubw_hu_bu(a: v32u8, b: v32u8) -> v16i16 { - unsafe { __lasx_xvhsubw_hu_bu(a, b) } +pub fn lasx_xvhsubw_hu_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhsubw_hu_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhsubw_wu_hu(a: v16u16, b: v16u16) -> v8i32 { - unsafe { __lasx_xvhsubw_wu_hu(a, b) } +pub fn lasx_xvhsubw_wu_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhsubw_wu_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhsubw_du_wu(a: v8u32, b: v8u32) -> v4i64 { - unsafe { __lasx_xvhsubw_du_wu(a, b) } +pub fn lasx_xvhsubw_du_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhsubw_du_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmod_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvmod_b(a, b) } +pub fn lasx_xvmod_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmod_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmod_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvmod_h(a, b) } +pub fn lasx_xvmod_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmod_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmod_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvmod_w(a, b) } +pub fn lasx_xvmod_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmod_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmod_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmod_d(a, b) } +pub fn lasx_xvmod_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmod_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmod_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvmod_bu(a, b) } +pub fn lasx_xvmod_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmod_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmod_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvmod_hu(a, b) } +pub fn lasx_xvmod_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmod_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmod_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvmod_wu(a, b) } +pub fn lasx_xvmod_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmod_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmod_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvmod_du(a, b) } +pub fn lasx_xvmod_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmod_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrepl128vei_b(a: v32i8) -> v32i8 { +pub fn lasx_xvrepl128vei_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvrepl128vei_b(a, IMM4) } + unsafe { transmute(__lasx_xvrepl128vei_b(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrepl128vei_h(a: v16i16) -> v16i16 { +pub fn lasx_xvrepl128vei_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvrepl128vei_h(a, IMM3) } + unsafe { transmute(__lasx_xvrepl128vei_h(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrepl128vei_w(a: v8i32) -> v8i32 { +pub fn lasx_xvrepl128vei_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lasx_xvrepl128vei_w(a, IMM2) } + unsafe { transmute(__lasx_xvrepl128vei_w(transmute(a), IMM2)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrepl128vei_d(a: v4i64) -> v4i64 { +pub fn lasx_xvrepl128vei_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM1, 1); - unsafe { __lasx_xvrepl128vei_d(a, IMM1) } + unsafe { transmute(__lasx_xvrepl128vei_d(transmute(a), IMM1)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickev_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvpickev_b(a, b) } +pub fn lasx_xvpickev_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpickev_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickev_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvpickev_h(a, b) } +pub fn lasx_xvpickev_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpickev_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickev_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvpickev_w(a, b) } +pub fn lasx_xvpickev_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpickev_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickev_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvpickev_d(a, b) } +pub fn lasx_xvpickev_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpickev_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickod_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvpickod_b(a, b) } +pub fn lasx_xvpickod_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpickod_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickod_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvpickod_h(a, b) } +pub fn lasx_xvpickod_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpickod_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickod_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvpickod_w(a, b) } +pub fn lasx_xvpickod_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpickod_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickod_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvpickod_d(a, b) } +pub fn lasx_xvpickod_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpickod_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvilvh_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvilvh_b(a, b) } +pub fn lasx_xvilvh_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvilvh_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvilvh_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvilvh_h(a, b) } +pub fn lasx_xvilvh_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvilvh_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvilvh_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvilvh_w(a, b) } +pub fn lasx_xvilvh_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvilvh_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvilvh_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvilvh_d(a, b) } +pub fn lasx_xvilvh_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvilvh_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvilvl_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvilvl_b(a, b) } +pub fn lasx_xvilvl_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvilvl_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvilvl_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvilvl_h(a, b) } +pub fn lasx_xvilvl_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvilvl_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvilvl_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvilvl_w(a, b) } +pub fn lasx_xvilvl_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvilvl_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvilvl_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvilvl_d(a, b) } +pub fn lasx_xvilvl_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvilvl_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpackev_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvpackev_b(a, b) } +pub fn lasx_xvpackev_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpackev_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpackev_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvpackev_h(a, b) } +pub fn lasx_xvpackev_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpackev_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpackev_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvpackev_w(a, b) } +pub fn lasx_xvpackev_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpackev_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpackev_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvpackev_d(a, b) } +pub fn lasx_xvpackev_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpackev_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpackod_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvpackod_b(a, b) } +pub fn lasx_xvpackod_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpackod_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpackod_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvpackod_h(a, b) } +pub fn lasx_xvpackod_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpackod_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpackod_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvpackod_w(a, b) } +pub fn lasx_xvpackod_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpackod_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpackod_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvpackod_d(a, b) } +pub fn lasx_xvpackod_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvpackod_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvshuf_b(a: v32i8, b: v32i8, c: v32i8) -> v32i8 { - unsafe { __lasx_xvshuf_b(a, b, c) } +pub fn lasx_xvshuf_b(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvshuf_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvshuf_h(a: v16i16, b: v16i16, c: v16i16) -> v16i16 { - unsafe { __lasx_xvshuf_h(a, b, c) } +pub fn lasx_xvshuf_h(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvshuf_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvshuf_w(a: v8i32, b: v8i32, c: v8i32) -> v8i32 { - unsafe { __lasx_xvshuf_w(a, b, c) } +pub fn lasx_xvshuf_w(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvshuf_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvshuf_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64 { - unsafe { __lasx_xvshuf_d(a, b, c) } +pub fn lasx_xvshuf_d(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvshuf_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvand_v(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvand_v(a, b) } +pub fn lasx_xvand_v(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvand_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvandi_b(a: v32u8) -> v32u8 { +pub fn lasx_xvandi_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvandi_b(a, IMM8) } + unsafe { transmute(__lasx_xvandi_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvor_v(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvor_v(a, b) } +pub fn lasx_xvor_v(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvor_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvori_b(a: v32u8) -> v32u8 { +pub fn lasx_xvori_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvori_b(a, IMM8) } + unsafe { transmute(__lasx_xvori_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvnor_v(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvnor_v(a, b) } +pub fn lasx_xvnor_v(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvnor_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvnori_b(a: v32u8) -> v32u8 { +pub fn lasx_xvnori_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvnori_b(a, IMM8) } + unsafe { transmute(__lasx_xvnori_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvxor_v(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvxor_v(a, b) } +pub fn lasx_xvxor_v(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvxor_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvxori_b(a: v32u8) -> v32u8 { +pub fn lasx_xvxori_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvxori_b(a, IMM8) } + unsafe { transmute(__lasx_xvxori_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitsel_v(a: v32u8, b: v32u8, c: v32u8) -> v32u8 { - unsafe { __lasx_xvbitsel_v(a, b, c) } +pub fn lasx_xvbitsel_v(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvbitsel_v(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbitseli_b(a: v32u8, b: v32u8) -> v32u8 { +pub fn lasx_xvbitseli_b(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvbitseli_b(a, b, IMM8) } + unsafe { transmute(__lasx_xvbitseli_b(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvshuf4i_b(a: v32i8) -> v32i8 { +pub fn lasx_xvshuf4i_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvshuf4i_b(a, IMM8) } + unsafe { transmute(__lasx_xvshuf4i_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvshuf4i_h(a: v16i16) -> v16i16 { +pub fn lasx_xvshuf4i_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvshuf4i_h(a, IMM8) } + unsafe { transmute(__lasx_xvshuf4i_h(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvshuf4i_w(a: v8i32) -> v8i32 { +pub fn lasx_xvshuf4i_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvshuf4i_w(a, IMM8) } + unsafe { transmute(__lasx_xvshuf4i_w(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplgr2vr_b(a: i32) -> v32i8 { - unsafe { __lasx_xvreplgr2vr_b(a) } +pub fn lasx_xvreplgr2vr_b(a: i32) -> m256i { + unsafe { transmute(__lasx_xvreplgr2vr_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplgr2vr_h(a: i32) -> v16i16 { - unsafe { __lasx_xvreplgr2vr_h(a) } +pub fn lasx_xvreplgr2vr_h(a: i32) -> m256i { + unsafe { transmute(__lasx_xvreplgr2vr_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplgr2vr_w(a: i32) -> v8i32 { - unsafe { __lasx_xvreplgr2vr_w(a) } +pub fn lasx_xvreplgr2vr_w(a: i32) -> m256i { + unsafe { transmute(__lasx_xvreplgr2vr_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplgr2vr_d(a: i64) -> v4i64 { - unsafe { __lasx_xvreplgr2vr_d(a) } +pub fn lasx_xvreplgr2vr_d(a: i64) -> m256i { + unsafe { transmute(__lasx_xvreplgr2vr_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpcnt_b(a: v32i8) -> v32i8 { - unsafe { __lasx_xvpcnt_b(a) } +pub fn lasx_xvpcnt_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvpcnt_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpcnt_h(a: v16i16) -> v16i16 { - unsafe { __lasx_xvpcnt_h(a) } +pub fn lasx_xvpcnt_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvpcnt_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpcnt_w(a: v8i32) -> v8i32 { - unsafe { __lasx_xvpcnt_w(a) } +pub fn lasx_xvpcnt_w(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvpcnt_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpcnt_d(a: v4i64) -> v4i64 { - unsafe { __lasx_xvpcnt_d(a) } +pub fn lasx_xvpcnt_d(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvpcnt_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvclo_b(a: v32i8) -> v32i8 { - unsafe { __lasx_xvclo_b(a) } +pub fn lasx_xvclo_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvclo_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvclo_h(a: v16i16) -> v16i16 { - unsafe { __lasx_xvclo_h(a) } +pub fn lasx_xvclo_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvclo_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvclo_w(a: v8i32) -> v8i32 { - unsafe { __lasx_xvclo_w(a) } +pub fn lasx_xvclo_w(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvclo_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvclo_d(a: v4i64) -> v4i64 { - unsafe { __lasx_xvclo_d(a) } +pub fn lasx_xvclo_d(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvclo_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvclz_b(a: v32i8) -> v32i8 { - unsafe { __lasx_xvclz_b(a) } +pub fn lasx_xvclz_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvclz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvclz_h(a: v16i16) -> v16i16 { - unsafe { __lasx_xvclz_h(a) } +pub fn lasx_xvclz_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvclz_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvclz_w(a: v8i32) -> v8i32 { - unsafe { __lasx_xvclz_w(a) } +pub fn lasx_xvclz_w(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvclz_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvclz_d(a: v4i64) -> v4i64 { - unsafe { __lasx_xvclz_d(a) } +pub fn lasx_xvclz_d(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvclz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfadd_s(a: v8f32, b: v8f32) -> v8f32 { - unsafe { __lasx_xvfadd_s(a, b) } +pub fn lasx_xvfadd_s(a: m256, b: m256) -> m256 { + unsafe { transmute(__lasx_xvfadd_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfadd_d(a: v4f64, b: v4f64) -> v4f64 { - unsafe { __lasx_xvfadd_d(a, b) } +pub fn lasx_xvfadd_d(a: m256d, b: m256d) -> m256d { + unsafe { transmute(__lasx_xvfadd_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfsub_s(a: v8f32, b: v8f32) -> v8f32 { - unsafe { __lasx_xvfsub_s(a, b) } +pub fn lasx_xvfsub_s(a: m256, b: m256) -> m256 { + unsafe { transmute(__lasx_xvfsub_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfsub_d(a: v4f64, b: v4f64) -> v4f64 { - unsafe { __lasx_xvfsub_d(a, b) } +pub fn lasx_xvfsub_d(a: m256d, b: m256d) -> m256d { + unsafe { transmute(__lasx_xvfsub_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmul_s(a: v8f32, b: v8f32) -> v8f32 { - unsafe { __lasx_xvfmul_s(a, b) } +pub fn lasx_xvfmul_s(a: m256, b: m256) -> m256 { + unsafe { transmute(__lasx_xvfmul_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmul_d(a: v4f64, b: v4f64) -> v4f64 { - unsafe { __lasx_xvfmul_d(a, b) } +pub fn lasx_xvfmul_d(a: m256d, b: m256d) -> m256d { + unsafe { transmute(__lasx_xvfmul_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfdiv_s(a: v8f32, b: v8f32) -> v8f32 { - unsafe { __lasx_xvfdiv_s(a, b) } +pub fn lasx_xvfdiv_s(a: m256, b: m256) -> m256 { + unsafe { transmute(__lasx_xvfdiv_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfdiv_d(a: v4f64, b: v4f64) -> v4f64 { - unsafe { __lasx_xvfdiv_d(a, b) } +pub fn lasx_xvfdiv_d(a: m256d, b: m256d) -> m256d { + unsafe { transmute(__lasx_xvfdiv_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcvt_h_s(a: v8f32, b: v8f32) -> v16i16 { - unsafe { __lasx_xvfcvt_h_s(a, b) } +pub fn lasx_xvfcvt_h_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcvt_h_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcvt_s_d(a: v4f64, b: v4f64) -> v8f32 { - unsafe { __lasx_xvfcvt_s_d(a, b) } +pub fn lasx_xvfcvt_s_d(a: m256d, b: m256d) -> m256 { + unsafe { transmute(__lasx_xvfcvt_s_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmin_s(a: v8f32, b: v8f32) -> v8f32 { - unsafe { __lasx_xvfmin_s(a, b) } +pub fn lasx_xvfmin_s(a: m256, b: m256) -> m256 { + unsafe { transmute(__lasx_xvfmin_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmin_d(a: v4f64, b: v4f64) -> v4f64 { - unsafe { __lasx_xvfmin_d(a, b) } +pub fn lasx_xvfmin_d(a: m256d, b: m256d) -> m256d { + unsafe { transmute(__lasx_xvfmin_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmina_s(a: v8f32, b: v8f32) -> v8f32 { - unsafe { __lasx_xvfmina_s(a, b) } +pub fn lasx_xvfmina_s(a: m256, b: m256) -> m256 { + unsafe { transmute(__lasx_xvfmina_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmina_d(a: v4f64, b: v4f64) -> v4f64 { - unsafe { __lasx_xvfmina_d(a, b) } +pub fn lasx_xvfmina_d(a: m256d, b: m256d) -> m256d { + unsafe { transmute(__lasx_xvfmina_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmax_s(a: v8f32, b: v8f32) -> v8f32 { - unsafe { __lasx_xvfmax_s(a, b) } +pub fn lasx_xvfmax_s(a: m256, b: m256) -> m256 { + unsafe { transmute(__lasx_xvfmax_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmax_d(a: v4f64, b: v4f64) -> v4f64 { - unsafe { __lasx_xvfmax_d(a, b) } +pub fn lasx_xvfmax_d(a: m256d, b: m256d) -> m256d { + unsafe { transmute(__lasx_xvfmax_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmaxa_s(a: v8f32, b: v8f32) -> v8f32 { - unsafe { __lasx_xvfmaxa_s(a, b) } +pub fn lasx_xvfmaxa_s(a: m256, b: m256) -> m256 { + unsafe { transmute(__lasx_xvfmaxa_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmaxa_d(a: v4f64, b: v4f64) -> v4f64 { - unsafe { __lasx_xvfmaxa_d(a, b) } +pub fn lasx_xvfmaxa_d(a: m256d, b: m256d) -> m256d { + unsafe { transmute(__lasx_xvfmaxa_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfclass_s(a: v8f32) -> v8i32 { - unsafe { __lasx_xvfclass_s(a) } +pub fn lasx_xvfclass_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvfclass_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfclass_d(a: v4f64) -> v4i64 { - unsafe { __lasx_xvfclass_d(a) } +pub fn lasx_xvfclass_d(a: m256d) -> m256i { + unsafe { transmute(__lasx_xvfclass_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfsqrt_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfsqrt_s(a) } +pub fn lasx_xvfsqrt_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfsqrt_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfsqrt_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfsqrt_d(a) } +pub fn lasx_xvfsqrt_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfsqrt_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrecip_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrecip_s(a) } +pub fn lasx_xvfrecip_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrecip_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrecip_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrecip_d(a) } +pub fn lasx_xvfrecip_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrecip_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx,frecipe")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrecipe_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrecipe_s(a) } +pub fn lasx_xvfrecipe_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrecipe_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx,frecipe")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrecipe_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrecipe_d(a) } +pub fn lasx_xvfrecipe_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrecipe_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx,frecipe")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrsqrte_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrsqrte_s(a) } +pub fn lasx_xvfrsqrte_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrsqrte_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx,frecipe")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrsqrte_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrsqrte_d(a) } +pub fn lasx_xvfrsqrte_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrsqrte_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrint_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrint_s(a) } +pub fn lasx_xvfrint_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrint_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrint_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrint_d(a) } +pub fn lasx_xvfrint_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrint_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrsqrt_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrsqrt_s(a) } +pub fn lasx_xvfrsqrt_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrsqrt_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrsqrt_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrsqrt_d(a) } +pub fn lasx_xvfrsqrt_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrsqrt_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvflogb_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvflogb_s(a) } +pub fn lasx_xvflogb_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvflogb_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvflogb_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvflogb_d(a) } +pub fn lasx_xvflogb_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvflogb_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcvth_s_h(a: v16i16) -> v8f32 { - unsafe { __lasx_xvfcvth_s_h(a) } +pub fn lasx_xvfcvth_s_h(a: m256i) -> m256 { + unsafe { transmute(__lasx_xvfcvth_s_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcvth_d_s(a: v8f32) -> v4f64 { - unsafe { __lasx_xvfcvth_d_s(a) } +pub fn lasx_xvfcvth_d_s(a: m256) -> m256d { + unsafe { transmute(__lasx_xvfcvth_d_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcvtl_s_h(a: v16i16) -> v8f32 { - unsafe { __lasx_xvfcvtl_s_h(a) } +pub fn lasx_xvfcvtl_s_h(a: m256i) -> m256 { + unsafe { transmute(__lasx_xvfcvtl_s_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcvtl_d_s(a: v8f32) -> v4f64 { - unsafe { __lasx_xvfcvtl_d_s(a) } +pub fn lasx_xvfcvtl_d_s(a: m256) -> m256d { + unsafe { transmute(__lasx_xvfcvtl_d_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftint_w_s(a: v8f32) -> v8i32 { - unsafe { __lasx_xvftint_w_s(a) } +pub fn lasx_xvftint_w_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftint_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftint_l_d(a: v4f64) -> v4i64 { - unsafe { __lasx_xvftint_l_d(a) } +pub fn lasx_xvftint_l_d(a: m256d) -> m256i { + unsafe { transmute(__lasx_xvftint_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftint_wu_s(a: v8f32) -> v8u32 { - unsafe { __lasx_xvftint_wu_s(a) } +pub fn lasx_xvftint_wu_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftint_wu_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftint_lu_d(a: v4f64) -> v4u64 { - unsafe { __lasx_xvftint_lu_d(a) } +pub fn lasx_xvftint_lu_d(a: m256d) -> m256i { + unsafe { transmute(__lasx_xvftint_lu_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrz_w_s(a: v8f32) -> v8i32 { - unsafe { __lasx_xvftintrz_w_s(a) } +pub fn lasx_xvftintrz_w_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrz_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrz_l_d(a: v4f64) -> v4i64 { - unsafe { __lasx_xvftintrz_l_d(a) } +pub fn lasx_xvftintrz_l_d(a: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrz_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrz_wu_s(a: v8f32) -> v8u32 { - unsafe { __lasx_xvftintrz_wu_s(a) } +pub fn lasx_xvftintrz_wu_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrz_wu_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrz_lu_d(a: v4f64) -> v4u64 { - unsafe { __lasx_xvftintrz_lu_d(a) } +pub fn lasx_xvftintrz_lu_d(a: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrz_lu_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvffint_s_w(a: v8i32) -> v8f32 { - unsafe { __lasx_xvffint_s_w(a) } +pub fn lasx_xvffint_s_w(a: m256i) -> m256 { + unsafe { transmute(__lasx_xvffint_s_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvffint_d_l(a: v4i64) -> v4f64 { - unsafe { __lasx_xvffint_d_l(a) } +pub fn lasx_xvffint_d_l(a: m256i) -> m256d { + unsafe { transmute(__lasx_xvffint_d_l(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvffint_s_wu(a: v8u32) -> v8f32 { - unsafe { __lasx_xvffint_s_wu(a) } +pub fn lasx_xvffint_s_wu(a: m256i) -> m256 { + unsafe { transmute(__lasx_xvffint_s_wu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvffint_d_lu(a: v4u64) -> v4f64 { - unsafe { __lasx_xvffint_d_lu(a) } +pub fn lasx_xvffint_d_lu(a: m256i) -> m256d { + unsafe { transmute(__lasx_xvffint_d_lu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve_b(a: v32i8, b: i32) -> v32i8 { - unsafe { __lasx_xvreplve_b(a, b) } +pub fn lasx_xvreplve_b(a: m256i, b: i32) -> m256i { + unsafe { transmute(__lasx_xvreplve_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve_h(a: v16i16, b: i32) -> v16i16 { - unsafe { __lasx_xvreplve_h(a, b) } +pub fn lasx_xvreplve_h(a: m256i, b: i32) -> m256i { + unsafe { transmute(__lasx_xvreplve_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve_w(a: v8i32, b: i32) -> v8i32 { - unsafe { __lasx_xvreplve_w(a, b) } +pub fn lasx_xvreplve_w(a: m256i, b: i32) -> m256i { + unsafe { transmute(__lasx_xvreplve_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve_d(a: v4i64, b: i32) -> v4i64 { - unsafe { __lasx_xvreplve_d(a, b) } +pub fn lasx_xvreplve_d(a: m256i, b: i32) -> m256i { + unsafe { transmute(__lasx_xvreplve_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpermi_w(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvpermi_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvpermi_w(a, b, IMM8) } + unsafe { transmute(__lasx_xvpermi_w(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvandn_v(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvandn_v(a, b) } +pub fn lasx_xvandn_v(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvandn_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvneg_b(a: v32i8) -> v32i8 { - unsafe { __lasx_xvneg_b(a) } +pub fn lasx_xvneg_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvneg_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvneg_h(a: v16i16) -> v16i16 { - unsafe { __lasx_xvneg_h(a) } +pub fn lasx_xvneg_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvneg_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvneg_w(a: v8i32) -> v8i32 { - unsafe { __lasx_xvneg_w(a) } +pub fn lasx_xvneg_w(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvneg_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvneg_d(a: v4i64) -> v4i64 { - unsafe { __lasx_xvneg_d(a) } +pub fn lasx_xvneg_d(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvneg_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmuh_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvmuh_b(a, b) } +pub fn lasx_xvmuh_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmuh_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmuh_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvmuh_h(a, b) } +pub fn lasx_xvmuh_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmuh_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmuh_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvmuh_w(a, b) } +pub fn lasx_xvmuh_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmuh_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmuh_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmuh_d(a, b) } +pub fn lasx_xvmuh_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmuh_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmuh_bu(a: v32u8, b: v32u8) -> v32u8 { - unsafe { __lasx_xvmuh_bu(a, b) } +pub fn lasx_xvmuh_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmuh_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmuh_hu(a: v16u16, b: v16u16) -> v16u16 { - unsafe { __lasx_xvmuh_hu(a, b) } +pub fn lasx_xvmuh_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmuh_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmuh_wu(a: v8u32, b: v8u32) -> v8u32 { - unsafe { __lasx_xvmuh_wu(a, b) } +pub fn lasx_xvmuh_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmuh_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmuh_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvmuh_du(a, b) } +pub fn lasx_xvmuh_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmuh_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsllwil_h_b(a: v32i8) -> v16i16 { +pub fn lasx_xvsllwil_h_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvsllwil_h_b(a, IMM3) } + unsafe { transmute(__lasx_xvsllwil_h_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsllwil_w_h(a: v16i16) -> v8i32 { +pub fn lasx_xvsllwil_w_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsllwil_w_h(a, IMM4) } + unsafe { transmute(__lasx_xvsllwil_w_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsllwil_d_w(a: v8i32) -> v4i64 { +pub fn lasx_xvsllwil_d_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsllwil_d_w(a, IMM5) } + unsafe { transmute(__lasx_xvsllwil_d_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsllwil_hu_bu(a: v32u8) -> v16u16 { +pub fn lasx_xvsllwil_hu_bu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvsllwil_hu_bu(a, IMM3) } + unsafe { transmute(__lasx_xvsllwil_hu_bu(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsllwil_wu_hu(a: v16u16) -> v8u32 { +pub fn lasx_xvsllwil_wu_hu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsllwil_wu_hu(a, IMM4) } + unsafe { transmute(__lasx_xvsllwil_wu_hu(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsllwil_du_wu(a: v8u32) -> v4u64 { +pub fn lasx_xvsllwil_du_wu(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsllwil_du_wu(a, IMM5) } + unsafe { transmute(__lasx_xvsllwil_du_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsran_b_h(a: v16i16, b: v16i16) -> v32i8 { - unsafe { __lasx_xvsran_b_h(a, b) } +pub fn lasx_xvsran_b_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsran_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsran_h_w(a: v8i32, b: v8i32) -> v16i16 { - unsafe { __lasx_xvsran_h_w(a, b) } +pub fn lasx_xvsran_h_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsran_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsran_w_d(a: v4i64, b: v4i64) -> v8i32 { - unsafe { __lasx_xvsran_w_d(a, b) } +pub fn lasx_xvsran_w_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsran_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssran_b_h(a: v16i16, b: v16i16) -> v32i8 { - unsafe { __lasx_xvssran_b_h(a, b) } +pub fn lasx_xvssran_b_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssran_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssran_h_w(a: v8i32, b: v8i32) -> v16i16 { - unsafe { __lasx_xvssran_h_w(a, b) } +pub fn lasx_xvssran_h_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssran_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssran_w_d(a: v4i64, b: v4i64) -> v8i32 { - unsafe { __lasx_xvssran_w_d(a, b) } +pub fn lasx_xvssran_w_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssran_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssran_bu_h(a: v16u16, b: v16u16) -> v32u8 { - unsafe { __lasx_xvssran_bu_h(a, b) } +pub fn lasx_xvssran_bu_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssran_bu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssran_hu_w(a: v8u32, b: v8u32) -> v16u16 { - unsafe { __lasx_xvssran_hu_w(a, b) } +pub fn lasx_xvssran_hu_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssran_hu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssran_wu_d(a: v4u64, b: v4u64) -> v8u32 { - unsafe { __lasx_xvssran_wu_d(a, b) } +pub fn lasx_xvssran_wu_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssran_wu_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrarn_b_h(a: v16i16, b: v16i16) -> v32i8 { - unsafe { __lasx_xvsrarn_b_h(a, b) } +pub fn lasx_xvsrarn_b_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrarn_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrarn_h_w(a: v8i32, b: v8i32) -> v16i16 { - unsafe { __lasx_xvsrarn_h_w(a, b) } +pub fn lasx_xvsrarn_h_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrarn_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrarn_w_d(a: v4i64, b: v4i64) -> v8i32 { - unsafe { __lasx_xvsrarn_w_d(a, b) } +pub fn lasx_xvsrarn_w_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrarn_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarn_b_h(a: v16i16, b: v16i16) -> v32i8 { - unsafe { __lasx_xvssrarn_b_h(a, b) } +pub fn lasx_xvssrarn_b_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrarn_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarn_h_w(a: v8i32, b: v8i32) -> v16i16 { - unsafe { __lasx_xvssrarn_h_w(a, b) } +pub fn lasx_xvssrarn_h_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrarn_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarn_w_d(a: v4i64, b: v4i64) -> v8i32 { - unsafe { __lasx_xvssrarn_w_d(a, b) } +pub fn lasx_xvssrarn_w_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrarn_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarn_bu_h(a: v16u16, b: v16u16) -> v32u8 { - unsafe { __lasx_xvssrarn_bu_h(a, b) } +pub fn lasx_xvssrarn_bu_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrarn_bu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarn_hu_w(a: v8u32, b: v8u32) -> v16u16 { - unsafe { __lasx_xvssrarn_hu_w(a, b) } +pub fn lasx_xvssrarn_hu_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrarn_hu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarn_wu_d(a: v4u64, b: v4u64) -> v8u32 { - unsafe { __lasx_xvssrarn_wu_d(a, b) } +pub fn lasx_xvssrarn_wu_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrarn_wu_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrln_b_h(a: v16i16, b: v16i16) -> v32i8 { - unsafe { __lasx_xvsrln_b_h(a, b) } +pub fn lasx_xvsrln_b_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrln_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrln_h_w(a: v8i32, b: v8i32) -> v16i16 { - unsafe { __lasx_xvsrln_h_w(a, b) } +pub fn lasx_xvsrln_h_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrln_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrln_w_d(a: v4i64, b: v4i64) -> v8i32 { - unsafe { __lasx_xvsrln_w_d(a, b) } +pub fn lasx_xvsrln_w_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrln_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrln_bu_h(a: v16u16, b: v16u16) -> v32u8 { - unsafe { __lasx_xvssrln_bu_h(a, b) } +pub fn lasx_xvssrln_bu_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrln_bu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrln_hu_w(a: v8u32, b: v8u32) -> v16u16 { - unsafe { __lasx_xvssrln_hu_w(a, b) } +pub fn lasx_xvssrln_hu_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrln_hu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrln_wu_d(a: v4u64, b: v4u64) -> v8u32 { - unsafe { __lasx_xvssrln_wu_d(a, b) } +pub fn lasx_xvssrln_wu_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrln_wu_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlrn_b_h(a: v16i16, b: v16i16) -> v32i8 { - unsafe { __lasx_xvsrlrn_b_h(a, b) } +pub fn lasx_xvsrlrn_b_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrlrn_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlrn_h_w(a: v8i32, b: v8i32) -> v16i16 { - unsafe { __lasx_xvsrlrn_h_w(a, b) } +pub fn lasx_xvsrlrn_h_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrlrn_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlrn_w_d(a: v4i64, b: v4i64) -> v8i32 { - unsafe { __lasx_xvsrlrn_w_d(a, b) } +pub fn lasx_xvsrlrn_w_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsrlrn_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrn_bu_h(a: v16u16, b: v16u16) -> v32u8 { - unsafe { __lasx_xvssrlrn_bu_h(a, b) } +pub fn lasx_xvssrlrn_bu_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrlrn_bu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrn_hu_w(a: v8u32, b: v8u32) -> v16u16 { - unsafe { __lasx_xvssrlrn_hu_w(a, b) } +pub fn lasx_xvssrlrn_hu_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrlrn_hu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrn_wu_d(a: v4u64, b: v4u64) -> v8u32 { - unsafe { __lasx_xvssrlrn_wu_d(a, b) } +pub fn lasx_xvssrlrn_wu_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrlrn_wu_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrstpi_b(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvfrstpi_b(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvfrstpi_b(a, b, IMM5) } + unsafe { transmute(__lasx_xvfrstpi_b(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrstpi_h(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvfrstpi_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvfrstpi_h(a, b, IMM5) } + unsafe { transmute(__lasx_xvfrstpi_h(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrstp_b(a: v32i8, b: v32i8, c: v32i8) -> v32i8 { - unsafe { __lasx_xvfrstp_b(a, b, c) } +pub fn lasx_xvfrstp_b(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvfrstp_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrstp_h(a: v16i16, b: v16i16, c: v16i16) -> v16i16 { - unsafe { __lasx_xvfrstp_h(a, b, c) } +pub fn lasx_xvfrstp_h(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvfrstp_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvshuf4i_d(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvshuf4i_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvshuf4i_d(a, b, IMM8) } + unsafe { transmute(__lasx_xvshuf4i_d(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbsrl_v(a: v32i8) -> v32i8 { +pub fn lasx_xvbsrl_v(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvbsrl_v(a, IMM5) } + unsafe { transmute(__lasx_xvbsrl_v(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvbsll_v(a: v32i8) -> v32i8 { +pub fn lasx_xvbsll_v(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvbsll_v(a, IMM5) } + unsafe { transmute(__lasx_xvbsll_v(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvextrins_b(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvextrins_b(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvextrins_b(a, b, IMM8) } + unsafe { transmute(__lasx_xvextrins_b(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvextrins_h(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvextrins_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvextrins_h(a, b, IMM8) } + unsafe { transmute(__lasx_xvextrins_h(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvextrins_w(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvextrins_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvextrins_w(a, b, IMM8) } + unsafe { transmute(__lasx_xvextrins_w(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvextrins_d(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvextrins_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvextrins_d(a, b, IMM8) } + unsafe { transmute(__lasx_xvextrins_d(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmskltz_b(a: v32i8) -> v32i8 { - unsafe { __lasx_xvmskltz_b(a) } +pub fn lasx_xvmskltz_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvmskltz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmskltz_h(a: v16i16) -> v16i16 { - unsafe { __lasx_xvmskltz_h(a) } +pub fn lasx_xvmskltz_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvmskltz_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmskltz_w(a: v8i32) -> v8i32 { - unsafe { __lasx_xvmskltz_w(a) } +pub fn lasx_xvmskltz_w(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvmskltz_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmskltz_d(a: v4i64) -> v4i64 { - unsafe { __lasx_xvmskltz_d(a) } +pub fn lasx_xvmskltz_d(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvmskltz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsigncov_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvsigncov_b(a, b) } +pub fn lasx_xvsigncov_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsigncov_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsigncov_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvsigncov_h(a, b) } +pub fn lasx_xvsigncov_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsigncov_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsigncov_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvsigncov_w(a, b) } +pub fn lasx_xvsigncov_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsigncov_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsigncov_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsigncov_d(a, b) } +pub fn lasx_xvsigncov_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsigncov_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmadd_s(a: v8f32, b: v8f32, c: v8f32) -> v8f32 { - unsafe { __lasx_xvfmadd_s(a, b, c) } +pub fn lasx_xvfmadd_s(a: m256, b: m256, c: m256) -> m256 { + unsafe { transmute(__lasx_xvfmadd_s(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmadd_d(a: v4f64, b: v4f64, c: v4f64) -> v4f64 { - unsafe { __lasx_xvfmadd_d(a, b, c) } +pub fn lasx_xvfmadd_d(a: m256d, b: m256d, c: m256d) -> m256d { + unsafe { transmute(__lasx_xvfmadd_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmsub_s(a: v8f32, b: v8f32, c: v8f32) -> v8f32 { - unsafe { __lasx_xvfmsub_s(a, b, c) } +pub fn lasx_xvfmsub_s(a: m256, b: m256, c: m256) -> m256 { + unsafe { transmute(__lasx_xvfmsub_s(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfmsub_d(a: v4f64, b: v4f64, c: v4f64) -> v4f64 { - unsafe { __lasx_xvfmsub_d(a, b, c) } +pub fn lasx_xvfmsub_d(a: m256d, b: m256d, c: m256d) -> m256d { + unsafe { transmute(__lasx_xvfmsub_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfnmadd_s(a: v8f32, b: v8f32, c: v8f32) -> v8f32 { - unsafe { __lasx_xvfnmadd_s(a, b, c) } +pub fn lasx_xvfnmadd_s(a: m256, b: m256, c: m256) -> m256 { + unsafe { transmute(__lasx_xvfnmadd_s(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfnmadd_d(a: v4f64, b: v4f64, c: v4f64) -> v4f64 { - unsafe { __lasx_xvfnmadd_d(a, b, c) } +pub fn lasx_xvfnmadd_d(a: m256d, b: m256d, c: m256d) -> m256d { + unsafe { transmute(__lasx_xvfnmadd_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfnmsub_s(a: v8f32, b: v8f32, c: v8f32) -> v8f32 { - unsafe { __lasx_xvfnmsub_s(a, b, c) } +pub fn lasx_xvfnmsub_s(a: m256, b: m256, c: m256) -> m256 { + unsafe { transmute(__lasx_xvfnmsub_s(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfnmsub_d(a: v4f64, b: v4f64, c: v4f64) -> v4f64 { - unsafe { __lasx_xvfnmsub_d(a, b, c) } +pub fn lasx_xvfnmsub_d(a: m256d, b: m256d, c: m256d) -> m256d { + unsafe { transmute(__lasx_xvfnmsub_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrne_w_s(a: v8f32) -> v8i32 { - unsafe { __lasx_xvftintrne_w_s(a) } +pub fn lasx_xvftintrne_w_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrne_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrne_l_d(a: v4f64) -> v4i64 { - unsafe { __lasx_xvftintrne_l_d(a) } +pub fn lasx_xvftintrne_l_d(a: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrne_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrp_w_s(a: v8f32) -> v8i32 { - unsafe { __lasx_xvftintrp_w_s(a) } +pub fn lasx_xvftintrp_w_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrp_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrp_l_d(a: v4f64) -> v4i64 { - unsafe { __lasx_xvftintrp_l_d(a) } +pub fn lasx_xvftintrp_l_d(a: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrp_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrm_w_s(a: v8f32) -> v8i32 { - unsafe { __lasx_xvftintrm_w_s(a) } +pub fn lasx_xvftintrm_w_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrm_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrm_l_d(a: v4f64) -> v4i64 { - unsafe { __lasx_xvftintrm_l_d(a) } +pub fn lasx_xvftintrm_l_d(a: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrm_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftint_w_d(a: v4f64, b: v4f64) -> v8i32 { - unsafe { __lasx_xvftint_w_d(a, b) } +pub fn lasx_xvftint_w_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvftint_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvffint_s_l(a: v4i64, b: v4i64) -> v8f32 { - unsafe { __lasx_xvffint_s_l(a, b) } +pub fn lasx_xvffint_s_l(a: m256i, b: m256i) -> m256 { + unsafe { transmute(__lasx_xvffint_s_l(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrz_w_d(a: v4f64, b: v4f64) -> v8i32 { - unsafe { __lasx_xvftintrz_w_d(a, b) } +pub fn lasx_xvftintrz_w_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrz_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrp_w_d(a: v4f64, b: v4f64) -> v8i32 { - unsafe { __lasx_xvftintrp_w_d(a, b) } +pub fn lasx_xvftintrp_w_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrp_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrm_w_d(a: v4f64, b: v4f64) -> v8i32 { - unsafe { __lasx_xvftintrm_w_d(a, b) } +pub fn lasx_xvftintrm_w_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrm_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrne_w_d(a: v4f64, b: v4f64) -> v8i32 { - unsafe { __lasx_xvftintrne_w_d(a, b) } +pub fn lasx_xvftintrne_w_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvftintrne_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftinth_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftinth_l_s(a) } +pub fn lasx_xvftinth_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftinth_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintl_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintl_l_s(a) } +pub fn lasx_xvftintl_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintl_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvffinth_d_w(a: v8i32) -> v4f64 { - unsafe { __lasx_xvffinth_d_w(a) } +pub fn lasx_xvffinth_d_w(a: m256i) -> m256d { + unsafe { transmute(__lasx_xvffinth_d_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvffintl_d_w(a: v8i32) -> v4f64 { - unsafe { __lasx_xvffintl_d_w(a) } +pub fn lasx_xvffintl_d_w(a: m256i) -> m256d { + unsafe { transmute(__lasx_xvffintl_d_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrzh_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintrzh_l_s(a) } +pub fn lasx_xvftintrzh_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrzh_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrzl_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintrzl_l_s(a) } +pub fn lasx_xvftintrzl_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrzl_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrph_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintrph_l_s(a) } +pub fn lasx_xvftintrph_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrph_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrpl_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintrpl_l_s(a) } +pub fn lasx_xvftintrpl_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrpl_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrmh_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintrmh_l_s(a) } +pub fn lasx_xvftintrmh_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrmh_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrml_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintrml_l_s(a) } +pub fn lasx_xvftintrml_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrml_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrneh_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintrneh_l_s(a) } +pub fn lasx_xvftintrneh_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrneh_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvftintrnel_l_s(a: v8f32) -> v4i64 { - unsafe { __lasx_xvftintrnel_l_s(a) } +pub fn lasx_xvftintrnel_l_s(a: m256) -> m256i { + unsafe { transmute(__lasx_xvftintrnel_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrintrne_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrintrne_s(a) } +pub fn lasx_xvfrintrne_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrintrne_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrintrne_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrintrne_d(a) } +pub fn lasx_xvfrintrne_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrintrne_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrintrz_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrintrz_s(a) } +pub fn lasx_xvfrintrz_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrintrz_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrintrz_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrintrz_d(a) } +pub fn lasx_xvfrintrz_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrintrz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrintrp_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrintrp_s(a) } +pub fn lasx_xvfrintrp_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrintrp_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrintrp_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrintrp_d(a) } +pub fn lasx_xvfrintrp_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrintrp_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrintrm_s(a: v8f32) -> v8f32 { - unsafe { __lasx_xvfrintrm_s(a) } +pub fn lasx_xvfrintrm_s(a: m256) -> m256 { + unsafe { transmute(__lasx_xvfrintrm_s(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfrintrm_d(a: v4f64) -> v4f64 { - unsafe { __lasx_xvfrintrm_d(a) } +pub fn lasx_xvfrintrm_d(a: m256d) -> m256d { + unsafe { transmute(__lasx_xvfrintrm_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvld(mem_addr: *const i8) -> v32i8 { +pub unsafe fn lasx_xvld(mem_addr: *const i8) -> m256i { static_assert_simm_bits!(IMM_S12, 12); - __lasx_xvld(mem_addr, IMM_S12) + transmute(__lasx_xvld(mem_addr, IMM_S12)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvst(a: v32i8, mem_addr: *mut i8) { +pub unsafe fn lasx_xvst(a: m256i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S12, 12); - __lasx_xvst(a, mem_addr, IMM_S12) + transmute(__lasx_xvst(transmute(a), mem_addr, IMM_S12)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2, 3)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvstelm_b(a: v32i8, mem_addr: *mut i8) { +pub unsafe fn lasx_xvstelm_b(a: m256i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S8, 8); static_assert_uimm_bits!(IMM4, 4); - __lasx_xvstelm_b(a, mem_addr, IMM_S8, IMM4) + transmute(__lasx_xvstelm_b(transmute(a), mem_addr, IMM_S8, IMM4)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2, 3)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvstelm_h(a: v16i16, mem_addr: *mut i8) { +pub unsafe fn lasx_xvstelm_h(a: m256i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S8, 8); static_assert_uimm_bits!(IMM3, 3); - __lasx_xvstelm_h(a, mem_addr, IMM_S8, IMM3) + transmute(__lasx_xvstelm_h(transmute(a), mem_addr, IMM_S8, IMM3)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2, 3)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvstelm_w(a: v8i32, mem_addr: *mut i8) { +pub unsafe fn lasx_xvstelm_w(a: m256i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S8, 8); static_assert_uimm_bits!(IMM2, 2); - __lasx_xvstelm_w(a, mem_addr, IMM_S8, IMM2) + transmute(__lasx_xvstelm_w(transmute(a), mem_addr, IMM_S8, IMM2)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2, 3)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvstelm_d(a: v4i64, mem_addr: *mut i8) { +pub unsafe fn lasx_xvstelm_d(a: m256i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S8, 8); static_assert_uimm_bits!(IMM1, 1); - __lasx_xvstelm_d(a, mem_addr, IMM_S8, IMM1) + transmute(__lasx_xvstelm_d(transmute(a), mem_addr, IMM_S8, IMM1)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvinsve0_w(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvinsve0_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvinsve0_w(a, b, IMM3) } + unsafe { transmute(__lasx_xvinsve0_w(transmute(a), transmute(b), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvinsve0_d(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvinsve0_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lasx_xvinsve0_d(a, b, IMM2) } + unsafe { transmute(__lasx_xvinsve0_d(transmute(a), transmute(b), IMM2)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickve_w(a: v8i32) -> v8i32 { +pub fn lasx_xvpickve_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvpickve_w(a, IMM3) } + unsafe { transmute(__lasx_xvpickve_w(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickve_d(a: v4i64) -> v4i64 { +pub fn lasx_xvpickve_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lasx_xvpickve_d(a, IMM2) } + unsafe { transmute(__lasx_xvpickve_d(transmute(a), IMM2)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrn_b_h(a: v16i16, b: v16i16) -> v32i8 { - unsafe { __lasx_xvssrlrn_b_h(a, b) } +pub fn lasx_xvssrlrn_b_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrlrn_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrn_h_w(a: v8i32, b: v8i32) -> v16i16 { - unsafe { __lasx_xvssrlrn_h_w(a, b) } +pub fn lasx_xvssrlrn_h_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrlrn_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrn_w_d(a: v4i64, b: v4i64) -> v8i32 { - unsafe { __lasx_xvssrlrn_w_d(a, b) } +pub fn lasx_xvssrlrn_w_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrlrn_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrln_b_h(a: v16i16, b: v16i16) -> v32i8 { - unsafe { __lasx_xvssrln_b_h(a, b) } +pub fn lasx_xvssrln_b_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrln_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrln_h_w(a: v8i32, b: v8i32) -> v16i16 { - unsafe { __lasx_xvssrln_h_w(a, b) } +pub fn lasx_xvssrln_h_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrln_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrln_w_d(a: v4i64, b: v4i64) -> v8i32 { - unsafe { __lasx_xvssrln_w_d(a, b) } +pub fn lasx_xvssrln_w_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvssrln_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvorn_v(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvorn_v(a, b) } +pub fn lasx_xvorn_v(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvorn_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvldi() -> v4i64 { +pub fn lasx_xvldi() -> m256i { static_assert_simm_bits!(IMM_S13, 13); - unsafe { __lasx_xvldi(IMM_S13) } + unsafe { transmute(__lasx_xvldi(IMM_S13)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvldx(mem_addr: *const i8, b: i64) -> v32i8 { - __lasx_xvldx(mem_addr, b) +pub unsafe fn lasx_xvldx(mem_addr: *const i8, b: i64) -> m256i { + transmute(__lasx_xvldx(mem_addr, transmute(b))) } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvstx(a: v32i8, mem_addr: *mut i8, b: i64) { - __lasx_xvstx(a, mem_addr, b) +pub unsafe fn lasx_xvstx(a: m256i, mem_addr: *mut i8, b: i64) { + transmute(__lasx_xvstx(transmute(a), mem_addr, transmute(b))) } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvextl_qu_du(a: v4u64) -> v4u64 { - unsafe { __lasx_xvextl_qu_du(a) } +pub fn lasx_xvextl_qu_du(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvextl_qu_du(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvinsgr2vr_w(a: v8i32, b: i32) -> v8i32 { +pub fn lasx_xvinsgr2vr_w(a: m256i, b: i32) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvinsgr2vr_w(a, b, IMM3) } + unsafe { transmute(__lasx_xvinsgr2vr_w(transmute(a), transmute(b), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvinsgr2vr_d(a: v4i64, b: i64) -> v4i64 { +pub fn lasx_xvinsgr2vr_d(a: m256i, b: i64) -> m256i { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lasx_xvinsgr2vr_d(a, b, IMM2) } + unsafe { transmute(__lasx_xvinsgr2vr_d(transmute(a), transmute(b), IMM2)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve0_b(a: v32i8) -> v32i8 { - unsafe { __lasx_xvreplve0_b(a) } +pub fn lasx_xvreplve0_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvreplve0_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve0_h(a: v16i16) -> v16i16 { - unsafe { __lasx_xvreplve0_h(a) } +pub fn lasx_xvreplve0_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvreplve0_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve0_w(a: v8i32) -> v8i32 { - unsafe { __lasx_xvreplve0_w(a) } +pub fn lasx_xvreplve0_w(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvreplve0_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve0_d(a: v4i64) -> v4i64 { - unsafe { __lasx_xvreplve0_d(a) } +pub fn lasx_xvreplve0_d(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvreplve0_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvreplve0_q(a: v32i8) -> v32i8 { - unsafe { __lasx_xvreplve0_q(a) } +pub fn lasx_xvreplve0_q(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvreplve0_q(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_h_b(a: v32i8) -> v16i16 { - unsafe { __lasx_vext2xv_h_b(a) } +pub fn lasx_vext2xv_h_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_h_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_w_h(a: v16i16) -> v8i32 { - unsafe { __lasx_vext2xv_w_h(a) } +pub fn lasx_vext2xv_w_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_w_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_d_w(a: v8i32) -> v4i64 { - unsafe { __lasx_vext2xv_d_w(a) } +pub fn lasx_vext2xv_d_w(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_d_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_w_b(a: v32i8) -> v8i32 { - unsafe { __lasx_vext2xv_w_b(a) } +pub fn lasx_vext2xv_w_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_w_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_d_h(a: v16i16) -> v4i64 { - unsafe { __lasx_vext2xv_d_h(a) } +pub fn lasx_vext2xv_d_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_d_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_d_b(a: v32i8) -> v4i64 { - unsafe { __lasx_vext2xv_d_b(a) } +pub fn lasx_vext2xv_d_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_d_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_hu_bu(a: v32i8) -> v16i16 { - unsafe { __lasx_vext2xv_hu_bu(a) } +pub fn lasx_vext2xv_hu_bu(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_hu_bu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_wu_hu(a: v16i16) -> v8i32 { - unsafe { __lasx_vext2xv_wu_hu(a) } +pub fn lasx_vext2xv_wu_hu(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_wu_hu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_du_wu(a: v8i32) -> v4i64 { - unsafe { __lasx_vext2xv_du_wu(a) } +pub fn lasx_vext2xv_du_wu(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_du_wu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_wu_bu(a: v32i8) -> v8i32 { - unsafe { __lasx_vext2xv_wu_bu(a) } +pub fn lasx_vext2xv_wu_bu(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_wu_bu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_du_hu(a: v16i16) -> v4i64 { - unsafe { __lasx_vext2xv_du_hu(a) } +pub fn lasx_vext2xv_du_hu(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_du_hu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_vext2xv_du_bu(a: v32i8) -> v4i64 { - unsafe { __lasx_vext2xv_du_bu(a) } +pub fn lasx_vext2xv_du_bu(a: m256i) -> m256i { + unsafe { transmute(__lasx_vext2xv_du_bu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpermi_q(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvpermi_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvpermi_q(a, b, IMM8) } + unsafe { transmute(__lasx_xvpermi_q(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpermi_d(a: v4i64) -> v4i64 { +pub fn lasx_xvpermi_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lasx_xvpermi_d(a, IMM8) } + unsafe { transmute(__lasx_xvpermi_d(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvperm_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvperm_w(a, b) } +pub fn lasx_xvperm_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvperm_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvldrepl_b(mem_addr: *const i8) -> v32i8 { +pub unsafe fn lasx_xvldrepl_b(mem_addr: *const i8) -> m256i { static_assert_simm_bits!(IMM_S12, 12); - __lasx_xvldrepl_b(mem_addr, IMM_S12) + transmute(__lasx_xvldrepl_b(mem_addr, IMM_S12)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvldrepl_h(mem_addr: *const i8) -> v16i16 { +pub unsafe fn lasx_xvldrepl_h(mem_addr: *const i8) -> m256i { static_assert_simm_bits!(IMM_S11, 11); - __lasx_xvldrepl_h(mem_addr, IMM_S11) + transmute(__lasx_xvldrepl_h(mem_addr, IMM_S11)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvldrepl_w(mem_addr: *const i8) -> v8i32 { +pub unsafe fn lasx_xvldrepl_w(mem_addr: *const i8) -> m256i { static_assert_simm_bits!(IMM_S10, 10); - __lasx_xvldrepl_w(mem_addr, IMM_S10) + transmute(__lasx_xvldrepl_w(mem_addr, IMM_S10)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lasx_xvldrepl_d(mem_addr: *const i8) -> v4i64 { +pub unsafe fn lasx_xvldrepl_d(mem_addr: *const i8) -> m256i { static_assert_simm_bits!(IMM_S9, 9); - __lasx_xvldrepl_d(mem_addr, IMM_S9) + transmute(__lasx_xvldrepl_d(mem_addr, IMM_S9)) } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickve2gr_w(a: v8i32) -> i32 { +pub fn lasx_xvpickve2gr_w(a: m256i) -> i32 { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvpickve2gr_w(a, IMM3) } + unsafe { transmute(__lasx_xvpickve2gr_w(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickve2gr_wu(a: v8i32) -> u32 { +pub fn lasx_xvpickve2gr_wu(a: m256i) -> u32 { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvpickve2gr_wu(a, IMM3) } + unsafe { transmute(__lasx_xvpickve2gr_wu(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickve2gr_d(a: v4i64) -> i64 { +pub fn lasx_xvpickve2gr_d(a: m256i) -> i64 { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lasx_xvpickve2gr_d(a, IMM2) } + unsafe { transmute(__lasx_xvpickve2gr_d(transmute(a), IMM2)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickve2gr_du(a: v4i64) -> u64 { +pub fn lasx_xvpickve2gr_du(a: m256i) -> u64 { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lasx_xvpickve2gr_du(a, IMM2) } + unsafe { transmute(__lasx_xvpickve2gr_du(transmute(a), IMM2)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_q_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvaddwev_q_d(a, b) } +pub fn lasx_xvaddwev_q_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_d_w(a: v8i32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvaddwev_d_w(a, b) } +pub fn lasx_xvaddwev_d_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_w_h(a: v16i16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvaddwev_w_h(a, b) } +pub fn lasx_xvaddwev_w_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_h_b(a: v32i8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvaddwev_h_b(a, b) } +pub fn lasx_xvaddwev_h_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_q_du(a: v4u64, b: v4u64) -> v4i64 { - unsafe { __lasx_xvaddwev_q_du(a, b) } +pub fn lasx_xvaddwev_q_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_d_wu(a: v8u32, b: v8u32) -> v4i64 { - unsafe { __lasx_xvaddwev_d_wu(a, b) } +pub fn lasx_xvaddwev_d_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_w_hu(a: v16u16, b: v16u16) -> v8i32 { - unsafe { __lasx_xvaddwev_w_hu(a, b) } +pub fn lasx_xvaddwev_w_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_h_bu(a: v32u8, b: v32u8) -> v16i16 { - unsafe { __lasx_xvaddwev_h_bu(a, b) } +pub fn lasx_xvaddwev_h_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwev_q_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsubwev_q_d(a, b) } +pub fn lasx_xvsubwev_q_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwev_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwev_d_w(a: v8i32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvsubwev_d_w(a, b) } +pub fn lasx_xvsubwev_d_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwev_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwev_w_h(a: v16i16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvsubwev_w_h(a, b) } +pub fn lasx_xvsubwev_w_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwev_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwev_h_b(a: v32i8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvsubwev_h_b(a, b) } +pub fn lasx_xvsubwev_h_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwev_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwev_q_du(a: v4u64, b: v4u64) -> v4i64 { - unsafe { __lasx_xvsubwev_q_du(a, b) } +pub fn lasx_xvsubwev_q_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwev_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwev_d_wu(a: v8u32, b: v8u32) -> v4i64 { - unsafe { __lasx_xvsubwev_d_wu(a, b) } +pub fn lasx_xvsubwev_d_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwev_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwev_w_hu(a: v16u16, b: v16u16) -> v8i32 { - unsafe { __lasx_xvsubwev_w_hu(a, b) } +pub fn lasx_xvsubwev_w_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwev_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwev_h_bu(a: v32u8, b: v32u8) -> v16i16 { - unsafe { __lasx_xvsubwev_h_bu(a, b) } +pub fn lasx_xvsubwev_h_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwev_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_q_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmulwev_q_d(a, b) } +pub fn lasx_xvmulwev_q_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_d_w(a: v8i32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvmulwev_d_w(a, b) } +pub fn lasx_xvmulwev_d_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_w_h(a: v16i16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvmulwev_w_h(a, b) } +pub fn lasx_xvmulwev_w_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_h_b(a: v32i8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvmulwev_h_b(a, b) } +pub fn lasx_xvmulwev_h_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_q_du(a: v4u64, b: v4u64) -> v4i64 { - unsafe { __lasx_xvmulwev_q_du(a, b) } +pub fn lasx_xvmulwev_q_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_d_wu(a: v8u32, b: v8u32) -> v4i64 { - unsafe { __lasx_xvmulwev_d_wu(a, b) } +pub fn lasx_xvmulwev_d_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_w_hu(a: v16u16, b: v16u16) -> v8i32 { - unsafe { __lasx_xvmulwev_w_hu(a, b) } +pub fn lasx_xvmulwev_w_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_h_bu(a: v32u8, b: v32u8) -> v16i16 { - unsafe { __lasx_xvmulwev_h_bu(a, b) } +pub fn lasx_xvmulwev_h_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_q_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvaddwod_q_d(a, b) } +pub fn lasx_xvaddwod_q_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_d_w(a: v8i32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvaddwod_d_w(a, b) } +pub fn lasx_xvaddwod_d_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_w_h(a: v16i16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvaddwod_w_h(a, b) } +pub fn lasx_xvaddwod_w_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_h_b(a: v32i8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvaddwod_h_b(a, b) } +pub fn lasx_xvaddwod_h_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_q_du(a: v4u64, b: v4u64) -> v4i64 { - unsafe { __lasx_xvaddwod_q_du(a, b) } +pub fn lasx_xvaddwod_q_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_d_wu(a: v8u32, b: v8u32) -> v4i64 { - unsafe { __lasx_xvaddwod_d_wu(a, b) } +pub fn lasx_xvaddwod_d_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_w_hu(a: v16u16, b: v16u16) -> v8i32 { - unsafe { __lasx_xvaddwod_w_hu(a, b) } +pub fn lasx_xvaddwod_w_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_h_bu(a: v32u8, b: v32u8) -> v16i16 { - unsafe { __lasx_xvaddwod_h_bu(a, b) } +pub fn lasx_xvaddwod_h_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwod_q_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsubwod_q_d(a, b) } +pub fn lasx_xvsubwod_q_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwod_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwod_d_w(a: v8i32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvsubwod_d_w(a, b) } +pub fn lasx_xvsubwod_d_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwod_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwod_w_h(a: v16i16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvsubwod_w_h(a, b) } +pub fn lasx_xvsubwod_w_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwod_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwod_h_b(a: v32i8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvsubwod_h_b(a, b) } +pub fn lasx_xvsubwod_h_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwod_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwod_q_du(a: v4u64, b: v4u64) -> v4i64 { - unsafe { __lasx_xvsubwod_q_du(a, b) } +pub fn lasx_xvsubwod_q_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwod_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwod_d_wu(a: v8u32, b: v8u32) -> v4i64 { - unsafe { __lasx_xvsubwod_d_wu(a, b) } +pub fn lasx_xvsubwod_d_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwod_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwod_w_hu(a: v16u16, b: v16u16) -> v8i32 { - unsafe { __lasx_xvsubwod_w_hu(a, b) } +pub fn lasx_xvsubwod_w_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwod_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsubwod_h_bu(a: v32u8, b: v32u8) -> v16i16 { - unsafe { __lasx_xvsubwod_h_bu(a, b) } +pub fn lasx_xvsubwod_h_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsubwod_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_q_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmulwod_q_d(a, b) } +pub fn lasx_xvmulwod_q_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_d_w(a: v8i32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvmulwod_d_w(a, b) } +pub fn lasx_xvmulwod_d_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_w_h(a: v16i16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvmulwod_w_h(a, b) } +pub fn lasx_xvmulwod_w_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_h_b(a: v32i8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvmulwod_h_b(a, b) } +pub fn lasx_xvmulwod_h_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_q_du(a: v4u64, b: v4u64) -> v4i64 { - unsafe { __lasx_xvmulwod_q_du(a, b) } +pub fn lasx_xvmulwod_q_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_d_wu(a: v8u32, b: v8u32) -> v4i64 { - unsafe { __lasx_xvmulwod_d_wu(a, b) } +pub fn lasx_xvmulwod_d_wu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_w_hu(a: v16u16, b: v16u16) -> v8i32 { - unsafe { __lasx_xvmulwod_w_hu(a, b) } +pub fn lasx_xvmulwod_w_hu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_h_bu(a: v32u8, b: v32u8) -> v16i16 { - unsafe { __lasx_xvmulwod_h_bu(a, b) } +pub fn lasx_xvmulwod_h_bu(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_d_wu_w(a: v8u32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvaddwev_d_wu_w(a, b) } +pub fn lasx_xvaddwev_d_wu_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_d_wu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_w_hu_h(a: v16u16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvaddwev_w_hu_h(a, b) } +pub fn lasx_xvaddwev_w_hu_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_w_hu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_h_bu_b(a: v32u8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvaddwev_h_bu_b(a, b) } +pub fn lasx_xvaddwev_h_bu_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_h_bu_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_d_wu_w(a: v8u32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvmulwev_d_wu_w(a, b) } +pub fn lasx_xvmulwev_d_wu_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_d_wu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_w_hu_h(a: v16u16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvmulwev_w_hu_h(a, b) } +pub fn lasx_xvmulwev_w_hu_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_w_hu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_h_bu_b(a: v32u8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvmulwev_h_bu_b(a, b) } +pub fn lasx_xvmulwev_h_bu_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_h_bu_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_d_wu_w(a: v8u32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvaddwod_d_wu_w(a, b) } +pub fn lasx_xvaddwod_d_wu_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_d_wu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_w_hu_h(a: v16u16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvaddwod_w_hu_h(a, b) } +pub fn lasx_xvaddwod_w_hu_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_w_hu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_h_bu_b(a: v32u8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvaddwod_h_bu_b(a, b) } +pub fn lasx_xvaddwod_h_bu_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_h_bu_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_d_wu_w(a: v8u32, b: v8i32) -> v4i64 { - unsafe { __lasx_xvmulwod_d_wu_w(a, b) } +pub fn lasx_xvmulwod_d_wu_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_d_wu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_w_hu_h(a: v16u16, b: v16i16) -> v8i32 { - unsafe { __lasx_xvmulwod_w_hu_h(a, b) } +pub fn lasx_xvmulwod_w_hu_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_w_hu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_h_bu_b(a: v32u8, b: v32i8) -> v16i16 { - unsafe { __lasx_xvmulwod_h_bu_b(a, b) } +pub fn lasx_xvmulwod_h_bu_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_h_bu_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhaddw_q_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvhaddw_q_d(a, b) } +pub fn lasx_xvhaddw_q_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhaddw_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhaddw_qu_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvhaddw_qu_du(a, b) } +pub fn lasx_xvhaddw_qu_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhaddw_qu_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhsubw_q_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvhsubw_q_d(a, b) } +pub fn lasx_xvhsubw_q_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhsubw_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvhsubw_qu_du(a: v4u64, b: v4u64) -> v4u64 { - unsafe { __lasx_xvhsubw_qu_du(a, b) } +pub fn lasx_xvhsubw_qu_du(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvhsubw_qu_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_q_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64 { - unsafe { __lasx_xvmaddwev_q_d(a, b, c) } +pub fn lasx_xvmaddwev_q_d(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_q_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_d_w(a: v4i64, b: v8i32, c: v8i32) -> v4i64 { - unsafe { __lasx_xvmaddwev_d_w(a, b, c) } +pub fn lasx_xvmaddwev_d_w(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_d_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_w_h(a: v8i32, b: v16i16, c: v16i16) -> v8i32 { - unsafe { __lasx_xvmaddwev_w_h(a, b, c) } +pub fn lasx_xvmaddwev_w_h(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_w_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_h_b(a: v16i16, b: v32i8, c: v32i8) -> v16i16 { - unsafe { __lasx_xvmaddwev_h_b(a, b, c) } +pub fn lasx_xvmaddwev_h_b(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_h_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_q_du(a: v4u64, b: v4u64, c: v4u64) -> v4u64 { - unsafe { __lasx_xvmaddwev_q_du(a, b, c) } +pub fn lasx_xvmaddwev_q_du(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_q_du(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_d_wu(a: v4u64, b: v8u32, c: v8u32) -> v4u64 { - unsafe { __lasx_xvmaddwev_d_wu(a, b, c) } +pub fn lasx_xvmaddwev_d_wu(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_d_wu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_w_hu(a: v8u32, b: v16u16, c: v16u16) -> v8u32 { - unsafe { __lasx_xvmaddwev_w_hu(a, b, c) } +pub fn lasx_xvmaddwev_w_hu(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_w_hu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_h_bu(a: v16u16, b: v32u8, c: v32u8) -> v16u16 { - unsafe { __lasx_xvmaddwev_h_bu(a, b, c) } +pub fn lasx_xvmaddwev_h_bu(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_h_bu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_q_d(a: v4i64, b: v4i64, c: v4i64) -> v4i64 { - unsafe { __lasx_xvmaddwod_q_d(a, b, c) } +pub fn lasx_xvmaddwod_q_d(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_q_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_d_w(a: v4i64, b: v8i32, c: v8i32) -> v4i64 { - unsafe { __lasx_xvmaddwod_d_w(a, b, c) } +pub fn lasx_xvmaddwod_d_w(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_d_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_w_h(a: v8i32, b: v16i16, c: v16i16) -> v8i32 { - unsafe { __lasx_xvmaddwod_w_h(a, b, c) } +pub fn lasx_xvmaddwod_w_h(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_w_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_h_b(a: v16i16, b: v32i8, c: v32i8) -> v16i16 { - unsafe { __lasx_xvmaddwod_h_b(a, b, c) } +pub fn lasx_xvmaddwod_h_b(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_h_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_q_du(a: v4u64, b: v4u64, c: v4u64) -> v4u64 { - unsafe { __lasx_xvmaddwod_q_du(a, b, c) } +pub fn lasx_xvmaddwod_q_du(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_q_du(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_d_wu(a: v4u64, b: v8u32, c: v8u32) -> v4u64 { - unsafe { __lasx_xvmaddwod_d_wu(a, b, c) } +pub fn lasx_xvmaddwod_d_wu(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_d_wu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_w_hu(a: v8u32, b: v16u16, c: v16u16) -> v8u32 { - unsafe { __lasx_xvmaddwod_w_hu(a, b, c) } +pub fn lasx_xvmaddwod_w_hu(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_w_hu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_h_bu(a: v16u16, b: v32u8, c: v32u8) -> v16u16 { - unsafe { __lasx_xvmaddwod_h_bu(a, b, c) } +pub fn lasx_xvmaddwod_h_bu(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_h_bu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_q_du_d(a: v4i64, b: v4u64, c: v4i64) -> v4i64 { - unsafe { __lasx_xvmaddwev_q_du_d(a, b, c) } +pub fn lasx_xvmaddwev_q_du_d(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_q_du_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_d_wu_w(a: v4i64, b: v8u32, c: v8i32) -> v4i64 { - unsafe { __lasx_xvmaddwev_d_wu_w(a, b, c) } +pub fn lasx_xvmaddwev_d_wu_w(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_d_wu_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_w_hu_h(a: v8i32, b: v16u16, c: v16i16) -> v8i32 { - unsafe { __lasx_xvmaddwev_w_hu_h(a, b, c) } +pub fn lasx_xvmaddwev_w_hu_h(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_w_hu_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwev_h_bu_b(a: v16i16, b: v32u8, c: v32i8) -> v16i16 { - unsafe { __lasx_xvmaddwev_h_bu_b(a, b, c) } +pub fn lasx_xvmaddwev_h_bu_b(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwev_h_bu_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_q_du_d(a: v4i64, b: v4u64, c: v4i64) -> v4i64 { - unsafe { __lasx_xvmaddwod_q_du_d(a, b, c) } +pub fn lasx_xvmaddwod_q_du_d(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_q_du_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_d_wu_w(a: v4i64, b: v8u32, c: v8i32) -> v4i64 { - unsafe { __lasx_xvmaddwod_d_wu_w(a, b, c) } +pub fn lasx_xvmaddwod_d_wu_w(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_d_wu_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_w_hu_h(a: v8i32, b: v16u16, c: v16i16) -> v8i32 { - unsafe { __lasx_xvmaddwod_w_hu_h(a, b, c) } +pub fn lasx_xvmaddwod_w_hu_h(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_w_hu_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmaddwod_h_bu_b(a: v16i16, b: v32u8, c: v32i8) -> v16i16 { - unsafe { __lasx_xvmaddwod_h_bu_b(a, b, c) } +pub fn lasx_xvmaddwod_h_bu_b(a: m256i, b: m256i, c: m256i) -> m256i { + unsafe { transmute(__lasx_xvmaddwod_h_bu_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrotr_b(a: v32i8, b: v32i8) -> v32i8 { - unsafe { __lasx_xvrotr_b(a, b) } +pub fn lasx_xvrotr_b(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvrotr_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrotr_h(a: v16i16, b: v16i16) -> v16i16 { - unsafe { __lasx_xvrotr_h(a, b) } +pub fn lasx_xvrotr_h(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvrotr_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrotr_w(a: v8i32, b: v8i32) -> v8i32 { - unsafe { __lasx_xvrotr_w(a, b) } +pub fn lasx_xvrotr_w(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvrotr_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrotr_d(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvrotr_d(a, b) } +pub fn lasx_xvrotr_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvrotr_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvadd_q(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvadd_q(a, b) } +pub fn lasx_xvadd_q(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvadd_q(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsub_q(a: v4i64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvsub_q(a, b) } +pub fn lasx_xvsub_q(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvsub_q(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwev_q_du_d(a: v4u64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvaddwev_q_du_d(a, b) } +pub fn lasx_xvaddwev_q_du_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwev_q_du_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvaddwod_q_du_d(a: v4u64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvaddwod_q_du_d(a, b) } +pub fn lasx_xvaddwod_q_du_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvaddwod_q_du_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwev_q_du_d(a: v4u64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmulwev_q_du_d(a, b) } +pub fn lasx_xvmulwev_q_du_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwev_q_du_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmulwod_q_du_d(a: v4u64, b: v4i64) -> v4i64 { - unsafe { __lasx_xvmulwod_q_du_d(a, b) } +pub fn lasx_xvmulwod_q_du_d(a: m256i, b: m256i) -> m256i { + unsafe { transmute(__lasx_xvmulwod_q_du_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmskgez_b(a: v32i8) -> v32i8 { - unsafe { __lasx_xvmskgez_b(a) } +pub fn lasx_xvmskgez_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvmskgez_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvmsknz_b(a: v32i8) -> v32i8 { - unsafe { __lasx_xvmsknz_b(a) } +pub fn lasx_xvmsknz_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvmsknz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvexth_h_b(a: v32i8) -> v16i16 { - unsafe { __lasx_xvexth_h_b(a) } +pub fn lasx_xvexth_h_b(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvexth_h_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvexth_w_h(a: v16i16) -> v8i32 { - unsafe { __lasx_xvexth_w_h(a) } +pub fn lasx_xvexth_w_h(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvexth_w_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvexth_d_w(a: v8i32) -> v4i64 { - unsafe { __lasx_xvexth_d_w(a) } +pub fn lasx_xvexth_d_w(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvexth_d_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvexth_q_d(a: v4i64) -> v4i64 { - unsafe { __lasx_xvexth_q_d(a) } +pub fn lasx_xvexth_q_d(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvexth_q_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvexth_hu_bu(a: v32u8) -> v16u16 { - unsafe { __lasx_xvexth_hu_bu(a) } +pub fn lasx_xvexth_hu_bu(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvexth_hu_bu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvexth_wu_hu(a: v16u16) -> v8u32 { - unsafe { __lasx_xvexth_wu_hu(a) } +pub fn lasx_xvexth_wu_hu(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvexth_wu_hu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvexth_du_wu(a: v8u32) -> v4u64 { - unsafe { __lasx_xvexth_du_wu(a) } +pub fn lasx_xvexth_du_wu(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvexth_du_wu(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvexth_qu_du(a: v4u64) -> v4u64 { - unsafe { __lasx_xvexth_qu_du(a) } +pub fn lasx_xvexth_qu_du(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvexth_qu_du(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrotri_b(a: v32i8) -> v32i8 { +pub fn lasx_xvrotri_b(a: m256i) -> m256i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvrotri_b(a, IMM3) } + unsafe { transmute(__lasx_xvrotri_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrotri_h(a: v16i16) -> v16i16 { +pub fn lasx_xvrotri_h(a: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvrotri_h(a, IMM4) } + unsafe { transmute(__lasx_xvrotri_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrotri_w(a: v8i32) -> v8i32 { +pub fn lasx_xvrotri_w(a: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvrotri_w(a, IMM5) } + unsafe { transmute(__lasx_xvrotri_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrotri_d(a: v4i64) -> v4i64 { +pub fn lasx_xvrotri_d(a: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvrotri_d(a, IMM6) } + unsafe { transmute(__lasx_xvrotri_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvextl_q_d(a: v4i64) -> v4i64 { - unsafe { __lasx_xvextl_q_d(a) } +pub fn lasx_xvextl_q_d(a: m256i) -> m256i { + unsafe { transmute(__lasx_xvextl_q_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlni_b_h(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvsrlni_b_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsrlni_b_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvsrlni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlni_h_w(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvsrlni_h_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsrlni_h_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvsrlni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlni_w_d(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvsrlni_w_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsrlni_w_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvsrlni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlni_d_q(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvsrlni_d_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvsrlni_d_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvsrlni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlrni_b_h(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvsrlrni_b_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsrlrni_b_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvsrlrni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlrni_h_w(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvsrlrni_h_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsrlrni_h_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvsrlrni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlrni_w_d(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvsrlrni_w_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsrlrni_w_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvsrlrni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrlrni_d_q(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvsrlrni_d_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvsrlrni_d_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvsrlrni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlni_b_h(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvssrlni_b_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvssrlni_b_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvssrlni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlni_h_w(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvssrlni_h_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvssrlni_h_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvssrlni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlni_w_d(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvssrlni_w_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvssrlni_w_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvssrlni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlni_d_q(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvssrlni_d_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvssrlni_d_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvssrlni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlni_bu_h(a: v32u8, b: v32i8) -> v32u8 { +pub fn lasx_xvssrlni_bu_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvssrlni_bu_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvssrlni_bu_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlni_hu_w(a: v16u16, b: v16i16) -> v16u16 { +pub fn lasx_xvssrlni_hu_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvssrlni_hu_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvssrlni_hu_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlni_wu_d(a: v8u32, b: v8i32) -> v8u32 { +pub fn lasx_xvssrlni_wu_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvssrlni_wu_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvssrlni_wu_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlni_du_q(a: v4u64, b: v4i64) -> v4u64 { +pub fn lasx_xvssrlni_du_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvssrlni_du_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvssrlni_du_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrni_b_h(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvssrlrni_b_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvssrlrni_b_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvssrlrni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrni_h_w(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvssrlrni_h_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvssrlrni_h_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvssrlrni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrni_w_d(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvssrlrni_w_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvssrlrni_w_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvssrlrni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrni_d_q(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvssrlrni_d_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvssrlrni_d_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvssrlrni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrni_bu_h(a: v32u8, b: v32i8) -> v32u8 { +pub fn lasx_xvssrlrni_bu_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvssrlrni_bu_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvssrlrni_bu_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrni_hu_w(a: v16u16, b: v16i16) -> v16u16 { +pub fn lasx_xvssrlrni_hu_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvssrlrni_hu_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvssrlrni_hu_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrni_wu_d(a: v8u32, b: v8i32) -> v8u32 { +pub fn lasx_xvssrlrni_wu_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvssrlrni_wu_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvssrlrni_wu_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrlrni_du_q(a: v4u64, b: v4i64) -> v4u64 { +pub fn lasx_xvssrlrni_du_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvssrlrni_du_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvssrlrni_du_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrani_b_h(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvsrani_b_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsrani_b_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvsrani_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrani_h_w(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvsrani_h_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsrani_h_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvsrani_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrani_w_d(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvsrani_w_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsrani_w_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvsrani_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrani_d_q(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvsrani_d_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvsrani_d_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvsrani_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrarni_b_h(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvsrarni_b_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvsrarni_b_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvsrarni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrarni_h_w(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvsrarni_h_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvsrarni_h_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvsrarni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrarni_w_d(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvsrarni_w_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvsrarni_w_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvsrarni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvsrarni_d_q(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvsrarni_d_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvsrarni_d_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvsrarni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrani_b_h(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvssrani_b_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvssrani_b_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvssrani_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrani_h_w(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvssrani_h_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvssrani_h_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvssrani_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrani_w_d(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvssrani_w_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvssrani_w_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvssrani_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrani_d_q(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvssrani_d_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvssrani_d_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvssrani_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrani_bu_h(a: v32u8, b: v32i8) -> v32u8 { +pub fn lasx_xvssrani_bu_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvssrani_bu_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvssrani_bu_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrani_hu_w(a: v16u16, b: v16i16) -> v16u16 { +pub fn lasx_xvssrani_hu_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvssrani_hu_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvssrani_hu_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrani_wu_d(a: v8u32, b: v8i32) -> v8u32 { +pub fn lasx_xvssrani_wu_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvssrani_wu_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvssrani_wu_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrani_du_q(a: v4u64, b: v4i64) -> v4u64 { +pub fn lasx_xvssrani_du_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvssrani_du_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvssrani_du_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarni_b_h(a: v32i8, b: v32i8) -> v32i8 { +pub fn lasx_xvssrarni_b_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvssrarni_b_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvssrarni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarni_h_w(a: v16i16, b: v16i16) -> v16i16 { +pub fn lasx_xvssrarni_h_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvssrarni_h_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvssrarni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarni_w_d(a: v8i32, b: v8i32) -> v8i32 { +pub fn lasx_xvssrarni_w_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvssrarni_w_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvssrarni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarni_d_q(a: v4i64, b: v4i64) -> v4i64 { +pub fn lasx_xvssrarni_d_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvssrarni_d_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvssrarni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarni_bu_h(a: v32u8, b: v32i8) -> v32u8 { +pub fn lasx_xvssrarni_bu_h(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lasx_xvssrarni_bu_h(a, b, IMM4) } + unsafe { transmute(__lasx_xvssrarni_bu_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarni_hu_w(a: v16u16, b: v16i16) -> v16u16 { +pub fn lasx_xvssrarni_hu_w(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lasx_xvssrarni_hu_w(a, b, IMM5) } + unsafe { transmute(__lasx_xvssrarni_hu_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarni_wu_d(a: v8u32, b: v8i32) -> v8u32 { +pub fn lasx_xvssrarni_wu_d(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lasx_xvssrarni_wu_d(a, b, IMM6) } + unsafe { transmute(__lasx_xvssrarni_wu_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvssrarni_du_q(a: v4u64, b: v4i64) -> v4u64 { +pub fn lasx_xvssrarni_du_q(a: m256i, b: m256i) -> m256i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lasx_xvssrarni_du_q(a, b, IMM7) } + unsafe { transmute(__lasx_xvssrarni_du_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbnz_b(a: v32u8) -> i32 { - unsafe { __lasx_xbnz_b(a) } +pub fn lasx_xbnz_b(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbnz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbnz_d(a: v4u64) -> i32 { - unsafe { __lasx_xbnz_d(a) } +pub fn lasx_xbnz_d(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbnz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbnz_h(a: v16u16) -> i32 { - unsafe { __lasx_xbnz_h(a) } +pub fn lasx_xbnz_h(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbnz_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbnz_v(a: v32u8) -> i32 { - unsafe { __lasx_xbnz_v(a) } +pub fn lasx_xbnz_v(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbnz_v(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbnz_w(a: v8u32) -> i32 { - unsafe { __lasx_xbnz_w(a) } +pub fn lasx_xbnz_w(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbnz_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbz_b(a: v32u8) -> i32 { - unsafe { __lasx_xbz_b(a) } +pub fn lasx_xbz_b(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbz_d(a: v4u64) -> i32 { - unsafe { __lasx_xbz_d(a) } +pub fn lasx_xbz_d(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbz_h(a: v16u16) -> i32 { - unsafe { __lasx_xbz_h(a) } +pub fn lasx_xbz_h(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbz_h(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbz_v(a: v32u8) -> i32 { - unsafe { __lasx_xbz_v(a) } +pub fn lasx_xbz_v(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbz_v(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xbz_w(a: v8u32) -> i32 { - unsafe { __lasx_xbz_w(a) } +pub fn lasx_xbz_w(a: m256i) -> i32 { + unsafe { transmute(__lasx_xbz_w(transmute(a))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_caf_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_caf_d(a, b) } +pub fn lasx_xvfcmp_caf_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_caf_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_caf_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_caf_s(a, b) } +pub fn lasx_xvfcmp_caf_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_caf_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_ceq_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_ceq_d(a, b) } +pub fn lasx_xvfcmp_ceq_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_ceq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_ceq_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_ceq_s(a, b) } +pub fn lasx_xvfcmp_ceq_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_ceq_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cle_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_cle_d(a, b) } +pub fn lasx_xvfcmp_cle_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cle_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cle_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_cle_s(a, b) } +pub fn lasx_xvfcmp_cle_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cle_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_clt_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_clt_d(a, b) } +pub fn lasx_xvfcmp_clt_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_clt_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_clt_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_clt_s(a, b) } +pub fn lasx_xvfcmp_clt_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_clt_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cne_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_cne_d(a, b) } +pub fn lasx_xvfcmp_cne_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cne_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cne_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_cne_s(a, b) } +pub fn lasx_xvfcmp_cne_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cne_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cor_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_cor_d(a, b) } +pub fn lasx_xvfcmp_cor_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cor_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cor_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_cor_s(a, b) } +pub fn lasx_xvfcmp_cor_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cor_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cueq_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_cueq_d(a, b) } +pub fn lasx_xvfcmp_cueq_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cueq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cueq_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_cueq_s(a, b) } +pub fn lasx_xvfcmp_cueq_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cueq_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cule_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_cule_d(a, b) } +pub fn lasx_xvfcmp_cule_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cule_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cule_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_cule_s(a, b) } +pub fn lasx_xvfcmp_cule_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cule_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cult_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_cult_d(a, b) } +pub fn lasx_xvfcmp_cult_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cult_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cult_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_cult_s(a, b) } +pub fn lasx_xvfcmp_cult_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cult_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cun_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_cun_d(a, b) } +pub fn lasx_xvfcmp_cun_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cun_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cune_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_cune_d(a, b) } +pub fn lasx_xvfcmp_cune_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cune_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cune_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_cune_s(a, b) } +pub fn lasx_xvfcmp_cune_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cune_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_cun_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_cun_s(a, b) } +pub fn lasx_xvfcmp_cun_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_cun_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_saf_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_saf_d(a, b) } +pub fn lasx_xvfcmp_saf_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_saf_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_saf_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_saf_s(a, b) } +pub fn lasx_xvfcmp_saf_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_saf_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_seq_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_seq_d(a, b) } +pub fn lasx_xvfcmp_seq_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_seq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_seq_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_seq_s(a, b) } +pub fn lasx_xvfcmp_seq_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_seq_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sle_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_sle_d(a, b) } +pub fn lasx_xvfcmp_sle_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sle_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sle_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_sle_s(a, b) } +pub fn lasx_xvfcmp_sle_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sle_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_slt_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_slt_d(a, b) } +pub fn lasx_xvfcmp_slt_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_slt_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_slt_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_slt_s(a, b) } +pub fn lasx_xvfcmp_slt_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_slt_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sne_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_sne_d(a, b) } +pub fn lasx_xvfcmp_sne_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sne_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sne_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_sne_s(a, b) } +pub fn lasx_xvfcmp_sne_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sne_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sor_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_sor_d(a, b) } +pub fn lasx_xvfcmp_sor_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sor_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sor_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_sor_s(a, b) } +pub fn lasx_xvfcmp_sor_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sor_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sueq_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_sueq_d(a, b) } +pub fn lasx_xvfcmp_sueq_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sueq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sueq_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_sueq_s(a, b) } +pub fn lasx_xvfcmp_sueq_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sueq_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sule_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_sule_d(a, b) } +pub fn lasx_xvfcmp_sule_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sule_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sule_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_sule_s(a, b) } +pub fn lasx_xvfcmp_sule_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sule_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sult_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_sult_d(a, b) } +pub fn lasx_xvfcmp_sult_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sult_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sult_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_sult_s(a, b) } +pub fn lasx_xvfcmp_sult_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sult_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sun_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_sun_d(a, b) } +pub fn lasx_xvfcmp_sun_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sun_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sune_d(a: v4f64, b: v4f64) -> v4i64 { - unsafe { __lasx_xvfcmp_sune_d(a, b) } +pub fn lasx_xvfcmp_sune_d(a: m256d, b: m256d) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sune_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sune_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_sune_s(a, b) } +pub fn lasx_xvfcmp_sune_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sune_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvfcmp_sun_s(a: v8f32, b: v8f32) -> v8i32 { - unsafe { __lasx_xvfcmp_sun_s(a, b) } +pub fn lasx_xvfcmp_sun_s(a: m256, b: m256) -> m256i { + unsafe { transmute(__lasx_xvfcmp_sun_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickve_d_f(a: v4f64) -> v4f64 { +pub fn lasx_xvpickve_d_f(a: m256d) -> m256d { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lasx_xvpickve_d_f(a, IMM2) } + unsafe { transmute(__lasx_xvpickve_d_f(transmute(a), IMM2)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvpickve_w_f(a: v8f32) -> v8f32 { +pub fn lasx_xvpickve_w_f(a: m256) -> m256 { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lasx_xvpickve_w_f(a, IMM3) } + unsafe { transmute(__lasx_xvpickve_w_f(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrepli_b() -> v32i8 { +pub fn lasx_xvrepli_b() -> m256i { static_assert_simm_bits!(IMM_S10, 10); - unsafe { __lasx_xvrepli_b(IMM_S10) } + unsafe { transmute(__lasx_xvrepli_b(IMM_S10)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrepli_d() -> v4i64 { +pub fn lasx_xvrepli_d() -> m256i { static_assert_simm_bits!(IMM_S10, 10); - unsafe { __lasx_xvrepli_d(IMM_S10) } + unsafe { transmute(__lasx_xvrepli_d(IMM_S10)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrepli_h() -> v16i16 { +pub fn lasx_xvrepli_h() -> m256i { static_assert_simm_bits!(IMM_S10, 10); - unsafe { __lasx_xvrepli_h(IMM_S10) } + unsafe { transmute(__lasx_xvrepli_h(IMM_S10)) } } #[inline] #[target_feature(enable = "lasx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lasx_xvrepli_w() -> v8i32 { +pub fn lasx_xvrepli_w() -> m256i { static_assert_simm_bits!(IMM_S10, 10); - unsafe { __lasx_xvrepli_w(IMM_S10) } + unsafe { transmute(__lasx_xvrepli_w(IMM_S10)) } } diff --git a/library/stdarch/crates/core_arch/src/loongarch64/lasx/types.rs b/library/stdarch/crates/core_arch/src/loongarch64/lasx/types.rs index 9611517e6370..a8ceede87390 100644 --- a/library/stdarch/crates/core_arch/src/loongarch64/lasx/types.rs +++ b/library/stdarch/crates/core_arch/src/loongarch64/lasx/types.rs @@ -1,33 +1,140 @@ types! { #![unstable(feature = "stdarch_loongarch", issue = "117427")] - /// LOONGARCH-specific 256-bit wide vector of 32 packed `i8`. - pub struct v32i8(32 x pub(crate) i8); + /// 256-bit wide integer vector type, LoongArch-specific + /// + /// This type is the same as the `__m256i` type defined in `lasxintrin.h`, + /// representing a 256-bit SIMD register. Usage of this type typically + /// occurs in conjunction with the `lasx` target features for LoongArch. + /// + /// Internally this type may be viewed as: + /// + /// * `i8x32` - thirty two `i8` values packed together + /// * `i16x16` - sixteen `i16` values packed together + /// * `i32x8` - eight `i32` values packed together + /// * `i64x4` - four `i64` values packed together + /// + /// (as well as unsigned versions). Each intrinsic may interpret the + /// internal bits differently, check the documentation of the intrinsic + /// to see how it's being used. + /// + /// The in-memory representation of this type is the same as the one of an + /// equivalent array (i.e. the in-memory order of elements is the same, and + /// there is no padding); however, the alignment is different and equal to + /// the size of the type. Note that the ABI for function calls may *not* be + /// the same. + /// + /// Note that this means that an instance of `m256i` typically just means + /// a "bag of bits" which is left up to interpretation at the point of use. + /// + /// Most intrinsics using `m256i` are prefixed with `lasx_` and the integer + /// types tend to correspond to suffixes like "b", "h", "w" or "d". + pub struct m256i(4 x i64); - /// LOONGARCH-specific 256-bit wide vector of 16 packed `i16`. - pub struct v16i16(16 x pub(crate) i16); + /// 256-bit wide set of eight `f32` values, LoongArch-specific + /// + /// This type is the same as the `__m256` type defined in `lasxintrin.h`, + /// representing a 256-bit SIMD register which internally consists of + /// eight packed `f32` instances. Usage of this type typically occurs in + /// conjunction with the `lasx` target features for LoongArch. + /// + /// Note that unlike `m256i`, the integer version of the 256-bit registers, + /// this `m256` type has *one* interpretation. Each instance of `m256` + /// always corresponds to `f32x8`, or eight `f32` values packed together. + /// + /// The in-memory representation of this type is the same as the one of an + /// equivalent array (i.e. the in-memory order of elements is the same, and + /// there is no padding between two consecutive elements); however, the + /// alignment is different and equal to the size of the type. Note that the + /// ABI for function calls may *not* be the same. + /// + /// Most intrinsics using `m256` are prefixed with `lasx_` and are + /// suffixed with "s". + pub struct m256(8 x f32); - /// LOONGARCH-specific 256-bit wide vector of 8 packed `i32`. - pub struct v8i32(8 x pub(crate) i32); + /// 256-bit wide set of four `f64` values, LoongArch-specific + /// + /// This type is the same as the `__m256d` type defined in `lasxintrin.h`, + /// representing a 256-bit SIMD register which internally consists of + /// four packed `f64` instances. Usage of this type typically occurs in + /// conjunction with the `lasx` target features for LoongArch. + /// + /// Note that unlike `m256i`, the integer version of the 256-bit registers, + /// this `m256d` type has *one* interpretation. Each instance of `m256d` + /// always corresponds to `f64x4`, or four `f64` values packed together. + /// + /// The in-memory representation of this type is the same as the one of an + /// equivalent array (i.e. the in-memory order of elements is the same, and + /// there is no padding); however, the alignment is different and equal to + /// the size of the type. Note that the ABI for function calls may *not* be + /// the same. + /// + /// Most intrinsics using `m256d` are prefixed with `lasx_` and are suffixed + /// with "d". Not to be confused with "d" which is used for `m256i`. + pub struct m256d(4 x f64); - /// LOONGARCH-specific 256-bit wide vector of 4 packed `i64`. - pub struct v4i64(4 x pub(crate) i64); - - /// LOONGARCH-specific 256-bit wide vector of 32 packed `u8`. - pub struct v32u8(32 x pub(crate) u8); - - /// LOONGARCH-specific 256-bit wide vector of 16 packed `u16`. - pub struct v16u16(16 x pub(crate) u16); - - /// LOONGARCH-specific 256-bit wide vector of 8 packed `u32`. - pub struct v8u32(8 x pub(crate) u32); - - /// LOONGARCH-specific 256-bit wide vector of 4 packed `u64`. - pub struct v4u64(4 x pub(crate) u64); +} - /// LOONGARCH-specific 128-bit wide vector of 8 packed `f32`. - pub struct v8f32(8 x pub(crate) f32); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v32i8([i8; 32]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v16i16([i16; 16]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v8i32([i32; 8]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v4i64([i64; 4]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v32u8([u8; 32]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v16u16([u16; 16]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v8u32([u32; 8]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v4u64([u64; 4]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v8f32([f32; 8]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v4f64([f64; 4]); - /// LOONGARCH-specific 256-bit wide vector of 4 packed `f64`. - pub struct v4f64(4 x pub(crate) f64); -} +// These type aliases are provided solely for transitional compatibility. +// They are temporary and will be removed when appropriate. +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v32i8 = m256i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v16i16 = m256i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v8i32 = m256i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v4i64 = m256i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v32u8 = m256i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v16u16 = m256i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v8u32 = m256i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v4u64 = m256i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v8f32 = m256; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v4f64 = m256d; diff --git a/library/stdarch/crates/core_arch/src/loongarch64/lsx/generated.rs b/library/stdarch/crates/core_arch/src/loongarch64/lsx/generated.rs index ba821a3e3dc6..764e69ca0544 100644 --- a/library/stdarch/crates/core_arch/src/loongarch64/lsx/generated.rs +++ b/library/stdarch/crates/core_arch/src/loongarch64/lsx/generated.rs @@ -6,6874 +6,6875 @@ // OUT_DIR=`pwd`/crates/core_arch cargo run -p stdarch-gen-loongarch -- crates/stdarch-gen-loongarch/lsx.spec // ``` +use crate::mem::transmute; use super::types::*; #[allow(improper_ctypes)] unsafe extern "unadjusted" { #[link_name = "llvm.loongarch.lsx.vsll.b"] - fn __lsx_vsll_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsll_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsll.h"] - fn __lsx_vsll_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsll_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsll.w"] - fn __lsx_vsll_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsll_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsll.d"] - fn __lsx_vsll_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsll_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vslli.b"] - fn __lsx_vslli_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vslli_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vslli.h"] - fn __lsx_vslli_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vslli_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vslli.w"] - fn __lsx_vslli_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vslli_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vslli.d"] - fn __lsx_vslli_d(a: v2i64, b: u32) -> v2i64; + fn __lsx_vslli_d(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsra.b"] - fn __lsx_vsra_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsra_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsra.h"] - fn __lsx_vsra_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsra_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsra.w"] - fn __lsx_vsra_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsra_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsra.d"] - fn __lsx_vsra_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsra_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrai.b"] - fn __lsx_vsrai_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vsrai_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrai.h"] - fn __lsx_vsrai_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vsrai_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrai.w"] - fn __lsx_vsrai_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vsrai_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrai.d"] - fn __lsx_vsrai_d(a: v2i64, b: u32) -> v2i64; + fn __lsx_vsrai_d(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrar.b"] - fn __lsx_vsrar_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsrar_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrar.h"] - fn __lsx_vsrar_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsrar_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrar.w"] - fn __lsx_vsrar_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsrar_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrar.d"] - fn __lsx_vsrar_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsrar_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrari.b"] - fn __lsx_vsrari_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vsrari_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrari.h"] - fn __lsx_vsrari_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vsrari_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrari.w"] - fn __lsx_vsrari_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vsrari_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrari.d"] - fn __lsx_vsrari_d(a: v2i64, b: u32) -> v2i64; + fn __lsx_vsrari_d(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrl.b"] - fn __lsx_vsrl_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsrl_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrl.h"] - fn __lsx_vsrl_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsrl_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrl.w"] - fn __lsx_vsrl_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsrl_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrl.d"] - fn __lsx_vsrl_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsrl_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrli.b"] - fn __lsx_vsrli_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vsrli_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrli.h"] - fn __lsx_vsrli_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vsrli_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrli.w"] - fn __lsx_vsrli_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vsrli_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrli.d"] - fn __lsx_vsrli_d(a: v2i64, b: u32) -> v2i64; + fn __lsx_vsrli_d(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrlr.b"] - fn __lsx_vsrlr_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsrlr_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrlr.h"] - fn __lsx_vsrlr_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsrlr_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrlr.w"] - fn __lsx_vsrlr_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsrlr_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrlr.d"] - fn __lsx_vsrlr_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsrlr_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrlri.b"] - fn __lsx_vsrlri_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vsrlri_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrlri.h"] - fn __lsx_vsrlri_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vsrlri_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrlri.w"] - fn __lsx_vsrlri_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vsrlri_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrlri.d"] - fn __lsx_vsrlri_d(a: v2i64, b: u32) -> v2i64; + fn __lsx_vsrlri_d(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vbitclr.b"] - fn __lsx_vbitclr_b(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vbitclr_b(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vbitclr.h"] - fn __lsx_vbitclr_h(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vbitclr_h(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vbitclr.w"] - fn __lsx_vbitclr_w(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vbitclr_w(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vbitclr.d"] - fn __lsx_vbitclr_d(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vbitclr_d(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vbitclri.b"] - fn __lsx_vbitclri_b(a: v16u8, b: u32) -> v16u8; + fn __lsx_vbitclri_b(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vbitclri.h"] - fn __lsx_vbitclri_h(a: v8u16, b: u32) -> v8u16; + fn __lsx_vbitclri_h(a: __v8u16, b: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vbitclri.w"] - fn __lsx_vbitclri_w(a: v4u32, b: u32) -> v4u32; + fn __lsx_vbitclri_w(a: __v4u32, b: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vbitclri.d"] - fn __lsx_vbitclri_d(a: v2u64, b: u32) -> v2u64; + fn __lsx_vbitclri_d(a: __v2u64, b: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vbitset.b"] - fn __lsx_vbitset_b(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vbitset_b(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vbitset.h"] - fn __lsx_vbitset_h(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vbitset_h(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vbitset.w"] - fn __lsx_vbitset_w(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vbitset_w(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vbitset.d"] - fn __lsx_vbitset_d(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vbitset_d(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vbitseti.b"] - fn __lsx_vbitseti_b(a: v16u8, b: u32) -> v16u8; + fn __lsx_vbitseti_b(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vbitseti.h"] - fn __lsx_vbitseti_h(a: v8u16, b: u32) -> v8u16; + fn __lsx_vbitseti_h(a: __v8u16, b: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vbitseti.w"] - fn __lsx_vbitseti_w(a: v4u32, b: u32) -> v4u32; + fn __lsx_vbitseti_w(a: __v4u32, b: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vbitseti.d"] - fn __lsx_vbitseti_d(a: v2u64, b: u32) -> v2u64; + fn __lsx_vbitseti_d(a: __v2u64, b: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vbitrev.b"] - fn __lsx_vbitrev_b(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vbitrev_b(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vbitrev.h"] - fn __lsx_vbitrev_h(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vbitrev_h(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vbitrev.w"] - fn __lsx_vbitrev_w(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vbitrev_w(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vbitrev.d"] - fn __lsx_vbitrev_d(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vbitrev_d(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vbitrevi.b"] - fn __lsx_vbitrevi_b(a: v16u8, b: u32) -> v16u8; + fn __lsx_vbitrevi_b(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vbitrevi.h"] - fn __lsx_vbitrevi_h(a: v8u16, b: u32) -> v8u16; + fn __lsx_vbitrevi_h(a: __v8u16, b: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vbitrevi.w"] - fn __lsx_vbitrevi_w(a: v4u32, b: u32) -> v4u32; + fn __lsx_vbitrevi_w(a: __v4u32, b: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vbitrevi.d"] - fn __lsx_vbitrevi_d(a: v2u64, b: u32) -> v2u64; + fn __lsx_vbitrevi_d(a: __v2u64, b: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vadd.b"] - fn __lsx_vadd_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vadd_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vadd.h"] - fn __lsx_vadd_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vadd_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vadd.w"] - fn __lsx_vadd_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vadd_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vadd.d"] - fn __lsx_vadd_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vadd_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddi.bu"] - fn __lsx_vaddi_bu(a: v16i8, b: u32) -> v16i8; + fn __lsx_vaddi_bu(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vaddi.hu"] - fn __lsx_vaddi_hu(a: v8i16, b: u32) -> v8i16; + fn __lsx_vaddi_hu(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vaddi.wu"] - fn __lsx_vaddi_wu(a: v4i32, b: u32) -> v4i32; + fn __lsx_vaddi_wu(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vaddi.du"] - fn __lsx_vaddi_du(a: v2i64, b: u32) -> v2i64; + fn __lsx_vaddi_du(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsub.b"] - fn __lsx_vsub_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsub_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsub.h"] - fn __lsx_vsub_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsub_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsub.w"] - fn __lsx_vsub_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsub_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsub.d"] - fn __lsx_vsub_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsub_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubi.bu"] - fn __lsx_vsubi_bu(a: v16i8, b: u32) -> v16i8; + fn __lsx_vsubi_bu(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsubi.hu"] - fn __lsx_vsubi_hu(a: v8i16, b: u32) -> v8i16; + fn __lsx_vsubi_hu(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsubi.wu"] - fn __lsx_vsubi_wu(a: v4i32, b: u32) -> v4i32; + fn __lsx_vsubi_wu(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsubi.du"] - fn __lsx_vsubi_du(a: v2i64, b: u32) -> v2i64; + fn __lsx_vsubi_du(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmax.b"] - fn __lsx_vmax_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vmax_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmax.h"] - fn __lsx_vmax_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vmax_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmax.w"] - fn __lsx_vmax_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vmax_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmax.d"] - fn __lsx_vmax_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vmax_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmaxi.b"] - fn __lsx_vmaxi_b(a: v16i8, b: i32) -> v16i8; + fn __lsx_vmaxi_b(a: __v16i8, b: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmaxi.h"] - fn __lsx_vmaxi_h(a: v8i16, b: i32) -> v8i16; + fn __lsx_vmaxi_h(a: __v8i16, b: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmaxi.w"] - fn __lsx_vmaxi_w(a: v4i32, b: i32) -> v4i32; + fn __lsx_vmaxi_w(a: __v4i32, b: i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmaxi.d"] - fn __lsx_vmaxi_d(a: v2i64, b: i32) -> v2i64; + fn __lsx_vmaxi_d(a: __v2i64, b: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmax.bu"] - fn __lsx_vmax_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vmax_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vmax.hu"] - fn __lsx_vmax_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vmax_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vmax.wu"] - fn __lsx_vmax_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vmax_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vmax.du"] - fn __lsx_vmax_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vmax_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmaxi.bu"] - fn __lsx_vmaxi_bu(a: v16u8, b: u32) -> v16u8; + fn __lsx_vmaxi_bu(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vmaxi.hu"] - fn __lsx_vmaxi_hu(a: v8u16, b: u32) -> v8u16; + fn __lsx_vmaxi_hu(a: __v8u16, b: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vmaxi.wu"] - fn __lsx_vmaxi_wu(a: v4u32, b: u32) -> v4u32; + fn __lsx_vmaxi_wu(a: __v4u32, b: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vmaxi.du"] - fn __lsx_vmaxi_du(a: v2u64, b: u32) -> v2u64; + fn __lsx_vmaxi_du(a: __v2u64, b: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmin.b"] - fn __lsx_vmin_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vmin_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmin.h"] - fn __lsx_vmin_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vmin_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmin.w"] - fn __lsx_vmin_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vmin_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmin.d"] - fn __lsx_vmin_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vmin_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmini.b"] - fn __lsx_vmini_b(a: v16i8, b: i32) -> v16i8; + fn __lsx_vmini_b(a: __v16i8, b: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmini.h"] - fn __lsx_vmini_h(a: v8i16, b: i32) -> v8i16; + fn __lsx_vmini_h(a: __v8i16, b: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmini.w"] - fn __lsx_vmini_w(a: v4i32, b: i32) -> v4i32; + fn __lsx_vmini_w(a: __v4i32, b: i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmini.d"] - fn __lsx_vmini_d(a: v2i64, b: i32) -> v2i64; + fn __lsx_vmini_d(a: __v2i64, b: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmin.bu"] - fn __lsx_vmin_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vmin_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vmin.hu"] - fn __lsx_vmin_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vmin_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vmin.wu"] - fn __lsx_vmin_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vmin_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vmin.du"] - fn __lsx_vmin_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vmin_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmini.bu"] - fn __lsx_vmini_bu(a: v16u8, b: u32) -> v16u8; + fn __lsx_vmini_bu(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vmini.hu"] - fn __lsx_vmini_hu(a: v8u16, b: u32) -> v8u16; + fn __lsx_vmini_hu(a: __v8u16, b: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vmini.wu"] - fn __lsx_vmini_wu(a: v4u32, b: u32) -> v4u32; + fn __lsx_vmini_wu(a: __v4u32, b: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vmini.du"] - fn __lsx_vmini_du(a: v2u64, b: u32) -> v2u64; + fn __lsx_vmini_du(a: __v2u64, b: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vseq.b"] - fn __lsx_vseq_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vseq_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vseq.h"] - fn __lsx_vseq_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vseq_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vseq.w"] - fn __lsx_vseq_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vseq_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vseq.d"] - fn __lsx_vseq_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vseq_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vseqi.b"] - fn __lsx_vseqi_b(a: v16i8, b: i32) -> v16i8; + fn __lsx_vseqi_b(a: __v16i8, b: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vseqi.h"] - fn __lsx_vseqi_h(a: v8i16, b: i32) -> v8i16; + fn __lsx_vseqi_h(a: __v8i16, b: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vseqi.w"] - fn __lsx_vseqi_w(a: v4i32, b: i32) -> v4i32; + fn __lsx_vseqi_w(a: __v4i32, b: i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vseqi.d"] - fn __lsx_vseqi_d(a: v2i64, b: i32) -> v2i64; + fn __lsx_vseqi_d(a: __v2i64, b: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vslti.b"] - fn __lsx_vslti_b(a: v16i8, b: i32) -> v16i8; + fn __lsx_vslti_b(a: __v16i8, b: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vslt.b"] - fn __lsx_vslt_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vslt_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vslt.h"] - fn __lsx_vslt_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vslt_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vslt.w"] - fn __lsx_vslt_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vslt_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vslt.d"] - fn __lsx_vslt_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vslt_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vslti.h"] - fn __lsx_vslti_h(a: v8i16, b: i32) -> v8i16; + fn __lsx_vslti_h(a: __v8i16, b: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vslti.w"] - fn __lsx_vslti_w(a: v4i32, b: i32) -> v4i32; + fn __lsx_vslti_w(a: __v4i32, b: i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vslti.d"] - fn __lsx_vslti_d(a: v2i64, b: i32) -> v2i64; + fn __lsx_vslti_d(a: __v2i64, b: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vslt.bu"] - fn __lsx_vslt_bu(a: v16u8, b: v16u8) -> v16i8; + fn __lsx_vslt_bu(a: __v16u8, b: __v16u8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vslt.hu"] - fn __lsx_vslt_hu(a: v8u16, b: v8u16) -> v8i16; + fn __lsx_vslt_hu(a: __v8u16, b: __v8u16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vslt.wu"] - fn __lsx_vslt_wu(a: v4u32, b: v4u32) -> v4i32; + fn __lsx_vslt_wu(a: __v4u32, b: __v4u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vslt.du"] - fn __lsx_vslt_du(a: v2u64, b: v2u64) -> v2i64; + fn __lsx_vslt_du(a: __v2u64, b: __v2u64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vslti.bu"] - fn __lsx_vslti_bu(a: v16u8, b: u32) -> v16i8; + fn __lsx_vslti_bu(a: __v16u8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vslti.hu"] - fn __lsx_vslti_hu(a: v8u16, b: u32) -> v8i16; + fn __lsx_vslti_hu(a: __v8u16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vslti.wu"] - fn __lsx_vslti_wu(a: v4u32, b: u32) -> v4i32; + fn __lsx_vslti_wu(a: __v4u32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vslti.du"] - fn __lsx_vslti_du(a: v2u64, b: u32) -> v2i64; + fn __lsx_vslti_du(a: __v2u64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsle.b"] - fn __lsx_vsle_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsle_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsle.h"] - fn __lsx_vsle_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsle_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsle.w"] - fn __lsx_vsle_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsle_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsle.d"] - fn __lsx_vsle_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsle_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vslei.b"] - fn __lsx_vslei_b(a: v16i8, b: i32) -> v16i8; + fn __lsx_vslei_b(a: __v16i8, b: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vslei.h"] - fn __lsx_vslei_h(a: v8i16, b: i32) -> v8i16; + fn __lsx_vslei_h(a: __v8i16, b: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vslei.w"] - fn __lsx_vslei_w(a: v4i32, b: i32) -> v4i32; + fn __lsx_vslei_w(a: __v4i32, b: i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vslei.d"] - fn __lsx_vslei_d(a: v2i64, b: i32) -> v2i64; + fn __lsx_vslei_d(a: __v2i64, b: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsle.bu"] - fn __lsx_vsle_bu(a: v16u8, b: v16u8) -> v16i8; + fn __lsx_vsle_bu(a: __v16u8, b: __v16u8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsle.hu"] - fn __lsx_vsle_hu(a: v8u16, b: v8u16) -> v8i16; + fn __lsx_vsle_hu(a: __v8u16, b: __v8u16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsle.wu"] - fn __lsx_vsle_wu(a: v4u32, b: v4u32) -> v4i32; + fn __lsx_vsle_wu(a: __v4u32, b: __v4u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsle.du"] - fn __lsx_vsle_du(a: v2u64, b: v2u64) -> v2i64; + fn __lsx_vsle_du(a: __v2u64, b: __v2u64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vslei.bu"] - fn __lsx_vslei_bu(a: v16u8, b: u32) -> v16i8; + fn __lsx_vslei_bu(a: __v16u8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vslei.hu"] - fn __lsx_vslei_hu(a: v8u16, b: u32) -> v8i16; + fn __lsx_vslei_hu(a: __v8u16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vslei.wu"] - fn __lsx_vslei_wu(a: v4u32, b: u32) -> v4i32; + fn __lsx_vslei_wu(a: __v4u32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vslei.du"] - fn __lsx_vslei_du(a: v2u64, b: u32) -> v2i64; + fn __lsx_vslei_du(a: __v2u64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsat.b"] - fn __lsx_vsat_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vsat_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsat.h"] - fn __lsx_vsat_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vsat_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsat.w"] - fn __lsx_vsat_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vsat_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsat.d"] - fn __lsx_vsat_d(a: v2i64, b: u32) -> v2i64; + fn __lsx_vsat_d(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsat.bu"] - fn __lsx_vsat_bu(a: v16u8, b: u32) -> v16u8; + fn __lsx_vsat_bu(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vsat.hu"] - fn __lsx_vsat_hu(a: v8u16, b: u32) -> v8u16; + fn __lsx_vsat_hu(a: __v8u16, b: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vsat.wu"] - fn __lsx_vsat_wu(a: v4u32, b: u32) -> v4u32; + fn __lsx_vsat_wu(a: __v4u32, b: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vsat.du"] - fn __lsx_vsat_du(a: v2u64, b: u32) -> v2u64; + fn __lsx_vsat_du(a: __v2u64, b: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vadda.b"] - fn __lsx_vadda_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vadda_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vadda.h"] - fn __lsx_vadda_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vadda_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vadda.w"] - fn __lsx_vadda_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vadda_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vadda.d"] - fn __lsx_vadda_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vadda_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsadd.b"] - fn __lsx_vsadd_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsadd_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsadd.h"] - fn __lsx_vsadd_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsadd_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsadd.w"] - fn __lsx_vsadd_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsadd_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsadd.d"] - fn __lsx_vsadd_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsadd_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsadd.bu"] - fn __lsx_vsadd_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vsadd_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vsadd.hu"] - fn __lsx_vsadd_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vsadd_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vsadd.wu"] - fn __lsx_vsadd_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vsadd_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vsadd.du"] - fn __lsx_vsadd_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vsadd_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vavg.b"] - fn __lsx_vavg_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vavg_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vavg.h"] - fn __lsx_vavg_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vavg_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vavg.w"] - fn __lsx_vavg_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vavg_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vavg.d"] - fn __lsx_vavg_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vavg_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vavg.bu"] - fn __lsx_vavg_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vavg_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vavg.hu"] - fn __lsx_vavg_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vavg_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vavg.wu"] - fn __lsx_vavg_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vavg_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vavg.du"] - fn __lsx_vavg_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vavg_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vavgr.b"] - fn __lsx_vavgr_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vavgr_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vavgr.h"] - fn __lsx_vavgr_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vavgr_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vavgr.w"] - fn __lsx_vavgr_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vavgr_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vavgr.d"] - fn __lsx_vavgr_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vavgr_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vavgr.bu"] - fn __lsx_vavgr_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vavgr_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vavgr.hu"] - fn __lsx_vavgr_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vavgr_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vavgr.wu"] - fn __lsx_vavgr_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vavgr_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vavgr.du"] - fn __lsx_vavgr_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vavgr_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vssub.b"] - fn __lsx_vssub_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vssub_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssub.h"] - fn __lsx_vssub_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vssub_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssub.w"] - fn __lsx_vssub_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vssub_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssub.d"] - fn __lsx_vssub_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vssub_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vssub.bu"] - fn __lsx_vssub_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vssub_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssub.hu"] - fn __lsx_vssub_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vssub_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssub.wu"] - fn __lsx_vssub_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vssub_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vssub.du"] - fn __lsx_vssub_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vssub_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vabsd.b"] - fn __lsx_vabsd_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vabsd_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vabsd.h"] - fn __lsx_vabsd_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vabsd_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vabsd.w"] - fn __lsx_vabsd_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vabsd_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vabsd.d"] - fn __lsx_vabsd_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vabsd_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vabsd.bu"] - fn __lsx_vabsd_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vabsd_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vabsd.hu"] - fn __lsx_vabsd_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vabsd_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vabsd.wu"] - fn __lsx_vabsd_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vabsd_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vabsd.du"] - fn __lsx_vabsd_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vabsd_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmul.b"] - fn __lsx_vmul_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vmul_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmul.h"] - fn __lsx_vmul_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vmul_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmul.w"] - fn __lsx_vmul_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vmul_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmul.d"] - fn __lsx_vmul_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vmul_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmadd.b"] - fn __lsx_vmadd_b(a: v16i8, b: v16i8, c: v16i8) -> v16i8; + fn __lsx_vmadd_b(a: __v16i8, b: __v16i8, c: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmadd.h"] - fn __lsx_vmadd_h(a: v8i16, b: v8i16, c: v8i16) -> v8i16; + fn __lsx_vmadd_h(a: __v8i16, b: __v8i16, c: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmadd.w"] - fn __lsx_vmadd_w(a: v4i32, b: v4i32, c: v4i32) -> v4i32; + fn __lsx_vmadd_w(a: __v4i32, b: __v4i32, c: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmadd.d"] - fn __lsx_vmadd_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64; + fn __lsx_vmadd_d(a: __v2i64, b: __v2i64, c: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmsub.b"] - fn __lsx_vmsub_b(a: v16i8, b: v16i8, c: v16i8) -> v16i8; + fn __lsx_vmsub_b(a: __v16i8, b: __v16i8, c: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmsub.h"] - fn __lsx_vmsub_h(a: v8i16, b: v8i16, c: v8i16) -> v8i16; + fn __lsx_vmsub_h(a: __v8i16, b: __v8i16, c: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmsub.w"] - fn __lsx_vmsub_w(a: v4i32, b: v4i32, c: v4i32) -> v4i32; + fn __lsx_vmsub_w(a: __v4i32, b: __v4i32, c: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmsub.d"] - fn __lsx_vmsub_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64; + fn __lsx_vmsub_d(a: __v2i64, b: __v2i64, c: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vdiv.b"] - fn __lsx_vdiv_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vdiv_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vdiv.h"] - fn __lsx_vdiv_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vdiv_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vdiv.w"] - fn __lsx_vdiv_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vdiv_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vdiv.d"] - fn __lsx_vdiv_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vdiv_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vdiv.bu"] - fn __lsx_vdiv_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vdiv_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vdiv.hu"] - fn __lsx_vdiv_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vdiv_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vdiv.wu"] - fn __lsx_vdiv_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vdiv_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vdiv.du"] - fn __lsx_vdiv_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vdiv_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vhaddw.h.b"] - fn __lsx_vhaddw_h_b(a: v16i8, b: v16i8) -> v8i16; + fn __lsx_vhaddw_h_b(a: __v16i8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vhaddw.w.h"] - fn __lsx_vhaddw_w_h(a: v8i16, b: v8i16) -> v4i32; + fn __lsx_vhaddw_w_h(a: __v8i16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vhaddw.d.w"] - fn __lsx_vhaddw_d_w(a: v4i32, b: v4i32) -> v2i64; + fn __lsx_vhaddw_d_w(a: __v4i32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vhaddw.hu.bu"] - fn __lsx_vhaddw_hu_bu(a: v16u8, b: v16u8) -> v8u16; + fn __lsx_vhaddw_hu_bu(a: __v16u8, b: __v16u8) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vhaddw.wu.hu"] - fn __lsx_vhaddw_wu_hu(a: v8u16, b: v8u16) -> v4u32; + fn __lsx_vhaddw_wu_hu(a: __v8u16, b: __v8u16) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vhaddw.du.wu"] - fn __lsx_vhaddw_du_wu(a: v4u32, b: v4u32) -> v2u64; + fn __lsx_vhaddw_du_wu(a: __v4u32, b: __v4u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vhsubw.h.b"] - fn __lsx_vhsubw_h_b(a: v16i8, b: v16i8) -> v8i16; + fn __lsx_vhsubw_h_b(a: __v16i8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vhsubw.w.h"] - fn __lsx_vhsubw_w_h(a: v8i16, b: v8i16) -> v4i32; + fn __lsx_vhsubw_w_h(a: __v8i16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vhsubw.d.w"] - fn __lsx_vhsubw_d_w(a: v4i32, b: v4i32) -> v2i64; + fn __lsx_vhsubw_d_w(a: __v4i32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vhsubw.hu.bu"] - fn __lsx_vhsubw_hu_bu(a: v16u8, b: v16u8) -> v8i16; + fn __lsx_vhsubw_hu_bu(a: __v16u8, b: __v16u8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vhsubw.wu.hu"] - fn __lsx_vhsubw_wu_hu(a: v8u16, b: v8u16) -> v4i32; + fn __lsx_vhsubw_wu_hu(a: __v8u16, b: __v8u16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vhsubw.du.wu"] - fn __lsx_vhsubw_du_wu(a: v4u32, b: v4u32) -> v2i64; + fn __lsx_vhsubw_du_wu(a: __v4u32, b: __v4u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmod.b"] - fn __lsx_vmod_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vmod_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmod.h"] - fn __lsx_vmod_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vmod_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmod.w"] - fn __lsx_vmod_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vmod_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmod.d"] - fn __lsx_vmod_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vmod_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmod.bu"] - fn __lsx_vmod_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vmod_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vmod.hu"] - fn __lsx_vmod_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vmod_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vmod.wu"] - fn __lsx_vmod_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vmod_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vmod.du"] - fn __lsx_vmod_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vmod_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vreplve.b"] - fn __lsx_vreplve_b(a: v16i8, b: i32) -> v16i8; + fn __lsx_vreplve_b(a: __v16i8, b: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vreplve.h"] - fn __lsx_vreplve_h(a: v8i16, b: i32) -> v8i16; + fn __lsx_vreplve_h(a: __v8i16, b: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vreplve.w"] - fn __lsx_vreplve_w(a: v4i32, b: i32) -> v4i32; + fn __lsx_vreplve_w(a: __v4i32, b: i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vreplve.d"] - fn __lsx_vreplve_d(a: v2i64, b: i32) -> v2i64; + fn __lsx_vreplve_d(a: __v2i64, b: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vreplvei.b"] - fn __lsx_vreplvei_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vreplvei_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vreplvei.h"] - fn __lsx_vreplvei_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vreplvei_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vreplvei.w"] - fn __lsx_vreplvei_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vreplvei_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vreplvei.d"] - fn __lsx_vreplvei_d(a: v2i64, b: u32) -> v2i64; + fn __lsx_vreplvei_d(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vpickev.b"] - fn __lsx_vpickev_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vpickev_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vpickev.h"] - fn __lsx_vpickev_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vpickev_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vpickev.w"] - fn __lsx_vpickev_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vpickev_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vpickev.d"] - fn __lsx_vpickev_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vpickev_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vpickod.b"] - fn __lsx_vpickod_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vpickod_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vpickod.h"] - fn __lsx_vpickod_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vpickod_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vpickod.w"] - fn __lsx_vpickod_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vpickod_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vpickod.d"] - fn __lsx_vpickod_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vpickod_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vilvh.b"] - fn __lsx_vilvh_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vilvh_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vilvh.h"] - fn __lsx_vilvh_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vilvh_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vilvh.w"] - fn __lsx_vilvh_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vilvh_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vilvh.d"] - fn __lsx_vilvh_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vilvh_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vilvl.b"] - fn __lsx_vilvl_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vilvl_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vilvl.h"] - fn __lsx_vilvl_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vilvl_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vilvl.w"] - fn __lsx_vilvl_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vilvl_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vilvl.d"] - fn __lsx_vilvl_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vilvl_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vpackev.b"] - fn __lsx_vpackev_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vpackev_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vpackev.h"] - fn __lsx_vpackev_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vpackev_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vpackev.w"] - fn __lsx_vpackev_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vpackev_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vpackev.d"] - fn __lsx_vpackev_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vpackev_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vpackod.b"] - fn __lsx_vpackod_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vpackod_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vpackod.h"] - fn __lsx_vpackod_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vpackod_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vpackod.w"] - fn __lsx_vpackod_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vpackod_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vpackod.d"] - fn __lsx_vpackod_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vpackod_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vshuf.h"] - fn __lsx_vshuf_h(a: v8i16, b: v8i16, c: v8i16) -> v8i16; + fn __lsx_vshuf_h(a: __v8i16, b: __v8i16, c: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vshuf.w"] - fn __lsx_vshuf_w(a: v4i32, b: v4i32, c: v4i32) -> v4i32; + fn __lsx_vshuf_w(a: __v4i32, b: __v4i32, c: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vshuf.d"] - fn __lsx_vshuf_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64; + fn __lsx_vshuf_d(a: __v2i64, b: __v2i64, c: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vand.v"] - fn __lsx_vand_v(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vand_v(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vandi.b"] - fn __lsx_vandi_b(a: v16u8, b: u32) -> v16u8; + fn __lsx_vandi_b(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vor.v"] - fn __lsx_vor_v(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vor_v(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vori.b"] - fn __lsx_vori_b(a: v16u8, b: u32) -> v16u8; + fn __lsx_vori_b(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vnor.v"] - fn __lsx_vnor_v(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vnor_v(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vnori.b"] - fn __lsx_vnori_b(a: v16u8, b: u32) -> v16u8; + fn __lsx_vnori_b(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vxor.v"] - fn __lsx_vxor_v(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vxor_v(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vxori.b"] - fn __lsx_vxori_b(a: v16u8, b: u32) -> v16u8; + fn __lsx_vxori_b(a: __v16u8, b: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vbitsel.v"] - fn __lsx_vbitsel_v(a: v16u8, b: v16u8, c: v16u8) -> v16u8; + fn __lsx_vbitsel_v(a: __v16u8, b: __v16u8, c: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vbitseli.b"] - fn __lsx_vbitseli_b(a: v16u8, b: v16u8, c: u32) -> v16u8; + fn __lsx_vbitseli_b(a: __v16u8, b: __v16u8, c: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vshuf4i.b"] - fn __lsx_vshuf4i_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vshuf4i_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vshuf4i.h"] - fn __lsx_vshuf4i_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vshuf4i_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vshuf4i.w"] - fn __lsx_vshuf4i_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vshuf4i_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vreplgr2vr.b"] - fn __lsx_vreplgr2vr_b(a: i32) -> v16i8; + fn __lsx_vreplgr2vr_b(a: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vreplgr2vr.h"] - fn __lsx_vreplgr2vr_h(a: i32) -> v8i16; + fn __lsx_vreplgr2vr_h(a: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vreplgr2vr.w"] - fn __lsx_vreplgr2vr_w(a: i32) -> v4i32; + fn __lsx_vreplgr2vr_w(a: i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vreplgr2vr.d"] - fn __lsx_vreplgr2vr_d(a: i64) -> v2i64; + fn __lsx_vreplgr2vr_d(a: i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vpcnt.b"] - fn __lsx_vpcnt_b(a: v16i8) -> v16i8; + fn __lsx_vpcnt_b(a: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vpcnt.h"] - fn __lsx_vpcnt_h(a: v8i16) -> v8i16; + fn __lsx_vpcnt_h(a: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vpcnt.w"] - fn __lsx_vpcnt_w(a: v4i32) -> v4i32; + fn __lsx_vpcnt_w(a: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vpcnt.d"] - fn __lsx_vpcnt_d(a: v2i64) -> v2i64; + fn __lsx_vpcnt_d(a: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vclo.b"] - fn __lsx_vclo_b(a: v16i8) -> v16i8; + fn __lsx_vclo_b(a: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vclo.h"] - fn __lsx_vclo_h(a: v8i16) -> v8i16; + fn __lsx_vclo_h(a: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vclo.w"] - fn __lsx_vclo_w(a: v4i32) -> v4i32; + fn __lsx_vclo_w(a: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vclo.d"] - fn __lsx_vclo_d(a: v2i64) -> v2i64; + fn __lsx_vclo_d(a: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vclz.b"] - fn __lsx_vclz_b(a: v16i8) -> v16i8; + fn __lsx_vclz_b(a: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vclz.h"] - fn __lsx_vclz_h(a: v8i16) -> v8i16; + fn __lsx_vclz_h(a: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vclz.w"] - fn __lsx_vclz_w(a: v4i32) -> v4i32; + fn __lsx_vclz_w(a: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vclz.d"] - fn __lsx_vclz_d(a: v2i64) -> v2i64; + fn __lsx_vclz_d(a: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vpickve2gr.b"] - fn __lsx_vpickve2gr_b(a: v16i8, b: u32) -> i32; + fn __lsx_vpickve2gr_b(a: __v16i8, b: u32) -> i32; #[link_name = "llvm.loongarch.lsx.vpickve2gr.h"] - fn __lsx_vpickve2gr_h(a: v8i16, b: u32) -> i32; + fn __lsx_vpickve2gr_h(a: __v8i16, b: u32) -> i32; #[link_name = "llvm.loongarch.lsx.vpickve2gr.w"] - fn __lsx_vpickve2gr_w(a: v4i32, b: u32) -> i32; + fn __lsx_vpickve2gr_w(a: __v4i32, b: u32) -> i32; #[link_name = "llvm.loongarch.lsx.vpickve2gr.d"] - fn __lsx_vpickve2gr_d(a: v2i64, b: u32) -> i64; + fn __lsx_vpickve2gr_d(a: __v2i64, b: u32) -> i64; #[link_name = "llvm.loongarch.lsx.vpickve2gr.bu"] - fn __lsx_vpickve2gr_bu(a: v16i8, b: u32) -> u32; + fn __lsx_vpickve2gr_bu(a: __v16i8, b: u32) -> u32; #[link_name = "llvm.loongarch.lsx.vpickve2gr.hu"] - fn __lsx_vpickve2gr_hu(a: v8i16, b: u32) -> u32; + fn __lsx_vpickve2gr_hu(a: __v8i16, b: u32) -> u32; #[link_name = "llvm.loongarch.lsx.vpickve2gr.wu"] - fn __lsx_vpickve2gr_wu(a: v4i32, b: u32) -> u32; + fn __lsx_vpickve2gr_wu(a: __v4i32, b: u32) -> u32; #[link_name = "llvm.loongarch.lsx.vpickve2gr.du"] - fn __lsx_vpickve2gr_du(a: v2i64, b: u32) -> u64; + fn __lsx_vpickve2gr_du(a: __v2i64, b: u32) -> u64; #[link_name = "llvm.loongarch.lsx.vinsgr2vr.b"] - fn __lsx_vinsgr2vr_b(a: v16i8, b: i32, c: u32) -> v16i8; + fn __lsx_vinsgr2vr_b(a: __v16i8, b: i32, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vinsgr2vr.h"] - fn __lsx_vinsgr2vr_h(a: v8i16, b: i32, c: u32) -> v8i16; + fn __lsx_vinsgr2vr_h(a: __v8i16, b: i32, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vinsgr2vr.w"] - fn __lsx_vinsgr2vr_w(a: v4i32, b: i32, c: u32) -> v4i32; + fn __lsx_vinsgr2vr_w(a: __v4i32, b: i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vinsgr2vr.d"] - fn __lsx_vinsgr2vr_d(a: v2i64, b: i64, c: u32) -> v2i64; + fn __lsx_vinsgr2vr_d(a: __v2i64, b: i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfadd.s"] - fn __lsx_vfadd_s(a: v4f32, b: v4f32) -> v4f32; + fn __lsx_vfadd_s(a: __v4f32, b: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfadd.d"] - fn __lsx_vfadd_d(a: v2f64, b: v2f64) -> v2f64; + fn __lsx_vfadd_d(a: __v2f64, b: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfsub.s"] - fn __lsx_vfsub_s(a: v4f32, b: v4f32) -> v4f32; + fn __lsx_vfsub_s(a: __v4f32, b: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfsub.d"] - fn __lsx_vfsub_d(a: v2f64, b: v2f64) -> v2f64; + fn __lsx_vfsub_d(a: __v2f64, b: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfmul.s"] - fn __lsx_vfmul_s(a: v4f32, b: v4f32) -> v4f32; + fn __lsx_vfmul_s(a: __v4f32, b: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfmul.d"] - fn __lsx_vfmul_d(a: v2f64, b: v2f64) -> v2f64; + fn __lsx_vfmul_d(a: __v2f64, b: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfdiv.s"] - fn __lsx_vfdiv_s(a: v4f32, b: v4f32) -> v4f32; + fn __lsx_vfdiv_s(a: __v4f32, b: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfdiv.d"] - fn __lsx_vfdiv_d(a: v2f64, b: v2f64) -> v2f64; + fn __lsx_vfdiv_d(a: __v2f64, b: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfcvt.h.s"] - fn __lsx_vfcvt_h_s(a: v4f32, b: v4f32) -> v8i16; + fn __lsx_vfcvt_h_s(a: __v4f32, b: __v4f32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vfcvt.s.d"] - fn __lsx_vfcvt_s_d(a: v2f64, b: v2f64) -> v4f32; + fn __lsx_vfcvt_s_d(a: __v2f64, b: __v2f64) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfmin.s"] - fn __lsx_vfmin_s(a: v4f32, b: v4f32) -> v4f32; + fn __lsx_vfmin_s(a: __v4f32, b: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfmin.d"] - fn __lsx_vfmin_d(a: v2f64, b: v2f64) -> v2f64; + fn __lsx_vfmin_d(a: __v2f64, b: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfmina.s"] - fn __lsx_vfmina_s(a: v4f32, b: v4f32) -> v4f32; + fn __lsx_vfmina_s(a: __v4f32, b: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfmina.d"] - fn __lsx_vfmina_d(a: v2f64, b: v2f64) -> v2f64; + fn __lsx_vfmina_d(a: __v2f64, b: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfmax.s"] - fn __lsx_vfmax_s(a: v4f32, b: v4f32) -> v4f32; + fn __lsx_vfmax_s(a: __v4f32, b: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfmax.d"] - fn __lsx_vfmax_d(a: v2f64, b: v2f64) -> v2f64; + fn __lsx_vfmax_d(a: __v2f64, b: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfmaxa.s"] - fn __lsx_vfmaxa_s(a: v4f32, b: v4f32) -> v4f32; + fn __lsx_vfmaxa_s(a: __v4f32, b: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfmaxa.d"] - fn __lsx_vfmaxa_d(a: v2f64, b: v2f64) -> v2f64; + fn __lsx_vfmaxa_d(a: __v2f64, b: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfclass.s"] - fn __lsx_vfclass_s(a: v4f32) -> v4i32; + fn __lsx_vfclass_s(a: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfclass.d"] - fn __lsx_vfclass_d(a: v2f64) -> v2i64; + fn __lsx_vfclass_d(a: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfsqrt.s"] - fn __lsx_vfsqrt_s(a: v4f32) -> v4f32; + fn __lsx_vfsqrt_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfsqrt.d"] - fn __lsx_vfsqrt_d(a: v2f64) -> v2f64; + fn __lsx_vfsqrt_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfrecip.s"] - fn __lsx_vfrecip_s(a: v4f32) -> v4f32; + fn __lsx_vfrecip_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrecip.d"] - fn __lsx_vfrecip_d(a: v2f64) -> v2f64; + fn __lsx_vfrecip_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfrecipe.s"] - fn __lsx_vfrecipe_s(a: v4f32) -> v4f32; + fn __lsx_vfrecipe_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrecipe.d"] - fn __lsx_vfrecipe_d(a: v2f64) -> v2f64; + fn __lsx_vfrecipe_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfrsqrte.s"] - fn __lsx_vfrsqrte_s(a: v4f32) -> v4f32; + fn __lsx_vfrsqrte_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrsqrte.d"] - fn __lsx_vfrsqrte_d(a: v2f64) -> v2f64; + fn __lsx_vfrsqrte_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfrint.s"] - fn __lsx_vfrint_s(a: v4f32) -> v4f32; + fn __lsx_vfrint_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrint.d"] - fn __lsx_vfrint_d(a: v2f64) -> v2f64; + fn __lsx_vfrint_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfrsqrt.s"] - fn __lsx_vfrsqrt_s(a: v4f32) -> v4f32; + fn __lsx_vfrsqrt_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrsqrt.d"] - fn __lsx_vfrsqrt_d(a: v2f64) -> v2f64; + fn __lsx_vfrsqrt_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vflogb.s"] - fn __lsx_vflogb_s(a: v4f32) -> v4f32; + fn __lsx_vflogb_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vflogb.d"] - fn __lsx_vflogb_d(a: v2f64) -> v2f64; + fn __lsx_vflogb_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfcvth.s.h"] - fn __lsx_vfcvth_s_h(a: v8i16) -> v4f32; + fn __lsx_vfcvth_s_h(a: __v8i16) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfcvth.d.s"] - fn __lsx_vfcvth_d_s(a: v4f32) -> v2f64; + fn __lsx_vfcvth_d_s(a: __v4f32) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfcvtl.s.h"] - fn __lsx_vfcvtl_s_h(a: v8i16) -> v4f32; + fn __lsx_vfcvtl_s_h(a: __v8i16) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfcvtl.d.s"] - fn __lsx_vfcvtl_d_s(a: v4f32) -> v2f64; + fn __lsx_vfcvtl_d_s(a: __v4f32) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vftint.w.s"] - fn __lsx_vftint_w_s(a: v4f32) -> v4i32; + fn __lsx_vftint_w_s(a: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftint.l.d"] - fn __lsx_vftint_l_d(a: v2f64) -> v2i64; + fn __lsx_vftint_l_d(a: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftint.wu.s"] - fn __lsx_vftint_wu_s(a: v4f32) -> v4u32; + fn __lsx_vftint_wu_s(a: __v4f32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vftint.lu.d"] - fn __lsx_vftint_lu_d(a: v2f64) -> v2u64; + fn __lsx_vftint_lu_d(a: __v2f64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vftintrz.w.s"] - fn __lsx_vftintrz_w_s(a: v4f32) -> v4i32; + fn __lsx_vftintrz_w_s(a: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftintrz.l.d"] - fn __lsx_vftintrz_l_d(a: v2f64) -> v2i64; + fn __lsx_vftintrz_l_d(a: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrz.wu.s"] - fn __lsx_vftintrz_wu_s(a: v4f32) -> v4u32; + fn __lsx_vftintrz_wu_s(a: __v4f32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vftintrz.lu.d"] - fn __lsx_vftintrz_lu_d(a: v2f64) -> v2u64; + fn __lsx_vftintrz_lu_d(a: __v2f64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vffint.s.w"] - fn __lsx_vffint_s_w(a: v4i32) -> v4f32; + fn __lsx_vffint_s_w(a: __v4i32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vffint.d.l"] - fn __lsx_vffint_d_l(a: v2i64) -> v2f64; + fn __lsx_vffint_d_l(a: __v2i64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vffint.s.wu"] - fn __lsx_vffint_s_wu(a: v4u32) -> v4f32; + fn __lsx_vffint_s_wu(a: __v4u32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vffint.d.lu"] - fn __lsx_vffint_d_lu(a: v2u64) -> v2f64; + fn __lsx_vffint_d_lu(a: __v2u64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vandn.v"] - fn __lsx_vandn_v(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vandn_v(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vneg.b"] - fn __lsx_vneg_b(a: v16i8) -> v16i8; + fn __lsx_vneg_b(a: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vneg.h"] - fn __lsx_vneg_h(a: v8i16) -> v8i16; + fn __lsx_vneg_h(a: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vneg.w"] - fn __lsx_vneg_w(a: v4i32) -> v4i32; + fn __lsx_vneg_w(a: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vneg.d"] - fn __lsx_vneg_d(a: v2i64) -> v2i64; + fn __lsx_vneg_d(a: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmuh.b"] - fn __lsx_vmuh_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vmuh_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmuh.h"] - fn __lsx_vmuh_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vmuh_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmuh.w"] - fn __lsx_vmuh_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vmuh_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmuh.d"] - fn __lsx_vmuh_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vmuh_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmuh.bu"] - fn __lsx_vmuh_bu(a: v16u8, b: v16u8) -> v16u8; + fn __lsx_vmuh_bu(a: __v16u8, b: __v16u8) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vmuh.hu"] - fn __lsx_vmuh_hu(a: v8u16, b: v8u16) -> v8u16; + fn __lsx_vmuh_hu(a: __v8u16, b: __v8u16) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vmuh.wu"] - fn __lsx_vmuh_wu(a: v4u32, b: v4u32) -> v4u32; + fn __lsx_vmuh_wu(a: __v4u32, b: __v4u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vmuh.du"] - fn __lsx_vmuh_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vmuh_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vsllwil.h.b"] - fn __lsx_vsllwil_h_b(a: v16i8, b: u32) -> v8i16; + fn __lsx_vsllwil_h_b(a: __v16i8, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsllwil.w.h"] - fn __lsx_vsllwil_w_h(a: v8i16, b: u32) -> v4i32; + fn __lsx_vsllwil_w_h(a: __v8i16, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsllwil.d.w"] - fn __lsx_vsllwil_d_w(a: v4i32, b: u32) -> v2i64; + fn __lsx_vsllwil_d_w(a: __v4i32, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsllwil.hu.bu"] - fn __lsx_vsllwil_hu_bu(a: v16u8, b: u32) -> v8u16; + fn __lsx_vsllwil_hu_bu(a: __v16u8, b: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vsllwil.wu.hu"] - fn __lsx_vsllwil_wu_hu(a: v8u16, b: u32) -> v4u32; + fn __lsx_vsllwil_wu_hu(a: __v8u16, b: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vsllwil.du.wu"] - fn __lsx_vsllwil_du_wu(a: v4u32, b: u32) -> v2u64; + fn __lsx_vsllwil_du_wu(a: __v4u32, b: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vsran.b.h"] - fn __lsx_vsran_b_h(a: v8i16, b: v8i16) -> v16i8; + fn __lsx_vsran_b_h(a: __v8i16, b: __v8i16) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsran.h.w"] - fn __lsx_vsran_h_w(a: v4i32, b: v4i32) -> v8i16; + fn __lsx_vsran_h_w(a: __v4i32, b: __v4i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsran.w.d"] - fn __lsx_vsran_w_d(a: v2i64, b: v2i64) -> v4i32; + fn __lsx_vsran_w_d(a: __v2i64, b: __v2i64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssran.b.h"] - fn __lsx_vssran_b_h(a: v8i16, b: v8i16) -> v16i8; + fn __lsx_vssran_b_h(a: __v8i16, b: __v8i16) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssran.h.w"] - fn __lsx_vssran_h_w(a: v4i32, b: v4i32) -> v8i16; + fn __lsx_vssran_h_w(a: __v4i32, b: __v4i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssran.w.d"] - fn __lsx_vssran_w_d(a: v2i64, b: v2i64) -> v4i32; + fn __lsx_vssran_w_d(a: __v2i64, b: __v2i64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssran.bu.h"] - fn __lsx_vssran_bu_h(a: v8u16, b: v8u16) -> v16u8; + fn __lsx_vssran_bu_h(a: __v8u16, b: __v8u16) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssran.hu.w"] - fn __lsx_vssran_hu_w(a: v4u32, b: v4u32) -> v8u16; + fn __lsx_vssran_hu_w(a: __v4u32, b: __v4u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssran.wu.d"] - fn __lsx_vssran_wu_d(a: v2u64, b: v2u64) -> v4u32; + fn __lsx_vssran_wu_d(a: __v2u64, b: __v2u64) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vsrarn.b.h"] - fn __lsx_vsrarn_b_h(a: v8i16, b: v8i16) -> v16i8; + fn __lsx_vsrarn_b_h(a: __v8i16, b: __v8i16) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrarn.h.w"] - fn __lsx_vsrarn_h_w(a: v4i32, b: v4i32) -> v8i16; + fn __lsx_vsrarn_h_w(a: __v4i32, b: __v4i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrarn.w.d"] - fn __lsx_vsrarn_w_d(a: v2i64, b: v2i64) -> v4i32; + fn __lsx_vsrarn_w_d(a: __v2i64, b: __v2i64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrarn.b.h"] - fn __lsx_vssrarn_b_h(a: v8i16, b: v8i16) -> v16i8; + fn __lsx_vssrarn_b_h(a: __v8i16, b: __v8i16) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssrarn.h.w"] - fn __lsx_vssrarn_h_w(a: v4i32, b: v4i32) -> v8i16; + fn __lsx_vssrarn_h_w(a: __v4i32, b: __v4i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssrarn.w.d"] - fn __lsx_vssrarn_w_d(a: v2i64, b: v2i64) -> v4i32; + fn __lsx_vssrarn_w_d(a: __v2i64, b: __v2i64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrarn.bu.h"] - fn __lsx_vssrarn_bu_h(a: v8u16, b: v8u16) -> v16u8; + fn __lsx_vssrarn_bu_h(a: __v8u16, b: __v8u16) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssrarn.hu.w"] - fn __lsx_vssrarn_hu_w(a: v4u32, b: v4u32) -> v8u16; + fn __lsx_vssrarn_hu_w(a: __v4u32, b: __v4u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssrarn.wu.d"] - fn __lsx_vssrarn_wu_d(a: v2u64, b: v2u64) -> v4u32; + fn __lsx_vssrarn_wu_d(a: __v2u64, b: __v2u64) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vsrln.b.h"] - fn __lsx_vsrln_b_h(a: v8i16, b: v8i16) -> v16i8; + fn __lsx_vsrln_b_h(a: __v8i16, b: __v8i16) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrln.h.w"] - fn __lsx_vsrln_h_w(a: v4i32, b: v4i32) -> v8i16; + fn __lsx_vsrln_h_w(a: __v4i32, b: __v4i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrln.w.d"] - fn __lsx_vsrln_w_d(a: v2i64, b: v2i64) -> v4i32; + fn __lsx_vsrln_w_d(a: __v2i64, b: __v2i64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrln.bu.h"] - fn __lsx_vssrln_bu_h(a: v8u16, b: v8u16) -> v16u8; + fn __lsx_vssrln_bu_h(a: __v8u16, b: __v8u16) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssrln.hu.w"] - fn __lsx_vssrln_hu_w(a: v4u32, b: v4u32) -> v8u16; + fn __lsx_vssrln_hu_w(a: __v4u32, b: __v4u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssrln.wu.d"] - fn __lsx_vssrln_wu_d(a: v2u64, b: v2u64) -> v4u32; + fn __lsx_vssrln_wu_d(a: __v2u64, b: __v2u64) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vsrlrn.b.h"] - fn __lsx_vsrlrn_b_h(a: v8i16, b: v8i16) -> v16i8; + fn __lsx_vsrlrn_b_h(a: __v8i16, b: __v8i16) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrlrn.h.w"] - fn __lsx_vsrlrn_h_w(a: v4i32, b: v4i32) -> v8i16; + fn __lsx_vsrlrn_h_w(a: __v4i32, b: __v4i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrlrn.w.d"] - fn __lsx_vsrlrn_w_d(a: v2i64, b: v2i64) -> v4i32; + fn __lsx_vsrlrn_w_d(a: __v2i64, b: __v2i64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrlrn.bu.h"] - fn __lsx_vssrlrn_bu_h(a: v8u16, b: v8u16) -> v16u8; + fn __lsx_vssrlrn_bu_h(a: __v8u16, b: __v8u16) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssrlrn.hu.w"] - fn __lsx_vssrlrn_hu_w(a: v4u32, b: v4u32) -> v8u16; + fn __lsx_vssrlrn_hu_w(a: __v4u32, b: __v4u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssrlrn.wu.d"] - fn __lsx_vssrlrn_wu_d(a: v2u64, b: v2u64) -> v4u32; + fn __lsx_vssrlrn_wu_d(a: __v2u64, b: __v2u64) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vfrstpi.b"] - fn __lsx_vfrstpi_b(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vfrstpi_b(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vfrstpi.h"] - fn __lsx_vfrstpi_h(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vfrstpi_h(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vfrstp.b"] - fn __lsx_vfrstp_b(a: v16i8, b: v16i8, c: v16i8) -> v16i8; + fn __lsx_vfrstp_b(a: __v16i8, b: __v16i8, c: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vfrstp.h"] - fn __lsx_vfrstp_h(a: v8i16, b: v8i16, c: v8i16) -> v8i16; + fn __lsx_vfrstp_h(a: __v8i16, b: __v8i16, c: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vshuf4i.d"] - fn __lsx_vshuf4i_d(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vshuf4i_d(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vbsrl.v"] - fn __lsx_vbsrl_v(a: v16i8, b: u32) -> v16i8; + fn __lsx_vbsrl_v(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vbsll.v"] - fn __lsx_vbsll_v(a: v16i8, b: u32) -> v16i8; + fn __lsx_vbsll_v(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vextrins.b"] - fn __lsx_vextrins_b(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vextrins_b(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vextrins.h"] - fn __lsx_vextrins_h(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vextrins_h(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vextrins.w"] - fn __lsx_vextrins_w(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vextrins_w(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vextrins.d"] - fn __lsx_vextrins_d(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vextrins_d(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmskltz.b"] - fn __lsx_vmskltz_b(a: v16i8) -> v16i8; + fn __lsx_vmskltz_b(a: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmskltz.h"] - fn __lsx_vmskltz_h(a: v8i16) -> v8i16; + fn __lsx_vmskltz_h(a: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmskltz.w"] - fn __lsx_vmskltz_w(a: v4i32) -> v4i32; + fn __lsx_vmskltz_w(a: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmskltz.d"] - fn __lsx_vmskltz_d(a: v2i64) -> v2i64; + fn __lsx_vmskltz_d(a: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsigncov.b"] - fn __lsx_vsigncov_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vsigncov_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsigncov.h"] - fn __lsx_vsigncov_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vsigncov_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsigncov.w"] - fn __lsx_vsigncov_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vsigncov_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsigncov.d"] - fn __lsx_vsigncov_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsigncov_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfmadd.s"] - fn __lsx_vfmadd_s(a: v4f32, b: v4f32, c: v4f32) -> v4f32; + fn __lsx_vfmadd_s(a: __v4f32, b: __v4f32, c: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfmadd.d"] - fn __lsx_vfmadd_d(a: v2f64, b: v2f64, c: v2f64) -> v2f64; + fn __lsx_vfmadd_d(a: __v2f64, b: __v2f64, c: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfmsub.s"] - fn __lsx_vfmsub_s(a: v4f32, b: v4f32, c: v4f32) -> v4f32; + fn __lsx_vfmsub_s(a: __v4f32, b: __v4f32, c: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfmsub.d"] - fn __lsx_vfmsub_d(a: v2f64, b: v2f64, c: v2f64) -> v2f64; + fn __lsx_vfmsub_d(a: __v2f64, b: __v2f64, c: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfnmadd.s"] - fn __lsx_vfnmadd_s(a: v4f32, b: v4f32, c: v4f32) -> v4f32; + fn __lsx_vfnmadd_s(a: __v4f32, b: __v4f32, c: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfnmadd.d"] - fn __lsx_vfnmadd_d(a: v2f64, b: v2f64, c: v2f64) -> v2f64; + fn __lsx_vfnmadd_d(a: __v2f64, b: __v2f64, c: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfnmsub.s"] - fn __lsx_vfnmsub_s(a: v4f32, b: v4f32, c: v4f32) -> v4f32; + fn __lsx_vfnmsub_s(a: __v4f32, b: __v4f32, c: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfnmsub.d"] - fn __lsx_vfnmsub_d(a: v2f64, b: v2f64, c: v2f64) -> v2f64; + fn __lsx_vfnmsub_d(a: __v2f64, b: __v2f64, c: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vftintrne.w.s"] - fn __lsx_vftintrne_w_s(a: v4f32) -> v4i32; + fn __lsx_vftintrne_w_s(a: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftintrne.l.d"] - fn __lsx_vftintrne_l_d(a: v2f64) -> v2i64; + fn __lsx_vftintrne_l_d(a: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrp.w.s"] - fn __lsx_vftintrp_w_s(a: v4f32) -> v4i32; + fn __lsx_vftintrp_w_s(a: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftintrp.l.d"] - fn __lsx_vftintrp_l_d(a: v2f64) -> v2i64; + fn __lsx_vftintrp_l_d(a: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrm.w.s"] - fn __lsx_vftintrm_w_s(a: v4f32) -> v4i32; + fn __lsx_vftintrm_w_s(a: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftintrm.l.d"] - fn __lsx_vftintrm_l_d(a: v2f64) -> v2i64; + fn __lsx_vftintrm_l_d(a: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftint.w.d"] - fn __lsx_vftint_w_d(a: v2f64, b: v2f64) -> v4i32; + fn __lsx_vftint_w_d(a: __v2f64, b: __v2f64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vffint.s.l"] - fn __lsx_vffint_s_l(a: v2i64, b: v2i64) -> v4f32; + fn __lsx_vffint_s_l(a: __v2i64, b: __v2i64) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vftintrz.w.d"] - fn __lsx_vftintrz_w_d(a: v2f64, b: v2f64) -> v4i32; + fn __lsx_vftintrz_w_d(a: __v2f64, b: __v2f64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftintrp.w.d"] - fn __lsx_vftintrp_w_d(a: v2f64, b: v2f64) -> v4i32; + fn __lsx_vftintrp_w_d(a: __v2f64, b: __v2f64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftintrm.w.d"] - fn __lsx_vftintrm_w_d(a: v2f64, b: v2f64) -> v4i32; + fn __lsx_vftintrm_w_d(a: __v2f64, b: __v2f64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftintrne.w.d"] - fn __lsx_vftintrne_w_d(a: v2f64, b: v2f64) -> v4i32; + fn __lsx_vftintrne_w_d(a: __v2f64, b: __v2f64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vftintl.l.s"] - fn __lsx_vftintl_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintl_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftinth.l.s"] - fn __lsx_vftinth_l_s(a: v4f32) -> v2i64; + fn __lsx_vftinth_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vffinth.d.w"] - fn __lsx_vffinth_d_w(a: v4i32) -> v2f64; + fn __lsx_vffinth_d_w(a: __v4i32) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vffintl.d.w"] - fn __lsx_vffintl_d_w(a: v4i32) -> v2f64; + fn __lsx_vffintl_d_w(a: __v4i32) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vftintrzl.l.s"] - fn __lsx_vftintrzl_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintrzl_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrzh.l.s"] - fn __lsx_vftintrzh_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintrzh_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrpl.l.s"] - fn __lsx_vftintrpl_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintrpl_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrph.l.s"] - fn __lsx_vftintrph_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintrph_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrml.l.s"] - fn __lsx_vftintrml_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintrml_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrmh.l.s"] - fn __lsx_vftintrmh_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintrmh_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrnel.l.s"] - fn __lsx_vftintrnel_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintrnel_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vftintrneh.l.s"] - fn __lsx_vftintrneh_l_s(a: v4f32) -> v2i64; + fn __lsx_vftintrneh_l_s(a: __v4f32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfrintrne.s"] - fn __lsx_vfrintrne_s(a: v4f32) -> v4f32; + fn __lsx_vfrintrne_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrintrne.d"] - fn __lsx_vfrintrne_d(a: v2f64) -> v2f64; + fn __lsx_vfrintrne_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfrintrz.s"] - fn __lsx_vfrintrz_s(a: v4f32) -> v4f32; + fn __lsx_vfrintrz_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrintrz.d"] - fn __lsx_vfrintrz_d(a: v2f64) -> v2f64; + fn __lsx_vfrintrz_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfrintrp.s"] - fn __lsx_vfrintrp_s(a: v4f32) -> v4f32; + fn __lsx_vfrintrp_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrintrp.d"] - fn __lsx_vfrintrp_d(a: v2f64) -> v2f64; + fn __lsx_vfrintrp_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vfrintrm.s"] - fn __lsx_vfrintrm_s(a: v4f32) -> v4f32; + fn __lsx_vfrintrm_s(a: __v4f32) -> __v4f32; #[link_name = "llvm.loongarch.lsx.vfrintrm.d"] - fn __lsx_vfrintrm_d(a: v2f64) -> v2f64; + fn __lsx_vfrintrm_d(a: __v2f64) -> __v2f64; #[link_name = "llvm.loongarch.lsx.vstelm.b"] - fn __lsx_vstelm_b(a: v16i8, b: *mut i8, c: i32, d: u32); + fn __lsx_vstelm_b(a: __v16i8, b: *mut i8, c: i32, d: u32); #[link_name = "llvm.loongarch.lsx.vstelm.h"] - fn __lsx_vstelm_h(a: v8i16, b: *mut i8, c: i32, d: u32); + fn __lsx_vstelm_h(a: __v8i16, b: *mut i8, c: i32, d: u32); #[link_name = "llvm.loongarch.lsx.vstelm.w"] - fn __lsx_vstelm_w(a: v4i32, b: *mut i8, c: i32, d: u32); + fn __lsx_vstelm_w(a: __v4i32, b: *mut i8, c: i32, d: u32); #[link_name = "llvm.loongarch.lsx.vstelm.d"] - fn __lsx_vstelm_d(a: v2i64, b: *mut i8, c: i32, d: u32); + fn __lsx_vstelm_d(a: __v2i64, b: *mut i8, c: i32, d: u32); #[link_name = "llvm.loongarch.lsx.vaddwev.d.w"] - fn __lsx_vaddwev_d_w(a: v4i32, b: v4i32) -> v2i64; + fn __lsx_vaddwev_d_w(a: __v4i32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwev.w.h"] - fn __lsx_vaddwev_w_h(a: v8i16, b: v8i16) -> v4i32; + fn __lsx_vaddwev_w_h(a: __v8i16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vaddwev.h.b"] - fn __lsx_vaddwev_h_b(a: v16i8, b: v16i8) -> v8i16; + fn __lsx_vaddwev_h_b(a: __v16i8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vaddwod.d.w"] - fn __lsx_vaddwod_d_w(a: v4i32, b: v4i32) -> v2i64; + fn __lsx_vaddwod_d_w(a: __v4i32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwod.w.h"] - fn __lsx_vaddwod_w_h(a: v8i16, b: v8i16) -> v4i32; + fn __lsx_vaddwod_w_h(a: __v8i16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vaddwod.h.b"] - fn __lsx_vaddwod_h_b(a: v16i8, b: v16i8) -> v8i16; + fn __lsx_vaddwod_h_b(a: __v16i8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vaddwev.d.wu"] - fn __lsx_vaddwev_d_wu(a: v4u32, b: v4u32) -> v2i64; + fn __lsx_vaddwev_d_wu(a: __v4u32, b: __v4u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwev.w.hu"] - fn __lsx_vaddwev_w_hu(a: v8u16, b: v8u16) -> v4i32; + fn __lsx_vaddwev_w_hu(a: __v8u16, b: __v8u16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vaddwev.h.bu"] - fn __lsx_vaddwev_h_bu(a: v16u8, b: v16u8) -> v8i16; + fn __lsx_vaddwev_h_bu(a: __v16u8, b: __v16u8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vaddwod.d.wu"] - fn __lsx_vaddwod_d_wu(a: v4u32, b: v4u32) -> v2i64; + fn __lsx_vaddwod_d_wu(a: __v4u32, b: __v4u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwod.w.hu"] - fn __lsx_vaddwod_w_hu(a: v8u16, b: v8u16) -> v4i32; + fn __lsx_vaddwod_w_hu(a: __v8u16, b: __v8u16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vaddwod.h.bu"] - fn __lsx_vaddwod_h_bu(a: v16u8, b: v16u8) -> v8i16; + fn __lsx_vaddwod_h_bu(a: __v16u8, b: __v16u8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vaddwev.d.wu.w"] - fn __lsx_vaddwev_d_wu_w(a: v4u32, b: v4i32) -> v2i64; + fn __lsx_vaddwev_d_wu_w(a: __v4u32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwev.w.hu.h"] - fn __lsx_vaddwev_w_hu_h(a: v8u16, b: v8i16) -> v4i32; + fn __lsx_vaddwev_w_hu_h(a: __v8u16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vaddwev.h.bu.b"] - fn __lsx_vaddwev_h_bu_b(a: v16u8, b: v16i8) -> v8i16; + fn __lsx_vaddwev_h_bu_b(a: __v16u8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vaddwod.d.wu.w"] - fn __lsx_vaddwod_d_wu_w(a: v4u32, b: v4i32) -> v2i64; + fn __lsx_vaddwod_d_wu_w(a: __v4u32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwod.w.hu.h"] - fn __lsx_vaddwod_w_hu_h(a: v8u16, b: v8i16) -> v4i32; + fn __lsx_vaddwod_w_hu_h(a: __v8u16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vaddwod.h.bu.b"] - fn __lsx_vaddwod_h_bu_b(a: v16u8, b: v16i8) -> v8i16; + fn __lsx_vaddwod_h_bu_b(a: __v16u8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsubwev.d.w"] - fn __lsx_vsubwev_d_w(a: v4i32, b: v4i32) -> v2i64; + fn __lsx_vsubwev_d_w(a: __v4i32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubwev.w.h"] - fn __lsx_vsubwev_w_h(a: v8i16, b: v8i16) -> v4i32; + fn __lsx_vsubwev_w_h(a: __v8i16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsubwev.h.b"] - fn __lsx_vsubwev_h_b(a: v16i8, b: v16i8) -> v8i16; + fn __lsx_vsubwev_h_b(a: __v16i8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsubwod.d.w"] - fn __lsx_vsubwod_d_w(a: v4i32, b: v4i32) -> v2i64; + fn __lsx_vsubwod_d_w(a: __v4i32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubwod.w.h"] - fn __lsx_vsubwod_w_h(a: v8i16, b: v8i16) -> v4i32; + fn __lsx_vsubwod_w_h(a: __v8i16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsubwod.h.b"] - fn __lsx_vsubwod_h_b(a: v16i8, b: v16i8) -> v8i16; + fn __lsx_vsubwod_h_b(a: __v16i8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsubwev.d.wu"] - fn __lsx_vsubwev_d_wu(a: v4u32, b: v4u32) -> v2i64; + fn __lsx_vsubwev_d_wu(a: __v4u32, b: __v4u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubwev.w.hu"] - fn __lsx_vsubwev_w_hu(a: v8u16, b: v8u16) -> v4i32; + fn __lsx_vsubwev_w_hu(a: __v8u16, b: __v8u16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsubwev.h.bu"] - fn __lsx_vsubwev_h_bu(a: v16u8, b: v16u8) -> v8i16; + fn __lsx_vsubwev_h_bu(a: __v16u8, b: __v16u8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsubwod.d.wu"] - fn __lsx_vsubwod_d_wu(a: v4u32, b: v4u32) -> v2i64; + fn __lsx_vsubwod_d_wu(a: __v4u32, b: __v4u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubwod.w.hu"] - fn __lsx_vsubwod_w_hu(a: v8u16, b: v8u16) -> v4i32; + fn __lsx_vsubwod_w_hu(a: __v8u16, b: __v8u16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsubwod.h.bu"] - fn __lsx_vsubwod_h_bu(a: v16u8, b: v16u8) -> v8i16; + fn __lsx_vsubwod_h_bu(a: __v16u8, b: __v16u8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vaddwev.q.d"] - fn __lsx_vaddwev_q_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vaddwev_q_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwod.q.d"] - fn __lsx_vaddwod_q_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vaddwod_q_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwev.q.du"] - fn __lsx_vaddwev_q_du(a: v2u64, b: v2u64) -> v2i64; + fn __lsx_vaddwev_q_du(a: __v2u64, b: __v2u64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwod.q.du"] - fn __lsx_vaddwod_q_du(a: v2u64, b: v2u64) -> v2i64; + fn __lsx_vaddwod_q_du(a: __v2u64, b: __v2u64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubwev.q.d"] - fn __lsx_vsubwev_q_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsubwev_q_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubwod.q.d"] - fn __lsx_vsubwod_q_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsubwod_q_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubwev.q.du"] - fn __lsx_vsubwev_q_du(a: v2u64, b: v2u64) -> v2i64; + fn __lsx_vsubwev_q_du(a: __v2u64, b: __v2u64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsubwod.q.du"] - fn __lsx_vsubwod_q_du(a: v2u64, b: v2u64) -> v2i64; + fn __lsx_vsubwod_q_du(a: __v2u64, b: __v2u64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwev.q.du.d"] - fn __lsx_vaddwev_q_du_d(a: v2u64, b: v2i64) -> v2i64; + fn __lsx_vaddwev_q_du_d(a: __v2u64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vaddwod.q.du.d"] - fn __lsx_vaddwod_q_du_d(a: v2u64, b: v2i64) -> v2i64; + fn __lsx_vaddwod_q_du_d(a: __v2u64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwev.d.w"] - fn __lsx_vmulwev_d_w(a: v4i32, b: v4i32) -> v2i64; + fn __lsx_vmulwev_d_w(a: __v4i32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwev.w.h"] - fn __lsx_vmulwev_w_h(a: v8i16, b: v8i16) -> v4i32; + fn __lsx_vmulwev_w_h(a: __v8i16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmulwev.h.b"] - fn __lsx_vmulwev_h_b(a: v16i8, b: v16i8) -> v8i16; + fn __lsx_vmulwev_h_b(a: __v16i8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmulwod.d.w"] - fn __lsx_vmulwod_d_w(a: v4i32, b: v4i32) -> v2i64; + fn __lsx_vmulwod_d_w(a: __v4i32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwod.w.h"] - fn __lsx_vmulwod_w_h(a: v8i16, b: v8i16) -> v4i32; + fn __lsx_vmulwod_w_h(a: __v8i16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmulwod.h.b"] - fn __lsx_vmulwod_h_b(a: v16i8, b: v16i8) -> v8i16; + fn __lsx_vmulwod_h_b(a: __v16i8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmulwev.d.wu"] - fn __lsx_vmulwev_d_wu(a: v4u32, b: v4u32) -> v2i64; + fn __lsx_vmulwev_d_wu(a: __v4u32, b: __v4u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwev.w.hu"] - fn __lsx_vmulwev_w_hu(a: v8u16, b: v8u16) -> v4i32; + fn __lsx_vmulwev_w_hu(a: __v8u16, b: __v8u16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmulwev.h.bu"] - fn __lsx_vmulwev_h_bu(a: v16u8, b: v16u8) -> v8i16; + fn __lsx_vmulwev_h_bu(a: __v16u8, b: __v16u8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmulwod.d.wu"] - fn __lsx_vmulwod_d_wu(a: v4u32, b: v4u32) -> v2i64; + fn __lsx_vmulwod_d_wu(a: __v4u32, b: __v4u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwod.w.hu"] - fn __lsx_vmulwod_w_hu(a: v8u16, b: v8u16) -> v4i32; + fn __lsx_vmulwod_w_hu(a: __v8u16, b: __v8u16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmulwod.h.bu"] - fn __lsx_vmulwod_h_bu(a: v16u8, b: v16u8) -> v8i16; + fn __lsx_vmulwod_h_bu(a: __v16u8, b: __v16u8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmulwev.d.wu.w"] - fn __lsx_vmulwev_d_wu_w(a: v4u32, b: v4i32) -> v2i64; + fn __lsx_vmulwev_d_wu_w(a: __v4u32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwev.w.hu.h"] - fn __lsx_vmulwev_w_hu_h(a: v8u16, b: v8i16) -> v4i32; + fn __lsx_vmulwev_w_hu_h(a: __v8u16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmulwev.h.bu.b"] - fn __lsx_vmulwev_h_bu_b(a: v16u8, b: v16i8) -> v8i16; + fn __lsx_vmulwev_h_bu_b(a: __v16u8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmulwod.d.wu.w"] - fn __lsx_vmulwod_d_wu_w(a: v4u32, b: v4i32) -> v2i64; + fn __lsx_vmulwod_d_wu_w(a: __v4u32, b: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwod.w.hu.h"] - fn __lsx_vmulwod_w_hu_h(a: v8u16, b: v8i16) -> v4i32; + fn __lsx_vmulwod_w_hu_h(a: __v8u16, b: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmulwod.h.bu.b"] - fn __lsx_vmulwod_h_bu_b(a: v16u8, b: v16i8) -> v8i16; + fn __lsx_vmulwod_h_bu_b(a: __v16u8, b: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmulwev.q.d"] - fn __lsx_vmulwev_q_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vmulwev_q_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwod.q.d"] - fn __lsx_vmulwod_q_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vmulwod_q_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwev.q.du"] - fn __lsx_vmulwev_q_du(a: v2u64, b: v2u64) -> v2i64; + fn __lsx_vmulwev_q_du(a: __v2u64, b: __v2u64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwod.q.du"] - fn __lsx_vmulwod_q_du(a: v2u64, b: v2u64) -> v2i64; + fn __lsx_vmulwod_q_du(a: __v2u64, b: __v2u64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwev.q.du.d"] - fn __lsx_vmulwev_q_du_d(a: v2u64, b: v2i64) -> v2i64; + fn __lsx_vmulwev_q_du_d(a: __v2u64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmulwod.q.du.d"] - fn __lsx_vmulwod_q_du_d(a: v2u64, b: v2i64) -> v2i64; + fn __lsx_vmulwod_q_du_d(a: __v2u64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vhaddw.q.d"] - fn __lsx_vhaddw_q_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vhaddw_q_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vhaddw.qu.du"] - fn __lsx_vhaddw_qu_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vhaddw_qu_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vhsubw.q.d"] - fn __lsx_vhsubw_q_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vhsubw_q_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vhsubw.qu.du"] - fn __lsx_vhsubw_qu_du(a: v2u64, b: v2u64) -> v2u64; + fn __lsx_vhsubw_qu_du(a: __v2u64, b: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmaddwev.d.w"] - fn __lsx_vmaddwev_d_w(a: v2i64, b: v4i32, c: v4i32) -> v2i64; + fn __lsx_vmaddwev_d_w(a: __v2i64, b: __v4i32, c: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmaddwev.w.h"] - fn __lsx_vmaddwev_w_h(a: v4i32, b: v8i16, c: v8i16) -> v4i32; + fn __lsx_vmaddwev_w_h(a: __v4i32, b: __v8i16, c: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmaddwev.h.b"] - fn __lsx_vmaddwev_h_b(a: v8i16, b: v16i8, c: v16i8) -> v8i16; + fn __lsx_vmaddwev_h_b(a: __v8i16, b: __v16i8, c: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmaddwev.d.wu"] - fn __lsx_vmaddwev_d_wu(a: v2u64, b: v4u32, c: v4u32) -> v2u64; + fn __lsx_vmaddwev_d_wu(a: __v2u64, b: __v4u32, c: __v4u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmaddwev.w.hu"] - fn __lsx_vmaddwev_w_hu(a: v4u32, b: v8u16, c: v8u16) -> v4u32; + fn __lsx_vmaddwev_w_hu(a: __v4u32, b: __v8u16, c: __v8u16) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vmaddwev.h.bu"] - fn __lsx_vmaddwev_h_bu(a: v8u16, b: v16u8, c: v16u8) -> v8u16; + fn __lsx_vmaddwev_h_bu(a: __v8u16, b: __v16u8, c: __v16u8) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vmaddwod.d.w"] - fn __lsx_vmaddwod_d_w(a: v2i64, b: v4i32, c: v4i32) -> v2i64; + fn __lsx_vmaddwod_d_w(a: __v2i64, b: __v4i32, c: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmaddwod.w.h"] - fn __lsx_vmaddwod_w_h(a: v4i32, b: v8i16, c: v8i16) -> v4i32; + fn __lsx_vmaddwod_w_h(a: __v4i32, b: __v8i16, c: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmaddwod.h.b"] - fn __lsx_vmaddwod_h_b(a: v8i16, b: v16i8, c: v16i8) -> v8i16; + fn __lsx_vmaddwod_h_b(a: __v8i16, b: __v16i8, c: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmaddwod.d.wu"] - fn __lsx_vmaddwod_d_wu(a: v2u64, b: v4u32, c: v4u32) -> v2u64; + fn __lsx_vmaddwod_d_wu(a: __v2u64, b: __v4u32, c: __v4u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmaddwod.w.hu"] - fn __lsx_vmaddwod_w_hu(a: v4u32, b: v8u16, c: v8u16) -> v4u32; + fn __lsx_vmaddwod_w_hu(a: __v4u32, b: __v8u16, c: __v8u16) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vmaddwod.h.bu"] - fn __lsx_vmaddwod_h_bu(a: v8u16, b: v16u8, c: v16u8) -> v8u16; + fn __lsx_vmaddwod_h_bu(a: __v8u16, b: __v16u8, c: __v16u8) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vmaddwev.d.wu.w"] - fn __lsx_vmaddwev_d_wu_w(a: v2i64, b: v4u32, c: v4i32) -> v2i64; + fn __lsx_vmaddwev_d_wu_w(a: __v2i64, b: __v4u32, c: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmaddwev.w.hu.h"] - fn __lsx_vmaddwev_w_hu_h(a: v4i32, b: v8u16, c: v8i16) -> v4i32; + fn __lsx_vmaddwev_w_hu_h(a: __v4i32, b: __v8u16, c: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmaddwev.h.bu.b"] - fn __lsx_vmaddwev_h_bu_b(a: v8i16, b: v16u8, c: v16i8) -> v8i16; + fn __lsx_vmaddwev_h_bu_b(a: __v8i16, b: __v16u8, c: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmaddwod.d.wu.w"] - fn __lsx_vmaddwod_d_wu_w(a: v2i64, b: v4u32, c: v4i32) -> v2i64; + fn __lsx_vmaddwod_d_wu_w(a: __v2i64, b: __v4u32, c: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmaddwod.w.hu.h"] - fn __lsx_vmaddwod_w_hu_h(a: v4i32, b: v8u16, c: v8i16) -> v4i32; + fn __lsx_vmaddwod_w_hu_h(a: __v4i32, b: __v8u16, c: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vmaddwod.h.bu.b"] - fn __lsx_vmaddwod_h_bu_b(a: v8i16, b: v16u8, c: v16i8) -> v8i16; + fn __lsx_vmaddwod_h_bu_b(a: __v8i16, b: __v16u8, c: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vmaddwev.q.d"] - fn __lsx_vmaddwev_q_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64; + fn __lsx_vmaddwev_q_d(a: __v2i64, b: __v2i64, c: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmaddwod.q.d"] - fn __lsx_vmaddwod_q_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64; + fn __lsx_vmaddwod_q_d(a: __v2i64, b: __v2i64, c: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmaddwev.q.du"] - fn __lsx_vmaddwev_q_du(a: v2u64, b: v2u64, c: v2u64) -> v2u64; + fn __lsx_vmaddwev_q_du(a: __v2u64, b: __v2u64, c: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmaddwod.q.du"] - fn __lsx_vmaddwod_q_du(a: v2u64, b: v2u64, c: v2u64) -> v2u64; + fn __lsx_vmaddwod_q_du(a: __v2u64, b: __v2u64, c: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vmaddwev.q.du.d"] - fn __lsx_vmaddwev_q_du_d(a: v2i64, b: v2u64, c: v2i64) -> v2i64; + fn __lsx_vmaddwev_q_du_d(a: __v2i64, b: __v2u64, c: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmaddwod.q.du.d"] - fn __lsx_vmaddwod_q_du_d(a: v2i64, b: v2u64, c: v2i64) -> v2i64; + fn __lsx_vmaddwod_q_du_d(a: __v2i64, b: __v2u64, c: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vrotr.b"] - fn __lsx_vrotr_b(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vrotr_b(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vrotr.h"] - fn __lsx_vrotr_h(a: v8i16, b: v8i16) -> v8i16; + fn __lsx_vrotr_h(a: __v8i16, b: __v8i16) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vrotr.w"] - fn __lsx_vrotr_w(a: v4i32, b: v4i32) -> v4i32; + fn __lsx_vrotr_w(a: __v4i32, b: __v4i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vrotr.d"] - fn __lsx_vrotr_d(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vrotr_d(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vadd.q"] - fn __lsx_vadd_q(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vadd_q(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsub.q"] - fn __lsx_vsub_q(a: v2i64, b: v2i64) -> v2i64; + fn __lsx_vsub_q(a: __v2i64, b: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vldrepl.b"] - fn __lsx_vldrepl_b(a: *const i8, b: i32) -> v16i8; + fn __lsx_vldrepl_b(a: *const i8, b: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vldrepl.h"] - fn __lsx_vldrepl_h(a: *const i8, b: i32) -> v8i16; + fn __lsx_vldrepl_h(a: *const i8, b: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vldrepl.w"] - fn __lsx_vldrepl_w(a: *const i8, b: i32) -> v4i32; + fn __lsx_vldrepl_w(a: *const i8, b: i32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vldrepl.d"] - fn __lsx_vldrepl_d(a: *const i8, b: i32) -> v2i64; + fn __lsx_vldrepl_d(a: *const i8, b: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vmskgez.b"] - fn __lsx_vmskgez_b(a: v16i8) -> v16i8; + fn __lsx_vmskgez_b(a: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vmsknz.b"] - fn __lsx_vmsknz_b(a: v16i8) -> v16i8; + fn __lsx_vmsknz_b(a: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vexth.h.b"] - fn __lsx_vexth_h_b(a: v16i8) -> v8i16; + fn __lsx_vexth_h_b(a: __v16i8) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vexth.w.h"] - fn __lsx_vexth_w_h(a: v8i16) -> v4i32; + fn __lsx_vexth_w_h(a: __v8i16) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vexth.d.w"] - fn __lsx_vexth_d_w(a: v4i32) -> v2i64; + fn __lsx_vexth_d_w(a: __v4i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vexth.q.d"] - fn __lsx_vexth_q_d(a: v2i64) -> v2i64; + fn __lsx_vexth_q_d(a: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vexth.hu.bu"] - fn __lsx_vexth_hu_bu(a: v16u8) -> v8u16; + fn __lsx_vexth_hu_bu(a: __v16u8) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vexth.wu.hu"] - fn __lsx_vexth_wu_hu(a: v8u16) -> v4u32; + fn __lsx_vexth_wu_hu(a: __v8u16) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vexth.du.wu"] - fn __lsx_vexth_du_wu(a: v4u32) -> v2u64; + fn __lsx_vexth_du_wu(a: __v4u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vexth.qu.du"] - fn __lsx_vexth_qu_du(a: v2u64) -> v2u64; + fn __lsx_vexth_qu_du(a: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vrotri.b"] - fn __lsx_vrotri_b(a: v16i8, b: u32) -> v16i8; + fn __lsx_vrotri_b(a: __v16i8, b: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vrotri.h"] - fn __lsx_vrotri_h(a: v8i16, b: u32) -> v8i16; + fn __lsx_vrotri_h(a: __v8i16, b: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vrotri.w"] - fn __lsx_vrotri_w(a: v4i32, b: u32) -> v4i32; + fn __lsx_vrotri_w(a: __v4i32, b: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vrotri.d"] - fn __lsx_vrotri_d(a: v2i64, b: u32) -> v2i64; + fn __lsx_vrotri_d(a: __v2i64, b: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vextl.q.d"] - fn __lsx_vextl_q_d(a: v2i64) -> v2i64; + fn __lsx_vextl_q_d(a: __v2i64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrlni.b.h"] - fn __lsx_vsrlni_b_h(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vsrlni_b_h(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrlni.h.w"] - fn __lsx_vsrlni_h_w(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vsrlni_h_w(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrlni.w.d"] - fn __lsx_vsrlni_w_d(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vsrlni_w_d(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrlni.d.q"] - fn __lsx_vsrlni_d_q(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vsrlni_d_q(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrlrni.b.h"] - fn __lsx_vsrlrni_b_h(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vsrlrni_b_h(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrlrni.h.w"] - fn __lsx_vsrlrni_h_w(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vsrlrni_h_w(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrlrni.w.d"] - fn __lsx_vsrlrni_w_d(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vsrlrni_w_d(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrlrni.d.q"] - fn __lsx_vsrlrni_d_q(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vsrlrni_d_q(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vssrlni.b.h"] - fn __lsx_vssrlni_b_h(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vssrlni_b_h(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssrlni.h.w"] - fn __lsx_vssrlni_h_w(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vssrlni_h_w(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssrlni.w.d"] - fn __lsx_vssrlni_w_d(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vssrlni_w_d(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrlni.d.q"] - fn __lsx_vssrlni_d_q(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vssrlni_d_q(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vssrlni.bu.h"] - fn __lsx_vssrlni_bu_h(a: v16u8, b: v16i8, c: u32) -> v16u8; + fn __lsx_vssrlni_bu_h(a: __v16u8, b: __v16i8, c: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssrlni.hu.w"] - fn __lsx_vssrlni_hu_w(a: v8u16, b: v8i16, c: u32) -> v8u16; + fn __lsx_vssrlni_hu_w(a: __v8u16, b: __v8i16, c: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssrlni.wu.d"] - fn __lsx_vssrlni_wu_d(a: v4u32, b: v4i32, c: u32) -> v4u32; + fn __lsx_vssrlni_wu_d(a: __v4u32, b: __v4i32, c: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vssrlni.du.q"] - fn __lsx_vssrlni_du_q(a: v2u64, b: v2i64, c: u32) -> v2u64; + fn __lsx_vssrlni_du_q(a: __v2u64, b: __v2i64, c: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vssrlrni.b.h"] - fn __lsx_vssrlrni_b_h(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vssrlrni_b_h(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssrlrni.h.w"] - fn __lsx_vssrlrni_h_w(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vssrlrni_h_w(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssrlrni.w.d"] - fn __lsx_vssrlrni_w_d(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vssrlrni_w_d(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrlrni.d.q"] - fn __lsx_vssrlrni_d_q(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vssrlrni_d_q(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vssrlrni.bu.h"] - fn __lsx_vssrlrni_bu_h(a: v16u8, b: v16i8, c: u32) -> v16u8; + fn __lsx_vssrlrni_bu_h(a: __v16u8, b: __v16i8, c: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssrlrni.hu.w"] - fn __lsx_vssrlrni_hu_w(a: v8u16, b: v8i16, c: u32) -> v8u16; + fn __lsx_vssrlrni_hu_w(a: __v8u16, b: __v8i16, c: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssrlrni.wu.d"] - fn __lsx_vssrlrni_wu_d(a: v4u32, b: v4i32, c: u32) -> v4u32; + fn __lsx_vssrlrni_wu_d(a: __v4u32, b: __v4i32, c: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vssrlrni.du.q"] - fn __lsx_vssrlrni_du_q(a: v2u64, b: v2i64, c: u32) -> v2u64; + fn __lsx_vssrlrni_du_q(a: __v2u64, b: __v2i64, c: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vsrani.b.h"] - fn __lsx_vsrani_b_h(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vsrani_b_h(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrani.h.w"] - fn __lsx_vsrani_h_w(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vsrani_h_w(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrani.w.d"] - fn __lsx_vsrani_w_d(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vsrani_w_d(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrani.d.q"] - fn __lsx_vsrani_d_q(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vsrani_d_q(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vsrarni.b.h"] - fn __lsx_vsrarni_b_h(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vsrarni_b_h(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vsrarni.h.w"] - fn __lsx_vsrarni_h_w(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vsrarni_h_w(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vsrarni.w.d"] - fn __lsx_vsrarni_w_d(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vsrarni_w_d(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vsrarni.d.q"] - fn __lsx_vsrarni_d_q(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vsrarni_d_q(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vssrani.b.h"] - fn __lsx_vssrani_b_h(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vssrani_b_h(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssrani.h.w"] - fn __lsx_vssrani_h_w(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vssrani_h_w(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssrani.w.d"] - fn __lsx_vssrani_w_d(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vssrani_w_d(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrani.d.q"] - fn __lsx_vssrani_d_q(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vssrani_d_q(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vssrani.bu.h"] - fn __lsx_vssrani_bu_h(a: v16u8, b: v16i8, c: u32) -> v16u8; + fn __lsx_vssrani_bu_h(a: __v16u8, b: __v16i8, c: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssrani.hu.w"] - fn __lsx_vssrani_hu_w(a: v8u16, b: v8i16, c: u32) -> v8u16; + fn __lsx_vssrani_hu_w(a: __v8u16, b: __v8i16, c: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssrani.wu.d"] - fn __lsx_vssrani_wu_d(a: v4u32, b: v4i32, c: u32) -> v4u32; + fn __lsx_vssrani_wu_d(a: __v4u32, b: __v4i32, c: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vssrani.du.q"] - fn __lsx_vssrani_du_q(a: v2u64, b: v2i64, c: u32) -> v2u64; + fn __lsx_vssrani_du_q(a: __v2u64, b: __v2i64, c: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vssrarni.b.h"] - fn __lsx_vssrarni_b_h(a: v16i8, b: v16i8, c: u32) -> v16i8; + fn __lsx_vssrarni_b_h(a: __v16i8, b: __v16i8, c: u32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssrarni.h.w"] - fn __lsx_vssrarni_h_w(a: v8i16, b: v8i16, c: u32) -> v8i16; + fn __lsx_vssrarni_h_w(a: __v8i16, b: __v8i16, c: u32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssrarni.w.d"] - fn __lsx_vssrarni_w_d(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vssrarni_w_d(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrarni.d.q"] - fn __lsx_vssrarni_d_q(a: v2i64, b: v2i64, c: u32) -> v2i64; + fn __lsx_vssrarni_d_q(a: __v2i64, b: __v2i64, c: u32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vssrarni.bu.h"] - fn __lsx_vssrarni_bu_h(a: v16u8, b: v16i8, c: u32) -> v16u8; + fn __lsx_vssrarni_bu_h(a: __v16u8, b: __v16i8, c: u32) -> __v16u8; #[link_name = "llvm.loongarch.lsx.vssrarni.hu.w"] - fn __lsx_vssrarni_hu_w(a: v8u16, b: v8i16, c: u32) -> v8u16; + fn __lsx_vssrarni_hu_w(a: __v8u16, b: __v8i16, c: u32) -> __v8u16; #[link_name = "llvm.loongarch.lsx.vssrarni.wu.d"] - fn __lsx_vssrarni_wu_d(a: v4u32, b: v4i32, c: u32) -> v4u32; + fn __lsx_vssrarni_wu_d(a: __v4u32, b: __v4i32, c: u32) -> __v4u32; #[link_name = "llvm.loongarch.lsx.vssrarni.du.q"] - fn __lsx_vssrarni_du_q(a: v2u64, b: v2i64, c: u32) -> v2u64; + fn __lsx_vssrarni_du_q(a: __v2u64, b: __v2i64, c: u32) -> __v2u64; #[link_name = "llvm.loongarch.lsx.vpermi.w"] - fn __lsx_vpermi_w(a: v4i32, b: v4i32, c: u32) -> v4i32; + fn __lsx_vpermi_w(a: __v4i32, b: __v4i32, c: u32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vld"] - fn __lsx_vld(a: *const i8, b: i32) -> v16i8; + fn __lsx_vld(a: *const i8, b: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vst"] - fn __lsx_vst(a: v16i8, b: *mut i8, c: i32); + fn __lsx_vst(a: __v16i8, b: *mut i8, c: i32); #[link_name = "llvm.loongarch.lsx.vssrlrn.b.h"] - fn __lsx_vssrlrn_b_h(a: v8i16, b: v8i16) -> v16i8; + fn __lsx_vssrlrn_b_h(a: __v8i16, b: __v8i16) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssrlrn.h.w"] - fn __lsx_vssrlrn_h_w(a: v4i32, b: v4i32) -> v8i16; + fn __lsx_vssrlrn_h_w(a: __v4i32, b: __v4i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssrlrn.w.d"] - fn __lsx_vssrlrn_w_d(a: v2i64, b: v2i64) -> v4i32; + fn __lsx_vssrlrn_w_d(a: __v2i64, b: __v2i64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vssrln.b.h"] - fn __lsx_vssrln_b_h(a: v8i16, b: v8i16) -> v16i8; + fn __lsx_vssrln_b_h(a: __v8i16, b: __v8i16) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vssrln.h.w"] - fn __lsx_vssrln_h_w(a: v4i32, b: v4i32) -> v8i16; + fn __lsx_vssrln_h_w(a: __v4i32, b: __v4i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vssrln.w.d"] - fn __lsx_vssrln_w_d(a: v2i64, b: v2i64) -> v4i32; + fn __lsx_vssrln_w_d(a: __v2i64, b: __v2i64) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vorn.v"] - fn __lsx_vorn_v(a: v16i8, b: v16i8) -> v16i8; + fn __lsx_vorn_v(a: __v16i8, b: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vldi"] - fn __lsx_vldi(a: i32) -> v2i64; + fn __lsx_vldi(a: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vshuf.b"] - fn __lsx_vshuf_b(a: v16i8, b: v16i8, c: v16i8) -> v16i8; + fn __lsx_vshuf_b(a: __v16i8, b: __v16i8, c: __v16i8) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vldx"] - fn __lsx_vldx(a: *const i8, b: i64) -> v16i8; + fn __lsx_vldx(a: *const i8, b: i64) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vstx"] - fn __lsx_vstx(a: v16i8, b: *mut i8, c: i64); + fn __lsx_vstx(a: __v16i8, b: *mut i8, c: i64); #[link_name = "llvm.loongarch.lsx.vextl.qu.du"] - fn __lsx_vextl_qu_du(a: v2u64) -> v2u64; + fn __lsx_vextl_qu_du(a: __v2u64) -> __v2u64; #[link_name = "llvm.loongarch.lsx.bnz.b"] - fn __lsx_bnz_b(a: v16u8) -> i32; + fn __lsx_bnz_b(a: __v16u8) -> i32; #[link_name = "llvm.loongarch.lsx.bnz.d"] - fn __lsx_bnz_d(a: v2u64) -> i32; + fn __lsx_bnz_d(a: __v2u64) -> i32; #[link_name = "llvm.loongarch.lsx.bnz.h"] - fn __lsx_bnz_h(a: v8u16) -> i32; + fn __lsx_bnz_h(a: __v8u16) -> i32; #[link_name = "llvm.loongarch.lsx.bnz.v"] - fn __lsx_bnz_v(a: v16u8) -> i32; + fn __lsx_bnz_v(a: __v16u8) -> i32; #[link_name = "llvm.loongarch.lsx.bnz.w"] - fn __lsx_bnz_w(a: v4u32) -> i32; + fn __lsx_bnz_w(a: __v4u32) -> i32; #[link_name = "llvm.loongarch.lsx.bz.b"] - fn __lsx_bz_b(a: v16u8) -> i32; + fn __lsx_bz_b(a: __v16u8) -> i32; #[link_name = "llvm.loongarch.lsx.bz.d"] - fn __lsx_bz_d(a: v2u64) -> i32; + fn __lsx_bz_d(a: __v2u64) -> i32; #[link_name = "llvm.loongarch.lsx.bz.h"] - fn __lsx_bz_h(a: v8u16) -> i32; + fn __lsx_bz_h(a: __v8u16) -> i32; #[link_name = "llvm.loongarch.lsx.bz.v"] - fn __lsx_bz_v(a: v16u8) -> i32; + fn __lsx_bz_v(a: __v16u8) -> i32; #[link_name = "llvm.loongarch.lsx.bz.w"] - fn __lsx_bz_w(a: v4u32) -> i32; + fn __lsx_bz_w(a: __v4u32) -> i32; #[link_name = "llvm.loongarch.lsx.vfcmp.caf.d"] - fn __lsx_vfcmp_caf_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_caf_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.caf.s"] - fn __lsx_vfcmp_caf_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_caf_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.ceq.d"] - fn __lsx_vfcmp_ceq_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_ceq_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.ceq.s"] - fn __lsx_vfcmp_ceq_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_ceq_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.cle.d"] - fn __lsx_vfcmp_cle_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_cle_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.cle.s"] - fn __lsx_vfcmp_cle_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_cle_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.clt.d"] - fn __lsx_vfcmp_clt_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_clt_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.clt.s"] - fn __lsx_vfcmp_clt_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_clt_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.cne.d"] - fn __lsx_vfcmp_cne_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_cne_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.cne.s"] - fn __lsx_vfcmp_cne_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_cne_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.cor.d"] - fn __lsx_vfcmp_cor_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_cor_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.cor.s"] - fn __lsx_vfcmp_cor_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_cor_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.cueq.d"] - fn __lsx_vfcmp_cueq_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_cueq_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.cueq.s"] - fn __lsx_vfcmp_cueq_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_cueq_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.cule.d"] - fn __lsx_vfcmp_cule_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_cule_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.cule.s"] - fn __lsx_vfcmp_cule_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_cule_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.cult.d"] - fn __lsx_vfcmp_cult_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_cult_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.cult.s"] - fn __lsx_vfcmp_cult_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_cult_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.cun.d"] - fn __lsx_vfcmp_cun_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_cun_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.cune.d"] - fn __lsx_vfcmp_cune_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_cune_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.cune.s"] - fn __lsx_vfcmp_cune_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_cune_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.cun.s"] - fn __lsx_vfcmp_cun_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_cun_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.saf.d"] - fn __lsx_vfcmp_saf_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_saf_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.saf.s"] - fn __lsx_vfcmp_saf_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_saf_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.seq.d"] - fn __lsx_vfcmp_seq_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_seq_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.seq.s"] - fn __lsx_vfcmp_seq_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_seq_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.sle.d"] - fn __lsx_vfcmp_sle_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_sle_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.sle.s"] - fn __lsx_vfcmp_sle_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_sle_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.slt.d"] - fn __lsx_vfcmp_slt_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_slt_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.slt.s"] - fn __lsx_vfcmp_slt_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_slt_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.sne.d"] - fn __lsx_vfcmp_sne_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_sne_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.sne.s"] - fn __lsx_vfcmp_sne_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_sne_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.sor.d"] - fn __lsx_vfcmp_sor_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_sor_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.sor.s"] - fn __lsx_vfcmp_sor_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_sor_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.sueq.d"] - fn __lsx_vfcmp_sueq_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_sueq_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.sueq.s"] - fn __lsx_vfcmp_sueq_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_sueq_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.sule.d"] - fn __lsx_vfcmp_sule_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_sule_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.sule.s"] - fn __lsx_vfcmp_sule_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_sule_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.sult.d"] - fn __lsx_vfcmp_sult_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_sult_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.sult.s"] - fn __lsx_vfcmp_sult_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_sult_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.sun.d"] - fn __lsx_vfcmp_sun_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_sun_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.sune.d"] - fn __lsx_vfcmp_sune_d(a: v2f64, b: v2f64) -> v2i64; + fn __lsx_vfcmp_sune_d(a: __v2f64, b: __v2f64) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vfcmp.sune.s"] - fn __lsx_vfcmp_sune_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_sune_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vfcmp.sun.s"] - fn __lsx_vfcmp_sun_s(a: v4f32, b: v4f32) -> v4i32; + fn __lsx_vfcmp_sun_s(a: __v4f32, b: __v4f32) -> __v4i32; #[link_name = "llvm.loongarch.lsx.vrepli.b"] - fn __lsx_vrepli_b(a: i32) -> v16i8; + fn __lsx_vrepli_b(a: i32) -> __v16i8; #[link_name = "llvm.loongarch.lsx.vrepli.d"] - fn __lsx_vrepli_d(a: i32) -> v2i64; + fn __lsx_vrepli_d(a: i32) -> __v2i64; #[link_name = "llvm.loongarch.lsx.vrepli.h"] - fn __lsx_vrepli_h(a: i32) -> v8i16; + fn __lsx_vrepli_h(a: i32) -> __v8i16; #[link_name = "llvm.loongarch.lsx.vrepli.w"] - fn __lsx_vrepli_w(a: i32) -> v4i32; + fn __lsx_vrepli_w(a: i32) -> __v4i32; } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsll_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsll_b(a, b) } +pub fn lsx_vsll_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsll_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsll_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsll_h(a, b) } +pub fn lsx_vsll_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsll_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsll_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsll_w(a, b) } +pub fn lsx_vsll_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsll_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsll_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsll_d(a, b) } +pub fn lsx_vsll_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsll_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslli_b(a: v16i8) -> v16i8 { +pub fn lsx_vslli_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vslli_b(a, IMM3) } + unsafe { transmute(__lsx_vslli_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslli_h(a: v8i16) -> v8i16 { +pub fn lsx_vslli_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vslli_h(a, IMM4) } + unsafe { transmute(__lsx_vslli_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslli_w(a: v4i32) -> v4i32 { +pub fn lsx_vslli_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslli_w(a, IMM5) } + unsafe { transmute(__lsx_vslli_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslli_d(a: v2i64) -> v2i64 { +pub fn lsx_vslli_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vslli_d(a, IMM6) } + unsafe { transmute(__lsx_vslli_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsra_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsra_b(a, b) } +pub fn lsx_vsra_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsra_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsra_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsra_h(a, b) } +pub fn lsx_vsra_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsra_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsra_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsra_w(a, b) } +pub fn lsx_vsra_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsra_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsra_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsra_d(a, b) } +pub fn lsx_vsra_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsra_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrai_b(a: v16i8) -> v16i8 { +pub fn lsx_vsrai_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vsrai_b(a, IMM3) } + unsafe { transmute(__lsx_vsrai_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrai_h(a: v8i16) -> v8i16 { +pub fn lsx_vsrai_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsrai_h(a, IMM4) } + unsafe { transmute(__lsx_vsrai_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrai_w(a: v4i32) -> v4i32 { +pub fn lsx_vsrai_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsrai_w(a, IMM5) } + unsafe { transmute(__lsx_vsrai_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrai_d(a: v2i64) -> v2i64 { +pub fn lsx_vsrai_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsrai_d(a, IMM6) } + unsafe { transmute(__lsx_vsrai_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrar_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsrar_b(a, b) } +pub fn lsx_vsrar_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrar_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrar_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsrar_h(a, b) } +pub fn lsx_vsrar_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrar_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrar_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsrar_w(a, b) } +pub fn lsx_vsrar_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrar_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrar_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsrar_d(a, b) } +pub fn lsx_vsrar_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrar_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrari_b(a: v16i8) -> v16i8 { +pub fn lsx_vsrari_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vsrari_b(a, IMM3) } + unsafe { transmute(__lsx_vsrari_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrari_h(a: v8i16) -> v8i16 { +pub fn lsx_vsrari_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsrari_h(a, IMM4) } + unsafe { transmute(__lsx_vsrari_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrari_w(a: v4i32) -> v4i32 { +pub fn lsx_vsrari_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsrari_w(a, IMM5) } + unsafe { transmute(__lsx_vsrari_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrari_d(a: v2i64) -> v2i64 { +pub fn lsx_vsrari_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsrari_d(a, IMM6) } + unsafe { transmute(__lsx_vsrari_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrl_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsrl_b(a, b) } +pub fn lsx_vsrl_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrl_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrl_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsrl_h(a, b) } +pub fn lsx_vsrl_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrl_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrl_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsrl_w(a, b) } +pub fn lsx_vsrl_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrl_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrl_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsrl_d(a, b) } +pub fn lsx_vsrl_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrl_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrli_b(a: v16i8) -> v16i8 { +pub fn lsx_vsrli_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vsrli_b(a, IMM3) } + unsafe { transmute(__lsx_vsrli_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrli_h(a: v8i16) -> v8i16 { +pub fn lsx_vsrli_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsrli_h(a, IMM4) } + unsafe { transmute(__lsx_vsrli_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrli_w(a: v4i32) -> v4i32 { +pub fn lsx_vsrli_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsrli_w(a, IMM5) } + unsafe { transmute(__lsx_vsrli_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrli_d(a: v2i64) -> v2i64 { +pub fn lsx_vsrli_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsrli_d(a, IMM6) } + unsafe { transmute(__lsx_vsrli_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlr_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsrlr_b(a, b) } +pub fn lsx_vsrlr_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrlr_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlr_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsrlr_h(a, b) } +pub fn lsx_vsrlr_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrlr_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlr_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsrlr_w(a, b) } +pub fn lsx_vsrlr_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrlr_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlr_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsrlr_d(a, b) } +pub fn lsx_vsrlr_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrlr_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlri_b(a: v16i8) -> v16i8 { +pub fn lsx_vsrlri_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vsrlri_b(a, IMM3) } + unsafe { transmute(__lsx_vsrlri_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlri_h(a: v8i16) -> v8i16 { +pub fn lsx_vsrlri_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsrlri_h(a, IMM4) } + unsafe { transmute(__lsx_vsrlri_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlri_w(a: v4i32) -> v4i32 { +pub fn lsx_vsrlri_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsrlri_w(a, IMM5) } + unsafe { transmute(__lsx_vsrlri_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlri_d(a: v2i64) -> v2i64 { +pub fn lsx_vsrlri_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsrlri_d(a, IMM6) } + unsafe { transmute(__lsx_vsrlri_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitclr_b(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vbitclr_b(a, b) } +pub fn lsx_vbitclr_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitclr_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitclr_h(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vbitclr_h(a, b) } +pub fn lsx_vbitclr_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitclr_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitclr_w(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vbitclr_w(a, b) } +pub fn lsx_vbitclr_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitclr_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitclr_d(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vbitclr_d(a, b) } +pub fn lsx_vbitclr_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitclr_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitclri_b(a: v16u8) -> v16u8 { +pub fn lsx_vbitclri_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vbitclri_b(a, IMM3) } + unsafe { transmute(__lsx_vbitclri_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitclri_h(a: v8u16) -> v8u16 { +pub fn lsx_vbitclri_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vbitclri_h(a, IMM4) } + unsafe { transmute(__lsx_vbitclri_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitclri_w(a: v4u32) -> v4u32 { +pub fn lsx_vbitclri_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vbitclri_w(a, IMM5) } + unsafe { transmute(__lsx_vbitclri_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitclri_d(a: v2u64) -> v2u64 { +pub fn lsx_vbitclri_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vbitclri_d(a, IMM6) } + unsafe { transmute(__lsx_vbitclri_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitset_b(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vbitset_b(a, b) } +pub fn lsx_vbitset_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitset_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitset_h(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vbitset_h(a, b) } +pub fn lsx_vbitset_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitset_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitset_w(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vbitset_w(a, b) } +pub fn lsx_vbitset_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitset_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitset_d(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vbitset_d(a, b) } +pub fn lsx_vbitset_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitset_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitseti_b(a: v16u8) -> v16u8 { +pub fn lsx_vbitseti_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vbitseti_b(a, IMM3) } + unsafe { transmute(__lsx_vbitseti_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitseti_h(a: v8u16) -> v8u16 { +pub fn lsx_vbitseti_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vbitseti_h(a, IMM4) } + unsafe { transmute(__lsx_vbitseti_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitseti_w(a: v4u32) -> v4u32 { +pub fn lsx_vbitseti_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vbitseti_w(a, IMM5) } + unsafe { transmute(__lsx_vbitseti_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitseti_d(a: v2u64) -> v2u64 { +pub fn lsx_vbitseti_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vbitseti_d(a, IMM6) } + unsafe { transmute(__lsx_vbitseti_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitrev_b(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vbitrev_b(a, b) } +pub fn lsx_vbitrev_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitrev_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitrev_h(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vbitrev_h(a, b) } +pub fn lsx_vbitrev_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitrev_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitrev_w(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vbitrev_w(a, b) } +pub fn lsx_vbitrev_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitrev_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitrev_d(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vbitrev_d(a, b) } +pub fn lsx_vbitrev_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vbitrev_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitrevi_b(a: v16u8) -> v16u8 { +pub fn lsx_vbitrevi_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vbitrevi_b(a, IMM3) } + unsafe { transmute(__lsx_vbitrevi_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitrevi_h(a: v8u16) -> v8u16 { +pub fn lsx_vbitrevi_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vbitrevi_h(a, IMM4) } + unsafe { transmute(__lsx_vbitrevi_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitrevi_w(a: v4u32) -> v4u32 { +pub fn lsx_vbitrevi_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vbitrevi_w(a, IMM5) } + unsafe { transmute(__lsx_vbitrevi_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitrevi_d(a: v2u64) -> v2u64 { +pub fn lsx_vbitrevi_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vbitrevi_d(a, IMM6) } + unsafe { transmute(__lsx_vbitrevi_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadd_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vadd_b(a, b) } +pub fn lsx_vadd_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadd_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadd_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vadd_h(a, b) } +pub fn lsx_vadd_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadd_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadd_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vadd_w(a, b) } +pub fn lsx_vadd_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadd_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadd_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vadd_d(a, b) } +pub fn lsx_vadd_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadd_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddi_bu(a: v16i8) -> v16i8 { +pub fn lsx_vaddi_bu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vaddi_bu(a, IMM5) } + unsafe { transmute(__lsx_vaddi_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddi_hu(a: v8i16) -> v8i16 { +pub fn lsx_vaddi_hu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vaddi_hu(a, IMM5) } + unsafe { transmute(__lsx_vaddi_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddi_wu(a: v4i32) -> v4i32 { +pub fn lsx_vaddi_wu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vaddi_wu(a, IMM5) } + unsafe { transmute(__lsx_vaddi_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddi_du(a: v2i64) -> v2i64 { +pub fn lsx_vaddi_du(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vaddi_du(a, IMM5) } + unsafe { transmute(__lsx_vaddi_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsub_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsub_b(a, b) } +pub fn lsx_vsub_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsub_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsub_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsub_h(a, b) } +pub fn lsx_vsub_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsub_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsub_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsub_w(a, b) } +pub fn lsx_vsub_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsub_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsub_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsub_d(a, b) } +pub fn lsx_vsub_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsub_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubi_bu(a: v16i8) -> v16i8 { +pub fn lsx_vsubi_bu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsubi_bu(a, IMM5) } + unsafe { transmute(__lsx_vsubi_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubi_hu(a: v8i16) -> v8i16 { +pub fn lsx_vsubi_hu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsubi_hu(a, IMM5) } + unsafe { transmute(__lsx_vsubi_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubi_wu(a: v4i32) -> v4i32 { +pub fn lsx_vsubi_wu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsubi_wu(a, IMM5) } + unsafe { transmute(__lsx_vsubi_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubi_du(a: v2i64) -> v2i64 { +pub fn lsx_vsubi_du(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsubi_du(a, IMM5) } + unsafe { transmute(__lsx_vsubi_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmax_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vmax_b(a, b) } +pub fn lsx_vmax_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmax_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmax_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vmax_h(a, b) } +pub fn lsx_vmax_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmax_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmax_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vmax_w(a, b) } +pub fn lsx_vmax_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmax_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmax_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmax_d(a, b) } +pub fn lsx_vmax_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmax_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaxi_b(a: v16i8) -> v16i8 { +pub fn lsx_vmaxi_b(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vmaxi_b(a, IMM_S5) } + unsafe { transmute(__lsx_vmaxi_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaxi_h(a: v8i16) -> v8i16 { +pub fn lsx_vmaxi_h(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vmaxi_h(a, IMM_S5) } + unsafe { transmute(__lsx_vmaxi_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaxi_w(a: v4i32) -> v4i32 { +pub fn lsx_vmaxi_w(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vmaxi_w(a, IMM_S5) } + unsafe { transmute(__lsx_vmaxi_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaxi_d(a: v2i64) -> v2i64 { +pub fn lsx_vmaxi_d(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vmaxi_d(a, IMM_S5) } + unsafe { transmute(__lsx_vmaxi_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmax_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vmax_bu(a, b) } +pub fn lsx_vmax_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmax_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmax_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vmax_hu(a, b) } +pub fn lsx_vmax_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmax_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmax_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vmax_wu(a, b) } +pub fn lsx_vmax_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmax_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmax_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vmax_du(a, b) } +pub fn lsx_vmax_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmax_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaxi_bu(a: v16u8) -> v16u8 { +pub fn lsx_vmaxi_bu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vmaxi_bu(a, IMM5) } + unsafe { transmute(__lsx_vmaxi_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaxi_hu(a: v8u16) -> v8u16 { +pub fn lsx_vmaxi_hu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vmaxi_hu(a, IMM5) } + unsafe { transmute(__lsx_vmaxi_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaxi_wu(a: v4u32) -> v4u32 { +pub fn lsx_vmaxi_wu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vmaxi_wu(a, IMM5) } + unsafe { transmute(__lsx_vmaxi_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaxi_du(a: v2u64) -> v2u64 { +pub fn lsx_vmaxi_du(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vmaxi_du(a, IMM5) } + unsafe { transmute(__lsx_vmaxi_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmin_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vmin_b(a, b) } +pub fn lsx_vmin_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmin_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmin_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vmin_h(a, b) } +pub fn lsx_vmin_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmin_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmin_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vmin_w(a, b) } +pub fn lsx_vmin_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmin_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmin_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmin_d(a, b) } +pub fn lsx_vmin_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmin_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmini_b(a: v16i8) -> v16i8 { +pub fn lsx_vmini_b(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vmini_b(a, IMM_S5) } + unsafe { transmute(__lsx_vmini_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmini_h(a: v8i16) -> v8i16 { +pub fn lsx_vmini_h(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vmini_h(a, IMM_S5) } + unsafe { transmute(__lsx_vmini_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmini_w(a: v4i32) -> v4i32 { +pub fn lsx_vmini_w(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vmini_w(a, IMM_S5) } + unsafe { transmute(__lsx_vmini_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmini_d(a: v2i64) -> v2i64 { +pub fn lsx_vmini_d(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vmini_d(a, IMM_S5) } + unsafe { transmute(__lsx_vmini_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmin_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vmin_bu(a, b) } +pub fn lsx_vmin_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmin_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmin_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vmin_hu(a, b) } +pub fn lsx_vmin_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmin_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmin_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vmin_wu(a, b) } +pub fn lsx_vmin_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmin_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmin_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vmin_du(a, b) } +pub fn lsx_vmin_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmin_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmini_bu(a: v16u8) -> v16u8 { +pub fn lsx_vmini_bu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vmini_bu(a, IMM5) } + unsafe { transmute(__lsx_vmini_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmini_hu(a: v8u16) -> v8u16 { +pub fn lsx_vmini_hu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vmini_hu(a, IMM5) } + unsafe { transmute(__lsx_vmini_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmini_wu(a: v4u32) -> v4u32 { +pub fn lsx_vmini_wu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vmini_wu(a, IMM5) } + unsafe { transmute(__lsx_vmini_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmini_du(a: v2u64) -> v2u64 { +pub fn lsx_vmini_du(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vmini_du(a, IMM5) } + unsafe { transmute(__lsx_vmini_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vseq_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vseq_b(a, b) } +pub fn lsx_vseq_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vseq_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vseq_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vseq_h(a, b) } +pub fn lsx_vseq_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vseq_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vseq_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vseq_w(a, b) } +pub fn lsx_vseq_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vseq_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vseq_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vseq_d(a, b) } +pub fn lsx_vseq_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vseq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vseqi_b(a: v16i8) -> v16i8 { +pub fn lsx_vseqi_b(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vseqi_b(a, IMM_S5) } + unsafe { transmute(__lsx_vseqi_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vseqi_h(a: v8i16) -> v8i16 { +pub fn lsx_vseqi_h(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vseqi_h(a, IMM_S5) } + unsafe { transmute(__lsx_vseqi_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vseqi_w(a: v4i32) -> v4i32 { +pub fn lsx_vseqi_w(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vseqi_w(a, IMM_S5) } + unsafe { transmute(__lsx_vseqi_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vseqi_d(a: v2i64) -> v2i64 { +pub fn lsx_vseqi_d(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vseqi_d(a, IMM_S5) } + unsafe { transmute(__lsx_vseqi_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslti_b(a: v16i8) -> v16i8 { +pub fn lsx_vslti_b(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vslti_b(a, IMM_S5) } + unsafe { transmute(__lsx_vslti_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslt_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vslt_b(a, b) } +pub fn lsx_vslt_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vslt_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslt_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vslt_h(a, b) } +pub fn lsx_vslt_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vslt_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslt_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vslt_w(a, b) } +pub fn lsx_vslt_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vslt_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslt_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vslt_d(a, b) } +pub fn lsx_vslt_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vslt_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslti_h(a: v8i16) -> v8i16 { +pub fn lsx_vslti_h(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vslti_h(a, IMM_S5) } + unsafe { transmute(__lsx_vslti_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslti_w(a: v4i32) -> v4i32 { +pub fn lsx_vslti_w(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vslti_w(a, IMM_S5) } + unsafe { transmute(__lsx_vslti_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslti_d(a: v2i64) -> v2i64 { +pub fn lsx_vslti_d(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vslti_d(a, IMM_S5) } + unsafe { transmute(__lsx_vslti_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslt_bu(a: v16u8, b: v16u8) -> v16i8 { - unsafe { __lsx_vslt_bu(a, b) } +pub fn lsx_vslt_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vslt_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslt_hu(a: v8u16, b: v8u16) -> v8i16 { - unsafe { __lsx_vslt_hu(a, b) } +pub fn lsx_vslt_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vslt_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslt_wu(a: v4u32, b: v4u32) -> v4i32 { - unsafe { __lsx_vslt_wu(a, b) } +pub fn lsx_vslt_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vslt_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslt_du(a: v2u64, b: v2u64) -> v2i64 { - unsafe { __lsx_vslt_du(a, b) } +pub fn lsx_vslt_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vslt_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslti_bu(a: v16u8) -> v16i8 { +pub fn lsx_vslti_bu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslti_bu(a, IMM5) } + unsafe { transmute(__lsx_vslti_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslti_hu(a: v8u16) -> v8i16 { +pub fn lsx_vslti_hu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslti_hu(a, IMM5) } + unsafe { transmute(__lsx_vslti_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslti_wu(a: v4u32) -> v4i32 { +pub fn lsx_vslti_wu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslti_wu(a, IMM5) } + unsafe { transmute(__lsx_vslti_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslti_du(a: v2u64) -> v2i64 { +pub fn lsx_vslti_du(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslti_du(a, IMM5) } + unsafe { transmute(__lsx_vslti_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsle_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsle_b(a, b) } +pub fn lsx_vsle_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsle_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsle_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsle_h(a, b) } +pub fn lsx_vsle_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsle_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsle_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsle_w(a, b) } +pub fn lsx_vsle_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsle_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsle_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsle_d(a, b) } +pub fn lsx_vsle_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsle_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslei_b(a: v16i8) -> v16i8 { +pub fn lsx_vslei_b(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vslei_b(a, IMM_S5) } + unsafe { transmute(__lsx_vslei_b(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslei_h(a: v8i16) -> v8i16 { +pub fn lsx_vslei_h(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vslei_h(a, IMM_S5) } + unsafe { transmute(__lsx_vslei_h(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslei_w(a: v4i32) -> v4i32 { +pub fn lsx_vslei_w(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vslei_w(a, IMM_S5) } + unsafe { transmute(__lsx_vslei_w(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslei_d(a: v2i64) -> v2i64 { +pub fn lsx_vslei_d(a: m128i) -> m128i { static_assert_simm_bits!(IMM_S5, 5); - unsafe { __lsx_vslei_d(a, IMM_S5) } + unsafe { transmute(__lsx_vslei_d(transmute(a), IMM_S5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsle_bu(a: v16u8, b: v16u8) -> v16i8 { - unsafe { __lsx_vsle_bu(a, b) } +pub fn lsx_vsle_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsle_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsle_hu(a: v8u16, b: v8u16) -> v8i16 { - unsafe { __lsx_vsle_hu(a, b) } +pub fn lsx_vsle_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsle_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsle_wu(a: v4u32, b: v4u32) -> v4i32 { - unsafe { __lsx_vsle_wu(a, b) } +pub fn lsx_vsle_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsle_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsle_du(a: v2u64, b: v2u64) -> v2i64 { - unsafe { __lsx_vsle_du(a, b) } +pub fn lsx_vsle_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsle_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslei_bu(a: v16u8) -> v16i8 { +pub fn lsx_vslei_bu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslei_bu(a, IMM5) } + unsafe { transmute(__lsx_vslei_bu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslei_hu(a: v8u16) -> v8i16 { +pub fn lsx_vslei_hu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslei_hu(a, IMM5) } + unsafe { transmute(__lsx_vslei_hu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslei_wu(a: v4u32) -> v4i32 { +pub fn lsx_vslei_wu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslei_wu(a, IMM5) } + unsafe { transmute(__lsx_vslei_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vslei_du(a: v2u64) -> v2i64 { +pub fn lsx_vslei_du(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vslei_du(a, IMM5) } + unsafe { transmute(__lsx_vslei_du(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsat_b(a: v16i8) -> v16i8 { +pub fn lsx_vsat_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vsat_b(a, IMM3) } + unsafe { transmute(__lsx_vsat_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsat_h(a: v8i16) -> v8i16 { +pub fn lsx_vsat_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsat_h(a, IMM4) } + unsafe { transmute(__lsx_vsat_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsat_w(a: v4i32) -> v4i32 { +pub fn lsx_vsat_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsat_w(a, IMM5) } + unsafe { transmute(__lsx_vsat_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsat_d(a: v2i64) -> v2i64 { +pub fn lsx_vsat_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsat_d(a, IMM6) } + unsafe { transmute(__lsx_vsat_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsat_bu(a: v16u8) -> v16u8 { +pub fn lsx_vsat_bu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vsat_bu(a, IMM3) } + unsafe { transmute(__lsx_vsat_bu(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsat_hu(a: v8u16) -> v8u16 { +pub fn lsx_vsat_hu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsat_hu(a, IMM4) } + unsafe { transmute(__lsx_vsat_hu(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsat_wu(a: v4u32) -> v4u32 { +pub fn lsx_vsat_wu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsat_wu(a, IMM5) } + unsafe { transmute(__lsx_vsat_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsat_du(a: v2u64) -> v2u64 { +pub fn lsx_vsat_du(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsat_du(a, IMM6) } + unsafe { transmute(__lsx_vsat_du(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadda_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vadda_b(a, b) } +pub fn lsx_vadda_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadda_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadda_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vadda_h(a, b) } +pub fn lsx_vadda_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadda_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadda_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vadda_w(a, b) } +pub fn lsx_vadda_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadda_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadda_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vadda_d(a, b) } +pub fn lsx_vadda_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadda_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsadd_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsadd_b(a, b) } +pub fn lsx_vsadd_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsadd_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsadd_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsadd_h(a, b) } +pub fn lsx_vsadd_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsadd_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsadd_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsadd_w(a, b) } +pub fn lsx_vsadd_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsadd_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsadd_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsadd_d(a, b) } +pub fn lsx_vsadd_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsadd_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsadd_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vsadd_bu(a, b) } +pub fn lsx_vsadd_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsadd_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsadd_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vsadd_hu(a, b) } +pub fn lsx_vsadd_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsadd_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsadd_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vsadd_wu(a, b) } +pub fn lsx_vsadd_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsadd_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsadd_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vsadd_du(a, b) } +pub fn lsx_vsadd_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsadd_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavg_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vavg_b(a, b) } +pub fn lsx_vavg_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavg_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavg_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vavg_h(a, b) } +pub fn lsx_vavg_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavg_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavg_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vavg_w(a, b) } +pub fn lsx_vavg_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavg_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavg_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vavg_d(a, b) } +pub fn lsx_vavg_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavg_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavg_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vavg_bu(a, b) } +pub fn lsx_vavg_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavg_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavg_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vavg_hu(a, b) } +pub fn lsx_vavg_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavg_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavg_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vavg_wu(a, b) } +pub fn lsx_vavg_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavg_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavg_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vavg_du(a, b) } +pub fn lsx_vavg_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavg_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavgr_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vavgr_b(a, b) } +pub fn lsx_vavgr_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavgr_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavgr_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vavgr_h(a, b) } +pub fn lsx_vavgr_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavgr_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavgr_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vavgr_w(a, b) } +pub fn lsx_vavgr_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavgr_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavgr_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vavgr_d(a, b) } +pub fn lsx_vavgr_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavgr_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavgr_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vavgr_bu(a, b) } +pub fn lsx_vavgr_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavgr_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavgr_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vavgr_hu(a, b) } +pub fn lsx_vavgr_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavgr_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavgr_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vavgr_wu(a, b) } +pub fn lsx_vavgr_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavgr_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vavgr_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vavgr_du(a, b) } +pub fn lsx_vavgr_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vavgr_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssub_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vssub_b(a, b) } +pub fn lsx_vssub_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssub_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssub_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vssub_h(a, b) } +pub fn lsx_vssub_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssub_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssub_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vssub_w(a, b) } +pub fn lsx_vssub_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssub_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssub_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vssub_d(a, b) } +pub fn lsx_vssub_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssub_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssub_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vssub_bu(a, b) } +pub fn lsx_vssub_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssub_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssub_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vssub_hu(a, b) } +pub fn lsx_vssub_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssub_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssub_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vssub_wu(a, b) } +pub fn lsx_vssub_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssub_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssub_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vssub_du(a, b) } +pub fn lsx_vssub_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssub_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vabsd_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vabsd_b(a, b) } +pub fn lsx_vabsd_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vabsd_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vabsd_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vabsd_h(a, b) } +pub fn lsx_vabsd_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vabsd_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vabsd_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vabsd_w(a, b) } +pub fn lsx_vabsd_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vabsd_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vabsd_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vabsd_d(a, b) } +pub fn lsx_vabsd_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vabsd_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vabsd_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vabsd_bu(a, b) } +pub fn lsx_vabsd_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vabsd_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vabsd_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vabsd_hu(a, b) } +pub fn lsx_vabsd_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vabsd_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vabsd_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vabsd_wu(a, b) } +pub fn lsx_vabsd_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vabsd_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vabsd_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vabsd_du(a, b) } +pub fn lsx_vabsd_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vabsd_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmul_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vmul_b(a, b) } +pub fn lsx_vmul_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmul_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmul_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vmul_h(a, b) } +pub fn lsx_vmul_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmul_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmul_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vmul_w(a, b) } +pub fn lsx_vmul_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmul_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmul_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmul_d(a, b) } +pub fn lsx_vmul_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmul_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmadd_b(a: v16i8, b: v16i8, c: v16i8) -> v16i8 { - unsafe { __lsx_vmadd_b(a, b, c) } +pub fn lsx_vmadd_b(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmadd_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmadd_h(a: v8i16, b: v8i16, c: v8i16) -> v8i16 { - unsafe { __lsx_vmadd_h(a, b, c) } +pub fn lsx_vmadd_h(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmadd_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmadd_w(a: v4i32, b: v4i32, c: v4i32) -> v4i32 { - unsafe { __lsx_vmadd_w(a, b, c) } +pub fn lsx_vmadd_w(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmadd_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmadd_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64 { - unsafe { __lsx_vmadd_d(a, b, c) } +pub fn lsx_vmadd_d(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmadd_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmsub_b(a: v16i8, b: v16i8, c: v16i8) -> v16i8 { - unsafe { __lsx_vmsub_b(a, b, c) } +pub fn lsx_vmsub_b(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmsub_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmsub_h(a: v8i16, b: v8i16, c: v8i16) -> v8i16 { - unsafe { __lsx_vmsub_h(a, b, c) } +pub fn lsx_vmsub_h(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmsub_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmsub_w(a: v4i32, b: v4i32, c: v4i32) -> v4i32 { - unsafe { __lsx_vmsub_w(a, b, c) } +pub fn lsx_vmsub_w(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmsub_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmsub_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64 { - unsafe { __lsx_vmsub_d(a, b, c) } +pub fn lsx_vmsub_d(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmsub_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vdiv_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vdiv_b(a, b) } +pub fn lsx_vdiv_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vdiv_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vdiv_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vdiv_h(a, b) } +pub fn lsx_vdiv_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vdiv_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vdiv_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vdiv_w(a, b) } +pub fn lsx_vdiv_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vdiv_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vdiv_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vdiv_d(a, b) } +pub fn lsx_vdiv_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vdiv_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vdiv_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vdiv_bu(a, b) } +pub fn lsx_vdiv_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vdiv_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vdiv_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vdiv_hu(a, b) } +pub fn lsx_vdiv_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vdiv_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vdiv_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vdiv_wu(a, b) } +pub fn lsx_vdiv_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vdiv_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vdiv_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vdiv_du(a, b) } +pub fn lsx_vdiv_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vdiv_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhaddw_h_b(a: v16i8, b: v16i8) -> v8i16 { - unsafe { __lsx_vhaddw_h_b(a, b) } +pub fn lsx_vhaddw_h_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhaddw_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhaddw_w_h(a: v8i16, b: v8i16) -> v4i32 { - unsafe { __lsx_vhaddw_w_h(a, b) } +pub fn lsx_vhaddw_w_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhaddw_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhaddw_d_w(a: v4i32, b: v4i32) -> v2i64 { - unsafe { __lsx_vhaddw_d_w(a, b) } +pub fn lsx_vhaddw_d_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhaddw_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhaddw_hu_bu(a: v16u8, b: v16u8) -> v8u16 { - unsafe { __lsx_vhaddw_hu_bu(a, b) } +pub fn lsx_vhaddw_hu_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhaddw_hu_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhaddw_wu_hu(a: v8u16, b: v8u16) -> v4u32 { - unsafe { __lsx_vhaddw_wu_hu(a, b) } +pub fn lsx_vhaddw_wu_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhaddw_wu_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhaddw_du_wu(a: v4u32, b: v4u32) -> v2u64 { - unsafe { __lsx_vhaddw_du_wu(a, b) } +pub fn lsx_vhaddw_du_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhaddw_du_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhsubw_h_b(a: v16i8, b: v16i8) -> v8i16 { - unsafe { __lsx_vhsubw_h_b(a, b) } +pub fn lsx_vhsubw_h_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhsubw_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhsubw_w_h(a: v8i16, b: v8i16) -> v4i32 { - unsafe { __lsx_vhsubw_w_h(a, b) } +pub fn lsx_vhsubw_w_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhsubw_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhsubw_d_w(a: v4i32, b: v4i32) -> v2i64 { - unsafe { __lsx_vhsubw_d_w(a, b) } +pub fn lsx_vhsubw_d_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhsubw_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhsubw_hu_bu(a: v16u8, b: v16u8) -> v8i16 { - unsafe { __lsx_vhsubw_hu_bu(a, b) } +pub fn lsx_vhsubw_hu_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhsubw_hu_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhsubw_wu_hu(a: v8u16, b: v8u16) -> v4i32 { - unsafe { __lsx_vhsubw_wu_hu(a, b) } +pub fn lsx_vhsubw_wu_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhsubw_wu_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhsubw_du_wu(a: v4u32, b: v4u32) -> v2i64 { - unsafe { __lsx_vhsubw_du_wu(a, b) } +pub fn lsx_vhsubw_du_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhsubw_du_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmod_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vmod_b(a, b) } +pub fn lsx_vmod_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmod_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmod_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vmod_h(a, b) } +pub fn lsx_vmod_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmod_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmod_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vmod_w(a, b) } +pub fn lsx_vmod_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmod_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmod_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmod_d(a, b) } +pub fn lsx_vmod_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmod_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmod_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vmod_bu(a, b) } +pub fn lsx_vmod_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmod_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmod_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vmod_hu(a, b) } +pub fn lsx_vmod_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmod_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmod_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vmod_wu(a, b) } +pub fn lsx_vmod_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmod_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmod_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vmod_du(a, b) } +pub fn lsx_vmod_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmod_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplve_b(a: v16i8, b: i32) -> v16i8 { - unsafe { __lsx_vreplve_b(a, b) } +pub fn lsx_vreplve_b(a: m128i, b: i32) -> m128i { + unsafe { transmute(__lsx_vreplve_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplve_h(a: v8i16, b: i32) -> v8i16 { - unsafe { __lsx_vreplve_h(a, b) } +pub fn lsx_vreplve_h(a: m128i, b: i32) -> m128i { + unsafe { transmute(__lsx_vreplve_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplve_w(a: v4i32, b: i32) -> v4i32 { - unsafe { __lsx_vreplve_w(a, b) } +pub fn lsx_vreplve_w(a: m128i, b: i32) -> m128i { + unsafe { transmute(__lsx_vreplve_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplve_d(a: v2i64, b: i32) -> v2i64 { - unsafe { __lsx_vreplve_d(a, b) } +pub fn lsx_vreplve_d(a: m128i, b: i32) -> m128i { + unsafe { transmute(__lsx_vreplve_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplvei_b(a: v16i8) -> v16i8 { +pub fn lsx_vreplvei_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vreplvei_b(a, IMM4) } + unsafe { transmute(__lsx_vreplvei_b(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplvei_h(a: v8i16) -> v8i16 { +pub fn lsx_vreplvei_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vreplvei_h(a, IMM3) } + unsafe { transmute(__lsx_vreplvei_h(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplvei_w(a: v4i32) -> v4i32 { +pub fn lsx_vreplvei_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lsx_vreplvei_w(a, IMM2) } + unsafe { transmute(__lsx_vreplvei_w(transmute(a), IMM2)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplvei_d(a: v2i64) -> v2i64 { +pub fn lsx_vreplvei_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM1, 1); - unsafe { __lsx_vreplvei_d(a, IMM1) } + unsafe { transmute(__lsx_vreplvei_d(transmute(a), IMM1)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickev_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vpickev_b(a, b) } +pub fn lsx_vpickev_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpickev_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickev_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vpickev_h(a, b) } +pub fn lsx_vpickev_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpickev_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickev_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vpickev_w(a, b) } +pub fn lsx_vpickev_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpickev_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickev_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vpickev_d(a, b) } +pub fn lsx_vpickev_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpickev_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickod_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vpickod_b(a, b) } +pub fn lsx_vpickod_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpickod_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickod_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vpickod_h(a, b) } +pub fn lsx_vpickod_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpickod_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickod_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vpickod_w(a, b) } +pub fn lsx_vpickod_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpickod_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickod_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vpickod_d(a, b) } +pub fn lsx_vpickod_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpickod_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vilvh_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vilvh_b(a, b) } +pub fn lsx_vilvh_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vilvh_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vilvh_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vilvh_h(a, b) } +pub fn lsx_vilvh_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vilvh_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vilvh_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vilvh_w(a, b) } +pub fn lsx_vilvh_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vilvh_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vilvh_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vilvh_d(a, b) } +pub fn lsx_vilvh_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vilvh_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vilvl_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vilvl_b(a, b) } +pub fn lsx_vilvl_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vilvl_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vilvl_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vilvl_h(a, b) } +pub fn lsx_vilvl_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vilvl_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vilvl_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vilvl_w(a, b) } +pub fn lsx_vilvl_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vilvl_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vilvl_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vilvl_d(a, b) } +pub fn lsx_vilvl_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vilvl_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpackev_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vpackev_b(a, b) } +pub fn lsx_vpackev_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpackev_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpackev_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vpackev_h(a, b) } +pub fn lsx_vpackev_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpackev_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpackev_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vpackev_w(a, b) } +pub fn lsx_vpackev_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpackev_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpackev_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vpackev_d(a, b) } +pub fn lsx_vpackev_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpackev_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpackod_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vpackod_b(a, b) } +pub fn lsx_vpackod_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpackod_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpackod_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vpackod_h(a, b) } +pub fn lsx_vpackod_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpackod_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpackod_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vpackod_w(a, b) } +pub fn lsx_vpackod_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpackod_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpackod_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vpackod_d(a, b) } +pub fn lsx_vpackod_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vpackod_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vshuf_h(a: v8i16, b: v8i16, c: v8i16) -> v8i16 { - unsafe { __lsx_vshuf_h(a, b, c) } +pub fn lsx_vshuf_h(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vshuf_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vshuf_w(a: v4i32, b: v4i32, c: v4i32) -> v4i32 { - unsafe { __lsx_vshuf_w(a, b, c) } +pub fn lsx_vshuf_w(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vshuf_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vshuf_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64 { - unsafe { __lsx_vshuf_d(a, b, c) } +pub fn lsx_vshuf_d(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vshuf_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vand_v(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vand_v(a, b) } +pub fn lsx_vand_v(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vand_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vandi_b(a: v16u8) -> v16u8 { +pub fn lsx_vandi_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vandi_b(a, IMM8) } + unsafe { transmute(__lsx_vandi_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vor_v(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vor_v(a, b) } +pub fn lsx_vor_v(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vor_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vori_b(a: v16u8) -> v16u8 { +pub fn lsx_vori_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vori_b(a, IMM8) } + unsafe { transmute(__lsx_vori_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vnor_v(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vnor_v(a, b) } +pub fn lsx_vnor_v(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vnor_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vnori_b(a: v16u8) -> v16u8 { +pub fn lsx_vnori_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vnori_b(a, IMM8) } + unsafe { transmute(__lsx_vnori_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vxor_v(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vxor_v(a, b) } +pub fn lsx_vxor_v(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vxor_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vxori_b(a: v16u8) -> v16u8 { +pub fn lsx_vxori_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vxori_b(a, IMM8) } + unsafe { transmute(__lsx_vxori_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitsel_v(a: v16u8, b: v16u8, c: v16u8) -> v16u8 { - unsafe { __lsx_vbitsel_v(a, b, c) } +pub fn lsx_vbitsel_v(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vbitsel_v(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbitseli_b(a: v16u8, b: v16u8) -> v16u8 { +pub fn lsx_vbitseli_b(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vbitseli_b(a, b, IMM8) } + unsafe { transmute(__lsx_vbitseli_b(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vshuf4i_b(a: v16i8) -> v16i8 { +pub fn lsx_vshuf4i_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vshuf4i_b(a, IMM8) } + unsafe { transmute(__lsx_vshuf4i_b(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vshuf4i_h(a: v8i16) -> v8i16 { +pub fn lsx_vshuf4i_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vshuf4i_h(a, IMM8) } + unsafe { transmute(__lsx_vshuf4i_h(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vshuf4i_w(a: v4i32) -> v4i32 { +pub fn lsx_vshuf4i_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vshuf4i_w(a, IMM8) } + unsafe { transmute(__lsx_vshuf4i_w(transmute(a), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplgr2vr_b(a: i32) -> v16i8 { - unsafe { __lsx_vreplgr2vr_b(a) } +pub fn lsx_vreplgr2vr_b(a: i32) -> m128i { + unsafe { transmute(__lsx_vreplgr2vr_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplgr2vr_h(a: i32) -> v8i16 { - unsafe { __lsx_vreplgr2vr_h(a) } +pub fn lsx_vreplgr2vr_h(a: i32) -> m128i { + unsafe { transmute(__lsx_vreplgr2vr_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplgr2vr_w(a: i32) -> v4i32 { - unsafe { __lsx_vreplgr2vr_w(a) } +pub fn lsx_vreplgr2vr_w(a: i32) -> m128i { + unsafe { transmute(__lsx_vreplgr2vr_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vreplgr2vr_d(a: i64) -> v2i64 { - unsafe { __lsx_vreplgr2vr_d(a) } +pub fn lsx_vreplgr2vr_d(a: i64) -> m128i { + unsafe { transmute(__lsx_vreplgr2vr_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpcnt_b(a: v16i8) -> v16i8 { - unsafe { __lsx_vpcnt_b(a) } +pub fn lsx_vpcnt_b(a: m128i) -> m128i { + unsafe { transmute(__lsx_vpcnt_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpcnt_h(a: v8i16) -> v8i16 { - unsafe { __lsx_vpcnt_h(a) } +pub fn lsx_vpcnt_h(a: m128i) -> m128i { + unsafe { transmute(__lsx_vpcnt_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpcnt_w(a: v4i32) -> v4i32 { - unsafe { __lsx_vpcnt_w(a) } +pub fn lsx_vpcnt_w(a: m128i) -> m128i { + unsafe { transmute(__lsx_vpcnt_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpcnt_d(a: v2i64) -> v2i64 { - unsafe { __lsx_vpcnt_d(a) } +pub fn lsx_vpcnt_d(a: m128i) -> m128i { + unsafe { transmute(__lsx_vpcnt_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vclo_b(a: v16i8) -> v16i8 { - unsafe { __lsx_vclo_b(a) } +pub fn lsx_vclo_b(a: m128i) -> m128i { + unsafe { transmute(__lsx_vclo_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vclo_h(a: v8i16) -> v8i16 { - unsafe { __lsx_vclo_h(a) } +pub fn lsx_vclo_h(a: m128i) -> m128i { + unsafe { transmute(__lsx_vclo_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vclo_w(a: v4i32) -> v4i32 { - unsafe { __lsx_vclo_w(a) } +pub fn lsx_vclo_w(a: m128i) -> m128i { + unsafe { transmute(__lsx_vclo_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vclo_d(a: v2i64) -> v2i64 { - unsafe { __lsx_vclo_d(a) } +pub fn lsx_vclo_d(a: m128i) -> m128i { + unsafe { transmute(__lsx_vclo_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vclz_b(a: v16i8) -> v16i8 { - unsafe { __lsx_vclz_b(a) } +pub fn lsx_vclz_b(a: m128i) -> m128i { + unsafe { transmute(__lsx_vclz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vclz_h(a: v8i16) -> v8i16 { - unsafe { __lsx_vclz_h(a) } +pub fn lsx_vclz_h(a: m128i) -> m128i { + unsafe { transmute(__lsx_vclz_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vclz_w(a: v4i32) -> v4i32 { - unsafe { __lsx_vclz_w(a) } +pub fn lsx_vclz_w(a: m128i) -> m128i { + unsafe { transmute(__lsx_vclz_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vclz_d(a: v2i64) -> v2i64 { - unsafe { __lsx_vclz_d(a) } +pub fn lsx_vclz_d(a: m128i) -> m128i { + unsafe { transmute(__lsx_vclz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickve2gr_b(a: v16i8) -> i32 { +pub fn lsx_vpickve2gr_b(a: m128i) -> i32 { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vpickve2gr_b(a, IMM4) } + unsafe { transmute(__lsx_vpickve2gr_b(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickve2gr_h(a: v8i16) -> i32 { +pub fn lsx_vpickve2gr_h(a: m128i) -> i32 { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vpickve2gr_h(a, IMM3) } + unsafe { transmute(__lsx_vpickve2gr_h(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickve2gr_w(a: v4i32) -> i32 { +pub fn lsx_vpickve2gr_w(a: m128i) -> i32 { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lsx_vpickve2gr_w(a, IMM2) } + unsafe { transmute(__lsx_vpickve2gr_w(transmute(a), IMM2)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickve2gr_d(a: v2i64) -> i64 { +pub fn lsx_vpickve2gr_d(a: m128i) -> i64 { static_assert_uimm_bits!(IMM1, 1); - unsafe { __lsx_vpickve2gr_d(a, IMM1) } + unsafe { transmute(__lsx_vpickve2gr_d(transmute(a), IMM1)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickve2gr_bu(a: v16i8) -> u32 { +pub fn lsx_vpickve2gr_bu(a: m128i) -> u32 { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vpickve2gr_bu(a, IMM4) } + unsafe { transmute(__lsx_vpickve2gr_bu(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickve2gr_hu(a: v8i16) -> u32 { +pub fn lsx_vpickve2gr_hu(a: m128i) -> u32 { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vpickve2gr_hu(a, IMM3) } + unsafe { transmute(__lsx_vpickve2gr_hu(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickve2gr_wu(a: v4i32) -> u32 { +pub fn lsx_vpickve2gr_wu(a: m128i) -> u32 { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lsx_vpickve2gr_wu(a, IMM2) } + unsafe { transmute(__lsx_vpickve2gr_wu(transmute(a), IMM2)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpickve2gr_du(a: v2i64) -> u64 { +pub fn lsx_vpickve2gr_du(a: m128i) -> u64 { static_assert_uimm_bits!(IMM1, 1); - unsafe { __lsx_vpickve2gr_du(a, IMM1) } + unsafe { transmute(__lsx_vpickve2gr_du(transmute(a), IMM1)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vinsgr2vr_b(a: v16i8, b: i32) -> v16i8 { +pub fn lsx_vinsgr2vr_b(a: m128i, b: i32) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vinsgr2vr_b(a, b, IMM4) } + unsafe { transmute(__lsx_vinsgr2vr_b(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vinsgr2vr_h(a: v8i16, b: i32) -> v8i16 { +pub fn lsx_vinsgr2vr_h(a: m128i, b: i32) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vinsgr2vr_h(a, b, IMM3) } + unsafe { transmute(__lsx_vinsgr2vr_h(transmute(a), transmute(b), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vinsgr2vr_w(a: v4i32, b: i32) -> v4i32 { +pub fn lsx_vinsgr2vr_w(a: m128i, b: i32) -> m128i { static_assert_uimm_bits!(IMM2, 2); - unsafe { __lsx_vinsgr2vr_w(a, b, IMM2) } + unsafe { transmute(__lsx_vinsgr2vr_w(transmute(a), transmute(b), IMM2)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vinsgr2vr_d(a: v2i64, b: i64) -> v2i64 { +pub fn lsx_vinsgr2vr_d(a: m128i, b: i64) -> m128i { static_assert_uimm_bits!(IMM1, 1); - unsafe { __lsx_vinsgr2vr_d(a, b, IMM1) } + unsafe { transmute(__lsx_vinsgr2vr_d(transmute(a), transmute(b), IMM1)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfadd_s(a: v4f32, b: v4f32) -> v4f32 { - unsafe { __lsx_vfadd_s(a, b) } +pub fn lsx_vfadd_s(a: m128, b: m128) -> m128 { + unsafe { transmute(__lsx_vfadd_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfadd_d(a: v2f64, b: v2f64) -> v2f64 { - unsafe { __lsx_vfadd_d(a, b) } +pub fn lsx_vfadd_d(a: m128d, b: m128d) -> m128d { + unsafe { transmute(__lsx_vfadd_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfsub_s(a: v4f32, b: v4f32) -> v4f32 { - unsafe { __lsx_vfsub_s(a, b) } +pub fn lsx_vfsub_s(a: m128, b: m128) -> m128 { + unsafe { transmute(__lsx_vfsub_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfsub_d(a: v2f64, b: v2f64) -> v2f64 { - unsafe { __lsx_vfsub_d(a, b) } +pub fn lsx_vfsub_d(a: m128d, b: m128d) -> m128d { + unsafe { transmute(__lsx_vfsub_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmul_s(a: v4f32, b: v4f32) -> v4f32 { - unsafe { __lsx_vfmul_s(a, b) } +pub fn lsx_vfmul_s(a: m128, b: m128) -> m128 { + unsafe { transmute(__lsx_vfmul_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmul_d(a: v2f64, b: v2f64) -> v2f64 { - unsafe { __lsx_vfmul_d(a, b) } +pub fn lsx_vfmul_d(a: m128d, b: m128d) -> m128d { + unsafe { transmute(__lsx_vfmul_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfdiv_s(a: v4f32, b: v4f32) -> v4f32 { - unsafe { __lsx_vfdiv_s(a, b) } +pub fn lsx_vfdiv_s(a: m128, b: m128) -> m128 { + unsafe { transmute(__lsx_vfdiv_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfdiv_d(a: v2f64, b: v2f64) -> v2f64 { - unsafe { __lsx_vfdiv_d(a, b) } +pub fn lsx_vfdiv_d(a: m128d, b: m128d) -> m128d { + unsafe { transmute(__lsx_vfdiv_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcvt_h_s(a: v4f32, b: v4f32) -> v8i16 { - unsafe { __lsx_vfcvt_h_s(a, b) } +pub fn lsx_vfcvt_h_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcvt_h_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcvt_s_d(a: v2f64, b: v2f64) -> v4f32 { - unsafe { __lsx_vfcvt_s_d(a, b) } +pub fn lsx_vfcvt_s_d(a: m128d, b: m128d) -> m128 { + unsafe { transmute(__lsx_vfcvt_s_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmin_s(a: v4f32, b: v4f32) -> v4f32 { - unsafe { __lsx_vfmin_s(a, b) } +pub fn lsx_vfmin_s(a: m128, b: m128) -> m128 { + unsafe { transmute(__lsx_vfmin_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmin_d(a: v2f64, b: v2f64) -> v2f64 { - unsafe { __lsx_vfmin_d(a, b) } +pub fn lsx_vfmin_d(a: m128d, b: m128d) -> m128d { + unsafe { transmute(__lsx_vfmin_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmina_s(a: v4f32, b: v4f32) -> v4f32 { - unsafe { __lsx_vfmina_s(a, b) } +pub fn lsx_vfmina_s(a: m128, b: m128) -> m128 { + unsafe { transmute(__lsx_vfmina_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmina_d(a: v2f64, b: v2f64) -> v2f64 { - unsafe { __lsx_vfmina_d(a, b) } +pub fn lsx_vfmina_d(a: m128d, b: m128d) -> m128d { + unsafe { transmute(__lsx_vfmina_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmax_s(a: v4f32, b: v4f32) -> v4f32 { - unsafe { __lsx_vfmax_s(a, b) } +pub fn lsx_vfmax_s(a: m128, b: m128) -> m128 { + unsafe { transmute(__lsx_vfmax_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmax_d(a: v2f64, b: v2f64) -> v2f64 { - unsafe { __lsx_vfmax_d(a, b) } +pub fn lsx_vfmax_d(a: m128d, b: m128d) -> m128d { + unsafe { transmute(__lsx_vfmax_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmaxa_s(a: v4f32, b: v4f32) -> v4f32 { - unsafe { __lsx_vfmaxa_s(a, b) } +pub fn lsx_vfmaxa_s(a: m128, b: m128) -> m128 { + unsafe { transmute(__lsx_vfmaxa_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmaxa_d(a: v2f64, b: v2f64) -> v2f64 { - unsafe { __lsx_vfmaxa_d(a, b) } +pub fn lsx_vfmaxa_d(a: m128d, b: m128d) -> m128d { + unsafe { transmute(__lsx_vfmaxa_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfclass_s(a: v4f32) -> v4i32 { - unsafe { __lsx_vfclass_s(a) } +pub fn lsx_vfclass_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vfclass_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfclass_d(a: v2f64) -> v2i64 { - unsafe { __lsx_vfclass_d(a) } +pub fn lsx_vfclass_d(a: m128d) -> m128i { + unsafe { transmute(__lsx_vfclass_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfsqrt_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfsqrt_s(a) } +pub fn lsx_vfsqrt_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfsqrt_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfsqrt_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfsqrt_d(a) } +pub fn lsx_vfsqrt_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfsqrt_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrecip_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrecip_s(a) } +pub fn lsx_vfrecip_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrecip_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrecip_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrecip_d(a) } +pub fn lsx_vfrecip_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrecip_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx,frecipe")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrecipe_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrecipe_s(a) } +pub fn lsx_vfrecipe_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrecipe_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx,frecipe")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrecipe_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrecipe_d(a) } +pub fn lsx_vfrecipe_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrecipe_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx,frecipe")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrsqrte_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrsqrte_s(a) } +pub fn lsx_vfrsqrte_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrsqrte_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx,frecipe")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrsqrte_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrsqrte_d(a) } +pub fn lsx_vfrsqrte_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrsqrte_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrint_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrint_s(a) } +pub fn lsx_vfrint_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrint_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrint_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrint_d(a) } +pub fn lsx_vfrint_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrint_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrsqrt_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrsqrt_s(a) } +pub fn lsx_vfrsqrt_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrsqrt_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrsqrt_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrsqrt_d(a) } +pub fn lsx_vfrsqrt_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrsqrt_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vflogb_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vflogb_s(a) } +pub fn lsx_vflogb_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vflogb_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vflogb_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vflogb_d(a) } +pub fn lsx_vflogb_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vflogb_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcvth_s_h(a: v8i16) -> v4f32 { - unsafe { __lsx_vfcvth_s_h(a) } +pub fn lsx_vfcvth_s_h(a: m128i) -> m128 { + unsafe { transmute(__lsx_vfcvth_s_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcvth_d_s(a: v4f32) -> v2f64 { - unsafe { __lsx_vfcvth_d_s(a) } +pub fn lsx_vfcvth_d_s(a: m128) -> m128d { + unsafe { transmute(__lsx_vfcvth_d_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcvtl_s_h(a: v8i16) -> v4f32 { - unsafe { __lsx_vfcvtl_s_h(a) } +pub fn lsx_vfcvtl_s_h(a: m128i) -> m128 { + unsafe { transmute(__lsx_vfcvtl_s_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcvtl_d_s(a: v4f32) -> v2f64 { - unsafe { __lsx_vfcvtl_d_s(a) } +pub fn lsx_vfcvtl_d_s(a: m128) -> m128d { + unsafe { transmute(__lsx_vfcvtl_d_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftint_w_s(a: v4f32) -> v4i32 { - unsafe { __lsx_vftint_w_s(a) } +pub fn lsx_vftint_w_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftint_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftint_l_d(a: v2f64) -> v2i64 { - unsafe { __lsx_vftint_l_d(a) } +pub fn lsx_vftint_l_d(a: m128d) -> m128i { + unsafe { transmute(__lsx_vftint_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftint_wu_s(a: v4f32) -> v4u32 { - unsafe { __lsx_vftint_wu_s(a) } +pub fn lsx_vftint_wu_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftint_wu_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftint_lu_d(a: v2f64) -> v2u64 { - unsafe { __lsx_vftint_lu_d(a) } +pub fn lsx_vftint_lu_d(a: m128d) -> m128i { + unsafe { transmute(__lsx_vftint_lu_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrz_w_s(a: v4f32) -> v4i32 { - unsafe { __lsx_vftintrz_w_s(a) } +pub fn lsx_vftintrz_w_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrz_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrz_l_d(a: v2f64) -> v2i64 { - unsafe { __lsx_vftintrz_l_d(a) } +pub fn lsx_vftintrz_l_d(a: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrz_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrz_wu_s(a: v4f32) -> v4u32 { - unsafe { __lsx_vftintrz_wu_s(a) } +pub fn lsx_vftintrz_wu_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrz_wu_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrz_lu_d(a: v2f64) -> v2u64 { - unsafe { __lsx_vftintrz_lu_d(a) } +pub fn lsx_vftintrz_lu_d(a: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrz_lu_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vffint_s_w(a: v4i32) -> v4f32 { - unsafe { __lsx_vffint_s_w(a) } +pub fn lsx_vffint_s_w(a: m128i) -> m128 { + unsafe { transmute(__lsx_vffint_s_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vffint_d_l(a: v2i64) -> v2f64 { - unsafe { __lsx_vffint_d_l(a) } +pub fn lsx_vffint_d_l(a: m128i) -> m128d { + unsafe { transmute(__lsx_vffint_d_l(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vffint_s_wu(a: v4u32) -> v4f32 { - unsafe { __lsx_vffint_s_wu(a) } +pub fn lsx_vffint_s_wu(a: m128i) -> m128 { + unsafe { transmute(__lsx_vffint_s_wu(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vffint_d_lu(a: v2u64) -> v2f64 { - unsafe { __lsx_vffint_d_lu(a) } +pub fn lsx_vffint_d_lu(a: m128i) -> m128d { + unsafe { transmute(__lsx_vffint_d_lu(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vandn_v(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vandn_v(a, b) } +pub fn lsx_vandn_v(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vandn_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vneg_b(a: v16i8) -> v16i8 { - unsafe { __lsx_vneg_b(a) } +pub fn lsx_vneg_b(a: m128i) -> m128i { + unsafe { transmute(__lsx_vneg_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vneg_h(a: v8i16) -> v8i16 { - unsafe { __lsx_vneg_h(a) } +pub fn lsx_vneg_h(a: m128i) -> m128i { + unsafe { transmute(__lsx_vneg_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vneg_w(a: v4i32) -> v4i32 { - unsafe { __lsx_vneg_w(a) } +pub fn lsx_vneg_w(a: m128i) -> m128i { + unsafe { transmute(__lsx_vneg_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vneg_d(a: v2i64) -> v2i64 { - unsafe { __lsx_vneg_d(a) } +pub fn lsx_vneg_d(a: m128i) -> m128i { + unsafe { transmute(__lsx_vneg_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmuh_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vmuh_b(a, b) } +pub fn lsx_vmuh_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmuh_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmuh_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vmuh_h(a, b) } +pub fn lsx_vmuh_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmuh_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmuh_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vmuh_w(a, b) } +pub fn lsx_vmuh_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmuh_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmuh_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmuh_d(a, b) } +pub fn lsx_vmuh_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmuh_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmuh_bu(a: v16u8, b: v16u8) -> v16u8 { - unsafe { __lsx_vmuh_bu(a, b) } +pub fn lsx_vmuh_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmuh_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmuh_hu(a: v8u16, b: v8u16) -> v8u16 { - unsafe { __lsx_vmuh_hu(a, b) } +pub fn lsx_vmuh_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmuh_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmuh_wu(a: v4u32, b: v4u32) -> v4u32 { - unsafe { __lsx_vmuh_wu(a, b) } +pub fn lsx_vmuh_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmuh_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmuh_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vmuh_du(a, b) } +pub fn lsx_vmuh_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmuh_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsllwil_h_b(a: v16i8) -> v8i16 { +pub fn lsx_vsllwil_h_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vsllwil_h_b(a, IMM3) } + unsafe { transmute(__lsx_vsllwil_h_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsllwil_w_h(a: v8i16) -> v4i32 { +pub fn lsx_vsllwil_w_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsllwil_w_h(a, IMM4) } + unsafe { transmute(__lsx_vsllwil_w_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsllwil_d_w(a: v4i32) -> v2i64 { +pub fn lsx_vsllwil_d_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsllwil_d_w(a, IMM5) } + unsafe { transmute(__lsx_vsllwil_d_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsllwil_hu_bu(a: v16u8) -> v8u16 { +pub fn lsx_vsllwil_hu_bu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vsllwil_hu_bu(a, IMM3) } + unsafe { transmute(__lsx_vsllwil_hu_bu(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsllwil_wu_hu(a: v8u16) -> v4u32 { +pub fn lsx_vsllwil_wu_hu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsllwil_wu_hu(a, IMM4) } + unsafe { transmute(__lsx_vsllwil_wu_hu(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsllwil_du_wu(a: v4u32) -> v2u64 { +pub fn lsx_vsllwil_du_wu(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsllwil_du_wu(a, IMM5) } + unsafe { transmute(__lsx_vsllwil_du_wu(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsran_b_h(a: v8i16, b: v8i16) -> v16i8 { - unsafe { __lsx_vsran_b_h(a, b) } +pub fn lsx_vsran_b_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsran_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsran_h_w(a: v4i32, b: v4i32) -> v8i16 { - unsafe { __lsx_vsran_h_w(a, b) } +pub fn lsx_vsran_h_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsran_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsran_w_d(a: v2i64, b: v2i64) -> v4i32 { - unsafe { __lsx_vsran_w_d(a, b) } +pub fn lsx_vsran_w_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsran_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssran_b_h(a: v8i16, b: v8i16) -> v16i8 { - unsafe { __lsx_vssran_b_h(a, b) } +pub fn lsx_vssran_b_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssran_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssran_h_w(a: v4i32, b: v4i32) -> v8i16 { - unsafe { __lsx_vssran_h_w(a, b) } +pub fn lsx_vssran_h_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssran_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssran_w_d(a: v2i64, b: v2i64) -> v4i32 { - unsafe { __lsx_vssran_w_d(a, b) } +pub fn lsx_vssran_w_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssran_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssran_bu_h(a: v8u16, b: v8u16) -> v16u8 { - unsafe { __lsx_vssran_bu_h(a, b) } +pub fn lsx_vssran_bu_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssran_bu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssran_hu_w(a: v4u32, b: v4u32) -> v8u16 { - unsafe { __lsx_vssran_hu_w(a, b) } +pub fn lsx_vssran_hu_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssran_hu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssran_wu_d(a: v2u64, b: v2u64) -> v4u32 { - unsafe { __lsx_vssran_wu_d(a, b) } +pub fn lsx_vssran_wu_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssran_wu_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrarn_b_h(a: v8i16, b: v8i16) -> v16i8 { - unsafe { __lsx_vsrarn_b_h(a, b) } +pub fn lsx_vsrarn_b_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrarn_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrarn_h_w(a: v4i32, b: v4i32) -> v8i16 { - unsafe { __lsx_vsrarn_h_w(a, b) } +pub fn lsx_vsrarn_h_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrarn_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrarn_w_d(a: v2i64, b: v2i64) -> v4i32 { - unsafe { __lsx_vsrarn_w_d(a, b) } +pub fn lsx_vsrarn_w_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrarn_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarn_b_h(a: v8i16, b: v8i16) -> v16i8 { - unsafe { __lsx_vssrarn_b_h(a, b) } +pub fn lsx_vssrarn_b_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrarn_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarn_h_w(a: v4i32, b: v4i32) -> v8i16 { - unsafe { __lsx_vssrarn_h_w(a, b) } +pub fn lsx_vssrarn_h_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrarn_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarn_w_d(a: v2i64, b: v2i64) -> v4i32 { - unsafe { __lsx_vssrarn_w_d(a, b) } +pub fn lsx_vssrarn_w_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrarn_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarn_bu_h(a: v8u16, b: v8u16) -> v16u8 { - unsafe { __lsx_vssrarn_bu_h(a, b) } +pub fn lsx_vssrarn_bu_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrarn_bu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarn_hu_w(a: v4u32, b: v4u32) -> v8u16 { - unsafe { __lsx_vssrarn_hu_w(a, b) } +pub fn lsx_vssrarn_hu_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrarn_hu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarn_wu_d(a: v2u64, b: v2u64) -> v4u32 { - unsafe { __lsx_vssrarn_wu_d(a, b) } +pub fn lsx_vssrarn_wu_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrarn_wu_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrln_b_h(a: v8i16, b: v8i16) -> v16i8 { - unsafe { __lsx_vsrln_b_h(a, b) } +pub fn lsx_vsrln_b_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrln_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrln_h_w(a: v4i32, b: v4i32) -> v8i16 { - unsafe { __lsx_vsrln_h_w(a, b) } +pub fn lsx_vsrln_h_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrln_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrln_w_d(a: v2i64, b: v2i64) -> v4i32 { - unsafe { __lsx_vsrln_w_d(a, b) } +pub fn lsx_vsrln_w_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrln_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrln_bu_h(a: v8u16, b: v8u16) -> v16u8 { - unsafe { __lsx_vssrln_bu_h(a, b) } +pub fn lsx_vssrln_bu_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrln_bu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrln_hu_w(a: v4u32, b: v4u32) -> v8u16 { - unsafe { __lsx_vssrln_hu_w(a, b) } +pub fn lsx_vssrln_hu_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrln_hu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrln_wu_d(a: v2u64, b: v2u64) -> v4u32 { - unsafe { __lsx_vssrln_wu_d(a, b) } +pub fn lsx_vssrln_wu_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrln_wu_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlrn_b_h(a: v8i16, b: v8i16) -> v16i8 { - unsafe { __lsx_vsrlrn_b_h(a, b) } +pub fn lsx_vsrlrn_b_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrlrn_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlrn_h_w(a: v4i32, b: v4i32) -> v8i16 { - unsafe { __lsx_vsrlrn_h_w(a, b) } +pub fn lsx_vsrlrn_h_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrlrn_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlrn_w_d(a: v2i64, b: v2i64) -> v4i32 { - unsafe { __lsx_vsrlrn_w_d(a, b) } +pub fn lsx_vsrlrn_w_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsrlrn_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrn_bu_h(a: v8u16, b: v8u16) -> v16u8 { - unsafe { __lsx_vssrlrn_bu_h(a, b) } +pub fn lsx_vssrlrn_bu_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrlrn_bu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrn_hu_w(a: v4u32, b: v4u32) -> v8u16 { - unsafe { __lsx_vssrlrn_hu_w(a, b) } +pub fn lsx_vssrlrn_hu_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrlrn_hu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrn_wu_d(a: v2u64, b: v2u64) -> v4u32 { - unsafe { __lsx_vssrlrn_wu_d(a, b) } +pub fn lsx_vssrlrn_wu_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrlrn_wu_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrstpi_b(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vfrstpi_b(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vfrstpi_b(a, b, IMM5) } + unsafe { transmute(__lsx_vfrstpi_b(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrstpi_h(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vfrstpi_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vfrstpi_h(a, b, IMM5) } + unsafe { transmute(__lsx_vfrstpi_h(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrstp_b(a: v16i8, b: v16i8, c: v16i8) -> v16i8 { - unsafe { __lsx_vfrstp_b(a, b, c) } +pub fn lsx_vfrstp_b(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vfrstp_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrstp_h(a: v8i16, b: v8i16, c: v8i16) -> v8i16 { - unsafe { __lsx_vfrstp_h(a, b, c) } +pub fn lsx_vfrstp_h(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vfrstp_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vshuf4i_d(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vshuf4i_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vshuf4i_d(a, b, IMM8) } + unsafe { transmute(__lsx_vshuf4i_d(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbsrl_v(a: v16i8) -> v16i8 { +pub fn lsx_vbsrl_v(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vbsrl_v(a, IMM5) } + unsafe { transmute(__lsx_vbsrl_v(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vbsll_v(a: v16i8) -> v16i8 { +pub fn lsx_vbsll_v(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vbsll_v(a, IMM5) } + unsafe { transmute(__lsx_vbsll_v(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vextrins_b(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vextrins_b(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vextrins_b(a, b, IMM8) } + unsafe { transmute(__lsx_vextrins_b(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vextrins_h(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vextrins_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vextrins_h(a, b, IMM8) } + unsafe { transmute(__lsx_vextrins_h(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vextrins_w(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vextrins_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vextrins_w(a, b, IMM8) } + unsafe { transmute(__lsx_vextrins_w(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vextrins_d(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vextrins_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vextrins_d(a, b, IMM8) } + unsafe { transmute(__lsx_vextrins_d(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmskltz_b(a: v16i8) -> v16i8 { - unsafe { __lsx_vmskltz_b(a) } +pub fn lsx_vmskltz_b(a: m128i) -> m128i { + unsafe { transmute(__lsx_vmskltz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmskltz_h(a: v8i16) -> v8i16 { - unsafe { __lsx_vmskltz_h(a) } +pub fn lsx_vmskltz_h(a: m128i) -> m128i { + unsafe { transmute(__lsx_vmskltz_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmskltz_w(a: v4i32) -> v4i32 { - unsafe { __lsx_vmskltz_w(a) } +pub fn lsx_vmskltz_w(a: m128i) -> m128i { + unsafe { transmute(__lsx_vmskltz_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmskltz_d(a: v2i64) -> v2i64 { - unsafe { __lsx_vmskltz_d(a) } +pub fn lsx_vmskltz_d(a: m128i) -> m128i { + unsafe { transmute(__lsx_vmskltz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsigncov_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vsigncov_b(a, b) } +pub fn lsx_vsigncov_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsigncov_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsigncov_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vsigncov_h(a, b) } +pub fn lsx_vsigncov_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsigncov_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsigncov_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vsigncov_w(a, b) } +pub fn lsx_vsigncov_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsigncov_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsigncov_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsigncov_d(a, b) } +pub fn lsx_vsigncov_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsigncov_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmadd_s(a: v4f32, b: v4f32, c: v4f32) -> v4f32 { - unsafe { __lsx_vfmadd_s(a, b, c) } +pub fn lsx_vfmadd_s(a: m128, b: m128, c: m128) -> m128 { + unsafe { transmute(__lsx_vfmadd_s(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmadd_d(a: v2f64, b: v2f64, c: v2f64) -> v2f64 { - unsafe { __lsx_vfmadd_d(a, b, c) } +pub fn lsx_vfmadd_d(a: m128d, b: m128d, c: m128d) -> m128d { + unsafe { transmute(__lsx_vfmadd_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmsub_s(a: v4f32, b: v4f32, c: v4f32) -> v4f32 { - unsafe { __lsx_vfmsub_s(a, b, c) } +pub fn lsx_vfmsub_s(a: m128, b: m128, c: m128) -> m128 { + unsafe { transmute(__lsx_vfmsub_s(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfmsub_d(a: v2f64, b: v2f64, c: v2f64) -> v2f64 { - unsafe { __lsx_vfmsub_d(a, b, c) } +pub fn lsx_vfmsub_d(a: m128d, b: m128d, c: m128d) -> m128d { + unsafe { transmute(__lsx_vfmsub_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfnmadd_s(a: v4f32, b: v4f32, c: v4f32) -> v4f32 { - unsafe { __lsx_vfnmadd_s(a, b, c) } +pub fn lsx_vfnmadd_s(a: m128, b: m128, c: m128) -> m128 { + unsafe { transmute(__lsx_vfnmadd_s(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfnmadd_d(a: v2f64, b: v2f64, c: v2f64) -> v2f64 { - unsafe { __lsx_vfnmadd_d(a, b, c) } +pub fn lsx_vfnmadd_d(a: m128d, b: m128d, c: m128d) -> m128d { + unsafe { transmute(__lsx_vfnmadd_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfnmsub_s(a: v4f32, b: v4f32, c: v4f32) -> v4f32 { - unsafe { __lsx_vfnmsub_s(a, b, c) } +pub fn lsx_vfnmsub_s(a: m128, b: m128, c: m128) -> m128 { + unsafe { transmute(__lsx_vfnmsub_s(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfnmsub_d(a: v2f64, b: v2f64, c: v2f64) -> v2f64 { - unsafe { __lsx_vfnmsub_d(a, b, c) } +pub fn lsx_vfnmsub_d(a: m128d, b: m128d, c: m128d) -> m128d { + unsafe { transmute(__lsx_vfnmsub_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrne_w_s(a: v4f32) -> v4i32 { - unsafe { __lsx_vftintrne_w_s(a) } +pub fn lsx_vftintrne_w_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrne_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrne_l_d(a: v2f64) -> v2i64 { - unsafe { __lsx_vftintrne_l_d(a) } +pub fn lsx_vftintrne_l_d(a: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrne_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrp_w_s(a: v4f32) -> v4i32 { - unsafe { __lsx_vftintrp_w_s(a) } +pub fn lsx_vftintrp_w_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrp_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrp_l_d(a: v2f64) -> v2i64 { - unsafe { __lsx_vftintrp_l_d(a) } +pub fn lsx_vftintrp_l_d(a: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrp_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrm_w_s(a: v4f32) -> v4i32 { - unsafe { __lsx_vftintrm_w_s(a) } +pub fn lsx_vftintrm_w_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrm_w_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrm_l_d(a: v2f64) -> v2i64 { - unsafe { __lsx_vftintrm_l_d(a) } +pub fn lsx_vftintrm_l_d(a: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrm_l_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftint_w_d(a: v2f64, b: v2f64) -> v4i32 { - unsafe { __lsx_vftint_w_d(a, b) } +pub fn lsx_vftint_w_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vftint_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vffint_s_l(a: v2i64, b: v2i64) -> v4f32 { - unsafe { __lsx_vffint_s_l(a, b) } +pub fn lsx_vffint_s_l(a: m128i, b: m128i) -> m128 { + unsafe { transmute(__lsx_vffint_s_l(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrz_w_d(a: v2f64, b: v2f64) -> v4i32 { - unsafe { __lsx_vftintrz_w_d(a, b) } +pub fn lsx_vftintrz_w_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrz_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrp_w_d(a: v2f64, b: v2f64) -> v4i32 { - unsafe { __lsx_vftintrp_w_d(a, b) } +pub fn lsx_vftintrp_w_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrp_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrm_w_d(a: v2f64, b: v2f64) -> v4i32 { - unsafe { __lsx_vftintrm_w_d(a, b) } +pub fn lsx_vftintrm_w_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrm_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrne_w_d(a: v2f64, b: v2f64) -> v4i32 { - unsafe { __lsx_vftintrne_w_d(a, b) } +pub fn lsx_vftintrne_w_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vftintrne_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintl_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintl_l_s(a) } +pub fn lsx_vftintl_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintl_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftinth_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftinth_l_s(a) } +pub fn lsx_vftinth_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftinth_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vffinth_d_w(a: v4i32) -> v2f64 { - unsafe { __lsx_vffinth_d_w(a) } +pub fn lsx_vffinth_d_w(a: m128i) -> m128d { + unsafe { transmute(__lsx_vffinth_d_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vffintl_d_w(a: v4i32) -> v2f64 { - unsafe { __lsx_vffintl_d_w(a) } +pub fn lsx_vffintl_d_w(a: m128i) -> m128d { + unsafe { transmute(__lsx_vffintl_d_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrzl_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintrzl_l_s(a) } +pub fn lsx_vftintrzl_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrzl_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrzh_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintrzh_l_s(a) } +pub fn lsx_vftintrzh_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrzh_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrpl_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintrpl_l_s(a) } +pub fn lsx_vftintrpl_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrpl_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrph_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintrph_l_s(a) } +pub fn lsx_vftintrph_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrph_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrml_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintrml_l_s(a) } +pub fn lsx_vftintrml_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrml_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrmh_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintrmh_l_s(a) } +pub fn lsx_vftintrmh_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrmh_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrnel_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintrnel_l_s(a) } +pub fn lsx_vftintrnel_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrnel_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vftintrneh_l_s(a: v4f32) -> v2i64 { - unsafe { __lsx_vftintrneh_l_s(a) } +pub fn lsx_vftintrneh_l_s(a: m128) -> m128i { + unsafe { transmute(__lsx_vftintrneh_l_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrintrne_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrintrne_s(a) } +pub fn lsx_vfrintrne_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrintrne_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrintrne_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrintrne_d(a) } +pub fn lsx_vfrintrne_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrintrne_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrintrz_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrintrz_s(a) } +pub fn lsx_vfrintrz_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrintrz_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrintrz_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrintrz_d(a) } +pub fn lsx_vfrintrz_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrintrz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrintrp_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrintrp_s(a) } +pub fn lsx_vfrintrp_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrintrp_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrintrp_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrintrp_d(a) } +pub fn lsx_vfrintrp_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrintrp_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrintrm_s(a: v4f32) -> v4f32 { - unsafe { __lsx_vfrintrm_s(a) } +pub fn lsx_vfrintrm_s(a: m128) -> m128 { + unsafe { transmute(__lsx_vfrintrm_s(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfrintrm_d(a: v2f64) -> v2f64 { - unsafe { __lsx_vfrintrm_d(a) } +pub fn lsx_vfrintrm_d(a: m128d) -> m128d { + unsafe { transmute(__lsx_vfrintrm_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2, 3)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vstelm_b(a: v16i8, mem_addr: *mut i8) { +pub unsafe fn lsx_vstelm_b(a: m128i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S8, 8); static_assert_uimm_bits!(IMM4, 4); - __lsx_vstelm_b(a, mem_addr, IMM_S8, IMM4) + transmute(__lsx_vstelm_b(transmute(a), mem_addr, IMM_S8, IMM4)) } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2, 3)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vstelm_h(a: v8i16, mem_addr: *mut i8) { +pub unsafe fn lsx_vstelm_h(a: m128i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S8, 8); static_assert_uimm_bits!(IMM3, 3); - __lsx_vstelm_h(a, mem_addr, IMM_S8, IMM3) + transmute(__lsx_vstelm_h(transmute(a), mem_addr, IMM_S8, IMM3)) } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2, 3)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vstelm_w(a: v4i32, mem_addr: *mut i8) { +pub unsafe fn lsx_vstelm_w(a: m128i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S8, 8); static_assert_uimm_bits!(IMM2, 2); - __lsx_vstelm_w(a, mem_addr, IMM_S8, IMM2) + transmute(__lsx_vstelm_w(transmute(a), mem_addr, IMM_S8, IMM2)) } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2, 3)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vstelm_d(a: v2i64, mem_addr: *mut i8) { +pub unsafe fn lsx_vstelm_d(a: m128i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S8, 8); static_assert_uimm_bits!(IMM1, 1); - __lsx_vstelm_d(a, mem_addr, IMM_S8, IMM1) + transmute(__lsx_vstelm_d(transmute(a), mem_addr, IMM_S8, IMM1)) } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_d_w(a: v4i32, b: v4i32) -> v2i64 { - unsafe { __lsx_vaddwev_d_w(a, b) } +pub fn lsx_vaddwev_d_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_w_h(a: v8i16, b: v8i16) -> v4i32 { - unsafe { __lsx_vaddwev_w_h(a, b) } +pub fn lsx_vaddwev_w_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_h_b(a: v16i8, b: v16i8) -> v8i16 { - unsafe { __lsx_vaddwev_h_b(a, b) } +pub fn lsx_vaddwev_h_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_d_w(a: v4i32, b: v4i32) -> v2i64 { - unsafe { __lsx_vaddwod_d_w(a, b) } +pub fn lsx_vaddwod_d_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_w_h(a: v8i16, b: v8i16) -> v4i32 { - unsafe { __lsx_vaddwod_w_h(a, b) } +pub fn lsx_vaddwod_w_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_h_b(a: v16i8, b: v16i8) -> v8i16 { - unsafe { __lsx_vaddwod_h_b(a, b) } +pub fn lsx_vaddwod_h_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_d_wu(a: v4u32, b: v4u32) -> v2i64 { - unsafe { __lsx_vaddwev_d_wu(a, b) } +pub fn lsx_vaddwev_d_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_w_hu(a: v8u16, b: v8u16) -> v4i32 { - unsafe { __lsx_vaddwev_w_hu(a, b) } +pub fn lsx_vaddwev_w_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_h_bu(a: v16u8, b: v16u8) -> v8i16 { - unsafe { __lsx_vaddwev_h_bu(a, b) } +pub fn lsx_vaddwev_h_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_d_wu(a: v4u32, b: v4u32) -> v2i64 { - unsafe { __lsx_vaddwod_d_wu(a, b) } +pub fn lsx_vaddwod_d_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_w_hu(a: v8u16, b: v8u16) -> v4i32 { - unsafe { __lsx_vaddwod_w_hu(a, b) } +pub fn lsx_vaddwod_w_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_h_bu(a: v16u8, b: v16u8) -> v8i16 { - unsafe { __lsx_vaddwod_h_bu(a, b) } +pub fn lsx_vaddwod_h_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_d_wu_w(a: v4u32, b: v4i32) -> v2i64 { - unsafe { __lsx_vaddwev_d_wu_w(a, b) } +pub fn lsx_vaddwev_d_wu_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_d_wu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_w_hu_h(a: v8u16, b: v8i16) -> v4i32 { - unsafe { __lsx_vaddwev_w_hu_h(a, b) } +pub fn lsx_vaddwev_w_hu_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_w_hu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_h_bu_b(a: v16u8, b: v16i8) -> v8i16 { - unsafe { __lsx_vaddwev_h_bu_b(a, b) } +pub fn lsx_vaddwev_h_bu_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_h_bu_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_d_wu_w(a: v4u32, b: v4i32) -> v2i64 { - unsafe { __lsx_vaddwod_d_wu_w(a, b) } +pub fn lsx_vaddwod_d_wu_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_d_wu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_w_hu_h(a: v8u16, b: v8i16) -> v4i32 { - unsafe { __lsx_vaddwod_w_hu_h(a, b) } +pub fn lsx_vaddwod_w_hu_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_w_hu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_h_bu_b(a: v16u8, b: v16i8) -> v8i16 { - unsafe { __lsx_vaddwod_h_bu_b(a, b) } +pub fn lsx_vaddwod_h_bu_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_h_bu_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwev_d_w(a: v4i32, b: v4i32) -> v2i64 { - unsafe { __lsx_vsubwev_d_w(a, b) } +pub fn lsx_vsubwev_d_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwev_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwev_w_h(a: v8i16, b: v8i16) -> v4i32 { - unsafe { __lsx_vsubwev_w_h(a, b) } +pub fn lsx_vsubwev_w_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwev_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwev_h_b(a: v16i8, b: v16i8) -> v8i16 { - unsafe { __lsx_vsubwev_h_b(a, b) } +pub fn lsx_vsubwev_h_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwev_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwod_d_w(a: v4i32, b: v4i32) -> v2i64 { - unsafe { __lsx_vsubwod_d_w(a, b) } +pub fn lsx_vsubwod_d_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwod_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwod_w_h(a: v8i16, b: v8i16) -> v4i32 { - unsafe { __lsx_vsubwod_w_h(a, b) } +pub fn lsx_vsubwod_w_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwod_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwod_h_b(a: v16i8, b: v16i8) -> v8i16 { - unsafe { __lsx_vsubwod_h_b(a, b) } +pub fn lsx_vsubwod_h_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwod_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwev_d_wu(a: v4u32, b: v4u32) -> v2i64 { - unsafe { __lsx_vsubwev_d_wu(a, b) } +pub fn lsx_vsubwev_d_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwev_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwev_w_hu(a: v8u16, b: v8u16) -> v4i32 { - unsafe { __lsx_vsubwev_w_hu(a, b) } +pub fn lsx_vsubwev_w_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwev_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwev_h_bu(a: v16u8, b: v16u8) -> v8i16 { - unsafe { __lsx_vsubwev_h_bu(a, b) } +pub fn lsx_vsubwev_h_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwev_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwod_d_wu(a: v4u32, b: v4u32) -> v2i64 { - unsafe { __lsx_vsubwod_d_wu(a, b) } +pub fn lsx_vsubwod_d_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwod_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwod_w_hu(a: v8u16, b: v8u16) -> v4i32 { - unsafe { __lsx_vsubwod_w_hu(a, b) } +pub fn lsx_vsubwod_w_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwod_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwod_h_bu(a: v16u8, b: v16u8) -> v8i16 { - unsafe { __lsx_vsubwod_h_bu(a, b) } +pub fn lsx_vsubwod_h_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwod_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_q_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vaddwev_q_d(a, b) } +pub fn lsx_vaddwev_q_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_q_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vaddwod_q_d(a, b) } +pub fn lsx_vaddwod_q_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_q_du(a: v2u64, b: v2u64) -> v2i64 { - unsafe { __lsx_vaddwev_q_du(a, b) } +pub fn lsx_vaddwev_q_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_q_du(a: v2u64, b: v2u64) -> v2i64 { - unsafe { __lsx_vaddwod_q_du(a, b) } +pub fn lsx_vaddwod_q_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwev_q_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsubwev_q_d(a, b) } +pub fn lsx_vsubwev_q_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwev_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwod_q_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsubwod_q_d(a, b) } +pub fn lsx_vsubwod_q_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwod_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwev_q_du(a: v2u64, b: v2u64) -> v2i64 { - unsafe { __lsx_vsubwev_q_du(a, b) } +pub fn lsx_vsubwev_q_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwev_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsubwod_q_du(a: v2u64, b: v2u64) -> v2i64 { - unsafe { __lsx_vsubwod_q_du(a, b) } +pub fn lsx_vsubwod_q_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsubwod_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwev_q_du_d(a: v2u64, b: v2i64) -> v2i64 { - unsafe { __lsx_vaddwev_q_du_d(a, b) } +pub fn lsx_vaddwev_q_du_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwev_q_du_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vaddwod_q_du_d(a: v2u64, b: v2i64) -> v2i64 { - unsafe { __lsx_vaddwod_q_du_d(a, b) } +pub fn lsx_vaddwod_q_du_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vaddwod_q_du_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_d_w(a: v4i32, b: v4i32) -> v2i64 { - unsafe { __lsx_vmulwev_d_w(a, b) } +pub fn lsx_vmulwev_d_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_w_h(a: v8i16, b: v8i16) -> v4i32 { - unsafe { __lsx_vmulwev_w_h(a, b) } +pub fn lsx_vmulwev_w_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_h_b(a: v16i8, b: v16i8) -> v8i16 { - unsafe { __lsx_vmulwev_h_b(a, b) } +pub fn lsx_vmulwev_h_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_d_w(a: v4i32, b: v4i32) -> v2i64 { - unsafe { __lsx_vmulwod_d_w(a, b) } +pub fn lsx_vmulwod_d_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_d_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_w_h(a: v8i16, b: v8i16) -> v4i32 { - unsafe { __lsx_vmulwod_w_h(a, b) } +pub fn lsx_vmulwod_w_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_w_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_h_b(a: v16i8, b: v16i8) -> v8i16 { - unsafe { __lsx_vmulwod_h_b(a, b) } +pub fn lsx_vmulwod_h_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_h_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_d_wu(a: v4u32, b: v4u32) -> v2i64 { - unsafe { __lsx_vmulwev_d_wu(a, b) } +pub fn lsx_vmulwev_d_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_w_hu(a: v8u16, b: v8u16) -> v4i32 { - unsafe { __lsx_vmulwev_w_hu(a, b) } +pub fn lsx_vmulwev_w_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_h_bu(a: v16u8, b: v16u8) -> v8i16 { - unsafe { __lsx_vmulwev_h_bu(a, b) } +pub fn lsx_vmulwev_h_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_d_wu(a: v4u32, b: v4u32) -> v2i64 { - unsafe { __lsx_vmulwod_d_wu(a, b) } +pub fn lsx_vmulwod_d_wu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_d_wu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_w_hu(a: v8u16, b: v8u16) -> v4i32 { - unsafe { __lsx_vmulwod_w_hu(a, b) } +pub fn lsx_vmulwod_w_hu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_w_hu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_h_bu(a: v16u8, b: v16u8) -> v8i16 { - unsafe { __lsx_vmulwod_h_bu(a, b) } +pub fn lsx_vmulwod_h_bu(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_h_bu(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_d_wu_w(a: v4u32, b: v4i32) -> v2i64 { - unsafe { __lsx_vmulwev_d_wu_w(a, b) } +pub fn lsx_vmulwev_d_wu_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_d_wu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_w_hu_h(a: v8u16, b: v8i16) -> v4i32 { - unsafe { __lsx_vmulwev_w_hu_h(a, b) } +pub fn lsx_vmulwev_w_hu_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_w_hu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_h_bu_b(a: v16u8, b: v16i8) -> v8i16 { - unsafe { __lsx_vmulwev_h_bu_b(a, b) } +pub fn lsx_vmulwev_h_bu_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_h_bu_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_d_wu_w(a: v4u32, b: v4i32) -> v2i64 { - unsafe { __lsx_vmulwod_d_wu_w(a, b) } +pub fn lsx_vmulwod_d_wu_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_d_wu_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_w_hu_h(a: v8u16, b: v8i16) -> v4i32 { - unsafe { __lsx_vmulwod_w_hu_h(a, b) } +pub fn lsx_vmulwod_w_hu_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_w_hu_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_h_bu_b(a: v16u8, b: v16i8) -> v8i16 { - unsafe { __lsx_vmulwod_h_bu_b(a, b) } +pub fn lsx_vmulwod_h_bu_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_h_bu_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_q_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmulwev_q_d(a, b) } +pub fn lsx_vmulwev_q_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_q_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmulwod_q_d(a, b) } +pub fn lsx_vmulwod_q_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_q_du(a: v2u64, b: v2u64) -> v2i64 { - unsafe { __lsx_vmulwev_q_du(a, b) } +pub fn lsx_vmulwev_q_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_q_du(a: v2u64, b: v2u64) -> v2i64 { - unsafe { __lsx_vmulwod_q_du(a, b) } +pub fn lsx_vmulwod_q_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_q_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwev_q_du_d(a: v2u64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmulwev_q_du_d(a, b) } +pub fn lsx_vmulwev_q_du_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwev_q_du_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmulwod_q_du_d(a: v2u64, b: v2i64) -> v2i64 { - unsafe { __lsx_vmulwod_q_du_d(a, b) } +pub fn lsx_vmulwod_q_du_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vmulwod_q_du_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhaddw_q_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vhaddw_q_d(a, b) } +pub fn lsx_vhaddw_q_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhaddw_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhaddw_qu_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vhaddw_qu_du(a, b) } +pub fn lsx_vhaddw_qu_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhaddw_qu_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhsubw_q_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vhsubw_q_d(a, b) } +pub fn lsx_vhsubw_q_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhsubw_q_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vhsubw_qu_du(a: v2u64, b: v2u64) -> v2u64 { - unsafe { __lsx_vhsubw_qu_du(a, b) } +pub fn lsx_vhsubw_qu_du(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vhsubw_qu_du(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_d_w(a: v2i64, b: v4i32, c: v4i32) -> v2i64 { - unsafe { __lsx_vmaddwev_d_w(a, b, c) } +pub fn lsx_vmaddwev_d_w(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_d_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_w_h(a: v4i32, b: v8i16, c: v8i16) -> v4i32 { - unsafe { __lsx_vmaddwev_w_h(a, b, c) } +pub fn lsx_vmaddwev_w_h(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_w_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_h_b(a: v8i16, b: v16i8, c: v16i8) -> v8i16 { - unsafe { __lsx_vmaddwev_h_b(a, b, c) } +pub fn lsx_vmaddwev_h_b(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_h_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_d_wu(a: v2u64, b: v4u32, c: v4u32) -> v2u64 { - unsafe { __lsx_vmaddwev_d_wu(a, b, c) } +pub fn lsx_vmaddwev_d_wu(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_d_wu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_w_hu(a: v4u32, b: v8u16, c: v8u16) -> v4u32 { - unsafe { __lsx_vmaddwev_w_hu(a, b, c) } +pub fn lsx_vmaddwev_w_hu(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_w_hu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_h_bu(a: v8u16, b: v16u8, c: v16u8) -> v8u16 { - unsafe { __lsx_vmaddwev_h_bu(a, b, c) } +pub fn lsx_vmaddwev_h_bu(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_h_bu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_d_w(a: v2i64, b: v4i32, c: v4i32) -> v2i64 { - unsafe { __lsx_vmaddwod_d_w(a, b, c) } +pub fn lsx_vmaddwod_d_w(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_d_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_w_h(a: v4i32, b: v8i16, c: v8i16) -> v4i32 { - unsafe { __lsx_vmaddwod_w_h(a, b, c) } +pub fn lsx_vmaddwod_w_h(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_w_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_h_b(a: v8i16, b: v16i8, c: v16i8) -> v8i16 { - unsafe { __lsx_vmaddwod_h_b(a, b, c) } +pub fn lsx_vmaddwod_h_b(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_h_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_d_wu(a: v2u64, b: v4u32, c: v4u32) -> v2u64 { - unsafe { __lsx_vmaddwod_d_wu(a, b, c) } +pub fn lsx_vmaddwod_d_wu(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_d_wu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_w_hu(a: v4u32, b: v8u16, c: v8u16) -> v4u32 { - unsafe { __lsx_vmaddwod_w_hu(a, b, c) } +pub fn lsx_vmaddwod_w_hu(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_w_hu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_h_bu(a: v8u16, b: v16u8, c: v16u8) -> v8u16 { - unsafe { __lsx_vmaddwod_h_bu(a, b, c) } +pub fn lsx_vmaddwod_h_bu(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_h_bu(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_d_wu_w(a: v2i64, b: v4u32, c: v4i32) -> v2i64 { - unsafe { __lsx_vmaddwev_d_wu_w(a, b, c) } +pub fn lsx_vmaddwev_d_wu_w(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_d_wu_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_w_hu_h(a: v4i32, b: v8u16, c: v8i16) -> v4i32 { - unsafe { __lsx_vmaddwev_w_hu_h(a, b, c) } +pub fn lsx_vmaddwev_w_hu_h(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_w_hu_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_h_bu_b(a: v8i16, b: v16u8, c: v16i8) -> v8i16 { - unsafe { __lsx_vmaddwev_h_bu_b(a, b, c) } +pub fn lsx_vmaddwev_h_bu_b(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_h_bu_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_d_wu_w(a: v2i64, b: v4u32, c: v4i32) -> v2i64 { - unsafe { __lsx_vmaddwod_d_wu_w(a, b, c) } +pub fn lsx_vmaddwod_d_wu_w(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_d_wu_w(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_w_hu_h(a: v4i32, b: v8u16, c: v8i16) -> v4i32 { - unsafe { __lsx_vmaddwod_w_hu_h(a, b, c) } +pub fn lsx_vmaddwod_w_hu_h(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_w_hu_h(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_h_bu_b(a: v8i16, b: v16u8, c: v16i8) -> v8i16 { - unsafe { __lsx_vmaddwod_h_bu_b(a, b, c) } +pub fn lsx_vmaddwod_h_bu_b(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_h_bu_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_q_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64 { - unsafe { __lsx_vmaddwev_q_d(a, b, c) } +pub fn lsx_vmaddwev_q_d(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_q_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_q_d(a: v2i64, b: v2i64, c: v2i64) -> v2i64 { - unsafe { __lsx_vmaddwod_q_d(a, b, c) } +pub fn lsx_vmaddwod_q_d(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_q_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_q_du(a: v2u64, b: v2u64, c: v2u64) -> v2u64 { - unsafe { __lsx_vmaddwev_q_du(a, b, c) } +pub fn lsx_vmaddwev_q_du(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_q_du(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_q_du(a: v2u64, b: v2u64, c: v2u64) -> v2u64 { - unsafe { __lsx_vmaddwod_q_du(a, b, c) } +pub fn lsx_vmaddwod_q_du(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_q_du(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwev_q_du_d(a: v2i64, b: v2u64, c: v2i64) -> v2i64 { - unsafe { __lsx_vmaddwev_q_du_d(a, b, c) } +pub fn lsx_vmaddwev_q_du_d(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwev_q_du_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmaddwod_q_du_d(a: v2i64, b: v2u64, c: v2i64) -> v2i64 { - unsafe { __lsx_vmaddwod_q_du_d(a, b, c) } +pub fn lsx_vmaddwod_q_du_d(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vmaddwod_q_du_d(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrotr_b(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vrotr_b(a, b) } +pub fn lsx_vrotr_b(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vrotr_b(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrotr_h(a: v8i16, b: v8i16) -> v8i16 { - unsafe { __lsx_vrotr_h(a, b) } +pub fn lsx_vrotr_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vrotr_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrotr_w(a: v4i32, b: v4i32) -> v4i32 { - unsafe { __lsx_vrotr_w(a, b) } +pub fn lsx_vrotr_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vrotr_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrotr_d(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vrotr_d(a, b) } +pub fn lsx_vrotr_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vrotr_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vadd_q(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vadd_q(a, b) } +pub fn lsx_vadd_q(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vadd_q(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsub_q(a: v2i64, b: v2i64) -> v2i64 { - unsafe { __lsx_vsub_q(a, b) } +pub fn lsx_vsub_q(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vsub_q(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vldrepl_b(mem_addr: *const i8) -> v16i8 { +pub unsafe fn lsx_vldrepl_b(mem_addr: *const i8) -> m128i { static_assert_simm_bits!(IMM_S12, 12); - __lsx_vldrepl_b(mem_addr, IMM_S12) + transmute(__lsx_vldrepl_b(mem_addr, IMM_S12)) } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vldrepl_h(mem_addr: *const i8) -> v8i16 { +pub unsafe fn lsx_vldrepl_h(mem_addr: *const i8) -> m128i { static_assert_simm_bits!(IMM_S11, 11); - __lsx_vldrepl_h(mem_addr, IMM_S11) + transmute(__lsx_vldrepl_h(mem_addr, IMM_S11)) } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vldrepl_w(mem_addr: *const i8) -> v4i32 { +pub unsafe fn lsx_vldrepl_w(mem_addr: *const i8) -> m128i { static_assert_simm_bits!(IMM_S10, 10); - __lsx_vldrepl_w(mem_addr, IMM_S10) + transmute(__lsx_vldrepl_w(mem_addr, IMM_S10)) } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vldrepl_d(mem_addr: *const i8) -> v2i64 { +pub unsafe fn lsx_vldrepl_d(mem_addr: *const i8) -> m128i { static_assert_simm_bits!(IMM_S9, 9); - __lsx_vldrepl_d(mem_addr, IMM_S9) + transmute(__lsx_vldrepl_d(mem_addr, IMM_S9)) } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmskgez_b(a: v16i8) -> v16i8 { - unsafe { __lsx_vmskgez_b(a) } +pub fn lsx_vmskgez_b(a: m128i) -> m128i { + unsafe { transmute(__lsx_vmskgez_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vmsknz_b(a: v16i8) -> v16i8 { - unsafe { __lsx_vmsknz_b(a) } +pub fn lsx_vmsknz_b(a: m128i) -> m128i { + unsafe { transmute(__lsx_vmsknz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vexth_h_b(a: v16i8) -> v8i16 { - unsafe { __lsx_vexth_h_b(a) } +pub fn lsx_vexth_h_b(a: m128i) -> m128i { + unsafe { transmute(__lsx_vexth_h_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vexth_w_h(a: v8i16) -> v4i32 { - unsafe { __lsx_vexth_w_h(a) } +pub fn lsx_vexth_w_h(a: m128i) -> m128i { + unsafe { transmute(__lsx_vexth_w_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vexth_d_w(a: v4i32) -> v2i64 { - unsafe { __lsx_vexth_d_w(a) } +pub fn lsx_vexth_d_w(a: m128i) -> m128i { + unsafe { transmute(__lsx_vexth_d_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vexth_q_d(a: v2i64) -> v2i64 { - unsafe { __lsx_vexth_q_d(a) } +pub fn lsx_vexth_q_d(a: m128i) -> m128i { + unsafe { transmute(__lsx_vexth_q_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vexth_hu_bu(a: v16u8) -> v8u16 { - unsafe { __lsx_vexth_hu_bu(a) } +pub fn lsx_vexth_hu_bu(a: m128i) -> m128i { + unsafe { transmute(__lsx_vexth_hu_bu(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vexth_wu_hu(a: v8u16) -> v4u32 { - unsafe { __lsx_vexth_wu_hu(a) } +pub fn lsx_vexth_wu_hu(a: m128i) -> m128i { + unsafe { transmute(__lsx_vexth_wu_hu(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vexth_du_wu(a: v4u32) -> v2u64 { - unsafe { __lsx_vexth_du_wu(a) } +pub fn lsx_vexth_du_wu(a: m128i) -> m128i { + unsafe { transmute(__lsx_vexth_du_wu(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vexth_qu_du(a: v2u64) -> v2u64 { - unsafe { __lsx_vexth_qu_du(a) } +pub fn lsx_vexth_qu_du(a: m128i) -> m128i { + unsafe { transmute(__lsx_vexth_qu_du(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrotri_b(a: v16i8) -> v16i8 { +pub fn lsx_vrotri_b(a: m128i) -> m128i { static_assert_uimm_bits!(IMM3, 3); - unsafe { __lsx_vrotri_b(a, IMM3) } + unsafe { transmute(__lsx_vrotri_b(transmute(a), IMM3)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrotri_h(a: v8i16) -> v8i16 { +pub fn lsx_vrotri_h(a: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vrotri_h(a, IMM4) } + unsafe { transmute(__lsx_vrotri_h(transmute(a), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrotri_w(a: v4i32) -> v4i32 { +pub fn lsx_vrotri_w(a: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vrotri_w(a, IMM5) } + unsafe { transmute(__lsx_vrotri_w(transmute(a), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrotri_d(a: v2i64) -> v2i64 { +pub fn lsx_vrotri_d(a: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vrotri_d(a, IMM6) } + unsafe { transmute(__lsx_vrotri_d(transmute(a), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vextl_q_d(a: v2i64) -> v2i64 { - unsafe { __lsx_vextl_q_d(a) } +pub fn lsx_vextl_q_d(a: m128i) -> m128i { + unsafe { transmute(__lsx_vextl_q_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlni_b_h(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vsrlni_b_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsrlni_b_h(a, b, IMM4) } + unsafe { transmute(__lsx_vsrlni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlni_h_w(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vsrlni_h_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsrlni_h_w(a, b, IMM5) } + unsafe { transmute(__lsx_vsrlni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlni_w_d(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vsrlni_w_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsrlni_w_d(a, b, IMM6) } + unsafe { transmute(__lsx_vsrlni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlni_d_q(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vsrlni_d_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vsrlni_d_q(a, b, IMM7) } + unsafe { transmute(__lsx_vsrlni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlrni_b_h(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vsrlrni_b_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsrlrni_b_h(a, b, IMM4) } + unsafe { transmute(__lsx_vsrlrni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlrni_h_w(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vsrlrni_h_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsrlrni_h_w(a, b, IMM5) } + unsafe { transmute(__lsx_vsrlrni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlrni_w_d(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vsrlrni_w_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsrlrni_w_d(a, b, IMM6) } + unsafe { transmute(__lsx_vsrlrni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrlrni_d_q(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vsrlrni_d_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vsrlrni_d_q(a, b, IMM7) } + unsafe { transmute(__lsx_vsrlrni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlni_b_h(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vssrlni_b_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vssrlni_b_h(a, b, IMM4) } + unsafe { transmute(__lsx_vssrlni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlni_h_w(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vssrlni_h_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vssrlni_h_w(a, b, IMM5) } + unsafe { transmute(__lsx_vssrlni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlni_w_d(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vssrlni_w_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vssrlni_w_d(a, b, IMM6) } + unsafe { transmute(__lsx_vssrlni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlni_d_q(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vssrlni_d_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vssrlni_d_q(a, b, IMM7) } + unsafe { transmute(__lsx_vssrlni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlni_bu_h(a: v16u8, b: v16i8) -> v16u8 { +pub fn lsx_vssrlni_bu_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vssrlni_bu_h(a, b, IMM4) } + unsafe { transmute(__lsx_vssrlni_bu_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlni_hu_w(a: v8u16, b: v8i16) -> v8u16 { +pub fn lsx_vssrlni_hu_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vssrlni_hu_w(a, b, IMM5) } + unsafe { transmute(__lsx_vssrlni_hu_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlni_wu_d(a: v4u32, b: v4i32) -> v4u32 { +pub fn lsx_vssrlni_wu_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vssrlni_wu_d(a, b, IMM6) } + unsafe { transmute(__lsx_vssrlni_wu_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlni_du_q(a: v2u64, b: v2i64) -> v2u64 { +pub fn lsx_vssrlni_du_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vssrlni_du_q(a, b, IMM7) } + unsafe { transmute(__lsx_vssrlni_du_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrni_b_h(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vssrlrni_b_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vssrlrni_b_h(a, b, IMM4) } + unsafe { transmute(__lsx_vssrlrni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrni_h_w(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vssrlrni_h_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vssrlrni_h_w(a, b, IMM5) } + unsafe { transmute(__lsx_vssrlrni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrni_w_d(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vssrlrni_w_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vssrlrni_w_d(a, b, IMM6) } + unsafe { transmute(__lsx_vssrlrni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrni_d_q(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vssrlrni_d_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vssrlrni_d_q(a, b, IMM7) } + unsafe { transmute(__lsx_vssrlrni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrni_bu_h(a: v16u8, b: v16i8) -> v16u8 { +pub fn lsx_vssrlrni_bu_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vssrlrni_bu_h(a, b, IMM4) } + unsafe { transmute(__lsx_vssrlrni_bu_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrni_hu_w(a: v8u16, b: v8i16) -> v8u16 { +pub fn lsx_vssrlrni_hu_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vssrlrni_hu_w(a, b, IMM5) } + unsafe { transmute(__lsx_vssrlrni_hu_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrni_wu_d(a: v4u32, b: v4i32) -> v4u32 { +pub fn lsx_vssrlrni_wu_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vssrlrni_wu_d(a, b, IMM6) } + unsafe { transmute(__lsx_vssrlrni_wu_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrni_du_q(a: v2u64, b: v2i64) -> v2u64 { +pub fn lsx_vssrlrni_du_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vssrlrni_du_q(a, b, IMM7) } + unsafe { transmute(__lsx_vssrlrni_du_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrani_b_h(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vsrani_b_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsrani_b_h(a, b, IMM4) } + unsafe { transmute(__lsx_vsrani_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrani_h_w(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vsrani_h_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsrani_h_w(a, b, IMM5) } + unsafe { transmute(__lsx_vsrani_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrani_w_d(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vsrani_w_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsrani_w_d(a, b, IMM6) } + unsafe { transmute(__lsx_vsrani_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrani_d_q(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vsrani_d_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vsrani_d_q(a, b, IMM7) } + unsafe { transmute(__lsx_vsrani_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrarni_b_h(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vsrarni_b_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vsrarni_b_h(a, b, IMM4) } + unsafe { transmute(__lsx_vsrarni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrarni_h_w(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vsrarni_h_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vsrarni_h_w(a, b, IMM5) } + unsafe { transmute(__lsx_vsrarni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrarni_w_d(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vsrarni_w_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vsrarni_w_d(a, b, IMM6) } + unsafe { transmute(__lsx_vsrarni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vsrarni_d_q(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vsrarni_d_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vsrarni_d_q(a, b, IMM7) } + unsafe { transmute(__lsx_vsrarni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrani_b_h(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vssrani_b_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vssrani_b_h(a, b, IMM4) } + unsafe { transmute(__lsx_vssrani_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrani_h_w(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vssrani_h_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vssrani_h_w(a, b, IMM5) } + unsafe { transmute(__lsx_vssrani_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrani_w_d(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vssrani_w_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vssrani_w_d(a, b, IMM6) } + unsafe { transmute(__lsx_vssrani_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrani_d_q(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vssrani_d_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vssrani_d_q(a, b, IMM7) } + unsafe { transmute(__lsx_vssrani_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrani_bu_h(a: v16u8, b: v16i8) -> v16u8 { +pub fn lsx_vssrani_bu_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vssrani_bu_h(a, b, IMM4) } + unsafe { transmute(__lsx_vssrani_bu_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrani_hu_w(a: v8u16, b: v8i16) -> v8u16 { +pub fn lsx_vssrani_hu_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vssrani_hu_w(a, b, IMM5) } + unsafe { transmute(__lsx_vssrani_hu_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrani_wu_d(a: v4u32, b: v4i32) -> v4u32 { +pub fn lsx_vssrani_wu_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vssrani_wu_d(a, b, IMM6) } + unsafe { transmute(__lsx_vssrani_wu_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrani_du_q(a: v2u64, b: v2i64) -> v2u64 { +pub fn lsx_vssrani_du_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vssrani_du_q(a, b, IMM7) } + unsafe { transmute(__lsx_vssrani_du_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarni_b_h(a: v16i8, b: v16i8) -> v16i8 { +pub fn lsx_vssrarni_b_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vssrarni_b_h(a, b, IMM4) } + unsafe { transmute(__lsx_vssrarni_b_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarni_h_w(a: v8i16, b: v8i16) -> v8i16 { +pub fn lsx_vssrarni_h_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vssrarni_h_w(a, b, IMM5) } + unsafe { transmute(__lsx_vssrarni_h_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarni_w_d(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vssrarni_w_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vssrarni_w_d(a, b, IMM6) } + unsafe { transmute(__lsx_vssrarni_w_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarni_d_q(a: v2i64, b: v2i64) -> v2i64 { +pub fn lsx_vssrarni_d_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vssrarni_d_q(a, b, IMM7) } + unsafe { transmute(__lsx_vssrarni_d_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarni_bu_h(a: v16u8, b: v16i8) -> v16u8 { +pub fn lsx_vssrarni_bu_h(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM4, 4); - unsafe { __lsx_vssrarni_bu_h(a, b, IMM4) } + unsafe { transmute(__lsx_vssrarni_bu_h(transmute(a), transmute(b), IMM4)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarni_hu_w(a: v8u16, b: v8i16) -> v8u16 { +pub fn lsx_vssrarni_hu_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM5, 5); - unsafe { __lsx_vssrarni_hu_w(a, b, IMM5) } + unsafe { transmute(__lsx_vssrarni_hu_w(transmute(a), transmute(b), IMM5)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarni_wu_d(a: v4u32, b: v4i32) -> v4u32 { +pub fn lsx_vssrarni_wu_d(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM6, 6); - unsafe { __lsx_vssrarni_wu_d(a, b, IMM6) } + unsafe { transmute(__lsx_vssrarni_wu_d(transmute(a), transmute(b), IMM6)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrarni_du_q(a: v2u64, b: v2i64) -> v2u64 { +pub fn lsx_vssrarni_du_q(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM7, 7); - unsafe { __lsx_vssrarni_du_q(a, b, IMM7) } + unsafe { transmute(__lsx_vssrarni_du_q(transmute(a), transmute(b), IMM7)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vpermi_w(a: v4i32, b: v4i32) -> v4i32 { +pub fn lsx_vpermi_w(a: m128i, b: m128i) -> m128i { static_assert_uimm_bits!(IMM8, 8); - unsafe { __lsx_vpermi_w(a, b, IMM8) } + unsafe { transmute(__lsx_vpermi_w(transmute(a), transmute(b), IMM8)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(1)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vld(mem_addr: *const i8) -> v16i8 { +pub unsafe fn lsx_vld(mem_addr: *const i8) -> m128i { static_assert_simm_bits!(IMM_S12, 12); - __lsx_vld(mem_addr, IMM_S12) + transmute(__lsx_vld(mem_addr, IMM_S12)) } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(2)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vst(a: v16i8, mem_addr: *mut i8) { +pub unsafe fn lsx_vst(a: m128i, mem_addr: *mut i8) { static_assert_simm_bits!(IMM_S12, 12); - __lsx_vst(a, mem_addr, IMM_S12) + transmute(__lsx_vst(transmute(a), mem_addr, IMM_S12)) } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrn_b_h(a: v8i16, b: v8i16) -> v16i8 { - unsafe { __lsx_vssrlrn_b_h(a, b) } +pub fn lsx_vssrlrn_b_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrlrn_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrn_h_w(a: v4i32, b: v4i32) -> v8i16 { - unsafe { __lsx_vssrlrn_h_w(a, b) } +pub fn lsx_vssrlrn_h_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrlrn_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrlrn_w_d(a: v2i64, b: v2i64) -> v4i32 { - unsafe { __lsx_vssrlrn_w_d(a, b) } +pub fn lsx_vssrlrn_w_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrlrn_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrln_b_h(a: v8i16, b: v8i16) -> v16i8 { - unsafe { __lsx_vssrln_b_h(a, b) } +pub fn lsx_vssrln_b_h(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrln_b_h(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrln_h_w(a: v4i32, b: v4i32) -> v8i16 { - unsafe { __lsx_vssrln_h_w(a, b) } +pub fn lsx_vssrln_h_w(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrln_h_w(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vssrln_w_d(a: v2i64, b: v2i64) -> v4i32 { - unsafe { __lsx_vssrln_w_d(a, b) } +pub fn lsx_vssrln_w_d(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vssrln_w_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vorn_v(a: v16i8, b: v16i8) -> v16i8 { - unsafe { __lsx_vorn_v(a, b) } +pub fn lsx_vorn_v(a: m128i, b: m128i) -> m128i { + unsafe { transmute(__lsx_vorn_v(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vldi() -> v2i64 { +pub fn lsx_vldi() -> m128i { static_assert_simm_bits!(IMM_S13, 13); - unsafe { __lsx_vldi(IMM_S13) } + unsafe { transmute(__lsx_vldi(IMM_S13)) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vshuf_b(a: v16i8, b: v16i8, c: v16i8) -> v16i8 { - unsafe { __lsx_vshuf_b(a, b, c) } +pub fn lsx_vshuf_b(a: m128i, b: m128i, c: m128i) -> m128i { + unsafe { transmute(__lsx_vshuf_b(transmute(a), transmute(b), transmute(c))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vldx(mem_addr: *const i8, b: i64) -> v16i8 { - __lsx_vldx(mem_addr, b) +pub unsafe fn lsx_vldx(mem_addr: *const i8, b: i64) -> m128i { + transmute(__lsx_vldx(mem_addr, transmute(b))) } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub unsafe fn lsx_vstx(a: v16i8, mem_addr: *mut i8, b: i64) { - __lsx_vstx(a, mem_addr, b) +pub unsafe fn lsx_vstx(a: m128i, mem_addr: *mut i8, b: i64) { + transmute(__lsx_vstx(transmute(a), mem_addr, transmute(b))) } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vextl_qu_du(a: v2u64) -> v2u64 { - unsafe { __lsx_vextl_qu_du(a) } +pub fn lsx_vextl_qu_du(a: m128i) -> m128i { + unsafe { transmute(__lsx_vextl_qu_du(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bnz_b(a: v16u8) -> i32 { - unsafe { __lsx_bnz_b(a) } +pub fn lsx_bnz_b(a: m128i) -> i32 { + unsafe { transmute(__lsx_bnz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bnz_d(a: v2u64) -> i32 { - unsafe { __lsx_bnz_d(a) } +pub fn lsx_bnz_d(a: m128i) -> i32 { + unsafe { transmute(__lsx_bnz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bnz_h(a: v8u16) -> i32 { - unsafe { __lsx_bnz_h(a) } +pub fn lsx_bnz_h(a: m128i) -> i32 { + unsafe { transmute(__lsx_bnz_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bnz_v(a: v16u8) -> i32 { - unsafe { __lsx_bnz_v(a) } +pub fn lsx_bnz_v(a: m128i) -> i32 { + unsafe { transmute(__lsx_bnz_v(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bnz_w(a: v4u32) -> i32 { - unsafe { __lsx_bnz_w(a) } +pub fn lsx_bnz_w(a: m128i) -> i32 { + unsafe { transmute(__lsx_bnz_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bz_b(a: v16u8) -> i32 { - unsafe { __lsx_bz_b(a) } +pub fn lsx_bz_b(a: m128i) -> i32 { + unsafe { transmute(__lsx_bz_b(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bz_d(a: v2u64) -> i32 { - unsafe { __lsx_bz_d(a) } +pub fn lsx_bz_d(a: m128i) -> i32 { + unsafe { transmute(__lsx_bz_d(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bz_h(a: v8u16) -> i32 { - unsafe { __lsx_bz_h(a) } +pub fn lsx_bz_h(a: m128i) -> i32 { + unsafe { transmute(__lsx_bz_h(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bz_v(a: v16u8) -> i32 { - unsafe { __lsx_bz_v(a) } +pub fn lsx_bz_v(a: m128i) -> i32 { + unsafe { transmute(__lsx_bz_v(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_bz_w(a: v4u32) -> i32 { - unsafe { __lsx_bz_w(a) } +pub fn lsx_bz_w(a: m128i) -> i32 { + unsafe { transmute(__lsx_bz_w(transmute(a))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_caf_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_caf_d(a, b) } +pub fn lsx_vfcmp_caf_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_caf_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_caf_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_caf_s(a, b) } +pub fn lsx_vfcmp_caf_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_caf_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_ceq_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_ceq_d(a, b) } +pub fn lsx_vfcmp_ceq_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_ceq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_ceq_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_ceq_s(a, b) } +pub fn lsx_vfcmp_ceq_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_ceq_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cle_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_cle_d(a, b) } +pub fn lsx_vfcmp_cle_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_cle_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cle_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_cle_s(a, b) } +pub fn lsx_vfcmp_cle_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_cle_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_clt_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_clt_d(a, b) } +pub fn lsx_vfcmp_clt_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_clt_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_clt_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_clt_s(a, b) } +pub fn lsx_vfcmp_clt_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_clt_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cne_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_cne_d(a, b) } +pub fn lsx_vfcmp_cne_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_cne_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cne_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_cne_s(a, b) } +pub fn lsx_vfcmp_cne_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_cne_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cor_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_cor_d(a, b) } +pub fn lsx_vfcmp_cor_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_cor_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cor_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_cor_s(a, b) } +pub fn lsx_vfcmp_cor_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_cor_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cueq_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_cueq_d(a, b) } +pub fn lsx_vfcmp_cueq_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_cueq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cueq_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_cueq_s(a, b) } +pub fn lsx_vfcmp_cueq_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_cueq_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cule_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_cule_d(a, b) } +pub fn lsx_vfcmp_cule_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_cule_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cule_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_cule_s(a, b) } +pub fn lsx_vfcmp_cule_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_cule_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cult_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_cult_d(a, b) } +pub fn lsx_vfcmp_cult_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_cult_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cult_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_cult_s(a, b) } +pub fn lsx_vfcmp_cult_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_cult_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cun_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_cun_d(a, b) } +pub fn lsx_vfcmp_cun_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_cun_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cune_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_cune_d(a, b) } +pub fn lsx_vfcmp_cune_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_cune_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cune_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_cune_s(a, b) } +pub fn lsx_vfcmp_cune_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_cune_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_cun_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_cun_s(a, b) } +pub fn lsx_vfcmp_cun_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_cun_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_saf_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_saf_d(a, b) } +pub fn lsx_vfcmp_saf_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_saf_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_saf_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_saf_s(a, b) } +pub fn lsx_vfcmp_saf_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_saf_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_seq_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_seq_d(a, b) } +pub fn lsx_vfcmp_seq_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_seq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_seq_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_seq_s(a, b) } +pub fn lsx_vfcmp_seq_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_seq_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sle_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_sle_d(a, b) } +pub fn lsx_vfcmp_sle_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_sle_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sle_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_sle_s(a, b) } +pub fn lsx_vfcmp_sle_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_sle_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_slt_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_slt_d(a, b) } +pub fn lsx_vfcmp_slt_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_slt_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_slt_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_slt_s(a, b) } +pub fn lsx_vfcmp_slt_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_slt_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sne_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_sne_d(a, b) } +pub fn lsx_vfcmp_sne_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_sne_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sne_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_sne_s(a, b) } +pub fn lsx_vfcmp_sne_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_sne_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sor_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_sor_d(a, b) } +pub fn lsx_vfcmp_sor_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_sor_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sor_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_sor_s(a, b) } +pub fn lsx_vfcmp_sor_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_sor_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sueq_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_sueq_d(a, b) } +pub fn lsx_vfcmp_sueq_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_sueq_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sueq_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_sueq_s(a, b) } +pub fn lsx_vfcmp_sueq_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_sueq_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sule_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_sule_d(a, b) } +pub fn lsx_vfcmp_sule_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_sule_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sule_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_sule_s(a, b) } +pub fn lsx_vfcmp_sule_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_sule_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sult_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_sult_d(a, b) } +pub fn lsx_vfcmp_sult_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_sult_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sult_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_sult_s(a, b) } +pub fn lsx_vfcmp_sult_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_sult_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sun_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_sun_d(a, b) } +pub fn lsx_vfcmp_sun_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_sun_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sune_d(a: v2f64, b: v2f64) -> v2i64 { - unsafe { __lsx_vfcmp_sune_d(a, b) } +pub fn lsx_vfcmp_sune_d(a: m128d, b: m128d) -> m128i { + unsafe { transmute(__lsx_vfcmp_sune_d(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sune_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_sune_s(a, b) } +pub fn lsx_vfcmp_sune_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_sune_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vfcmp_sun_s(a: v4f32, b: v4f32) -> v4i32 { - unsafe { __lsx_vfcmp_sun_s(a, b) } +pub fn lsx_vfcmp_sun_s(a: m128, b: m128) -> m128i { + unsafe { transmute(__lsx_vfcmp_sun_s(transmute(a), transmute(b))) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrepli_b() -> v16i8 { +pub fn lsx_vrepli_b() -> m128i { static_assert_simm_bits!(IMM_S10, 10); - unsafe { __lsx_vrepli_b(IMM_S10) } + unsafe { transmute(__lsx_vrepli_b(IMM_S10)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrepli_d() -> v2i64 { +pub fn lsx_vrepli_d() -> m128i { static_assert_simm_bits!(IMM_S10, 10); - unsafe { __lsx_vrepli_d(IMM_S10) } + unsafe { transmute(__lsx_vrepli_d(IMM_S10)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrepli_h() -> v8i16 { +pub fn lsx_vrepli_h() -> m128i { static_assert_simm_bits!(IMM_S10, 10); - unsafe { __lsx_vrepli_h(IMM_S10) } + unsafe { transmute(__lsx_vrepli_h(IMM_S10)) } } #[inline] #[target_feature(enable = "lsx")] #[rustc_legacy_const_generics(0)] #[unstable(feature = "stdarch_loongarch", issue = "117427")] -pub fn lsx_vrepli_w() -> v4i32 { +pub fn lsx_vrepli_w() -> m128i { static_assert_simm_bits!(IMM_S10, 10); - unsafe { __lsx_vrepli_w(IMM_S10) } + unsafe { transmute(__lsx_vrepli_w(IMM_S10)) } } diff --git a/library/stdarch/crates/core_arch/src/loongarch64/lsx/types.rs b/library/stdarch/crates/core_arch/src/loongarch64/lsx/types.rs index 4097164c2fae..4fb694571747 100644 --- a/library/stdarch/crates/core_arch/src/loongarch64/lsx/types.rs +++ b/library/stdarch/crates/core_arch/src/loongarch64/lsx/types.rs @@ -1,33 +1,140 @@ types! { #![unstable(feature = "stdarch_loongarch", issue = "117427")] - /// LOONGARCH-specific 128-bit wide vector of 16 packed `i8`. - pub struct v16i8(16 x pub(crate) i8); + /// 128-bit wide integer vector type, LoongArch-specific + /// + /// This type is the same as the `__m128i` type defined in `lsxintrin.h`, + /// representing a 128-bit SIMD register. Usage of this type typically + /// occurs in conjunction with the `lsx` and higher target features for + /// LoongArch. + /// + /// Internally this type may be viewed as: + /// + /// * `i8x16` - sixteen `i8` values packed together + /// * `i16x8` - eight `i16` values packed together + /// * `i32x4` - four `i32` values packed together + /// * `i64x2` - two `i64` values packed together + /// + /// (as well as unsigned versions). Each intrinsic may interpret the + /// internal bits differently, check the documentation of the intrinsic + /// to see how it's being used. + /// + /// The in-memory representation of this type is the same as the one of an + /// equivalent array (i.e. the in-memory order of elements is the same, and + /// there is no padding); however, the alignment is different and equal to + /// the size of the type. Note that the ABI for function calls may *not* be + /// the same. + /// + /// Note that this means that an instance of `m128i` typically just means + /// a "bag of bits" which is left up to interpretation at the point of use. + /// + /// Most intrinsics using `m128i` are prefixed with `lsx_` and the integer + /// types tend to correspond to suffixes like "b", "h", "w" or "d". + pub struct m128i(2 x i64); - /// LOONGARCH-specific 128-bit wide vector of 8 packed `i16`. - pub struct v8i16(8 x pub(crate) i16); + /// 128-bit wide set of four `f32` values, LoongArch-specific + /// + /// This type is the same as the `__m128` type defined in `lsxintrin.h`, + /// representing a 128-bit SIMD register which internally consists of + /// four packed `f32` instances. Usage of this type typically occurs in + /// conjunction with the `lsx` and higher target features for LoongArch. + /// + /// Note that unlike `m128i`, the integer version of the 128-bit registers, + /// this `m128` type has *one* interpretation. Each instance of `m128` + /// corresponds to `f32x4`, or four `f32` values packed together. + /// + /// The in-memory representation of this type is the same as the one of an + /// equivalent array (i.e. the in-memory order of elements is the same, and + /// there is no padding); however, the alignment is different and equal to + /// the size of the type. Note that the ABI for function calls may *not* be + /// the same. + /// + /// Most intrinsics using `m128` are prefixed with `lsx_` and are suffixed + /// with "s". + pub struct m128(4 x f32); - /// LOONGARCH-specific 128-bit wide vector of 4 packed `i32`. - pub struct v4i32(4 x pub(crate) i32); - - /// LOONGARCH-specific 128-bit wide vector of 2 packed `i64`. - pub struct v2i64(2 x pub(crate) i64); - - /// LOONGARCH-specific 128-bit wide vector of 16 packed `u8`. - pub struct v16u8(16 x pub(crate) u8); - - /// LOONGARCH-specific 128-bit wide vector of 8 packed `u16`. - pub struct v8u16(8 x pub(crate) u16); - - /// LOONGARCH-specific 128-bit wide vector of 4 packed `u32`. - pub struct v4u32(4 x pub(crate) u32); - - /// LOONGARCH-specific 128-bit wide vector of 2 packed `u64`. - pub struct v2u64(2 x pub(crate) u64); + /// 128-bit wide set of two `f64` values, LoongArch-specific + /// + /// This type is the same as the `__m128d` type defined in `lsxintrin.h`, + /// representing a 128-bit SIMD register which internally consists of + /// two packed `f64` instances. Usage of this type typically occurs in + /// conjunction with the `lsx` and higher target features for LoongArch. + /// + /// Note that unlike `m128i`, the integer version of the 128-bit registers, + /// this `m128d` type has *one* interpretation. Each instance of `m128d` + /// always corresponds to `f64x2`, or two `f64` values packed together. + /// + /// The in-memory representation of this type is the same as the one of an + /// equivalent array (i.e. the in-memory order of elements is the same, and + /// there is no padding); however, the alignment is different and equal to + /// the size of the type. Note that the ABI for function calls may *not* be + /// the same. + /// + /// Most intrinsics using `m128d` are prefixed with `lsx_` and are suffixed + /// with "d". Not to be confused with "d" which is used for `m128i`. + pub struct m128d(2 x f64); +} - /// LOONGARCH-specific 128-bit wide vector of 4 packed `f32`. - pub struct v4f32(4 x pub(crate) f32); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v16i8([i8; 16]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v8i16([i16; 8]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v4i32([i32; 4]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v2i64([i64; 2]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v16u8([u8; 16]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v8u16([u16; 8]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v4u32([u32; 4]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v2u64([u64; 2]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v4f32([f32; 4]); +#[allow(non_camel_case_types)] +#[repr(simd)] +pub(crate) struct __v2f64([f64; 2]); - /// LOONGARCH-specific 128-bit wide vector of 2 packed `f64`. - pub struct v2f64(2 x pub(crate) f64); -} +// These type aliases are provided solely for transitional compatibility. +// They are temporary and will be removed when appropriate. +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v16i8 = m128i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v8i16 = m128i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v4i32 = m128i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v2i64 = m128i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v16u8 = m128i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v8u16 = m128i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v4u32 = m128i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v2u64 = m128i; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v4f32 = m128; +#[allow(non_camel_case_types)] +#[unstable(feature = "stdarch_loongarch", issue = "117427")] +pub type v2f64 = m128d; diff --git a/library/stdarch/crates/stdarch-gen-loongarch/src/main.rs b/library/stdarch/crates/stdarch-gen-loongarch/src/main.rs index 40132097f5de..5076064ffcdd 100644 --- a/library/stdarch/crates/stdarch-gen-loongarch/src/main.rs +++ b/library/stdarch/crates/stdarch-gen-loongarch/src/main.rs @@ -156,6 +156,7 @@ fn gen_bind(in_file: String, ext_name: &str) -> io::Result<()> { // OUT_DIR=`pwd`/crates/core_arch cargo run -p stdarch-gen-loongarch -- {in_file} // ``` +use crate::mem::transmute; use super::types::*; "# )); @@ -239,38 +240,63 @@ fn gen_bind_body( para_num: i32, target: TargetFeature, ) -> (String, String) { - let type_to_rst = |t: &str, s: bool| -> &str { - match (t, s) { - ("V16QI", _) => "v16i8", - ("V32QI", _) => "v32i8", - ("V8HI", _) => "v8i16", - ("V16HI", _) => "v16i16", - ("V4SI", _) => "v4i32", - ("V8SI", _) => "v8i32", - ("V2DI", _) => "v2i64", - ("V4DI", _) => "v4i64", - ("UV16QI", _) => "v16u8", - ("UV32QI", _) => "v32u8", - ("UV8HI", _) => "v8u16", - ("UV16HI", _) => "v16u16", - ("UV4SI", _) => "v4u32", - ("UV8SI", _) => "v8u32", - ("UV2DI", _) => "v2u64", - ("UV4DI", _) => "v4u64", - ("SI", _) => "i32", - ("DI", _) => "i64", - ("USI", _) => "u32", - ("UDI", _) => "u64", - ("V4SF", _) => "v4f32", - ("V8SF", _) => "v8f32", - ("V2DF", _) => "v2f64", - ("V4DF", _) => "v4f64", - ("UQI", _) => "u32", - ("QI", _) => "i32", - ("CVPOINTER", false) => "*const i8", - ("CVPOINTER", true) => "*mut i8", - ("HI", _) => "i32", - (_, _) => panic!("unknown type: {t}"), + enum TypeKind { + Vector, + Intrinsic, + } + use TypeKind::*; + let type_to_rst = |t: &str, s: bool, k: TypeKind| -> &str { + match (t, s, k) { + ("V16QI", _, Vector) => "__v16i8", + ("V16QI", _, Intrinsic) => "m128i", + ("V32QI", _, Vector) => "__v32i8", + ("V32QI", _, Intrinsic) => "m256i", + ("V8HI", _, Vector) => "__v8i16", + ("V8HI", _, Intrinsic) => "m128i", + ("V16HI", _, Vector) => "__v16i16", + ("V16HI", _, Intrinsic) => "m256i", + ("V4SI", _, Vector) => "__v4i32", + ("V4SI", _, Intrinsic) => "m128i", + ("V8SI", _, Vector) => "__v8i32", + ("V8SI", _, Intrinsic) => "m256i", + ("V2DI", _, Vector) => "__v2i64", + ("V2DI", _, Intrinsic) => "m128i", + ("V4DI", _, Vector) => "__v4i64", + ("V4DI", _, Intrinsic) => "m256i", + ("UV16QI", _, Vector) => "__v16u8", + ("UV16QI", _, Intrinsic) => "m128i", + ("UV32QI", _, Vector) => "__v32u8", + ("UV32QI", _, Intrinsic) => "m256i", + ("UV8HI", _, Vector) => "__v8u16", + ("UV8HI", _, Intrinsic) => "m128i", + ("UV16HI", _, Vector) => "__v16u16", + ("UV16HI", _, Intrinsic) => "m256i", + ("UV4SI", _, Vector) => "__v4u32", + ("UV4SI", _, Intrinsic) => "m128i", + ("UV8SI", _, Vector) => "__v8u32", + ("UV8SI", _, Intrinsic) => "m256i", + ("UV2DI", _, Vector) => "__v2u64", + ("UV2DI", _, Intrinsic) => "m128i", + ("UV4DI", _, Vector) => "__v4u64", + ("UV4DI", _, Intrinsic) => "m256i", + ("SI", _, _) => "i32", + ("DI", _, _) => "i64", + ("USI", _, _) => "u32", + ("UDI", _, _) => "u64", + ("V4SF", _, Vector) => "__v4f32", + ("V4SF", _, Intrinsic) => "m128", + ("V8SF", _, Vector) => "__v8f32", + ("V8SF", _, Intrinsic) => "m256", + ("V2DF", _, Vector) => "__v2f64", + ("V2DF", _, Intrinsic) => "m128d", + ("V4DF", _, Vector) => "__v4f64", + ("V4DF", _, Intrinsic) => "m256d", + ("UQI", _, _) => "u32", + ("QI", _, _) => "i32", + ("CVPOINTER", false, _) => "*const i8", + ("CVPOINTER", true, _) => "*mut i8", + ("HI", _, _) => "i32", + (_, _, _) => panic!("unknown type: {t}"), } }; @@ -281,27 +307,27 @@ fn gen_bind_body( let fn_output = if out_t.to_lowercase() == "void" { String::new() } else { - format!(" -> {}", type_to_rst(out_t, is_store)) + format!(" -> {}", type_to_rst(out_t, is_store, Vector)) }; let fn_inputs = match para_num { - 1 => format!("(a: {})", type_to_rst(in_t[0], is_store)), + 1 => format!("(a: {})", type_to_rst(in_t[0], is_store, Vector)), 2 => format!( "(a: {}, b: {})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store) + type_to_rst(in_t[0], is_store, Vector), + type_to_rst(in_t[1], is_store, Vector) ), 3 => format!( "(a: {}, b: {}, c: {})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), - type_to_rst(in_t[2], is_store) + type_to_rst(in_t[0], is_store, Vector), + type_to_rst(in_t[1], is_store, Vector), + type_to_rst(in_t[2], is_store, Vector) ), 4 => format!( "(a: {}, b: {}, c: {}, d: {})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), - type_to_rst(in_t[2], is_store), - type_to_rst(in_t[3], is_store) + type_to_rst(in_t[0], is_store, Vector), + type_to_rst(in_t[1], is_store, Vector), + type_to_rst(in_t[2], is_store, Vector), + type_to_rst(in_t[3], is_store, Vector) ), _ => panic!("unsupported parameter number"), }; @@ -330,34 +356,40 @@ fn gen_bind_body( let fn_output = if out_t.to_lowercase() == "void" { String::new() } else { - format!("-> {} ", type_to_rst(out_t, is_store)) + format!("-> {} ", type_to_rst(out_t, is_store, Intrinsic)) }; let mut fn_inputs = match para_num { - 1 => format!("(a: {})", type_to_rst(in_t[0], is_store)), + 1 => format!("(a: {})", type_to_rst(in_t[0], is_store, Intrinsic)), 2 => format!( "(a: {}, b: {})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store) + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic) ), 3 => format!( "(a: {}, b: {}, c: {})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), - type_to_rst(in_t[2], is_store) + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), + type_to_rst(in_t[2], is_store, Intrinsic) ), 4 => format!( "(a: {}, b: {}, c: {}, d: {})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), - type_to_rst(in_t[2], is_store), - type_to_rst(in_t[3], is_store) + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), + type_to_rst(in_t[2], is_store, Intrinsic), + type_to_rst(in_t[3], is_store, Intrinsic) ), _ => panic!("unsupported parameter number"), }; if para_num == 1 && in_t[0] == "HI" { fn_inputs = match asm_fmts[1].as_str() { - "si13" | "i13" => format!("()", type_to_rst(in_t[0], is_store)), - "si10" => format!("()", type_to_rst(in_t[0], is_store)), + "si13" | "i13" => format!( + "()", + type_to_rst(in_t[0], is_store, Intrinsic) + ), + "si10" => format!( + "()", + type_to_rst(in_t[0], is_store, Intrinsic) + ), _ => panic!("unsupported assembly format: {}", asm_fmts[1]), }; rustc_legacy_const_generics = "rustc_legacy_const_generics(0)"; @@ -365,8 +397,8 @@ fn gen_bind_body( fn_inputs = if asm_fmts[2].starts_with("ui") { format!( "(a: {0})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), asm_fmts[2].get(2..).unwrap() ) } else { @@ -377,8 +409,8 @@ fn gen_bind_body( fn_inputs = if asm_fmts[2].starts_with("si") { format!( "(a: {0})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), asm_fmts[2].get(2..).unwrap() ) } else { @@ -389,8 +421,8 @@ fn gen_bind_body( fn_inputs = if asm_fmts[2].starts_with("si") { format!( "(mem_addr: {0})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), asm_fmts[2].get(2..).unwrap() ) } else { @@ -401,8 +433,8 @@ fn gen_bind_body( fn_inputs = match asm_fmts[2].as_str() { "rk" => format!( "(mem_addr: {}, b: {})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store) + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic) ), _ => panic!("unsupported assembly format: {}", asm_fmts[2]), }; @@ -410,9 +442,9 @@ fn gen_bind_body( fn_inputs = if asm_fmts[2].starts_with("ui") { format!( "(a: {0}, b: {1})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), - type_to_rst(in_t[2], is_store), + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), + type_to_rst(in_t[2], is_store, Intrinsic), asm_fmts[2].get(2..).unwrap() ) } else { @@ -423,9 +455,9 @@ fn gen_bind_body( fn_inputs = match asm_fmts[2].as_str() { "si12" => format!( "(a: {0}, mem_addr: {1})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), - type_to_rst(in_t[2], is_store) + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), + type_to_rst(in_t[2], is_store, Intrinsic) ), _ => panic!("unsupported assembly format: {}", asm_fmts[2]), }; @@ -434,9 +466,9 @@ fn gen_bind_body( fn_inputs = match asm_fmts[2].as_str() { "rk" => format!( "(a: {}, mem_addr: {}, b: {})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), - type_to_rst(in_t[2], is_store) + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), + type_to_rst(in_t[2], is_store, Intrinsic) ), _ => panic!("unsupported assembly format: {}", asm_fmts[2]), }; @@ -444,10 +476,10 @@ fn gen_bind_body( fn_inputs = match (asm_fmts[2].as_str(), current_name.chars().last().unwrap()) { ("si8", t) => format!( "(a: {0}, mem_addr: {1})", - type_to_rst(in_t[0], is_store), - type_to_rst(in_t[1], is_store), - type_to_rst(in_t[2], is_store), - type_to_rst(in_t[3], is_store), + type_to_rst(in_t[0], is_store, Intrinsic), + type_to_rst(in_t[1], is_store, Intrinsic), + type_to_rst(in_t[2], is_store, Intrinsic), + type_to_rst(in_t[3], is_store, Intrinsic), type_to_imm(t), ), (_, _) => panic!( @@ -466,10 +498,16 @@ fn gen_bind_body( let unsafe_end = if !is_mem { " }" } else { "" }; let mut call_params = { match para_num { - 1 => format!("{unsafe_start}__{current_name}(a){unsafe_end}"), - 2 => format!("{unsafe_start}__{current_name}(a, b){unsafe_end}"), - 3 => format!("{unsafe_start}__{current_name}(a, b, c){unsafe_end}"), - 4 => format!("{unsafe_start}__{current_name}(a, b, c, d){unsafe_end}"), + 1 => format!("{unsafe_start}transmute(__{current_name}(transmute(a))){unsafe_end}"), + 2 => format!( + "{unsafe_start}transmute(__{current_name}(transmute(a), transmute(b))){unsafe_end}" + ), + 3 => format!( + "{unsafe_start}transmute(__{current_name}(transmute(a), transmute(b), transmute(c))){unsafe_end}" + ), + 4 => format!( + "{unsafe_start}transmute(__{current_name}(transmute(a), transmute(b), transmute(c), transmute(d))){unsafe_end}" + ), _ => panic!("unsupported parameter number"), } }; @@ -477,12 +515,12 @@ fn gen_bind_body( call_params = match asm_fmts[1].as_str() { "si10" => { format!( - "static_assert_simm_bits!(IMM_S10, 10);\n {unsafe_start}__{current_name}(IMM_S10){unsafe_end}" + "static_assert_simm_bits!(IMM_S10, 10);\n {unsafe_start}transmute(__{current_name}(IMM_S10)){unsafe_end}" ) } "i13" => { format!( - "static_assert_simm_bits!(IMM_S13, 13);\n {unsafe_start}__{current_name}(IMM_S13){unsafe_end}" + "static_assert_simm_bits!(IMM_S13, 13);\n {unsafe_start}transmute(__{current_name}(IMM_S13)){unsafe_end}" ) } _ => panic!("unsupported assembly format: {}", asm_fmts[2]), @@ -490,7 +528,7 @@ fn gen_bind_body( } else if para_num == 2 && (in_t[1] == "UQI" || in_t[1] == "USI") { call_params = if asm_fmts[2].starts_with("ui") { format!( - "static_assert_uimm_bits!(IMM{0}, {0});\n {unsafe_start}__{current_name}(a, IMM{0}){unsafe_end}", + "static_assert_uimm_bits!(IMM{0}, {0});\n {unsafe_start}transmute(__{current_name}(transmute(a), IMM{0})){unsafe_end}", asm_fmts[2].get(2..).unwrap() ) } else { @@ -500,7 +538,7 @@ fn gen_bind_body( call_params = match asm_fmts[2].as_str() { "si5" => { format!( - "static_assert_simm_bits!(IMM_S5, 5);\n {unsafe_start}__{current_name}(a, IMM_S5){unsafe_end}" + "static_assert_simm_bits!(IMM_S5, 5);\n {unsafe_start}transmute(__{current_name}(transmute(a), IMM_S5)){unsafe_end}" ) } _ => panic!("unsupported assembly format: {}", asm_fmts[2]), @@ -508,7 +546,7 @@ fn gen_bind_body( } else if para_num == 2 && in_t[0] == "CVPOINTER" && in_t[1] == "SI" { call_params = if asm_fmts[2].starts_with("si") { format!( - "static_assert_simm_bits!(IMM_S{0}, {0});\n {unsafe_start}__{current_name}(mem_addr, IMM_S{0}){unsafe_end}", + "static_assert_simm_bits!(IMM_S{0}, {0});\n {unsafe_start}transmute(__{current_name}(mem_addr, IMM_S{0})){unsafe_end}", asm_fmts[2].get(2..).unwrap() ) } else { @@ -516,13 +554,15 @@ fn gen_bind_body( } } else if para_num == 2 && in_t[0] == "CVPOINTER" && in_t[1] == "DI" { call_params = match asm_fmts[2].as_str() { - "rk" => format!("{unsafe_start}__{current_name}(mem_addr, b){unsafe_end}"), + "rk" => format!( + "{unsafe_start}transmute(__{current_name}(mem_addr, transmute(b))){unsafe_end}" + ), _ => panic!("unsupported assembly format: {}", asm_fmts[2]), }; } else if para_num == 3 && (in_t[2] == "USI" || in_t[2] == "UQI") { call_params = if asm_fmts[2].starts_with("ui") { format!( - "static_assert_uimm_bits!(IMM{0}, {0});\n {unsafe_start}__{current_name}(a, b, IMM{0}){unsafe_end}", + "static_assert_uimm_bits!(IMM{0}, {0});\n {unsafe_start}transmute(__{current_name}(transmute(a), transmute(b), IMM{0})){unsafe_end}", asm_fmts[2].get(2..).unwrap() ) } else { @@ -531,19 +571,21 @@ fn gen_bind_body( } else if para_num == 3 && in_t[1] == "CVPOINTER" && in_t[2] == "SI" { call_params = match asm_fmts[2].as_str() { "si12" => format!( - "static_assert_simm_bits!(IMM_S12, 12);\n {unsafe_start}__{current_name}(a, mem_addr, IMM_S12){unsafe_end}" + "static_assert_simm_bits!(IMM_S12, 12);\n {unsafe_start}transmute(__{current_name}(transmute(a), mem_addr, IMM_S12)){unsafe_end}" ), _ => panic!("unsupported assembly format: {}", asm_fmts[2]), }; } else if para_num == 3 && in_t[1] == "CVPOINTER" && in_t[2] == "DI" { call_params = match asm_fmts[2].as_str() { - "rk" => format!("{unsafe_start}__{current_name}(a, mem_addr, b){unsafe_end}"), + "rk" => format!( + "{unsafe_start}transmute(__{current_name}(transmute(a), mem_addr, transmute(b))){unsafe_end}" + ), _ => panic!("unsupported assembly format: {}", asm_fmts[2]), }; } else if para_num == 4 { call_params = match (asm_fmts[2].as_str(), current_name.chars().last().unwrap()) { ("si8", t) => format!( - "static_assert_simm_bits!(IMM_S8, 8);\n static_assert_uimm_bits!(IMM{0}, {0});\n {unsafe_start}__{current_name}(a, mem_addr, IMM_S8, IMM{0}){unsafe_end}", + "static_assert_simm_bits!(IMM_S8, 8);\n static_assert_uimm_bits!(IMM{0}, {0});\n {unsafe_start}transmute(__{current_name}(transmute(a), mem_addr, IMM_S8, IMM{0})){unsafe_end}", type_to_imm(t) ), (_, _) => panic!( From 35404461e29343ec61eb79ca8408ae31f8941452 Mon Sep 17 00:00:00 2001 From: A4-Tacks Date: Fri, 25 Jul 2025 10:57:38 +0800 Subject: [PATCH 0132/1134] Fix gen panics doc template for debug_assert And add assert_eq, assert_ne, assert_matches support Input: ```rust pub fn $0foo(x: bool) { debug_assert!(x); } ``` Old: ```rust /// . /// /// # Panics /// /// Panics if . pub fn foo(x: bool) { debug_assert!(x); } ``` This PR fixes: ```rust /// . pub fn foo(x: bool) { debug_assert!(x); } ``` --- .../generate_documentation_template.rs | 68 +++++++++++++++++-- 1 file changed, 62 insertions(+), 6 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_documentation_template.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_documentation_template.rs index d4d1b3490cb6..68587f0cb5bc 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_documentation_template.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_documentation_template.rs @@ -313,12 +313,28 @@ fn crate_name(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option { /// `None` if function without a body; some bool to guess if function can panic fn can_panic(ast_func: &ast::Fn) -> Option { let body = ast_func.body()?.to_string(); - let can_panic = body.contains("panic!(") - // FIXME it would be better to not match `debug_assert*!` macro invocations - || body.contains("assert!(") - || body.contains(".unwrap()") - || body.contains(".expect("); - Some(can_panic) + let mut iter = body.chars(); + let assert_postfix = |s| { + ["!(", "_eq!(", "_ne!(", "_matches!("].iter().any(|postfix| str::starts_with(s, postfix)) + }; + + while !iter.as_str().is_empty() { + let s = iter.as_str(); + iter.next(); + if s.strip_prefix("debug_assert").is_some_and(assert_postfix) { + iter.nth(10); + continue; + } + if s.strip_prefix("assert").is_some_and(assert_postfix) + || s.starts_with("panic!(") + || s.starts_with(".unwrap()") + || s.starts_with(".expect(") + { + return Some(true); + } + } + + Some(false) } /// Helper function to get the name that should be given to `self` arguments @@ -677,6 +693,24 @@ pub fn panics_if(a: bool) { ); } + #[test] + fn guesses_debug_assert_macro_cannot_panic() { + check_assist( + generate_documentation_template, + r#" +pub fn $0debug_panics_if_not(a: bool) { + debug_assert!(a == true); +} +"#, + r#" +/// . +pub fn debug_panics_if_not(a: bool) { + debug_assert!(a == true); +} +"#, + ); + } + #[test] fn guesses_assert_macro_can_panic() { check_assist( @@ -699,6 +733,28 @@ pub fn panics_if_not(a: bool) { ); } + #[test] + fn guesses_assert_eq_macro_can_panic() { + check_assist( + generate_documentation_template, + r#" +pub fn $0panics_if_not(a: bool) { + assert_eq!(a, true); +} +"#, + r#" +/// . +/// +/// # Panics +/// +/// Panics if . +pub fn panics_if_not(a: bool) { + assert_eq!(a, true); +} +"#, + ); + } + #[test] fn guesses_unwrap_can_panic() { check_assist( From 90bb5cacb5c1a5fe20ba821d28e7eb7a21e35d09 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Thu, 24 Jul 2025 18:29:09 +0500 Subject: [PATCH 0133/1134] moved 34 tests to organized locations --- .../issue-16256.rs => closures/unused-closure-warning-16256.rs} | 0 .../array-slice-coercion-mismatch-15783.rs} | 0 .../derive-partial-ord-discriminant-64bit.rs} | 0 .../issue-15523.rs => derives/derive-partial-ord-discriminant.rs} | 0 .../ui/{issues/issue-15763.rs => drop/early-return-drop-order.rs} | 0 tests/ui/{issues/issue-15063.rs => drop/enum-drop-impl-15063.rs} | 0 .../issue-15858.rs => drop/generic-drop-trait-bound-15858.rs} | 0 .../ui/{issues/issue-16492.rs => drop/struct-field-drop-order.rs} | 0 .../issue-16151.rs => drop/vec-replace-skip-while-drop.rs} | 0 .../issue-16441.rs => extern/empty-struct-extern-fn-16441.rs} | 0 .../issue-15094.rs => fn/fn-traits-call-once-signature.rs} | 0 .../issue-15774.rs => imports/enum-variant-import-path-15774.rs} | 0 .../return-block-type-inference-15965.rs} | 0 .../issue-15756.rs => iterators/chunk-iterator-mut-pattern.rs} | 0 .../issue-15673.rs => iterators/iterator-sum-array-15673.rs} | 0 .../explicit-lifetime-required-15034.rs} | 0 .../struct-lifetime-inference-15735.rs} | 0 .../issue-15167.rs => macros/macro-hygiene-scope-15167.rs} | 0 .../issue-15189.rs => macros/macro-variable-capture-15189.rs} | 0 .../issue-15793.rs => match/nested-enum-match-optimization.rs} | 0 .../issue-15571.rs => moves/match-move-same-binding-15571.rs} | 0 .../issue-15207.rs => never/never-type-method-call-15207.rs} | 0 .../issue-15896.rs => pattern/enum-struct-pattern-mismatch.rs} | 0 .../refutable-pattern-for-loop-15381.rs} | 0 .../issue-15104.rs => pattern/slice-pattern-recursion-15104.rs} | 0 .../issue-16149.rs => pattern/static-binding-shadow-16149.rs} | 0 .../issue-15260.rs => pattern/struct-field-duplicate-binding.rs} | 0 .../issue-15129-rpass.rs => pattern/tuple-enum-match-15129.rs} | 0 .../unit-type-struct-pattern-mismatch.rs} | 0 .../issue-16452.rs => statics/conditional-static-declaration.rs} | 0 .../issue-15043.rs => structs/static-struct-init-15043.rs} | 0 .../{issues/issue-15444.rs => traits/fn-type-trait-impl-15444.rs} | 0 .../issue-15734.rs => traits/index-trait-multiple-impls.rs} | 0 .../issue-16048.rs => traits/lifetime-mismatch-trait-impl.rs} | 0 34 files changed, 0 insertions(+), 0 deletions(-) rename tests/ui/{issues/issue-16256.rs => closures/unused-closure-warning-16256.rs} (100%) rename tests/ui/{issues/issue-15783.rs => coercion/array-slice-coercion-mismatch-15783.rs} (100%) rename tests/ui/{issues/issue-15523-big.rs => derives/derive-partial-ord-discriminant-64bit.rs} (100%) rename tests/ui/{issues/issue-15523.rs => derives/derive-partial-ord-discriminant.rs} (100%) rename tests/ui/{issues/issue-15763.rs => drop/early-return-drop-order.rs} (100%) rename tests/ui/{issues/issue-15063.rs => drop/enum-drop-impl-15063.rs} (100%) rename tests/ui/{issues/issue-15858.rs => drop/generic-drop-trait-bound-15858.rs} (100%) rename tests/ui/{issues/issue-16492.rs => drop/struct-field-drop-order.rs} (100%) rename tests/ui/{issues/issue-16151.rs => drop/vec-replace-skip-while-drop.rs} (100%) rename tests/ui/{issues/issue-16441.rs => extern/empty-struct-extern-fn-16441.rs} (100%) rename tests/ui/{issues/issue-15094.rs => fn/fn-traits-call-once-signature.rs} (100%) rename tests/ui/{issues/issue-15774.rs => imports/enum-variant-import-path-15774.rs} (100%) rename tests/ui/{issues/issue-15965.rs => inference/return-block-type-inference-15965.rs} (100%) rename tests/ui/{issues/issue-15756.rs => iterators/chunk-iterator-mut-pattern.rs} (100%) rename tests/ui/{issues/issue-15673.rs => iterators/iterator-sum-array-15673.rs} (100%) rename tests/ui/{issues/issue-15034.rs => lifetimes/explicit-lifetime-required-15034.rs} (100%) rename tests/ui/{issues/issue-15735.rs => lifetimes/struct-lifetime-inference-15735.rs} (100%) rename tests/ui/{issues/issue-15167.rs => macros/macro-hygiene-scope-15167.rs} (100%) rename tests/ui/{issues/issue-15189.rs => macros/macro-variable-capture-15189.rs} (100%) rename tests/ui/{issues/issue-15793.rs => match/nested-enum-match-optimization.rs} (100%) rename tests/ui/{issues/issue-15571.rs => moves/match-move-same-binding-15571.rs} (100%) rename tests/ui/{issues/issue-15207.rs => never/never-type-method-call-15207.rs} (100%) rename tests/ui/{issues/issue-15896.rs => pattern/enum-struct-pattern-mismatch.rs} (100%) rename tests/ui/{issues/issue-15381.rs => pattern/refutable-pattern-for-loop-15381.rs} (100%) rename tests/ui/{issues/issue-15104.rs => pattern/slice-pattern-recursion-15104.rs} (100%) rename tests/ui/{issues/issue-16149.rs => pattern/static-binding-shadow-16149.rs} (100%) rename tests/ui/{issues/issue-15260.rs => pattern/struct-field-duplicate-binding.rs} (100%) rename tests/ui/{issues/issue-15129-rpass.rs => pattern/tuple-enum-match-15129.rs} (100%) rename tests/ui/{issues/issue-16401.rs => pattern/unit-type-struct-pattern-mismatch.rs} (100%) rename tests/ui/{issues/issue-16452.rs => statics/conditional-static-declaration.rs} (100%) rename tests/ui/{issues/issue-15043.rs => structs/static-struct-init-15043.rs} (100%) rename tests/ui/{issues/issue-15444.rs => traits/fn-type-trait-impl-15444.rs} (100%) rename tests/ui/{issues/issue-15734.rs => traits/index-trait-multiple-impls.rs} (100%) rename tests/ui/{issues/issue-16048.rs => traits/lifetime-mismatch-trait-impl.rs} (100%) diff --git a/tests/ui/issues/issue-16256.rs b/tests/ui/closures/unused-closure-warning-16256.rs similarity index 100% rename from tests/ui/issues/issue-16256.rs rename to tests/ui/closures/unused-closure-warning-16256.rs diff --git a/tests/ui/issues/issue-15783.rs b/tests/ui/coercion/array-slice-coercion-mismatch-15783.rs similarity index 100% rename from tests/ui/issues/issue-15783.rs rename to tests/ui/coercion/array-slice-coercion-mismatch-15783.rs diff --git a/tests/ui/issues/issue-15523-big.rs b/tests/ui/derives/derive-partial-ord-discriminant-64bit.rs similarity index 100% rename from tests/ui/issues/issue-15523-big.rs rename to tests/ui/derives/derive-partial-ord-discriminant-64bit.rs diff --git a/tests/ui/issues/issue-15523.rs b/tests/ui/derives/derive-partial-ord-discriminant.rs similarity index 100% rename from tests/ui/issues/issue-15523.rs rename to tests/ui/derives/derive-partial-ord-discriminant.rs diff --git a/tests/ui/issues/issue-15763.rs b/tests/ui/drop/early-return-drop-order.rs similarity index 100% rename from tests/ui/issues/issue-15763.rs rename to tests/ui/drop/early-return-drop-order.rs diff --git a/tests/ui/issues/issue-15063.rs b/tests/ui/drop/enum-drop-impl-15063.rs similarity index 100% rename from tests/ui/issues/issue-15063.rs rename to tests/ui/drop/enum-drop-impl-15063.rs diff --git a/tests/ui/issues/issue-15858.rs b/tests/ui/drop/generic-drop-trait-bound-15858.rs similarity index 100% rename from tests/ui/issues/issue-15858.rs rename to tests/ui/drop/generic-drop-trait-bound-15858.rs diff --git a/tests/ui/issues/issue-16492.rs b/tests/ui/drop/struct-field-drop-order.rs similarity index 100% rename from tests/ui/issues/issue-16492.rs rename to tests/ui/drop/struct-field-drop-order.rs diff --git a/tests/ui/issues/issue-16151.rs b/tests/ui/drop/vec-replace-skip-while-drop.rs similarity index 100% rename from tests/ui/issues/issue-16151.rs rename to tests/ui/drop/vec-replace-skip-while-drop.rs diff --git a/tests/ui/issues/issue-16441.rs b/tests/ui/extern/empty-struct-extern-fn-16441.rs similarity index 100% rename from tests/ui/issues/issue-16441.rs rename to tests/ui/extern/empty-struct-extern-fn-16441.rs diff --git a/tests/ui/issues/issue-15094.rs b/tests/ui/fn/fn-traits-call-once-signature.rs similarity index 100% rename from tests/ui/issues/issue-15094.rs rename to tests/ui/fn/fn-traits-call-once-signature.rs diff --git a/tests/ui/issues/issue-15774.rs b/tests/ui/imports/enum-variant-import-path-15774.rs similarity index 100% rename from tests/ui/issues/issue-15774.rs rename to tests/ui/imports/enum-variant-import-path-15774.rs diff --git a/tests/ui/issues/issue-15965.rs b/tests/ui/inference/return-block-type-inference-15965.rs similarity index 100% rename from tests/ui/issues/issue-15965.rs rename to tests/ui/inference/return-block-type-inference-15965.rs diff --git a/tests/ui/issues/issue-15756.rs b/tests/ui/iterators/chunk-iterator-mut-pattern.rs similarity index 100% rename from tests/ui/issues/issue-15756.rs rename to tests/ui/iterators/chunk-iterator-mut-pattern.rs diff --git a/tests/ui/issues/issue-15673.rs b/tests/ui/iterators/iterator-sum-array-15673.rs similarity index 100% rename from tests/ui/issues/issue-15673.rs rename to tests/ui/iterators/iterator-sum-array-15673.rs diff --git a/tests/ui/issues/issue-15034.rs b/tests/ui/lifetimes/explicit-lifetime-required-15034.rs similarity index 100% rename from tests/ui/issues/issue-15034.rs rename to tests/ui/lifetimes/explicit-lifetime-required-15034.rs diff --git a/tests/ui/issues/issue-15735.rs b/tests/ui/lifetimes/struct-lifetime-inference-15735.rs similarity index 100% rename from tests/ui/issues/issue-15735.rs rename to tests/ui/lifetimes/struct-lifetime-inference-15735.rs diff --git a/tests/ui/issues/issue-15167.rs b/tests/ui/macros/macro-hygiene-scope-15167.rs similarity index 100% rename from tests/ui/issues/issue-15167.rs rename to tests/ui/macros/macro-hygiene-scope-15167.rs diff --git a/tests/ui/issues/issue-15189.rs b/tests/ui/macros/macro-variable-capture-15189.rs similarity index 100% rename from tests/ui/issues/issue-15189.rs rename to tests/ui/macros/macro-variable-capture-15189.rs diff --git a/tests/ui/issues/issue-15793.rs b/tests/ui/match/nested-enum-match-optimization.rs similarity index 100% rename from tests/ui/issues/issue-15793.rs rename to tests/ui/match/nested-enum-match-optimization.rs diff --git a/tests/ui/issues/issue-15571.rs b/tests/ui/moves/match-move-same-binding-15571.rs similarity index 100% rename from tests/ui/issues/issue-15571.rs rename to tests/ui/moves/match-move-same-binding-15571.rs diff --git a/tests/ui/issues/issue-15207.rs b/tests/ui/never/never-type-method-call-15207.rs similarity index 100% rename from tests/ui/issues/issue-15207.rs rename to tests/ui/never/never-type-method-call-15207.rs diff --git a/tests/ui/issues/issue-15896.rs b/tests/ui/pattern/enum-struct-pattern-mismatch.rs similarity index 100% rename from tests/ui/issues/issue-15896.rs rename to tests/ui/pattern/enum-struct-pattern-mismatch.rs diff --git a/tests/ui/issues/issue-15381.rs b/tests/ui/pattern/refutable-pattern-for-loop-15381.rs similarity index 100% rename from tests/ui/issues/issue-15381.rs rename to tests/ui/pattern/refutable-pattern-for-loop-15381.rs diff --git a/tests/ui/issues/issue-15104.rs b/tests/ui/pattern/slice-pattern-recursion-15104.rs similarity index 100% rename from tests/ui/issues/issue-15104.rs rename to tests/ui/pattern/slice-pattern-recursion-15104.rs diff --git a/tests/ui/issues/issue-16149.rs b/tests/ui/pattern/static-binding-shadow-16149.rs similarity index 100% rename from tests/ui/issues/issue-16149.rs rename to tests/ui/pattern/static-binding-shadow-16149.rs diff --git a/tests/ui/issues/issue-15260.rs b/tests/ui/pattern/struct-field-duplicate-binding.rs similarity index 100% rename from tests/ui/issues/issue-15260.rs rename to tests/ui/pattern/struct-field-duplicate-binding.rs diff --git a/tests/ui/issues/issue-15129-rpass.rs b/tests/ui/pattern/tuple-enum-match-15129.rs similarity index 100% rename from tests/ui/issues/issue-15129-rpass.rs rename to tests/ui/pattern/tuple-enum-match-15129.rs diff --git a/tests/ui/issues/issue-16401.rs b/tests/ui/pattern/unit-type-struct-pattern-mismatch.rs similarity index 100% rename from tests/ui/issues/issue-16401.rs rename to tests/ui/pattern/unit-type-struct-pattern-mismatch.rs diff --git a/tests/ui/issues/issue-16452.rs b/tests/ui/statics/conditional-static-declaration.rs similarity index 100% rename from tests/ui/issues/issue-16452.rs rename to tests/ui/statics/conditional-static-declaration.rs diff --git a/tests/ui/issues/issue-15043.rs b/tests/ui/structs/static-struct-init-15043.rs similarity index 100% rename from tests/ui/issues/issue-15043.rs rename to tests/ui/structs/static-struct-init-15043.rs diff --git a/tests/ui/issues/issue-15444.rs b/tests/ui/traits/fn-type-trait-impl-15444.rs similarity index 100% rename from tests/ui/issues/issue-15444.rs rename to tests/ui/traits/fn-type-trait-impl-15444.rs diff --git a/tests/ui/issues/issue-15734.rs b/tests/ui/traits/index-trait-multiple-impls.rs similarity index 100% rename from tests/ui/issues/issue-15734.rs rename to tests/ui/traits/index-trait-multiple-impls.rs diff --git a/tests/ui/issues/issue-16048.rs b/tests/ui/traits/lifetime-mismatch-trait-impl.rs similarity index 100% rename from tests/ui/issues/issue-16048.rs rename to tests/ui/traits/lifetime-mismatch-trait-impl.rs From da4687bafe4ff78a9816797c3b74b6bcc0c5a3bc Mon Sep 17 00:00:00 2001 From: Alisa Sireneva Date: Fri, 25 Jul 2025 16:09:29 +0300 Subject: [PATCH 0134/1134] Link to Mutex poisoning docs from RwLock docs --- library/std/src/sync/poison/rwlock.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/library/std/src/sync/poison/rwlock.rs b/library/std/src/sync/poison/rwlock.rs index 0a50b6c2d8f1..2c92602bc878 100644 --- a/library/std/src/sync/poison/rwlock.rs +++ b/library/std/src/sync/poison/rwlock.rs @@ -46,11 +46,13 @@ use crate::sys::sync as sys; /// /// # Poisoning /// -/// An `RwLock`, like [`Mutex`], will usually become poisoned on a panic. Note, +/// An `RwLock`, like [`Mutex`], will [usually] become poisoned on a panic. Note, /// however, that an `RwLock` may only be poisoned if a panic occurs while it is /// locked exclusively (write mode). If a panic occurs in any reader, then the /// lock will not be poisoned. /// +/// [usually]: super::Mutex#poisoning +/// /// # Examples /// /// ``` From 5c7418b38afeb0f7256917b7bbee481b854e3113 Mon Sep 17 00:00:00 2001 From: Philipp Krones Date: Fri, 25 Jul 2025 15:54:22 +0200 Subject: [PATCH 0135/1134] Merge commit '1db89a1b1ca87f24bf22d0bad21d14b2d81b3e99' into clippy-subtree-update --- .github/workflows/feature_freeze.yml | 36 ++- .gitignore | 2 + clippy_dev/src/fmt.rs | 4 +- clippy_lints/src/approx_const.rs | 33 ++- .../src/arbitrary_source_item_ordering.rs | 15 +- clippy_lints/src/arc_with_non_send_sync.rs | 2 +- clippy_lints/src/attrs/useless_attribute.rs | 1 + .../casts/confusing_method_to_numeric_cast.rs | 5 +- clippy_lints/src/casts/fn_to_numeric_cast.rs | 33 +-- .../src/casts/fn_to_numeric_cast_any.rs | 9 +- .../fn_to_numeric_cast_with_truncation.rs | 33 +-- clippy_lints/src/casts/ptr_as_ptr.rs | 16 +- clippy_lints/src/cognitive_complexity.rs | 1 - clippy_lints/src/copies.rs | 16 +- clippy_lints/src/derive.rs | 5 + clippy_lints/src/disallowed_macros.rs | 8 +- clippy_lints/src/doc/mod.rs | 1 - clippy_lints/src/empty_with_brackets.rs | 12 +- clippy_lints/src/escape.rs | 10 +- clippy_lints/src/eta_reduction.rs | 6 - clippy_lints/src/fallible_impl_from.rs | 8 +- clippy_lints/src/format_args.rs | 12 +- clippy_lints/src/from_over_into.rs | 2 +- clippy_lints/src/functions/must_use.rs | 29 +- clippy_lints/src/if_then_some_else_none.rs | 7 +- clippy_lints/src/incompatible_msrv.rs | 149 +++++++--- clippy_lints/src/ineffective_open_options.rs | 98 +++---- clippy_lints/src/infallible_try_from.rs | 8 +- clippy_lints/src/item_name_repetitions.rs | 4 +- clippy_lints/src/iter_without_into_iter.rs | 10 +- clippy_lints/src/large_enum_variant.rs | 5 +- clippy_lints/src/legacy_numeric_constants.rs | 56 ++-- clippy_lints/src/len_zero.rs | 15 +- clippy_lints/src/loops/needless_range_loop.rs | 22 +- clippy_lints/src/loops/never_loop.rs | 139 +++++++-- clippy_lints/src/macro_use.rs | 4 +- clippy_lints/src/manual_abs_diff.rs | 13 +- clippy_lints/src/manual_assert.rs | 3 +- clippy_lints/src/matches/single_match.rs | 21 +- clippy_lints/src/methods/expect_fun_call.rs | 176 ++++-------- .../src/methods/filter_map_bool_then.rs | 10 +- clippy_lints/src/methods/manual_inspect.rs | 1 - clippy_lints/src/methods/mod.rs | 19 +- clippy_lints/src/methods/or_fun_call.rs | 26 +- clippy_lints/src/missing_fields_in_debug.rs | 4 +- clippy_lints/src/missing_inline.rs | 25 +- clippy_lints/src/missing_trait_methods.rs | 4 +- .../src/mixed_read_write_in_expression.rs | 13 +- clippy_lints/src/mut_reference.rs | 2 +- clippy_lints/src/needless_for_each.rs | 21 +- clippy_lints/src/needless_pass_by_value.rs | 12 +- clippy_lints/src/new_without_default.rs | 9 +- .../src/operators/arithmetic_side_effects.rs | 51 ++-- .../src/operators/manual_is_multiple_of.rs | 25 +- clippy_lints/src/pattern_type_mismatch.rs | 6 + clippy_lints/src/ptr.rs | 17 +- clippy_lints/src/ranges.rs | 264 +++++++++++++----- clippy_lints/src/same_name_method.rs | 17 +- clippy_lints/src/unused_async.rs | 29 +- clippy_lints/src/unused_self.rs | 20 +- clippy_lints/src/unused_trait_names.rs | 4 +- clippy_lints/src/useless_conversion.rs | 53 ++-- .../derive_deserialize_allowing_unknown.rs | 7 +- .../src/lint_without_lint_pass.rs | 7 +- clippy_lints_internal/src/msrv_attr_impl.rs | 5 +- clippy_utils/README.md | 2 +- clippy_utils/src/diagnostics.rs | 11 +- clippy_utils/src/lib.rs | 45 ++- clippy_utils/src/paths.rs | 9 +- clippy_utils/src/sym.rs | 3 + clippy_utils/src/ty/mod.rs | 5 +- clippy_utils/src/ty/type_certainty/mod.rs | 74 +++-- clippy_utils/src/usage.rs | 42 +++ rust-toolchain.toml | 2 +- rustc_tools_util/src/lib.rs | 5 +- tests/compile-test.rs | 9 +- ..._incompatible_msrv_in_tests.enabled.stderr | 2 + .../enum_variant_size.stderr | 2 +- tests/ui/approx_const.rs | 15 + tests/ui/approx_const.stderr | 34 ++- tests/ui/arc_with_non_send_sync.stderr | 6 +- tests/ui/arithmetic_side_effects.rs | 14 + tests/ui/arithmetic_side_effects.stderr | 4 +- tests/ui/assign_ops.fixed | 1 + tests/ui/assign_ops.rs | 1 + tests/ui/auxiliary/external_item.rs | 2 +- tests/ui/checked_conversions.fixed | 2 +- tests/ui/checked_conversions.rs | 4 +- tests/ui/checked_conversions.stderr | 4 +- tests/ui/expect.rs | 19 ++ tests/ui/expect.stderr | 34 ++- tests/ui/expect_fun_call.fixed | 34 ++- tests/ui/expect_fun_call.rs | 24 ++ tests/ui/expect_fun_call.stderr | 36 ++- tests/ui/filter_map_bool_then.fixed | 21 ++ tests/ui/filter_map_bool_then.rs | 21 ++ tests/ui/filter_map_bool_then.stderr | 8 +- tests/ui/flat_map_identity.fixed | 13 + tests/ui/flat_map_identity.rs | 13 + tests/ui/flat_map_identity.stderr | 8 +- tests/ui/if_then_some_else_none.fixed | 43 +++ tests/ui/if_then_some_else_none.rs | 68 +++++ tests/ui/if_then_some_else_none.stderr | 60 +++- tests/ui/if_then_some_else_none_unfixable.rs | 35 +++ .../if_then_some_else_none_unfixable.stderr | 28 ++ tests/ui/incompatible_msrv.rs | 111 +++++++- tests/ui/incompatible_msrv.stderr | 96 +++++-- tests/ui/large_enum_variant.32bit.stderr | 36 +-- tests/ui/large_enum_variant.64bit.stderr | 40 +-- tests/ui/large_enum_variant_no_std.rs | 8 + tests/ui/large_enum_variant_no_std.stderr | 22 ++ tests/ui/legacy_numeric_constants.fixed | 22 ++ tests/ui/legacy_numeric_constants.rs | 22 ++ tests/ui/legacy_numeric_constants.stderr | 110 +++++++- tests/ui/manual_abs_diff.fixed | 4 + tests/ui/manual_abs_diff.rs | 9 + tests/ui/manual_abs_diff.stderr | 13 +- tests/ui/manual_assert.edition2018.stderr | 20 +- tests/ui/manual_assert.edition2021.stderr | 20 +- tests/ui/manual_assert.rs | 14 + tests/ui/manual_is_multiple_of.fixed | 78 ++++++ tests/ui/manual_is_multiple_of.rs | 78 ++++++ tests/ui/manual_is_multiple_of.stderr | 32 ++- tests/ui/map_identity.fixed | 12 + tests/ui/map_identity.rs | 12 + tests/ui/map_identity.stderr | 8 +- tests/ui/missing_inline.rs | 17 ++ tests/ui/module_name_repetitions.rs | 18 ++ tests/ui/must_use_candidates.fixed | 15 +- tests/ui/must_use_candidates.stderr | 49 +++- tests/ui/needless_for_each_fixable.fixed | 6 + tests/ui/needless_for_each_fixable.rs | 6 + tests/ui/needless_for_each_fixable.stderr | 8 +- tests/ui/needless_range_loop.rs | 25 ++ tests/ui/never_loop.rs | 32 +++ tests/ui/never_loop.stderr | 71 ++++- tests/ui/or_fun_call.fixed | 4 + tests/ui/or_fun_call.rs | 4 + tests/ui/or_fun_call.stderr | 50 ++-- .../auxiliary/external.rs | 13 + tests/ui/pattern_type_mismatch/syntax.rs | 9 + tests/ui/pattern_type_mismatch/syntax.stderr | 18 +- tests/ui/ptr_arg.rs | 140 ++++++++-- tests/ui/ptr_arg.stderr | 64 ++++- tests/ui/ptr_as_ptr.fixed | 8 + tests/ui/ptr_as_ptr.rs | 8 + tests/ui/ptr_as_ptr.stderr | 8 +- tests/ui/range_plus_minus_one.fixed | 134 ++++++++- tests/ui/range_plus_minus_one.rs | 126 ++++++++- tests/ui/range_plus_minus_one.stderr | 78 ++++-- .../ui/single_match_else_deref_patterns.fixed | 53 ++++ tests/ui/single_match_else_deref_patterns.rs | 94 +++++++ .../single_match_else_deref_patterns.stderr | 188 +++++++++++++ tests/ui/unsafe_derive_deserialize.rs | 29 ++ tests/ui/unsafe_derive_deserialize.stderr | 11 +- tests/ui/unused_async.rs | 10 + tests/ui/unused_trait_names.fixed | 4 +- tests/ui/unused_trait_names.rs | 2 +- tests/ui/unused_trait_names.stderr | 13 +- tests/ui/used_underscore_items.rs | 4 +- tests/ui/useless_attribute.fixed | 12 + tests/ui/useless_attribute.rs | 12 + triagebot.toml | 1 + util/gh-pages/index_template.html | 250 ++++++++--------- util/gh-pages/script.js | 23 +- util/gh-pages/style.css | 88 +++--- 166 files changed, 3790 insertions(+), 1125 deletions(-) create mode 100644 tests/ui/if_then_some_else_none_unfixable.rs create mode 100644 tests/ui/if_then_some_else_none_unfixable.stderr create mode 100644 tests/ui/large_enum_variant_no_std.rs create mode 100644 tests/ui/large_enum_variant_no_std.stderr create mode 100644 tests/ui/pattern_type_mismatch/auxiliary/external.rs create mode 100644 tests/ui/single_match_else_deref_patterns.fixed create mode 100644 tests/ui/single_match_else_deref_patterns.rs create mode 100644 tests/ui/single_match_else_deref_patterns.stderr diff --git a/.github/workflows/feature_freeze.yml b/.github/workflows/feature_freeze.yml index 7ad58af77d4a..ec59be3e7f67 100644 --- a/.github/workflows/feature_freeze.yml +++ b/.github/workflows/feature_freeze.yml @@ -20,16 +20,26 @@ jobs: # of the pull request, as malicious code would be able to access the private # GitHub token. steps: - - name: Check PR Changes - id: pr-changes - run: echo "::set-output name=changes::${{ toJson(github.event.pull_request.changed_files) }}" - - - name: Create Comment - if: steps.pr-changes.outputs.changes != '[]' - run: | - # Use GitHub API to create a comment on the PR - PR_NUMBER=${{ github.event.pull_request.number }} - COMMENT="**Seems that you are trying to add a new lint!**\nWe are currently in a [feature freeze](https://doc.rust-lang.org/nightly/clippy/development/feature_freeze.html), so we are delaying all lint-adding PRs to September 18 and focusing on bugfixes.\nThanks a lot for your contribution, and sorry for the inconvenience.\nWith ❤ from the Clippy team\n\n@rustbot note Feature-freeze\n@rustbot blocked\n@rustbot label +A-lint\n" - GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} - COMMENT_URL="https://api.github.com/repos/${{ github.repository }}/issues/${PR_NUMBER}/comments" - curl -s -H "Authorization: token ${GITHUB_TOKEN}" -X POST $COMMENT_URL -d "{\"body\":\"$COMMENT\"}" + - name: Add freeze warning comment + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + COMMENT=$(echo "**Seems that you are trying to add a new lint!**\n\ + \n\ + We are currently in a [feature freeze](https://doc.rust-lang.org/nightly/clippy/development/feature_freeze.html), so we are delaying all lint-adding PRs to September 18 and [focusing on bugfixes](https://github.com/rust-lang/rust-clippy/issues/15086).\n\ + \n\ + Thanks a lot for your contribution, and sorry for the inconvenience.\n\ + \n\ + With ❤ from the Clippy team.\n\ + \n\ + @rustbot note Feature-freeze\n\ + @rustbot blocked\n\ + @rustbot label +A-lint" + ) + curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \ + -H "Content-Type: application/vnd.github.raw+json" \ + -X POST \ + --data "{\"body\":\"${COMMENT}\"}" \ + "https://api.github.com/repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" diff --git a/.gitignore b/.gitignore index a7c25b29021f..36a4cdc1c352 100644 --- a/.gitignore +++ b/.gitignore @@ -19,8 +19,10 @@ out # Generated by Cargo *Cargo.lock +!/clippy_test_deps/Cargo.lock /target /clippy_lints/target +/clippy_lints_internal/target /clippy_utils/target /clippy_dev/target /lintcheck/target diff --git a/clippy_dev/src/fmt.rs b/clippy_dev/src/fmt.rs index bd9e57c9f6da..2b2138d3108d 100644 --- a/clippy_dev/src/fmt.rs +++ b/clippy_dev/src/fmt.rs @@ -3,7 +3,7 @@ use crate::utils::{ walk_dir_no_dot_or_target, }; use itertools::Itertools; -use rustc_lexer::{TokenKind, tokenize}; +use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize}; use std::fmt::Write; use std::fs; use std::io::{self, Read}; @@ -92,7 +92,7 @@ fn fmt_conf(check: bool) -> Result<(), Error> { let mut fields = Vec::new(); let mut state = State::Start; - for (i, t) in tokenize(conf) + for (i, t) in tokenize(conf, FrontmatterAllowed::No) .map(|x| { let start = pos; pos += x.len; diff --git a/clippy_lints/src/approx_const.rs b/clippy_lints/src/approx_const.rs index 5ed4c82634aa..184fbbf77962 100644 --- a/clippy_lints/src/approx_const.rs +++ b/clippy_lints/src/approx_const.rs @@ -92,9 +92,11 @@ impl LateLintPass<'_> for ApproxConstant { impl ApproxConstant { fn check_known_consts(&self, cx: &LateContext<'_>, span: Span, s: symbol::Symbol, module: &str) { let s = s.as_str(); - if s.parse::().is_ok() { + if let Ok(maybe_constant) = s.parse::() { for &(constant, name, min_digits, msrv) in &KNOWN_CONSTS { - if is_approx_const(constant, s, min_digits) && msrv.is_none_or(|msrv| self.msrv.meets(cx, msrv)) { + if is_approx_const(constant, s, maybe_constant, min_digits) + && msrv.is_none_or(|msrv| self.msrv.meets(cx, msrv)) + { span_lint_and_help( cx, APPROX_CONSTANT, @@ -112,18 +114,35 @@ impl ApproxConstant { impl_lint_pass!(ApproxConstant => [APPROX_CONSTANT]); +fn count_digits_after_dot(input: &str) -> usize { + input + .char_indices() + .find(|(_, ch)| *ch == '.') + .map_or(0, |(i, _)| input.len() - i - 1) +} + /// Returns `false` if the number of significant figures in `value` are /// less than `min_digits`; otherwise, returns true if `value` is equal -/// to `constant`, rounded to the number of digits present in `value`. +/// to `constant`, rounded to the number of significant digits present in `value`. #[must_use] -fn is_approx_const(constant: f64, value: &str, min_digits: usize) -> bool { +fn is_approx_const(constant: f64, value: &str, f_value: f64, min_digits: usize) -> bool { if value.len() <= min_digits { + // The value is not precise enough false - } else if constant.to_string().starts_with(value) { - // The value is a truncated constant + } else if f_value.to_string().len() > min_digits && constant.to_string().starts_with(&f_value.to_string()) { + // The value represents the same value true } else { - let round_const = format!("{constant:.*}", value.len() - 2); + // The value is a truncated constant + + // Print constant with numeric formatting (`0`), with the length of `value` as minimum width + // (`value_len$`), and with the same precision as `value` (`.value_prec$`). + // See https://doc.rust-lang.org/std/fmt/index.html. + let round_const = format!( + "{constant:0value_len$.value_prec$}", + value_len = value.len(), + value_prec = count_digits_after_dot(value) + ); value == round_const } } diff --git a/clippy_lints/src/arbitrary_source_item_ordering.rs b/clippy_lints/src/arbitrary_source_item_ordering.rs index a9d3015ce5c4..7b4cf0336741 100644 --- a/clippy_lints/src/arbitrary_source_item_ordering.rs +++ b/clippy_lints/src/arbitrary_source_item_ordering.rs @@ -8,11 +8,11 @@ use clippy_utils::diagnostics::span_lint_and_note; use clippy_utils::is_cfg_test; use rustc_attr_data_structures::AttributeKind; use rustc_hir::{ - Attribute, FieldDef, HirId, IsAuto, ImplItemId, Item, ItemKind, Mod, OwnerId, QPath, TraitItemId, TyKind, - Variant, VariantData, + Attribute, FieldDef, HirId, ImplItemId, IsAuto, Item, ItemKind, Mod, OwnerId, QPath, TraitItemId, TyKind, Variant, + VariantData, }; -use rustc_middle::ty::AssocKind; use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_middle::ty::AssocKind; use rustc_session::impl_lint_pass; use rustc_span::Ident; @@ -469,13 +469,14 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering { /// This is implemented here because `rustc_hir` is not a dependency of /// `clippy_config`. fn convert_assoc_item_kind(cx: &LateContext<'_>, owner_id: OwnerId) -> SourceItemOrderingTraitAssocItemKind { - let kind = cx.tcx.associated_item(owner_id.def_id).kind; - #[allow(clippy::enum_glob_use)] // Very local glob use for legibility. use SourceItemOrderingTraitAssocItemKind::*; + + let kind = cx.tcx.associated_item(owner_id.def_id).kind; + match kind { - AssocKind::Const{..} => Const, - AssocKind::Type {..}=> Type, + AssocKind::Const { .. } => Const, + AssocKind::Type { .. } => Type, AssocKind::Fn { .. } => Fn, } } diff --git a/clippy_lints/src/arc_with_non_send_sync.rs b/clippy_lints/src/arc_with_non_send_sync.rs index 9e09fb5bb439..085029a744be 100644 --- a/clippy_lints/src/arc_with_non_send_sync.rs +++ b/clippy_lints/src/arc_with_non_send_sync.rs @@ -73,7 +73,7 @@ impl<'tcx> LateLintPass<'tcx> for ArcWithNonSendSync { diag.note(format!( "`Arc<{arg_ty}>` is not `Send` and `Sync` as `{arg_ty}` is {reason}" )); - diag.help("if the `Arc` will not used be across threads replace it with an `Rc`"); + diag.help("if the `Arc` will not be used across threads replace it with an `Rc`"); diag.help(format!( "otherwise make `{arg_ty}` `Send` and `Sync` or consider a wrapper type such as `Mutex`" )); diff --git a/clippy_lints/src/attrs/useless_attribute.rs b/clippy_lints/src/attrs/useless_attribute.rs index 4059f9603c33..b9b5cedb5aa7 100644 --- a/clippy_lints/src/attrs/useless_attribute.rs +++ b/clippy_lints/src/attrs/useless_attribute.rs @@ -36,6 +36,7 @@ pub(super) fn check(cx: &EarlyContext<'_>, item: &Item, attrs: &[Attribute]) { | sym::unused_braces | sym::unused_import_braces | sym::unused_imports + | sym::redundant_imports ) { return; diff --git a/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs b/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs index 769cc120c950..849de22cfbaa 100644 --- a/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs +++ b/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs @@ -59,9 +59,8 @@ fn get_const_name_and_ty_name( pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) { // We allow casts from any function type to any function type. - match cast_to.kind() { - ty::FnDef(..) | ty::FnPtr(..) => return, - _ => { /* continue to checks */ }, + if cast_to.is_fn() { + return; } if let ty::FnDef(def_id, generics) = cast_from.kind() diff --git a/clippy_lints/src/casts/fn_to_numeric_cast.rs b/clippy_lints/src/casts/fn_to_numeric_cast.rs index 55e27a05f3c0..c5d9643f56a5 100644 --- a/clippy_lints/src/casts/fn_to_numeric_cast.rs +++ b/clippy_lints/src/casts/fn_to_numeric_cast.rs @@ -3,7 +3,7 @@ use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::Ty; use super::{FN_TO_NUMERIC_CAST, utils}; @@ -13,23 +13,20 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, return; }; - match cast_from.kind() { - ty::FnDef(..) | ty::FnPtr(..) => { - let mut applicability = Applicability::MaybeIncorrect; + if cast_from.is_fn() { + let mut applicability = Applicability::MaybeIncorrect; - if to_nbits >= cx.tcx.data_layout.pointer_size().bits() && !cast_to.is_usize() { - let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability); - span_lint_and_sugg( - cx, - FN_TO_NUMERIC_CAST, - expr.span, - format!("casting function pointer `{from_snippet}` to `{cast_to}`"), - "try", - format!("{from_snippet} as usize"), - applicability, - ); - } - }, - _ => {}, + if to_nbits >= cx.tcx.data_layout.pointer_size().bits() && !cast_to.is_usize() { + let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability); + span_lint_and_sugg( + cx, + FN_TO_NUMERIC_CAST, + expr.span, + format!("casting function pointer `{from_snippet}` to `{cast_to}`"), + "try", + format!("{from_snippet} as usize"), + applicability, + ); + } } } diff --git a/clippy_lints/src/casts/fn_to_numeric_cast_any.rs b/clippy_lints/src/casts/fn_to_numeric_cast_any.rs index b22e8f4ee891..43ee91af6e5a 100644 --- a/clippy_lints/src/casts/fn_to_numeric_cast_any.rs +++ b/clippy_lints/src/casts/fn_to_numeric_cast_any.rs @@ -3,18 +3,17 @@ use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::Ty; use super::FN_TO_NUMERIC_CAST_ANY; pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) { // We allow casts from any function type to any function type. - match cast_to.kind() { - ty::FnDef(..) | ty::FnPtr(..) => return, - _ => { /* continue to checks */ }, + if cast_to.is_fn() { + return; } - if let ty::FnDef(..) | ty::FnPtr(..) = cast_from.kind() { + if cast_from.is_fn() { let mut applicability = Applicability::MaybeIncorrect; let from_snippet = snippet_with_applicability(cx, cast_expr.span, "..", &mut applicability); diff --git a/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs b/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs index 4da79205e208..9a2e44e07d4b 100644 --- a/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs +++ b/clippy_lints/src/casts/fn_to_numeric_cast_with_truncation.rs @@ -3,7 +3,7 @@ use clippy_utils::source::snippet_with_applicability; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::Ty; use super::{FN_TO_NUMERIC_CAST_WITH_TRUNCATION, utils}; @@ -12,23 +12,20 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, let Some(to_nbits) = utils::int_ty_to_nbits(cx.tcx, cast_to) else { return; }; - match cast_from.kind() { - ty::FnDef(..) | ty::FnPtr(..) => { - let mut applicability = Applicability::MaybeIncorrect; - let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability); + if cast_from.is_fn() { + let mut applicability = Applicability::MaybeIncorrect; + let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability); - if to_nbits < cx.tcx.data_layout.pointer_size().bits() { - span_lint_and_sugg( - cx, - FN_TO_NUMERIC_CAST_WITH_TRUNCATION, - expr.span, - format!("casting function pointer `{from_snippet}` to `{cast_to}`, which truncates the value"), - "try", - format!("{from_snippet} as usize"), - applicability, - ); - } - }, - _ => {}, + if to_nbits < cx.tcx.data_layout.pointer_size().bits() { + span_lint_and_sugg( + cx, + FN_TO_NUMERIC_CAST_WITH_TRUNCATION, + expr.span, + format!("casting function pointer `{from_snippet}` to `{cast_to}`, which truncates the value"), + "try", + format!("{from_snippet} as usize"), + applicability, + ); + } } } diff --git a/clippy_lints/src/casts/ptr_as_ptr.rs b/clippy_lints/src/casts/ptr_as_ptr.rs index 6f944914b8fd..ee0f3fa81c6d 100644 --- a/clippy_lints/src/casts/ptr_as_ptr.rs +++ b/clippy_lints/src/casts/ptr_as_ptr.rs @@ -4,10 +4,9 @@ use clippy_utils::source::snippet_with_applicability; use clippy_utils::sugg::Sugg; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, Mutability, QPath, TyKind}; -use rustc_hir_pretty::qpath_to_string; use rustc_lint::LateContext; use rustc_middle::ty; -use rustc_span::sym; +use rustc_span::{Span, sym}; use super::PTR_AS_PTR; @@ -74,7 +73,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, msrv: Msrv) { let (help, final_suggestion) = if let Some(method) = omit_cast.corresponding_item() { // don't force absolute path - let method = qpath_to_string(&cx.tcx, method); + let method = snippet_with_applicability(cx, qpath_span_without_turbofish(method), "..", &mut app); ("try call directly", format!("{method}{turbofish}()")) } else { let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut app); @@ -96,3 +95,14 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, msrv: Msrv) { ); } } + +fn qpath_span_without_turbofish(qpath: &QPath<'_>) -> Span { + if let QPath::Resolved(_, path) = qpath + && let [.., last_ident] = path.segments + && last_ident.args.is_some() + { + return qpath.span().shrink_to_lo().to(last_ident.ident.span); + } + + qpath.span() +} diff --git a/clippy_lints/src/cognitive_complexity.rs b/clippy_lints/src/cognitive_complexity.rs index d5d937d91338..518535e8c8bf 100644 --- a/clippy_lints/src/cognitive_complexity.rs +++ b/clippy_lints/src/cognitive_complexity.rs @@ -110,7 +110,6 @@ impl CognitiveComplexity { FnKind::ItemFn(ident, _, _) | FnKind::Method(ident, _) => ident.span, FnKind::Closure => { let header_span = body_span.with_hi(decl.output.span().lo()); - #[expect(clippy::range_plus_one)] if let Some(range) = header_span.map_range(cx, |_, src, range| { let mut idxs = src.get(range.clone())?.match_indices('|'); Some(range.start + idxs.next()?.0..range.start + idxs.next()?.0 + 1) diff --git a/clippy_lints/src/copies.rs b/clippy_lints/src/copies.rs index 27918698cd6b..4bd34527d21f 100644 --- a/clippy_lints/src/copies.rs +++ b/clippy_lints/src/copies.rs @@ -1,5 +1,6 @@ use clippy_config::Conf; use clippy_utils::diagnostics::{span_lint, span_lint_and_note, span_lint_and_then}; +use clippy_utils::higher::has_let_expr; use clippy_utils::source::{IntoSpan, SpanRangeExt, first_line_of_span, indent_of, reindent_multiline, snippet}; use clippy_utils::ty::{InteriorMut, needs_ordered_drop}; use clippy_utils::visitors::for_each_expr_without_closures; @@ -11,7 +12,7 @@ use clippy_utils::{ use core::iter; use core::ops::ControlFlow; use rustc_errors::Applicability; -use rustc_hir::{BinOpKind, Block, Expr, ExprKind, HirId, HirIdSet, LetStmt, Node, Stmt, StmtKind, intravisit}; +use rustc_hir::{Block, Expr, ExprKind, HirId, HirIdSet, LetStmt, Node, Stmt, StmtKind, intravisit}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::TyCtxt; use rustc_session::impl_lint_pass; @@ -189,24 +190,13 @@ impl<'tcx> LateLintPass<'tcx> for CopyAndPaste<'tcx> { } } -/// Checks if the given expression is a let chain. -fn contains_let(e: &Expr<'_>) -> bool { - match e.kind { - ExprKind::Let(..) => true, - ExprKind::Binary(op, lhs, rhs) if op.node == BinOpKind::And => { - matches!(lhs.kind, ExprKind::Let(..)) || contains_let(rhs) - }, - _ => false, - } -} - fn lint_if_same_then_else(cx: &LateContext<'_>, conds: &[&Expr<'_>], blocks: &[&Block<'_>]) -> bool { let mut eq = SpanlessEq::new(cx); blocks .array_windows::<2>() .enumerate() .fold(true, |all_eq, (i, &[lhs, rhs])| { - if eq.eq_block(lhs, rhs) && !contains_let(conds[i]) && conds.get(i + 1).is_none_or(|e| !contains_let(e)) { + if eq.eq_block(lhs, rhs) && !has_let_expr(conds[i]) && conds.get(i + 1).is_none_or(|e| !has_let_expr(e)) { span_lint_and_note( cx, IF_SAME_THEN_ELSE, diff --git a/clippy_lints/src/derive.rs b/clippy_lints/src/derive.rs index 062f7cef3a72..49dd1bb09c61 100644 --- a/clippy_lints/src/derive.rs +++ b/clippy_lints/src/derive.rs @@ -432,6 +432,11 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> { fn visit_expr(&mut self, expr: &'tcx Expr<'_>) -> Self::Result { if let ExprKind::Block(block, _) = expr.kind && block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) + && block + .span + .source_callee() + .and_then(|expr| expr.macro_def_id) + .is_none_or(|did| !self.cx.tcx.is_diagnostic_item(sym::pin_macro, did)) { return ControlFlow::Break(()); } diff --git a/clippy_lints/src/disallowed_macros.rs b/clippy_lints/src/disallowed_macros.rs index d55aeae98ede..23e7c7251cf1 100644 --- a/clippy_lints/src/disallowed_macros.rs +++ b/clippy_lints/src/disallowed_macros.rs @@ -72,11 +72,11 @@ pub struct DisallowedMacros { // When a macro is disallowed in an early pass, it's stored // and emitted during the late pass. This happens for attributes. - earlies: AttrStorage, + early_macro_cache: AttrStorage, } impl DisallowedMacros { - pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf, earlies: AttrStorage) -> Self { + pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf, early_macro_cache: AttrStorage) -> Self { let (disallowed, _) = create_disallowed_map( tcx, &conf.disallowed_macros, @@ -89,7 +89,7 @@ impl DisallowedMacros { disallowed, seen: FxHashSet::default(), derive_src: None, - earlies, + early_macro_cache, } } @@ -130,7 +130,7 @@ impl_lint_pass!(DisallowedMacros => [DISALLOWED_MACROS]); impl LateLintPass<'_> for DisallowedMacros { fn check_crate(&mut self, cx: &LateContext<'_>) { // once we check a crate in the late pass we can emit the early pass lints - if let Some(attr_spans) = self.earlies.clone().0.get() { + if let Some(attr_spans) = self.early_macro_cache.clone().0.get() { for span in attr_spans { self.check(cx, *span, None); } diff --git a/clippy_lints/src/doc/mod.rs b/clippy_lints/src/doc/mod.rs index 22b781b89294..ea0da0d24675 100644 --- a/clippy_lints/src/doc/mod.rs +++ b/clippy_lints/src/doc/mod.rs @@ -1232,7 +1232,6 @@ fn check_doc<'a, Events: Iterator, Range) -> Option> { if range.end < range.start { return None; diff --git a/clippy_lints/src/empty_with_brackets.rs b/clippy_lints/src/empty_with_brackets.rs index 4414aebbf9a3..f2757407ba57 100644 --- a/clippy_lints/src/empty_with_brackets.rs +++ b/clippy_lints/src/empty_with_brackets.rs @@ -92,8 +92,10 @@ impl_lint_pass!(EmptyWithBrackets => [EMPTY_STRUCTS_WITH_BRACKETS, EMPTY_ENUM_VA impl LateLintPass<'_> for EmptyWithBrackets { fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { + // FIXME: handle `struct $name {}` if let ItemKind::Struct(ident, _, var_data) = &item.kind && !item.span.from_expansion() + && !ident.span.from_expansion() && has_brackets(var_data) && let span_after_ident = item.span.with_lo(ident.span.hi()) && has_no_fields(cx, var_data, span_after_ident) @@ -116,10 +118,12 @@ impl LateLintPass<'_> for EmptyWithBrackets { } fn check_variant(&mut self, cx: &LateContext<'_>, variant: &Variant<'_>) { - // the span of the parentheses/braces - let span_after_ident = variant.span.with_lo(variant.ident.span.hi()); - - if has_no_fields(cx, &variant.data, span_after_ident) { + // FIXME: handle `$name {}` + if !variant.span.from_expansion() + && !variant.ident.span.from_expansion() + && let span_after_ident = variant.span.with_lo(variant.ident.span.hi()) + && has_no_fields(cx, &variant.data, span_after_ident) + { match variant.data { VariantData::Struct { .. } => { // Empty struct variants can be linted immediately diff --git a/clippy_lints/src/escape.rs b/clippy_lints/src/escape.rs index db2fea1aae95..fc224fa5f924 100644 --- a/clippy_lints/src/escape.rs +++ b/clippy_lints/src/escape.rs @@ -1,8 +1,8 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_hir; use rustc_abi::ExternAbi; -use rustc_hir::{Body, FnDecl, HirId, HirIdSet, Node, Pat, PatKind, intravisit}; use rustc_hir::def::DefKind; +use rustc_hir::{Body, FnDecl, HirId, HirIdSet, Node, Pat, PatKind, intravisit}; use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::FakeReadCause; @@ -87,16 +87,14 @@ impl<'tcx> LateLintPass<'tcx> for BoxedLocal { let mut trait_self_ty = None; match cx.tcx.def_kind(parent_id) { // If the method is an impl for a trait, don't warn. - DefKind::Impl { of_trait: true } => { - return - } + DefKind::Impl { of_trait: true } => return, // find `self` ty for this trait if relevant DefKind::Trait => { trait_self_ty = Some(TraitRef::identity(cx.tcx, parent_id.to_def_id()).self_ty()); - } + }, - _ => {} + _ => {}, } let mut v = EscapeDelegate { diff --git a/clippy_lints/src/eta_reduction.rs b/clippy_lints/src/eta_reduction.rs index 0288747d6f3e..9b627678bd35 100644 --- a/clippy_lints/src/eta_reduction.rs +++ b/clippy_lints/src/eta_reduction.rs @@ -29,12 +29,6 @@ declare_clippy_lint! { /// Needlessly creating a closure adds code for no benefit /// and gives the optimizer more work. /// - /// ### Known problems - /// If creating the closure inside the closure has a side- - /// effect then moving the closure creation out will change when that side- - /// effect runs. - /// See [#1439](https://github.com/rust-lang/rust-clippy/issues/1439) for more details. - /// /// ### Example /// ```rust,ignore /// xs.map(|x| foo(x)) diff --git a/clippy_lints/src/fallible_impl_from.rs b/clippy_lints/src/fallible_impl_from.rs index 552cd721f4ef..fdfcbb540bce 100644 --- a/clippy_lints/src/fallible_impl_from.rs +++ b/clippy_lints/src/fallible_impl_from.rs @@ -64,8 +64,8 @@ impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { } fn lint_impl_body(cx: &LateContext<'_>, item_def_id: hir::OwnerId, impl_span: Span) { - use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::Expr; + use rustc_hir::intravisit::{self, Visitor}; struct FindPanicUnwrap<'a, 'tcx> { lcx: &'a LateContext<'tcx>, @@ -96,10 +96,12 @@ fn lint_impl_body(cx: &LateContext<'_>, item_def_id: hir::OwnerId, impl_span: Sp } } - for impl_item in cx.tcx.associated_items(item_def_id) + for impl_item in cx + .tcx + .associated_items(item_def_id) .filter_by_name_unhygienic_and_kind(sym::from, ty::AssocTag::Fn) { - let impl_item_def_id= impl_item.def_id.expect_local(); + let impl_item_def_id = impl_item.def_id.expect_local(); // check the body for `begin_panic` or `unwrap` let body = cx.tcx.hir_body_owned_by(impl_item_def_id); diff --git a/clippy_lints/src/format_args.rs b/clippy_lints/src/format_args.rs index 16c58ecb455e..a251f15ba3da 100644 --- a/clippy_lints/src/format_args.rs +++ b/clippy_lints/src/format_args.rs @@ -17,7 +17,7 @@ use rustc_ast::{ FormatArgPosition, FormatArgPositionKind, FormatArgsPiece, FormatArgumentKind, FormatCount, FormatOptions, FormatPlaceholder, FormatTrait, }; -use rustc_attr_data_structures::RustcVersion; +use rustc_attr_data_structures::{AttributeKind, RustcVersion, find_attr}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_errors::SuggestionStyle::{CompletelyHidden, ShowCode}; @@ -30,7 +30,6 @@ use rustc_span::edition::Edition::Edition2021; use rustc_span::{Span, Symbol, sym}; use rustc_trait_selection::infer::TyCtxtInferExt; use rustc_trait_selection::traits::{Obligation, ObligationCause, Selection, SelectionContext}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; declare_clippy_lint! { /// ### What it does @@ -129,6 +128,7 @@ declare_clippy_lint! { /// # let width = 1; /// # let prec = 2; /// format!("{}", var); + /// format!("{:?}", var); /// format!("{v:?}", v = var); /// format!("{0} {0}", var); /// format!("{0:1$}", var, width); @@ -141,6 +141,7 @@ declare_clippy_lint! { /// # let prec = 2; /// format!("{var}"); /// format!("{var:?}"); + /// format!("{var:?}"); /// format!("{var} {var}"); /// format!("{var:width$}"); /// format!("{var:.prec$}"); @@ -164,7 +165,7 @@ declare_clippy_lint! { /// nothing will be suggested, e.g. `println!("{0}={1}", var, 1+2)`. #[clippy::version = "1.66.0"] pub UNINLINED_FORMAT_ARGS, - style, + pedantic, "using non-inlined variables in `format!` calls" } @@ -657,7 +658,10 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> { }; let selection = SelectionContext::new(&infcx).select(&obligation); let derived = if let Ok(Some(Selection::UserDefined(data))) = selection { - find_attr!(tcx.get_all_attrs(data.impl_def_id), AttributeKind::AutomaticallyDerived(..)) + find_attr!( + tcx.get_all_attrs(data.impl_def_id), + AttributeKind::AutomaticallyDerived(..) + ) } else { false }; diff --git a/clippy_lints/src/from_over_into.rs b/clippy_lints/src/from_over_into.rs index 85b40ba7419b..1da6952eb64c 100644 --- a/clippy_lints/src/from_over_into.rs +++ b/clippy_lints/src/from_over_into.rs @@ -9,7 +9,7 @@ use clippy_utils::source::SpanRangeExt; use rustc_errors::Applicability; use rustc_hir::intravisit::{Visitor, walk_path}; use rustc_hir::{ - FnRetTy, GenericArg, GenericArgs, HirId, Impl, ImplItemKind, ImplItemId, Item, ItemKind, PatKind, Path, + FnRetTy, GenericArg, GenericArgs, HirId, Impl, ImplItemId, ImplItemKind, Item, ItemKind, PatKind, Path, PathSegment, Ty, TyKind, }; use rustc_lint::{LateContext, LateLintPass}; diff --git a/clippy_lints/src/functions/must_use.rs b/clippy_lints/src/functions/must_use.rs index d959981a83ce..b8d0cec5aeb1 100644 --- a/clippy_lints/src/functions/must_use.rs +++ b/clippy_lints/src/functions/must_use.rs @@ -10,7 +10,7 @@ use rustc_span::{Span, sym}; use clippy_utils::attrs::is_proc_macro; use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_then}; -use clippy_utils::source::SpanRangeExt; +use clippy_utils::source::snippet_indent; use clippy_utils::ty::is_must_use_ty; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{return_ty, trait_ref_of_method}; @@ -28,6 +28,7 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> if let hir::ItemKind::Fn { ref sig, body: ref body_id, + ident, .. } = item.kind { @@ -51,8 +52,8 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> sig.decl, cx.tcx.hir_body(*body_id), item.span, + ident.span, item.owner_id, - item.span.with_hi(sig.decl.output.span().hi()), "this function could have a `#[must_use]` attribute", ); } @@ -84,8 +85,8 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Imp sig.decl, cx.tcx.hir_body(*body_id), item.span, + item.ident.span, item.owner_id, - item.span.with_hi(sig.decl.output.span().hi()), "this method could have a `#[must_use]` attribute", ); } @@ -120,8 +121,8 @@ pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Tr sig.decl, body, item.span, + item.ident.span, item.owner_id, - item.span.with_hi(sig.decl.output.span().hi()), "this method could have a `#[must_use]` attribute", ); } @@ -198,8 +199,8 @@ fn check_must_use_candidate<'tcx>( decl: &'tcx hir::FnDecl<'_>, body: &'tcx hir::Body<'_>, item_span: Span, + ident_span: Span, item_id: hir::OwnerId, - fn_span: Span, msg: &'static str, ) { if has_mutable_arg(cx, body) @@ -208,18 +209,18 @@ fn check_must_use_candidate<'tcx>( || returns_unit(decl) || !cx.effective_visibilities.is_exported(item_id.def_id) || is_must_use_ty(cx, return_ty(cx, item_id)) + || item_span.from_expansion() { return; } - span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |diag| { - if let Some(snippet) = fn_span.get_source_text(cx) { - diag.span_suggestion( - fn_span, - "add the attribute", - format!("#[must_use] {snippet}"), - Applicability::MachineApplicable, - ); - } + span_lint_and_then(cx, MUST_USE_CANDIDATE, ident_span, msg, |diag| { + let indent = snippet_indent(cx, item_span).unwrap_or_default(); + diag.span_suggestion( + item_span.shrink_to_lo(), + "add the attribute", + format!("#[must_use] \n{indent}"), + Applicability::MachineApplicable, + ); }); } diff --git a/clippy_lints/src/if_then_some_else_none.rs b/clippy_lints/src/if_then_some_else_none.rs index 9e94280fc074..7158f9419c1c 100644 --- a/clippy_lints/src/if_then_some_else_none.rs +++ b/clippy_lints/src/if_then_some_else_none.rs @@ -5,7 +5,8 @@ use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::snippet_with_context; use clippy_utils::sugg::Sugg; use clippy_utils::{ - contains_return, higher, is_else_clause, is_in_const_context, is_res_lang_ctor, path_res, peel_blocks, + contains_return, expr_adjustment_requires_coercion, higher, is_else_clause, is_in_const_context, is_res_lang_ctor, + path_res, peel_blocks, }; use rustc_errors::Applicability; use rustc_hir::LangItem::{OptionNone, OptionSome}; @@ -92,6 +93,10 @@ impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone { expr.span, format!("this could be simplified with `bool::{method_name}`"), |diag| { + if expr_adjustment_requires_coercion(cx, then_arg) { + return; + } + let mut app = Applicability::MachineApplicable; let cond_snip = Sugg::hir_with_context(cx, cond, expr.span.ctxt(), "[condition]", &mut app) .maybe_paren() diff --git a/clippy_lints/src/incompatible_msrv.rs b/clippy_lints/src/incompatible_msrv.rs index 5d0bd3e8ca30..116d63c3bb15 100644 --- a/clippy_lints/src/incompatible_msrv.rs +++ b/clippy_lints/src/incompatible_msrv.rs @@ -1,10 +1,11 @@ use clippy_config::Conf; -use clippy_utils::diagnostics::span_lint; -use clippy_utils::is_in_test; +use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::Msrv; +use clippy_utils::{is_in_const_context, is_in_test}; use rustc_attr_data_structures::{RustcVersion, StabilityLevel, StableSince}; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::{Expr, ExprKind, HirId, QPath}; +use rustc_hir::def::DefKind; +use rustc_hir::{self as hir, AmbigArg, Expr, ExprKind, HirId, QPath}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::TyCtxt; use rustc_session::impl_lint_pass; @@ -33,15 +34,54 @@ declare_clippy_lint! { /// /// To fix this problem, either increase your MSRV or use another item /// available in your current MSRV. + /// + /// You can also locally change the MSRV that should be checked by Clippy, + /// for example if a feature in your crate (e.g., `modern_compiler`) should + /// allow you to use an item: + /// + /// ```no_run + /// //! This crate has a MSRV of 1.3.0, but we also have an optional feature + /// //! `sleep_well` which requires at least Rust 1.4.0. + /// + /// // When the `sleep_well` feature is set, do not warn for functions available + /// // in Rust 1.4.0 and below. + /// #![cfg_attr(feature = "sleep_well", clippy::msrv = "1.4.0")] + /// + /// use std::time::Duration; + /// + /// #[cfg(feature = "sleep_well")] + /// fn sleep_for_some_time() { + /// std::thread::sleep(Duration::new(1, 0)); // Will not trigger the lint + /// } + /// ``` + /// + /// You can also increase the MSRV in tests, by using: + /// + /// ```no_run + /// // Use a much higher MSRV for tests while keeping the main one low + /// #![cfg_attr(test, clippy::msrv = "1.85.0")] + /// + /// #[test] + /// fn my_test() { + /// // The tests can use items introduced in Rust 1.85.0 and lower + /// // without triggering the `incompatible_msrv` lint. + /// } + /// ``` #[clippy::version = "1.78.0"] pub INCOMPATIBLE_MSRV, suspicious, "ensures that all items used in the crate are available for the current MSRV" } +#[derive(Clone, Copy)] +enum Availability { + FeatureEnabled, + Since(RustcVersion), +} + pub struct IncompatibleMsrv { msrv: Msrv, - is_above_msrv: FxHashMap, + availability_cache: FxHashMap<(DefId, bool), Availability>, check_in_tests: bool, } @@ -51,38 +91,50 @@ impl IncompatibleMsrv { pub fn new(conf: &'static Conf) -> Self { Self { msrv: conf.msrv, - is_above_msrv: FxHashMap::default(), + availability_cache: FxHashMap::default(), check_in_tests: conf.check_incompatible_msrv_in_tests, } } - fn get_def_id_version(&mut self, tcx: TyCtxt<'_>, def_id: DefId) -> RustcVersion { - if let Some(version) = self.is_above_msrv.get(&def_id) { - return *version; + /// Returns the availability of `def_id`, whether it is enabled through a feature or + /// available since a given version (the default being Rust 1.0.0). `needs_const` requires + /// the `const`-stability to be looked up instead of the stability in non-`const` contexts. + fn get_def_id_availability(&mut self, tcx: TyCtxt<'_>, def_id: DefId, needs_const: bool) -> Availability { + if let Some(availability) = self.availability_cache.get(&(def_id, needs_const)) { + return *availability; } - let version = if let Some(version) = tcx - .lookup_stability(def_id) - .and_then(|stability| match stability.level { - StabilityLevel::Stable { - since: StableSince::Version(version), - .. - } => Some(version), - _ => None, - }) { - version + let (feature, stability_level) = if needs_const { + tcx.lookup_const_stability(def_id) + .map(|stability| (stability.feature, stability.level)) + .unzip() + } else { + tcx.lookup_stability(def_id) + .map(|stability| (stability.feature, stability.level)) + .unzip() + }; + let version = if feature.is_some_and(|feature| tcx.features().enabled(feature)) { + Availability::FeatureEnabled + } else if let Some(StableSince::Version(version)) = + stability_level.as_ref().and_then(StabilityLevel::stable_since) + { + Availability::Since(version) + } else if needs_const { + // Fallback to regular stability + self.get_def_id_availability(tcx, def_id, false) } else if let Some(parent_def_id) = tcx.opt_parent(def_id) { - self.get_def_id_version(tcx, parent_def_id) + self.get_def_id_availability(tcx, parent_def_id, needs_const) } else { - RustcVersion { + Availability::Since(RustcVersion { major: 1, minor: 0, patch: 0, - } + }) }; - self.is_above_msrv.insert(def_id, version); + self.availability_cache.insert((def_id, needs_const), version); version } + /// Emit lint if `def_id`, associated with `node` and `span`, is below the current MSRV. fn emit_lint_if_under_msrv(&mut self, cx: &LateContext<'_>, def_id: DefId, node: HirId, span: Span) { if def_id.is_local() { // We don't check local items since their MSRV is supposed to always be valid. @@ -108,18 +160,28 @@ impl IncompatibleMsrv { return; } + let needs_const = cx.enclosing_body.is_some() + && is_in_const_context(cx) + && matches!(cx.tcx.def_kind(def_id), DefKind::AssocFn | DefKind::Fn); + if (self.check_in_tests || !is_in_test(cx.tcx, node)) && let Some(current) = self.msrv.current(cx) - && let version = self.get_def_id_version(cx.tcx, def_id) + && let Availability::Since(version) = self.get_def_id_availability(cx.tcx, def_id, needs_const) && version > current { - span_lint( + span_lint_and_then( cx, INCOMPATIBLE_MSRV, span, format!( - "current MSRV (Minimum Supported Rust Version) is `{current}` but this item is stable since `{version}`" + "current MSRV (Minimum Supported Rust Version) is `{current}` but this item is stable{} since `{version}`", + if needs_const { " in a `const` context" } else { "" }, ), + |diag| { + if is_under_cfg_attribute(cx, node) { + diag.note_once("you may want to conditionally increase the MSRV considered by Clippy using the `clippy::msrv` attribute"); + } + }, ); } } @@ -133,17 +195,38 @@ impl<'tcx> LateLintPass<'tcx> for IncompatibleMsrv { self.emit_lint_if_under_msrv(cx, method_did, expr.hir_id, span); } }, - ExprKind::Call(call, _) => { - // Desugaring into function calls by the compiler will use `QPath::LangItem` variants. Those should - // not be linted as they will not be generated in older compilers if the function is not available, - // and the compiler is allowed to call unstable functions. - if let ExprKind::Path(qpath @ (QPath::Resolved(..) | QPath::TypeRelative(..))) = call.kind - && let Some(path_def_id) = cx.qpath_res(&qpath, call.hir_id).opt_def_id() - { - self.emit_lint_if_under_msrv(cx, path_def_id, expr.hir_id, call.span); + // Desugaring into function calls by the compiler will use `QPath::LangItem` variants. Those should + // not be linted as they will not be generated in older compilers if the function is not available, + // and the compiler is allowed to call unstable functions. + ExprKind::Path(qpath @ (QPath::Resolved(..) | QPath::TypeRelative(..))) => { + if let Some(path_def_id) = cx.qpath_res(&qpath, expr.hir_id).opt_def_id() { + self.emit_lint_if_under_msrv(cx, path_def_id, expr.hir_id, expr.span); } }, _ => {}, } } + + fn check_ty(&mut self, cx: &LateContext<'tcx>, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) { + if let hir::TyKind::Path(qpath @ (QPath::Resolved(..) | QPath::TypeRelative(..))) = hir_ty.kind + && let Some(ty_def_id) = cx.qpath_res(&qpath, hir_ty.hir_id).opt_def_id() + // `CStr` and `CString` have been moved around but have been available since Rust 1.0.0 + && !matches!(cx.tcx.get_diagnostic_name(ty_def_id), Some(sym::cstr_type | sym::cstring_type)) + { + self.emit_lint_if_under_msrv(cx, ty_def_id, hir_ty.hir_id, hir_ty.span); + } + } +} + +/// Heuristic checking if the node `hir_id` is under a `#[cfg()]` or `#[cfg_attr()]` +/// attribute. +fn is_under_cfg_attribute(cx: &LateContext<'_>, hir_id: HirId) -> bool { + cx.tcx.hir_parent_id_iter(hir_id).any(|id| { + cx.tcx.hir_attrs(id).iter().any(|attr| { + matches!( + attr.ident().map(|ident| ident.name), + Some(sym::cfg_trace | sym::cfg_attr_trace) + ) + }) + }) } diff --git a/clippy_lints/src/ineffective_open_options.rs b/clippy_lints/src/ineffective_open_options.rs index 7a751514b647..a159f6157183 100644 --- a/clippy_lints/src/ineffective_open_options.rs +++ b/clippy_lints/src/ineffective_open_options.rs @@ -1,13 +1,12 @@ -use crate::methods::method_call; use clippy_utils::diagnostics::span_lint_and_sugg; -use clippy_utils::{peel_blocks, sym}; +use clippy_utils::source::SpanRangeExt; +use clippy_utils::ty::is_type_diagnostic_item; +use clippy_utils::{peel_blocks, peel_hir_expr_while, sym}; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty; use rustc_session::declare_lint_pass; -use rustc_span::{BytePos, Span}; declare_clippy_lint! { /// ### What it does @@ -43,53 +42,58 @@ declare_clippy_lint! { declare_lint_pass!(IneffectiveOpenOptions => [INEFFECTIVE_OPEN_OPTIONS]); -fn index_if_arg_is_boolean(args: &[Expr<'_>], call_span: Span) -> Option { - if let [arg] = args - && let ExprKind::Lit(lit) = peel_blocks(arg).kind - && lit.node == LitKind::Bool(true) - { - // The `.` is not included in the span so we cheat a little bit to include it as well. - Some(call_span.with_lo(call_span.lo() - BytePos(1))) - } else { - None - } -} - impl<'tcx> LateLintPass<'tcx> for IneffectiveOpenOptions { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { - let Some((sym::open, mut receiver, [_arg], _, _)) = method_call(expr) else { - return; - }; - let receiver_ty = cx.typeck_results().expr_ty(receiver); - match receiver_ty.peel_refs().kind() { - ty::Adt(adt, _) if cx.tcx.is_diagnostic_item(sym::FsOpenOptions, adt.did()) => {}, - _ => return, - } - - let mut append = None; - let mut write = None; + if let ExprKind::MethodCall(name, recv, [_], _) = expr.kind + && name.ident.name == sym::open + && !expr.span.from_expansion() + && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv).peel_refs(), sym::FsOpenOptions) + { + let mut append = false; + let mut write = None; + peel_hir_expr_while(recv, |e| { + if let ExprKind::MethodCall(name, recv, args, call_span) = e.kind + && !e.span.from_expansion() + { + if let [arg] = args + && let ExprKind::Lit(lit) = peel_blocks(arg).kind + && matches!(lit.node, LitKind::Bool(true)) + && !arg.span.from_expansion() + && !lit.span.from_expansion() + { + match name.ident.name { + sym::append => append = true, + sym::write + if let Some(range) = call_span.map_range(cx, |_, text, range| { + if text.get(..range.start)?.ends_with('.') { + Some(range.start - 1..range.end) + } else { + None + } + }) => + { + write = Some(call_span.with_lo(range.start)); + }, + _ => {}, + } + } + Some(recv) + } else { + None + } + }); - while let Some((name, recv, args, _, span)) = method_call(receiver) { - if name == sym::append { - append = index_if_arg_is_boolean(args, span); - } else if name == sym::write { - write = index_if_arg_is_boolean(args, span); + if append && let Some(write_span) = write { + span_lint_and_sugg( + cx, + INEFFECTIVE_OPEN_OPTIONS, + write_span, + "unnecessary use of `.write(true)` because there is `.append(true)`", + "remove `.write(true)`", + String::new(), + Applicability::MachineApplicable, + ); } - receiver = recv; - } - - if let Some(write_span) = write - && append.is_some() - { - span_lint_and_sugg( - cx, - INEFFECTIVE_OPEN_OPTIONS, - write_span, - "unnecessary use of `.write(true)` because there is `.append(true)`", - "remove `.write(true)`", - String::new(), - Applicability::MachineApplicable, - ); } } } diff --git a/clippy_lints/src/infallible_try_from.rs b/clippy_lints/src/infallible_try_from.rs index e79fcec6e6ac..f7cdf05359a3 100644 --- a/clippy_lints/src/infallible_try_from.rs +++ b/clippy_lints/src/infallible_try_from.rs @@ -52,13 +52,17 @@ impl<'tcx> LateLintPass<'tcx> for InfallibleTryFrom { if !cx.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id) { return; } - for ii in cx.tcx.associated_items(item.owner_id.def_id) + for ii in cx + .tcx + .associated_items(item.owner_id.def_id) .filter_by_name_unhygienic_and_kind(sym::Error, AssocTag::Type) { let ii_ty = cx.tcx.type_of(ii.def_id).instantiate_identity(); if !ii_ty.is_inhabited_from(cx.tcx, ii.def_id, cx.typing_env()) { let mut span = MultiSpan::from_span(cx.tcx.def_span(item.owner_id.to_def_id())); - let ii_ty_span = cx.tcx.hir_node_by_def_id(ii.def_id.expect_local()) + let ii_ty_span = cx + .tcx + .hir_node_by_def_id(ii.def_id.expect_local()) .expect_impl_item() .expect_type() .span; diff --git a/clippy_lints/src/item_name_repetitions.rs b/clippy_lints/src/item_name_repetitions.rs index 9c91cf680851..95e16aae40f9 100644 --- a/clippy_lints/src/item_name_repetitions.rs +++ b/clippy_lints/src/item_name_repetitions.rs @@ -8,6 +8,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir::{EnumDef, FieldDef, Item, ItemKind, OwnerId, QPath, TyKind, Variant, VariantData}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; +use rustc_span::MacroKind; use rustc_span::symbol::Symbol; declare_clippy_lint! { @@ -502,7 +503,8 @@ impl LateLintPass<'_> for ItemNameRepetitions { ); } - if both_are_public && item_camel.len() > mod_camel.len() { + let is_macro_rule = matches!(item.kind, ItemKind::Macro(_, _, MacroKind::Bang)); + if both_are_public && item_camel.len() > mod_camel.len() && !is_macro_rule { let matching = count_match_start(mod_camel, &item_camel); let rmatching = count_match_end(mod_camel, &item_camel); let nchars = mod_camel.chars().count(); diff --git a/clippy_lints/src/iter_without_into_iter.rs b/clippy_lints/src/iter_without_into_iter.rs index 03038f0ab49c..b89f91f7255f 100644 --- a/clippy_lints/src/iter_without_into_iter.rs +++ b/clippy_lints/src/iter_without_into_iter.rs @@ -139,11 +139,17 @@ impl LateLintPass<'_> for IterWithoutIntoIter { // We can't check inherent impls for slices, but we know that they have an `iter(_mut)` method ty.peel_refs().is_slice() || get_adt_inherent_method(cx, ty, expected_method_name).is_some() }) - && let Some(iter_assoc_span) = cx.tcx.associated_items(item.owner_id) + && let Some(iter_assoc_span) = cx + .tcx + .associated_items(item.owner_id) .filter_by_name_unhygienic_and_kind(sym::IntoIter, ty::AssocTag::Type) .next() .map(|assoc_item| { - cx.tcx.hir_node_by_def_id(assoc_item.def_id.expect_local()).expect_impl_item().expect_type().span + cx.tcx + .hir_node_by_def_id(assoc_item.def_id.expect_local()) + .expect_impl_item() + .expect_type() + .span }) && is_ty_exported(cx, ty) { diff --git a/clippy_lints/src/large_enum_variant.rs b/clippy_lints/src/large_enum_variant.rs index e85d779b4880..c2b739431060 100644 --- a/clippy_lints/src/large_enum_variant.rs +++ b/clippy_lints/src/large_enum_variant.rs @@ -1,5 +1,6 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::is_no_std_crate; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{AdtVariantInfo, approx_ty_size, is_copy}; use rustc_errors::Applicability; @@ -83,7 +84,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { let mut difference = variants_size[0].size - variants_size[1].size; if difference > self.maximum_size_difference_allowed { - let help_text = "consider boxing the large fields to reduce the total size of the enum"; + let help_text = "consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum"; span_lint_and_then( cx, LARGE_ENUM_VARIANT, @@ -117,7 +118,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { ident.span, "boxing a variant would require the type no longer be `Copy`", ); - } else { + } else if !is_no_std_crate(cx) { let sugg: Vec<(Span, String)> = variants_size[0] .fields_size .iter() diff --git a/clippy_lints/src/legacy_numeric_constants.rs b/clippy_lints/src/legacy_numeric_constants.rs index b3c63f022d35..42c636505c01 100644 --- a/clippy_lints/src/legacy_numeric_constants.rs +++ b/clippy_lints/src/legacy_numeric_constants.rs @@ -1,7 +1,8 @@ use clippy_config::Conf; -use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then}; +use clippy_utils::diagnostics::span_lint_and_then; +use clippy_utils::is_from_proc_macro; use clippy_utils::msrvs::{self, Msrv}; -use clippy_utils::{get_parent_expr, is_from_proc_macro}; +use clippy_utils::source::SpanRangeExt; use hir::def_id::DefId; use rustc_errors::Applicability; use rustc_hir as hir; @@ -102,39 +103,45 @@ impl<'tcx> LateLintPass<'tcx> for LegacyNumericConstants { } fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) { - let ExprKind::Path(qpath) = &expr.kind else { - return; - }; - // `std::::` check - let (span, sugg, msg) = if let QPath::Resolved(None, path) = qpath + let (sugg, msg) = if let ExprKind::Path(qpath) = &expr.kind + && let QPath::Resolved(None, path) = qpath && let Some(def_id) = path.res.opt_def_id() && is_numeric_const(cx, def_id) - && let def_path = cx.get_def_path(def_id) - && let [.., mod_name, name] = &*def_path + && let [.., mod_name, name] = &*cx.get_def_path(def_id) // Skip linting if this usage looks identical to the associated constant, // since this would only require removing a `use` import (which is already linted). && !is_numeric_const_path_canonical(path, [*mod_name, *name]) { ( - expr.span, - format!("{mod_name}::{name}"), + vec![(expr.span, format!("{mod_name}::{name}"))], "usage of a legacy numeric constant", ) // `::xxx_value` check - } else if let QPath::TypeRelative(_, last_segment) = qpath - && let Some(def_id) = cx.qpath_res(qpath, expr.hir_id).opt_def_id() - && let Some(par_expr) = get_parent_expr(cx, expr) - && let ExprKind::Call(_, []) = par_expr.kind + } else if let ExprKind::Call(func, []) = &expr.kind + && let ExprKind::Path(qpath) = &func.kind + && let QPath::TypeRelative(ty, last_segment) = qpath + && let Some(def_id) = cx.qpath_res(qpath, func.hir_id).opt_def_id() && is_integer_method(cx, def_id) { - let name = last_segment.ident.name.as_str(); - - ( - last_segment.ident.span.with_hi(par_expr.span.hi()), - name[..=2].to_ascii_uppercase(), - "usage of a legacy numeric method", - ) + let mut sugg = vec![ + // Replace the function name up to the end by the constant name + ( + last_segment.ident.span.to(expr.span.shrink_to_hi()), + last_segment.ident.name.as_str()[..=2].to_ascii_uppercase(), + ), + ]; + let before_span = expr.span.shrink_to_lo().until(ty.span); + if !before_span.is_empty() { + // Remove everything before the type name + sugg.push((before_span, String::new())); + } + // Use `::` between the type name and the constant + let between_span = ty.span.shrink_to_hi().until(last_segment.ident.span); + if !between_span.check_source_text(cx, |s| s == "::") { + sugg.push((between_span, String::from("::"))); + } + (sugg, "usage of a legacy numeric method") } else { return; }; @@ -143,9 +150,8 @@ impl<'tcx> LateLintPass<'tcx> for LegacyNumericConstants { && self.msrv.meets(cx, msrvs::NUMERIC_ASSOCIATED_CONSTANTS) && !is_from_proc_macro(cx, expr) { - span_lint_hir_and_then(cx, LEGACY_NUMERIC_CONSTANTS, expr.hir_id, span, msg, |diag| { - diag.span_suggestion_verbose( - span, + span_lint_and_then(cx, LEGACY_NUMERIC_CONSTANTS, expr.span, msg, |diag| { + diag.multipart_suggestion_verbose( "use the associated constant instead", sugg, Applicability::MaybeIncorrect, diff --git a/clippy_lints/src/len_zero.rs b/clippy_lints/src/len_zero.rs index 1bf03480c825..6beddc1be144 100644 --- a/clippy_lints/src/len_zero.rs +++ b/clippy_lints/src/len_zero.rs @@ -10,9 +10,9 @@ use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_hir::{ - BinOpKind, Expr, ExprKind, FnRetTy, GenericArg, GenericBound, HirId, ImplItem, ImplItemKind, - ImplicitSelfKind, Item, ItemKind, Mutability, Node, OpaqueTyOrigin, PatExprKind, PatKind, PathSegment, PrimTy, - QPath, TraitItemId, TyKind, + BinOpKind, Expr, ExprKind, FnRetTy, GenericArg, GenericBound, HirId, ImplItem, ImplItemKind, ImplicitSelfKind, + Item, ItemKind, Mutability, Node, OpaqueTyOrigin, PatExprKind, PatKind, PathSegment, PrimTy, QPath, TraitItemId, + TyKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, FnSig, Ty}; @@ -266,11 +266,14 @@ fn span_without_enclosing_paren(cx: &LateContext<'_>, span: Span) -> Span { } fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, ident: Ident, trait_items: &[TraitItemId]) { - fn is_named_self(cx: &LateContext<'_>, item: &TraitItemId, name: Symbol) -> bool { + fn is_named_self(cx: &LateContext<'_>, item: TraitItemId, name: Symbol) -> bool { cx.tcx.item_name(item.owner_id) == name && matches!( cx.tcx.fn_arg_idents(item.owner_id), - [Some(Ident { name: kw::SelfLower, .. })], + [Some(Ident { + name: kw::SelfLower, + .. + })], ) } @@ -284,7 +287,7 @@ fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, ident: Iden } if cx.effective_visibilities.is_exported(visited_trait.owner_id.def_id) - && trait_items.iter().any(|i| is_named_self(cx, i, sym::len)) + && trait_items.iter().any(|&i| is_named_self(cx, i, sym::len)) { let mut current_and_super_traits = DefIdSet::default(); fill_trait_set(visited_trait.owner_id.to_def_id(), &mut current_and_super_traits, cx); diff --git a/clippy_lints/src/loops/needless_range_loop.rs b/clippy_lints/src/loops/needless_range_loop.rs index 7837b18bcd36..972b0b110e0e 100644 --- a/clippy_lints/src/loops/needless_range_loop.rs +++ b/clippy_lints/src/loops/needless_range_loop.rs @@ -39,7 +39,9 @@ pub(super) fn check<'tcx>( var: canonical_id, indexed_mut: FxHashSet::default(), indexed_indirectly: FxHashMap::default(), + unnamed_indexed_indirectly: false, indexed_directly: FxIndexMap::default(), + unnamed_indexed_directly: false, referenced: FxHashSet::default(), nonindex: false, prefer_mutable: false, @@ -47,7 +49,11 @@ pub(super) fn check<'tcx>( walk_expr(&mut visitor, body); // linting condition: we only indexed one variable, and indexed it directly - if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 { + if visitor.indexed_indirectly.is_empty() + && !visitor.unnamed_indexed_indirectly + && !visitor.unnamed_indexed_directly + && visitor.indexed_directly.len() == 1 + { let (indexed, (indexed_extent, indexed_ty)) = visitor .indexed_directly .into_iter() @@ -217,6 +223,7 @@ fn is_end_eq_array_len<'tcx>( false } +#[expect(clippy::struct_excessive_bools)] struct VarVisitor<'a, 'tcx> { /// context reference cx: &'a LateContext<'tcx>, @@ -226,9 +233,13 @@ struct VarVisitor<'a, 'tcx> { indexed_mut: FxHashSet, /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global indexed_indirectly: FxHashMap>, + /// indirectly indexed literals, like `[1, 2, 3][(i + 4) % N]` + unnamed_indexed_indirectly: bool, /// subset of `indexed` of vars that are indexed directly: `v[i]` /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]` indexed_directly: FxIndexMap, Ty<'tcx>)>, + /// directly indexed literals, like `[1, 2, 3][i]` + unnamed_indexed_directly: bool, /// Any names that are used outside an index operation. /// Used to detect things like `&mut vec` used together with `vec[i]` referenced: FxHashSet, @@ -242,6 +253,7 @@ struct VarVisitor<'a, 'tcx> { impl<'tcx> VarVisitor<'_, 'tcx> { fn check(&mut self, idx: &'tcx Expr<'_>, seqexpr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) -> bool { + let index_used_directly = matches!(idx.kind, ExprKind::Path(_)); if let ExprKind::Path(ref seqpath) = seqexpr.kind // the indexed container is referenced by a name && let QPath::Resolved(None, seqvar) = *seqpath @@ -251,7 +263,6 @@ impl<'tcx> VarVisitor<'_, 'tcx> { if self.prefer_mutable { self.indexed_mut.insert(seqvar.segments[0].ident.name); } - let index_used_directly = matches!(idx.kind, ExprKind::Path(_)); let res = self.cx.qpath_res(seqpath, seqexpr.hir_id); match res { Res::Local(hir_id) => { @@ -286,6 +297,13 @@ impl<'tcx> VarVisitor<'_, 'tcx> { }, _ => (), } + } else if let ExprKind::Repeat(..) | ExprKind::Array(..) = seqexpr.kind { + if index_used_directly { + self.unnamed_indexed_directly = true; + } else { + self.unnamed_indexed_indirectly = true; + } + return false; } true } diff --git a/clippy_lints/src/loops/never_loop.rs b/clippy_lints/src/loops/never_loop.rs index 69c84bc7038e..8a253ae5810f 100644 --- a/clippy_lints/src/loops/never_loop.rs +++ b/clippy_lints/src/loops/never_loop.rs @@ -6,9 +6,11 @@ use clippy_utils::macros::root_macro_call_first_node; use clippy_utils::source::snippet; use clippy_utils::visitors::{Descend, for_each_expr_without_closures}; use rustc_errors::Applicability; -use rustc_hir::{Block, Destination, Expr, ExprKind, HirId, InlineAsmOperand, Pat, Stmt, StmtKind, StructTailExpr}; +use rustc_hir::{ + Block, Destination, Expr, ExprKind, HirId, InlineAsmOperand, Node, Pat, Stmt, StmtKind, StructTailExpr, +}; use rustc_lint::LateContext; -use rustc_span::{Span, sym}; +use rustc_span::{BytePos, Span, sym}; use std::iter::once; use std::ops::ControlFlow; @@ -20,7 +22,7 @@ pub(super) fn check<'tcx>( for_loop: Option<&ForLoop<'_>>, ) { match never_loop_block(cx, block, &mut Vec::new(), loop_id) { - NeverLoopResult::Diverging => { + NeverLoopResult::Diverging { ref break_spans } => { span_lint_and_then(cx, NEVER_LOOP, span, "this loop never actually loops", |diag| { if let Some(ForLoop { arg: iterator, @@ -38,10 +40,15 @@ pub(super) fn check<'tcx>( Applicability::Unspecified }; - diag.span_suggestion_verbose( + let mut suggestions = vec![( for_span.with_hi(iterator.span.hi()), - "if you need the first element of the iterator, try writing", for_to_if_let_sugg(cx, iterator, pat), + )]; + // Make sure to clear up the diverging sites when we remove a loopp. + suggestions.extend(break_spans.iter().map(|span| (*span, String::new()))); + diag.multipart_suggestion_verbose( + "if you need the first element of the iterator, try writing", + suggestions, app, ); } @@ -70,22 +77,22 @@ fn contains_any_break_or_continue(block: &Block<'_>) -> bool { /// The first two bits of information are in this enum, and the last part is in the /// `local_labels` variable, which contains a list of `(block_id, reachable)` pairs ordered by /// scope. -#[derive(Copy, Clone)] +#[derive(Clone)] enum NeverLoopResult { /// A continue may occur for the main loop. MayContinueMainLoop, /// We have not encountered any main loop continue, /// but we are diverging (subsequent control flow is not reachable) - Diverging, + Diverging { break_spans: Vec }, /// We have not encountered any main loop continue, /// and subsequent control flow is (possibly) reachable Normal, } #[must_use] -fn absorb_break(arg: NeverLoopResult) -> NeverLoopResult { +fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult { match arg { - NeverLoopResult::Diverging | NeverLoopResult::Normal => NeverLoopResult::Normal, + NeverLoopResult::Diverging { .. } | NeverLoopResult::Normal => NeverLoopResult::Normal, NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop, } } @@ -94,7 +101,7 @@ fn absorb_break(arg: NeverLoopResult) -> NeverLoopResult { #[must_use] fn combine_seq(first: NeverLoopResult, second: impl FnOnce() -> NeverLoopResult) -> NeverLoopResult { match first { - NeverLoopResult::Diverging | NeverLoopResult::MayContinueMainLoop => first, + NeverLoopResult::Diverging { .. } | NeverLoopResult::MayContinueMainLoop => first, NeverLoopResult::Normal => second(), } } @@ -103,7 +110,7 @@ fn combine_seq(first: NeverLoopResult, second: impl FnOnce() -> NeverLoopResult) #[must_use] fn combine_seq_many(iter: impl IntoIterator) -> NeverLoopResult { for e in iter { - if let NeverLoopResult::Diverging | NeverLoopResult::MayContinueMainLoop = e { + if let NeverLoopResult::Diverging { .. } | NeverLoopResult::MayContinueMainLoop = e { return e; } } @@ -118,7 +125,19 @@ fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult NeverLoopResult::MayContinueMainLoop }, (NeverLoopResult::Normal, _) | (_, NeverLoopResult::Normal) => NeverLoopResult::Normal, - (NeverLoopResult::Diverging, NeverLoopResult::Diverging) => NeverLoopResult::Diverging, + ( + NeverLoopResult::Diverging { + break_spans: mut break_spans1, + }, + NeverLoopResult::Diverging { + break_spans: mut break_spans2, + }, + ) => { + break_spans1.append(&mut break_spans2); + NeverLoopResult::Diverging { + break_spans: break_spans1, + } + }, } } @@ -136,7 +155,7 @@ fn never_loop_block<'tcx>( combine_seq_many(iter.map(|(e, els)| { let e = never_loop_expr(cx, e, local_labels, main_loop_id); // els is an else block in a let...else binding - els.map_or(e, |els| { + els.map_or(e.clone(), |els| { combine_seq(e, || match never_loop_block(cx, els, local_labels, main_loop_id) { // Returning MayContinueMainLoop here means that // we will not evaluate the rest of the body @@ -144,7 +163,7 @@ fn never_loop_block<'tcx>( // An else block always diverges, so the Normal case should not happen, // but the analysis is approximate so it might return Normal anyway. // Returning Normal here says that nothing more happens on the main path - NeverLoopResult::Diverging | NeverLoopResult::Normal => NeverLoopResult::Normal, + NeverLoopResult::Diverging { .. } | NeverLoopResult::Normal => NeverLoopResult::Normal, }) }) })) @@ -159,6 +178,45 @@ fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<(&'tcx Expr<'tcx>, Option<&'t } } +fn stmt_source_span(stmt: &Stmt<'_>) -> Span { + let call_span = stmt.span.source_callsite(); + // if it is a macro call, the span will be missing the trailing semicolon + if stmt.span == call_span { + return call_span; + } + + // An expression without a trailing semi-colon (must have unit type). + if let StmtKind::Expr(..) = stmt.kind { + return call_span; + } + + call_span.with_hi(call_span.hi() + BytePos(1)) +} + +/// Returns a Vec of all the individual spans after the highlighted expression in a block +fn all_spans_after_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> Vec { + if let Node::Stmt(stmt) = cx.tcx.parent_hir_node(expr.hir_id) { + if let Node::Block(block) = cx.tcx.parent_hir_node(stmt.hir_id) { + return block + .stmts + .iter() + .skip_while(|inner| inner.hir_id != stmt.hir_id) + .map(stmt_source_span) + .chain(if let Some(e) = block.expr { vec![e.span] } else { vec![] }) + .collect(); + } + + return vec![stmt.span]; + } + + vec![] +} + +fn is_label_for_block(cx: &LateContext<'_>, dest: &Destination) -> bool { + dest.target_id + .is_ok_and(|hir_id| matches!(cx.tcx.hir_node(hir_id), Node::Block(_))) +} + #[allow(clippy::too_many_lines)] fn never_loop_expr<'tcx>( cx: &LateContext<'tcx>, @@ -197,7 +255,7 @@ fn never_loop_expr<'tcx>( ExprKind::Loop(b, _, _, _) => { // We don't attempt to track reachability after a loop, // just assume there may have been a break somewhere - absorb_break(never_loop_block(cx, b, local_labels, main_loop_id)) + absorb_break(&never_loop_block(cx, b, local_labels, main_loop_id)) }, ExprKind::If(e, e2, e3) => { let e1 = never_loop_expr(cx, e, local_labels, main_loop_id); @@ -212,9 +270,10 @@ fn never_loop_expr<'tcx>( ExprKind::Match(e, arms, _) => { let e = never_loop_expr(cx, e, local_labels, main_loop_id); combine_seq(e, || { - arms.iter().fold(NeverLoopResult::Diverging, |a, b| { - combine_branches(a, never_loop_expr(cx, b.body, local_labels, main_loop_id)) - }) + arms.iter() + .fold(NeverLoopResult::Diverging { break_spans: vec![] }, |a, b| { + combine_branches(a, never_loop_expr(cx, b.body, local_labels, main_loop_id)) + }) }) }, ExprKind::Block(b, _) => { @@ -224,7 +283,7 @@ fn never_loop_expr<'tcx>( let ret = never_loop_block(cx, b, local_labels, main_loop_id); let jumped_to = b.targeted_by_break && local_labels.pop().unwrap().1; match ret { - NeverLoopResult::Diverging if jumped_to => NeverLoopResult::Normal, + NeverLoopResult::Diverging { .. } if jumped_to => NeverLoopResult::Normal, _ => ret, } }, @@ -235,25 +294,39 @@ fn never_loop_expr<'tcx>( if id == main_loop_id { NeverLoopResult::MayContinueMainLoop } else { - NeverLoopResult::Diverging + NeverLoopResult::Diverging { + break_spans: all_spans_after_expr(cx, expr), + } } }, - ExprKind::Break(_, e) | ExprKind::Ret(e) => { + ExprKind::Ret(e) => { let first = e.as_ref().map_or(NeverLoopResult::Normal, |e| { never_loop_expr(cx, e, local_labels, main_loop_id) }); combine_seq(first, || { // checks if break targets a block instead of a loop - if let ExprKind::Break(Destination { target_id: Ok(t), .. }, _) = expr.kind - && let Some((_, reachable)) = local_labels.iter_mut().find(|(label, _)| *label == t) - { - *reachable = true; + mark_block_as_reachable(expr, local_labels); + NeverLoopResult::Diverging { break_spans: vec![] } + }) + }, + ExprKind::Break(dest, e) => { + let first = e.as_ref().map_or(NeverLoopResult::Normal, |e| { + never_loop_expr(cx, e, local_labels, main_loop_id) + }); + combine_seq(first, || { + // checks if break targets a block instead of a loop + mark_block_as_reachable(expr, local_labels); + NeverLoopResult::Diverging { + break_spans: if is_label_for_block(cx, &dest) { + vec![] + } else { + all_spans_after_expr(cx, expr) + }, } - NeverLoopResult::Diverging }) }, ExprKind::Become(e) => combine_seq(never_loop_expr(cx, e, local_labels, main_loop_id), || { - NeverLoopResult::Diverging + NeverLoopResult::Diverging { break_spans: vec![] } }), ExprKind::InlineAsm(asm) => combine_seq_many(asm.operands.iter().map(|(o, _)| match o { InlineAsmOperand::In { expr, .. } | InlineAsmOperand::InOut { expr, .. } => { @@ -283,12 +356,12 @@ fn never_loop_expr<'tcx>( }; let result = combine_seq(result, || { if cx.typeck_results().expr_ty(expr).is_never() { - NeverLoopResult::Diverging + NeverLoopResult::Diverging { break_spans: vec![] } } else { NeverLoopResult::Normal } }); - if let NeverLoopResult::Diverging = result + if let NeverLoopResult::Diverging { .. } = result && let Some(macro_call) = root_macro_call_first_node(cx, expr) && let Some(sym::todo_macro) = cx.tcx.get_diagnostic_name(macro_call.def_id) { @@ -316,3 +389,11 @@ fn for_to_if_let_sugg(cx: &LateContext<'_>, iterator: &Expr<'_>, pat: &Pat<'_>) format!("if let Some({pat_snippet}) = {iter_snippet}.next()") } + +fn mark_block_as_reachable(expr: &Expr<'_>, local_labels: &mut [(HirId, bool)]) { + if let ExprKind::Break(Destination { target_id: Ok(t), .. }, _) = expr.kind + && let Some((_, reachable)) = local_labels.iter_mut().find(|(label, _)| *label == t) + { + *reachable = true; + } +} diff --git a/clippy_lints/src/macro_use.rs b/clippy_lints/src/macro_use.rs index d1a54df988f5..3aa449f64118 100644 --- a/clippy_lints/src/macro_use.rs +++ b/clippy_lints/src/macro_use.rs @@ -1,15 +1,15 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::source::snippet; use hir::def::{DefKind, Res}; +use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{self as hir, AmbigArg}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::impl_lint_pass; +use rustc_span::Span; use rustc_span::edition::Edition; -use rustc_span::{Span}; use std::collections::BTreeMap; -use rustc_attr_data_structures::{AttributeKind, find_attr}; declare_clippy_lint! { /// ### What it does diff --git a/clippy_lints/src/manual_abs_diff.rs b/clippy_lints/src/manual_abs_diff.rs index bac4b3d32f2a..288f27db8ca2 100644 --- a/clippy_lints/src/manual_abs_diff.rs +++ b/clippy_lints/src/manual_abs_diff.rs @@ -5,7 +5,7 @@ use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::HasSession as _; use clippy_utils::sugg::Sugg; use clippy_utils::ty::is_type_diagnostic_item; -use clippy_utils::{eq_expr_value, peel_blocks, span_contains_comment}; +use clippy_utils::{eq_expr_value, peel_blocks, peel_middle_ty_refs, span_contains_comment}; use rustc_errors::Applicability; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; @@ -62,7 +62,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualAbsDiff { && let ExprKind::Binary(op, rhs, lhs) = if_expr.cond.kind && let (BinOpKind::Gt | BinOpKind::Ge, mut a, mut b) | (BinOpKind::Lt | BinOpKind::Le, mut b, mut a) = (op.node, rhs, lhs) - && let Some(ty) = self.are_ty_eligible(cx, a, b) + && let Some((ty, b_n_refs)) = self.are_ty_eligible(cx, a, b) && is_sub_expr(cx, if_expr.then, a, b, ty) && is_sub_expr(cx, r#else, b, a, ty) { @@ -86,8 +86,9 @@ impl<'tcx> LateLintPass<'tcx> for ManualAbsDiff { } }; let sugg = format!( - "{}.abs_diff({})", + "{}.abs_diff({}{})", Sugg::hir(cx, a, "..").maybe_paren(), + "*".repeat(b_n_refs), Sugg::hir(cx, b, "..") ); diag.span_suggestion(expr.span, "replace with `abs_diff`", sugg, applicability); @@ -100,13 +101,15 @@ impl<'tcx> LateLintPass<'tcx> for ManualAbsDiff { impl ManualAbsDiff { /// Returns a type if `a` and `b` are both of it, and this lint can be applied to that /// type (currently, any primitive int, or a `Duration`) - fn are_ty_eligible<'tcx>(&self, cx: &LateContext<'tcx>, a: &Expr<'_>, b: &Expr<'_>) -> Option> { + fn are_ty_eligible<'tcx>(&self, cx: &LateContext<'tcx>, a: &Expr<'_>, b: &Expr<'_>) -> Option<(Ty<'tcx>, usize)> { let is_int = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) && self.msrv.meets(cx, msrvs::ABS_DIFF); let is_duration = |ty| is_type_diagnostic_item(cx, ty, sym::Duration) && self.msrv.meets(cx, msrvs::DURATION_ABS_DIFF); let a_ty = cx.typeck_results().expr_ty(a).peel_refs(); - (a_ty == cx.typeck_results().expr_ty(b).peel_refs() && (is_int(a_ty) || is_duration(a_ty))).then_some(a_ty) + let (b_ty, b_n_refs) = peel_middle_ty_refs(cx.typeck_results().expr_ty(b)); + + (a_ty == b_ty && (is_int(a_ty) || is_duration(a_ty))).then_some((a_ty, b_n_refs)) } } diff --git a/clippy_lints/src/manual_assert.rs b/clippy_lints/src/manual_assert.rs index 8378e15c581c..ea6b01a053a3 100644 --- a/clippy_lints/src/manual_assert.rs +++ b/clippy_lints/src/manual_assert.rs @@ -60,7 +60,8 @@ impl<'tcx> LateLintPass<'tcx> for ManualAssert { ExprKind::Unary(UnOp::Not, e) => (e, ""), _ => (cond, "!"), }; - let cond_sugg = sugg::Sugg::hir_with_applicability(cx, cond, "..", &mut applicability).maybe_paren(); + let cond_sugg = + sugg::Sugg::hir_with_context(cx, cond, expr.span.ctxt(), "..", &mut applicability).maybe_paren(); let semicolon = if is_parent_stmt(cx, expr.hir_id) { ";" } else { "" }; let sugg = format!("assert!({not}{cond_sugg}, {format_args_snip}){semicolon}"); // we show to the user the suggestion without the comments, but when applying the fix, include the diff --git a/clippy_lints/src/matches/single_match.rs b/clippy_lints/src/matches/single_match.rs index 08c0caa4266c..7e530e98ac4a 100644 --- a/clippy_lints/src/matches/single_match.rs +++ b/clippy_lints/src/matches/single_match.rs @@ -152,21 +152,26 @@ fn report_single_pattern( }) if lit.node.is_str() || lit.node.is_bytestr() => pat_ref_count + 1, _ => pat_ref_count, }; - // References are only implicitly added to the pattern, so no overflow here. - // e.g. will work: match &Some(_) { Some(_) => () } - // will not: match Some(_) { &Some(_) => () } - let ref_count_diff = ty_ref_count - pat_ref_count; - // Try to remove address of expressions first. - let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff); - let ref_count_diff = ref_count_diff - removed; + // References are implicitly removed when `deref_patterns` are used. + // They are implicitly added when match ergonomics are used. + let (ex, ref_or_deref_adjust) = if ty_ref_count > pat_ref_count { + let ref_count_diff = ty_ref_count - pat_ref_count; + + // Try to remove address of expressions first. + let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff); + + (ex, String::from(if ref_count_diff == removed { "" } else { "&" })) + } else { + (ex, "*".repeat(pat_ref_count - ty_ref_count)) + }; let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`"; let sugg = format!( "if {} == {}{} {}{els_str}", snippet_with_context(cx, ex.span, ctxt, "..", &mut app).0, // PartialEq for different reference counts may not exist. - "&".repeat(ref_count_diff), + ref_or_deref_adjust, snippet_with_applicability(cx, arm.pat.span, "..", &mut app), expr_block(cx, arm.body, ctxt, "..", Some(expr.span), &mut app), ); diff --git a/clippy_lints/src/methods/expect_fun_call.rs b/clippy_lints/src/methods/expect_fun_call.rs index 82e5a6d5a412..6e5da5bda8c9 100644 --- a/clippy_lints/src/methods/expect_fun_call.rs +++ b/clippy_lints/src/methods/expect_fun_call.rs @@ -2,13 +2,15 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::macros::{FormatArgsStorage, format_args_inputs_span, root_macro_call_first_node}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, is_type_lang_item}; +use clippy_utils::visitors::for_each_expr; +use clippy_utils::{contains_return, is_inside_always_const_context, peel_blocks}; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; -use rustc_middle::ty; use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; use std::borrow::Cow; +use std::ops::ControlFlow; use super::EXPECT_FUN_CALL; @@ -23,10 +25,10 @@ pub(super) fn check<'tcx>( receiver: &'tcx hir::Expr<'tcx>, args: &'tcx [hir::Expr<'tcx>], ) { - // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or + // Strip `{}`, `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or // `&str` fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> { - let mut arg_root = arg; + let mut arg_root = peel_blocks(arg); loop { arg_root = match &arg_root.kind { hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr, @@ -47,124 +49,68 @@ pub(super) fn check<'tcx>( arg_root } - // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be - // converted to string. - fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool { - let arg_ty = cx.typeck_results().expr_ty(arg); - if is_type_lang_item(cx, arg_ty, hir::LangItem::String) { - return false; - } - if let ty::Ref(_, ty, ..) = arg_ty.kind() - && ty.is_str() - && can_be_static_str(cx, arg) - { - return false; - } - true + fn contains_call<'a>(cx: &LateContext<'a>, arg: &'a hir::Expr<'a>) -> bool { + for_each_expr(cx, arg, |expr| { + if matches!(expr.kind, hir::ExprKind::MethodCall { .. } | hir::ExprKind::Call { .. }) + && !is_inside_always_const_context(cx.tcx, expr.hir_id) + { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }) + .is_some() } - // Check if an expression could have type `&'static str`, knowing that it - // has type `&str` for some lifetime. - fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool { - match arg.kind { - hir::ExprKind::Lit(_) => true, - hir::ExprKind::Call(fun, _) => { - if let hir::ExprKind::Path(ref p) = fun.kind { - match cx.qpath_res(p, fun.hir_id) { - hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!( - cx.tcx.fn_sig(def_id).instantiate_identity().output().skip_binder().kind(), - ty::Ref(re, ..) if re.is_static(), - ), - _ => false, - } - } else { - false - } - }, - hir::ExprKind::MethodCall(..) => { - cx.typeck_results() - .type_dependent_def_id(arg.hir_id) - .is_some_and(|method_id| { - matches!( - cx.tcx.fn_sig(method_id).instantiate_identity().output().skip_binder().kind(), - ty::Ref(re, ..) if re.is_static() - ) - }) - }, - hir::ExprKind::Path(ref p) => matches!( - cx.qpath_res(p, arg.hir_id), - hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static { .. }, _) - ), - _ => false, - } - } + if name == sym::expect + && let [arg] = args + && let arg_root = get_arg_root(cx, arg) + && contains_call(cx, arg_root) + && !contains_return(arg_root) + { + let receiver_type = cx.typeck_results().expr_ty_adjusted(receiver); + let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym::Option) { + "||" + } else if is_type_diagnostic_item(cx, receiver_type, sym::Result) { + "|_|" + } else { + return; + }; - fn is_call(node: &hir::ExprKind<'_>) -> bool { - match node { - hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => { - is_call(&expr.kind) - }, - hir::ExprKind::Call(..) - | hir::ExprKind::MethodCall(..) - // These variants are debatable or require further examination - | hir::ExprKind::If(..) - | hir::ExprKind::Match(..) - | hir::ExprKind::Block{ .. } => true, - _ => false, - } - } + let span_replace_word = method_span.with_hi(expr.span.hi()); - if args.len() != 1 || name != sym::expect || !is_call(&args[0].kind) { - return; - } + let mut applicability = Applicability::MachineApplicable; - let receiver_type = cx.typeck_results().expr_ty_adjusted(receiver); - let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym::Option) { - "||" - } else if is_type_diagnostic_item(cx, receiver_type, sym::Result) { - "|_|" - } else { - return; - }; - - let arg_root = get_arg_root(cx, &args[0]); - - let span_replace_word = method_span.with_hi(expr.span.hi()); - - let mut applicability = Applicability::MachineApplicable; - - // Special handling for `format!` as arg_root - if let Some(macro_call) = root_macro_call_first_node(cx, arg_root) { - if cx.tcx.is_diagnostic_item(sym::format_macro, macro_call.def_id) - && let Some(format_args) = format_args_storage.get(cx, arg_root, macro_call.expn) - { - let span = format_args_inputs_span(format_args); - let sugg = snippet_with_applicability(cx, span, "..", &mut applicability); - span_lint_and_sugg( - cx, - EXPECT_FUN_CALL, - span_replace_word, - format!("function call inside of `{name}`"), - "try", - format!("unwrap_or_else({closure_args} panic!({sugg}))"), - applicability, - ); + // Special handling for `format!` as arg_root + if let Some(macro_call) = root_macro_call_first_node(cx, arg_root) { + if cx.tcx.is_diagnostic_item(sym::format_macro, macro_call.def_id) + && let Some(format_args) = format_args_storage.get(cx, arg_root, macro_call.expn) + { + let span = format_args_inputs_span(format_args); + let sugg = snippet_with_applicability(cx, span, "..", &mut applicability); + span_lint_and_sugg( + cx, + EXPECT_FUN_CALL, + span_replace_word, + format!("function call inside of `{name}`"), + "try", + format!("unwrap_or_else({closure_args} panic!({sugg}))"), + applicability, + ); + } + return; } - return; - } - let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability); - if requires_to_string(cx, arg_root) { - arg_root_snippet.to_mut().push_str(".to_string()"); - } + let arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability); - span_lint_and_sugg( - cx, - EXPECT_FUN_CALL, - span_replace_word, - format!("function call inside of `{name}`"), - "try", - format!("unwrap_or_else({closure_args} {{ panic!(\"{{}}\", {arg_root_snippet}) }})"), - applicability, - ); + span_lint_and_sugg( + cx, + EXPECT_FUN_CALL, + span_replace_word, + format!("function call inside of `{name}`"), + "try", + format!("unwrap_or_else({closure_args} panic!(\"{{}}\", {arg_root_snippet}))"), + applicability, + ); + } } diff --git a/clippy_lints/src/methods/filter_map_bool_then.rs b/clippy_lints/src/methods/filter_map_bool_then.rs index 965993808f6b..94944bd9445b 100644 --- a/clippy_lints/src/methods/filter_map_bool_then.rs +++ b/clippy_lints/src/methods/filter_map_bool_then.rs @@ -1,6 +1,6 @@ use super::FILTER_MAP_BOOL_THEN; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::SpanRangeExt; +use clippy_utils::source::{SpanRangeExt, snippet_with_context}; use clippy_utils::ty::is_copy; use clippy_utils::{ CaptureKind, can_move_expr_to_closure, contains_return, is_from_proc_macro, is_trait_method, peel_blocks, @@ -45,9 +45,11 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, arg: & .filter(|adj| matches!(adj.kind, Adjust::Deref(_))) .count() && let Some(param_snippet) = param.span.get_source_text(cx) - && let Some(filter) = recv.span.get_source_text(cx) - && let Some(map) = then_body.span.get_source_text(cx) { + let mut applicability = Applicability::MachineApplicable; + let (filter, _) = snippet_with_context(cx, recv.span, expr.span.ctxt(), "..", &mut applicability); + let (map, _) = snippet_with_context(cx, then_body.span, expr.span.ctxt(), "..", &mut applicability); + span_lint_and_then( cx, FILTER_MAP_BOOL_THEN, @@ -62,7 +64,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, arg: & "filter(|&{param_snippet}| {derefs}{filter}).map(|{param_snippet}| {map})", derefs = "*".repeat(needed_derefs) ), - Applicability::MachineApplicable, + applicability, ); } else { diag.help("consider using `filter` then `map` instead"); diff --git a/clippy_lints/src/methods/manual_inspect.rs b/clippy_lints/src/methods/manual_inspect.rs index 21f2ce8b7c90..bc96815944d5 100644 --- a/clippy_lints/src/methods/manual_inspect.rs +++ b/clippy_lints/src/methods/manual_inspect.rs @@ -100,7 +100,6 @@ pub(crate) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, arg: &Expr<'_>, name: match x { UseKind::Return(s) => edits.push((s.with_leading_whitespace(cx).with_ctxt(s.ctxt()), String::new())), UseKind::Borrowed(s) => { - #[expect(clippy::range_plus_one)] let range = s.map_range(cx, |_, src, range| { let src = src.get(range.clone())?; let trimmed = src.trim_start_matches([' ', '\t', '\n', '\r', '(']); diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index f2dabdd34387..bcd54557331b 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -3859,6 +3859,7 @@ declare_clippy_lint! { declare_clippy_lint! { /// ### What it does /// Checks for usage of `option.map(f).unwrap_or_default()` and `result.map(f).unwrap_or_default()` where f is a function or closure that returns the `bool` type. + /// Also checks for equality comparisons like `option.map(f) == Some(true)` and `result.map(f) == Ok(true)`. /// /// ### Why is this bad? /// Readability. These can be written more concisely as `option.is_some_and(f)` and `result.is_ok_and(f)`. @@ -3869,6 +3870,11 @@ declare_clippy_lint! { /// # let result: Result = Ok(1); /// option.map(|a| a > 10).unwrap_or_default(); /// result.map(|a| a > 10).unwrap_or_default(); + /// + /// option.map(|a| a > 10) == Some(true); + /// result.map(|a| a > 10) == Ok(true); + /// option.map(|a| a > 10) != Some(true); + /// result.map(|a| a > 10) != Ok(true); /// ``` /// Use instead: /// ```no_run @@ -3876,11 +3882,16 @@ declare_clippy_lint! { /// # let result: Result = Ok(1); /// option.is_some_and(|a| a > 10); /// result.is_ok_and(|a| a > 10); + /// + /// option.is_some_and(|a| a > 10); + /// result.is_ok_and(|a| a > 10); + /// option.is_none_or(|a| a > 10); + /// !result.is_ok_and(|a| a > 10); /// ``` #[clippy::version = "1.77.0"] pub MANUAL_IS_VARIANT_AND, pedantic, - "using `.map(f).unwrap_or_default()`, which is more succinctly expressed as `is_some_and(f)` or `is_ok_and(f)`" + "using `.map(f).unwrap_or_default()` or `.map(f) == Some/Ok(true)`, which are more succinctly expressed as `is_some_and(f)` or `is_ok_and(f)`" } declare_clippy_lint! { @@ -5275,10 +5286,6 @@ impl Methods { } map_identity::check(cx, expr, recv, m_arg, name, span); manual_inspect::check(cx, expr, m_arg, name, span, self.msrv); - crate::useless_conversion::check_function_application(cx, expr, recv, m_arg); - }, - (sym::map_break | sym::map_continue, [m_arg]) => { - crate::useless_conversion::check_function_application(cx, expr, recv, m_arg); }, (sym::map_or, [def, map]) => { option_map_or_none::check(cx, expr, recv, def, map); @@ -5546,7 +5553,7 @@ impl Methods { // Handle method calls whose receiver and arguments may come from expansion if let ExprKind::MethodCall(path, recv, args, _call_span) = expr.kind { match (path.ident.name, args) { - (sym::expect, [_]) if !matches!(method_call(recv), Some((sym::ok | sym::err, _, [], _, _))) => { + (sym::expect, [_]) => { unwrap_expect_used::check( cx, expr, diff --git a/clippy_lints/src/methods/or_fun_call.rs b/clippy_lints/src/methods/or_fun_call.rs index 6ce7dd3d4d0a..04f0e3c0479e 100644 --- a/clippy_lints/src/methods/or_fun_call.rs +++ b/clippy_lints/src/methods/or_fun_call.rs @@ -242,15 +242,23 @@ pub(super) fn check<'tcx>( let inner_arg = peel_blocks(arg); for_each_expr(cx, inner_arg, |ex| { let is_top_most_expr = ex.hir_id == inner_arg.hir_id; - if let hir::ExprKind::Call(fun, fun_args) = ex.kind { - let fun_span = if fun_args.is_empty() && is_top_most_expr { - Some(fun.span) - } else { - None - }; - if check_or_fn_call(cx, name, method_span, receiver, arg, Some(lambda), expr.span, fun_span) { - return ControlFlow::Break(()); - } + match ex.kind { + hir::ExprKind::Call(fun, fun_args) => { + let fun_span = if fun_args.is_empty() && is_top_most_expr { + Some(fun.span) + } else { + None + }; + if check_or_fn_call(cx, name, method_span, receiver, arg, Some(lambda), expr.span, fun_span) { + return ControlFlow::Break(()); + } + }, + hir::ExprKind::MethodCall(..) => { + if check_or_fn_call(cx, name, method_span, receiver, arg, Some(lambda), expr.span, None) { + return ControlFlow::Break(()); + } + }, + _ => {}, } ControlFlow::Continue(()) }); diff --git a/clippy_lints/src/missing_fields_in_debug.rs b/clippy_lints/src/missing_fields_in_debug.rs index 760ecf075892..18e2b384a463 100644 --- a/clippy_lints/src/missing_fields_in_debug.rs +++ b/clippy_lints/src/missing_fields_in_debug.rs @@ -7,9 +7,7 @@ use clippy_utils::{is_path_lang_item, sym}; use rustc_ast::LitKind; use rustc_data_structures::fx::FxHashSet; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::{ - Block, Expr, ExprKind, Impl, Item, ItemKind, LangItem, Node, QPath, TyKind, VariantData, -}; +use rustc_hir::{Block, Expr, ExprKind, Impl, Item, ItemKind, LangItem, Node, QPath, TyKind, VariantData}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{Ty, TypeckResults}; use rustc_session::declare_lint_pass; diff --git a/clippy_lints/src/missing_inline.rs b/clippy_lints/src/missing_inline.rs index c4a3d10299b6..5a5025973b5b 100644 --- a/clippy_lints/src/missing_inline.rs +++ b/clippy_lints/src/missing_inline.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint; use rustc_attr_data_structures::{AttributeKind, find_attr}; -use rustc_hir as hir; -use rustc_hir::Attribute; +use rustc_hir::def_id::DefId; +use rustc_hir::{self as hir, Attribute}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::ty::AssocItemContainer; use rustc_session::declare_lint_pass; @@ -97,11 +97,23 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { } match it.kind { hir::ItemKind::Fn { .. } => { + if fn_is_externally_exported(cx, it.owner_id.to_def_id()) { + return; + } + let desc = "a function"; let attrs = cx.tcx.hir_attrs(it.hir_id()); check_missing_inline_attrs(cx, attrs, it.span, desc); }, - hir::ItemKind::Trait(ref _constness, ref _is_auto, ref _unsafe, _ident, _generics, _bounds, trait_items) => { + hir::ItemKind::Trait( + ref _constness, + ref _is_auto, + ref _unsafe, + _ident, + _generics, + _bounds, + trait_items, + ) => { // note: we need to check if the trait is exported so we can't use // `LateLintPass::check_trait_item` here. for &tit in trait_items { @@ -173,3 +185,10 @@ impl<'tcx> LateLintPass<'tcx> for MissingInline { check_missing_inline_attrs(cx, attrs, impl_item.span, desc); } } + +/// Checks if this function is externally exported, where #[inline] wouldn't have the desired effect +/// and a rustc warning would be triggered, see #15301 +fn fn_is_externally_exported(cx: &LateContext<'_>, def_id: DefId) -> bool { + let attrs = cx.tcx.codegen_fn_attrs(def_id); + attrs.contains_extern_indicator() +} diff --git a/clippy_lints/src/missing_trait_methods.rs b/clippy_lints/src/missing_trait_methods.rs index fa61d0fa11af..399bf4e18064 100644 --- a/clippy_lints/src/missing_trait_methods.rs +++ b/clippy_lints/src/missing_trait_methods.rs @@ -66,7 +66,9 @@ impl<'tcx> LateLintPass<'tcx> for MissingTraitMethods { }) = item.kind && let Some(trait_id) = trait_ref.trait_def_id() { - let trait_item_ids: DefIdSet = cx.tcx.associated_items(item.owner_id) + let trait_item_ids: DefIdSet = cx + .tcx + .associated_items(item.owner_id) .in_definition_order() .filter_map(|assoc_item| assoc_item.trait_item_def_id) .collect(); diff --git a/clippy_lints/src/mixed_read_write_in_expression.rs b/clippy_lints/src/mixed_read_write_in_expression.rs index d9f4fb271fb4..a489c0a4a5a1 100644 --- a/clippy_lints/src/mixed_read_write_in_expression.rs +++ b/clippy_lints/src/mixed_read_write_in_expression.rs @@ -171,14 +171,11 @@ impl<'tcx> Visitor<'tcx> for DivergenceVisitor<'_, 'tcx> { ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => self.report_diverging_sub_expr(e), ExprKind::Call(func, _) => { let typ = self.cx.typeck_results().expr_ty(func); - match typ.kind() { - ty::FnDef(..) | ty::FnPtr(..) => { - let sig = typ.fn_sig(self.cx.tcx); - if self.cx.tcx.instantiate_bound_regions_with_erased(sig).output().kind() == &ty::Never { - self.report_diverging_sub_expr(e); - } - }, - _ => {}, + if typ.is_fn() { + let sig = typ.fn_sig(self.cx.tcx); + if self.cx.tcx.instantiate_bound_regions_with_erased(sig).output().kind() == &ty::Never { + self.report_diverging_sub_expr(e); + } } }, ExprKind::MethodCall(..) => { diff --git a/clippy_lints/src/mut_reference.rs b/clippy_lints/src/mut_reference.rs index 2f1ab3d2652a..31f51b457540 100644 --- a/clippy_lints/src/mut_reference.rs +++ b/clippy_lints/src/mut_reference.rs @@ -79,7 +79,7 @@ fn check_arguments<'tcx>( name: &str, fn_kind: &str, ) { - if let ty::FnDef(..) | ty::FnPtr(..) = type_definition.kind() { + if type_definition.is_fn() { let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs(); for (argument, parameter) in iter::zip(arguments, parameters) { if let ty::Ref(_, _, Mutability::Not) | ty::RawPtr(_, Mutability::Not) = parameter.kind() diff --git a/clippy_lints/src/needless_for_each.rs b/clippy_lints/src/needless_for_each.rs index 6a7c8436bad4..a67545e419ce 100644 --- a/clippy_lints/src/needless_for_each.rs +++ b/clippy_lints/src/needless_for_each.rs @@ -6,7 +6,7 @@ use rustc_session::declare_lint_pass; use rustc_span::Span; use clippy_utils::diagnostics::span_lint_and_then; -use clippy_utils::source::snippet_with_applicability; +use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::ty::has_iter_method; use clippy_utils::{is_trait_method, sym}; @@ -101,18 +101,23 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach { let body_param_sugg = snippet_with_applicability(cx, body.params[0].pat.span, "..", &mut applicability); let for_each_rev_sugg = snippet_with_applicability(cx, for_each_recv.span, "..", &mut applicability); - let body_value_sugg = snippet_with_applicability(cx, body.value.span, "..", &mut applicability); + let (body_value_sugg, is_macro_call) = + snippet_with_context(cx, body.value.span, for_each_recv.span.ctxt(), "..", &mut applicability); let sugg = format!( "for {} in {} {}", body_param_sugg, for_each_rev_sugg, - match body.value.kind { - ExprKind::Block(block, _) if is_let_desugar(block) => { - format!("{{ {body_value_sugg} }}") - }, - ExprKind::Block(_, _) => body_value_sugg.to_string(), - _ => format!("{{ {body_value_sugg}; }}"), + if is_macro_call { + format!("{{ {body_value_sugg}; }}") + } else { + match body.value.kind { + ExprKind::Block(block, _) if is_let_desugar(block) => { + format!("{{ {body_value_sugg} }}") + }, + ExprKind::Block(_, _) => body_value_sugg.to_string(), + _ => format!("{{ {body_value_sugg}; }}"), + } } ); diff --git a/clippy_lints/src/needless_pass_by_value.rs b/clippy_lints/src/needless_pass_by_value.rs index c97ecce75b46..2006a824402d 100644 --- a/clippy_lints/src/needless_pass_by_value.rs +++ b/clippy_lints/src/needless_pass_by_value.rs @@ -246,8 +246,10 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { for (span, suggestion) in clone_spans { diag.span_suggestion( span, - span.get_source_text(cx) - .map_or("change the call to".to_owned(), |src| format!("change `{src}` to")), + span.get_source_text(cx).map_or_else( + || "change the call to".to_owned(), + |src| format!("change `{src}` to"), + ), suggestion, Applicability::Unspecified, ); @@ -275,8 +277,10 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { for (span, suggestion) in clone_spans { diag.span_suggestion( span, - span.get_source_text(cx) - .map_or("change the call to".to_owned(), |src| format!("change `{src}` to")), + span.get_source_text(cx).map_or_else( + || "change the call to".to_owned(), + |src| format!("change `{src}` to"), + ), suggestion, Applicability::Unspecified, ); diff --git a/clippy_lints/src/new_without_default.rs b/clippy_lints/src/new_without_default.rs index 3b86f1d1f593..b598a390005b 100644 --- a/clippy_lints/src/new_without_default.rs +++ b/clippy_lints/src/new_without_default.rs @@ -65,11 +65,16 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { .. }) = item.kind { - for assoc_item in cx.tcx.associated_items(item.owner_id.def_id) + for assoc_item in cx + .tcx + .associated_items(item.owner_id.def_id) .filter_by_name_unhygienic(sym::new) { if let AssocKind::Fn { has_self: false, .. } = assoc_item.kind { - let impl_item = cx.tcx.hir_node_by_def_id(assoc_item.def_id.expect_local()).expect_impl_item(); + let impl_item = cx + .tcx + .hir_node_by_def_id(assoc_item.def_id.expect_local()) + .expect_impl_item(); if impl_item.span.in_external_macro(cx.sess().source_map()) { return; } diff --git a/clippy_lints/src/operators/arithmetic_side_effects.rs b/clippy_lints/src/operators/arithmetic_side_effects.rs index a78a342d4fe3..466beb04b074 100644 --- a/clippy_lints/src/operators/arithmetic_side_effects.rs +++ b/clippy_lints/src/operators/arithmetic_side_effects.rs @@ -3,12 +3,11 @@ use clippy_config::Conf; use clippy_utils::consts::{ConstEvalCtxt, Constant}; use clippy_utils::diagnostics::span_lint; use clippy_utils::ty::is_type_diagnostic_item; -use clippy_utils::{expr_or_init, is_from_proc_macro, is_lint_allowed, peel_hir_expr_refs, peel_hir_expr_unary}; +use clippy_utils::{expr_or_init, is_from_proc_macro, is_lint_allowed, peel_hir_expr_refs, peel_hir_expr_unary, sym}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, Ty}; use rustc_session::impl_lint_pass; -use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; use {rustc_ast as ast, rustc_hir as hir}; @@ -89,6 +88,18 @@ impl ArithmeticSideEffects { self.allowed_unary.contains(ty_string_elem) } + fn is_non_zero_u(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { + if let ty::Adt(adt, substs) = ty.kind() + && cx.tcx.is_diagnostic_item(sym::NonZero, adt.did()) + && let int_type = substs.type_at(0) + && matches!(int_type.kind(), ty::Uint(_)) + { + true + } else { + false + } + } + /// Verifies built-in types that have specific allowed operations fn has_specific_allowed_type_and_operation<'tcx>( cx: &LateContext<'tcx>, @@ -97,33 +108,12 @@ impl ArithmeticSideEffects { rhs_ty: Ty<'tcx>, ) -> bool { let is_div_or_rem = matches!(op, hir::BinOpKind::Div | hir::BinOpKind::Rem); - let is_non_zero_u = |cx: &LateContext<'tcx>, ty: Ty<'tcx>| { - let tcx = cx.tcx; - - let ty::Adt(adt, substs) = ty.kind() else { return false }; - - if !tcx.is_diagnostic_item(sym::NonZero, adt.did()) { - return false; - } - - let int_type = substs.type_at(0); - let unsigned_int_types = [ - tcx.types.u8, - tcx.types.u16, - tcx.types.u32, - tcx.types.u64, - tcx.types.u128, - tcx.types.usize, - ]; - - unsigned_int_types.contains(&int_type) - }; let is_sat_or_wrap = |ty: Ty<'_>| { is_type_diagnostic_item(cx, ty, sym::Saturating) || is_type_diagnostic_item(cx, ty, sym::Wrapping) }; // If the RHS is `NonZero`, then division or module by zero will never occur. - if is_non_zero_u(cx, rhs_ty) && is_div_or_rem { + if Self::is_non_zero_u(cx, rhs_ty) && is_div_or_rem { return true; } @@ -219,6 +209,18 @@ impl ArithmeticSideEffects { let (mut actual_rhs, rhs_ref_counter) = peel_hir_expr_refs(rhs); actual_lhs = expr_or_init(cx, actual_lhs); actual_rhs = expr_or_init(cx, actual_rhs); + + // `NonZeroU*.get() - 1`, will never overflow + if let hir::BinOpKind::Sub = op + && let hir::ExprKind::MethodCall(method, receiver, [], _) = actual_lhs.kind + && method.ident.name == sym::get + && let receiver_ty = cx.typeck_results().expr_ty(receiver).peel_refs() + && Self::is_non_zero_u(cx, receiver_ty) + && let Some(1) = Self::literal_integer(cx, actual_rhs) + { + return; + } + let lhs_ty = cx.typeck_results().expr_ty(actual_lhs).peel_refs(); let rhs_ty = cx.typeck_results().expr_ty_adjusted(actual_rhs).peel_refs(); if self.has_allowed_binary(lhs_ty, rhs_ty) { @@ -227,6 +229,7 @@ impl ArithmeticSideEffects { if Self::has_specific_allowed_type_and_operation(cx, lhs_ty, op, rhs_ty) { return; } + let has_valid_op = if Self::is_integral(lhs_ty) && Self::is_integral(rhs_ty) { if let hir::BinOpKind::Shl | hir::BinOpKind::Shr = op { // At least for integers, shifts are already handled by the CTFE diff --git a/clippy_lints/src/operators/manual_is_multiple_of.rs b/clippy_lints/src/operators/manual_is_multiple_of.rs index 821178a43158..55bb78cfce5f 100644 --- a/clippy_lints/src/operators/manual_is_multiple_of.rs +++ b/clippy_lints/src/operators/manual_is_multiple_of.rs @@ -2,11 +2,12 @@ use clippy_utils::consts::is_zero_integer_const; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::sugg::Sugg; +use clippy_utils::ty::expr_type_is_certain; use rustc_ast::BinOpKind; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind}; use rustc_lint::LateContext; -use rustc_middle::ty; +use rustc_middle::ty::{self, Ty}; use super::MANUAL_IS_MULTIPLE_OF; @@ -22,9 +23,21 @@ pub(super) fn check<'tcx>( && let Some(operand) = uint_compare_to_zero(cx, op, lhs, rhs) && let ExprKind::Binary(operand_op, operand_left, operand_right) = operand.kind && operand_op.node == BinOpKind::Rem + && matches!( + cx.typeck_results().expr_ty_adjusted(operand_left).peel_refs().kind(), + ty::Uint(_) + ) + && matches!( + cx.typeck_results().expr_ty_adjusted(operand_right).peel_refs().kind(), + ty::Uint(_) + ) + && expr_type_is_certain(cx, operand_left) { let mut app = Applicability::MachineApplicable; - let divisor = Sugg::hir_with_applicability(cx, operand_right, "_", &mut app); + let divisor = deref_sugg( + Sugg::hir_with_applicability(cx, operand_right, "_", &mut app), + cx.typeck_results().expr_ty_adjusted(operand_right), + ); span_lint_and_sugg( cx, MANUAL_IS_MULTIPLE_OF, @@ -64,3 +77,11 @@ fn uint_compare_to_zero<'tcx>( matches!(cx.typeck_results().expr_ty_adjusted(operand).kind(), ty::Uint(_)).then_some(operand) } + +fn deref_sugg<'a>(sugg: Sugg<'a>, ty: Ty<'_>) -> Sugg<'a> { + if let ty::Ref(_, target_ty, _) = ty.kind() { + deref_sugg(sugg.deref(), *target_ty) + } else { + sugg + } +} diff --git a/clippy_lints/src/pattern_type_mismatch.rs b/clippy_lints/src/pattern_type_mismatch.rs index 19d9acfc9305..4197680dd047 100644 --- a/clippy_lints/src/pattern_type_mismatch.rs +++ b/clippy_lints/src/pattern_type_mismatch.rs @@ -96,6 +96,12 @@ impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Match(_, arms, _) = expr.kind { + // if the match is generated by an external macro, the writer does not control + // how the scrutinee (`match &scrutiny { ... }`) is matched + if expr.span.in_external_macro(cx.sess().source_map()) { + return; + } + for arm in arms { let pat = &arm.pat; if apply_lint(cx, pat, DerefPossible::Possible) { diff --git a/clippy_lints/src/ptr.rs b/clippy_lints/src/ptr.rs index 94cdcf000548..b3058c51afdb 100644 --- a/clippy_lints/src/ptr.rs +++ b/clippy_lints/src/ptr.rs @@ -584,7 +584,13 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &Body<'tcx>, args: &[ Some((Node::Stmt(_), _)) => (), Some((Node::LetStmt(l), _)) => { // Only trace simple bindings. e.g `let x = y;` - if let PatKind::Binding(BindingMode::NONE, id, _, None) = l.pat.kind { + if let PatKind::Binding(BindingMode::NONE, id, ident, None) = l.pat.kind + // Let's not lint for the current parameter. The user may still intend to mutate + // (or, if not mutate, then perhaps call a method that's not otherwise available + // for) the referenced value behind the parameter through this local let binding + // with the underscore being only temporary. + && !ident.name.as_str().starts_with('_') + { self.bindings.insert(id, args_idx); } else { set_skip_flag(); @@ -650,7 +656,14 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &Body<'tcx>, args: &[ .filter_map(|(i, arg)| { let param = &body.params[arg.idx]; match param.pat.kind { - PatKind::Binding(BindingMode::NONE, id, _, None) if !is_lint_allowed(cx, PTR_ARG, param.hir_id) => { + PatKind::Binding(BindingMode::NONE, id, ident, None) + if !is_lint_allowed(cx, PTR_ARG, param.hir_id) + // Let's not lint for the current parameter. The user may still intend to mutate + // (or, if not mutate, then perhaps call a method that's not otherwise available + // for) the referenced value behind the parameter with the underscore being only + // temporary. + && !ident.name.as_str().starts_with('_') => + { Some((id, i)) }, _ => { diff --git a/clippy_lints/src/ranges.rs b/clippy_lints/src/ranges.rs index d292ed86ea4c..9281678b3d83 100644 --- a/clippy_lints/src/ranges.rs +++ b/clippy_lints/src/ranges.rs @@ -4,15 +4,20 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_the use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::{SpanRangeExt, snippet, snippet_with_applicability}; use clippy_utils::sugg::Sugg; -use clippy_utils::{get_parent_expr, higher, is_in_const_context, is_integer_const, path_to_local}; +use clippy_utils::ty::implements_trait; +use clippy_utils::{ + expr_use_ctxt, fn_def_id, get_parent_expr, higher, is_in_const_context, is_integer_const, is_path_lang_item, + path_to_local, +}; +use rustc_ast::Mutability; use rustc_ast::ast::RangeLimits; use rustc_errors::Applicability; -use rustc_hir::{BinOpKind, Expr, ExprKind, HirId}; -use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty; +use rustc_hir::{BinOpKind, Expr, ExprKind, HirId, LangItem, Node}; +use rustc_lint::{LateContext, LateLintPass, Lint}; +use rustc_middle::ty::{self, ClauseKind, GenericArgKind, PredicatePolarity, Ty}; use rustc_session::impl_lint_pass; -use rustc_span::Span; use rustc_span::source_map::Spanned; +use rustc_span::{Span, sym}; use std::cmp::Ordering; declare_clippy_lint! { @@ -24,6 +29,12 @@ declare_clippy_lint! { /// The code is more readable with an inclusive range /// like `x..=y`. /// + /// ### Limitations + /// The lint is conservative and will trigger only when switching + /// from an exclusive to an inclusive range is provably safe from + /// a typing point of view. This corresponds to situations where + /// the range is used as an iterator, or for indexing. + /// /// ### Known problems /// Will add unnecessary pair of parentheses when the /// expression is not wrapped in a pair but starts with an opening parenthesis @@ -34,11 +45,6 @@ declare_clippy_lint! { /// exclusive ranges, because they essentially add an extra branch that /// LLVM may fail to hoist out of the loop. /// - /// This will cause a warning that cannot be fixed if the consumer of the - /// range only accepts a specific range type, instead of the generic - /// `RangeBounds` trait - /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)). - /// /// ### Example /// ```no_run /// # let x = 0; @@ -71,11 +77,11 @@ declare_clippy_lint! { /// The code is more readable with an exclusive range /// like `x..y`. /// - /// ### Known problems - /// This will cause a warning that cannot be fixed if - /// the consumer of the range only accepts a specific range type, instead of - /// the generic `RangeBounds` trait - /// ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)). + /// ### Limitations + /// The lint is conservative and will trigger only when switching + /// from an inclusive to an exclusive range is provably safe from + /// a typing point of view. This corresponds to situations where + /// the range is used as an iterator, or for indexing. /// /// ### Example /// ```no_run @@ -344,70 +350,188 @@ fn check_range_bounds<'a, 'tcx>(cx: &'a LateContext<'tcx>, ex: &'a Expr<'_>) -> None } -// exclusive range plus one: `x..(y+1)` -fn check_exclusive_range_plus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { - if expr.span.can_be_used_for_suggestions() - && let Some(higher::Range { - start, - end: Some(end), - limits: RangeLimits::HalfOpen, - }) = higher::Range::hir(expr) - && let Some(y) = y_plus_one(cx, end) +/// Check whether `expr` could switch range types without breaking the typing requirements. This is +/// generally the case when `expr` is used as an iterator for example, or as a slice or `&str` +/// index. +/// +/// FIXME: Note that the current implementation may still return false positives. A proper fix would +/// check that the obligations are still satisfied after switching the range type. +fn can_switch_ranges<'tcx>( + cx: &LateContext<'tcx>, + expr: &'tcx Expr<'_>, + original: RangeLimits, + inner_ty: Ty<'tcx>, +) -> bool { + let use_ctxt = expr_use_ctxt(cx, expr); + let (Node::Expr(parent_expr), false) = (use_ctxt.node, use_ctxt.is_ty_unified) else { + return false; + }; + + // Check if `expr` is the argument of a compiler-generated `IntoIter::into_iter(expr)` + if let ExprKind::Call(func, [arg]) = parent_expr.kind + && arg.hir_id == use_ctxt.child_id + && is_path_lang_item(cx, func, LangItem::IntoIterIntoIter) { - let span = expr.span; - span_lint_and_then( - cx, - RANGE_PLUS_ONE, - span, - "an inclusive range would be more readable", - |diag| { - let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").maybe_paren().to_string()); - let end = Sugg::hir(cx, y, "y").maybe_paren(); - match span.with_source_text(cx, |src| src.starts_with('(') && src.ends_with(')')) { - Some(true) => { - diag.span_suggestion(span, "use", format!("({start}..={end})"), Applicability::MaybeIncorrect); - }, - Some(false) => { - diag.span_suggestion( - span, - "use", - format!("{start}..={end}"), - Applicability::MachineApplicable, // snippet - ); - }, - None => {}, - } - }, - ); + return true; + } + + // Check if `expr` is used as the receiver of a method of the `Iterator`, `IntoIterator`, + // or `RangeBounds` traits. + if let ExprKind::MethodCall(_, receiver, _, _) = parent_expr.kind + && receiver.hir_id == use_ctxt.child_id + && let Some(method_did) = cx.typeck_results().type_dependent_def_id(parent_expr.hir_id) + && let Some(trait_did) = cx.tcx.trait_of_item(method_did) + && matches!( + cx.tcx.get_diagnostic_name(trait_did), + Some(sym::Iterator | sym::IntoIterator | sym::RangeBounds) + ) + { + return true; + } + + // Check if `expr` is an argument of a call which requires an `Iterator`, `IntoIterator`, + // or `RangeBounds` trait. + if let ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args, _) = parent_expr.kind + && let Some(id) = fn_def_id(cx, parent_expr) + && let Some(arg_idx) = args.iter().position(|e| e.hir_id == use_ctxt.child_id) + { + let input_idx = if matches!(parent_expr.kind, ExprKind::MethodCall(..)) { + arg_idx + 1 + } else { + arg_idx + }; + let inputs = cx + .tcx + .liberate_late_bound_regions(id, cx.tcx.fn_sig(id).instantiate_identity()) + .inputs(); + let expr_ty = inputs[input_idx]; + // Check that the `expr` type is present only once, otherwise modifying just one of them might be + // risky if they are referenced using the same generic type for example. + if inputs.iter().enumerate().all(|(n, ty)| + n == input_idx + || !ty.walk().any(|arg| matches!(arg.kind(), + GenericArgKind::Type(ty) if ty == expr_ty))) + // Look for a clause requiring `Iterator`, `IntoIterator`, or `RangeBounds`, and resolving to `expr_type`. + && cx + .tcx + .param_env(id) + .caller_bounds() + .into_iter() + .any(|p| { + if let ClauseKind::Trait(t) = p.kind().skip_binder() + && t.polarity == PredicatePolarity::Positive + && matches!( + cx.tcx.get_diagnostic_name(t.trait_ref.def_id), + Some(sym::Iterator | sym::IntoIterator | sym::RangeBounds) + ) + { + t.self_ty() == expr_ty + } else { + false + } + }) + { + return true; + } + } + + // Check if `expr` is used for indexing, and if the switched range type could be used + // as well. + if let ExprKind::Index(outer_expr, index, _) = parent_expr.kind + && index.hir_id == expr.hir_id + // Build the switched range type (for example `RangeInclusive`). + && let Some(switched_range_def_id) = match original { + RangeLimits::HalfOpen => cx.tcx.lang_items().range_inclusive_struct(), + RangeLimits::Closed => cx.tcx.lang_items().range_struct(), + } + && let switched_range_ty = cx + .tcx + .type_of(switched_range_def_id) + .instantiate(cx.tcx, &[inner_ty.into()]) + // Check that the switched range type can be used for indexing the original expression + // through the `Index` or `IndexMut` trait. + && let ty::Ref(_, outer_ty, mutability) = cx.typeck_results().expr_ty_adjusted(outer_expr).kind() + && let Some(index_def_id) = match mutability { + Mutability::Not => cx.tcx.lang_items().index_trait(), + Mutability::Mut => cx.tcx.lang_items().index_mut_trait(), + } + && implements_trait(cx, *outer_ty, index_def_id, &[switched_range_ty.into()]) + // We could also check that the associated item of the `index_def_id` trait with the switched range type + // return the same type, but it is reasonable to expect so. We can't check that the result is identical + // in both `Index>` and `Index>` anyway. + { + return true; } + + false +} + +// exclusive range plus one: `x..(y+1)` +fn check_exclusive_range_plus_one<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { + check_range_switch( + cx, + expr, + RangeLimits::HalfOpen, + y_plus_one, + RANGE_PLUS_ONE, + "an inclusive range would be more readable", + "..=", + ); } // inclusive range minus one: `x..=(y-1)` -fn check_inclusive_range_minus_one(cx: &LateContext<'_>, expr: &Expr<'_>) { +fn check_inclusive_range_minus_one<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { + check_range_switch( + cx, + expr, + RangeLimits::Closed, + y_minus_one, + RANGE_MINUS_ONE, + "an exclusive range would be more readable", + "..", + ); +} + +/// Check for a `kind` of range in `expr`, check for `predicate` on the end, +/// and emit the `lint` with `msg` and the `operator`. +fn check_range_switch<'tcx>( + cx: &LateContext<'tcx>, + expr: &'tcx Expr<'_>, + kind: RangeLimits, + predicate: impl for<'hir> FnOnce(&LateContext<'_>, &Expr<'hir>) -> Option<&'hir Expr<'hir>>, + lint: &'static Lint, + msg: &'static str, + operator: &str, +) { if expr.span.can_be_used_for_suggestions() && let Some(higher::Range { start, end: Some(end), - limits: RangeLimits::Closed, + limits, }) = higher::Range::hir(expr) - && let Some(y) = y_minus_one(cx, end) + && limits == kind + && let Some(y) = predicate(cx, end) + && can_switch_ranges(cx, expr, kind, cx.typeck_results().expr_ty(y)) { - span_lint_and_then( - cx, - RANGE_MINUS_ONE, - expr.span, - "an exclusive range would be more readable", - |diag| { - let start = start.map_or(String::new(), |x| Sugg::hir(cx, x, "x").maybe_paren().to_string()); - let end = Sugg::hir(cx, y, "y").maybe_paren(); - diag.span_suggestion( - expr.span, - "use", - format!("{start}..{end}"), - Applicability::MachineApplicable, // snippet - ); - }, - ); + let span = expr.span; + span_lint_and_then(cx, lint, span, msg, |diag| { + let mut app = Applicability::MachineApplicable; + let start = start.map_or(String::new(), |x| { + Sugg::hir_with_applicability(cx, x, "", &mut app) + .maybe_paren() + .to_string() + }); + let end = Sugg::hir_with_applicability(cx, y, "", &mut app).maybe_paren(); + match span.with_source_text(cx, |src| src.starts_with('(') && src.ends_with(')')) { + Some(true) => { + diag.span_suggestion(span, "use", format!("({start}{operator}{end})"), app); + }, + Some(false) => { + diag.span_suggestion(span, "use", format!("{start}{operator}{end}"), app); + }, + None => {}, + } + }); } } @@ -494,7 +618,7 @@ fn check_reversed_empty_range(cx: &LateContext<'_>, expr: &Expr<'_>) { } } -fn y_plus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> { +fn y_plus_one<'tcx>(cx: &LateContext<'_>, expr: &Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { match expr.kind { ExprKind::Binary( Spanned { @@ -515,7 +639,7 @@ fn y_plus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<' } } -fn y_minus_one<'t>(cx: &LateContext<'_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> { +fn y_minus_one<'tcx>(cx: &LateContext<'_>, expr: &Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { match expr.kind { ExprKind::Binary( Spanned { diff --git a/clippy_lints/src/same_name_method.rs b/clippy_lints/src/same_name_method.rs index 85fde780e681..67eb71f7d074 100644 --- a/clippy_lints/src/same_name_method.rs +++ b/clippy_lints/src/same_name_method.rs @@ -3,7 +3,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{HirId, Impl, ItemKind, Node, Path, QPath, TraitRef, TyKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::{AssocKind, AssocItem}; +use rustc_middle::ty::{AssocItem, AssocKind}; use rustc_session::declare_lint_pass; use rustc_span::Span; use rustc_span::symbol::Symbol; @@ -53,11 +53,7 @@ impl<'tcx> LateLintPass<'tcx> for SameNameMethod { for id in cx.tcx.hir_free_items() { if matches!(cx.tcx.def_kind(id.owner_id), DefKind::Impl { .. }) && let item = cx.tcx.hir_item(id) - && let ItemKind::Impl(Impl { - of_trait, - self_ty, - .. - }) = &item.kind + && let ItemKind::Impl(Impl { of_trait, self_ty, .. }) = &item.kind && let TyKind::Path(QPath::Resolved(_, Path { res, .. })) = self_ty.kind { if !map.contains_key(res) { @@ -127,7 +123,9 @@ impl<'tcx> LateLintPass<'tcx> for SameNameMethod { }, None => { for assoc_item in cx.tcx.associated_items(id.owner_id).in_definition_order() { - let AssocKind::Fn { name, .. } = assoc_item.kind else { continue }; + let AssocKind::Fn { name, .. } = assoc_item.kind else { + continue; + }; let impl_span = cx.tcx.def_span(assoc_item.def_id); let hir_id = cx.tcx.local_def_id_to_hir_id(assoc_item.def_id.expect_local()); if let Some(trait_spans) = existing_name.trait_methods.get(&name) { @@ -140,10 +138,7 @@ impl<'tcx> LateLintPass<'tcx> for SameNameMethod { |diag| { // TODO should we `span_note` on every trait? // iterate on trait_spans? - diag.span_note( - trait_spans[0], - format!("existing `{name}` defined here"), - ); + diag.span_note(trait_spans[0], format!("existing `{name}` defined here")); }, ); } diff --git a/clippy_lints/src/unused_async.rs b/clippy_lints/src/unused_async.rs index e67afc7f5a8b..5a3e4b7adf64 100644 --- a/clippy_lints/src/unused_async.rs +++ b/clippy_lints/src/unused_async.rs @@ -1,8 +1,12 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::is_def_id_trait_method; +use clippy_utils::usage::is_todo_unimplemented_stub; use rustc_hir::def::DefKind; use rustc_hir::intravisit::{FnKind, Visitor, walk_expr, walk_fn}; -use rustc_hir::{Body, Defaultness, Expr, ExprKind, FnDecl, HirId, Node, TraitItem, YieldSource}; +use rustc_hir::{ + Body, Closure, ClosureKind, CoroutineDesugaring, CoroutineKind, Defaultness, Expr, ExprKind, FnDecl, HirId, Node, + TraitItem, YieldSource, +}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::nested_filter; use rustc_session::impl_lint_pass; @@ -81,11 +85,8 @@ impl<'tcx> Visitor<'tcx> for AsyncFnVisitor<'_, 'tcx> { let is_async_block = matches!( ex.kind, - ExprKind::Closure(rustc_hir::Closure { - kind: rustc_hir::ClosureKind::Coroutine(rustc_hir::CoroutineKind::Desugared( - rustc_hir::CoroutineDesugaring::Async, - _ - )), + ExprKind::Closure(Closure { + kind: ClosureKind::Coroutine(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)), .. }) ); @@ -120,6 +121,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedAsync { && fn_kind.asyncness().is_async() && !is_def_id_trait_method(cx, def_id) && !is_default_trait_impl(cx, def_id) + && !async_fn_contains_todo_unimplemented_macro(cx, body) { let mut visitor = AsyncFnVisitor { cx, @@ -203,3 +205,18 @@ fn is_default_trait_impl(cx: &LateContext<'_>, def_id: LocalDefId) -> bool { }) ) } + +fn async_fn_contains_todo_unimplemented_macro(cx: &LateContext<'_>, body: &Body<'_>) -> bool { + if let ExprKind::Closure(closure) = body.value.kind + && let ClosureKind::Coroutine(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) = closure.kind + && let body = cx.tcx.hir_body(closure.body) + && let ExprKind::Block(block, _) = body.value.kind + && block.stmts.is_empty() + && let Some(expr) = block.expr + && let ExprKind::DropTemps(inner) = expr.kind + { + return is_todo_unimplemented_stub(cx, inner); + } + + false +} diff --git a/clippy_lints/src/unused_self.rs b/clippy_lints/src/unused_self.rs index 12da891a71b1..dff39974a373 100644 --- a/clippy_lints/src/unused_self.rs +++ b/clippy_lints/src/unused_self.rs @@ -1,12 +1,10 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_help; -use clippy_utils::macros::root_macro_call_first_node; -use clippy_utils::sym; +use clippy_utils::usage::is_todo_unimplemented_stub; use clippy_utils::visitors::is_local_used; -use rustc_hir::{Body, Impl, ImplItem, ImplItemKind, ItemKind}; +use rustc_hir::{Impl, ImplItem, ImplItemKind, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; -use std::ops::ControlFlow; declare_clippy_lint! { /// ### What it does @@ -60,18 +58,6 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id()).def_id; let parent_item = cx.tcx.hir_expect_item(parent); let assoc_item = cx.tcx.associated_item(impl_item.owner_id); - let contains_todo = |cx, body: &'_ Body<'_>| -> bool { - clippy_utils::visitors::for_each_expr_without_closures(body.value, |e| { - if let Some(macro_call) = root_macro_call_first_node(cx, e) - && cx.tcx.is_diagnostic_item(sym::todo_macro, macro_call.def_id) - { - ControlFlow::Break(()) - } else { - ControlFlow::Continue(()) - } - }) - .is_some() - }; if let ItemKind::Impl(Impl { of_trait: None, .. }) = parent_item.kind && assoc_item.is_method() && let ImplItemKind::Fn(.., body_id) = &impl_item.kind @@ -79,7 +65,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedSelf { && let body = cx.tcx.hir_body(*body_id) && let [self_param, ..] = body.params && !is_local_used(cx, body, self_param.pat.hir_id) - && !contains_todo(cx, body) + && !is_todo_unimplemented_stub(cx, body.value) { span_lint_and_help( cx, diff --git a/clippy_lints/src/unused_trait_names.rs b/clippy_lints/src/unused_trait_names.rs index b7a1d5b2123e..12f2804dbaa1 100644 --- a/clippy_lints/src/unused_trait_names.rs +++ b/clippy_lints/src/unused_trait_names.rs @@ -6,7 +6,7 @@ use clippy_utils::source::snippet_opt; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{Item, ItemKind, UseKind}; -use rustc_lint::{LateContext, LateLintPass, LintContext as _}; +use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::Visibility; use rustc_session::impl_lint_pass; use rustc_span::symbol::kw; @@ -59,7 +59,7 @@ impl_lint_pass!(UnusedTraitNames => [UNUSED_TRAIT_NAMES]); impl<'tcx> LateLintPass<'tcx> for UnusedTraitNames { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { - if !item.span.in_external_macro(cx.sess().source_map()) + if !item.span.from_expansion() && let ItemKind::Use(path, UseKind::Single(ident)) = item.kind // Ignore imports that already use Underscore && ident.name != kw::Underscore diff --git a/clippy_lints/src/useless_conversion.rs b/clippy_lints/src/useless_conversion.rs index 380ddea4e1e8..e5b20c0e0a13 100644 --- a/clippy_lints/src/useless_conversion.rs +++ b/clippy_lints/src/useless_conversion.rs @@ -176,6 +176,33 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { } }, + ExprKind::MethodCall(path, recv, [arg], _) => { + if matches!( + path.ident.name, + sym::map | sym::map_err | sym::map_break | sym::map_continue + ) && has_eligible_receiver(cx, recv, e) + && (is_trait_item(cx, arg, sym::Into) || is_trait_item(cx, arg, sym::From)) + && let ty::FnDef(_, args) = cx.typeck_results().expr_ty(arg).kind() + && let &[from_ty, to_ty] = args.into_type_list(cx.tcx).as_slice() + && same_type_and_consts(from_ty, to_ty) + { + span_lint_and_then( + cx, + USELESS_CONVERSION, + e.span.with_lo(recv.span.hi()), + format!("useless conversion to the same type: `{from_ty}`"), + |diag| { + diag.suggest_remove_item( + cx, + e.span.with_lo(recv.span.hi()), + "consider removing", + Applicability::MachineApplicable, + ); + }, + ); + } + }, + ExprKind::MethodCall(name, recv, [], _) => { if is_trait_method(cx, e, sym::Into) && name.ident.name == sym::into { let a = cx.typeck_results().expr_ty(e); @@ -412,32 +439,6 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { } } -/// Check if `arg` is a `Into::into` or `From::from` applied to `receiver` to give `expr`, through a -/// higher-order mapping function. -pub fn check_function_application(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, arg: &Expr<'_>) { - if has_eligible_receiver(cx, recv, expr) - && (is_trait_item(cx, arg, sym::Into) || is_trait_item(cx, arg, sym::From)) - && let ty::FnDef(_, args) = cx.typeck_results().expr_ty(arg).kind() - && let &[from_ty, to_ty] = args.into_type_list(cx.tcx).as_slice() - && same_type_and_consts(from_ty, to_ty) - { - span_lint_and_then( - cx, - USELESS_CONVERSION, - expr.span.with_lo(recv.span.hi()), - format!("useless conversion to the same type: `{from_ty}`"), - |diag| { - diag.suggest_remove_item( - cx, - expr.span.with_lo(recv.span.hi()), - "consider removing", - Applicability::MachineApplicable, - ); - }, - ); - } -} - fn has_eligible_receiver(cx: &LateContext<'_>, recv: &Expr<'_>, expr: &Expr<'_>) -> bool { if is_inherent_method_call(cx, expr) { matches!( diff --git a/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs b/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs index 88b099c477f9..41fafc08c259 100644 --- a/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs +++ b/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs @@ -2,6 +2,7 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::paths; use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_ast::{AttrStyle, DelimArgs}; +use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_hir::def::Res; use rustc_hir::def_id::LocalDefId; use rustc_hir::{ @@ -11,7 +12,6 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_lint_defs::declare_tool_lint; use rustc_middle::ty::TyCtxt; use rustc_session::declare_lint_pass; -use rustc_span::sym; declare_tool_lint! { /// ### What it does @@ -88,7 +88,10 @@ impl<'tcx> LateLintPass<'tcx> for DeriveDeserializeAllowingUnknown { } // Is it derived? - if !find_attr!(cx.tcx.get_all_attrs(item.owner_id), AttributeKind::AutomaticallyDerived(..)) { + if !find_attr!( + cx.tcx.get_all_attrs(item.owner_id), + AttributeKind::AutomaticallyDerived(..) + ) { return; } diff --git a/clippy_lints_internal/src/lint_without_lint_pass.rs b/clippy_lints_internal/src/lint_without_lint_pass.rs index 45a866030b2d..fda65bc84eda 100644 --- a/clippy_lints_internal/src/lint_without_lint_pass.rs +++ b/clippy_lints_internal/src/lint_without_lint_pass.rs @@ -1,7 +1,7 @@ use crate::internal_paths; use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; -use clippy_utils::is_lint_allowed; use clippy_utils::macros::root_macro_call_first_node; +use clippy_utils::{is_lint_allowed, sym}; use rustc_ast::ast::LitKind; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_hir as hir; @@ -12,9 +12,9 @@ use rustc_hir::{ExprKind, HirId, Item, MutTy, Mutability, Path, TyKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::nested_filter; use rustc_session::{declare_tool_lint, impl_lint_pass}; +use rustc_span::Span; use rustc_span::source_map::Spanned; use rustc_span::symbol::Symbol; -use rustc_span::{Span, sym}; declare_tool_lint! { /// ### What it does @@ -160,9 +160,8 @@ impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass { let body = cx.tcx.hir_body_owned_by( impl_item_refs .iter() - .find(|iiref| iiref.ident.as_str() == "lint_vec") + .find(|&&iiref| cx.tcx.item_name(iiref.owner_id) == sym::lint_vec) .expect("LintPass needs to implement lint_vec") - .id .owner_id .def_id, ); diff --git a/clippy_lints_internal/src/msrv_attr_impl.rs b/clippy_lints_internal/src/msrv_attr_impl.rs index 70b3c03d2bbd..66aeb910891a 100644 --- a/clippy_lints_internal/src/msrv_attr_impl.rs +++ b/clippy_lints_internal/src/msrv_attr_impl.rs @@ -1,6 +1,7 @@ use crate::internal_paths; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet; +use clippy_utils::sym; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass, LintContext}; @@ -40,7 +41,9 @@ impl LateLintPass<'_> for MsrvAttrImpl { .filter(|t| matches!(t.kind(), GenericArgKind::Type(_))) .any(|t| internal_paths::MSRV_STACK.matches_ty(cx, t.expect_ty())) }) - && !items.iter().any(|item| item.ident.name.as_str() == "check_attributes") + && !items + .iter() + .any(|&item| cx.tcx.item_name(item.owner_id) == sym::check_attributes) { let span = cx.sess().source_map().span_through_char(item.span, '{'); span_lint_and_sugg( diff --git a/clippy_utils/README.md b/clippy_utils/README.md index 645b644d9f4e..19e71f6af1de 100644 --- a/clippy_utils/README.md +++ b/clippy_utils/README.md @@ -8,7 +8,7 @@ This crate is only guaranteed to build with this `nightly` toolchain: ``` -nightly-2025-07-10 +nightly-2025-07-25 ``` diff --git a/clippy_utils/src/diagnostics.rs b/clippy_utils/src/diagnostics.rs index 8453165818b3..625e1eead213 100644 --- a/clippy_utils/src/diagnostics.rs +++ b/clippy_utils/src/diagnostics.rs @@ -22,10 +22,13 @@ fn docs_link(diag: &mut Diag<'_, ()>, lint: &'static Lint) { { diag.help(format!( "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{lint}", - &option_env!("RUST_RELEASE_NUM").map_or("master".to_string(), |n| { - // extract just major + minor version and ignore patch versions - format!("rust-{}", n.rsplit_once('.').unwrap().1) - }) + &option_env!("RUST_RELEASE_NUM").map_or_else( + || "master".to_string(), + |n| { + // extract just major + minor version and ignore patch versions + format!("rust-{}", n.rsplit_once('.').unwrap().1) + } + ) )); } } diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index ff1ee663f9bf..ce5af4d2f482 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -89,8 +89,8 @@ use std::sync::{Mutex, MutexGuard, OnceLock}; use itertools::Itertools; use rustc_abi::Integer; -use rustc_ast::join_path_syms; use rustc_ast::ast::{self, LitKind, RangeLimits}; +use rustc_ast::join_path_syms; use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::packed::Pu128; @@ -114,7 +114,7 @@ use rustc_middle::hir::nested_filter; use rustc_middle::hir::place::PlaceBase; use rustc_middle::lint::LevelAndSource; use rustc_middle::mir::{AggregateKind, Operand, RETURN_PLACE, Rvalue, StatementKind, TerminatorKind}; -use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow}; +use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, PointerCoercion}; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{ self as rustc_ty, Binder, BorrowKind, ClosureKind, EarlyBinder, GenericArgKind, GenericArgsRef, IntTy, Ty, TyCtxt, @@ -1897,6 +1897,7 @@ pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { /// * `|x| { return x }` /// * `|x| { return x; }` /// * `|(x, y)| (x, y)` +/// * `|[x, y]| [x, y]` /// /// Consider calling [`is_expr_untyped_identity_function`] or [`is_expr_identity_function`] instead. fn is_body_identity_function(cx: &LateContext<'_>, func: &Body<'_>) -> bool { @@ -1907,9 +1908,9 @@ fn is_body_identity_function(cx: &LateContext<'_>, func: &Body<'_>) -> bool { .get(pat.hir_id) .is_some_and(|mode| matches!(mode.0, ByRef::Yes(_))) { - // If a tuple `(x, y)` is of type `&(i32, i32)`, then due to match ergonomics, - // the inner patterns become references. Don't consider this the identity function - // as that changes types. + // If the parameter is `(x, y)` of type `&(T, T)`, or `[x, y]` of type `&[T; 2]`, then + // due to match ergonomics, the inner patterns become references. Don't consider this + // the identity function as that changes types. return false; } @@ -1922,6 +1923,13 @@ fn is_body_identity_function(cx: &LateContext<'_>, func: &Body<'_>) -> bool { { pats.iter().zip(tup).all(|(pat, expr)| check_pat(cx, pat, expr)) }, + (PatKind::Slice(before, slice, after), ExprKind::Array(arr)) + if slice.is_none() && before.len() + after.len() == arr.len() => + { + (before.iter().chain(after)) + .zip(arr) + .all(|(pat, expr)| check_pat(cx, pat, expr)) + }, _ => false, } } @@ -3269,15 +3277,13 @@ fn maybe_get_relative_path(from: &DefPath, to: &DefPath, max_super: usize) -> St if go_up_by > max_super { // `super` chain would be too long, just use the absolute path instead - join_path_syms( - once(kw::Crate).chain(to.data.iter().filter_map(|el| { - if let DefPathData::TypeNs(sym) = el.data { - Some(sym) - } else { - None - } - })) - ) + join_path_syms(once(kw::Crate).chain(to.data.iter().filter_map(|el| { + if let DefPathData::TypeNs(sym) = el.data { + Some(sym) + } else { + None + } + }))) } else { join_path_syms(repeat_n(kw::Super, go_up_by).chain(path)) } @@ -3560,3 +3566,14 @@ pub fn potential_return_of_enclosing_body(cx: &LateContext<'_>, expr: &Expr<'_>) // enclosing body. false } + +/// Checks if the expression has adjustments that require coercion, for example: dereferencing with +/// overloaded deref, coercing pointers and `dyn` objects. +pub fn expr_adjustment_requires_coercion(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { + cx.typeck_results().expr_adjustments(expr).iter().any(|adj| { + matches!( + adj.kind, + Adjust::Deref(Some(_)) | Adjust::Pointer(PointerCoercion::Unsize) | Adjust::NeverToAny + ) + }) +} diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index c681806517af..ea8cfc59356a 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -308,10 +308,11 @@ fn local_item_child_by_name(tcx: TyCtxt<'_>, local_id: LocalDefId, ns: PathNS, n None } }), - ItemKind::Impl(..) | ItemKind::Trait(..) - => tcx.associated_items(local_id).filter_by_name_unhygienic(name) - .find(|assoc_item| ns.matches(Some(assoc_item.namespace()))) - .map(|assoc_item| assoc_item.def_id), + ItemKind::Impl(..) | ItemKind::Trait(..) => tcx + .associated_items(local_id) + .filter_by_name_unhygienic(name) + .find(|assoc_item| ns.matches(Some(assoc_item.namespace()))) + .map(|assoc_item| assoc_item.def_id), _ => None, } } diff --git a/clippy_utils/src/sym.rs b/clippy_utils/src/sym.rs index 8a8218c6976f..934be97d94e5 100644 --- a/clippy_utils/src/sym.rs +++ b/clippy_utils/src/sym.rs @@ -98,6 +98,7 @@ generate! { ceil_char_boundary, chain, chars, + check_attributes, checked_abs, checked_add, checked_isqrt, @@ -196,6 +197,7 @@ generate! { kw, last, lazy_static, + lint_vec, ln, lock, lock_api, @@ -261,6 +263,7 @@ generate! { read_to_end, read_to_string, read_unaligned, + redundant_imports, redundant_pub_crate, regex, rem_euclid, diff --git a/clippy_utils/src/ty/mod.rs b/clippy_utils/src/ty/mod.rs index fe208c032f4c..d70232ef3aa5 100644 --- a/clippy_utils/src/ty/mod.rs +++ b/clippy_utils/src/ty/mod.rs @@ -492,10 +492,7 @@ pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) { /// Returns `true` if the given type is an `unsafe` function. pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { - match ty.kind() { - ty::FnDef(..) | ty::FnPtr(..) => ty.fn_sig(cx.tcx).safety().is_unsafe(), - _ => false, - } + ty.is_fn() && ty.fn_sig(cx.tcx).safety().is_unsafe() } /// Returns the base type for HIR references and pointers. diff --git a/clippy_utils/src/ty/type_certainty/mod.rs b/clippy_utils/src/ty/type_certainty/mod.rs index 84df36c75bf8..d9c7e6eac9f6 100644 --- a/clippy_utils/src/ty/type_certainty/mod.rs +++ b/clippy_utils/src/ty/type_certainty/mod.rs @@ -12,10 +12,11 @@ //! be considered a bug. use crate::paths::{PathNS, lookup_path}; +use rustc_ast::{LitFloatType, LitIntType, LitKind}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt, walk_qpath, walk_ty}; -use rustc_hir::{self as hir, AmbigArg, Expr, ExprKind, GenericArgs, HirId, Node, PathSegment, QPath, TyKind}; +use rustc_hir::{self as hir, AmbigArg, Expr, ExprKind, GenericArgs, HirId, Node, Param, PathSegment, QPath, TyKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, AdtDef, GenericArgKind, Ty}; use rustc_span::Span; @@ -24,22 +25,24 @@ mod certainty; use certainty::{Certainty, Meet, join, meet}; pub fn expr_type_is_certain(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { - expr_type_certainty(cx, expr).is_certain() + expr_type_certainty(cx, expr, false).is_certain() } -fn expr_type_certainty(cx: &LateContext<'_>, expr: &Expr<'_>) -> Certainty { +/// Determine the type certainty of `expr`. `in_arg` indicates that the expression happens within +/// the evaluation of a function or method call argument. +fn expr_type_certainty(cx: &LateContext<'_>, expr: &Expr<'_>, in_arg: bool) -> Certainty { let certainty = match &expr.kind { ExprKind::Unary(_, expr) | ExprKind::Field(expr, _) | ExprKind::Index(expr, _, _) - | ExprKind::AddrOf(_, _, expr) => expr_type_certainty(cx, expr), + | ExprKind::AddrOf(_, _, expr) => expr_type_certainty(cx, expr, in_arg), - ExprKind::Array(exprs) => join(exprs.iter().map(|expr| expr_type_certainty(cx, expr))), + ExprKind::Array(exprs) => join(exprs.iter().map(|expr| expr_type_certainty(cx, expr, in_arg))), ExprKind::Call(callee, args) => { - let lhs = expr_type_certainty(cx, callee); + let lhs = expr_type_certainty(cx, callee, false); let rhs = if type_is_inferable_from_arguments(cx, expr) { - meet(args.iter().map(|arg| expr_type_certainty(cx, arg))) + meet(args.iter().map(|arg| expr_type_certainty(cx, arg, true))) } else { Certainty::Uncertain }; @@ -47,7 +50,7 @@ fn expr_type_certainty(cx: &LateContext<'_>, expr: &Expr<'_>) -> Certainty { }, ExprKind::MethodCall(method, receiver, args, _) => { - let mut receiver_type_certainty = expr_type_certainty(cx, receiver); + let mut receiver_type_certainty = expr_type_certainty(cx, receiver, false); // Even if `receiver_type_certainty` is `Certain(Some(..))`, the `Self` type in the method // identified by `type_dependent_def_id(..)` can differ. This can happen as a result of a `deref`, // for example. So update the `DefId` in `receiver_type_certainty` (if any). @@ -59,7 +62,8 @@ fn expr_type_certainty(cx: &LateContext<'_>, expr: &Expr<'_>) -> Certainty { let lhs = path_segment_certainty(cx, receiver_type_certainty, method, false); let rhs = if type_is_inferable_from_arguments(cx, expr) { meet( - std::iter::once(receiver_type_certainty).chain(args.iter().map(|arg| expr_type_certainty(cx, arg))), + std::iter::once(receiver_type_certainty) + .chain(args.iter().map(|arg| expr_type_certainty(cx, arg, true))), ) } else { Certainty::Uncertain @@ -67,16 +71,39 @@ fn expr_type_certainty(cx: &LateContext<'_>, expr: &Expr<'_>) -> Certainty { lhs.join(rhs) }, - ExprKind::Tup(exprs) => meet(exprs.iter().map(|expr| expr_type_certainty(cx, expr))), + ExprKind::Tup(exprs) => meet(exprs.iter().map(|expr| expr_type_certainty(cx, expr, in_arg))), - ExprKind::Binary(_, lhs, rhs) => expr_type_certainty(cx, lhs).meet(expr_type_certainty(cx, rhs)), + ExprKind::Binary(_, lhs, rhs) => { + // If one of the side of the expression is uncertain, the certainty will come from the other side, + // with no information on the type. + match ( + expr_type_certainty(cx, lhs, in_arg), + expr_type_certainty(cx, rhs, in_arg), + ) { + (Certainty::Uncertain, Certainty::Certain(_)) | (Certainty::Certain(_), Certainty::Uncertain) => { + Certainty::Certain(None) + }, + (l, r) => l.meet(r), + } + }, - ExprKind::Lit(_) => Certainty::Certain(None), + ExprKind::Lit(lit) => { + if !in_arg + && matches!( + lit.node, + LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) + ) + { + Certainty::Uncertain + } else { + Certainty::Certain(None) + } + }, ExprKind::Cast(_, ty) => type_certainty(cx, ty), ExprKind::If(_, if_expr, Some(else_expr)) => { - expr_type_certainty(cx, if_expr).join(expr_type_certainty(cx, else_expr)) + expr_type_certainty(cx, if_expr, in_arg).join(expr_type_certainty(cx, else_expr, in_arg)) }, ExprKind::Path(qpath) => qpath_certainty(cx, qpath, false), @@ -188,6 +215,20 @@ fn qpath_certainty(cx: &LateContext<'_>, qpath: &QPath<'_>, resolves_to_type: bo certainty } +/// Tries to tell whether `param` resolves to something certain, e.g., a non-wildcard type if +/// present. The certainty `DefId` is cleared before returning. +fn param_certainty(cx: &LateContext<'_>, param: &Param<'_>) -> Certainty { + let owner_did = cx.tcx.hir_enclosing_body_owner(param.hir_id); + let Some(fn_decl) = cx.tcx.hir_fn_decl_by_hir_id(cx.tcx.local_def_id_to_hir_id(owner_did)) else { + return Certainty::Uncertain; + }; + let inputs = fn_decl.inputs; + let body_params = cx.tcx.hir_body_owned_by(owner_did).params; + std::iter::zip(body_params, inputs) + .find(|(p, _)| p.hir_id == param.hir_id) + .map_or(Certainty::Uncertain, |(_, ty)| type_certainty(cx, ty).clear_def_id()) +} + fn path_segment_certainty( cx: &LateContext<'_>, parent_certainty: Certainty, @@ -240,15 +281,16 @@ fn path_segment_certainty( // `get_parent` because `hir_id` refers to a `Pat`, and we're interested in the node containing the `Pat`. Res::Local(hir_id) => match cx.tcx.parent_hir_node(hir_id) { - // An argument's type is always certain. - Node::Param(..) => Certainty::Certain(None), + // A parameter's type is not always certain, as it may come from an untyped closure definition, + // or from a wildcard in a typed closure definition. + Node::Param(param) => param_certainty(cx, param), // A local's type is certain if its type annotation is certain or it has an initializer whose // type is certain. Node::LetStmt(local) => { let lhs = local.ty.map_or(Certainty::Uncertain, |ty| type_certainty(cx, ty)); let rhs = local .init - .map_or(Certainty::Uncertain, |init| expr_type_certainty(cx, init)); + .map_or(Certainty::Uncertain, |init| expr_type_certainty(cx, init, false)); let certainty = lhs.join(rhs); if resolves_to_type { certainty diff --git a/clippy_utils/src/usage.rs b/clippy_utils/src/usage.rs index 1b049b6d12c4..76d43feee12e 100644 --- a/clippy_utils/src/usage.rs +++ b/clippy_utils/src/usage.rs @@ -1,3 +1,4 @@ +use crate::macros::root_macro_call_first_node; use crate::visitors::{Descend, Visitable, for_each_expr, for_each_expr_without_closures}; use crate::{self as utils, get_enclosing_loop_or_multi_call_closure}; use core::ops::ControlFlow; @@ -9,6 +10,7 @@ use rustc_lint::LateContext; use rustc_middle::hir::nested_filter; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty; +use rustc_span::sym; /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined. pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option { @@ -140,6 +142,46 @@ impl<'tcx> Visitor<'tcx> for BindingUsageFinder<'_, 'tcx> { } } +/// Checks if the given expression is a macro call to `todo!()` or `unimplemented!()`. +pub fn is_todo_unimplemented_macro(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { + root_macro_call_first_node(cx, expr).is_some_and(|macro_call| { + [sym::todo_macro, sym::unimplemented_macro] + .iter() + .any(|&sym| cx.tcx.is_diagnostic_item(sym, macro_call.def_id)) + }) +} + +/// Checks if the given expression is a stub, i.e., a `todo!()` or `unimplemented!()` expression, +/// or a block whose last expression is a `todo!()` or `unimplemented!()`. +pub fn is_todo_unimplemented_stub(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { + if let ExprKind::Block(block, _) = expr.kind { + if let Some(last_expr) = block.expr { + return is_todo_unimplemented_macro(cx, last_expr); + } + + return block.stmts.last().is_some_and(|stmt| { + if let hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr) = stmt.kind { + return is_todo_unimplemented_macro(cx, expr); + } + false + }); + } + + is_todo_unimplemented_macro(cx, expr) +} + +/// Checks if the given expression contains macro call to `todo!()` or `unimplemented!()`. +pub fn contains_todo_unimplement_macro(cx: &LateContext<'_>, expr: &'_ Expr<'_>) -> bool { + for_each_expr_without_closures(expr, |e| { + if is_todo_unimplemented_macro(cx, e) { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }) + .is_some() +} + pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool { for_each_expr_without_closures(expression, |e| { match e.kind { diff --git a/rust-toolchain.toml b/rust-toolchain.toml index f46e079db3f1..0edb80edd04e 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,6 +1,6 @@ [toolchain] # begin autogenerated nightly -channel = "nightly-2025-07-10" +channel = "nightly-2025-07-25" # end autogenerated nightly components = ["cargo", "llvm-tools", "rust-src", "rust-std", "rustc", "rustc-dev", "rustfmt"] profile = "minimal" diff --git a/rustc_tools_util/src/lib.rs b/rustc_tools_util/src/lib.rs index b45edf234558..194ed84d04c2 100644 --- a/rustc_tools_util/src/lib.rs +++ b/rustc_tools_util/src/lib.rs @@ -157,7 +157,8 @@ pub fn get_commit_date() -> Option { #[must_use] pub fn get_compiler_version() -> Option { - get_output("rustc", &["-V"]) + let compiler = std::option_env!("RUSTC").unwrap_or("rustc"); + get_output(compiler, &["-V"]) } #[must_use] @@ -172,6 +173,8 @@ pub fn get_channel(compiler_version: Option) -> String { return String::from("beta"); } else if rustc_output.contains("nightly") { return String::from("nightly"); + } else if rustc_output.contains("dev") { + return String::from("dev"); } } diff --git a/tests/compile-test.rs b/tests/compile-test.rs index 83f91ccaa7b4..464efc45c6b4 100644 --- a/tests/compile-test.rs +++ b/tests/compile-test.rs @@ -162,6 +162,10 @@ impl TestContext { // however has some staging logic that is hurting us here, so to work around // that we set both the "real" and "staging" rustc to TEST_RUSTC, including the // associated library paths. + #[expect( + clippy::option_env_unwrap, + reason = "TEST_RUSTC will ensure that the requested env vars are set during compile time" + )] if let Some(rustc) = option_env!("TEST_RUSTC") { let libdir = option_env!("TEST_RUSTC_LIB").unwrap(); let sysroot = option_env!("TEST_SYSROOT").unwrap(); @@ -169,10 +173,7 @@ impl TestContext { p.envs.push(("RUSTC_REAL_LIBDIR".into(), Some(libdir.into()))); p.envs.push(("RUSTC_SNAPSHOT".into(), Some(rustc.into()))); p.envs.push(("RUSTC_SNAPSHOT_LIBDIR".into(), Some(libdir.into()))); - p.envs.push(( - "RUSTC_SYSROOT".into(), - Some(sysroot.into()), - )); + p.envs.push(("RUSTC_SYSROOT".into(), Some(sysroot.into()))); } p }, diff --git a/tests/ui-toml/check_incompatible_msrv_in_tests/check_incompatible_msrv_in_tests.enabled.stderr b/tests/ui-toml/check_incompatible_msrv_in_tests/check_incompatible_msrv_in_tests.enabled.stderr index 8a85d38fba3c..608264beb102 100644 --- a/tests/ui-toml/check_incompatible_msrv_in_tests/check_incompatible_msrv_in_tests.enabled.stderr +++ b/tests/ui-toml/check_incompatible_msrv_in_tests/check_incompatible_msrv_in_tests.enabled.stderr @@ -18,6 +18,8 @@ error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is | LL | sleep(Duration::new(1, 0)); | ^^^^^ + | + = note: you may want to conditionally increase the MSRV considered by Clippy using the `clippy::msrv` attribute error: aborting due to 3 previous errors diff --git a/tests/ui-toml/enum_variant_size/enum_variant_size.stderr b/tests/ui-toml/enum_variant_size/enum_variant_size.stderr index 020b3cc78782..a5dfd7015a39 100644 --- a/tests/ui-toml/enum_variant_size/enum_variant_size.stderr +++ b/tests/ui-toml/enum_variant_size/enum_variant_size.stderr @@ -12,7 +12,7 @@ LL | | } | = note: `-D clippy::large-enum-variant` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::large_enum_variant)]` -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B([u8; 501]), LL + B(Box<[u8; 501]>), diff --git a/tests/ui/approx_const.rs b/tests/ui/approx_const.rs index 6461666be8f5..fc493421a165 100644 --- a/tests/ui/approx_const.rs +++ b/tests/ui/approx_const.rs @@ -106,4 +106,19 @@ fn main() { //~^ approx_constant let no_tau = 6.3; + + // issue #15194 + #[allow(clippy::excessive_precision)] + let x: f64 = 3.1415926535897932384626433832; + //~^ approx_constant + + #[allow(clippy::excessive_precision)] + let _: f64 = 003.14159265358979311599796346854418516159057617187500; + //~^ approx_constant + + let almost_frac_1_sqrt_2 = 00.70711; + //~^ approx_constant + + let almost_frac_1_sqrt_2 = 00.707_11; + //~^ approx_constant } diff --git a/tests/ui/approx_const.stderr b/tests/ui/approx_const.stderr index f7bda0468cbd..32a3517ff2e4 100644 --- a/tests/ui/approx_const.stderr +++ b/tests/ui/approx_const.stderr @@ -184,5 +184,37 @@ LL | let almost_tau = 6.28; | = help: consider using the constant directly -error: aborting due to 23 previous errors +error: approximate value of `f{32, 64}::consts::PI` found + --> tests/ui/approx_const.rs:112:18 + | +LL | let x: f64 = 3.1415926535897932384626433832; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using the constant directly + +error: approximate value of `f{32, 64}::consts::PI` found + --> tests/ui/approx_const.rs:116:18 + | +LL | let _: f64 = 003.14159265358979311599796346854418516159057617187500; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider using the constant directly + +error: approximate value of `f{32, 64}::consts::FRAC_1_SQRT_2` found + --> tests/ui/approx_const.rs:119:32 + | +LL | let almost_frac_1_sqrt_2 = 00.70711; + | ^^^^^^^^ + | + = help: consider using the constant directly + +error: approximate value of `f{32, 64}::consts::FRAC_1_SQRT_2` found + --> tests/ui/approx_const.rs:122:32 + | +LL | let almost_frac_1_sqrt_2 = 00.707_11; + | ^^^^^^^^^ + | + = help: consider using the constant directly + +error: aborting due to 27 previous errors diff --git a/tests/ui/arc_with_non_send_sync.stderr b/tests/ui/arc_with_non_send_sync.stderr index 5556b0df88c9..ce726206b0cd 100644 --- a/tests/ui/arc_with_non_send_sync.stderr +++ b/tests/ui/arc_with_non_send_sync.stderr @@ -5,7 +5,7 @@ LL | let _ = Arc::new(RefCell::new(42)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `Arc>` is not `Send` and `Sync` as `RefCell` is not `Sync` - = help: if the `Arc` will not used be across threads replace it with an `Rc` + = help: if the `Arc` will not be used across threads replace it with an `Rc` = help: otherwise make `RefCell` `Send` and `Sync` or consider a wrapper type such as `Mutex` = note: `-D clippy::arc-with-non-send-sync` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::arc_with_non_send_sync)]` @@ -17,7 +17,7 @@ LL | let _ = Arc::new(mutex.lock().unwrap()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `Arc>` is not `Send` and `Sync` as `MutexGuard<'_, i32>` is not `Send` - = help: if the `Arc` will not used be across threads replace it with an `Rc` + = help: if the `Arc` will not be used across threads replace it with an `Rc` = help: otherwise make `MutexGuard<'_, i32>` `Send` and `Sync` or consider a wrapper type such as `Mutex` error: usage of an `Arc` that is not `Send` and `Sync` @@ -27,7 +27,7 @@ LL | let _ = Arc::new(&42 as *const i32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `Arc<*const i32>` is not `Send` and `Sync` as `*const i32` is neither `Send` nor `Sync` - = help: if the `Arc` will not used be across threads replace it with an `Rc` + = help: if the `Arc` will not be used across threads replace it with an `Rc` = help: otherwise make `*const i32` `Send` and `Sync` or consider a wrapper type such as `Mutex` error: aborting due to 3 previous errors diff --git a/tests/ui/arithmetic_side_effects.rs b/tests/ui/arithmetic_side_effects.rs index 21be2af201f0..3245b2c983e1 100644 --- a/tests/ui/arithmetic_side_effects.rs +++ b/tests/ui/arithmetic_side_effects.rs @@ -664,6 +664,20 @@ pub fn issue_12318() { //~^ arithmetic_side_effects } +pub fn issue_15225() { + use core::num::{NonZero, NonZeroU8}; + + let one = const { NonZeroU8::new(1).unwrap() }; + let _ = one.get() - 1; + + let one: NonZero = const { NonZero::new(1).unwrap() }; + let _ = one.get() - 1; + + type AliasedType = u8; + let one: NonZero = const { NonZero::new(1).unwrap() }; + let _ = one.get() - 1; +} + pub fn explicit_methods() { use core::ops::Add; let one: i32 = 1; diff --git a/tests/ui/arithmetic_side_effects.stderr b/tests/ui/arithmetic_side_effects.stderr index e15fb612be5e..4150493ba94a 100644 --- a/tests/ui/arithmetic_side_effects.stderr +++ b/tests/ui/arithmetic_side_effects.stderr @@ -758,13 +758,13 @@ LL | one.sub_assign(1); | ^^^^^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> tests/ui/arithmetic_side_effects.rs:670:5 + --> tests/ui/arithmetic_side_effects.rs:684:5 | LL | one.add(&one); | ^^^^^^^^^^^^^ error: arithmetic operation that can potentially result in unexpected side-effects - --> tests/ui/arithmetic_side_effects.rs:672:5 + --> tests/ui/arithmetic_side_effects.rs:686:5 | LL | Box::new(one).add(one); | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/assign_ops.fixed b/tests/ui/assign_ops.fixed index eee61f949e76..3754b9dfe744 100644 --- a/tests/ui/assign_ops.fixed +++ b/tests/ui/assign_ops.fixed @@ -84,6 +84,7 @@ mod issue14871 { const ONE: Self; } + #[rustfmt::skip] // rustfmt doesn't understand the order of pub const on traits (yet) pub const trait NumberConstants { fn constant(value: usize) -> Self; } diff --git a/tests/ui/assign_ops.rs b/tests/ui/assign_ops.rs index 13ffcee0a3c8..0b878d4f490b 100644 --- a/tests/ui/assign_ops.rs +++ b/tests/ui/assign_ops.rs @@ -84,6 +84,7 @@ mod issue14871 { const ONE: Self; } + #[rustfmt::skip] // rustfmt doesn't understand the order of pub const on traits (yet) pub const trait NumberConstants { fn constant(value: usize) -> Self; } diff --git a/tests/ui/auxiliary/external_item.rs b/tests/ui/auxiliary/external_item.rs index ca4bc369e449..621e18f5c017 100644 --- a/tests/ui/auxiliary/external_item.rs +++ b/tests/ui/auxiliary/external_item.rs @@ -4,4 +4,4 @@ impl _ExternalStruct { pub fn _foo(self) {} } -pub fn _exernal_foo() {} +pub fn _external_foo() {} diff --git a/tests/ui/checked_conversions.fixed b/tests/ui/checked_conversions.fixed index 279a5b6e1ff8..6175275ef047 100644 --- a/tests/ui/checked_conversions.fixed +++ b/tests/ui/checked_conversions.fixed @@ -95,7 +95,7 @@ pub const fn issue_8898(i: u32) -> bool { #[clippy::msrv = "1.33"] fn msrv_1_33() { let value: i64 = 33; - let _ = value <= (u32::MAX as i64) && value >= 0; + let _ = value <= (u32::max_value() as i64) && value >= 0; } #[clippy::msrv = "1.34"] diff --git a/tests/ui/checked_conversions.rs b/tests/ui/checked_conversions.rs index c339bc674bbb..9ed0e8f660d0 100644 --- a/tests/ui/checked_conversions.rs +++ b/tests/ui/checked_conversions.rs @@ -95,13 +95,13 @@ pub const fn issue_8898(i: u32) -> bool { #[clippy::msrv = "1.33"] fn msrv_1_33() { let value: i64 = 33; - let _ = value <= (u32::MAX as i64) && value >= 0; + let _ = value <= (u32::max_value() as i64) && value >= 0; } #[clippy::msrv = "1.34"] fn msrv_1_34() { let value: i64 = 34; - let _ = value <= (u32::MAX as i64) && value >= 0; + let _ = value <= (u32::max_value() as i64) && value >= 0; //~^ checked_conversions } diff --git a/tests/ui/checked_conversions.stderr b/tests/ui/checked_conversions.stderr index 3841b9d5a4dd..624876dacb26 100644 --- a/tests/ui/checked_conversions.stderr +++ b/tests/ui/checked_conversions.stderr @@ -100,8 +100,8 @@ LL | let _ = value <= u16::MAX as u32 && value as i32 == 5; error: checked cast can be simplified --> tests/ui/checked_conversions.rs:104:13 | -LL | let _ = value <= (u32::MAX as i64) && value >= 0; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `u32::try_from(value).is_ok()` +LL | let _ = value <= (u32::max_value() as i64) && value >= 0; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `u32::try_from(value).is_ok()` error: aborting due to 17 previous errors diff --git a/tests/ui/expect.rs b/tests/ui/expect.rs index 8f7379f00214..1ab01ecfcfe3 100644 --- a/tests/ui/expect.rs +++ b/tests/ui/expect.rs @@ -16,7 +16,26 @@ fn expect_result() { //~^ expect_used } +#[allow(clippy::ok_expect)] +#[allow(clippy::err_expect)] +fn issue_15247() { + let x: Result = Err(0); + x.ok().expect("Huh"); + //~^ expect_used + + { x.ok() }.expect("..."); + //~^ expect_used + + let y: Result = Ok(0); + y.err().expect("Huh"); + //~^ expect_used + + { y.err() }.expect("..."); + //~^ expect_used +} + fn main() { expect_option(); expect_result(); + issue_15247(); } diff --git a/tests/ui/expect.stderr b/tests/ui/expect.stderr index 70cf3072003e..353fb7765315 100644 --- a/tests/ui/expect.stderr +++ b/tests/ui/expect.stderr @@ -24,5 +24,37 @@ LL | let _ = res.expect_err(""); | = note: if this value is an `Ok`, it will panic -error: aborting due to 3 previous errors +error: used `expect()` on an `Option` value + --> tests/ui/expect.rs:23:5 + | +LL | x.ok().expect("Huh"); + | ^^^^^^^^^^^^^^^^^^^^ + | + = note: if this value is `None`, it will panic + +error: used `expect()` on an `Option` value + --> tests/ui/expect.rs:26:5 + | +LL | { x.ok() }.expect("..."); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: if this value is `None`, it will panic + +error: used `expect()` on an `Option` value + --> tests/ui/expect.rs:30:5 + | +LL | y.err().expect("Huh"); + | ^^^^^^^^^^^^^^^^^^^^^ + | + = note: if this value is `None`, it will panic + +error: used `expect()` on an `Option` value + --> tests/ui/expect.rs:33:5 + | +LL | { y.err() }.expect("..."); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: if this value is `None`, it will panic + +error: aborting due to 7 previous errors diff --git a/tests/ui/expect_fun_call.fixed b/tests/ui/expect_fun_call.fixed index 73eaebf773c8..b923521afde1 100644 --- a/tests/ui/expect_fun_call.fixed +++ b/tests/ui/expect_fun_call.fixed @@ -90,17 +90,30 @@ fn main() { "foo" } - Some("foo").unwrap_or_else(|| { panic!("{}", get_string()) }); + const fn const_evaluable() -> &'static str { + "foo" + } + + Some("foo").unwrap_or_else(|| panic!("{}", get_string())); //~^ expect_fun_call - Some("foo").unwrap_or_else(|| { panic!("{}", get_string()) }); + Some("foo").unwrap_or_else(|| panic!("{}", get_string())); //~^ expect_fun_call - Some("foo").unwrap_or_else(|| { panic!("{}", get_string()) }); + Some("foo").unwrap_or_else(|| panic!("{}", get_string())); //~^ expect_fun_call - Some("foo").unwrap_or_else(|| { panic!("{}", get_static_str()) }); + Some("foo").unwrap_or_else(|| panic!("{}", get_static_str())); //~^ expect_fun_call - Some("foo").unwrap_or_else(|| { panic!("{}", get_non_static_str(&0).to_string()) }); + Some("foo").unwrap_or_else(|| panic!("{}", get_non_static_str(&0))); + //~^ expect_fun_call + + Some("foo").unwrap_or_else(|| panic!("{}", const_evaluable())); //~^ expect_fun_call + + const { + Some("foo").expect(const_evaluable()); + } + + Some("foo").expect(const { const_evaluable() }); } //Issue #3839 @@ -122,4 +135,15 @@ fn main() { let format_capture_and_value: Option = None; format_capture_and_value.unwrap_or_else(|| panic!("{error_code}, {}", 1)); //~^ expect_fun_call + + // Issue #15056 + let a = false; + Some(5).expect(if a { "a" } else { "b" }); + + let return_in_expect: Option = None; + return_in_expect.expect(if true { + "Error" + } else { + return; + }); } diff --git a/tests/ui/expect_fun_call.rs b/tests/ui/expect_fun_call.rs index ecebc9ebfb6f..bc58d24bc812 100644 --- a/tests/ui/expect_fun_call.rs +++ b/tests/ui/expect_fun_call.rs @@ -90,6 +90,10 @@ fn main() { "foo" } + const fn const_evaluable() -> &'static str { + "foo" + } + Some("foo").expect(&get_string()); //~^ expect_fun_call Some("foo").expect(get_string().as_ref()); @@ -101,6 +105,15 @@ fn main() { //~^ expect_fun_call Some("foo").expect(get_non_static_str(&0)); //~^ expect_fun_call + + Some("foo").expect(const_evaluable()); + //~^ expect_fun_call + + const { + Some("foo").expect(const_evaluable()); + } + + Some("foo").expect(const { const_evaluable() }); } //Issue #3839 @@ -122,4 +135,15 @@ fn main() { let format_capture_and_value: Option = None; format_capture_and_value.expect(&format!("{error_code}, {}", 1)); //~^ expect_fun_call + + // Issue #15056 + let a = false; + Some(5).expect(if a { "a" } else { "b" }); + + let return_in_expect: Option = None; + return_in_expect.expect(if true { + "Error" + } else { + return; + }); } diff --git a/tests/ui/expect_fun_call.stderr b/tests/ui/expect_fun_call.stderr index 36713196cb92..0692ecb4862e 100644 --- a/tests/ui/expect_fun_call.stderr +++ b/tests/ui/expect_fun_call.stderr @@ -38,58 +38,64 @@ LL | Some("foo").expect(format!("{} {}", 1, 2).as_ref()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{} {}", 1, 2))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:93:21 + --> tests/ui/expect_fun_call.rs:97:21 | LL | Some("foo").expect(&get_string()); - | ^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| { panic!("{}", get_string()) })` + | ^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", get_string()))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:95:21 + --> tests/ui/expect_fun_call.rs:99:21 | LL | Some("foo").expect(get_string().as_ref()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| { panic!("{}", get_string()) })` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", get_string()))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:97:21 + --> tests/ui/expect_fun_call.rs:101:21 | LL | Some("foo").expect(get_string().as_str()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| { panic!("{}", get_string()) })` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", get_string()))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:100:21 + --> tests/ui/expect_fun_call.rs:104:21 | LL | Some("foo").expect(get_static_str()); - | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| { panic!("{}", get_static_str()) })` + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", get_static_str()))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:102:21 + --> tests/ui/expect_fun_call.rs:106:21 | LL | Some("foo").expect(get_non_static_str(&0)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| { panic!("{}", get_non_static_str(&0).to_string()) })` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", get_non_static_str(&0)))` + +error: function call inside of `expect` + --> tests/ui/expect_fun_call.rs:109:21 + | +LL | Some("foo").expect(const_evaluable()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", const_evaluable()))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:107:16 + --> tests/ui/expect_fun_call.rs:120:16 | LL | Some(true).expect(&format!("key {}, {}", 1, 2)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("key {}, {}", 1, 2))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:114:17 + --> tests/ui/expect_fun_call.rs:127:17 | LL | opt_ref.expect(&format!("{:?}", opt_ref)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{:?}", opt_ref))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:119:20 + --> tests/ui/expect_fun_call.rs:132:20 | LL | format_capture.expect(&format!("{error_code}")); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{error_code}"))` error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:123:30 + --> tests/ui/expect_fun_call.rs:136:30 | LL | format_capture_and_value.expect(&format!("{error_code}, {}", 1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{error_code}, {}", 1))` -error: aborting due to 15 previous errors +error: aborting due to 16 previous errors diff --git a/tests/ui/filter_map_bool_then.fixed b/tests/ui/filter_map_bool_then.fixed index b3e112f19eb4..d370b85a67ef 100644 --- a/tests/ui/filter_map_bool_then.fixed +++ b/tests/ui/filter_map_bool_then.fixed @@ -89,3 +89,24 @@ fn issue11503() { let _: Vec = bools.iter().enumerate().filter(|&(i, b)| ****b).map(|(i, b)| i).collect(); //~^ filter_map_bool_then } + +fn issue15047() { + #[derive(Clone, Copy)] + enum MyEnum { + A, + B, + C, + } + + macro_rules! foo { + ($e:expr) => { + $e + 1 + }; + } + + let x = 1; + let _ = [(MyEnum::A, "foo", 1i32)] + .iter() + .filter(|&(t, s, i)| matches!(t, MyEnum::A if s.starts_with("bar"))).map(|(t, s, i)| foo!(x)); + //~^ filter_map_bool_then +} diff --git a/tests/ui/filter_map_bool_then.rs b/tests/ui/filter_map_bool_then.rs index d996b3cb3c52..12295cc24823 100644 --- a/tests/ui/filter_map_bool_then.rs +++ b/tests/ui/filter_map_bool_then.rs @@ -89,3 +89,24 @@ fn issue11503() { let _: Vec = bools.iter().enumerate().filter_map(|(i, b)| b.then(|| i)).collect(); //~^ filter_map_bool_then } + +fn issue15047() { + #[derive(Clone, Copy)] + enum MyEnum { + A, + B, + C, + } + + macro_rules! foo { + ($e:expr) => { + $e + 1 + }; + } + + let x = 1; + let _ = [(MyEnum::A, "foo", 1i32)] + .iter() + .filter_map(|(t, s, i)| matches!(t, MyEnum::A if s.starts_with("bar")).then(|| foo!(x))); + //~^ filter_map_bool_then +} diff --git a/tests/ui/filter_map_bool_then.stderr b/tests/ui/filter_map_bool_then.stderr index aeb1baeb35e6..edf6c6559396 100644 --- a/tests/ui/filter_map_bool_then.stderr +++ b/tests/ui/filter_map_bool_then.stderr @@ -61,5 +61,11 @@ error: usage of `bool::then` in `filter_map` LL | let _: Vec = bools.iter().enumerate().filter_map(|(i, b)| b.then(|| i)).collect(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `filter` then `map` instead: `filter(|&(i, b)| ****b).map(|(i, b)| i)` -error: aborting due to 10 previous errors +error: usage of `bool::then` in `filter_map` + --> tests/ui/filter_map_bool_then.rs:110:10 + | +LL | .filter_map(|(t, s, i)| matches!(t, MyEnum::A if s.starts_with("bar")).then(|| foo!(x))); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `filter` then `map` instead: `filter(|&(t, s, i)| matches!(t, MyEnum::A if s.starts_with("bar"))).map(|(t, s, i)| foo!(x))` + +error: aborting due to 11 previous errors diff --git a/tests/ui/flat_map_identity.fixed b/tests/ui/flat_map_identity.fixed index f62062326126..06a3eee9d84c 100644 --- a/tests/ui/flat_map_identity.fixed +++ b/tests/ui/flat_map_identity.fixed @@ -16,3 +16,16 @@ fn main() { let _ = iterator.flatten(); //~^ flat_map_identity } + +fn issue15198() { + let x = [[1, 2], [3, 4]]; + // don't lint: this is an `Iterator` + // match ergonomics makes the binding patterns into references + // so that its type changes to `Iterator` + let _ = x.iter().flat_map(|[x, y]| [x, y]); + let _ = x.iter().flat_map(|x| [x[0]]); + + // no match ergonomics for `[i32, i32]` + let _ = x.iter().copied().flatten(); + //~^ flat_map_identity +} diff --git a/tests/ui/flat_map_identity.rs b/tests/ui/flat_map_identity.rs index c59e749474ee..1cab7d559d8f 100644 --- a/tests/ui/flat_map_identity.rs +++ b/tests/ui/flat_map_identity.rs @@ -16,3 +16,16 @@ fn main() { let _ = iterator.flat_map(|x| return x); //~^ flat_map_identity } + +fn issue15198() { + let x = [[1, 2], [3, 4]]; + // don't lint: this is an `Iterator` + // match ergonomics makes the binding patterns into references + // so that its type changes to `Iterator` + let _ = x.iter().flat_map(|[x, y]| [x, y]); + let _ = x.iter().flat_map(|x| [x[0]]); + + // no match ergonomics for `[i32, i32]` + let _ = x.iter().copied().flat_map(|[x, y]| [x, y]); + //~^ flat_map_identity +} diff --git a/tests/ui/flat_map_identity.stderr b/tests/ui/flat_map_identity.stderr index 75137f5d9e57..18c863bf96d5 100644 --- a/tests/ui/flat_map_identity.stderr +++ b/tests/ui/flat_map_identity.stderr @@ -19,5 +19,11 @@ error: use of `flat_map` with an identity function LL | let _ = iterator.flat_map(|x| return x); | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `flatten()` -error: aborting due to 3 previous errors +error: use of `flat_map` with an identity function + --> tests/ui/flat_map_identity.rs:29:31 + | +LL | let _ = x.iter().copied().flat_map(|[x, y]| [x, y]); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `flatten()` + +error: aborting due to 4 previous errors diff --git a/tests/ui/if_then_some_else_none.fixed b/tests/ui/if_then_some_else_none.fixed index f774608712d1..d14a805b6667 100644 --- a/tests/ui/if_then_some_else_none.fixed +++ b/tests/ui/if_then_some_else_none.fixed @@ -122,3 +122,46 @@ const fn issue12103(x: u32) -> Option { // Should not issue an error in `const` context if x > 42 { Some(150) } else { None } } + +mod issue15257 { + struct Range { + start: u8, + end: u8, + } + + fn can_be_safely_rewrite(rs: &[&Range]) -> Option> { + (rs.len() == 1 && rs[0].start == rs[0].end).then(|| vec![rs[0].start]) + } + + fn reborrow_as_ptr(i: *mut i32) -> Option<*const i32> { + let modulo = unsafe { *i % 2 }; + (modulo == 0).then_some(i) + } + + fn reborrow_as_fn_ptr(i: i32) { + fn do_something(fn_: Option) { + todo!() + } + + fn item_fn(i: i32) { + todo!() + } + + do_something((i % 2 == 0).then_some(item_fn)); + } + + fn reborrow_as_fn_unsafe(i: i32) { + fn do_something(fn_: Option) { + todo!() + } + + fn item_fn(i: i32) { + todo!() + } + + do_something((i % 2 == 0).then_some(item_fn)); + + let closure_fn = |i: i32| {}; + do_something((i % 2 == 0).then_some(closure_fn)); + } +} diff --git a/tests/ui/if_then_some_else_none.rs b/tests/ui/if_then_some_else_none.rs index 8b8ff0a6ea00..bb0072f31573 100644 --- a/tests/ui/if_then_some_else_none.rs +++ b/tests/ui/if_then_some_else_none.rs @@ -143,3 +143,71 @@ const fn issue12103(x: u32) -> Option { // Should not issue an error in `const` context if x > 42 { Some(150) } else { None } } + +mod issue15257 { + struct Range { + start: u8, + end: u8, + } + + fn can_be_safely_rewrite(rs: &[&Range]) -> Option> { + if rs.len() == 1 && rs[0].start == rs[0].end { + //~^ if_then_some_else_none + Some(vec![rs[0].start]) + } else { + None + } + } + + fn reborrow_as_ptr(i: *mut i32) -> Option<*const i32> { + let modulo = unsafe { *i % 2 }; + if modulo == 0 { + //~^ if_then_some_else_none + Some(i) + } else { + None + } + } + + fn reborrow_as_fn_ptr(i: i32) { + fn do_something(fn_: Option) { + todo!() + } + + fn item_fn(i: i32) { + todo!() + } + + do_something(if i % 2 == 0 { + //~^ if_then_some_else_none + Some(item_fn) + } else { + None + }); + } + + fn reborrow_as_fn_unsafe(i: i32) { + fn do_something(fn_: Option) { + todo!() + } + + fn item_fn(i: i32) { + todo!() + } + + do_something(if i % 2 == 0 { + //~^ if_then_some_else_none + Some(item_fn) + } else { + None + }); + + let closure_fn = |i: i32| {}; + do_something(if i % 2 == 0 { + //~^ if_then_some_else_none + Some(closure_fn) + } else { + None + }); + } +} diff --git a/tests/ui/if_then_some_else_none.stderr b/tests/ui/if_then_some_else_none.stderr index 71285574ef24..c2e624a0a73b 100644 --- a/tests/ui/if_then_some_else_none.stderr +++ b/tests/ui/if_then_some_else_none.stderr @@ -58,5 +58,63 @@ error: this could be simplified with `bool::then` LL | if s == "1" { Some(true) } else { None } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `(s == "1").then(|| true)` -error: aborting due to 6 previous errors +error: this could be simplified with `bool::then` + --> tests/ui/if_then_some_else_none.rs:154:9 + | +LL | / if rs.len() == 1 && rs[0].start == rs[0].end { +LL | | +LL | | Some(vec![rs[0].start]) +LL | | } else { +LL | | None +LL | | } + | |_________^ help: try: `(rs.len() == 1 && rs[0].start == rs[0].end).then(|| vec![rs[0].start])` + +error: this could be simplified with `bool::then_some` + --> tests/ui/if_then_some_else_none.rs:164:9 + | +LL | / if modulo == 0 { +LL | | +LL | | Some(i) +LL | | } else { +LL | | None +LL | | } + | |_________^ help: try: `(modulo == 0).then_some(i)` + +error: this could be simplified with `bool::then_some` + --> tests/ui/if_then_some_else_none.rs:181:22 + | +LL | do_something(if i % 2 == 0 { + | ______________________^ +LL | | +LL | | Some(item_fn) +LL | | } else { +LL | | None +LL | | }); + | |_________^ help: try: `(i % 2 == 0).then_some(item_fn)` + +error: this could be simplified with `bool::then_some` + --> tests/ui/if_then_some_else_none.rs:198:22 + | +LL | do_something(if i % 2 == 0 { + | ______________________^ +LL | | +LL | | Some(item_fn) +LL | | } else { +LL | | None +LL | | }); + | |_________^ help: try: `(i % 2 == 0).then_some(item_fn)` + +error: this could be simplified with `bool::then_some` + --> tests/ui/if_then_some_else_none.rs:206:22 + | +LL | do_something(if i % 2 == 0 { + | ______________________^ +LL | | +LL | | Some(closure_fn) +LL | | } else { +LL | | None +LL | | }); + | |_________^ help: try: `(i % 2 == 0).then_some(closure_fn)` + +error: aborting due to 11 previous errors diff --git a/tests/ui/if_then_some_else_none_unfixable.rs b/tests/ui/if_then_some_else_none_unfixable.rs new file mode 100644 index 000000000000..be04299a6ab1 --- /dev/null +++ b/tests/ui/if_then_some_else_none_unfixable.rs @@ -0,0 +1,35 @@ +#![warn(clippy::if_then_some_else_none)] +#![allow(clippy::manual_is_multiple_of)] + +mod issue15257 { + use std::pin::Pin; + + #[derive(Default)] + pub struct Foo {} + pub trait Bar {} + impl Bar for Foo {} + + fn pointer_unsized_coercion(i: u32) -> Option> { + if i % 2 == 0 { + //~^ if_then_some_else_none + Some(Box::new(Foo::default())) + } else { + None + } + } + + fn reborrow_as_pin(i: Pin<&mut i32>) { + use std::ops::Rem; + + fn do_something(i: Option<&i32>) { + todo!() + } + + do_something(if i.rem(2) == 0 { + //~^ if_then_some_else_none + Some(&i) + } else { + None + }); + } +} diff --git a/tests/ui/if_then_some_else_none_unfixable.stderr b/tests/ui/if_then_some_else_none_unfixable.stderr new file mode 100644 index 000000000000..f77ce7910e76 --- /dev/null +++ b/tests/ui/if_then_some_else_none_unfixable.stderr @@ -0,0 +1,28 @@ +error: this could be simplified with `bool::then` + --> tests/ui/if_then_some_else_none_unfixable.rs:13:9 + | +LL | / if i % 2 == 0 { +LL | | +LL | | Some(Box::new(Foo::default())) +LL | | } else { +LL | | None +LL | | } + | |_________^ + | + = note: `-D clippy::if-then-some-else-none` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::if_then_some_else_none)]` + +error: this could be simplified with `bool::then` + --> tests/ui/if_then_some_else_none_unfixable.rs:28:22 + | +LL | do_something(if i.rem(2) == 0 { + | ______________________^ +LL | | +LL | | Some(&i) +LL | | } else { +LL | | None +LL | | }); + | |_________^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/incompatible_msrv.rs b/tests/ui/incompatible_msrv.rs index 99101b2bb8f2..f7f21e1850d0 100644 --- a/tests/ui/incompatible_msrv.rs +++ b/tests/ui/incompatible_msrv.rs @@ -1,8 +1,10 @@ #![warn(clippy::incompatible_msrv)] #![feature(custom_inner_attributes)] -#![feature(panic_internals)] +#![allow(stable_features)] +#![feature(strict_provenance)] // For use in test #![clippy::msrv = "1.3.0"] +use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::future::Future; @@ -13,6 +15,8 @@ fn foo() { let mut map: HashMap<&str, u32> = HashMap::new(); assert_eq!(map.entry("poneyland").key(), &"poneyland"); //~^ incompatible_msrv + //~| NOTE: `-D clippy::incompatible-msrv` implied by `-D warnings` + //~| HELP: to override `-D warnings` add `#[allow(clippy::incompatible_msrv)]` if let Entry::Vacant(v) = map.entry("poneyland") { v.into_key(); @@ -23,6 +27,18 @@ fn foo() { //~^ incompatible_msrv } +#[clippy::msrv = "1.2.0"] +static NO_BODY_BAD_MSRV: Option = None; +//~^ incompatible_msrv + +static NO_BODY_GOOD_MSRV: Option = None; + +#[clippy::msrv = "1.2.0"] +fn bad_type_msrv() { + let _: Option = None; + //~^ incompatible_msrv +} + #[test] fn test() { sleep(Duration::new(1, 0)); @@ -43,21 +59,22 @@ fn core_special_treatment(p: bool) { // But still lint code calling `core` functions directly if p { - core::panicking::panic("foo"); - //~^ ERROR: is `1.3.0` but this item is stable since `1.6.0` + let _ = core::iter::once_with(|| 0); + //~^ incompatible_msrv } // Lint code calling `core` from non-`core` macros macro_rules! my_panic { ($msg:expr) => { - core::panicking::panic($msg) - }; //~^ ERROR: is `1.3.0` but this item is stable since `1.6.0` + let _ = core::iter::once_with(|| $msg); + //~^ incompatible_msrv + }; } my_panic!("foo"); // Lint even when the macro comes from `core` and calls `core` functions - assert!(core::panicking::panic("out of luck")); - //~^ ERROR: is `1.3.0` but this item is stable since `1.6.0` + assert!(core::iter::once_with(|| 0).next().is_some()); + //~^ incompatible_msrv } #[clippy::msrv = "1.26.0"] @@ -70,7 +87,85 @@ fn lang_items() { #[clippy::msrv = "1.80.0"] fn issue14212() { let _ = std::iter::repeat_n((), 5); - //~^ ERROR: is `1.80.0` but this item is stable since `1.82.0` + //~^ incompatible_msrv +} + +#[clippy::msrv = "1.0.0"] +fn cstr_and_cstring_ok() { + let _: Option<&'static std::ffi::CStr> = None; + let _: Option = None; +} + +fn local_msrv_change_suggestion() { + let _ = std::iter::repeat_n((), 5); + //~^ incompatible_msrv + + #[cfg(any(test, not(test)))] + { + let _ = std::iter::repeat_n((), 5); + //~^ incompatible_msrv + //~| NOTE: you may want to conditionally increase the MSRV + + // Emit the additional note only once + let _ = std::iter::repeat_n((), 5); + //~^ incompatible_msrv + } +} + +#[clippy::msrv = "1.78.0"] +fn feature_enable_14425(ptr: *const u8) -> usize { + // Do not warn, because it is enabled through a feature even though + // it is stabilized only since Rust 1.84.0. + let r = ptr.addr(); + + // Warn about this which has been introduced in the same Rust version + // but is not allowed through a feature. + r.isqrt() + //~^ incompatible_msrv +} + +fn non_fn_items() { + let _ = std::io::ErrorKind::CrossesDevices; + //~^ incompatible_msrv +} + +#[clippy::msrv = "1.87.0"] +fn msrv_non_ok_in_const() { + { + let c = Cell::new(42); + _ = c.get(); + } + const { + let c = Cell::new(42); + _ = c.get(); + //~^ incompatible_msrv + } +} + +#[clippy::msrv = "1.88.0"] +fn msrv_ok_in_const() { + { + let c = Cell::new(42); + _ = c.get(); + } + const { + let c = Cell::new(42); + _ = c.get(); + } +} + +#[clippy::msrv = "1.86.0"] +fn enum_variant_not_ok() { + let _ = std::io::ErrorKind::InvalidFilename; + //~^ incompatible_msrv + let _ = const { std::io::ErrorKind::InvalidFilename }; + //~^ incompatible_msrv +} + +#[clippy::msrv = "1.87.0"] +fn enum_variant_ok() { + let _ = std::io::ErrorKind::InvalidFilename; + let _ = const { std::io::ErrorKind::InvalidFilename }; } fn main() {} diff --git a/tests/ui/incompatible_msrv.stderr b/tests/ui/incompatible_msrv.stderr index 5ea2bb9cc58b..e42360d296f5 100644 --- a/tests/ui/incompatible_msrv.stderr +++ b/tests/ui/incompatible_msrv.stderr @@ -1,5 +1,5 @@ error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.10.0` - --> tests/ui/incompatible_msrv.rs:14:39 + --> tests/ui/incompatible_msrv.rs:16:39 | LL | assert_eq!(map.entry("poneyland").key(), &"poneyland"); | ^^^^^ @@ -8,45 +8,107 @@ LL | assert_eq!(map.entry("poneyland").key(), &"poneyland"); = help: to override `-D warnings` add `#[allow(clippy::incompatible_msrv)]` error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.12.0` - --> tests/ui/incompatible_msrv.rs:18:11 + --> tests/ui/incompatible_msrv.rs:22:11 | LL | v.into_key(); | ^^^^^^^^^^ error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.4.0` - --> tests/ui/incompatible_msrv.rs:22:5 + --> tests/ui/incompatible_msrv.rs:26:5 | LL | sleep(Duration::new(1, 0)); | ^^^^^ -error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.6.0` - --> tests/ui/incompatible_msrv.rs:46:9 +error: current MSRV (Minimum Supported Rust Version) is `1.2.0` but this item is stable since `1.3.0` + --> tests/ui/incompatible_msrv.rs:31:33 | -LL | core::panicking::panic("foo"); - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | static NO_BODY_BAD_MSRV: Option = None; + | ^^^^^^^^ -error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.6.0` - --> tests/ui/incompatible_msrv.rs:53:13 +error: current MSRV (Minimum Supported Rust Version) is `1.2.0` but this item is stable since `1.3.0` + --> tests/ui/incompatible_msrv.rs:38:19 | -LL | core::panicking::panic($msg) - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | let _: Option = None; + | ^^^^^^^^ + +error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.43.0` + --> tests/ui/incompatible_msrv.rs:62:17 + | +LL | let _ = core::iter::once_with(|| 0); + | ^^^^^^^^^^^^^^^^^^^^^ + +error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.43.0` + --> tests/ui/incompatible_msrv.rs:69:21 + | +LL | let _ = core::iter::once_with(|| $msg); + | ^^^^^^^^^^^^^^^^^^^^^ ... LL | my_panic!("foo"); | ---------------- in this macro invocation | = note: this error originates in the macro `my_panic` (in Nightly builds, run with -Z macro-backtrace for more info) -error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.6.0` - --> tests/ui/incompatible_msrv.rs:59:13 +error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.43.0` + --> tests/ui/incompatible_msrv.rs:76:13 | -LL | assert!(core::panicking::panic("out of luck")); - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | assert!(core::iter::once_with(|| 0).next().is_some()); + | ^^^^^^^^^^^^^^^^^^^^^ error: current MSRV (Minimum Supported Rust Version) is `1.80.0` but this item is stable since `1.82.0` - --> tests/ui/incompatible_msrv.rs:72:13 + --> tests/ui/incompatible_msrv.rs:89:13 + | +LL | let _ = std::iter::repeat_n((), 5); + | ^^^^^^^^^^^^^^^^^^^ + +error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.82.0` + --> tests/ui/incompatible_msrv.rs:100:13 | LL | let _ = std::iter::repeat_n((), 5); | ^^^^^^^^^^^^^^^^^^^ -error: aborting due to 7 previous errors +error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.82.0` + --> tests/ui/incompatible_msrv.rs:105:17 + | +LL | let _ = std::iter::repeat_n((), 5); + | ^^^^^^^^^^^^^^^^^^^ + | + = note: you may want to conditionally increase the MSRV considered by Clippy using the `clippy::msrv` attribute + +error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.82.0` + --> tests/ui/incompatible_msrv.rs:110:17 + | +LL | let _ = std::iter::repeat_n((), 5); + | ^^^^^^^^^^^^^^^^^^^ + +error: current MSRV (Minimum Supported Rust Version) is `1.78.0` but this item is stable since `1.84.0` + --> tests/ui/incompatible_msrv.rs:123:7 + | +LL | r.isqrt() + | ^^^^^^^ + +error: current MSRV (Minimum Supported Rust Version) is `1.3.0` but this item is stable since `1.85.0` + --> tests/ui/incompatible_msrv.rs:128:13 + | +LL | let _ = std::io::ErrorKind::CrossesDevices; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: current MSRV (Minimum Supported Rust Version) is `1.87.0` but this item is stable in a `const` context since `1.88.0` + --> tests/ui/incompatible_msrv.rs:140:15 + | +LL | _ = c.get(); + | ^^^^^ + +error: current MSRV (Minimum Supported Rust Version) is `1.86.0` but this item is stable since `1.87.0` + --> tests/ui/incompatible_msrv.rs:159:13 + | +LL | let _ = std::io::ErrorKind::InvalidFilename; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: current MSRV (Minimum Supported Rust Version) is `1.86.0` but this item is stable since `1.87.0` + --> tests/ui/incompatible_msrv.rs:161:21 + | +LL | let _ = const { std::io::ErrorKind::InvalidFilename }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 17 previous errors diff --git a/tests/ui/large_enum_variant.32bit.stderr b/tests/ui/large_enum_variant.32bit.stderr index 80ca5daa1d57..ac1ed27a6b3b 100644 --- a/tests/ui/large_enum_variant.32bit.stderr +++ b/tests/ui/large_enum_variant.32bit.stderr @@ -12,7 +12,7 @@ LL | | } | = note: `-D clippy::large-enum-variant` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::large_enum_variant)]` -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B([i32; 8000]), LL + B(Box<[i32; 8000]>), @@ -30,7 +30,7 @@ LL | | ContainingLargeEnum(LargeEnum), LL | | } | |_^ the entire enum is at least 32004 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - ContainingLargeEnum(LargeEnum), LL + ContainingLargeEnum(Box), @@ -49,7 +49,7 @@ LL | | StructLikeLittle { x: i32, y: i32 }, LL | | } | |_^ the entire enum is at least 70008 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - ContainingMoreThanOneField(i32, [i32; 8000], [i32; 9500]), LL + ContainingMoreThanOneField(i32, Box<[i32; 8000]>, Box<[i32; 9500]>), @@ -67,7 +67,7 @@ LL | | StructLikeLarge { x: [i32; 8000], y: i32 }, LL | | } | |_^ the entire enum is at least 32008 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - StructLikeLarge { x: [i32; 8000], y: i32 }, LL + StructLikeLarge { x: Box<[i32; 8000]>, y: i32 }, @@ -85,7 +85,7 @@ LL | | StructLikeLarge2 { x: [i32; 8000] }, LL | | } | |_^ the entire enum is at least 32004 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - StructLikeLarge2 { x: [i32; 8000] }, LL + StructLikeLarge2 { x: Box<[i32; 8000]> }, @@ -104,7 +104,7 @@ LL | | C([u8; 200]), LL | | } | |_^ the entire enum is at least 1256 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B([u8; 1255]), LL + B(Box<[u8; 1255]>), @@ -122,7 +122,7 @@ LL | | ContainingMoreThanOneField([i32; 8000], [i32; 2], [i32; 9500], [i32; LL | | } | |_^ the entire enum is at least 70132 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - ContainingMoreThanOneField([i32; 8000], [i32; 2], [i32; 9500], [i32; 30]), LL + ContainingMoreThanOneField(Box<[i32; 8000]>, [i32; 2], Box<[i32; 9500]>, [i32; 30]), @@ -140,7 +140,7 @@ LL | | B(Struct2), LL | | } | |_^ the entire enum is at least 32004 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B(Struct2), LL + B(Box), @@ -158,7 +158,7 @@ LL | | B(Struct2), LL | | } | |_^ the entire enum is at least 32000 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B(Struct2), LL + B(Box), @@ -176,7 +176,7 @@ LL | | B(Struct2), LL | | } | |_^ the entire enum is at least 32000 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B(Struct2), LL + B(Box), @@ -199,7 +199,7 @@ note: boxing a variant would require the type no longer be `Copy` | LL | enum CopyableLargeEnum { | ^^^^^^^^^^^^^^^^^ -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum --> tests/ui/large_enum_variant.rs:118:5 | LL | B([u64; 8000]), @@ -222,7 +222,7 @@ note: boxing a variant would require the type no longer be `Copy` | LL | enum ManuallyCopyLargeEnum { | ^^^^^^^^^^^^^^^^^^^^^ -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum --> tests/ui/large_enum_variant.rs:124:5 | LL | B([u64; 8000]), @@ -245,7 +245,7 @@ note: boxing a variant would require the type no longer be `Copy` | LL | enum SomeGenericPossiblyCopyEnum { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum --> tests/ui/large_enum_variant.rs:138:5 | LL | B([u64; 4000]), @@ -263,7 +263,7 @@ LL | | Large((T, [u8; 512])), LL | | } | |_^ the entire enum is at least 512 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Large((T, [u8; 512])), LL + Large(Box<(T, [u8; 512])>), @@ -281,7 +281,7 @@ LL | | Small(u8), LL | | } | |_^ the entire enum is at least 516 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Large([Foo; 64]), LL + Large(Box<[Foo; 64]>), @@ -299,7 +299,7 @@ LL | | Error(PossiblyLargeEnumWithConst<256>), LL | | } | |_^ the entire enum is at least 514 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Error(PossiblyLargeEnumWithConst<256>), LL + Error(Box>), @@ -317,7 +317,7 @@ LL | | Recursive(Box), LL | | } | |_^ the entire enum is at least 516 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Large([u64; 64]), LL + Large(Box<[u64; 64]>), @@ -335,7 +335,7 @@ LL | | Error(WithRecursionAndGenerics), LL | | } | |_^ the entire enum is at least 516 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Error(WithRecursionAndGenerics), LL + Error(Box>), diff --git a/tests/ui/large_enum_variant.64bit.stderr b/tests/ui/large_enum_variant.64bit.stderr index 559bdf2a2f50..d8199f9090f6 100644 --- a/tests/ui/large_enum_variant.64bit.stderr +++ b/tests/ui/large_enum_variant.64bit.stderr @@ -12,7 +12,7 @@ LL | | } | = note: `-D clippy::large-enum-variant` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::large_enum_variant)]` -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B([i32; 8000]), LL + B(Box<[i32; 8000]>), @@ -30,7 +30,7 @@ LL | | ContainingLargeEnum(LargeEnum), LL | | } | |_^ the entire enum is at least 32004 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - ContainingLargeEnum(LargeEnum), LL + ContainingLargeEnum(Box), @@ -49,7 +49,7 @@ LL | | StructLikeLittle { x: i32, y: i32 }, LL | | } | |_^ the entire enum is at least 70008 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - ContainingMoreThanOneField(i32, [i32; 8000], [i32; 9500]), LL + ContainingMoreThanOneField(i32, Box<[i32; 8000]>, Box<[i32; 9500]>), @@ -67,7 +67,7 @@ LL | | StructLikeLarge { x: [i32; 8000], y: i32 }, LL | | } | |_^ the entire enum is at least 32008 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - StructLikeLarge { x: [i32; 8000], y: i32 }, LL + StructLikeLarge { x: Box<[i32; 8000]>, y: i32 }, @@ -85,7 +85,7 @@ LL | | StructLikeLarge2 { x: [i32; 8000] }, LL | | } | |_^ the entire enum is at least 32004 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - StructLikeLarge2 { x: [i32; 8000] }, LL + StructLikeLarge2 { x: Box<[i32; 8000]> }, @@ -104,7 +104,7 @@ LL | | C([u8; 200]), LL | | } | |_^ the entire enum is at least 1256 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B([u8; 1255]), LL + B(Box<[u8; 1255]>), @@ -122,7 +122,7 @@ LL | | ContainingMoreThanOneField([i32; 8000], [i32; 2], [i32; 9500], [i32; LL | | } | |_^ the entire enum is at least 70132 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - ContainingMoreThanOneField([i32; 8000], [i32; 2], [i32; 9500], [i32; 30]), LL + ContainingMoreThanOneField(Box<[i32; 8000]>, [i32; 2], Box<[i32; 9500]>, [i32; 30]), @@ -140,7 +140,7 @@ LL | | B(Struct2), LL | | } | |_^ the entire enum is at least 32004 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B(Struct2), LL + B(Box), @@ -158,7 +158,7 @@ LL | | B(Struct2), LL | | } | |_^ the entire enum is at least 32000 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B(Struct2), LL + B(Box), @@ -176,7 +176,7 @@ LL | | B(Struct2), LL | | } | |_^ the entire enum is at least 32000 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - B(Struct2), LL + B(Box), @@ -199,7 +199,7 @@ note: boxing a variant would require the type no longer be `Copy` | LL | enum CopyableLargeEnum { | ^^^^^^^^^^^^^^^^^ -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum --> tests/ui/large_enum_variant.rs:118:5 | LL | B([u64; 8000]), @@ -222,7 +222,7 @@ note: boxing a variant would require the type no longer be `Copy` | LL | enum ManuallyCopyLargeEnum { | ^^^^^^^^^^^^^^^^^^^^^ -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum --> tests/ui/large_enum_variant.rs:124:5 | LL | B([u64; 8000]), @@ -245,7 +245,7 @@ note: boxing a variant would require the type no longer be `Copy` | LL | enum SomeGenericPossiblyCopyEnum { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum --> tests/ui/large_enum_variant.rs:138:5 | LL | B([u64; 4000]), @@ -263,7 +263,7 @@ LL | | Large((T, [u8; 512])), LL | | } | |_^ the entire enum is at least 512 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Large((T, [u8; 512])), LL + Large(Box<(T, [u8; 512])>), @@ -281,7 +281,7 @@ LL | | Small(u8), LL | | } | |_^ the entire enum is at least 520 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Large([Foo; 64]), LL + Large(Box<[Foo; 64]>), @@ -299,7 +299,7 @@ LL | | Error(PossiblyLargeEnumWithConst<256>), LL | | } | |_^ the entire enum is at least 514 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Error(PossiblyLargeEnumWithConst<256>), LL + Error(Box>), @@ -317,7 +317,7 @@ LL | | Recursive(Box), LL | | } | |_^ the entire enum is at least 520 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Large([u64; 64]), LL + Large(Box<[u64; 64]>), @@ -335,7 +335,7 @@ LL | | Error(WithRecursionAndGenerics), LL | | } | |_^ the entire enum is at least 520 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - Error(WithRecursionAndGenerics), LL + Error(Box>), @@ -353,7 +353,7 @@ LL | | _SmallBoi(u8), LL | | } | |_____^ the entire enum is at least 296 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - BigBoi(PublishWithBytes), LL + BigBoi(Box), @@ -371,7 +371,7 @@ LL | | _SmallBoi(u8), LL | | } | |_____^ the entire enum is at least 224 bytes | -help: consider boxing the large fields to reduce the total size of the enum +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum | LL - BigBoi(PublishWithVec), LL + BigBoi(Box), diff --git a/tests/ui/large_enum_variant_no_std.rs b/tests/ui/large_enum_variant_no_std.rs new file mode 100644 index 000000000000..ff0213155b6c --- /dev/null +++ b/tests/ui/large_enum_variant_no_std.rs @@ -0,0 +1,8 @@ +#![no_std] +#![warn(clippy::large_enum_variant)] + +enum Myenum { + //~^ ERROR: large size difference between variants + Small(u8), + Large([u8; 1024]), +} diff --git a/tests/ui/large_enum_variant_no_std.stderr b/tests/ui/large_enum_variant_no_std.stderr new file mode 100644 index 000000000000..4f32e3e4835f --- /dev/null +++ b/tests/ui/large_enum_variant_no_std.stderr @@ -0,0 +1,22 @@ +error: large size difference between variants + --> tests/ui/large_enum_variant_no_std.rs:4:1 + | +LL | / enum Myenum { +LL | | +LL | | Small(u8), + | | --------- the second-largest variant contains at least 1 bytes +LL | | Large([u8; 1024]), + | | ----------------- the largest variant contains at least 1024 bytes +LL | | } + | |_^ the entire enum is at least 1025 bytes + | +help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum + --> tests/ui/large_enum_variant_no_std.rs:7:5 + | +LL | Large([u8; 1024]), + | ^^^^^^^^^^^^^^^^^ + = note: `-D clippy::large-enum-variant` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::large_enum_variant)]` + +error: aborting due to 1 previous error + diff --git a/tests/ui/legacy_numeric_constants.fixed b/tests/ui/legacy_numeric_constants.fixed index 30bb549a9d65..d90e7bec027c 100644 --- a/tests/ui/legacy_numeric_constants.fixed +++ b/tests/ui/legacy_numeric_constants.fixed @@ -79,9 +79,31 @@ fn main() { f64::consts::E; b!(); + std::primitive::i32::MAX; + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead [(0, "", i128::MAX)]; //~^ ERROR: usage of a legacy numeric constant //~| HELP: use the associated constant instead + i32::MAX; + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead + assert_eq!(0, -i32::MAX); + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead + i128::MAX; + //~^ ERROR: usage of a legacy numeric constant + //~| HELP: use the associated constant instead + u32::MAX; + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead + i32::MAX; + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead + type Ω = i32; + Ω::MAX; + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead } #[warn(clippy::legacy_numeric_constants)] diff --git a/tests/ui/legacy_numeric_constants.rs b/tests/ui/legacy_numeric_constants.rs index d3878199055f..4a2ef3f70c21 100644 --- a/tests/ui/legacy_numeric_constants.rs +++ b/tests/ui/legacy_numeric_constants.rs @@ -79,9 +79,31 @@ fn main() { f64::consts::E; b!(); + ::max_value(); + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead [(0, "", std::i128::MAX)]; //~^ ERROR: usage of a legacy numeric constant //~| HELP: use the associated constant instead + (i32::max_value()); + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead + assert_eq!(0, -(i32::max_value())); + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead + (std::i128::MAX); + //~^ ERROR: usage of a legacy numeric constant + //~| HELP: use the associated constant instead + (::max_value()); + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead + ((i32::max_value)()); + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead + type Ω = i32; + Ω::max_value(); + //~^ ERROR: usage of a legacy numeric method + //~| HELP: use the associated constant instead } #[warn(clippy::legacy_numeric_constants)] diff --git a/tests/ui/legacy_numeric_constants.stderr b/tests/ui/legacy_numeric_constants.stderr index 4d69b8165a34..0b4f32e0abc3 100644 --- a/tests/ui/legacy_numeric_constants.stderr +++ b/tests/ui/legacy_numeric_constants.stderr @@ -72,10 +72,10 @@ LL | u32::MAX; | +++++ error: usage of a legacy numeric method - --> tests/ui/legacy_numeric_constants.rs:50:10 + --> tests/ui/legacy_numeric_constants.rs:50:5 | LL | i32::max_value(); - | ^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | help: use the associated constant instead | @@ -84,10 +84,10 @@ LL + i32::MAX; | error: usage of a legacy numeric method - --> tests/ui/legacy_numeric_constants.rs:53:9 + --> tests/ui/legacy_numeric_constants.rs:53:5 | LL | u8::max_value(); - | ^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | help: use the associated constant instead | @@ -96,10 +96,10 @@ LL + u8::MAX; | error: usage of a legacy numeric method - --> tests/ui/legacy_numeric_constants.rs:56:9 + --> tests/ui/legacy_numeric_constants.rs:56:5 | LL | u8::min_value(); - | ^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | help: use the associated constant instead | @@ -120,10 +120,10 @@ LL + u8::MIN; | error: usage of a legacy numeric method - --> tests/ui/legacy_numeric_constants.rs:62:27 + --> tests/ui/legacy_numeric_constants.rs:62:5 | LL | ::std::primitive::u8::min_value(); - | ^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: use the associated constant instead | @@ -132,10 +132,10 @@ LL + ::std::primitive::u8::MIN; | error: usage of a legacy numeric method - --> tests/ui/legacy_numeric_constants.rs:65:26 + --> tests/ui/legacy_numeric_constants.rs:65:5 | LL | std::primitive::i32::max_value(); - | ^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: use the associated constant instead | @@ -171,8 +171,20 @@ LL - let x = std::u64::MAX; LL + let x = u64::MAX; | +error: usage of a legacy numeric method + --> tests/ui/legacy_numeric_constants.rs:82:5 + | +LL | ::max_value(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use the associated constant instead + | +LL - ::max_value(); +LL + std::primitive::i32::MAX; + | + error: usage of a legacy numeric constant - --> tests/ui/legacy_numeric_constants.rs:82:14 + --> tests/ui/legacy_numeric_constants.rs:85:14 | LL | [(0, "", std::i128::MAX)]; | ^^^^^^^^^^^^^^ @@ -183,8 +195,80 @@ LL - [(0, "", std::i128::MAX)]; LL + [(0, "", i128::MAX)]; | +error: usage of a legacy numeric method + --> tests/ui/legacy_numeric_constants.rs:88:5 + | +LL | (i32::max_value()); + | ^^^^^^^^^^^^^^^^^^ + | +help: use the associated constant instead + | +LL - (i32::max_value()); +LL + i32::MAX; + | + +error: usage of a legacy numeric method + --> tests/ui/legacy_numeric_constants.rs:91:20 + | +LL | assert_eq!(0, -(i32::max_value())); + | ^^^^^^^^^^^^^^^^^^ + | +help: use the associated constant instead + | +LL - assert_eq!(0, -(i32::max_value())); +LL + assert_eq!(0, -i32::MAX); + | + +error: usage of a legacy numeric constant + --> tests/ui/legacy_numeric_constants.rs:94:5 + | +LL | (std::i128::MAX); + | ^^^^^^^^^^^^^^^^ + | +help: use the associated constant instead + | +LL - (std::i128::MAX); +LL + i128::MAX; + | + +error: usage of a legacy numeric method + --> tests/ui/legacy_numeric_constants.rs:97:5 + | +LL | (::max_value()); + | ^^^^^^^^^^^^^^^^^^^^ + | +help: use the associated constant instead + | +LL - (::max_value()); +LL + u32::MAX; + | + +error: usage of a legacy numeric method + --> tests/ui/legacy_numeric_constants.rs:100:5 + | +LL | ((i32::max_value)()); + | ^^^^^^^^^^^^^^^^^^^^ + | +help: use the associated constant instead + | +LL - ((i32::max_value)()); +LL + i32::MAX; + | + +error: usage of a legacy numeric method + --> tests/ui/legacy_numeric_constants.rs:104:5 + | +LL | Ω::max_value(); + | ^^^^^^^^^^^^^^ + | +help: use the associated constant instead + | +LL - Ω::max_value(); +LL + Ω::MAX; + | + error: usage of a legacy numeric constant - --> tests/ui/legacy_numeric_constants.rs:116:5 + --> tests/ui/legacy_numeric_constants.rs:138:5 | LL | std::u32::MAX; | ^^^^^^^^^^^^^ @@ -195,5 +279,5 @@ LL - std::u32::MAX; LL + u32::MAX; | -error: aborting due to 16 previous errors +error: aborting due to 23 previous errors diff --git a/tests/ui/manual_abs_diff.fixed b/tests/ui/manual_abs_diff.fixed index f1b1278ea6d2..2766942140ce 100644 --- a/tests/ui/manual_abs_diff.fixed +++ b/tests/ui/manual_abs_diff.fixed @@ -104,3 +104,7 @@ fn non_primitive_ty() { let (a, b) = (S(10), S(20)); let _ = if a < b { b - a } else { a - b }; } + +fn issue15254(a: &usize, b: &usize) -> usize { + b.abs_diff(*a) +} diff --git a/tests/ui/manual_abs_diff.rs b/tests/ui/manual_abs_diff.rs index 60ef819c12d3..2c408f2be375 100644 --- a/tests/ui/manual_abs_diff.rs +++ b/tests/ui/manual_abs_diff.rs @@ -114,3 +114,12 @@ fn non_primitive_ty() { let (a, b) = (S(10), S(20)); let _ = if a < b { b - a } else { a - b }; } + +fn issue15254(a: &usize, b: &usize) -> usize { + if a < b { + //~^ manual_abs_diff + b - a + } else { + a - b + } +} diff --git a/tests/ui/manual_abs_diff.stderr b/tests/ui/manual_abs_diff.stderr index c14c1dc830fb..bb6d312b435f 100644 --- a/tests/ui/manual_abs_diff.stderr +++ b/tests/ui/manual_abs_diff.stderr @@ -79,5 +79,16 @@ error: manual absolute difference pattern without using `abs_diff` LL | let _ = if a > b { (a - b) as u32 } else { (b - a) as u32 }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with `abs_diff`: `a.abs_diff(b)` -error: aborting due to 11 previous errors +error: manual absolute difference pattern without using `abs_diff` + --> tests/ui/manual_abs_diff.rs:119:5 + | +LL | / if a < b { +LL | | +LL | | b - a +LL | | } else { +LL | | a - b +LL | | } + | |_____^ help: replace with `abs_diff`: `b.abs_diff(*a)` + +error: aborting due to 12 previous errors diff --git a/tests/ui/manual_assert.edition2018.stderr b/tests/ui/manual_assert.edition2018.stderr index 8cedf2c68636..221cddf069db 100644 --- a/tests/ui/manual_assert.edition2018.stderr +++ b/tests/ui/manual_assert.edition2018.stderr @@ -189,5 +189,23 @@ LL - }; LL + const BAR: () = assert!(!(N == 0), ); | -error: aborting due to 10 previous errors +error: only a `panic!` in `if`-then statement + --> tests/ui/manual_assert.rs:116:5 + | +LL | / if !is_x86_feature_detected!("ssse3") { +LL | | +LL | | panic!("SSSE3 is not supported"); +LL | | } + | |_____^ + | +help: try instead + | +LL - if !is_x86_feature_detected!("ssse3") { +LL - +LL - panic!("SSSE3 is not supported"); +LL - } +LL + assert!(is_x86_feature_detected!("ssse3"), "SSSE3 is not supported"); + | + +error: aborting due to 11 previous errors diff --git a/tests/ui/manual_assert.edition2021.stderr b/tests/ui/manual_assert.edition2021.stderr index 8cedf2c68636..221cddf069db 100644 --- a/tests/ui/manual_assert.edition2021.stderr +++ b/tests/ui/manual_assert.edition2021.stderr @@ -189,5 +189,23 @@ LL - }; LL + const BAR: () = assert!(!(N == 0), ); | -error: aborting due to 10 previous errors +error: only a `panic!` in `if`-then statement + --> tests/ui/manual_assert.rs:116:5 + | +LL | / if !is_x86_feature_detected!("ssse3") { +LL | | +LL | | panic!("SSSE3 is not supported"); +LL | | } + | |_____^ + | +help: try instead + | +LL - if !is_x86_feature_detected!("ssse3") { +LL - +LL - panic!("SSSE3 is not supported"); +LL - } +LL + assert!(is_x86_feature_detected!("ssse3"), "SSSE3 is not supported"); + | + +error: aborting due to 11 previous errors diff --git a/tests/ui/manual_assert.rs b/tests/ui/manual_assert.rs index 46a42c3d00af..ab02bd5f5e53 100644 --- a/tests/ui/manual_assert.rs +++ b/tests/ui/manual_assert.rs @@ -105,3 +105,17 @@ fn issue12505() { }; } } + +fn issue15227(left: u64, right: u64) -> u64 { + macro_rules! is_x86_feature_detected { + ($feature:literal) => { + $feature.len() > 0 && $feature.starts_with("ss") + }; + } + + if !is_x86_feature_detected!("ssse3") { + //~^ manual_assert + panic!("SSSE3 is not supported"); + } + unsafe { todo!() } +} diff --git a/tests/ui/manual_is_multiple_of.fixed b/tests/ui/manual_is_multiple_of.fixed index 6735b99f298c..03f75e725ed5 100644 --- a/tests/ui/manual_is_multiple_of.fixed +++ b/tests/ui/manual_is_multiple_of.fixed @@ -23,3 +23,81 @@ fn f(a: u64, b: u64) { fn g(a: u64, b: u64) { let _ = a % b == 0; } + +fn needs_deref(a: &u64, b: &u64) { + let _ = a.is_multiple_of(*b); //~ manual_is_multiple_of +} + +fn closures(a: u64, b: u64) { + // Do not lint, types are ambiguous at this point + let cl = |a, b| a % b == 0; + let _ = cl(a, b); + + // Do not lint, types are ambiguous at this point + let cl = |a: _, b: _| a % b == 0; + let _ = cl(a, b); + + // Type of `a` is enough + let cl = |a: u64, b| a.is_multiple_of(b); //~ manual_is_multiple_of + let _ = cl(a, b); + + // Type of `a` is enough + let cl = |a: &u64, b| a.is_multiple_of(b); //~ manual_is_multiple_of + let _ = cl(&a, b); + + // Type of `b` is not enough + let cl = |a, b: u64| a % b == 0; + let _ = cl(&a, b); +} + +fn any_rem>(a: T, b: T) { + // An arbitrary `Rem` implementation should not lint + let _ = a % b == 0; +} + +mod issue15103 { + fn foo() -> Option { + let mut n: u64 = 150_000_000; + + (2..).find(|p| { + while n.is_multiple_of(*p) { + //~^ manual_is_multiple_of + n /= p; + } + n <= 1 + }) + } + + const fn generate_primes() -> [u64; N] { + let mut result = [0; N]; + if N == 0 { + return result; + } + result[0] = 2; + if N == 1 { + return result; + } + let mut idx = 1; + let mut p = 3; + while idx < N { + let mut j = 0; + while j < idx && p % result[j] != 0 { + j += 1; + } + if j == idx { + result[idx] = p; + idx += 1; + } + p += 1; + } + result + } + + fn bar() -> u32 { + let d = |n: u32| -> u32 { (1..=n / 2).filter(|i| n.is_multiple_of(*i)).sum() }; + //~^ manual_is_multiple_of + + let d = |n| (1..=n / 2).filter(|i| n % i == 0).sum(); + (1..1_000).filter(|&i| i == d(d(i)) && i != d(i)).sum() + } +} diff --git a/tests/ui/manual_is_multiple_of.rs b/tests/ui/manual_is_multiple_of.rs index 00b638e4fd9f..7b6fa64c843d 100644 --- a/tests/ui/manual_is_multiple_of.rs +++ b/tests/ui/manual_is_multiple_of.rs @@ -23,3 +23,81 @@ fn f(a: u64, b: u64) { fn g(a: u64, b: u64) { let _ = a % b == 0; } + +fn needs_deref(a: &u64, b: &u64) { + let _ = a % b == 0; //~ manual_is_multiple_of +} + +fn closures(a: u64, b: u64) { + // Do not lint, types are ambiguous at this point + let cl = |a, b| a % b == 0; + let _ = cl(a, b); + + // Do not lint, types are ambiguous at this point + let cl = |a: _, b: _| a % b == 0; + let _ = cl(a, b); + + // Type of `a` is enough + let cl = |a: u64, b| a % b == 0; //~ manual_is_multiple_of + let _ = cl(a, b); + + // Type of `a` is enough + let cl = |a: &u64, b| a % b == 0; //~ manual_is_multiple_of + let _ = cl(&a, b); + + // Type of `b` is not enough + let cl = |a, b: u64| a % b == 0; + let _ = cl(&a, b); +} + +fn any_rem>(a: T, b: T) { + // An arbitrary `Rem` implementation should not lint + let _ = a % b == 0; +} + +mod issue15103 { + fn foo() -> Option { + let mut n: u64 = 150_000_000; + + (2..).find(|p| { + while n % p == 0 { + //~^ manual_is_multiple_of + n /= p; + } + n <= 1 + }) + } + + const fn generate_primes() -> [u64; N] { + let mut result = [0; N]; + if N == 0 { + return result; + } + result[0] = 2; + if N == 1 { + return result; + } + let mut idx = 1; + let mut p = 3; + while idx < N { + let mut j = 0; + while j < idx && p % result[j] != 0 { + j += 1; + } + if j == idx { + result[idx] = p; + idx += 1; + } + p += 1; + } + result + } + + fn bar() -> u32 { + let d = |n: u32| -> u32 { (1..=n / 2).filter(|i| n % i == 0).sum() }; + //~^ manual_is_multiple_of + + let d = |n| (1..=n / 2).filter(|i| n % i == 0).sum(); + (1..1_000).filter(|&i| i == d(d(i)) && i != d(i)).sum() + } +} diff --git a/tests/ui/manual_is_multiple_of.stderr b/tests/ui/manual_is_multiple_of.stderr index 0b1ae70c2a70..8523599ec402 100644 --- a/tests/ui/manual_is_multiple_of.stderr +++ b/tests/ui/manual_is_multiple_of.stderr @@ -37,5 +37,35 @@ error: manual implementation of `.is_multiple_of()` LL | let _ = 0 < a % b; | ^^^^^^^^^ help: replace with: `!a.is_multiple_of(b)` -error: aborting due to 6 previous errors +error: manual implementation of `.is_multiple_of()` + --> tests/ui/manual_is_multiple_of.rs:28:13 + | +LL | let _ = a % b == 0; + | ^^^^^^^^^^ help: replace with: `a.is_multiple_of(*b)` + +error: manual implementation of `.is_multiple_of()` + --> tests/ui/manual_is_multiple_of.rs:41:26 + | +LL | let cl = |a: u64, b| a % b == 0; + | ^^^^^^^^^^ help: replace with: `a.is_multiple_of(b)` + +error: manual implementation of `.is_multiple_of()` + --> tests/ui/manual_is_multiple_of.rs:45:27 + | +LL | let cl = |a: &u64, b| a % b == 0; + | ^^^^^^^^^^ help: replace with: `a.is_multiple_of(b)` + +error: manual implementation of `.is_multiple_of()` + --> tests/ui/manual_is_multiple_of.rs:63:19 + | +LL | while n % p == 0 { + | ^^^^^^^^^^ help: replace with: `n.is_multiple_of(*p)` + +error: manual implementation of `.is_multiple_of()` + --> tests/ui/manual_is_multiple_of.rs:97:58 + | +LL | let d = |n: u32| -> u32 { (1..=n / 2).filter(|i| n % i == 0).sum() }; + | ^^^^^^^^^^ help: replace with: `n.is_multiple_of(*i)` + +error: aborting due to 11 previous errors diff --git a/tests/ui/map_identity.fixed b/tests/ui/map_identity.fixed index 83b2dac5fc51..b82d3e6d9567 100644 --- a/tests/ui/map_identity.fixed +++ b/tests/ui/map_identity.fixed @@ -87,3 +87,15 @@ fn issue13904() { let _ = { it }.next(); //~^ map_identity } + +// same as `issue11764`, but for arrays +fn issue15198() { + let x = [[1, 2], [3, 4]]; + // don't lint: `&[i32; 2]` becomes `[&i32; 2]` + let _ = x.iter().map(|[x, y]| [x, y]); + let _ = x.iter().map(|x| [x[0]]).map(|[x]| x); + + // no match ergonomics for `[i32, i32]` + let _ = x.iter().copied(); + //~^ map_identity +} diff --git a/tests/ui/map_identity.rs b/tests/ui/map_identity.rs index e839c551364b..c295bf872701 100644 --- a/tests/ui/map_identity.rs +++ b/tests/ui/map_identity.rs @@ -93,3 +93,15 @@ fn issue13904() { let _ = { it }.map(|x| x).next(); //~^ map_identity } + +// same as `issue11764`, but for arrays +fn issue15198() { + let x = [[1, 2], [3, 4]]; + // don't lint: `&[i32; 2]` becomes `[&i32; 2]` + let _ = x.iter().map(|[x, y]| [x, y]); + let _ = x.iter().map(|x| [x[0]]).map(|[x]| x); + + // no match ergonomics for `[i32, i32]` + let _ = x.iter().copied().map(|[x, y]| [x, y]); + //~^ map_identity +} diff --git a/tests/ui/map_identity.stderr b/tests/ui/map_identity.stderr index 9836f3b4cc5f..9b624a0dc755 100644 --- a/tests/ui/map_identity.stderr +++ b/tests/ui/map_identity.stderr @@ -87,5 +87,11 @@ error: unnecessary map of the identity function LL | let _ = { it }.map(|x| x).next(); | ^^^^^^^^^^^ help: remove the call to `map` -error: aborting due to 13 previous errors +error: unnecessary map of the identity function + --> tests/ui/map_identity.rs:105:30 + | +LL | let _ = x.iter().copied().map(|[x, y]| [x, y]); + | ^^^^^^^^^^^^^^^^^^^^^ help: remove the call to `map` + +error: aborting due to 14 previous errors diff --git a/tests/ui/missing_inline.rs b/tests/ui/missing_inline.rs index c1801005b777..223c7447975a 100644 --- a/tests/ui/missing_inline.rs +++ b/tests/ui/missing_inline.rs @@ -80,3 +80,20 @@ impl PubFoo { // do not lint this since users cannot control the external code #[derive(Debug)] pub struct S; + +pub mod issue15301 { + #[unsafe(no_mangle)] + pub extern "C" fn call_from_c() { + println!("Just called a Rust function from C!"); + } + + #[unsafe(no_mangle)] + pub extern "Rust" fn call_from_rust() { + println!("Just called a Rust function from Rust!"); + } + + #[unsafe(no_mangle)] + pub fn call_from_rust_no_extern() { + println!("Just called a Rust function from Rust!"); + } +} diff --git a/tests/ui/module_name_repetitions.rs b/tests/ui/module_name_repetitions.rs index 2fde98d7927c..5d16858bf85e 100644 --- a/tests/ui/module_name_repetitions.rs +++ b/tests/ui/module_name_repetitions.rs @@ -55,3 +55,21 @@ pub mod foo { } fn main() {} + +pub mod issue14095 { + pub mod widget { + #[macro_export] + macro_rules! define_widget { + ($id:ident) => { + /* ... */ + }; + } + + #[macro_export] + macro_rules! widget_impl { + ($id:ident) => { + /* ... */ + }; + } + } +} diff --git a/tests/ui/must_use_candidates.fixed b/tests/ui/must_use_candidates.fixed index 4c1d6b1ccb59..1e8589cf39d6 100644 --- a/tests/ui/must_use_candidates.fixed +++ b/tests/ui/must_use_candidates.fixed @@ -13,13 +13,15 @@ use std::sync::atomic::{AtomicBool, Ordering}; pub struct MyAtomic(AtomicBool); pub struct MyPure; -#[must_use] pub fn pure(i: u8) -> u8 { +#[must_use] +pub fn pure(i: u8) -> u8 { //~^ must_use_candidate i } impl MyPure { - #[must_use] pub fn inherent_pure(&self) -> u8 { + #[must_use] + pub fn inherent_pure(&self) -> u8 { //~^ must_use_candidate 0 } @@ -51,7 +53,8 @@ pub fn with_callback bool>(f: &F) -> bool { f(0) } -#[must_use] pub fn with_marker(_d: std::marker::PhantomData<&mut u32>) -> bool { +#[must_use] +pub fn with_marker(_d: std::marker::PhantomData<&mut u32>) -> bool { //~^ must_use_candidate true } @@ -64,7 +67,8 @@ pub fn atomics(b: &AtomicBool) -> bool { b.load(Ordering::SeqCst) } -#[must_use] pub fn rcd(_x: Rc) -> bool { +#[must_use] +pub fn rcd(_x: Rc) -> bool { //~^ must_use_candidate true } @@ -73,7 +77,8 @@ pub fn rcmut(_x: Rc<&mut u32>) -> bool { true } -#[must_use] pub fn arcd(_x: Arc) -> bool { +#[must_use] +pub fn arcd(_x: Arc) -> bool { //~^ must_use_candidate false } diff --git a/tests/ui/must_use_candidates.stderr b/tests/ui/must_use_candidates.stderr index 590253d95f9e..5ddbd0260629 100644 --- a/tests/ui/must_use_candidates.stderr +++ b/tests/ui/must_use_candidates.stderr @@ -1,35 +1,64 @@ error: this function could have a `#[must_use]` attribute - --> tests/ui/must_use_candidates.rs:16:1 + --> tests/ui/must_use_candidates.rs:16:8 | LL | pub fn pure(i: u8) -> u8 { - | ^^^^^^^^^^^^^^^^^^^^^^^^ help: add the attribute: `#[must_use] pub fn pure(i: u8) -> u8` + | ^^^^ | = note: `-D clippy::must-use-candidate` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::must_use_candidate)]` +help: add the attribute + | +LL + #[must_use] +LL | pub fn pure(i: u8) -> u8 { + | error: this method could have a `#[must_use]` attribute - --> tests/ui/must_use_candidates.rs:22:5 + --> tests/ui/must_use_candidates.rs:22:12 | LL | pub fn inherent_pure(&self) -> u8 { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: add the attribute: `#[must_use] pub fn inherent_pure(&self) -> u8` + | ^^^^^^^^^^^^^ + | +help: add the attribute + | +LL ~ #[must_use] +LL ~ pub fn inherent_pure(&self) -> u8 { + | error: this function could have a `#[must_use]` attribute - --> tests/ui/must_use_candidates.rs:54:1 + --> tests/ui/must_use_candidates.rs:54:8 + | +LL | pub fn with_marker(_d: std::marker::PhantomData<&mut u32>) -> bool { + | ^^^^^^^^^^^ + | +help: add the attribute | +LL + #[must_use] LL | pub fn with_marker(_d: std::marker::PhantomData<&mut u32>) -> bool { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: add the attribute: `#[must_use] pub fn with_marker(_d: std::marker::PhantomData<&mut u32>) -> bool` + | error: this function could have a `#[must_use]` attribute - --> tests/ui/must_use_candidates.rs:67:1 + --> tests/ui/must_use_candidates.rs:67:8 | LL | pub fn rcd(_x: Rc) -> bool { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: add the attribute: `#[must_use] pub fn rcd(_x: Rc) -> bool` + | ^^^ + | +help: add the attribute + | +LL + #[must_use] +LL | pub fn rcd(_x: Rc) -> bool { + | error: this function could have a `#[must_use]` attribute - --> tests/ui/must_use_candidates.rs:76:1 + --> tests/ui/must_use_candidates.rs:76:8 | LL | pub fn arcd(_x: Arc) -> bool { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: add the attribute: `#[must_use] pub fn arcd(_x: Arc) -> bool` + | ^^^^ + | +help: add the attribute + | +LL + #[must_use] +LL | pub fn arcd(_x: Arc) -> bool { + | error: aborting due to 5 previous errors diff --git a/tests/ui/needless_for_each_fixable.fixed b/tests/ui/needless_for_each_fixable.fixed index a73aff556399..a6d64d9afc1a 100644 --- a/tests/ui/needless_for_each_fixable.fixed +++ b/tests/ui/needless_for_each_fixable.fixed @@ -143,3 +143,9 @@ mod issue14734 { //~^ needless_for_each } } + +fn issue15256() { + let vec: Vec = Vec::new(); + for v in vec.iter() { println!("{v}"); } + //~^ needless_for_each +} diff --git a/tests/ui/needless_for_each_fixable.rs b/tests/ui/needless_for_each_fixable.rs index d92f055d3f45..7e74d2b428fd 100644 --- a/tests/ui/needless_for_each_fixable.rs +++ b/tests/ui/needless_for_each_fixable.rs @@ -143,3 +143,9 @@ mod issue14734 { //~^ needless_for_each } } + +fn issue15256() { + let vec: Vec = Vec::new(); + vec.iter().for_each(|v| println!("{v}")); + //~^ needless_for_each +} diff --git a/tests/ui/needless_for_each_fixable.stderr b/tests/ui/needless_for_each_fixable.stderr index f80144560976..204cfa36b022 100644 --- a/tests/ui/needless_for_each_fixable.stderr +++ b/tests/ui/needless_for_each_fixable.stderr @@ -148,5 +148,11 @@ error: needless use of `for_each` LL | rows.iter().for_each(|x| do_something(x, 1u8)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for x in rows.iter() { do_something(x, 1u8); }` -error: aborting due to 10 previous errors +error: needless use of `for_each` + --> tests/ui/needless_for_each_fixable.rs:149:5 + | +LL | vec.iter().for_each(|v| println!("{v}")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for v in vec.iter() { println!("{v}"); }` + +error: aborting due to 11 previous errors diff --git a/tests/ui/needless_range_loop.rs b/tests/ui/needless_range_loop.rs index 8a1c1be289cf..70cf9fa7369f 100644 --- a/tests/ui/needless_range_loop.rs +++ b/tests/ui/needless_range_loop.rs @@ -185,3 +185,28 @@ mod issue_2496 { unimplemented!() } } + +fn needless_loop() { + use std::hint::black_box; + let x = [0; 64]; + for i in 0..64 { + let y = [0; 64]; + + black_box(x[i]); + black_box(y[i]); + } + + for i in 0..64 { + black_box(x[i]); + black_box([0; 64][i]); + } + + for i in 0..64 { + black_box(x[i]); + black_box([1, 2, 3, 4, 5, 6, 7, 8][i]); + } + + for i in 0..64 { + black_box([1, 2, 3, 4, 5, 6, 7, 8][i]); + } +} diff --git a/tests/ui/never_loop.rs b/tests/ui/never_loop.rs index e0f54ef899b0..48d4b8ad1519 100644 --- a/tests/ui/never_loop.rs +++ b/tests/ui/never_loop.rs @@ -466,3 +466,35 @@ fn main() { test13(); test14(); } + +fn issue15059() { + 'a: for _ in 0..1 { + //~^ never_loop + break 'a; + } + + let mut b = 1; + 'a: for i in 0..1 { + //~^ never_loop + match i { + 0 => { + b *= 2; + break 'a; + }, + x => { + b += x; + break 'a; + }, + } + } + + #[allow(clippy::unused_unit)] + for v in 0..10 { + //~^ never_loop + break; + println!("{v}"); + // This is comment and should be kept + println!("This is a comment"); + () + } +} diff --git a/tests/ui/never_loop.stderr b/tests/ui/never_loop.stderr index bc9a7ec48b48..54b463266a3a 100644 --- a/tests/ui/never_loop.stderr +++ b/tests/ui/never_loop.stderr @@ -176,8 +176,10 @@ LL | | } | help: if you need the first element of the iterator, try writing | -LL - for v in 0..10 { -LL + if let Some(v) = (0..10).next() { +LL ~ if let Some(v) = (0..10).next() { +LL | +LL ~ +LL ~ | error: this loop never actually loops @@ -232,5 +234,68 @@ LL | | break 'inner; LL | | } | |_________^ -error: aborting due to 21 previous errors +error: this loop never actually loops + --> tests/ui/never_loop.rs:471:5 + | +LL | / 'a: for _ in 0..1 { +LL | | +LL | | break 'a; +LL | | } + | |_____^ + | +help: if you need the first element of the iterator, try writing + | +LL ~ if let Some(_) = (0..1).next() { +LL | +LL ~ + | + +error: this loop never actually loops + --> tests/ui/never_loop.rs:477:5 + | +LL | / 'a: for i in 0..1 { +LL | | +LL | | match i { +LL | | 0 => { +... | +LL | | } + | |_____^ + | +help: if you need the first element of the iterator, try writing + | +LL ~ if let Some(i) = (0..1).next() { +LL | +... +LL | b *= 2; +LL ~ +LL | }, +LL | x => { +LL | b += x; +LL ~ + | + +error: this loop never actually loops + --> tests/ui/never_loop.rs:492:5 + | +LL | / for v in 0..10 { +LL | | +LL | | break; +LL | | println!("{v}"); +... | +LL | | () +LL | | } + | |_____^ + | +help: if you need the first element of the iterator, try writing + | +LL ~ if let Some(v) = (0..10).next() { +LL | +LL ~ +LL ~ +LL | // This is comment and should be kept +LL ~ +LL ~ + | + +error: aborting due to 24 previous errors diff --git a/tests/ui/or_fun_call.fixed b/tests/ui/or_fun_call.fixed index bcd2602edb6a..0a8525a12f5e 100644 --- a/tests/ui/or_fun_call.fixed +++ b/tests/ui/or_fun_call.fixed @@ -283,6 +283,8 @@ mod issue8993 { let _ = Some(4).map_or_else(g, f); //~^ or_fun_call let _ = Some(4).map_or(0, f); + let _ = Some(4).map_or_else(|| "asd".to_string().len() as i32, f); + //~^ or_fun_call } } @@ -426,6 +428,8 @@ mod result_map_or { let _ = x.map_or_else(|_| g(), f); //~^ or_fun_call let _ = x.map_or(0, f); + let _ = x.map_or_else(|_| "asd".to_string().len() as i32, f); + //~^ or_fun_call } } diff --git a/tests/ui/or_fun_call.rs b/tests/ui/or_fun_call.rs index 8d1202ebf914..b4f9b950a7fe 100644 --- a/tests/ui/or_fun_call.rs +++ b/tests/ui/or_fun_call.rs @@ -283,6 +283,8 @@ mod issue8993 { let _ = Some(4).map_or(g(), f); //~^ or_fun_call let _ = Some(4).map_or(0, f); + let _ = Some(4).map_or("asd".to_string().len() as i32, f); + //~^ or_fun_call } } @@ -426,6 +428,8 @@ mod result_map_or { let _ = x.map_or(g(), f); //~^ or_fun_call let _ = x.map_or(0, f); + let _ = x.map_or("asd".to_string().len() as i32, f); + //~^ or_fun_call } } diff --git a/tests/ui/or_fun_call.stderr b/tests/ui/or_fun_call.stderr index 585ee2d0e19d..3e4df772668d 100644 --- a/tests/ui/or_fun_call.stderr +++ b/tests/ui/or_fun_call.stderr @@ -154,62 +154,68 @@ error: function call inside of `map_or` LL | let _ = Some(4).map_or(g(), f); | ^^^^^^^^^^^^^^ help: try: `map_or_else(g, f)` +error: function call inside of `map_or` + --> tests/ui/or_fun_call.rs:286:25 + | +LL | let _ = Some(4).map_or("asd".to_string().len() as i32, f); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map_or_else(|| "asd".to_string().len() as i32, f)` + error: use of `unwrap_or_else` to construct default value - --> tests/ui/or_fun_call.rs:315:18 + --> tests/ui/or_fun_call.rs:317:18 | LL | with_new.unwrap_or_else(Vec::new); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/or_fun_call.rs:319:28 + --> tests/ui/or_fun_call.rs:321:28 | LL | with_default_trait.unwrap_or_else(Default::default); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/or_fun_call.rs:323:27 + --> tests/ui/or_fun_call.rs:325:27 | LL | with_default_type.unwrap_or_else(u64::default); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/or_fun_call.rs:327:22 + --> tests/ui/or_fun_call.rs:329:22 | LL | real_default.unwrap_or_else(::default); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: use of `or_insert_with` to construct default value - --> tests/ui/or_fun_call.rs:331:23 + --> tests/ui/or_fun_call.rs:333:23 | LL | map.entry(42).or_insert_with(String::new); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `or_default()` error: use of `or_insert_with` to construct default value - --> tests/ui/or_fun_call.rs:335:25 + --> tests/ui/or_fun_call.rs:337:25 | LL | btree.entry(42).or_insert_with(String::new); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `or_default()` error: use of `unwrap_or_else` to construct default value - --> tests/ui/or_fun_call.rs:339:25 + --> tests/ui/or_fun_call.rs:341:25 | LL | let _ = stringy.unwrap_or_else(String::new); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: function call inside of `unwrap_or` - --> tests/ui/or_fun_call.rs:381:17 + --> tests/ui/or_fun_call.rs:383:17 | LL | let _ = opt.unwrap_or({ f() }); // suggest `.unwrap_or_else(f)` | ^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(f)` error: function call inside of `unwrap_or` - --> tests/ui/or_fun_call.rs:386:17 + --> tests/ui/or_fun_call.rs:388:17 | LL | let _ = opt.unwrap_or(f() + 1); // suggest `.unwrap_or_else(|| f() + 1)` | ^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| f() + 1)` error: function call inside of `unwrap_or` - --> tests/ui/or_fun_call.rs:391:17 + --> tests/ui/or_fun_call.rs:393:17 | LL | let _ = opt.unwrap_or({ | _________________^ @@ -229,52 +235,58 @@ LL ~ }); | error: function call inside of `map_or` - --> tests/ui/or_fun_call.rs:397:17 + --> tests/ui/or_fun_call.rs:399:17 | LL | let _ = opt.map_or(f() + 1, |v| v); // suggest `.map_or_else(|| f() + 1, |v| v)` | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `map_or_else(|| f() + 1, |v| v)` error: use of `unwrap_or` to construct default value - --> tests/ui/or_fun_call.rs:402:17 + --> tests/ui/or_fun_call.rs:404:17 | LL | let _ = opt.unwrap_or({ i32::default() }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()` error: function call inside of `unwrap_or` - --> tests/ui/or_fun_call.rs:409:21 + --> tests/ui/or_fun_call.rs:411:21 | LL | let _ = opt_foo.unwrap_or(Foo { val: String::default() }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| Foo { val: String::default() })` error: function call inside of `map_or` - --> tests/ui/or_fun_call.rs:424:19 + --> tests/ui/or_fun_call.rs:426:19 | LL | let _ = x.map_or(g(), |v| v); | ^^^^^^^^^^^^^^^^^^ help: try: `map_or_else(|_| g(), |v| v)` error: function call inside of `map_or` - --> tests/ui/or_fun_call.rs:426:19 + --> tests/ui/or_fun_call.rs:428:19 | LL | let _ = x.map_or(g(), f); | ^^^^^^^^^^^^^^ help: try: `map_or_else(|_| g(), f)` +error: function call inside of `map_or` + --> tests/ui/or_fun_call.rs:431:19 + | +LL | let _ = x.map_or("asd".to_string().len() as i32, f); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `map_or_else(|_| "asd".to_string().len() as i32, f)` + error: function call inside of `get_or_insert` - --> tests/ui/or_fun_call.rs:438:15 + --> tests/ui/or_fun_call.rs:442:15 | LL | let _ = x.get_or_insert(g()); | ^^^^^^^^^^^^^^^^^^ help: try: `get_or_insert_with(g)` error: function call inside of `and` - --> tests/ui/or_fun_call.rs:448:15 + --> tests/ui/or_fun_call.rs:452:15 | LL | let _ = x.and(g()); | ^^^^^^^^ help: try: `and_then(|_| g())` error: function call inside of `and` - --> tests/ui/or_fun_call.rs:458:15 + --> tests/ui/or_fun_call.rs:462:15 | LL | let _ = x.and(g()); | ^^^^^^^^ help: try: `and_then(|_| g())` -error: aborting due to 43 previous errors +error: aborting due to 45 previous errors diff --git a/tests/ui/pattern_type_mismatch/auxiliary/external.rs b/tests/ui/pattern_type_mismatch/auxiliary/external.rs new file mode 100644 index 000000000000..cd27c5c74aa9 --- /dev/null +++ b/tests/ui/pattern_type_mismatch/auxiliary/external.rs @@ -0,0 +1,13 @@ +//! **FAKE** external macro crate. + +#[macro_export] +macro_rules! macro_with_match { + ( $p:pat ) => { + let something = (); + + match &something { + $p => true, + _ => false, + } + }; +} diff --git a/tests/ui/pattern_type_mismatch/syntax.rs b/tests/ui/pattern_type_mismatch/syntax.rs index 49ea1d3f7a67..aa988a577df2 100644 --- a/tests/ui/pattern_type_mismatch/syntax.rs +++ b/tests/ui/pattern_type_mismatch/syntax.rs @@ -6,6 +6,9 @@ clippy::single_match )] +//@aux-build:external.rs +use external::macro_with_match; + fn main() {} fn syntax_match() { @@ -159,3 +162,9 @@ fn macro_expansion() { let value = &Some(23); matching_macro!(value); } + +fn external_macro_expansion() { + macro_with_match! { + () + }; +} diff --git a/tests/ui/pattern_type_mismatch/syntax.stderr b/tests/ui/pattern_type_mismatch/syntax.stderr index cd604d604c12..636841e0a21a 100644 --- a/tests/ui/pattern_type_mismatch/syntax.stderr +++ b/tests/ui/pattern_type_mismatch/syntax.stderr @@ -1,5 +1,5 @@ error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:16:9 + --> tests/ui/pattern_type_mismatch/syntax.rs:19:9 | LL | Some(_) => (), | ^^^^^^^ @@ -9,7 +9,7 @@ LL | Some(_) => (), = help: to override `-D warnings` add `#[allow(clippy::pattern_type_mismatch)]` error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:36:12 + --> tests/ui/pattern_type_mismatch/syntax.rs:39:12 | LL | if let Some(_) = ref_value {} | ^^^^^^^ @@ -17,7 +17,7 @@ LL | if let Some(_) = ref_value {} = help: use `*` to dereference the match expression or explicitly match against a `&_` pattern and adjust the enclosed variable bindings error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:48:15 + --> tests/ui/pattern_type_mismatch/syntax.rs:51:15 | LL | while let Some(_) = ref_value { | ^^^^^^^ @@ -25,7 +25,7 @@ LL | while let Some(_) = ref_value { = help: use `*` to dereference the match expression or explicitly match against a `&_` pattern and adjust the enclosed variable bindings error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:68:9 + --> tests/ui/pattern_type_mismatch/syntax.rs:71:9 | LL | for (_a, _b) in slice.iter() {} | ^^^^^^^^ @@ -33,7 +33,7 @@ LL | for (_a, _b) in slice.iter() {} = help: explicitly match against a `&_` pattern and adjust the enclosed variable bindings error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:79:9 + --> tests/ui/pattern_type_mismatch/syntax.rs:82:9 | LL | let (_n, _m) = ref_value; | ^^^^^^^^ @@ -41,7 +41,7 @@ LL | let (_n, _m) = ref_value; = help: use `*` to dereference the match expression or explicitly match against a `&_` pattern and adjust the enclosed variable bindings error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:89:12 + --> tests/ui/pattern_type_mismatch/syntax.rs:92:12 | LL | fn foo((_a, _b): &(i32, i32)) {} | ^^^^^^^^ @@ -49,7 +49,7 @@ LL | fn foo((_a, _b): &(i32, i32)) {} = help: explicitly match against a `&_` pattern and adjust the enclosed variable bindings error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:104:10 + --> tests/ui/pattern_type_mismatch/syntax.rs:107:10 | LL | foo(|(_a, _b)| ()); | ^^^^^^^^ @@ -57,7 +57,7 @@ LL | foo(|(_a, _b)| ()); = help: explicitly match against a `&_` pattern and adjust the enclosed variable bindings error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:121:9 + --> tests/ui/pattern_type_mismatch/syntax.rs:124:9 | LL | Some(_) => (), | ^^^^^^^ @@ -65,7 +65,7 @@ LL | Some(_) => (), = help: use `*` to dereference the match expression or explicitly match against a `&_` pattern and adjust the enclosed variable bindings error: type of pattern does not match the expression type - --> tests/ui/pattern_type_mismatch/syntax.rs:142:17 + --> tests/ui/pattern_type_mismatch/syntax.rs:145:17 | LL | Some(_) => (), | ^^^^^^^ diff --git a/tests/ui/ptr_arg.rs b/tests/ui/ptr_arg.rs index 578641e910dc..be14e0762ff4 100644 --- a/tests/ui/ptr_arg.rs +++ b/tests/ui/ptr_arg.rs @@ -123,7 +123,7 @@ fn test_cow_with_ref(c: &Cow<[i32]>) {} //~^ ptr_arg fn test_cow(c: Cow<[i32]>) { - let _c = c; + let d = c; } trait Foo2 { @@ -141,36 +141,36 @@ mod issue_5644 { use std::path::PathBuf; fn allowed( - #[allow(clippy::ptr_arg)] _v: &Vec, - #[allow(clippy::ptr_arg)] _s: &String, - #[allow(clippy::ptr_arg)] _p: &PathBuf, - #[allow(clippy::ptr_arg)] _c: &Cow<[i32]>, - #[expect(clippy::ptr_arg)] _expect: &Cow<[i32]>, + #[allow(clippy::ptr_arg)] v: &Vec, + #[allow(clippy::ptr_arg)] s: &String, + #[allow(clippy::ptr_arg)] p: &PathBuf, + #[allow(clippy::ptr_arg)] c: &Cow<[i32]>, + #[expect(clippy::ptr_arg)] expect: &Cow<[i32]>, ) { } - fn some_allowed(#[allow(clippy::ptr_arg)] _v: &Vec, _s: &String) {} + fn some_allowed(#[allow(clippy::ptr_arg)] v: &Vec, s: &String) {} //~^ ptr_arg struct S; impl S { fn allowed( - #[allow(clippy::ptr_arg)] _v: &Vec, - #[allow(clippy::ptr_arg)] _s: &String, - #[allow(clippy::ptr_arg)] _p: &PathBuf, - #[allow(clippy::ptr_arg)] _c: &Cow<[i32]>, - #[expect(clippy::ptr_arg)] _expect: &Cow<[i32]>, + #[allow(clippy::ptr_arg)] v: &Vec, + #[allow(clippy::ptr_arg)] s: &String, + #[allow(clippy::ptr_arg)] p: &PathBuf, + #[allow(clippy::ptr_arg)] c: &Cow<[i32]>, + #[expect(clippy::ptr_arg)] expect: &Cow<[i32]>, ) { } } trait T { fn allowed( - #[allow(clippy::ptr_arg)] _v: &Vec, - #[allow(clippy::ptr_arg)] _s: &String, - #[allow(clippy::ptr_arg)] _p: &PathBuf, - #[allow(clippy::ptr_arg)] _c: &Cow<[i32]>, - #[expect(clippy::ptr_arg)] _expect: &Cow<[i32]>, + #[allow(clippy::ptr_arg)] v: &Vec, + #[allow(clippy::ptr_arg)] s: &String, + #[allow(clippy::ptr_arg)] p: &PathBuf, + #[allow(clippy::ptr_arg)] c: &Cow<[i32]>, + #[expect(clippy::ptr_arg)] expect: &Cow<[i32]>, ) { } } @@ -182,22 +182,22 @@ mod issue6509 { fn foo_vec(vec: &Vec) { //~^ ptr_arg - let _ = vec.clone().pop(); - let _ = vec.clone().clone(); + let a = vec.clone().pop(); + let b = vec.clone().clone(); } fn foo_path(path: &PathBuf) { //~^ ptr_arg - let _ = path.clone().pop(); - let _ = path.clone().clone(); + let c = path.clone().pop(); + let d = path.clone().clone(); } - fn foo_str(str: &PathBuf) { + fn foo_str(str: &String) { //~^ ptr_arg - let _ = str.clone().pop(); - let _ = str.clone().clone(); + let e = str.clone().pop(); + let f = str.clone().clone(); } } @@ -340,8 +340,8 @@ mod issue_13308 { ToOwned::clone_into(source, destination); } - fn h1(_: &::Target) {} - fn h2(_: T, _: &T::Target) {} + fn h1(x: &::Target) {} + fn h2(x: T, y: &T::Target) {} // Other cases that are still ok to lint and ideally shouldn't regress fn good(v1: &String, v2: &String) { @@ -352,3 +352,91 @@ mod issue_13308 { h2(String::new(), v2); } } + +mod issue_13489_and_13728 { + // This is a no-lint from now on. + fn foo(_x: &Vec) { + todo!(); + } + + // But this still gives us a lint. + fn foo_used(x: &Vec) { + //~^ ptr_arg + + todo!(); + } + + // This is also a no-lint from now on. + fn foo_local(x: &Vec) { + let _y = x; + + todo!(); + } + + // But this still gives us a lint. + fn foo_local_used(x: &Vec) { + //~^ ptr_arg + + let y = x; + + todo!(); + } + + // This only lints once from now on. + fn foofoo(_x: &Vec, y: &String) { + //~^ ptr_arg + + todo!(); + } + + // And this is also a no-lint from now on. + fn foofoo_local(_x: &Vec, y: &String) { + let _z = y; + + todo!(); + } +} + +mod issue_13489_and_13728_mut { + // This is a no-lint from now on. + fn bar(_x: &mut Vec) { + todo!() + } + + // But this still gives us a lint. + fn bar_used(x: &mut Vec) { + //~^ ptr_arg + + todo!() + } + + // This is also a no-lint from now on. + fn bar_local(x: &mut Vec) { + let _y = x; + + todo!() + } + + // But this still gives us a lint. + fn bar_local_used(x: &mut Vec) { + //~^ ptr_arg + + let y = x; + + todo!() + } + + // This only lints once from now on. + fn barbar(_x: &mut Vec, y: &mut String) { + //~^ ptr_arg + + todo!() + } + + // And this is also a no-lint from now on. + fn barbar_local(_x: &mut Vec, y: &mut String) { + let _z = y; + + todo!() + } +} diff --git a/tests/ui/ptr_arg.stderr b/tests/ui/ptr_arg.stderr index fd9ceddfe11c..87235057349e 100644 --- a/tests/ui/ptr_arg.stderr +++ b/tests/ui/ptr_arg.stderr @@ -127,10 +127,10 @@ LL | fn test_cow_with_ref(c: &Cow<[i32]>) {} | ^^^^^^^^^^^ help: change this to: `&[i32]` error: writing `&String` instead of `&str` involves a new object where a slice will do - --> tests/ui/ptr_arg.rs:152:66 + --> tests/ui/ptr_arg.rs:152:64 | -LL | fn some_allowed(#[allow(clippy::ptr_arg)] _v: &Vec, _s: &String) {} - | ^^^^^^^ help: change this to: `&str` +LL | fn some_allowed(#[allow(clippy::ptr_arg)] v: &Vec, s: &String) {} + | ^^^^^^^ help: change this to: `&str` error: writing `&Vec` instead of `&[_]` involves a new object where a slice will do --> tests/ui/ptr_arg.rs:182:21 @@ -143,8 +143,8 @@ help: change this to LL ~ fn foo_vec(vec: &[u8]) { LL | LL | -LL ~ let _ = vec.to_owned().pop(); -LL ~ let _ = vec.to_owned().clone(); +LL ~ let a = vec.to_owned().pop(); +LL ~ let b = vec.to_owned().clone(); | error: writing `&PathBuf` instead of `&Path` involves a new object where a slice will do @@ -158,23 +158,23 @@ help: change this to LL ~ fn foo_path(path: &Path) { LL | LL | -LL ~ let _ = path.to_path_buf().pop(); -LL ~ let _ = path.to_path_buf().clone(); +LL ~ let c = path.to_path_buf().pop(); +LL ~ let d = path.to_path_buf().clone(); | -error: writing `&PathBuf` instead of `&Path` involves a new object where a slice will do +error: writing `&String` instead of `&str` involves a new object where a slice will do --> tests/ui/ptr_arg.rs:196:21 | -LL | fn foo_str(str: &PathBuf) { - | ^^^^^^^^ +LL | fn foo_str(str: &String) { + | ^^^^^^^ | help: change this to | -LL ~ fn foo_str(str: &Path) { +LL ~ fn foo_str(str: &str) { LL | LL | -LL ~ let _ = str.to_path_buf().pop(); -LL ~ let _ = str.to_path_buf().clone(); +LL ~ let e = str.to_owned().pop(); +LL ~ let f = str.to_owned().clone(); | error: writing `&mut Vec` instead of `&mut [_]` involves a new object where a slice will do @@ -231,6 +231,42 @@ error: writing `&String` instead of `&str` involves a new object where a slice w LL | fn good(v1: &String, v2: &String) { | ^^^^^^^ help: change this to: `&str` +error: writing `&Vec` instead of `&[_]` involves a new object where a slice will do + --> tests/ui/ptr_arg.rs:363:20 + | +LL | fn foo_used(x: &Vec) { + | ^^^^^^^^^ help: change this to: `&[i32]` + +error: writing `&Vec` instead of `&[_]` involves a new object where a slice will do + --> tests/ui/ptr_arg.rs:377:26 + | +LL | fn foo_local_used(x: &Vec) { + | ^^^^^^^^^ help: change this to: `&[i32]` + +error: writing `&String` instead of `&str` involves a new object where a slice will do + --> tests/ui/ptr_arg.rs:386:33 + | +LL | fn foofoo(_x: &Vec, y: &String) { + | ^^^^^^^ help: change this to: `&str` + +error: writing `&mut Vec` instead of `&mut [_]` involves a new object where a slice will do + --> tests/ui/ptr_arg.rs:407:20 + | +LL | fn bar_used(x: &mut Vec) { + | ^^^^^^^^^^^^^ help: change this to: `&mut [u32]` + +error: writing `&mut Vec` instead of `&mut [_]` involves a new object where a slice will do + --> tests/ui/ptr_arg.rs:421:26 + | +LL | fn bar_local_used(x: &mut Vec) { + | ^^^^^^^^^^^^^ help: change this to: `&mut [u32]` + +error: writing `&mut String` instead of `&mut str` involves a new object where a slice will do + --> tests/ui/ptr_arg.rs:430:37 + | +LL | fn barbar(_x: &mut Vec, y: &mut String) { + | ^^^^^^^^^^^ help: change this to: `&mut str` + error: eliding a lifetime that's named elsewhere is confusing --> tests/ui/ptr_arg.rs:314:36 | @@ -248,5 +284,5 @@ help: consistently use `'a` LL | fn cow_good_ret_ty<'a>(input: &'a Cow<'a, str>) -> &'a str { | ++ -error: aborting due to 27 previous errors +error: aborting due to 33 previous errors diff --git a/tests/ui/ptr_as_ptr.fixed b/tests/ui/ptr_as_ptr.fixed index 2033f31c1eec..71fea6144e76 100644 --- a/tests/ui/ptr_as_ptr.fixed +++ b/tests/ui/ptr_as_ptr.fixed @@ -219,3 +219,11 @@ mod null_entire_infer { //~^ ptr_as_ptr } } + +#[allow(clippy::transmute_null_to_fn)] +fn issue15283() { + unsafe { + let _: fn() = std::mem::transmute(std::ptr::null::()); + //~^ ptr_as_ptr + } +} diff --git a/tests/ui/ptr_as_ptr.rs b/tests/ui/ptr_as_ptr.rs index 224d09b0eb6e..4d507592a1e3 100644 --- a/tests/ui/ptr_as_ptr.rs +++ b/tests/ui/ptr_as_ptr.rs @@ -219,3 +219,11 @@ mod null_entire_infer { //~^ ptr_as_ptr } } + +#[allow(clippy::transmute_null_to_fn)] +fn issue15283() { + unsafe { + let _: fn() = std::mem::transmute(std::ptr::null::<()>() as *const u8); + //~^ ptr_as_ptr + } +} diff --git a/tests/ui/ptr_as_ptr.stderr b/tests/ui/ptr_as_ptr.stderr index 66dae8e0135e..adad159bb0f2 100644 --- a/tests/ui/ptr_as_ptr.stderr +++ b/tests/ui/ptr_as_ptr.stderr @@ -201,5 +201,11 @@ error: `as` casting between raw pointers without changing their constness LL | core::ptr::null() as _ | ^^^^^^^^^^^^^^^^^^^^^^ help: try call directly: `core::ptr::null()` -error: aborting due to 33 previous errors +error: `as` casting between raw pointers without changing their constness + --> tests/ui/ptr_as_ptr.rs:226:43 + | +LL | let _: fn() = std::mem::transmute(std::ptr::null::<()>() as *const u8); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try call directly: `std::ptr::null::()` + +error: aborting due to 34 previous errors diff --git a/tests/ui/range_plus_minus_one.fixed b/tests/ui/range_plus_minus_one.fixed index ee716ef3a6a0..5c6da6d5aed3 100644 --- a/tests/ui/range_plus_minus_one.fixed +++ b/tests/ui/range_plus_minus_one.fixed @@ -1,5 +1,9 @@ +#![warn(clippy::range_minus_one, clippy::range_plus_one)] #![allow(unused_parens)] #![allow(clippy::iter_with_drain)] + +use std::ops::{Index, IndexMut, Range, RangeBounds, RangeInclusive}; + fn f() -> usize { 42 } @@ -20,8 +24,6 @@ macro_rules! macro_minus_one { }; } -#[warn(clippy::range_plus_one)] -#[warn(clippy::range_minus_one)] fn main() { for _ in 0..2 {} for _ in 0..=2 {} @@ -45,15 +47,13 @@ fn main() { //~^ range_plus_one for _ in 0..=(1 + f()) {} + // Those are not linted, as in the general case we cannot be sure that the exact type won't be + // important. let _ = ..11 - 1; - let _ = ..11; - //~^ range_minus_one - let _ = ..11; - //~^ range_minus_one - let _ = (1..=11); - //~^ range_plus_one - let _ = ((f() + 1)..=f()); - //~^ range_plus_one + let _ = ..=11 - 1; + let _ = ..=(11 - 1); + let _ = (1..11 + 1); + let _ = (f() + 1)..(f() + 1); const ONE: usize = 1; // integer consts are linted, too @@ -65,4 +65,118 @@ fn main() { macro_plus_one!(5); macro_minus_one!(5); + + // As an instance of `Iterator` + (1..=10).for_each(|_| {}); + //~^ range_plus_one + + // As an instance of `IntoIterator` + #[allow(clippy::useless_conversion)] + (1..=10).into_iter().for_each(|_| {}); + //~^ range_plus_one + + // As an instance of `RangeBounds` + { + let _ = (1..=10).start_bound(); + //~^ range_plus_one + } + + // As a `SliceIndex` + let a = [10, 20, 30]; + let _ = &a[1..=1]; + //~^ range_plus_one + + // As method call argument + vec.drain(2..=3); + //~^ range_plus_one + + // As function call argument + take_arg(10..=20); + //~^ range_plus_one + + // As function call argument inside a block + take_arg({ 10..=20 }); + //~^ range_plus_one + + // Do not lint in case types are unified + take_arg(if true { 10..20 } else { 10..20 + 1 }); + + // Do not lint, as the same type is used for both parameters + take_args(10..20 + 1, 10..21); + + // Do not lint, as the range type is also used indirectly in second parameter + take_arg_and_struct(10..20 + 1, S { t: 1..2 }); + + // As target of `IndexMut` + let mut a = [10, 20, 30]; + a[0..=2][0] = 1; + //~^ range_plus_one +} + +fn take_arg>(_: T) {} +fn take_args>(_: T, _: T) {} + +struct S { + t: T, +} +fn take_arg_and_struct>(_: T, _: S) {} + +fn no_index_by_range_inclusive(a: usize) { + struct S; + + impl Index> for S { + type Output = [u32]; + fn index(&self, _: Range) -> &Self::Output { + &[] + } + } + + _ = &S[0..a + 1]; +} + +fn no_index_mut_with_switched_range(a: usize) { + struct S(u32); + + impl Index> for S { + type Output = u32; + fn index(&self, _: Range) -> &Self::Output { + &self.0 + } + } + + impl IndexMut> for S { + fn index_mut(&mut self, _: Range) -> &mut Self::Output { + &mut self.0 + } + } + + impl Index> for S { + type Output = u32; + fn index(&self, _: RangeInclusive) -> &Self::Output { + &self.0 + } + } + + S(2)[0..a + 1] = 3; +} + +fn issue9908() { + // Simplified test case + let _ = || 0..=1; + + // Original test case + let full_length = 1024; + let range = { + // do some stuff, omit here + None + }; + + let range = range.map(|(s, t)| s..=t).unwrap_or(0..=(full_length - 1)); + + assert_eq!(range, 0..=1023); +} + +fn issue9908_2(n: usize) -> usize { + (1..n).sum() + //~^ range_minus_one } diff --git a/tests/ui/range_plus_minus_one.rs b/tests/ui/range_plus_minus_one.rs index f2d5ae2c1506..7172da6034b8 100644 --- a/tests/ui/range_plus_minus_one.rs +++ b/tests/ui/range_plus_minus_one.rs @@ -1,5 +1,9 @@ +#![warn(clippy::range_minus_one, clippy::range_plus_one)] #![allow(unused_parens)] #![allow(clippy::iter_with_drain)] + +use std::ops::{Index, IndexMut, Range, RangeBounds, RangeInclusive}; + fn f() -> usize { 42 } @@ -20,8 +24,6 @@ macro_rules! macro_minus_one { }; } -#[warn(clippy::range_plus_one)] -#[warn(clippy::range_minus_one)] fn main() { for _ in 0..2 {} for _ in 0..=2 {} @@ -45,15 +47,13 @@ fn main() { //~^ range_plus_one for _ in 0..=(1 + f()) {} + // Those are not linted, as in the general case we cannot be sure that the exact type won't be + // important. let _ = ..11 - 1; let _ = ..=11 - 1; - //~^ range_minus_one let _ = ..=(11 - 1); - //~^ range_minus_one let _ = (1..11 + 1); - //~^ range_plus_one let _ = (f() + 1)..(f() + 1); - //~^ range_plus_one const ONE: usize = 1; // integer consts are linted, too @@ -65,4 +65,118 @@ fn main() { macro_plus_one!(5); macro_minus_one!(5); + + // As an instance of `Iterator` + (1..10 + 1).for_each(|_| {}); + //~^ range_plus_one + + // As an instance of `IntoIterator` + #[allow(clippy::useless_conversion)] + (1..10 + 1).into_iter().for_each(|_| {}); + //~^ range_plus_one + + // As an instance of `RangeBounds` + { + let _ = (1..10 + 1).start_bound(); + //~^ range_plus_one + } + + // As a `SliceIndex` + let a = [10, 20, 30]; + let _ = &a[1..1 + 1]; + //~^ range_plus_one + + // As method call argument + vec.drain(2..3 + 1); + //~^ range_plus_one + + // As function call argument + take_arg(10..20 + 1); + //~^ range_plus_one + + // As function call argument inside a block + take_arg({ 10..20 + 1 }); + //~^ range_plus_one + + // Do not lint in case types are unified + take_arg(if true { 10..20 } else { 10..20 + 1 }); + + // Do not lint, as the same type is used for both parameters + take_args(10..20 + 1, 10..21); + + // Do not lint, as the range type is also used indirectly in second parameter + take_arg_and_struct(10..20 + 1, S { t: 1..2 }); + + // As target of `IndexMut` + let mut a = [10, 20, 30]; + a[0..2 + 1][0] = 1; + //~^ range_plus_one +} + +fn take_arg>(_: T) {} +fn take_args>(_: T, _: T) {} + +struct S { + t: T, +} +fn take_arg_and_struct>(_: T, _: S) {} + +fn no_index_by_range_inclusive(a: usize) { + struct S; + + impl Index> for S { + type Output = [u32]; + fn index(&self, _: Range) -> &Self::Output { + &[] + } + } + + _ = &S[0..a + 1]; +} + +fn no_index_mut_with_switched_range(a: usize) { + struct S(u32); + + impl Index> for S { + type Output = u32; + fn index(&self, _: Range) -> &Self::Output { + &self.0 + } + } + + impl IndexMut> for S { + fn index_mut(&mut self, _: Range) -> &mut Self::Output { + &mut self.0 + } + } + + impl Index> for S { + type Output = u32; + fn index(&self, _: RangeInclusive) -> &Self::Output { + &self.0 + } + } + + S(2)[0..a + 1] = 3; +} + +fn issue9908() { + // Simplified test case + let _ = || 0..=1; + + // Original test case + let full_length = 1024; + let range = { + // do some stuff, omit here + None + }; + + let range = range.map(|(s, t)| s..=t).unwrap_or(0..=(full_length - 1)); + + assert_eq!(range, 0..=1023); +} + +fn issue9908_2(n: usize) -> usize { + (1..=n - 1).sum() + //~^ range_minus_one } diff --git a/tests/ui/range_plus_minus_one.stderr b/tests/ui/range_plus_minus_one.stderr index 9b23a8b8c0b4..a419d935bd62 100644 --- a/tests/ui/range_plus_minus_one.stderr +++ b/tests/ui/range_plus_minus_one.stderr @@ -1,5 +1,5 @@ error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:29:14 + --> tests/ui/range_plus_minus_one.rs:31:14 | LL | for _ in 0..3 + 1 {} | ^^^^^^^^ help: use: `0..=3` @@ -8,55 +8,85 @@ LL | for _ in 0..3 + 1 {} = help: to override `-D warnings` add `#[allow(clippy::range_plus_one)]` error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:33:14 + --> tests/ui/range_plus_minus_one.rs:35:14 | LL | for _ in 0..1 + 5 {} | ^^^^^^^^ help: use: `0..=5` error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:37:14 + --> tests/ui/range_plus_minus_one.rs:39:14 | LL | for _ in 1..1 + 1 {} | ^^^^^^^^ help: use: `1..=1` error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:44:14 + --> tests/ui/range_plus_minus_one.rs:46:14 | LL | for _ in 0..(1 + f()) {} | ^^^^^^^^^^^^ help: use: `0..=f()` -error: an exclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:49:13 +error: an inclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:60:14 | -LL | let _ = ..=11 - 1; - | ^^^^^^^^^ help: use: `..11` +LL | for _ in 1..ONE + ONE {} + | ^^^^^^^^^^^^ help: use: `1..=ONE` + +error: an inclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:70:5 | - = note: `-D clippy::range-minus-one` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::range_minus_one)]` +LL | (1..10 + 1).for_each(|_| {}); + | ^^^^^^^^^^^ help: use: `(1..=10)` -error: an exclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:51:13 +error: an inclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:75:5 | -LL | let _ = ..=(11 - 1); - | ^^^^^^^^^^^ help: use: `..11` +LL | (1..10 + 1).into_iter().for_each(|_| {}); + | ^^^^^^^^^^^ help: use: `(1..=10)` error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:53:13 + --> tests/ui/range_plus_minus_one.rs:80:17 | -LL | let _ = (1..11 + 1); - | ^^^^^^^^^^^ help: use: `(1..=11)` +LL | let _ = (1..10 + 1).start_bound(); + | ^^^^^^^^^^^ help: use: `(1..=10)` error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:55:13 + --> tests/ui/range_plus_minus_one.rs:86:16 | -LL | let _ = (f() + 1)..(f() + 1); - | ^^^^^^^^^^^^^^^^^^^^ help: use: `((f() + 1)..=f())` +LL | let _ = &a[1..1 + 1]; + | ^^^^^^^^ help: use: `1..=1` error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:60:14 + --> tests/ui/range_plus_minus_one.rs:90:15 | -LL | for _ in 1..ONE + ONE {} - | ^^^^^^^^^^^^ help: use: `1..=ONE` +LL | vec.drain(2..3 + 1); + | ^^^^^^^^ help: use: `2..=3` + +error: an inclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:94:14 + | +LL | take_arg(10..20 + 1); + | ^^^^^^^^^^ help: use: `10..=20` + +error: an inclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:98:16 + | +LL | take_arg({ 10..20 + 1 }); + | ^^^^^^^^^^ help: use: `10..=20` + +error: an inclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:112:7 + | +LL | a[0..2 + 1][0] = 1; + | ^^^^^^^^ help: use: `0..=2` + +error: an exclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:180:5 + | +LL | (1..=n - 1).sum() + | ^^^^^^^^^^^ help: use: `(1..n)` + | + = note: `-D clippy::range-minus-one` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::range_minus_one)]` -error: aborting due to 9 previous errors +error: aborting due to 14 previous errors diff --git a/tests/ui/single_match_else_deref_patterns.fixed b/tests/ui/single_match_else_deref_patterns.fixed new file mode 100644 index 000000000000..7a9f80630964 --- /dev/null +++ b/tests/ui/single_match_else_deref_patterns.fixed @@ -0,0 +1,53 @@ +#![feature(deref_patterns)] +#![allow( + incomplete_features, + clippy::eq_op, + clippy::op_ref, + clippy::deref_addrof, + clippy::borrow_deref_ref, + clippy::needless_if +)] +#![deny(clippy::single_match_else)] + +fn string() { + if *"" == *"" {} + + if *&*&*&*"" == *"" {} + + if ***&&"" == *"" {} + + if *&*&*"" == *"" {} + + if **&&*"" == *"" {} +} + +fn int() { + if &&&1 == &&&2 { unreachable!() } else { + // ok + } + //~^^^^^^ single_match_else + if &&1 == &&2 { unreachable!() } else { + // ok + } + //~^^^^^^ single_match_else + if &&1 == &&2 { unreachable!() } else { + // ok + } + //~^^^^^^ single_match_else + if &1 == &2 { unreachable!() } else { + // ok + } + //~^^^^^^ single_match_else + if &1 == &2 { unreachable!() } else { + // ok + } + //~^^^^^^ single_match_else + if 1 == 2 { unreachable!() } else { + // ok + } + //~^^^^^^ single_match_else + if 1 == 2 { unreachable!() } else { + // ok + } + //~^^^^^^ single_match_else +} diff --git a/tests/ui/single_match_else_deref_patterns.rs b/tests/ui/single_match_else_deref_patterns.rs new file mode 100644 index 000000000000..ef19c7cbde2b --- /dev/null +++ b/tests/ui/single_match_else_deref_patterns.rs @@ -0,0 +1,94 @@ +#![feature(deref_patterns)] +#![allow( + incomplete_features, + clippy::eq_op, + clippy::op_ref, + clippy::deref_addrof, + clippy::borrow_deref_ref, + clippy::needless_if +)] +#![deny(clippy::single_match_else)] + +fn string() { + match *"" { + //~^ single_match + "" => {}, + _ => {}, + } + + match *&*&*&*"" { + //~^ single_match + "" => {}, + _ => {}, + } + + match ***&&"" { + //~^ single_match + "" => {}, + _ => {}, + } + + match *&*&*"" { + //~^ single_match + "" => {}, + _ => {}, + } + + match **&&*"" { + //~^ single_match + "" => {}, + _ => {}, + } +} + +fn int() { + match &&&1 { + &&&2 => unreachable!(), + _ => { + // ok + }, + } + //~^^^^^^ single_match_else + match &&&1 { + &&2 => unreachable!(), + _ => { + // ok + }, + } + //~^^^^^^ single_match_else + match &&1 { + &&2 => unreachable!(), + _ => { + // ok + }, + } + //~^^^^^^ single_match_else + match &&&1 { + &2 => unreachable!(), + _ => { + // ok + }, + } + //~^^^^^^ single_match_else + match &&1 { + &2 => unreachable!(), + _ => { + // ok + }, + } + //~^^^^^^ single_match_else + match &&&1 { + 2 => unreachable!(), + _ => { + // ok + }, + } + //~^^^^^^ single_match_else + match &&1 { + 2 => unreachable!(), + _ => { + // ok + }, + } + //~^^^^^^ single_match_else +} diff --git a/tests/ui/single_match_else_deref_patterns.stderr b/tests/ui/single_match_else_deref_patterns.stderr new file mode 100644 index 000000000000..a47df55459be --- /dev/null +++ b/tests/ui/single_match_else_deref_patterns.stderr @@ -0,0 +1,188 @@ +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:13:5 + | +LL | / match *"" { +LL | | +LL | | "" => {}, +LL | | _ => {}, +LL | | } + | |_____^ help: try: `if *"" == *"" {}` + | + = note: you might want to preserve the comments from inside the `match` + = note: `-D clippy::single-match` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::single_match)]` + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:19:5 + | +LL | / match *&*&*&*"" { +LL | | +LL | | "" => {}, +LL | | _ => {}, +LL | | } + | |_____^ help: try: `if *&*&*&*"" == *"" {}` + | + = note: you might want to preserve the comments from inside the `match` + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:25:5 + | +LL | / match ***&&"" { +LL | | +LL | | "" => {}, +LL | | _ => {}, +LL | | } + | |_____^ help: try: `if ***&&"" == *"" {}` + | + = note: you might want to preserve the comments from inside the `match` + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:31:5 + | +LL | / match *&*&*"" { +LL | | +LL | | "" => {}, +LL | | _ => {}, +LL | | } + | |_____^ help: try: `if *&*&*"" == *"" {}` + | + = note: you might want to preserve the comments from inside the `match` + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:37:5 + | +LL | / match **&&*"" { +LL | | +LL | | "" => {}, +LL | | _ => {}, +LL | | } + | |_____^ help: try: `if **&&*"" == *"" {}` + | + = note: you might want to preserve the comments from inside the `match` + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:45:5 + | +LL | / match &&&1 { +LL | | &&&2 => unreachable!(), +LL | | _ => { +... | +LL | | } + | |_____^ + | +note: the lint level is defined here + --> tests/ui/single_match_else_deref_patterns.rs:10:9 + | +LL | #![deny(clippy::single_match_else)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ +help: try + | +LL ~ if &&&1 == &&&2 { unreachable!() } else { +LL + // ok +LL + } + | + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:52:5 + | +LL | / match &&&1 { +LL | | &&2 => unreachable!(), +LL | | _ => { +... | +LL | | } + | |_____^ + | +help: try + | +LL ~ if &&1 == &&2 { unreachable!() } else { +LL + // ok +LL + } + | + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:59:5 + | +LL | / match &&1 { +LL | | &&2 => unreachable!(), +LL | | _ => { +... | +LL | | } + | |_____^ + | +help: try + | +LL ~ if &&1 == &&2 { unreachable!() } else { +LL + // ok +LL + } + | + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:66:5 + | +LL | / match &&&1 { +LL | | &2 => unreachable!(), +LL | | _ => { +... | +LL | | } + | |_____^ + | +help: try + | +LL ~ if &1 == &2 { unreachable!() } else { +LL + // ok +LL + } + | + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:73:5 + | +LL | / match &&1 { +LL | | &2 => unreachable!(), +LL | | _ => { +... | +LL | | } + | |_____^ + | +help: try + | +LL ~ if &1 == &2 { unreachable!() } else { +LL + // ok +LL + } + | + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:80:5 + | +LL | / match &&&1 { +LL | | 2 => unreachable!(), +LL | | _ => { +... | +LL | | } + | |_____^ + | +help: try + | +LL ~ if 1 == 2 { unreachable!() } else { +LL + // ok +LL + } + | + +error: you seem to be trying to use `match` for an equality check. Consider using `if` + --> tests/ui/single_match_else_deref_patterns.rs:87:5 + | +LL | / match &&1 { +LL | | 2 => unreachable!(), +LL | | _ => { +... | +LL | | } + | |_____^ + | +help: try + | +LL ~ if 1 == 2 { unreachable!() } else { +LL + // ok +LL + } + | + +error: aborting due to 12 previous errors + diff --git a/tests/ui/unsafe_derive_deserialize.rs b/tests/ui/unsafe_derive_deserialize.rs index 14371bc203b3..d0022f3b6d93 100644 --- a/tests/ui/unsafe_derive_deserialize.rs +++ b/tests/ui/unsafe_derive_deserialize.rs @@ -82,3 +82,32 @@ impl H { } fn main() {} + +mod issue15120 { + macro_rules! uns { + ($e:expr) => { + unsafe { $e } + }; + } + + #[derive(serde::Deserialize)] + struct Foo; + + impl Foo { + fn foo(&self) { + // Do not lint if `unsafe` comes from the `core::pin::pin!()` macro + std::pin::pin!(()); + } + } + + //~v unsafe_derive_deserialize + #[derive(serde::Deserialize)] + struct Bar; + + impl Bar { + fn bar(&self) { + // Lint if `unsafe` comes from the another macro + _ = uns!(42); + } + } +} diff --git a/tests/ui/unsafe_derive_deserialize.stderr b/tests/ui/unsafe_derive_deserialize.stderr index f2d4429f707a..4b5dd6e61fcc 100644 --- a/tests/ui/unsafe_derive_deserialize.stderr +++ b/tests/ui/unsafe_derive_deserialize.stderr @@ -36,5 +36,14 @@ LL | #[derive(Deserialize)] = help: consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html = note: this error originates in the derive macro `Deserialize` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 4 previous errors +error: you are deriving `serde::Deserialize` on a type that has methods using `unsafe` + --> tests/ui/unsafe_derive_deserialize.rs:104:14 + | +LL | #[derive(serde::Deserialize)] + | ^^^^^^^^^^^^^^^^^^ + | + = help: consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html + = note: this error originates in the derive macro `serde::Deserialize` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 5 previous errors diff --git a/tests/ui/unused_async.rs b/tests/ui/unused_async.rs index 433459253dd7..7a0be825a2de 100644 --- a/tests/ui/unused_async.rs +++ b/tests/ui/unused_async.rs @@ -127,3 +127,13 @@ mod issue14704 { async fn cancel(self: Arc) {} } } + +mod issue15305 { + async fn todo_task() -> Result<(), String> { + todo!("Implement task"); + } + + async fn unimplemented_task() -> Result<(), String> { + unimplemented!("Implement task"); + } +} diff --git a/tests/ui/unused_trait_names.fixed b/tests/ui/unused_trait_names.fixed index 17e32ddfd9d9..6abbed01bb02 100644 --- a/tests/ui/unused_trait_names.fixed +++ b/tests/ui/unused_trait_names.fixed @@ -200,11 +200,11 @@ fn msrv_1_33() { MyStruct.do_things(); } +// Linting inside macro expansion is no longer supported mod lint_inside_macro_expansion_bad { macro_rules! foo { () => { - use std::any::Any as _; - //~^ unused_trait_names + use std::any::Any; fn bar() { "bar".type_id(); } diff --git a/tests/ui/unused_trait_names.rs b/tests/ui/unused_trait_names.rs index 3cf8597e5351..4a06f062dc37 100644 --- a/tests/ui/unused_trait_names.rs +++ b/tests/ui/unused_trait_names.rs @@ -200,11 +200,11 @@ fn msrv_1_33() { MyStruct.do_things(); } +// Linting inside macro expansion is no longer supported mod lint_inside_macro_expansion_bad { macro_rules! foo { () => { use std::any::Any; - //~^ unused_trait_names fn bar() { "bar".type_id(); } diff --git a/tests/ui/unused_trait_names.stderr b/tests/ui/unused_trait_names.stderr index 3183289d8533..28067e17414f 100644 --- a/tests/ui/unused_trait_names.stderr +++ b/tests/ui/unused_trait_names.stderr @@ -58,16 +58,5 @@ error: importing trait that is only used anonymously LL | use simple_trait::{MyStruct, MyTrait}; | ^^^^^^^ help: use: `MyTrait as _` -error: importing trait that is only used anonymously - --> tests/ui/unused_trait_names.rs:206:27 - | -LL | use std::any::Any; - | ^^^ help: use: `Any as _` -... -LL | foo!(); - | ------ in this macro invocation - | - = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: aborting due to 10 previous errors +error: aborting due to 9 previous errors diff --git a/tests/ui/used_underscore_items.rs b/tests/ui/used_underscore_items.rs index 7e8289f1406b..aecdd32693c1 100644 --- a/tests/ui/used_underscore_items.rs +++ b/tests/ui/used_underscore_items.rs @@ -62,13 +62,13 @@ fn main() { //~^ used_underscore_items } -// should not lint exteranl crate. +// should not lint external crate. // user cannot control how others name their items fn external_item_call() { let foo_struct3 = external_item::_ExternalStruct {}; foo_struct3._foo(); - external_item::_exernal_foo(); + external_item::_external_foo(); } // should not lint foreign functions. diff --git a/tests/ui/useless_attribute.fixed b/tests/ui/useless_attribute.fixed index 930bc1eaecf9..be4fb55ddfb8 100644 --- a/tests/ui/useless_attribute.fixed +++ b/tests/ui/useless_attribute.fixed @@ -146,3 +146,15 @@ pub mod unknown_namespace { #[allow(rustc::non_glob_import_of_type_ir_inherent)] use some_module::SomeType; } + +// Regression test for https://github.com/rust-lang/rust-clippy/issues/15316 +pub mod redundant_imports_issue { + macro_rules! empty { + () => {}; + } + + #[expect(redundant_imports)] + pub(crate) use empty; + + empty!(); +} diff --git a/tests/ui/useless_attribute.rs b/tests/ui/useless_attribute.rs index 50fafd478e51..5a1bcf97a5b4 100644 --- a/tests/ui/useless_attribute.rs +++ b/tests/ui/useless_attribute.rs @@ -146,3 +146,15 @@ pub mod unknown_namespace { #[allow(rustc::non_glob_import_of_type_ir_inherent)] use some_module::SomeType; } + +// Regression test for https://github.com/rust-lang/rust-clippy/issues/15316 +pub mod redundant_imports_issue { + macro_rules! empty { + () => {}; + } + + #[expect(redundant_imports)] + pub(crate) use empty; + + empty!(); +} diff --git a/triagebot.toml b/triagebot.toml index 805baf2af6dd..a62b6269a3bf 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -54,6 +54,7 @@ contributing_url = "https://github.com/rust-lang/rust-clippy/blob/master/CONTRIB users_on_vacation = [ "matthiaskrgr", "Manishearth", + "samueltardieu", ] [assign.owners] diff --git a/util/gh-pages/index_template.html b/util/gh-pages/index_template.html index 6f380ec8feef..5d65ea585df6 100644 --- a/util/gh-pages/index_template.html +++ b/util/gh-pages/index_template.html @@ -49,9 +49,7 @@ {# #}
{# #} - {# #} +

Clippy Lints

{# #} {# #} -
{# #} - {# #} lint.group != "deprecated"); const totalLints = allLints.length; - + const countElement = document.getElementById("lint-count"); if (countElement) { countElement.innerText = `Total number: ${totalLints}`; } } + +generateSettings(); +generateSearch(); +parseURLFilters(); +scrollToLintByURL(); +filters.filterLints(); +updateLintCount(); diff --git a/util/gh-pages/style.css b/util/gh-pages/style.css index 022ea8752000..66abf4598b0e 100644 --- a/util/gh-pages/style.css +++ b/util/gh-pages/style.css @@ -30,17 +30,25 @@ blockquote { font-size: 1em; } background-color: var(--theme-hover); } -div.panel div.panel-body button { +.container > * { + margin-bottom: 20px; + border-radius: 4px; + background: var(--bg); + border: 1px solid var(--theme-popup-border); + box-shadow: 0 1px 1px rgba(0,0,0,.05); +} + +div.panel-body button { background: var(--searchbar-bg); color: var(--searchbar-fg); border-color: var(--theme-popup-border); } -div.panel div.panel-body button:hover { +div.panel-body button:hover { box-shadow: 0 0 3px var(--searchbar-shadow-color); } -div.panel div.panel-body button.open { +div.panel-body button.open { filter: brightness(90%); } @@ -48,8 +56,6 @@ div.panel div.panel-body button.open { background-color: #777; } -.panel-heading { cursor: pointer; } - .lint-title { cursor: pointer; margin-top: 0; @@ -70,8 +76,8 @@ div.panel div.panel-body button.open { .panel-title-name { flex: 1; min-width: 400px;} -.panel .panel-title-name .anchor { display: none; } -.panel:hover .panel-title-name .anchor { display: inline;} +.panel-title-name .anchor { display: none; } +article:hover .panel-title-name .anchor { display: inline;} .search-control { margin-top: 15px; @@ -111,40 +117,48 @@ div.panel div.panel-body button.open { padding-bottom: 0.3em; } -.label-lint-group { - min-width: 8em; -} -.label-lint-level { +.lint-level { min-width: 4em; } - -.label-lint-level-allow { +.level-allow { background-color: #5cb85c; } -.label-lint-level-warn { +.level-warn { background-color: #f0ad4e; } -.label-lint-level-deny { +.level-deny { background-color: #d9534f; } -.label-lint-level-none { +.level-none { background-color: #777777; opacity: 0.5; } -.label-group-deprecated { +.lint-group { + min-width: 8em; +} +.group-deprecated { opacity: 0.5; } -.label-doc-folding { +.doc-folding { color: #000; background-color: #fff; border: 1px solid var(--theme-popup-border); } -.label-doc-folding:hover { +.doc-folding:hover { background-color: #e6e6e6; } +.lint-doc-md { + position: relative; + display: block; + padding: 10px 15px; + margin-bottom: -1px; + background: 0%; + border-bottom: 1px solid var(--theme-popup-border); + border-top: 1px solid var(--theme-popup-border); +} .lint-doc-md > h3 { border-top: 1px solid var(--theme-popup-border); padding: 10px 15px; @@ -157,32 +171,32 @@ div.panel div.panel-body button.open { } @media (max-width:749px) { - .lint-additional-info-container { + .lint-additional-info { display: flex; flex-flow: column; } - .lint-additional-info-container > div + div { + .lint-additional-info > div + div { border-top: 1px solid var(--theme-popup-border); } } @media (min-width:750px) { - .lint-additional-info-container { + .lint-additional-info { display: flex; flex-flow: row; } - .lint-additional-info-container > div + div { + .lint-additional-info > div + div { border-left: 1px solid var(--theme-popup-border); } } -.lint-additional-info-container > div { +.lint-additional-info > div { display: inline-flex; min-width: 200px; flex-grow: 1; padding: 9px 5px 5px 15px; } -.label-applicability { +.applicability { background-color: #777777; margin: auto 5px; } @@ -332,21 +346,12 @@ L4.75,12h2.5l0.5393066-2.1572876 c0.2276001-0.1062012,0.4459839-0.2269287,0.649 border: 1px solid var(--theme-popup-border); } .page-header { - border-color: var(--theme-popup-border); -} -.panel-default .panel-heading { - background: var(--theme-hover); - color: var(--fg); - border: 1px solid var(--theme-popup-border); -} -.panel-default .panel-heading:hover { - filter: brightness(90%); -} -.list-group-item { - background: 0%; - border: 1px solid var(--theme-popup-border); + border: 0; + border-bottom: 1px solid var(--theme-popup-border); + padding-bottom: 19px; + border-radius: 0; } -.panel, pre, hr { +pre, hr { background: var(--bg); border: 1px solid var(--theme-popup-border); } @@ -442,14 +447,15 @@ article > label { article > input[type="checkbox"] { display: none; } -article > input[type="checkbox"] + label .label-doc-folding::before { +article > input[type="checkbox"] + label .doc-folding::before { content: "+"; } -article > input[type="checkbox"]:checked + label .label-doc-folding::before { +article > input[type="checkbox"]:checked + label .doc-folding::before { content: "−"; } .lint-docs { display: none; + margin-bottom: 0; } article > input[type="checkbox"]:checked ~ .lint-docs { display: block; From c6ac515a2bcf6dbb4e27b11111da80f5ff36a88d Mon Sep 17 00:00:00 2001 From: "Pascal S. de Kloe" Date: Thu, 26 Jun 2025 14:52:39 +0200 Subject: [PATCH 0136/1134] fmt of non-decimals is always non-negative due to the two's-complement output --- library/core/src/fmt/num.rs | 88 ++++++++++++++++++++----------------- 1 file changed, 48 insertions(+), 40 deletions(-) diff --git a/library/core/src/fmt/num.rs b/library/core/src/fmt/num.rs index 7d41ae45093e..a52749d43259 100644 --- a/library/core/src/fmt/num.rs +++ b/library/core/src/fmt/num.rs @@ -54,44 +54,31 @@ unsafe trait GenericRadix: Sized { /// Converts an integer to corresponding radix digit. fn digit(x: u8) -> u8; - /// Format an integer using the radix using a formatter. + /// Format an unsigned integer using the radix using a formatter. fn fmt_int(&self, mut x: T, f: &mut fmt::Formatter<'_>) -> fmt::Result { // The radix can be as low as 2, so we need a buffer of at least 128 // characters for a base 2 number. let zero = T::zero(); - let is_nonnegative = x >= zero; let mut buf = [MaybeUninit::::uninit(); 128]; let mut offset = buf.len(); let base = T::from_u8(Self::BASE); - if is_nonnegative { - // Accumulate each digit of the number from the least significant - // to the most significant figure. - loop { - let n = x % base; // Get the current place value. - x = x / base; // Deaccumulate the number. - offset -= 1; - buf[offset].write(Self::digit(n.to_u8())); // Store the digit in the buffer. - if x == zero { - // No more digits left to accumulate. - break; - }; - } - } else { - // Do the same as above, but accounting for two's complement. - loop { - let n = zero - (x % base); // Get the current place value. - x = x / base; // Deaccumulate the number. - offset -= 1; - buf[offset].write(Self::digit(n.to_u8())); // Store the digit in the buffer. - if x == zero { - // No more digits left to accumulate. - break; - }; - } + + // Accumulate each digit of the number from the least significant + // to the most significant figure. + loop { + let n = x % base; // Get the current place value. + x = x / base; // Deaccumulate the number. + offset -= 1; + buf[offset].write(Self::digit(n.to_u8())); // Store the digit in the buffer. + if x == zero { + // No more digits left to accumulate. + break; + }; } + // SAFETY: Starting from `offset`, all elements of the slice have been set. - let buf_slice = unsafe { slice_buffer_to_str(&buf, offset) }; - f.pad_integral(is_nonnegative, Self::PREFIX, buf_slice) + let digits = unsafe { slice_buffer_to_str(&buf, offset) }; + f.pad_integral(true, Self::PREFIX, digits) } } @@ -132,11 +119,11 @@ radix! { LowerHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, x @ 10 ..= 15 => b'a' + radix! { UpperHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, x @ 10 ..= 15 => b'A' + (x - 10) } macro_rules! int_base { - (fmt::$Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { + (fmt::$Trait:ident for $T:ident -> $Radix:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - $Radix.fmt_int(*self as $U, f) + $Radix.fmt_int(*self, f) } } }; @@ -144,15 +131,36 @@ macro_rules! int_base { macro_rules! integer { ($Int:ident, $Uint:ident) => { - int_base! { fmt::Binary for $Int as $Uint -> Binary } - int_base! { fmt::Octal for $Int as $Uint -> Octal } - int_base! { fmt::LowerHex for $Int as $Uint -> LowerHex } - int_base! { fmt::UpperHex for $Int as $Uint -> UpperHex } - - int_base! { fmt::Binary for $Uint as $Uint -> Binary } - int_base! { fmt::Octal for $Uint as $Uint -> Octal } - int_base! { fmt::LowerHex for $Uint as $Uint -> LowerHex } - int_base! { fmt::UpperHex for $Uint as $Uint -> UpperHex } + int_base! { fmt::Binary for $Uint -> Binary } + int_base! { fmt::Octal for $Uint -> Octal } + int_base! { fmt::LowerHex for $Uint -> LowerHex } + int_base! { fmt::UpperHex for $Uint -> UpperHex } + + // Format signed integers as unsigned (two’s complement representation). + #[stable(feature = "rust1", since = "1.0.0")] + impl fmt::Binary for $Int { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Binary::fmt(&self.cast_unsigned(), f) + } + } + #[stable(feature = "rust1", since = "1.0.0")] + impl fmt::Octal for $Int { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Octal::fmt(&self.cast_unsigned(), f) + } + } + #[stable(feature = "rust1", since = "1.0.0")] + impl fmt::LowerHex for $Int { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::LowerHex::fmt(&self.cast_unsigned(), f) + } + } + #[stable(feature = "rust1", since = "1.0.0")] + impl fmt::UpperHex for $Int { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::UpperHex::fmt(&self.cast_unsigned(), f) + } + } }; } integer! { isize, usize } From 7704a3968523e872dbda05e449cd6375e4520bad Mon Sep 17 00:00:00 2001 From: "Pascal S. de Kloe" Date: Sun, 29 Jun 2025 17:08:40 +0200 Subject: [PATCH 0137/1134] fmt benchmarks for binary, octal and hex --- library/coretests/benches/fmt.rs | 180 +++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) diff --git a/library/coretests/benches/fmt.rs b/library/coretests/benches/fmt.rs index ee8e981b46b9..f45b921b9393 100644 --- a/library/coretests/benches/fmt.rs +++ b/library/coretests/benches/fmt.rs @@ -162,3 +162,183 @@ fn write_u8_min(bh: &mut Bencher) { black_box(format!("{}", black_box(u8::MIN))); }); } + +#[bench] +fn write_i8_bin(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:b}", black_box(0_i8)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(100_i8)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(-100_i8)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(1_i8 << 4)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i16_bin(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:b}", black_box(0_i16)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(100_i16)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(-100_i16)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(1_i16 << 8)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i32_bin(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:b}", black_box(0_i32)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(100_i32)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(-100_i32)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(1_i32 << 16)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i64_bin(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:b}", black_box(0_i64)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(100_i64)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(-100_i64)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(1_i64 << 32)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i128_bin(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:b}", black_box(0_i128)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(100_i128)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(-100_i128)).unwrap(); + write!(black_box(&mut buf), "{:b}", black_box(1_i128 << 64)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i8_oct(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:o}", black_box(0_i8)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(100_i8)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(-100_i8)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(1_i8 << 4)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i16_oct(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:o}", black_box(0_i16)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(100_i16)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(-100_i16)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(1_i16 << 8)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i32_oct(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:o}", black_box(0_i32)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(100_i32)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(-100_i32)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(1_i32 << 16)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i64_oct(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:o}", black_box(0_i64)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(100_i64)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(-100_i64)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(1_i64 << 32)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i128_oct(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:o}", black_box(0_i128)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(100_i128)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(-100_i128)).unwrap(); + write!(black_box(&mut buf), "{:o}", black_box(1_i128 << 64)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i8_hex(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:x}", black_box(0_i8)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(100_i8)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(-100_i8)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(1_i8 << 4)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i16_hex(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:x}", black_box(0_i16)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(100_i16)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(-100_i16)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(1_i16 << 8)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i32_hex(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:x}", black_box(0_i32)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(100_i32)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(-100_i32)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(1_i32 << 16)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i64_hex(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:x}", black_box(0_i64)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(100_i64)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(-100_i64)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(1_i64 << 32)).unwrap(); + black_box(&mut buf).clear(); + }); +} + +#[bench] +fn write_i128_hex(bh: &mut Bencher) { + let mut buf = String::with_capacity(256); + bh.iter(|| { + write!(black_box(&mut buf), "{:x}", black_box(0_i128)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(100_i128)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(-100_i128)).unwrap(); + write!(black_box(&mut buf), "{:x}", black_box(1_i128 << 64)).unwrap(); + black_box(&mut buf).clear(); + }); +} From 5b8c61494f85a58759dad04194c8353de07d75e1 Mon Sep 17 00:00:00 2001 From: Alisa Sireneva Date: Fri, 25 Jul 2025 21:03:09 +0300 Subject: [PATCH 0138/1134] Add a list of failure conditions for poisoning --- library/std/src/sync/poison/mutex.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/library/std/src/sync/poison/mutex.rs b/library/std/src/sync/poison/mutex.rs index 15dfe116133b..317e5fc3bfb9 100644 --- a/library/std/src/sync/poison/mutex.rs +++ b/library/std/src/sync/poison/mutex.rs @@ -35,8 +35,20 @@ use crate::sys::sync as sys; /// /// In addition, the panic detection is not ideal, so even unpoisoned mutexes /// need to be handled with care, since certain panics may have been skipped. -/// Therefore, `unsafe` code cannot rely on poisoning for soundness. Here's an -/// example of **incorrect** use of poisoning: +/// Here is a non-exhaustive list of situations where this might occur: +/// +/// - If a mutex is locked while a panic is underway, e.g. within a [`Drop`] +/// implementation or a [panic hook], panicking for the second time while the +/// lock is held will leave the mutex unpoisoned. Note that while double panic +/// usually aborts the program, [`catch_unwind`] can prevent this. +/// +/// - Locking and unlocking the mutex across different panic contexts, e.g. by +/// storing the guard to a [`Cell`] within [`Drop::drop`] and accessing it +/// outside, or vice versa, can affect poisoning status in an unexpected way. +/// +/// While this rarely happens in realistic code, `unsafe` code cannot rely on +/// poisoning for soundness, since the behavior of poisoning can depend on +/// outside context. Here's an example of **incorrect** use of poisoning: /// /// ```rust /// use std::sync::Mutex; @@ -58,8 +70,8 @@ use crate::sys::sync as sys; /// // panics, `*ptr` keeps pointing at a dropped value. The intention /// // is that this will poison the mutex, so the following calls to /// // `replace_with` will panic without reading `*ptr`. But since -/// // poisoning is not guaranteed to occur, this can lead to -/// // use-after-free. +/// // poisoning is not guaranteed to occur if this is run from a panic +/// // hook, this can lead to use-after-free. /// unsafe { /// (*ptr).write(f((*ptr).read())); /// } @@ -73,6 +85,9 @@ use crate::sys::sync as sys; /// [`unwrap()`]: Result::unwrap /// [`PoisonError`]: super::PoisonError /// [`into_inner`]: super::PoisonError::into_inner +/// [panic hook]: crate::panic::set_hook +/// [`catch_unwind`]: crate::panic::catch_unwind +/// [`Cell`]: crate::cell::Cell /// /// # Examples /// From c1d06cccaed537c799838dc5338dda28bbace52b Mon Sep 17 00:00:00 2001 From: Alisa Sireneva Date: Fri, 25 Jul 2025 22:14:02 +0300 Subject: [PATCH 0139/1134] Add a note on foreign exceptions --- library/std/src/sync/poison/mutex.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/library/std/src/sync/poison/mutex.rs b/library/std/src/sync/poison/mutex.rs index 317e5fc3bfb9..363220baf7b9 100644 --- a/library/std/src/sync/poison/mutex.rs +++ b/library/std/src/sync/poison/mutex.rs @@ -46,6 +46,9 @@ use crate::sys::sync as sys; /// storing the guard to a [`Cell`] within [`Drop::drop`] and accessing it /// outside, or vice versa, can affect poisoning status in an unexpected way. /// +/// - Foreign exceptions do not currently trigger poisoning even in absence of +/// other panics. +/// /// While this rarely happens in realistic code, `unsafe` code cannot rely on /// poisoning for soundness, since the behavior of poisoning can depend on /// outside context. Here's an example of **incorrect** use of poisoning: From 03986e640cc5a3ca70259484a6f271831c0bc241 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Fri, 25 Jul 2025 22:51:39 +0200 Subject: [PATCH 0140/1134] Get myself back on assignment rotation --- triagebot.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/triagebot.toml b/triagebot.toml index a62b6269a3bf..805baf2af6dd 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -54,7 +54,6 @@ contributing_url = "https://github.com/rust-lang/rust-clippy/blob/master/CONTRIB users_on_vacation = [ "matthiaskrgr", "Manishearth", - "samueltardieu", ] [assign.owners] From d852f7cb123cde2f0ed12ef09ef3bf58de391a4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joel=20Wejdenst=C3=A5l?= Date: Fri, 25 Jul 2025 21:21:42 +0200 Subject: [PATCH 0141/1134] Implement support for explicit tail calls in the MIR block builders and the LLVM codegen backend. --- messages.ftl | 2 ++ src/builder.rs | 15 +++++++++++++++ src/errors.rs | 4 ++++ 3 files changed, 21 insertions(+) diff --git a/messages.ftl b/messages.ftl index a70ac08f01ae..b9b77b7d18c6 100644 --- a/messages.ftl +++ b/messages.ftl @@ -4,3 +4,5 @@ codegen_gcc_unwinding_inline_asm = codegen_gcc_copy_bitcode = failed to copy bitcode to object file: {$err} codegen_gcc_lto_bitcode_from_rlib = failed to get bitcode from object file for LTO ({$gcc_err}) + +codegen_gcc_explicit_tail_calls_unsupported = explicit tail calls with the 'become' keyword are not implemented in the GCC backend diff --git a/src/builder.rs b/src/builder.rs index a4ec4bf8deac..4aee211e2efa 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -34,6 +34,7 @@ use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi}; use crate::common::{SignType, TypeReflection, type_is_pointer}; use crate::context::CodegenCx; +use crate::errors; use crate::intrinsic::llvm; use crate::type_of::LayoutGccExt; @@ -1742,6 +1743,20 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { call } + fn tail_call( + &mut self, + _llty: Self::Type, + _fn_attrs: Option<&CodegenFnAttrs>, + _fn_abi: &FnAbi<'tcx, Ty<'tcx>>, + _llfn: Self::Value, + _args: &[Self::Value], + _funclet: Option<&Self::Funclet>, + _instance: Option>, + ) { + // FIXME: implement support for explicit tail calls like rustc_codegen_llvm. + self.tcx.dcx().emit_fatal(errors::ExplicitTailCallsUnsupported); + } + fn zext(&mut self, value: RValue<'gcc>, dest_typ: Type<'gcc>) -> RValue<'gcc> { // FIXME(antoyo): this does not zero-extend. self.gcc_int_cast(value, dest_typ) diff --git a/src/errors.rs b/src/errors.rs index 0aa16bd88b43..b252c39c0c05 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -19,3 +19,7 @@ pub(crate) struct CopyBitcode { pub(crate) struct LtoBitcodeFromRlib { pub gcc_err: String, } + +#[derive(Diagnostic)] +#[diag(codegen_gcc_explicit_tail_calls_unsupported)] +pub(crate) struct ExplicitTailCallsUnsupported; From 3352dfc4a232fa6f38db3ea3ed465f56e6c8f85b Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Fri, 25 Jul 2025 17:27:08 -0700 Subject: [PATCH 0142/1134] Skip formatting for some compiler documentation code These examples feature Rust code that's presented primarily to illustrate how its compilation would be handled, and these examples are formatted to highlight those aspects in ways that rustfmt wouldn't preserve. Turn formatting off in those examples. (Doc code isn't formatted yet, but this will make it easier to enable doc code formatting in the future.) --- compiler/rustc_borrowck/src/region_infer/mod.rs | 2 +- compiler/rustc_hir/src/def.rs | 2 +- compiler/rustc_mir_dataflow/src/impls/initialized.rs | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index 5f1b655c6b60..d3bf9f0ec4a6 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -417,7 +417,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { /// minimum values. /// /// For example: - /// ``` + /// ```ignore (illustrative) /// fn foo<'a, 'b>( /* ... */ ) where 'a: 'b { /* ... */ } /// ``` /// would initialize two variables like so: diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index ca57c4f31641..5024c85e2a8a 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -356,7 +356,7 @@ impl DefKind { /// For example, everything prefixed with `/* Res */` in this example has /// an associated `Res`: /// -/// ``` +/// ```ignore (illustrative) /// fn str_to_string(s: & /* Res */ str) -> /* Res */ String { /// /* Res */ String::from(/* Res */ s) /// } diff --git a/compiler/rustc_mir_dataflow/src/impls/initialized.rs b/compiler/rustc_mir_dataflow/src/impls/initialized.rs index 085757f0fb6e..ebf43300f98a 100644 --- a/compiler/rustc_mir_dataflow/src/impls/initialized.rs +++ b/compiler/rustc_mir_dataflow/src/impls/initialized.rs @@ -108,6 +108,7 @@ impl<'tcx> MaybePlacesSwitchIntData<'tcx> { /// /// ```rust /// struct S; +/// #[rustfmt::skip] /// fn foo(pred: bool) { // maybe-init: /// // {} /// let a = S; let mut b = S; let c; let d; // {a, b} @@ -197,6 +198,7 @@ impl<'a, 'tcx> HasMoveData<'tcx> for MaybeInitializedPlaces<'a, 'tcx> { /// /// ```rust /// struct S; +/// #[rustfmt::skip] /// fn foo(pred: bool) { // maybe-uninit: /// // {a, b, c, d} /// let a = S; let mut b = S; let c; let d; // { c, d} @@ -289,6 +291,7 @@ impl<'tcx> HasMoveData<'tcx> for MaybeUninitializedPlaces<'_, 'tcx> { /// /// ```rust /// struct S; +/// #[rustfmt::skip] /// fn foo(pred: bool) { // ever-init: /// // { } /// let a = S; let mut b = S; let c; let d; // {a, b } From 715088094c2e2ef31158b4767ceacfba62c8e6ef Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Fri, 25 Jul 2025 17:35:47 -0700 Subject: [PATCH 0143/1134] Improve and regularize comment placement in doc code Because doc code does not get automatically formatted, some doc code has creative placements of comments that automatic formatting can't handle. Reformat those comments to make the resulting code support standard Rust formatting without breaking; this is generally an improvement to readability as well. Some comments are not indented to the prevailing indent, and are instead aligned under some bit of code. Indent them to the prevailing indent, and put spaces *inside* the comments to align them with code. Some comments span several lines of code (which aren't the line the comment is about) and expect alignment. Reformat them into one comment not broken up by unrelated intervening code. Some comments are placed on the same line as an opening brace, placing them effectively inside the subsequent block, such that formatting would typically format them like a line of that block. Move those comments to attach them to what they apply to. Some comments are placed on the same line as a one-line braced block, effectively attaching them to the closing brace, even though they're about the code inside the block. Reformat to make sure the comment will stay on the same line as the code it's commenting. --- compiler/rustc_hir/src/def.rs | 2 +- .../src/check/compare_impl_item.rs | 2 +- compiler/rustc_hir_typeck/src/upvar.rs | 4 +--- .../src/infer/outlives/obligations.rs | 2 +- compiler/rustc_middle/src/hir/map.rs | 12 +++++++---- compiler/rustc_middle/src/mir/mod.rs | 3 ++- .../src/builder/expr/as_operand.rs | 4 +++- compiler/rustc_span/src/hygiene.rs | 4 +++- compiler/rustc_thread_pool/src/scope/mod.rs | 6 +++--- library/alloc/src/vec/mod.rs | 2 +- library/core/src/cell.rs | 6 +++--- library/core/src/hint.rs | 2 -- library/core/src/iter/mod.rs | 6 ++++-- library/core/src/macros/mod.rs | 10 +++++++-- library/core/src/marker.rs | 3 +-- library/core/src/mem/maybe_uninit.rs | 21 +++++++++---------- library/core/src/result.rs | 2 +- 17 files changed, 51 insertions(+), 40 deletions(-) diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index 5024c85e2a8a..0ef70a6ecaa8 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -417,7 +417,7 @@ pub enum Res { /// } /// /// impl Foo for Bar { - /// fn foo() -> Box { // SelfTyAlias + /// fn foo() -> Box { /// let _: Self; // SelfTyAlias /// /// todo!() diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index e24426f9fedc..bd9125363fc4 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -425,7 +425,7 @@ impl<'tcx> TypeFolder> for RemapLateParam<'tcx> { /// /// trait Foo { /// fn bar() -> impl Deref; -/// // ^- RPITIT #1 ^- RPITIT #2 +/// // ^- RPITIT #1 ^- RPITIT #2 /// } /// /// impl Foo for () { diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index be774106abf8..7ebdba9f80aa 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -2391,13 +2391,11 @@ fn migration_suggestion_for_2229( /// let mut p = Point { x: 10, y: 10 }; /// /// let c = || { -/// p.x += 10; -/// // ^ E1 ^ +/// p.x += 10; // E1 /// // ... /// // More code /// // ... /// p.x += 10; // E2 -/// // ^ E2 ^ /// }; /// ``` /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow), diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index a8520c0e71dd..d6243d727aca 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -36,7 +36,7 @@ //! fn bar(a: T, b: impl for<'a> Fn(&'a T)) {} //! fn foo(x: T) { //! bar(x, |y| { /* ... */}) -//! // ^ closure arg +//! // ^ closure arg //! } //! ``` //! diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index 42a1e7377f4b..1b1735ab2bf5 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -533,8 +533,10 @@ impl<'tcx> TyCtxt<'tcx> { /// ``` /// fn foo(x: usize) -> bool { /// if x == 1 { - /// true // If `get_fn_id_for_return_block` gets passed the `id` corresponding - /// } else { // to this, it will return `foo`'s `HirId`. + /// // If `get_fn_id_for_return_block` gets passed the `id` corresponding to this, it + /// // will return `foo`'s `HirId`. + /// true + /// } else { /// false /// } /// } @@ -543,8 +545,10 @@ impl<'tcx> TyCtxt<'tcx> { /// ```compile_fail,E0308 /// fn foo(x: usize) -> bool { /// loop { - /// true // If `get_fn_id_for_return_block` gets passed the `id` corresponding - /// } // to this, it will return `None`. + /// // If `get_fn_id_for_return_block` gets passed the `id` corresponding to this, it + /// // will return `None`. + /// true + /// } /// false /// } /// ``` diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index e819aa2d8f81..c55c7fc6002c 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -1017,7 +1017,8 @@ pub struct LocalDecl<'tcx> { /// ``` /// fn foo(x: &str) { /// #[allow(unused_mut)] - /// let mut x: u32 = { // <- one unused mut + /// let mut x: u32 = { + /// //^ one unused mut /// let mut y: u32 = x.parse().unwrap(); /// y + 2 /// }; diff --git a/compiler/rustc_mir_build/src/builder/expr/as_operand.rs b/compiler/rustc_mir_build/src/builder/expr/as_operand.rs index 982e7aa8246b..6a4222239904 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_operand.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_operand.rs @@ -57,7 +57,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// ``` /// #![feature(unsized_fn_params)] /// # use core::fmt::Debug; - /// fn foo(_p: dyn Debug) { /* ... */ } + /// fn foo(_p: dyn Debug) { + /// /* ... */ + /// } /// /// fn bar(box_p: Box) { foo(*box_p); } /// ``` diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index c3080875da80..6ea774eeccaa 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -756,7 +756,9 @@ impl SyntaxContext { /// /// ```rust /// #![feature(decl_macro)] - /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty. + /// mod foo { + /// pub fn f() {} // `f`'s `SyntaxContext` is empty. + /// } /// m!(f); /// macro m($f:ident) { /// mod bar { diff --git a/compiler/rustc_thread_pool/src/scope/mod.rs b/compiler/rustc_thread_pool/src/scope/mod.rs index 382303839650..677009a9bc3d 100644 --- a/compiler/rustc_thread_pool/src/scope/mod.rs +++ b/compiler/rustc_thread_pool/src/scope/mod.rs @@ -501,9 +501,9 @@ impl<'scope> Scope<'scope> { /// let mut value_c = None; /// rayon::scope(|s| { /// s.spawn(|s1| { - /// // ^ this is the same scope as `s`; this handle `s1` - /// // is intended for use by the spawned task, - /// // since scope handles cannot cross thread boundaries. + /// // ^ this is the same scope as `s`; this handle `s1` + /// // is intended for use by the spawned task, + /// // since scope handles cannot cross thread boundaries. /// /// value_a = Some(22); /// diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 9856e9c18ec6..387adab70c68 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -3778,8 +3778,8 @@ impl Vec { /// while i < vec.len() - end_items { /// if some_predicate(&mut vec[i]) { /// let val = vec.remove(i); - /// # extracted.push(val); /// // your code here + /// # extracted.push(val); /// } else { /// i += 1; /// } diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index d6d1bf2effae..d67408cae1b9 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -2068,9 +2068,9 @@ impl fmt::Display for RefMut<'_, T> { /// implies exclusive access to its `T`: /// /// ```rust -/// #![forbid(unsafe_code)] // with exclusive accesses, -/// // `UnsafeCell` is a transparent no-op wrapper, -/// // so no need for `unsafe` here. +/// #![forbid(unsafe_code)] +/// // with exclusive accesses, `UnsafeCell` is a transparent no-op wrapper, so no need for +/// // `unsafe` here. /// use std::cell::UnsafeCell; /// /// let mut x: UnsafeCell = 42.into(); diff --git a/library/core/src/hint.rs b/library/core/src/hint.rs index 696d323c66d2..c72eeb9a9c97 100644 --- a/library/core/src/hint.rs +++ b/library/core/src/hint.rs @@ -649,8 +649,6 @@ pub const fn must_use(value: T) -> T { /// } /// } /// ``` -/// -/// #[unstable(feature = "likely_unlikely", issue = "136873")] #[inline(always)] pub const fn likely(b: bool) -> bool { diff --git a/library/core/src/iter/mod.rs b/library/core/src/iter/mod.rs index 7ca41d224a0a..56ca1305b601 100644 --- a/library/core/src/iter/mod.rs +++ b/library/core/src/iter/mod.rs @@ -233,10 +233,12 @@ //! //! ``` //! let mut values = vec![41]; -//! for x in &mut values { // same as `values.iter_mut()` +//! for x in &mut values { +//! // ^ same as `values.iter_mut()` //! *x += 1; //! } -//! for x in &values { // same as `values.iter()` +//! for x in &values { +//! // ^ same as `values.iter()` //! assert_eq!(*x, 42); //! } //! assert_eq!(values.len(), 1); diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 8ac6ce2242d4..ae75d166d0cf 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -271,7 +271,10 @@ pub macro cfg_select($($tt:tt)*) { /// // expression given. /// debug_assert!(true); /// -/// fn some_expensive_computation() -> bool { true } // a very simple function +/// fn some_expensive_computation() -> bool { +/// // Some expensive computation here +/// true +/// } /// debug_assert!(some_expensive_computation()); /// /// // assert with a custom message @@ -1545,7 +1548,10 @@ pub(crate) mod builtin { /// // expression given. /// assert!(true); /// - /// fn some_computation() -> bool { true } // a very simple function + /// fn some_computation() -> bool { + /// // Some expensive computation here + /// true + /// } /// /// assert!(some_computation()); /// diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 45277a1c82d3..ba00ee17b652 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -138,8 +138,7 @@ unsafe impl Send for &T {} /// impl Bar for Impl { } /// /// let x: &dyn Foo = &Impl; // OK -/// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot -/// // be made into an object +/// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot be made into an object /// ``` /// /// [trait object]: ../../book/ch17-02-trait-objects.html diff --git a/library/core/src/mem/maybe_uninit.rs b/library/core/src/mem/maybe_uninit.rs index 34d8370da7ec..c160360cfacf 100644 --- a/library/core/src/mem/maybe_uninit.rs +++ b/library/core/src/mem/maybe_uninit.rs @@ -773,8 +773,7 @@ impl MaybeUninit { /// // Initialize the `MaybeUninit` using `Cell::set`: /// unsafe { /// b.assume_init_ref().set(true); - /// // ^^^^^^^^^^^^^^^ - /// // Reference to an uninitialized `Cell`: UB! + /// //^^^^^^^^^^^^^^^ Reference to an uninitialized `Cell`: UB! /// } /// ``` #[stable(feature = "maybe_uninit_ref", since = "1.55.0")] @@ -864,9 +863,9 @@ impl MaybeUninit { /// { /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit(); /// reader.read_exact(unsafe { buffer.assume_init_mut() })?; - /// // ^^^^^^^^^^^^^^^^^^^^^^^^ - /// // (mutable) reference to uninitialized memory! - /// // This is undefined behavior. + /// // ^^^^^^^^^^^^^^^^^^^^^^^^ + /// // (mutable) reference to uninitialized memory! + /// // This is undefined behavior. /// Ok(unsafe { buffer.assume_init() }) /// } /// ``` @@ -884,13 +883,13 @@ impl MaybeUninit { /// let foo: Foo = unsafe { /// let mut foo = MaybeUninit::::uninit(); /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337); - /// // ^^^^^^^^^^^^^^^^^^^^^ - /// // (mutable) reference to uninitialized memory! - /// // This is undefined behavior. + /// // ^^^^^^^^^^^^^^^^^^^^^ + /// // (mutable) reference to uninitialized memory! + /// // This is undefined behavior. /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42); - /// // ^^^^^^^^^^^^^^^^^^^^^ - /// // (mutable) reference to uninitialized memory! - /// // This is undefined behavior. + /// // ^^^^^^^^^^^^^^^^^^^^^ + /// // (mutable) reference to uninitialized memory! + /// // This is undefined behavior. /// foo.assume_init() /// }; /// ``` diff --git a/library/core/src/result.rs b/library/core/src/result.rs index f65257ff59b9..4db7e5021edb 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1544,7 +1544,7 @@ impl Result { /// /// ```no_run /// let x: Result = Err("emergency failure"); - /// unsafe { x.unwrap_unchecked(); } // Undefined behavior! + /// unsafe { x.unwrap_unchecked() }; // Undefined behavior! /// ``` #[inline] #[track_caller] From b6c54a97b3ce019b48a7e98f952532b9d1670834 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Fri, 25 Jul 2025 17:52:13 -0700 Subject: [PATCH 0144/1134] Avoid placing `// FIXME` comments inside doc code blocks This leads tools like rustfmt to get confused, because the doc code block effectively spans two doc comments. As a result, the tools think the first code block is unclosed, and the subsequent terminator opens a new block. Move the FIXME comments outside the doc code blocks, instead. --- library/alloc/src/string.rs | 4 ++-- library/alloc/src/vec/mod.rs | 8 ++++---- library/core/src/primitive_docs.rs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index a189c00a6b61..3bcc9920c99f 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -265,12 +265,12 @@ use crate::vec::{self, Vec}; /// You can look at these with the [`as_ptr`], [`len`], and [`capacity`] /// methods: /// +// FIXME Update this when vec_into_raw_parts is stabilized /// ``` /// use std::mem; /// /// let story = String::from("Once upon a time..."); /// -// FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent automatically dropping the String's data /// let mut story = mem::ManuallyDrop::new(story); /// @@ -970,13 +970,13 @@ impl String { /// /// # Examples /// + // FIXME Update this when vec_into_raw_parts is stabilized /// ``` /// use std::mem; /// /// unsafe { /// let s = String::from("hello"); /// - // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent automatically dropping the String's data /// let mut s = mem::ManuallyDrop::new(s); /// diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 387adab70c68..3a182fe341f3 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -566,13 +566,13 @@ impl Vec { /// /// # Examples /// + // FIXME Update this when vec_into_raw_parts is stabilized /// ``` /// use std::ptr; /// use std::mem; /// /// let v = vec![1, 2, 3]; /// - // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent running `v`'s destructor so we are in complete control /// // of the allocation. /// let mut v = mem::ManuallyDrop::new(v); @@ -674,6 +674,7 @@ impl Vec { /// /// # Examples /// + // FIXME Update this when vec_into_raw_parts is stabilized /// ``` /// #![feature(box_vec_non_null)] /// @@ -682,7 +683,6 @@ impl Vec { /// /// let v = vec![1, 2, 3]; /// - // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent running `v`'s destructor so we are in complete control /// // of the allocation. /// let mut v = mem::ManuallyDrop::new(v); @@ -994,6 +994,7 @@ impl Vec { /// /// # Examples /// + // FIXME Update this when vec_into_raw_parts is stabilized /// ``` /// #![feature(allocator_api)] /// @@ -1007,7 +1008,6 @@ impl Vec { /// v.push(2); /// v.push(3); /// - // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent running `v`'s destructor so we are in complete control /// // of the allocation. /// let mut v = mem::ManuallyDrop::new(v); @@ -1114,6 +1114,7 @@ impl Vec { /// /// # Examples /// + // FIXME Update this when vec_into_raw_parts is stabilized /// ``` /// #![feature(allocator_api, box_vec_non_null)] /// @@ -1127,7 +1128,6 @@ impl Vec { /// v.push(2); /// v.push(3); /// - // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent running `v`'s destructor so we are in complete control /// // of the allocation. /// let mut v = mem::ManuallyDrop::new(v); diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 9a1ba7d1728c..1c824e336bed 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -271,6 +271,7 @@ mod prim_bool {} /// When the compiler sees a value of type `!` in a [coercion site], it implicitly inserts a /// coercion to allow the type checker to infer any type: /// +// FIXME: use `core::convert::absurd` here instead, once it's merged /// ```rust,ignore (illustrative-and-has-placeholders) /// // this /// let x: u8 = panic!(); @@ -281,7 +282,6 @@ mod prim_bool {} /// // where absurd is a function with the following signature /// // (it's sound, because `!` always marks unreachable code): /// fn absurd(_: !) -> T { ... } -// FIXME: use `core::convert::absurd` here instead, once it's merged /// ``` /// /// This can lead to compilation errors if the type cannot be inferred: From 56c5b1df941664567d3c1f820d5861fdb25a3ca4 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Fri, 25 Jul 2025 17:53:58 -0700 Subject: [PATCH 0145/1134] Add parentheses around expression arguments to `..` This makes it easier for humans to parse, and improves the result of potential future automatic formatting. --- library/core/src/iter/traits/iterator.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 10f9d464f7d7..29313867ff26 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -807,7 +807,7 @@ pub trait Iterator { /// might be preferable to keep a functional style with longer iterators: /// /// ``` - /// (0..5).flat_map(|x| x * 100 .. x * 110) + /// (0..5).flat_map(|x| (x * 100)..(x * 110)) /// .enumerate() /// .filter(|&(i, x)| (i + x) % 3 == 0) /// .for_each(|(i, x)| println!("{i}:{x}")); From 1e2d58798fab4aa6275acf3746e1aec5340fc97f Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Fri, 25 Jul 2025 17:55:45 -0700 Subject: [PATCH 0146/1134] Avoid making the start of a doc code block conditional Placing the opening triple-backquote inside a `cfg_attr` makes many tools confused, including syntax highlighters (e.g. vim's) and rustfmt. Instead, use a `cfg` inside the doc code block. --- library/std/src/path.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/library/std/src/path.rs b/library/std/src/path.rs index d9c34d4fa045..055e7f814800 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -3259,8 +3259,8 @@ impl Path { /// /// # Examples /// - #[cfg_attr(unix, doc = "```no_run")] - #[cfg_attr(not(unix), doc = "```ignore")] + /// ```rust,no_run + /// # #[cfg(unix)] { /// use std::path::Path; /// use std::os::unix::fs::symlink; /// @@ -3268,6 +3268,7 @@ impl Path { /// symlink("/origin_does_not_exist/", link_path).unwrap(); /// assert_eq!(link_path.is_symlink(), true); /// assert_eq!(link_path.exists(), false); + /// # } /// ``` /// /// # See Also From e910c0e7e6338bdc4c63b584bfff3f2abf1c3896 Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Fri, 28 Mar 2025 12:27:04 -0400 Subject: [PATCH 0147/1134] Deprecate `string_to_string` --- clippy_lints/src/declared_lints.rs | 1 - clippy_lints/src/deprecated_lints.rs | 2 + clippy_lints/src/lib.rs | 1 - clippy_lints/src/strings.rs | 109 ------------------------ tests/ui/deprecated.rs | 1 + tests/ui/deprecated.stderr | 18 ++-- tests/ui/string_to_string.fixed | 21 ----- tests/ui/string_to_string.rs | 21 ----- tests/ui/string_to_string.stderr | 23 ----- tests/ui/string_to_string_in_map.fixed | 20 ----- tests/ui/string_to_string_in_map.rs | 20 ----- tests/ui/string_to_string_in_map.stderr | 38 --------- 12 files changed, 15 insertions(+), 260 deletions(-) delete mode 100644 tests/ui/string_to_string.fixed delete mode 100644 tests/ui/string_to_string.rs delete mode 100644 tests/ui/string_to_string.stderr delete mode 100644 tests/ui/string_to_string_in_map.fixed delete mode 100644 tests/ui/string_to_string_in_map.rs delete mode 100644 tests/ui/string_to_string_in_map.stderr diff --git a/clippy_lints/src/declared_lints.rs b/clippy_lints/src/declared_lints.rs index 5fcb851dfebc..1b0e87ffa710 100644 --- a/clippy_lints/src/declared_lints.rs +++ b/clippy_lints/src/declared_lints.rs @@ -683,7 +683,6 @@ pub static LINTS: &[&crate::LintInfo] = &[ crate::strings::STRING_FROM_UTF8_AS_BYTES_INFO, crate::strings::STRING_LIT_AS_BYTES_INFO, crate::strings::STRING_SLICE_INFO, - crate::strings::STRING_TO_STRING_INFO, crate::strings::STR_TO_STRING_INFO, crate::strings::TRIM_SPLIT_WHITESPACE_INFO, crate::strlen_on_c_strings::STRLEN_ON_C_STRINGS_INFO, diff --git a/clippy_lints/src/deprecated_lints.rs b/clippy_lints/src/deprecated_lints.rs index 5204f73ea0a9..88aebc3e6a16 100644 --- a/clippy_lints/src/deprecated_lints.rs +++ b/clippy_lints/src/deprecated_lints.rs @@ -34,6 +34,8 @@ declare_with_version! { DEPRECATED(DEPRECATED_VERSION) = [ ("clippy::replace_consts", "`min_value` and `max_value` are now deprecated"), #[clippy::version = "pre 1.29.0"] ("clippy::should_assert_eq", "`assert!(a == b)` can now print the values the same way `assert_eq!(a, b) can"), + #[clippy::version = "1.90.0"] + ("clippy::string_to_string", "`clippy:implicit_clone` covers those cases"), #[clippy::version = "pre 1.29.0"] ("clippy::unsafe_vector_initialization", "the suggested alternative could be substantially slower"), #[clippy::version = "pre 1.29.0"] diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index ca1a0b357108..cd9917e3ac88 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -782,7 +782,6 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) { store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86IntelSyntax)); store.register_late_pass(|_| Box::new(empty_drop::EmptyDrop)); store.register_late_pass(|_| Box::new(strings::StrToString)); - store.register_late_pass(|_| Box::new(strings::StringToString)); store.register_late_pass(|_| Box::new(zero_sized_map_values::ZeroSizedMapValues)); store.register_late_pass(|_| Box::::default()); store.register_late_pass(|_| Box::new(redundant_slicing::RedundantSlicing)); diff --git a/clippy_lints/src/strings.rs b/clippy_lints/src/strings.rs index 9fcef84eeb34..d520df95ae89 100644 --- a/clippy_lints/src/strings.rs +++ b/clippy_lints/src/strings.rs @@ -13,8 +13,6 @@ use rustc_middle::ty; use rustc_session::declare_lint_pass; use rustc_span::source_map::Spanned; -use std::ops::ControlFlow; - declare_clippy_lint! { /// ### What it does /// Checks for string appends of the form `x = x + y` (without @@ -411,113 +409,6 @@ impl<'tcx> LateLintPass<'tcx> for StrToString { } } -declare_clippy_lint! { - /// ### What it does - /// This lint checks for `.to_string()` method calls on values of type `String`. - /// - /// ### Why restrict this? - /// The `to_string` method is also used on other types to convert them to a string. - /// When called on a `String` it only clones the `String`, which can be more specifically - /// expressed with `.clone()`. - /// - /// ### Example - /// ```no_run - /// let msg = String::from("Hello World"); - /// let _ = msg.to_string(); - /// ``` - /// Use instead: - /// ```no_run - /// let msg = String::from("Hello World"); - /// let _ = msg.clone(); - /// ``` - #[clippy::version = "pre 1.29.0"] - pub STRING_TO_STRING, - restriction, - "using `to_string()` on a `String`, which should be `clone()`" -} - -declare_lint_pass!(StringToString => [STRING_TO_STRING]); - -fn is_parent_map_like(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { - if let Some(parent_expr) = get_parent_expr(cx, expr) - && let ExprKind::MethodCall(name, _, _, parent_span) = parent_expr.kind - && name.ident.name == sym::map - && let Some(caller_def_id) = cx.typeck_results().type_dependent_def_id(parent_expr.hir_id) - && (clippy_utils::is_diag_item_method(cx, caller_def_id, sym::Result) - || clippy_utils::is_diag_item_method(cx, caller_def_id, sym::Option) - || clippy_utils::is_diag_trait_item(cx, caller_def_id, sym::Iterator)) - { - Some(parent_span) - } else { - None - } -} - -fn is_called_from_map_like(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { - // Look for a closure as parent of `expr`, discarding simple blocks - let parent_closure = cx - .tcx - .hir_parent_iter(expr.hir_id) - .try_fold(expr.hir_id, |child_hir_id, (_, node)| match node { - // Check that the child expression is the only expression in the block - Node::Block(block) if block.stmts.is_empty() && block.expr.map(|e| e.hir_id) == Some(child_hir_id) => { - ControlFlow::Continue(block.hir_id) - }, - Node::Expr(expr) if matches!(expr.kind, ExprKind::Block(..)) => ControlFlow::Continue(expr.hir_id), - Node::Expr(expr) if matches!(expr.kind, ExprKind::Closure(_)) => ControlFlow::Break(Some(expr)), - _ => ControlFlow::Break(None), - }) - .break_value()?; - is_parent_map_like(cx, parent_closure?) -} - -fn suggest_cloned_string_to_string(cx: &LateContext<'_>, span: rustc_span::Span) { - span_lint_and_sugg( - cx, - STRING_TO_STRING, - span, - "`to_string()` called on a `String`", - "try", - "cloned()".to_string(), - Applicability::MachineApplicable, - ); -} - -impl<'tcx> LateLintPass<'tcx> for StringToString { - fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) { - if expr.span.from_expansion() { - return; - } - - match &expr.kind { - ExprKind::MethodCall(path, self_arg, [], _) => { - if path.ident.name == sym::to_string - && let ty = cx.typeck_results().expr_ty(self_arg) - && is_type_lang_item(cx, ty.peel_refs(), LangItem::String) - && let Some(parent_span) = is_called_from_map_like(cx, expr) - { - suggest_cloned_string_to_string(cx, parent_span); - } - }, - ExprKind::Path(QPath::TypeRelative(ty, segment)) => { - if segment.ident.name == sym::to_string - && let rustc_hir::TyKind::Path(QPath::Resolved(_, path)) = ty.peel_refs().kind - && let rustc_hir::def::Res::Def(_, def_id) = path.res - && cx - .tcx - .lang_items() - .get(LangItem::String) - .is_some_and(|lang_id| lang_id == def_id) - && let Some(parent_span) = is_parent_map_like(cx, expr) - { - suggest_cloned_string_to_string(cx, parent_span); - } - }, - _ => {}, - } - } -} - declare_clippy_lint! { /// ### What it does /// Warns about calling `str::trim` (or variants) before `str::split_whitespace`. diff --git a/tests/ui/deprecated.rs b/tests/ui/deprecated.rs index 6b69bdd29cea..9743a83fb934 100644 --- a/tests/ui/deprecated.rs +++ b/tests/ui/deprecated.rs @@ -12,6 +12,7 @@ #![warn(clippy::regex_macro)] //~ ERROR: lint `clippy::regex_macro` #![warn(clippy::replace_consts)] //~ ERROR: lint `clippy::replace_consts` #![warn(clippy::should_assert_eq)] //~ ERROR: lint `clippy::should_assert_eq` +#![warn(clippy::string_to_string)] //~ ERROR: lint `clippy::string_to_string` #![warn(clippy::unsafe_vector_initialization)] //~ ERROR: lint `clippy::unsafe_vector_initialization` #![warn(clippy::unstable_as_mut_slice)] //~ ERROR: lint `clippy::unstable_as_mut_slice` #![warn(clippy::unstable_as_slice)] //~ ERROR: lint `clippy::unstable_as_slice` diff --git a/tests/ui/deprecated.stderr b/tests/ui/deprecated.stderr index 07e59d33d608..cd225da611c4 100644 --- a/tests/ui/deprecated.stderr +++ b/tests/ui/deprecated.stderr @@ -61,35 +61,41 @@ error: lint `clippy::should_assert_eq` has been removed: `assert!(a == b)` can n LL | #![warn(clippy::should_assert_eq)] | ^^^^^^^^^^^^^^^^^^^^^^^^ -error: lint `clippy::unsafe_vector_initialization` has been removed: the suggested alternative could be substantially slower +error: lint `clippy::string_to_string` has been removed: `clippy:implicit_clone` covers those cases --> tests/ui/deprecated.rs:15:9 | +LL | #![warn(clippy::string_to_string)] + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +error: lint `clippy::unsafe_vector_initialization` has been removed: the suggested alternative could be substantially slower + --> tests/ui/deprecated.rs:16:9 + | LL | #![warn(clippy::unsafe_vector_initialization)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: lint `clippy::unstable_as_mut_slice` has been removed: `Vec::as_mut_slice` is now stable - --> tests/ui/deprecated.rs:16:9 + --> tests/ui/deprecated.rs:17:9 | LL | #![warn(clippy::unstable_as_mut_slice)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: lint `clippy::unstable_as_slice` has been removed: `Vec::as_slice` is now stable - --> tests/ui/deprecated.rs:17:9 + --> tests/ui/deprecated.rs:18:9 | LL | #![warn(clippy::unstable_as_slice)] | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: lint `clippy::unused_collect` has been removed: `Iterator::collect` is now marked as `#[must_use]` - --> tests/ui/deprecated.rs:18:9 + --> tests/ui/deprecated.rs:19:9 | LL | #![warn(clippy::unused_collect)] | ^^^^^^^^^^^^^^^^^^^^^^ error: lint `clippy::wrong_pub_self_convention` has been removed: `clippy::wrong_self_convention` now covers this case via the `avoid-breaking-exported-api` config - --> tests/ui/deprecated.rs:19:9 + --> tests/ui/deprecated.rs:20:9 | LL | #![warn(clippy::wrong_pub_self_convention)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 15 previous errors +error: aborting due to 16 previous errors diff --git a/tests/ui/string_to_string.fixed b/tests/ui/string_to_string.fixed deleted file mode 100644 index 751f451cb685..000000000000 --- a/tests/ui/string_to_string.fixed +++ /dev/null @@ -1,21 +0,0 @@ -#![warn(clippy::implicit_clone, clippy::string_to_string)] -#![allow(clippy::redundant_clone, clippy::unnecessary_literal_unwrap)] - -fn main() { - let mut message = String::from("Hello"); - let mut v = message.clone(); - //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type - - let variable1 = String::new(); - let v = &variable1; - let variable2 = Some(v); - let _ = variable2.map(|x| { - println!(); - x.clone() - //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type - }); - - let x = Some(String::new()); - let _ = x.unwrap_or_else(|| v.clone()); - //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type -} diff --git a/tests/ui/string_to_string.rs b/tests/ui/string_to_string.rs deleted file mode 100644 index d519677d59ec..000000000000 --- a/tests/ui/string_to_string.rs +++ /dev/null @@ -1,21 +0,0 @@ -#![warn(clippy::implicit_clone, clippy::string_to_string)] -#![allow(clippy::redundant_clone, clippy::unnecessary_literal_unwrap)] - -fn main() { - let mut message = String::from("Hello"); - let mut v = message.to_string(); - //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type - - let variable1 = String::new(); - let v = &variable1; - let variable2 = Some(v); - let _ = variable2.map(|x| { - println!(); - x.to_string() - //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type - }); - - let x = Some(String::new()); - let _ = x.unwrap_or_else(|| v.to_string()); - //~^ ERROR: implicitly cloning a `String` by calling `to_string` on its dereferenced type -} diff --git a/tests/ui/string_to_string.stderr b/tests/ui/string_to_string.stderr deleted file mode 100644 index 220fe3170c6e..000000000000 --- a/tests/ui/string_to_string.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error: implicitly cloning a `String` by calling `to_string` on its dereferenced type - --> tests/ui/string_to_string.rs:6:17 - | -LL | let mut v = message.to_string(); - | ^^^^^^^^^^^^^^^^^^^ help: consider using: `message.clone()` - | - = note: `-D clippy::implicit-clone` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::implicit_clone)]` - -error: implicitly cloning a `String` by calling `to_string` on its dereferenced type - --> tests/ui/string_to_string.rs:14:9 - | -LL | x.to_string() - | ^^^^^^^^^^^^^ help: consider using: `x.clone()` - -error: implicitly cloning a `String` by calling `to_string` on its dereferenced type - --> tests/ui/string_to_string.rs:19:33 - | -LL | let _ = x.unwrap_or_else(|| v.to_string()); - | ^^^^^^^^^^^^^ help: consider using: `v.clone()` - -error: aborting due to 3 previous errors - diff --git a/tests/ui/string_to_string_in_map.fixed b/tests/ui/string_to_string_in_map.fixed deleted file mode 100644 index efc085539f15..000000000000 --- a/tests/ui/string_to_string_in_map.fixed +++ /dev/null @@ -1,20 +0,0 @@ -#![deny(clippy::string_to_string)] -#![allow(clippy::unnecessary_literal_unwrap, clippy::useless_vec, clippy::iter_cloned_collect)] - -fn main() { - let variable1 = String::new(); - let v = &variable1; - let variable2 = Some(v); - let _ = variable2.cloned(); - //~^ string_to_string - let _ = variable2.cloned(); - //~^ string_to_string - #[rustfmt::skip] - let _ = variable2.cloned(); - //~^ string_to_string - - let _ = vec![String::new()].iter().cloned().collect::>(); - //~^ string_to_string - let _ = vec![String::new()].iter().cloned().collect::>(); - //~^ string_to_string -} diff --git a/tests/ui/string_to_string_in_map.rs b/tests/ui/string_to_string_in_map.rs deleted file mode 100644 index 5bf1d7ba5a2e..000000000000 --- a/tests/ui/string_to_string_in_map.rs +++ /dev/null @@ -1,20 +0,0 @@ -#![deny(clippy::string_to_string)] -#![allow(clippy::unnecessary_literal_unwrap, clippy::useless_vec, clippy::iter_cloned_collect)] - -fn main() { - let variable1 = String::new(); - let v = &variable1; - let variable2 = Some(v); - let _ = variable2.map(String::to_string); - //~^ string_to_string - let _ = variable2.map(|x| x.to_string()); - //~^ string_to_string - #[rustfmt::skip] - let _ = variable2.map(|x| { x.to_string() }); - //~^ string_to_string - - let _ = vec![String::new()].iter().map(String::to_string).collect::>(); - //~^ string_to_string - let _ = vec![String::new()].iter().map(|x| x.to_string()).collect::>(); - //~^ string_to_string -} diff --git a/tests/ui/string_to_string_in_map.stderr b/tests/ui/string_to_string_in_map.stderr deleted file mode 100644 index 35aeed656eed..000000000000 --- a/tests/ui/string_to_string_in_map.stderr +++ /dev/null @@ -1,38 +0,0 @@ -error: `to_string()` called on a `String` - --> tests/ui/string_to_string_in_map.rs:8:23 - | -LL | let _ = variable2.map(String::to_string); - | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `cloned()` - | -note: the lint level is defined here - --> tests/ui/string_to_string_in_map.rs:1:9 - | -LL | #![deny(clippy::string_to_string)] - | ^^^^^^^^^^^^^^^^^^^^^^^^ - -error: `to_string()` called on a `String` - --> tests/ui/string_to_string_in_map.rs:10:23 - | -LL | let _ = variable2.map(|x| x.to_string()); - | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `cloned()` - -error: `to_string()` called on a `String` - --> tests/ui/string_to_string_in_map.rs:13:23 - | -LL | let _ = variable2.map(|x| { x.to_string() }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `cloned()` - -error: `to_string()` called on a `String` - --> tests/ui/string_to_string_in_map.rs:16:40 - | -LL | let _ = vec![String::new()].iter().map(String::to_string).collect::>(); - | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `cloned()` - -error: `to_string()` called on a `String` - --> tests/ui/string_to_string_in_map.rs:18:40 - | -LL | let _ = vec![String::new()].iter().map(|x| x.to_string()).collect::>(); - | ^^^^^^^^^^^^^^^^^^^^^^ help: try: `cloned()` - -error: aborting due to 5 previous errors - From 534b1355efe3fc0dc962634773b0f6b1474bad13 Mon Sep 17 00:00:00 2001 From: Martin Nordholts Date: Sat, 26 Jul 2025 11:41:25 +0200 Subject: [PATCH 0148/1134] tests: Add test for basic line-by-line stepping in a debugger Let's wait with lldb testing until the test works properly with gdb. --- tests/debuginfo/basic-stepping.rs | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 tests/debuginfo/basic-stepping.rs diff --git a/tests/debuginfo/basic-stepping.rs b/tests/debuginfo/basic-stepping.rs new file mode 100644 index 000000000000..6e1344d22a50 --- /dev/null +++ b/tests/debuginfo/basic-stepping.rs @@ -0,0 +1,47 @@ +//! Test that stepping through a simple program with a debugger one line at a +//! time works intuitively, e.g. that `next` takes you to the next source line. +//! Regression test for . + +//@ ignore-aarch64: Doesn't work yet. +//@ compile-flags: -g + +// gdb-command: run +// FIXME(#97083): Should we be able to break on initialization of zero-sized types? +// FIXME(#97083): Right now the first breakable line is: +// gdb-check: let mut c = 27; +// gdb-command: next +// gdb-check: let d = c = 99; +// gdb-command: next +// FIXME(#33013): gdb-check: let e = "hi bob"; +// FIXME(#33013): gdb-command: next +// FIXME(#33013): gdb-check: let f = b"hi bob"; +// FIXME(#33013): gdb-command: next +// FIXME(#33013): gdb-check: let g = b'9'; +// FIXME(#33013): gdb-command: next +// FIXME(#33013): gdb-check: let h = ["whatever"; 8]; +// FIXME(#33013): gdb-command: next +// gdb-check: let i = [1,2,3,4]; +// gdb-command: next +// gdb-check: let j = (23, "hi"); +// gdb-command: next +// gdb-check: let k = 2..3; +// gdb-command: next +// gdb-check: let l = &i[k]; +// gdb-command: next +// gdb-check: let m: *const() = &a; + +fn main () { + let a = (); // #break + let b : [i32; 0] = []; + let mut c = 27; + let d = c = 99; + let e = "hi bob"; + let f = b"hi bob"; + let g = b'9'; + let h = ["whatever"; 8]; + let i = [1,2,3,4]; + let j = (23, "hi"); + let k = 2..3; + let l = &i[k]; + let m: *const() = &a; +} From 013b3eb8055d730f152e9a26df0317ef16f0f86b Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Sun, 6 Jul 2025 18:03:07 +0000 Subject: [PATCH 0149/1134] Remove support for -Zcombine-cgu Nobody seems to actually use this, while still adding some extra complexity to the already rather complex codegen coordinator code. It is also not supported by any backend other than the LLVM backend. --- src/back/write.rs | 9 --------- src/lib.rs | 8 -------- 2 files changed, 17 deletions(-) diff --git a/src/back/write.rs b/src/back/write.rs index 113abe70805b..c1231142c658 100644 --- a/src/back/write.rs +++ b/src/back/write.rs @@ -4,7 +4,6 @@ use gccjit::{Context, OutputKind}; use rustc_codegen_ssa::back::link::ensure_removed; use rustc_codegen_ssa::back::write::{BitcodeSection, CodegenContext, EmitObj, ModuleConfig}; use rustc_codegen_ssa::{CompiledModule, ModuleCodegen}; -use rustc_errors::DiagCtxtHandle; use rustc_fs_util::link_or_copy; use rustc_session::config::OutputType; use rustc_span::fatal_error::FatalError; @@ -258,14 +257,6 @@ pub(crate) fn codegen( )) } -pub(crate) fn link( - _cgcx: &CodegenContext, - _dcx: DiagCtxtHandle<'_>, - mut _modules: Vec>, -) -> Result, FatalError> { - unimplemented!(); -} - pub(crate) fn save_temp_bitcode( cgcx: &CodegenContext, _module: &ModuleCodegen, diff --git a/src/lib.rs b/src/lib.rs index 71765c511381..a31206825007 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -426,14 +426,6 @@ impl WriteBackendMethods for GccCodegenBackend { fn serialize_module(_module: ModuleCodegen) -> (String, Self::ModuleBuffer) { unimplemented!(); } - - fn run_link( - cgcx: &CodegenContext, - dcx: DiagCtxtHandle<'_>, - modules: Vec>, - ) -> Result, FatalError> { - back::write::link(cgcx, dcx, modules) - } } /// This is the entrypoint for a hot plugged rustc_codegen_gccjit From 26a7a24405f4a71b491cf1e9dfa6246dd23d88b0 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Sat, 26 Jul 2025 11:00:36 -0700 Subject: [PATCH 0150/1134] Add release notes for 1.89.0 --- RELEASES.md | 136 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) diff --git a/RELEASES.md b/RELEASES.md index 1ae221774dc9..bb8fd41f2bb6 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,3 +1,139 @@ +Version 1.89.0 (2025-08-07) +========================== + + + +Language +-------- +- [Stabilize explicitly inferred const arguments (`feature(generic_arg_infer)`)](https://github.com/rust-lang/rust/pull/141610) +- [Add a warn-by-default `mismatched_lifetime_syntaxes` lint.](https://github.com/rust-lang/rust/pull/138677) + This lint detects when the same lifetime is referred to by different syntax categories between function arguments and return values, which can be confusing to read, especially in unsafe code. + This lint supersedes the warn-by-default `elided_named_lifetimes` lint. +- [Expand `unpredictable_function_pointer_comparisons` to also lint on function pointer comparisons in external macros](https://github.com/rust-lang/rust/pull/134536) +- [Make the `dangerous_implicit_autorefs` lint deny-by-default](https://github.com/rust-lang/rust/pull/141661) +- [Stabilize the avx512 target features](https://github.com/rust-lang/rust/pull/138940) +- [Stabilize `kl` and `widekl` target features for x86](https://github.com/rust-lang/rust/pull/140766) +- [Stabilize `sha512`, `sm3` and `sm4` target features for x86](https://github.com/rust-lang/rust/pull/140767) +- [Stabilize LoongArch target features `f`, `d`, `frecipe`, `lasx`, `lbt`, `lsx`, and `lvz`](https://github.com/rust-lang/rust/pull/135015) +- [Remove `i128` and `u128` from `improper_ctypes_definitions`](https://github.com/rust-lang/rust/pull/137306) +- [Stabilize `repr128` (`#[repr(u128)]`, `#[repr(i128)]`)](https://github.com/rust-lang/rust/pull/138285) +- [Allow `#![doc(test(attr(..)))]` everywhere](https://github.com/rust-lang/rust/pull/140560) +- [Extend temporary lifetime extension to also go through tuple struct and tuple variant constructors](https://github.com/rust-lang/rust/pull/140593) + + + + +Compiler +-------- +- [Default to non-leaf frame pointers on aarch64-linux](https://github.com/rust-lang/rust/pull/140832) +- [Enable non-leaf frame pointers for Arm64EC Windows](https://github.com/rust-lang/rust/pull/140862) +- [Set Apple frame pointers by architecture](https://github.com/rust-lang/rust/pull/141797) + + + + +Platform Support +---------------- +- [Add new Tier-3 targets `loongarch32-unknown-none` and `loongarch32-unknown-none-softfloat`](https://github.com/rust-lang/rust/pull/142053) + +Refer to Rust's [platform support page][platform-support-doc] +for more information on Rust's tiered platform support. + +[platform-support-doc]: https://doc.rust-lang.org/rustc/platform-support.html + + + +Libraries +--------- +- [Specify the base path for `file!`](https://github.com/rust-lang/rust/pull/134442) +- [Allow storing `format_args!()` in a variable](https://github.com/rust-lang/rust/pull/140748) +- [Add `#[must_use]` to `[T; N]::map`](https://github.com/rust-lang/rust/pull/140957) +- [Implement `DerefMut` for `Lazy{Cell,Lock}`](https://github.com/rust-lang/rust/pull/129334) +- [Implement `Default` for `array::IntoIter`](https://github.com/rust-lang/rust/pull/141574) +- [Implement `Clone` for `slice::ChunkBy`](https://github.com/rust-lang/rust/pull/138016) +- [Implement `io::Seek` for `io::Take`](https://github.com/rust-lang/rust/pull/138023) + + + + +Stabilized APIs +--------------- + +- [Allow `NonZero`](https://github.com/rust-lang/rust/pull/141001) +- Many intrinsics for x86, not enumerated here + - [AVX512 intrinsics](https://github.com/rust-lang/rust/issues/111137) + - [`SHA512`, `SM3` and `SM4` intrinsics](https://github.com/rust-lang/rust/issues/126624) +- [`File::lock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.lock) +- [`File::lock_shared`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.lock_shared) +- [`File::try_lock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.try_lock) +- [`File::try_lock_shared`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.try_lock_shared) +- [`File::unlock`](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.unlock) +- [`NonNull::from_ref`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.from_ref) +- [`NonNull::from_mut`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.from_mut) +- [`NonNull::without_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.without_provenance) +- [`NonNull::with_exposed_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.with_exposed_provenance) +- [`NonNull::expose_provenance`](https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.expose_provenance) +- [`OsString::leak`](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html#method.leak) +- [`PathBuf::leak`](https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.leak) +- [`Result::flatten`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.flatten) +- [`std::os::linux::net::TcpStreamExt::quickack`](https://doc.rust-lang.org/stable/std/os/linux/net/trait.TcpStreamExt.html#tymethod.quickack) +- [`std::os::linux::net::TcpStreamExt::set_quickack`](https://doc.rust-lang.org/stable/std/os/linux/net/trait.TcpStreamExt.html#tymethod.set_quickack) + +These previously stable APIs are now stable in const contexts: + +- [`<[T; N]>::as_mut_slice`](https://doc.rust-lang.org/stable/std/primitive.array.html#method.as_mut_slice) +- [`<[u8]>::eq_ignore_ascii_case`](https://doc.rust-lang.org/stable/std/primitive.slice.html#impl-%5Bu8%5D/method.eq_ignore_ascii_case) +- [`str::eq_ignore_ascii_case`](https://doc.rust-lang.org/stable/std/primitive.str.html#impl-str/method.eq_ignore_ascii_case) + + + + +Cargo +----- +- [`cargo fix` and `cargo clippy --fix` now default to the same Cargo target selection as other build commands.](https://github.com/rust-lang/cargo/pull/15192/) Previously it would apply to all targets (like binaries, examples, tests, etc.). The `--edition` flag still applies to all targets. +- [Stabilize doctest-xcompile.](https://github.com/rust-lang/cargo/pull/15462/) Doctests are now tested when cross-compiling. Just like other tests, it will use the [`runner` setting](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerunner) to run the tests. If you need to disable tests for a target, you can use the [ignore doctest attribute](https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html#ignoring-targets) to specify the targets to ignore. + + + + +Rustdoc +----- +- [On mobile, make the sidebar full width and linewrap](https://github.com/rust-lang/rust/pull/139831). This makes long section and item names much easier to deal with on mobile. + + + + +Compatibility Notes +------------------- +- [Make `missing_fragment_specifier` an unconditional error](https://github.com/rust-lang/rust/pull/128425) +- [Enabling the `neon` target feature on `aarch64-unknown-none-softfloat` causes a warning](https://github.com/rust-lang/rust/pull/135160) because mixing code with and without that target feature is not properly supported by LLVM +- [Sized Hierarchy: Part I](https://github.com/rust-lang/rust/pull/137944) + - Introduces a small breaking change affecting `?Sized` bounds on impls on recursive types which contain associated type projections. It is not expected to affect any existing published crates. Can be fixed by refactoring the involved types or opting into the `sized_hierarchy` unstable feature. See the [FCP report](https://github.com/rust-lang/rust/pull/137944#issuecomment-2912207485) for a code example. +- The warn-by-default `elided_named_lifetimes` lint is [superseded by the warn-by-default `mismatched_lifetime_syntaxes` lint.](https://github.com/rust-lang/rust/pull/138677) +- [Error on recursive opaque types earlier in the type checker](https://github.com/rust-lang/rust/pull/139419) +- [Type inference side effects from requiring element types of array repeat expressions are `Copy` are now only available at the end of type checking](https://github.com/rust-lang/rust/pull/139635) +- [The deprecated accidentally-stable `std::intrinsics::{copy,copy_nonoverlapping,write_bytes}` are now proper intrinsics](https://github.com/rust-lang/rust/pull/139916). There are no debug assertions guarding against UB, and they cannot be coerced to function pointers. +- [Remove long-deprecated `std::intrinsics::drop_in_place`](https://github.com/rust-lang/rust/pull/140151) +- [Make well-formedness predicates no longer coinductive](https://github.com/rust-lang/rust/pull/140208) +- [Remove hack when checking impl method compatibility](https://github.com/rust-lang/rust/pull/140557) +- [Remove unnecessary type inference due to built-in trait object impls](https://github.com/rust-lang/rust/pull/141352) +- [Lint against "stdcall", "fastcall", and "cdecl" on non-x86-32 targets](https://github.com/rust-lang/rust/pull/141435) +- [Future incompatibility warnings relating to the never type (`!`) are now reported in dependencies](https://github.com/rust-lang/rust/pull/141937) +- [Ensure `std::ptr::copy_*` intrinsics also perform the static self-init checks](https://github.com/rust-lang/rust/pull/142575) + + + + +Internal Changes +---------------- + +These changes do not affect any public interfaces of Rust, but they represent +significant improvements to the performance or internals of rustc and related +tools. + +- [Correctly un-remap compiler sources paths with the `rustc-dev` component](https://github.com/rust-lang/rust/pull/142377) + + Version 1.88.0 (2025-06-26) ========================== From 31b6b666386146e5e88ff9f5d1327ee541c02939 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Mon, 7 Jul 2025 22:28:37 +0200 Subject: [PATCH 0151/1134] Fix tooling Signed-off-by: Jonathan Brouwer --- clippy_lints/src/needless_pass_by_value.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/clippy_lints/src/needless_pass_by_value.rs b/clippy_lints/src/needless_pass_by_value.rs index 2006a824402d..7b057998063f 100644 --- a/clippy_lints/src/needless_pass_by_value.rs +++ b/clippy_lints/src/needless_pass_by_value.rs @@ -312,9 +312,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { /// Functions marked with these attributes must have the exact signature. pub(crate) fn requires_exact_signature(attrs: &[Attribute]) -> bool { attrs.iter().any(|attr| { - [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive] - .iter() - .any(|&allow| attr.has_name(allow)) + attr.is_proc_macro_attr() }) } From 7ead5764a88d91803db898e679dd49f2520cdae6 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sat, 26 Jul 2025 13:22:24 -0700 Subject: [PATCH 0152/1134] Implement `ptr_cast_array` --- library/core/src/ptr/const_ptr.rs | 9 +++++++++ library/core/src/ptr/mut_ptr.rs | 9 +++++++++ library/core/src/ptr/non_null.rs | 7 +++++++ 3 files changed, 25 insertions(+) diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 2ad520b7ead7..90d08f60a045 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -1547,6 +1547,15 @@ impl *const [T] { } } +impl *const T { + /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`. + #[inline] + #[unstable(feature = "ptr_cast_array", issue = "144514")] + pub const fn cast_array(self) -> *const [T; N] { + self.cast() + } +} + impl *const [T; N] { /// Returns a raw pointer to the array's buffer. /// diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 579e2461103d..dec212d04c96 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -1965,6 +1965,15 @@ impl *mut [T] { } } +impl *mut T { + /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`. + #[inline] + #[unstable(feature = "ptr_cast_array", issue = "144514")] + pub const fn cast_array(self) -> *mut [T; N] { + self.cast() + } +} + impl *mut [T; N] { /// Returns a raw pointer to the array's buffer. /// diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index 62da6567cca7..245a0a08321c 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -193,6 +193,13 @@ impl NonNull { // requirements for a reference. unsafe { &mut *self.cast().as_ptr() } } + + /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`. + #[inline] + #[unstable(feature = "ptr_cast_array", issue = "144514")] + pub const fn cast_array(self) -> NonNull<[T; N]> { + self.cast() + } } impl NonNull { From 51b0416c19f436393b3c070cc037a8f062bcbd83 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sat, 26 Jul 2025 13:26:53 -0700 Subject: [PATCH 0153/1134] Use `cast_array` in core --- library/core/src/slice/mod.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 6fe5affc48be..13e182b5f87a 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -330,7 +330,7 @@ impl [T] { } else { // SAFETY: We explicitly check for the correct number of elements, // and do not let the reference outlive the slice. - Some(unsafe { &*(self.as_ptr().cast::<[T; N]>()) }) + Some(unsafe { &*(self.as_ptr().cast_array()) }) } } @@ -361,7 +361,7 @@ impl [T] { // SAFETY: We explicitly check for the correct number of elements, // do not let the reference outlive the slice, // and require exclusive access to the entire slice to mutate the chunk. - Some(unsafe { &mut *(self.as_mut_ptr().cast::<[T; N]>()) }) + Some(unsafe { &mut *(self.as_mut_ptr().cast_array()) }) } } @@ -389,7 +389,7 @@ impl [T] { // SAFETY: We explicitly check for the correct number of elements, // and do not let the references outlive the slice. - Some((unsafe { &*(first.as_ptr().cast::<[T; N]>()) }, tail)) + Some((unsafe { &*(first.as_ptr().cast_array()) }, tail)) } /// Returns a mutable array reference to the first `N` items in the slice and the remaining @@ -422,7 +422,7 @@ impl [T] { // SAFETY: We explicitly check for the correct number of elements, // do not let the reference outlive the slice, // and enforce exclusive mutability of the chunk by the split. - Some((unsafe { &mut *(first.as_mut_ptr().cast::<[T; N]>()) }, tail)) + Some((unsafe { &mut *(first.as_mut_ptr().cast_array()) }, tail)) } /// Returns an array reference to the last `N` items in the slice and the remaining slice. @@ -450,7 +450,7 @@ impl [T] { // SAFETY: We explicitly check for the correct number of elements, // and do not let the references outlive the slice. - Some((init, unsafe { &*(last.as_ptr().cast::<[T; N]>()) })) + Some((init, unsafe { &*(last.as_ptr().cast_array()) })) } /// Returns a mutable array reference to the last `N` items in the slice and the remaining @@ -484,7 +484,7 @@ impl [T] { // SAFETY: We explicitly check for the correct number of elements, // do not let the reference outlive the slice, // and enforce exclusive mutability of the chunk by the split. - Some((init, unsafe { &mut *(last.as_mut_ptr().cast::<[T; N]>()) })) + Some((init, unsafe { &mut *(last.as_mut_ptr().cast_array()) })) } /// Returns an array reference to the last `N` items in the slice. @@ -513,7 +513,7 @@ impl [T] { // SAFETY: We explicitly check for the correct number of elements, // and do not let the references outlive the slice. - Some(unsafe { &*(last.as_ptr().cast::<[T; N]>()) }) + Some(unsafe { &*(last.as_ptr().cast_array()) }) } /// Returns a mutable array reference to the last `N` items in the slice. @@ -544,7 +544,7 @@ impl [T] { // SAFETY: We explicitly check for the correct number of elements, // do not let the reference outlive the slice, // and require exclusive access to the entire slice to mutate the chunk. - Some(unsafe { &mut *(last.as_mut_ptr().cast::<[T; N]>()) }) + Some(unsafe { &mut *(last.as_mut_ptr().cast_array()) }) } /// Returns a reference to an element or subslice depending on the type of @@ -848,7 +848,7 @@ impl [T] { #[must_use] pub const fn as_array(&self) -> Option<&[T; N]> { if self.len() == N { - let ptr = self.as_ptr() as *const [T; N]; + let ptr = self.as_ptr().cast_array(); // SAFETY: The underlying array of a slice can be reinterpreted as an actual array `[T; N]` if `N` is not greater than the slice's length. let me = unsafe { &*ptr }; @@ -866,7 +866,7 @@ impl [T] { #[must_use] pub const fn as_mut_array(&mut self) -> Option<&mut [T; N]> { if self.len() == N { - let ptr = self.as_mut_ptr() as *mut [T; N]; + let ptr = self.as_mut_ptr().cast_array(); // SAFETY: The underlying array of a slice can be reinterpreted as an actual array `[T; N]` if `N` is not greater than the slice's length. let me = unsafe { &mut *ptr }; From 474315828b5a6eca321b2e2816829ccd530b210b Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Sat, 26 Jul 2025 16:51:58 -0500 Subject: [PATCH 0154/1134] libm: Update for new warn-by-default clippy lints Silence the approximate constant lint because it is noisy and not always correct. `single_component_path_imports` is also not accurate when built as part of `compiler-builtins`, so that needs to be `allow`ed as well. --- library/compiler-builtins/libm/src/math/mod.rs | 2 ++ library/compiler-builtins/libm/src/math/support/mod.rs | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/library/compiler-builtins/libm/src/math/mod.rs b/library/compiler-builtins/libm/src/math/mod.rs index ce9b8fc58bbd..8eecfe5667d1 100644 --- a/library/compiler-builtins/libm/src/math/mod.rs +++ b/library/compiler-builtins/libm/src/math/mod.rs @@ -1,3 +1,5 @@ +#![allow(clippy::approx_constant)] // many false positives + macro_rules! force_eval { ($e:expr) => { unsafe { ::core::ptr::read_volatile(&$e) } diff --git a/library/compiler-builtins/libm/src/math/support/mod.rs b/library/compiler-builtins/libm/src/math/support/mod.rs index 2e7edd03c421..b2d7bd8d5567 100644 --- a/library/compiler-builtins/libm/src/math/support/mod.rs +++ b/library/compiler-builtins/libm/src/math/support/mod.rs @@ -11,7 +11,8 @@ mod int_traits; #[allow(unused_imports)] pub use big::{i256, u256}; -#[allow(unused_imports)] +// Clippy seems to have a false positive +#[allow(unused_imports, clippy::single_component_path_imports)] pub(crate) use cfg_if; pub use env::{FpResult, Round, Status}; #[allow(unused_imports)] From c061e73d9ff3fa07dcb005a40453e124302bdeb8 Mon Sep 17 00:00:00 2001 From: quaternic <57393910+quaternic@users.noreply.github.com> Date: Sun, 27 Jul 2025 08:26:58 +0300 Subject: [PATCH 0155/1134] Avoid inlining `floor` into `rem_pio2` Possible workaround for https://github.com/rust-lang/compiler-builtins/pull/976#issuecomment-3085530354 Inline assembly in the body of a function currently causes the compiler to consider that function possibly unwinding, even if said asm originated from inlining an `extern "C"` function. This patch wraps the problematic callsite with `#[inline(never)]`. --- .../compiler-builtins/libm/src/math/rem_pio2_large.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/library/compiler-builtins/libm/src/math/rem_pio2_large.rs b/library/compiler-builtins/libm/src/math/rem_pio2_large.rs index 6d679bbe98c4..792c09fb17eb 100644 --- a/library/compiler-builtins/libm/src/math/rem_pio2_large.rs +++ b/library/compiler-builtins/libm/src/math/rem_pio2_large.rs @@ -11,7 +11,7 @@ * ==================================================== */ -use super::{floor, scalbn}; +use super::scalbn; // initial value for jk const INIT_JK: [usize; 4] = [3, 4, 4, 6]; @@ -223,6 +223,14 @@ const PIO2: [f64; 8] = [ /// independent of the exponent of the input. #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub(crate) fn rem_pio2_large(x: &[f64], y: &mut [f64], e0: i32, prec: usize) -> i32 { + // FIXME(rust-lang/rust#144518): Inline assembly would cause `no_panic` to fail + // on the callers of this function. As a workaround, avoid inlining `floor` here + // when implemented with assembly. + #[cfg_attr(x86_no_sse, inline(never))] + extern "C" fn floor(x: f64) -> f64 { + super::floor(x) + } + let x1p24 = f64::from_bits(0x4170000000000000); // 0x1p24 === 2 ^ 24 let x1p_24 = f64::from_bits(0x3e70000000000000); // 0x1p_24 === 2 ^ (-24) From 90d97f617fcf514db538738cde2179d854714ded Mon Sep 17 00:00:00 2001 From: Madhav Madhusoodanan Date: Sun, 27 Jul 2025 11:40:00 +0530 Subject: [PATCH 0156/1134] feat: updated Argument type for functional compatibility with other architectures too --- .../crates/intrinsic-test/src/arm/argument.rs | 15 ++++++++ .../intrinsic-test/src/arm/json_parser.rs | 7 ++-- .../crates/intrinsic-test/src/arm/mod.rs | 4 ++- .../intrinsic-test/src/common/argument.rs | 36 +++++-------------- 4 files changed, 32 insertions(+), 30 deletions(-) create mode 100644 library/stdarch/crates/intrinsic-test/src/arm/argument.rs diff --git a/library/stdarch/crates/intrinsic-test/src/arm/argument.rs b/library/stdarch/crates/intrinsic-test/src/arm/argument.rs new file mode 100644 index 000000000000..c43609bb2db0 --- /dev/null +++ b/library/stdarch/crates/intrinsic-test/src/arm/argument.rs @@ -0,0 +1,15 @@ +use crate::arm::intrinsic::ArmIntrinsicType; +use crate::common::argument::Argument; + +// This functionality is present due to the nature +// of how intrinsics are defined in the JSON source +// of ARM intrinsics. +impl Argument { + pub fn type_and_name_from_c(arg: &str) -> (&str, &str) { + let split_index = arg + .rfind([' ', '*']) + .expect("Couldn't split type and argname"); + + (arg[..split_index + 1].trim_end(), &arg[split_index + 1..]) + } +} diff --git a/library/stdarch/crates/intrinsic-test/src/arm/json_parser.rs b/library/stdarch/crates/intrinsic-test/src/arm/json_parser.rs index 58d366c86a93..56ec183bdd3e 100644 --- a/library/stdarch/crates/intrinsic-test/src/arm/json_parser.rs +++ b/library/stdarch/crates/intrinsic-test/src/arm/json_parser.rs @@ -86,13 +86,16 @@ fn json_to_intrinsic( .into_iter() .enumerate() .map(|(i, arg)| { - let arg_name = Argument::::type_and_name_from_c(&arg).1; + let (type_name, arg_name) = Argument::::type_and_name_from_c(&arg); let metadata = intr.args_prep.as_mut(); let metadata = metadata.and_then(|a| a.remove(arg_name)); let arg_prep: Option = metadata.and_then(|a| a.try_into().ok()); let constraint: Option = arg_prep.and_then(|a| a.try_into().ok()); + let ty = ArmIntrinsicType::from_c(type_name, target) + .unwrap_or_else(|_| panic!("Failed to parse argument '{arg}'")); - let mut arg = Argument::::from_c(i, &arg, target, constraint); + let mut arg = + Argument::::new(i, String::from(arg_name), ty, constraint); // The JSON doesn't list immediates as const let IntrinsicType { diff --git a/library/stdarch/crates/intrinsic-test/src/arm/mod.rs b/library/stdarch/crates/intrinsic-test/src/arm/mod.rs index 5d0320c4cdda..917f1293b727 100644 --- a/library/stdarch/crates/intrinsic-test/src/arm/mod.rs +++ b/library/stdarch/crates/intrinsic-test/src/arm/mod.rs @@ -1,10 +1,11 @@ +mod argument; mod compile; mod config; mod intrinsic; mod json_parser; mod types; -use std::fs::File; +use std::fs::{self, File}; use rayon::prelude::*; @@ -72,6 +73,7 @@ impl SupportedArchitectureTest for ArmArchitectureTest { let cpp_compiler = compile::build_cpp_compilation(&self.cli_options).unwrap(); let notice = &build_notices("// "); + fs::create_dir_all("c_programs").unwrap(); self.intrinsics .par_chunks(chunk_size) .enumerate() diff --git a/library/stdarch/crates/intrinsic-test/src/common/argument.rs b/library/stdarch/crates/intrinsic-test/src/common/argument.rs index 1550cbd97f58..f38515e40a9d 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/argument.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/argument.rs @@ -20,6 +20,15 @@ impl Argument where T: IntrinsicTypeDefinition, { + pub fn new(pos: usize, name: String, ty: T, constraint: Option) -> Self { + Argument { + pos, + name, + ty, + constraint, + } + } + pub fn to_c_type(&self) -> String { self.ty.c_type() } @@ -36,14 +45,6 @@ where self.constraint.is_some() } - pub fn type_and_name_from_c(arg: &str) -> (&str, &str) { - let split_index = arg - .rfind([' ', '*']) - .expect("Couldn't split type and argname"); - - (arg[..split_index + 1].trim_end(), &arg[split_index + 1..]) - } - /// The binding keyword (e.g. "const" or "let") for the array of possible test inputs. fn rust_vals_array_binding(&self) -> impl std::fmt::Display { if self.ty.is_rust_vals_array_const() { @@ -62,25 +63,6 @@ where } } - pub fn from_c( - pos: usize, - arg: &str, - target: &str, - constraint: Option, - ) -> Argument { - let (ty, var_name) = Self::type_and_name_from_c(arg); - - let ty = - T::from_c(ty, target).unwrap_or_else(|_| panic!("Failed to parse argument '{arg}'")); - - Argument { - pos, - name: String::from(var_name), - ty: ty, - constraint, - } - } - fn as_call_param_c(&self) -> String { self.ty.as_call_param_c(&self.name) } From c78f3aedfc262c95b08d944c878976dcc133dcf3 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Sun, 27 Jul 2025 15:13:34 +0800 Subject: [PATCH 0157/1134] fix: `empty_structs_with_brackets` suggests wrongly on generics --- clippy_lints/src/empty_with_brackets.rs | 4 ++-- tests/ui/empty_structs_with_brackets.fixed | 14 ++++++++++++++ tests/ui/empty_structs_with_brackets.rs | 14 ++++++++++++++ tests/ui/empty_structs_with_brackets.stderr | 10 +++++++++- 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/empty_with_brackets.rs b/clippy_lints/src/empty_with_brackets.rs index f2757407ba57..e7230ebf8cba 100644 --- a/clippy_lints/src/empty_with_brackets.rs +++ b/clippy_lints/src/empty_with_brackets.rs @@ -93,11 +93,11 @@ impl_lint_pass!(EmptyWithBrackets => [EMPTY_STRUCTS_WITH_BRACKETS, EMPTY_ENUM_VA impl LateLintPass<'_> for EmptyWithBrackets { fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { // FIXME: handle `struct $name {}` - if let ItemKind::Struct(ident, _, var_data) = &item.kind + if let ItemKind::Struct(ident, generics, var_data) = &item.kind && !item.span.from_expansion() && !ident.span.from_expansion() && has_brackets(var_data) - && let span_after_ident = item.span.with_lo(ident.span.hi()) + && let span_after_ident = item.span.with_lo(generics.span.hi()) && has_no_fields(cx, var_data, span_after_ident) { span_lint_and_then( diff --git a/tests/ui/empty_structs_with_brackets.fixed b/tests/ui/empty_structs_with_brackets.fixed index 419cf2354f89..22386245ffe6 100644 --- a/tests/ui/empty_structs_with_brackets.fixed +++ b/tests/ui/empty_structs_with_brackets.fixed @@ -32,3 +32,17 @@ macro_rules! empty_struct { empty_struct!(FromMacro); fn main() {} + +mod issue15349 { + trait Bar {} + impl Bar for [u8; 7] {} + + struct Foo; + //~^ empty_structs_with_brackets + impl Foo + where + [u8; N]: Bar<[(); N]>, + { + fn foo() {} + } +} diff --git a/tests/ui/empty_structs_with_brackets.rs b/tests/ui/empty_structs_with_brackets.rs index 90c415c12206..5cb54b661349 100644 --- a/tests/ui/empty_structs_with_brackets.rs +++ b/tests/ui/empty_structs_with_brackets.rs @@ -32,3 +32,17 @@ macro_rules! empty_struct { empty_struct!(FromMacro); fn main() {} + +mod issue15349 { + trait Bar {} + impl Bar for [u8; 7] {} + + struct Foo {} + //~^ empty_structs_with_brackets + impl Foo + where + [u8; N]: Bar<[(); N]>, + { + fn foo() {} + } +} diff --git a/tests/ui/empty_structs_with_brackets.stderr b/tests/ui/empty_structs_with_brackets.stderr index 86ef43aa9600..f662bb9423e3 100644 --- a/tests/ui/empty_structs_with_brackets.stderr +++ b/tests/ui/empty_structs_with_brackets.stderr @@ -16,5 +16,13 @@ LL | struct MyEmptyTupleStruct(); // should trigger lint | = help: remove the brackets -error: aborting due to 2 previous errors +error: found empty brackets on struct declaration + --> tests/ui/empty_structs_with_brackets.rs:40:31 + | +LL | struct Foo {} + | ^^^ + | + = help: remove the brackets + +error: aborting due to 3 previous errors From 81fc22753e3e75dae62a5837c2b641c0fbd57cde Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Fri, 25 Jul 2025 22:32:41 +0200 Subject: [PATCH 0158/1134] fix: `unnecessary_map_or` don't add parens if the parent expr comes from a macro --- .../src/methods/unnecessary_map_or.rs | 14 ++++++--- tests/ui/unnecessary_map_or.fixed | 20 +++++++++++++ tests/ui/unnecessary_map_or.rs | 20 +++++++++++++ tests/ui/unnecessary_map_or.stderr | 30 +++++++++++++++++-- 4 files changed, 77 insertions(+), 7 deletions(-) diff --git a/clippy_lints/src/methods/unnecessary_map_or.rs b/clippy_lints/src/methods/unnecessary_map_or.rs index 4a9007c607c8..1f5e3de6e7a2 100644 --- a/clippy_lints/src/methods/unnecessary_map_or.rs +++ b/clippy_lints/src/methods/unnecessary_map_or.rs @@ -109,10 +109,16 @@ pub(super) fn check<'a>( ); let sugg = if let Some(parent_expr) = get_parent_expr(cx, expr) { - match parent_expr.kind { - ExprKind::Binary(..) | ExprKind::Unary(..) | ExprKind::Cast(..) => binop.maybe_paren(), - ExprKind::MethodCall(_, receiver, _, _) if receiver.hir_id == expr.hir_id => binop.maybe_paren(), - _ => binop, + if parent_expr.span.eq_ctxt(expr.span) { + match parent_expr.kind { + ExprKind::Binary(..) | ExprKind::Unary(..) | ExprKind::Cast(..) => binop.maybe_paren(), + ExprKind::MethodCall(_, receiver, _, _) if receiver.hir_id == expr.hir_id => binop.maybe_paren(), + _ => binop, + } + } else { + // if our parent expr is created by a macro, then it should be the one taking care of + // parenthesising us if necessary + binop } } else { binop diff --git a/tests/ui/unnecessary_map_or.fixed b/tests/ui/unnecessary_map_or.fixed index 3109c4af8e28..10552431d65d 100644 --- a/tests/ui/unnecessary_map_or.fixed +++ b/tests/ui/unnecessary_map_or.fixed @@ -131,6 +131,26 @@ fn issue14201(a: Option, b: Option, s: &String) -> bool { x && y } +fn issue14714() { + assert!(Some("test") == Some("test")); + //~^ unnecessary_map_or + + // even though we're in a macro context, we still need to parenthesise because of the `then` + assert!((Some("test") == Some("test")).then(|| 1).is_some()); + //~^ unnecessary_map_or + + // method lints don't fire on macros + macro_rules! m { + ($x:expr) => { + // should become !($x == Some(1)) + let _ = !$x.map_or(false, |v| v == 1); + // should become $x == Some(1) + let _ = $x.map_or(false, |v| v == 1); + }; + } + m!(Some(5)); +} + fn issue15180() { let s = std::sync::Mutex::new(Some("foo")); _ = s.lock().unwrap().is_some_and(|s| s == "foo"); diff --git a/tests/ui/unnecessary_map_or.rs b/tests/ui/unnecessary_map_or.rs index 52a55f9fc9e4..4b406ec2998b 100644 --- a/tests/ui/unnecessary_map_or.rs +++ b/tests/ui/unnecessary_map_or.rs @@ -135,6 +135,26 @@ fn issue14201(a: Option, b: Option, s: &String) -> bool { x && y } +fn issue14714() { + assert!(Some("test").map_or(false, |x| x == "test")); + //~^ unnecessary_map_or + + // even though we're in a macro context, we still need to parenthesise because of the `then` + assert!(Some("test").map_or(false, |x| x == "test").then(|| 1).is_some()); + //~^ unnecessary_map_or + + // method lints don't fire on macros + macro_rules! m { + ($x:expr) => { + // should become !($x == Some(1)) + let _ = !$x.map_or(false, |v| v == 1); + // should become $x == Some(1) + let _ = $x.map_or(false, |v| v == 1); + }; + } + m!(Some(5)); +} + fn issue15180() { let s = std::sync::Mutex::new(Some("foo")); _ = s.lock().unwrap().map_or(false, |s| s == "foo"); diff --git a/tests/ui/unnecessary_map_or.stderr b/tests/ui/unnecessary_map_or.stderr index 99e17e8b34ba..b8a22346c378 100644 --- a/tests/ui/unnecessary_map_or.stderr +++ b/tests/ui/unnecessary_map_or.stderr @@ -327,7 +327,31 @@ LL + let y = b.is_none_or(|b| b == *s); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:140:9 + --> tests/ui/unnecessary_map_or.rs:139:13 + | +LL | assert!(Some("test").map_or(false, |x| x == "test")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use a standard comparison instead + | +LL - assert!(Some("test").map_or(false, |x| x == "test")); +LL + assert!(Some("test") == Some("test")); + | + +error: this `map_or` can be simplified + --> tests/ui/unnecessary_map_or.rs:143:13 + | +LL | assert!(Some("test").map_or(false, |x| x == "test").then(|| 1).is_some()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: use a standard comparison instead + | +LL - assert!(Some("test").map_or(false, |x| x == "test").then(|| 1).is_some()); +LL + assert!((Some("test") == Some("test")).then(|| 1).is_some()); + | + +error: this `map_or` can be simplified + --> tests/ui/unnecessary_map_or.rs:160:9 | LL | _ = s.lock().unwrap().map_or(false, |s| s == "foo"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -339,7 +363,7 @@ LL + _ = s.lock().unwrap().is_some_and(|s| s == "foo"); | error: this `map_or` can be simplified - --> tests/ui/unnecessary_map_or.rs:144:9 + --> tests/ui/unnecessary_map_or.rs:164:9 | LL | _ = s.map_or(false, |s| s == "foo"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -350,5 +374,5 @@ LL - _ = s.map_or(false, |s| s == "foo"); LL + _ = s.is_some_and(|s| s == "foo"); | -error: aborting due to 28 previous errors +error: aborting due to 30 previous errors From c07f8bbdc2b2febed3592f112bd004e1a9016904 Mon Sep 17 00:00:00 2001 From: Madhav Madhusoodanan Date: Sun, 27 Jul 2025 18:00:41 +0530 Subject: [PATCH 0159/1134] chore: handling the case where --generate-only flag is passed --- .../crates/intrinsic-test/src/arm/mod.rs | 49 +++++++++++-------- .../intrinsic-test/src/common/gen_rust.rs | 12 +++-- 2 files changed, 37 insertions(+), 24 deletions(-) diff --git a/library/stdarch/crates/intrinsic-test/src/arm/mod.rs b/library/stdarch/crates/intrinsic-test/src/arm/mod.rs index 917f1293b727..63663ff5fc16 100644 --- a/library/stdarch/crates/intrinsic-test/src/arm/mod.rs +++ b/library/stdarch/crates/intrinsic-test/src/arm/mod.rs @@ -70,7 +70,7 @@ impl SupportedArchitectureTest for ArmArchitectureTest { let (chunk_size, chunk_count) = chunk_info(self.intrinsics.len()); - let cpp_compiler = compile::build_cpp_compilation(&self.cli_options).unwrap(); + let cpp_compiler_wrapped = compile::build_cpp_compilation(&self.cli_options); let notice = &build_notices("// "); fs::create_dir_all("c_programs").unwrap(); @@ -82,10 +82,15 @@ impl SupportedArchitectureTest for ArmArchitectureTest { let mut file = File::create(&c_filename).unwrap(); write_mod_cpp(&mut file, notice, c_target, platform_headers, chunk).unwrap(); - // compile this cpp file into a .o file - let output = cpp_compiler - .compile_object_file(&format!("mod_{i}.cpp"), &format!("mod_{i}.o"))?; - assert!(output.status.success(), "{output:?}"); + // compile this cpp file into a .o file. + // + // This is done because `cpp_compiler_wrapped` is None when + // the --generate-only flag is passed + if let Some(cpp_compiler) = cpp_compiler_wrapped.as_ref() { + let output = cpp_compiler + .compile_object_file(&format!("mod_{i}.cpp"), &format!("mod_{i}.o"))?; + assert!(output.status.success(), "{output:?}"); + } Ok(()) }) @@ -101,21 +106,25 @@ impl SupportedArchitectureTest for ArmArchitectureTest { ) .unwrap(); - // compile this cpp file into a .o file - info!("compiling main.cpp"); - let output = cpp_compiler - .compile_object_file("main.cpp", "intrinsic-test-programs.o") - .unwrap(); - assert!(output.status.success(), "{output:?}"); - - let object_files = (0..chunk_count) - .map(|i| format!("mod_{i}.o")) - .chain(["intrinsic-test-programs.o".to_owned()]); - - let output = cpp_compiler - .link_executable(object_files, "intrinsic-test-programs") - .unwrap(); - assert!(output.status.success(), "{output:?}"); + // This is done because `cpp_compiler_wrapped` is None when + // the --generate-only flag is passed + if let Some(cpp_compiler) = cpp_compiler_wrapped.as_ref() { + // compile this cpp file into a .o file + info!("compiling main.cpp"); + let output = cpp_compiler + .compile_object_file("main.cpp", "intrinsic-test-programs.o") + .unwrap(); + assert!(output.status.success(), "{output:?}"); + + let object_files = (0..chunk_count) + .map(|i| format!("mod_{i}.o")) + .chain(["intrinsic-test-programs.o".to_owned()]); + + let output = cpp_compiler + .link_executable(object_files, "intrinsic-test-programs") + .unwrap(); + assert!(output.status.success(), "{output:?}"); + } true } diff --git a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs index 60bb577a80c9..acc18cfb92bc 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs @@ -130,6 +130,12 @@ pub fn compile_rust_programs(toolchain: Option<&str>, target: &str, linker: Opti /* If there has been a linker explicitly set from the command line then * we want to set it via setting it in the RUSTFLAGS*/ + // This is done because `toolchain` is None when + // the --generate-only flag is passed + if toolchain.is_none() { + return true; + } + trace!("Building cargo command"); let mut cargo_command = Command::new("cargo"); @@ -138,10 +144,8 @@ pub fn compile_rust_programs(toolchain: Option<&str>, target: &str, linker: Opti // Do not use the target directory of the workspace please. cargo_command.env("CARGO_TARGET_DIR", "target"); - if let Some(toolchain) = toolchain - && !toolchain.is_empty() - { - cargo_command.arg(toolchain); + if toolchain.is_some_and(|val| !val.is_empty()) { + cargo_command.arg(toolchain.unwrap()); } cargo_command.args(["build", "--target", target, "--release"]); From 9339d8cac3e6ea8c10ad11c581f8cfed5014d89e Mon Sep 17 00:00:00 2001 From: Samuel Moelius <35515885+smoelius@users.noreply.github.com> Date: Sun, 27 Jul 2025 08:55:33 -0400 Subject: [PATCH 0160/1134] Fix typo non_std_lazy_statics.rs Changes `MaybeIncorret` to `MaybeIncorrect`. And since this is part of a doc comment, it might as well be a link. changelog: none --- clippy_lints/src/non_std_lazy_statics.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/non_std_lazy_statics.rs b/clippy_lints/src/non_std_lazy_statics.rs index abee3c44c5a3..7ecde40aee01 100644 --- a/clippy_lints/src/non_std_lazy_statics.rs +++ b/clippy_lints/src/non_std_lazy_statics.rs @@ -49,7 +49,7 @@ declare_clippy_lint! { /// Some functions could be replaced as well if we have replaced `Lazy` to `LazyLock`, /// therefore after suggesting replace the type, we need to make sure the function calls can be /// replaced, otherwise the suggestions cannot be applied thus the applicability should be -/// `Unspecified` or `MaybeIncorret`. +/// [`Applicability::Unspecified`] or [`Applicability::MaybeIncorrect`]. static FUNCTION_REPLACEMENTS: &[(&str, Option<&str>)] = &[ ("once_cell::sync::Lazy::force", Some("std::sync::LazyLock::force")), ("once_cell::sync::Lazy::get", None), // `std::sync::LazyLock::get` is experimental From 1d5a582ba03f2ecda47a2c904bedb17adf5ee2dd Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Sun, 27 Jul 2025 21:53:35 +0900 Subject: [PATCH 0161/1134] refactor: conpare text of name_ref instead of syntax name_ref --- .../crates/ide-assists/src/handlers/inline_type_alias.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs index 4511072b041b..f667d6259354 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs @@ -322,7 +322,10 @@ fn create_replacement( replacements.push((syntax.clone(), new_lifetime.syntax().clone_for_update())); } - } else if let Some(replacement_syntax) = const_and_type_map.0.get(syntax_str) { + } else if let Some(name_ref) = ast::NameRef::cast(syntax.clone()) { + let Some(replacement_syntax) = const_and_type_map.0.get(&name_ref.to_string()) else { + continue; + }; let new_string = replacement_syntax.to_string(); let new = if new_string == "_" { make::wildcard_pat().syntax().clone_for_update() From b3ea82f2eb0a5d9b895111b8b1eb165cd4da58a3 Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Sun, 27 Jul 2025 22:04:25 +0900 Subject: [PATCH 0162/1134] Migrate `inline_type_alias` assist to use `SyntaxEditor` --- .../src/handlers/inline_type_alias.rs | 63 ++++++++++--------- 1 file changed, 34 insertions(+), 29 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs index f667d6259354..62535531435d 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs @@ -9,10 +9,10 @@ use ide_db::{ search::FileReference, }; use itertools::Itertools; +use syntax::syntax_editor::SyntaxEditor; use syntax::{ AstNode, NodeOrToken, SyntaxNode, ast::{self, HasGenericParams, HasName, make}, - ted, }; use crate::{ @@ -68,37 +68,41 @@ pub(crate) fn inline_type_alias_uses(acc: &mut Assists, ctx: &AssistContext<'_>) let mut definition_deleted = false; let mut inline_refs_for_file = |file_id, refs: Vec| { - builder.edit_file(file_id); + let source = ctx.sema.parse(file_id); + let mut editor = builder.make_editor(source.syntax()); let (path_types, path_type_uses) = split_refs_and_uses(builder, refs, |path_type| { path_type.syntax().ancestors().nth(3).and_then(ast::PathType::cast) }); - path_type_uses .iter() .flat_map(ast_to_remove_for_path_in_use_stmt) - .for_each(|x| builder.delete(x.syntax().text_range())); + .for_each(|x| editor.delete(x.syntax())); + for (target, replacement) in path_types.into_iter().filter_map(|path_type| { - let replacement = inline(&ast_alias, &path_type)?.to_text(&concrete_type); - let target = path_type.syntax().text_range(); + let replacement = + inline(&ast_alias, &path_type)?.replace_generic(&concrete_type); + let target = path_type.syntax().clone(); Some((target, replacement)) }) { - builder.replace(target, replacement); + editor.replace(target, replacement); } - if file_id == ctx.vfs_file_id() { - builder.delete(ast_alias.syntax().text_range()); + if file_id.file_id(ctx.db()) == ctx.vfs_file_id() { + editor.delete(ast_alias.syntax()); definition_deleted = true; } + builder.add_file_edits(file_id.file_id(ctx.db()), editor); }; for (file_id, refs) in usages.into_iter() { - inline_refs_for_file(file_id.file_id(ctx.db()), refs); + inline_refs_for_file(file_id, refs); } if !definition_deleted { - builder.edit_file(ctx.vfs_file_id()); - builder.delete(ast_alias.syntax().text_range()); + let mut editor = builder.make_editor(ast_alias.syntax()); + editor.delete(ast_alias.syntax()); + builder.add_file_edits(ctx.vfs_file_id(), editor) } }, ) @@ -146,23 +150,26 @@ pub(crate) fn inline_type_alias(acc: &mut Assists, ctx: &AssistContext<'_>) -> O } } - let target = alias_instance.syntax().text_range(); - acc.add( AssistId::refactor_inline("inline_type_alias"), "Inline type alias", - target, - |builder| builder.replace(target, replacement.to_text(&concrete_type)), + alias_instance.syntax().text_range(), + |builder| { + let mut editor = builder.make_editor(alias_instance.syntax()); + let replace = replacement.replace_generic(&concrete_type); + editor.replace(alias_instance.syntax(), replace); + builder.add_file_edits(ctx.vfs_file_id(), editor); + }, ) } impl Replacement { - fn to_text(&self, concrete_type: &ast::Type) -> String { + fn replace_generic(&self, concrete_type: &ast::Type) -> SyntaxNode { match self { Replacement::Generic { lifetime_map, const_and_type_map } => { create_replacement(lifetime_map, const_and_type_map, concrete_type) } - Replacement::Plain => concrete_type.to_string(), + Replacement::Plain => concrete_type.syntax().clone_subtree().clone_for_update(), } } } @@ -299,15 +306,14 @@ fn create_replacement( lifetime_map: &LifetimeMap, const_and_type_map: &ConstAndTypeMap, concrete_type: &ast::Type, -) -> String { - let updated_concrete_type = concrete_type.clone_for_update(); - let mut replacements = Vec::new(); - let mut removals = Vec::new(); +) -> SyntaxNode { + let updated_concrete_type = concrete_type.syntax().clone_subtree(); + let mut editor = SyntaxEditor::new(updated_concrete_type.clone()); - for syntax in updated_concrete_type.syntax().descendants() { - let syntax_string = syntax.to_string(); - let syntax_str = syntax_string.as_str(); + let mut replacements: Vec<(SyntaxNode, SyntaxNode)> = Vec::new(); + let mut removals: Vec> = Vec::new(); + for syntax in updated_concrete_type.descendants() { if let Some(old_lifetime) = ast::Lifetime::cast(syntax.clone()) { if let Some(new_lifetime) = lifetime_map.0.get(&old_lifetime.to_string()) { if new_lifetime.text() == "'_" { @@ -338,14 +344,13 @@ fn create_replacement( } for (old, new) in replacements { - ted::replace(old, new); + editor.replace(old, new); } for syntax in removals { - ted::remove(syntax); + editor.delete(syntax); } - - updated_concrete_type.to_string() + editor.finish().new_root().clone() } fn get_type_alias(ctx: &AssistContext<'_>, path: &ast::PathType) -> Option { From b1b7077b42668ebee51c28eac86786567711ab91 Mon Sep 17 00:00:00 2001 From: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com> Date: Sat, 26 Jul 2025 22:31:41 +0900 Subject: [PATCH 0163/1134] remove ted from convert_tuple_struct_to_named_struct Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com> --- .../handlers/convert_tuple_struct_to_named_struct.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs index 80756197fb70..44361560f486 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs @@ -3,7 +3,8 @@ use ide_db::defs::{Definition, NameRefClass}; use syntax::{ SyntaxKind, SyntaxNode, ast::{self, AstNode, HasAttrs, HasGenericParams, HasVisibility}, - match_ast, ted, + match_ast, + syntax_editor::{Position, SyntaxEditor}, }; use crate::{AssistContext, AssistId, Assists, assist_context::SourceChangeBuilder}; @@ -93,12 +94,13 @@ fn edit_struct_def( names: Vec, ) { let record_fields = tuple_fields.fields().zip(names).filter_map(|(f, name)| { - let field = ast::make::record_field(f.visibility(), name, f.ty()?).clone_for_update(); - ted::insert_all( - ted::Position::first_child_of(field.syntax()), + let field = ast::make::record_field(f.visibility(), name, f.ty()?); + let mut editor = SyntaxEditor::new(field.syntax().clone()); + editor.insert_all( + Position::first_child_of(field.syntax()), f.attrs().map(|attr| attr.syntax().clone_subtree().clone_for_update().into()).collect(), ); - Some(field) + ast::RecordField::cast(editor.finish().new_root().clone()) }); let record_fields = ast::make::record_field_list(record_fields); let tuple_fields_text_range = tuple_fields.syntax().text_range(); From 85486a7bff683fd9ec241a92ca75f38659b4e76c Mon Sep 17 00:00:00 2001 From: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com> Date: Sat, 26 Jul 2025 23:20:31 +0900 Subject: [PATCH 0164/1134] migrate `fn edit_struct_def` in `convert_tuple_struct_to_named_struct` to SyntaxEditor Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com> --- .../convert_tuple_struct_to_named_struct.rs | 54 +++++++++---------- 1 file changed, 24 insertions(+), 30 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs index 44361560f486..6d729c9ea995 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs @@ -1,10 +1,10 @@ use either::Either; use ide_db::defs::{Definition, NameRefClass}; use syntax::{ - SyntaxKind, SyntaxNode, + SyntaxKind, SyntaxNode, T, ast::{self, AstNode, HasAttrs, HasGenericParams, HasVisibility}, match_ast, - syntax_editor::{Position, SyntaxEditor}, + syntax_editor::{Element, Position, SyntaxEditor}, }; use crate::{AssistContext, AssistId, Assists, assist_context::SourceChangeBuilder}; @@ -72,7 +72,7 @@ pub(crate) fn convert_tuple_struct_to_named_struct( Either::Right(v) => Either::Right(ctx.sema.to_def(v)?), }; let target = strukt_or_variant.as_ref().either(|s| s.syntax(), |v| v.syntax()).text_range(); - + let syntax = strukt_or_variant.as_ref().either(|s| s.syntax(), |v| v.syntax()); acc.add( AssistId::refactor_rewrite("convert_tuple_struct_to_named_struct"), "Convert to named struct", @@ -81,58 +81,53 @@ pub(crate) fn convert_tuple_struct_to_named_struct( let names = generate_names(tuple_fields.fields()); edit_field_references(ctx, edit, tuple_fields.fields(), &names); edit_struct_references(ctx, edit, strukt_def, &names); - edit_struct_def(ctx, edit, &strukt_or_variant, tuple_fields, names); + let mut editor = edit.make_editor(syntax); + edit_struct_def(&mut editor, &strukt_or_variant, tuple_fields, names); + edit.add_file_edits(ctx.vfs_file_id(), editor); }, ) } fn edit_struct_def( - ctx: &AssistContext<'_>, - edit: &mut SourceChangeBuilder, + editor: &mut SyntaxEditor, strukt: &Either, tuple_fields: ast::TupleFieldList, names: Vec, ) { let record_fields = tuple_fields.fields().zip(names).filter_map(|(f, name)| { let field = ast::make::record_field(f.visibility(), name, f.ty()?); - let mut editor = SyntaxEditor::new(field.syntax().clone()); - editor.insert_all( + let mut field_editor = SyntaxEditor::new(field.syntax().clone()); + field_editor.insert_all( Position::first_child_of(field.syntax()), f.attrs().map(|attr| attr.syntax().clone_subtree().clone_for_update().into()).collect(), ); - ast::RecordField::cast(editor.finish().new_root().clone()) + ast::RecordField::cast(field_editor.finish().new_root().clone()) }); - let record_fields = ast::make::record_field_list(record_fields); - let tuple_fields_text_range = tuple_fields.syntax().text_range(); - - edit.edit_file(ctx.vfs_file_id()); + let record_fields = ast::make::record_field_list(record_fields).clone_for_update(); + let tuple_fields_before = Position::before(tuple_fields.syntax()); if let Either::Left(strukt) = strukt { if let Some(w) = strukt.where_clause() { - edit.delete(w.syntax().text_range()); - edit.insert( - tuple_fields_text_range.start(), - ast::make::tokens::single_newline().text(), - ); - edit.insert(tuple_fields_text_range.start(), w.syntax().text()); + editor.delete(w.syntax()); + let mut insert_element = Vec::new(); + insert_element.push(ast::make::tokens::single_newline().syntax_element()); + insert_element.push(w.syntax().clone_for_update().syntax_element()); if w.syntax().last_token().is_none_or(|t| t.kind() != SyntaxKind::COMMA) { - edit.insert(tuple_fields_text_range.start(), ","); + insert_element.push(ast::make::token(T![,]).into()); } - edit.insert( - tuple_fields_text_range.start(), - ast::make::tokens::single_newline().text(), - ); + insert_element.push(ast::make::tokens::single_newline().syntax_element()); + editor.insert_all(tuple_fields_before, insert_element); } else { - edit.insert(tuple_fields_text_range.start(), ast::make::tokens::single_space().text()); + editor.insert(tuple_fields_before, ast::make::tokens::single_space()); } if let Some(t) = strukt.semicolon_token() { - edit.delete(t.text_range()); + editor.delete(t); } } else { - edit.insert(tuple_fields_text_range.start(), ast::make::tokens::single_space().text()); + editor.insert(tuple_fields_before, ast::make::tokens::single_space()); } - edit.replace(tuple_fields_text_range, record_fields.to_string()); + editor.replace(tuple_fields.syntax(), record_fields.syntax()); } fn edit_struct_references( @@ -1015,8 +1010,7 @@ where pub struct $0Foo(#[my_custom_attr] u32); "#, r#" -pub struct Foo { #[my_custom_attr] -field1: u32 } +pub struct Foo { #[my_custom_attr]field1: u32 } "#, ); } From 8f898729220258b58d8044d4adaff14d45288fe6 Mon Sep 17 00:00:00 2001 From: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com> Date: Sun, 27 Jul 2025 13:24:08 +0900 Subject: [PATCH 0165/1134] Migrate `convert_tuple_struct_to_named_struct' assist to use `SyntaxEditor' Signed-off-by: Hayashi Mikihiro <34ttrweoewiwe28@gmail.com> --- .../convert_tuple_struct_to_named_struct.rs | 103 ++++++++++++------ 1 file changed, 68 insertions(+), 35 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs index 6d729c9ea995..f4041f49419a 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs @@ -1,7 +1,9 @@ use either::Either; +use hir::FileRangeWrapper; use ide_db::defs::{Definition, NameRefClass}; +use std::ops::RangeInclusive; use syntax::{ - SyntaxKind, SyntaxNode, T, + SyntaxElement, SyntaxKind, SyntaxNode, T, TextSize, ast::{self, AstNode, HasAttrs, HasGenericParams, HasVisibility}, match_ast, syntax_editor::{Element, Position, SyntaxEditor}, @@ -80,8 +82,8 @@ pub(crate) fn convert_tuple_struct_to_named_struct( |edit| { let names = generate_names(tuple_fields.fields()); edit_field_references(ctx, edit, tuple_fields.fields(), &names); - edit_struct_references(ctx, edit, strukt_def, &names); let mut editor = edit.make_editor(syntax); + edit_struct_references(ctx, edit, strukt_def, &names); edit_struct_def(&mut editor, &strukt_or_variant, tuple_fields, names); edit.add_file_edits(ctx.vfs_file_id(), editor); }, @@ -142,27 +144,21 @@ fn edit_struct_references( }; let usages = strukt_def.usages(&ctx.sema).include_self_refs().all(); - let edit_node = |edit: &mut SourceChangeBuilder, node: SyntaxNode| -> Option<()> { + let edit_node = |node: SyntaxNode| -> Option { match_ast! { match node { ast::TupleStructPat(tuple_struct_pat) => { - let file_range = ctx.sema.original_range_opt(&node)?; - edit.edit_file(file_range.file_id.file_id(ctx.db())); - edit.replace( - file_range.range, - ast::make::record_pat_with_fields( - tuple_struct_pat.path()?, - ast::make::record_pat_field_list(tuple_struct_pat.fields().zip(names).map( - |(pat, name)| { - ast::make::record_pat_field( - ast::make::name_ref(&name.to_string()), - pat, - ) - }, - ), None), - ) - .to_string(), - ); + Some(ast::make::record_pat_with_fields( + tuple_struct_pat.path()?, + ast::make::record_pat_field_list(tuple_struct_pat.fields().zip(names).map( + |(pat, name)| { + ast::make::record_pat_field( + ast::make::name_ref(&name.to_string()), + pat, + ) + }, + ), None), + ).syntax().clone_for_update()) }, // for tuple struct creations like Foo(42) ast::CallExpr(call_expr) => { @@ -179,8 +175,7 @@ fn edit_struct_references( let arg_list = call_expr.syntax().descendants().find_map(ast::ArgList::cast)?; - edit.replace( - ctx.sema.original_range(&node).range, + Some( ast::make::record_expr( path, ast::make::record_expr_field_list(arg_list.args().zip(names).map( @@ -191,25 +186,58 @@ fn edit_struct_references( ) }, )), - ) - .to_string(), - ); + ).syntax().clone_for_update() + ) }, _ => return None, } } - Some(()) }; for (file_id, refs) in usages { - edit.edit_file(file_id.file_id(ctx.db())); - for r in refs { - for node in r.name.syntax().ancestors() { - if edit_node(edit, node).is_some() { - break; + let source = ctx.sema.parse(file_id); + let source = source.syntax(); + + let mut editor = edit.make_editor(source); + for r in refs.iter().rev() { + if let Some((old_node, new_node)) = r + .name + .syntax() + .ancestors() + .find_map(|node| Some((node.clone(), edit_node(node.clone())?))) + { + if let Some(old_node) = ctx.sema.original_syntax_node_rooted(&old_node) { + editor.replace(old_node, new_node); + } else { + let FileRangeWrapper { file_id: _, range } = ctx.sema.original_range(&old_node); + let parent = source.covering_element(range); + match parent { + SyntaxElement::Token(token) => { + editor.replace(token, new_node.syntax_element()); + } + SyntaxElement::Node(parent_node) => { + // replace the part of macro + // ``` + // foo!(a, Test::A(0)); + // ^^^^^^^^^^^^^^^ // parent_node + // ^^^^^^^^^^ // replace_range + // ``` + let start = parent_node + .children_with_tokens() + .find(|t| t.text_range().contains(range.start())); + let end = parent_node + .children_with_tokens() + .find(|t| t.text_range().contains(range.end() - TextSize::new(1))); + if let (Some(start), Some(end)) = (start, end) { + let replace_range = RangeInclusive::new(start, end); + editor.replace_all(replace_range, vec![new_node.into()]); + } + } + } } } } + edit.add_file_edits(file_id.file_id(ctx.db()), editor); } } @@ -227,12 +255,17 @@ fn edit_field_references( let def = Definition::Field(field); let usages = def.usages(&ctx.sema).all(); for (file_id, refs) in usages { - edit.edit_file(file_id.file_id(ctx.db())); + let source = ctx.sema.parse(file_id); + let source = source.syntax(); + let mut editor = edit.make_editor(source); for r in refs { - if let Some(name_ref) = r.name.as_name_ref() { - edit.replace(ctx.sema.original_range(name_ref.syntax()).range, name.text()); + if let Some(name_ref) = r.name.as_name_ref() + && let Some(original) = ctx.sema.original_ast_node(name_ref.clone()) + { + editor.replace(original.syntax(), name.syntax()); } } + edit.add_file_edits(file_id.file_id(ctx.db()), editor); } } } @@ -242,7 +275,7 @@ fn generate_names(fields: impl Iterator) -> Vec Date: Sun, 27 Jul 2025 23:27:40 +0200 Subject: [PATCH 0166/1134] Implement `floor` and `ceil` in assembly on `i586` Fixes: https://github.com/rust-lang/compiler-builtins/issues/837 The assembly is based on - https://github.com/NetBSD/src/blob/20433927938987dd64c8f6aa46904b7aca3fa39e/lib/libm/arch/i387/s_floor.S - https://github.com/NetBSD/src/blob/20433927938987dd64c8f6aa46904b7aca3fa39e/lib/libm/arch/i387/s_ceil.S Which both state /* * Written by J.T. Conklin . * Public domain. */ Which I believe means we're good in terms of licensing. --- .../libm-test/src/precision.rs | 22 ----- .../libm/src/math/arch/i586.rs | 85 ++++++++++++------- 2 files changed, 55 insertions(+), 52 deletions(-) diff --git a/library/compiler-builtins/libm-test/src/precision.rs b/library/compiler-builtins/libm-test/src/precision.rs index 32825b15d476..3fb8c1b37109 100644 --- a/library/compiler-builtins/libm-test/src/precision.rs +++ b/library/compiler-builtins/libm-test/src/precision.rs @@ -271,18 +271,6 @@ impl MaybeOverride<(f32,)> for SpecialCase { impl MaybeOverride<(f64,)> for SpecialCase { fn check_float(input: (f64,), actual: F, expected: F, ctx: &CheckCtx) -> CheckAction { - if cfg!(x86_no_sse) - && ctx.base_name == BaseName::Ceil - && ctx.basis == CheckBasis::Musl - && input.0 < 0.0 - && input.0 > -1.0 - && expected == F::ZERO - && actual == F::ZERO - { - // musl returns -0.0, we return +0.0 - return XFAIL("i586 ceil signed zero"); - } - if cfg!(x86_no_sse) && (ctx.base_name == BaseName::Rint || ctx.base_name == BaseName::Roundeven) && (expected - actual).abs() <= F::ONE @@ -292,16 +280,6 @@ impl MaybeOverride<(f64,)> for SpecialCase { return XFAIL("i586 rint rounding mode"); } - if cfg!(x86_no_sse) - && (ctx.fn_ident == Identifier::Ceil || ctx.fn_ident == Identifier::Floor) - && expected.eq_repr(F::NEG_ZERO) - && actual.eq_repr(F::ZERO) - { - // FIXME: the x87 implementations do not keep the distinction between -0.0 and 0.0. - // See https://github.com/rust-lang/libm/pull/404#issuecomment-2572399955 - return XFAIL("i586 ceil/floor signed zero"); - } - if cfg!(x86_no_sse) && (ctx.fn_ident == Identifier::Exp10 || ctx.fn_ident == Identifier::Exp2) { diff --git a/library/compiler-builtins/libm/src/math/arch/i586.rs b/library/compiler-builtins/libm/src/math/arch/i586.rs index f92b9a2af711..b9a66762063d 100644 --- a/library/compiler-builtins/libm/src/math/arch/i586.rs +++ b/library/compiler-builtins/libm/src/math/arch/i586.rs @@ -1,37 +1,62 @@ //! Architecture-specific support for x86-32 without SSE2 +//! +//! We use an alternative implementation on x86, because the +//! main implementation fails with the x87 FPU used by +//! debian i386, probably due to excess precision issues. +//! +//! See https://github.com/rust-lang/compiler-builtins/pull/976 for discussion on why these +//! functions are implemented in this way. -use super::super::fabs; - -/// Use an alternative implementation on x86, because the -/// main implementation fails with the x87 FPU used by -/// debian i386, probably due to excess precision issues. -/// Basic implementation taken from https://github.com/rust-lang/libm/issues/219. -pub fn ceil(x: f64) -> f64 { - if fabs(x).to_bits() < 4503599627370496.0_f64.to_bits() { - let truncated = x as i64 as f64; - if truncated < x { - return truncated + 1.0; - } else { - return truncated; - } - } else { - return x; +pub fn ceil(mut x: f64) -> f64 { + unsafe { + core::arch::asm!( + "fld qword ptr [{x}]", + // Save the FPU control word, using `x` as scratch space. + "fstcw [{x}]", + // Set rounding control to 0b10 (+∞). + "mov word ptr [{x} + 2], 0x0b7f", + "fldcw [{x} + 2]", + // Round. + "frndint", + // Restore FPU control word. + "fldcw [{x}]", + // Save rounded value to memory. + "fstp qword ptr [{x}]", + x = in(reg) &mut x, + // All the x87 FPU stack is used, all registers must be clobbered + out("st(0)") _, out("st(1)") _, + out("st(2)") _, out("st(3)") _, + out("st(4)") _, out("st(5)") _, + out("st(6)") _, out("st(7)") _, + options(nostack), + ); } + x } -/// Use an alternative implementation on x86, because the -/// main implementation fails with the x87 FPU used by -/// debian i386, probably due to excess precision issues. -/// Basic implementation taken from https://github.com/rust-lang/libm/issues/219. -pub fn floor(x: f64) -> f64 { - if fabs(x).to_bits() < 4503599627370496.0_f64.to_bits() { - let truncated = x as i64 as f64; - if truncated > x { - return truncated - 1.0; - } else { - return truncated; - } - } else { - return x; +pub fn floor(mut x: f64) -> f64 { + unsafe { + core::arch::asm!( + "fld qword ptr [{x}]", + // Save the FPU control word, using `x` as scratch space. + "fstcw [{x}]", + // Set rounding control to 0b01 (-∞). + "mov word ptr [{x} + 2], 0x077f", + "fldcw [{x} + 2]", + // Round. + "frndint", + // Restore FPU control word. + "fldcw [{x}]", + // Save rounded value to memory. + "fstp qword ptr [{x}]", + x = in(reg) &mut x, + // All the x87 FPU stack is used, all registers must be clobbered + out("st(0)") _, out("st(1)") _, + out("st(2)") _, out("st(3)") _, + out("st(4)") _, out("st(5)") _, + out("st(6)") _, out("st(7)") _, + options(nostack), + ); } + x } From 16cb37c9574b35a3b54c7aa3604f328347f304ab Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Fri, 25 Jul 2025 17:36:25 -0500 Subject: [PATCH 0167/1134] Remove `no-asm` gating when there is no alternative implementation Assembly-related configuration was added in 1621c6dbf9eb ("Use `specialized-div-rem` 1.0.0 for division algorithms") to account for Cranelift not yet supporting assembly. This hasn't been relevant for a while, so we no longer need to gate `asm!` behind this configuration. Thus, remove `cfg(not(feature = "no-asm"))` in places where there is no generic fallback. There are other cases, however, where setting the `no-asm` configuration enables testing of generic version of builtins when there are platform- specific implementations available; these cases are left unchanged. This could be improved in the future by exposing both versions for testing rather than using a configuration and running the entire testsuite twice. This is the compiler-builtins portion of https://github.com/rust-lang/rust/pull/144471. --- library/compiler-builtins/builtins-shim/Cargo.toml | 5 +++-- library/compiler-builtins/builtins-test/tests/lse.rs | 2 +- library/compiler-builtins/compiler-builtins/Cargo.toml | 5 +++-- .../compiler-builtins/compiler-builtins/src/aarch64.rs | 2 +- library/compiler-builtins/compiler-builtins/src/arm.rs | 2 -- .../compiler-builtins/compiler-builtins/src/hexagon.rs | 2 -- library/compiler-builtins/compiler-builtins/src/lib.rs | 2 +- .../compiler-builtins/src/probestack.rs | 2 -- library/compiler-builtins/compiler-builtins/src/x86.rs | 10 ++-------- .../compiler-builtins/compiler-builtins/src/x86_64.rs | 9 +-------- 10 files changed, 12 insertions(+), 29 deletions(-) diff --git a/library/compiler-builtins/builtins-shim/Cargo.toml b/library/compiler-builtins/builtins-shim/Cargo.toml index 8eb880c6fd1d..707ebdbc77b2 100644 --- a/library/compiler-builtins/builtins-shim/Cargo.toml +++ b/library/compiler-builtins/builtins-shim/Cargo.toml @@ -37,8 +37,9 @@ default = ["compiler-builtins"] # implementations and also filling in unimplemented intrinsics c = ["dep:cc"] -# Workaround for the Cranelift codegen backend. Disables any implementations -# which use inline assembly and fall back to pure Rust versions (if available). +# For implementations where there is both a generic version and a platform- +# specific version, use the generic version. This is meant to enable testing +# the generic versions on all platforms. no-asm = [] # Workaround for codegen backends which haven't yet implemented `f16` and diff --git a/library/compiler-builtins/builtins-test/tests/lse.rs b/library/compiler-builtins/builtins-test/tests/lse.rs index 0d85228d7a22..5d59fbb7f44d 100644 --- a/library/compiler-builtins/builtins-test/tests/lse.rs +++ b/library/compiler-builtins/builtins-test/tests/lse.rs @@ -1,6 +1,6 @@ #![feature(decl_macro)] // so we can use pub(super) #![feature(macro_metavar_expr_concat)] -#![cfg(all(target_arch = "aarch64", target_os = "linux", not(feature = "no-asm")))] +#![cfg(all(target_arch = "aarch64", target_os = "linux"))] /// Translate a byte size to a Rust type. macro int_ty { diff --git a/library/compiler-builtins/compiler-builtins/Cargo.toml b/library/compiler-builtins/compiler-builtins/Cargo.toml index 3ccb05f73fb8..8bbe136ce33e 100644 --- a/library/compiler-builtins/compiler-builtins/Cargo.toml +++ b/library/compiler-builtins/compiler-builtins/Cargo.toml @@ -35,8 +35,9 @@ default = ["compiler-builtins"] # implementations and also filling in unimplemented intrinsics c = ["dep:cc"] -# Workaround for the Cranelift codegen backend. Disables any implementations -# which use inline assembly and fall back to pure Rust versions (if available). +# For implementations where there is both a generic version and a platform- +# specific version, use the generic version. This is meant to enable testing +# the generic versions on all platforms. no-asm = [] # Workaround for codegen backends which haven't yet implemented `f16` and diff --git a/library/compiler-builtins/compiler-builtins/src/aarch64.rs b/library/compiler-builtins/compiler-builtins/src/aarch64.rs index a72b30d29f0b..039fab2061c5 100644 --- a/library/compiler-builtins/compiler-builtins/src/aarch64.rs +++ b/library/compiler-builtins/compiler-builtins/src/aarch64.rs @@ -4,7 +4,7 @@ use core::intrinsics; intrinsics! { #[unsafe(naked)] - #[cfg(all(target_os = "uefi", not(feature = "no-asm")))] + #[cfg(target_os = "uefi")] pub unsafe extern "custom" fn __chkstk() { core::arch::naked_asm!( ".p2align 2", diff --git a/library/compiler-builtins/compiler-builtins/src/arm.rs b/library/compiler-builtins/compiler-builtins/src/arm.rs index fbec93ca4312..0c15b37df1dc 100644 --- a/library/compiler-builtins/compiler-builtins/src/arm.rs +++ b/library/compiler-builtins/compiler-builtins/src/arm.rs @@ -1,5 +1,3 @@ -#![cfg(not(feature = "no-asm"))] - // Interfaces used by naked trampolines. // SAFETY: these are defined in compiler-builtins unsafe extern "C" { diff --git a/library/compiler-builtins/compiler-builtins/src/hexagon.rs b/library/compiler-builtins/compiler-builtins/src/hexagon.rs index 91cf91c31421..a5c7b4dfdda9 100644 --- a/library/compiler-builtins/compiler-builtins/src/hexagon.rs +++ b/library/compiler-builtins/compiler-builtins/src/hexagon.rs @@ -1,5 +1,3 @@ -#![cfg(not(feature = "no-asm"))] - use core::arch::global_asm; global_asm!(include_str!("hexagon/func_macro.s"), options(raw)); diff --git a/library/compiler-builtins/compiler-builtins/src/lib.rs b/library/compiler-builtins/compiler-builtins/src/lib.rs index fe0ad81dd3a3..ca75f44e02a9 100644 --- a/library/compiler-builtins/compiler-builtins/src/lib.rs +++ b/library/compiler-builtins/compiler-builtins/src/lib.rs @@ -60,7 +60,7 @@ pub mod arm; #[cfg(any(target_arch = "aarch64", target_arch = "arm64ec"))] pub mod aarch64; -#[cfg(all(target_arch = "aarch64", target_os = "linux", not(feature = "no-asm"),))] +#[cfg(all(target_arch = "aarch64", target_os = "linux"))] pub mod aarch64_linux; #[cfg(all( diff --git a/library/compiler-builtins/compiler-builtins/src/probestack.rs b/library/compiler-builtins/compiler-builtins/src/probestack.rs index f4105dde57e6..9a18216da99a 100644 --- a/library/compiler-builtins/compiler-builtins/src/probestack.rs +++ b/library/compiler-builtins/compiler-builtins/src/probestack.rs @@ -44,8 +44,6 @@ #![cfg(not(feature = "mangled-names"))] // Windows and Cygwin already has builtins to do this. #![cfg(not(any(windows, target_os = "cygwin")))] -// All these builtins require assembly -#![cfg(not(feature = "no-asm"))] // We only define stack probing for these architectures today. #![cfg(any(target_arch = "x86_64", target_arch = "x86"))] diff --git a/library/compiler-builtins/compiler-builtins/src/x86.rs b/library/compiler-builtins/compiler-builtins/src/x86.rs index 16e50922a945..51940b3b338a 100644 --- a/library/compiler-builtins/compiler-builtins/src/x86.rs +++ b/library/compiler-builtins/compiler-builtins/src/x86.rs @@ -9,10 +9,7 @@ use core::intrinsics; intrinsics! { #[unsafe(naked)] - #[cfg(all( - any(all(windows, target_env = "gnu"), target_os = "uefi"), - not(feature = "no-asm") - ))] + #[cfg(any(all(windows, target_env = "gnu"), target_os = "uefi"))] pub unsafe extern "custom" fn __chkstk() { core::arch::naked_asm!( "jmp {}", // Jump to __alloca since fallthrough may be unreliable" @@ -21,10 +18,7 @@ intrinsics! { } #[unsafe(naked)] - #[cfg(all( - any(all(windows, target_env = "gnu"), target_os = "uefi"), - not(feature = "no-asm") - ))] + #[cfg(any(all(windows, target_env = "gnu"), target_os = "uefi"))] pub unsafe extern "custom" fn _alloca() { // __chkstk and _alloca are the same function core::arch::naked_asm!( diff --git a/library/compiler-builtins/compiler-builtins/src/x86_64.rs b/library/compiler-builtins/compiler-builtins/src/x86_64.rs index 9b7133b482e4..f9ae784d5752 100644 --- a/library/compiler-builtins/compiler-builtins/src/x86_64.rs +++ b/library/compiler-builtins/compiler-builtins/src/x86_64.rs @@ -9,14 +9,7 @@ use core::intrinsics; intrinsics! { #[unsafe(naked)] - #[cfg(all( - any( - all(windows, target_env = "gnu"), - target_os = "cygwin", - target_os = "uefi" - ), - not(feature = "no-asm") - ))] + #[cfg(any(all(windows, target_env = "gnu"), target_os = "cygwin", target_os = "uefi"))] pub unsafe extern "custom" fn ___chkstk_ms() { core::arch::naked_asm!( "push %rcx", From 6bf3cbe39e09f4d9187a0b1f6a7bd45101f7aad8 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Mon, 28 Jul 2025 00:01:28 +0300 Subject: [PATCH 0168/1134] In rustc_pattern_analysis, put `true` witnesses before `false` witnesses In rustc it doesn't really matter what the order of the witnesses is, but I'm planning to use the witnesses for implementing the "add missing match arms" assist in rust-analyzer, and there `true` before `false` is the natural order (like `Some` before `None`), and also what the current assist does. The current order doesn't seem to be intentional; the code was created when bool ctors became their own thing, not just int ctors, but for integer, 0 before 1 is indeed the natural order. --- compiler/rustc_pattern_analysis/src/constructor.rs | 10 +++++----- .../rustc_pattern_analysis/tests/exhaustiveness.rs | 3 +++ .../deref-patterns/usefulness/non-exhaustive.rs | 2 +- .../deref-patterns/usefulness/non-exhaustive.stderr | 6 +++--- tests/ui/pattern/usefulness/unions.rs | 2 +- tests/ui/pattern/usefulness/unions.stderr | 4 ++-- 6 files changed, 15 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_pattern_analysis/src/constructor.rs b/compiler/rustc_pattern_analysis/src/constructor.rs index 9a9e0db964c9..12f653a13371 100644 --- a/compiler/rustc_pattern_analysis/src/constructor.rs +++ b/compiler/rustc_pattern_analysis/src/constructor.rs @@ -1130,16 +1130,16 @@ impl ConstructorSet { seen_false = true; } } - if seen_false { - present.push(Bool(false)); - } else { - missing.push(Bool(false)); - } if seen_true { present.push(Bool(true)); } else { missing.push(Bool(true)); } + if seen_false { + present.push(Bool(false)); + } else { + missing.push(Bool(false)); + } } ConstructorSet::Integers { range_1, range_2 } => { let seen_ranges: Vec<_> = diff --git a/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs b/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs index 14ca0d057f06..4ad64f81560a 100644 --- a/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs +++ b/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs @@ -176,6 +176,9 @@ fn test_witnesses() { ), vec!["Enum::Variant1(_)", "Enum::Variant2(_)", "_"], ); + + // Assert we put `true` before `false`. + assert_witnesses(AllOfThem, Ty::Bool, Vec::new(), vec!["true", "false"]); } #[test] diff --git a/tests/ui/pattern/deref-patterns/usefulness/non-exhaustive.rs b/tests/ui/pattern/deref-patterns/usefulness/non-exhaustive.rs index 704cae8bdbc4..bab6308223e5 100644 --- a/tests/ui/pattern/deref-patterns/usefulness/non-exhaustive.rs +++ b/tests/ui/pattern/deref-patterns/usefulness/non-exhaustive.rs @@ -15,7 +15,7 @@ fn main() { } match Box::new((true, Box::new(false))) { - //~^ ERROR non-exhaustive patterns: `deref!((false, deref!(false)))` and `deref!((true, deref!(true)))` not covered + //~^ ERROR non-exhaustive patterns: `deref!((true, deref!(true)))` and `deref!((false, deref!(false)))` not covered (true, false) => {} (false, true) => {} } diff --git a/tests/ui/pattern/deref-patterns/usefulness/non-exhaustive.stderr b/tests/ui/pattern/deref-patterns/usefulness/non-exhaustive.stderr index 55fa84bafde2..a1abd5f0e3f4 100644 --- a/tests/ui/pattern/deref-patterns/usefulness/non-exhaustive.stderr +++ b/tests/ui/pattern/deref-patterns/usefulness/non-exhaustive.stderr @@ -28,11 +28,11 @@ LL ~ true => {}, LL + deref!(deref!(false)) => todo!() | -error[E0004]: non-exhaustive patterns: `deref!((false, deref!(false)))` and `deref!((true, deref!(true)))` not covered +error[E0004]: non-exhaustive patterns: `deref!((true, deref!(true)))` and `deref!((false, deref!(false)))` not covered --> $DIR/non-exhaustive.rs:17:11 | LL | match Box::new((true, Box::new(false))) { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ patterns `deref!((false, deref!(false)))` and `deref!((true, deref!(true)))` not covered + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ patterns `deref!((true, deref!(true)))` and `deref!((false, deref!(false)))` not covered | note: `Box<(bool, Box)>` defined here --> $SRC_DIR/alloc/src/boxed.rs:LL:COL @@ -40,7 +40,7 @@ note: `Box<(bool, Box)>` defined here help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern, a match arm with multiple or-patterns as shown, or multiple match arms | LL ~ (false, true) => {}, -LL + deref!((false, deref!(false))) | deref!((true, deref!(true))) => todo!() +LL + deref!((true, deref!(true))) | deref!((false, deref!(false))) => todo!() | error[E0004]: non-exhaustive patterns: `deref!((deref!(T::C), _))` not covered diff --git a/tests/ui/pattern/usefulness/unions.rs b/tests/ui/pattern/usefulness/unions.rs index 80a7f36a09a2..3de79c6f8495 100644 --- a/tests/ui/pattern/usefulness/unions.rs +++ b/tests/ui/pattern/usefulness/unions.rs @@ -26,7 +26,7 @@ fn main() { } // Our approach can report duplicate witnesses sometimes. match (x, true) { - //~^ ERROR non-exhaustive patterns: `(U8AsBool { n: 0_u8 }, false)`, `(U8AsBool { b: false }, false)`, `(U8AsBool { n: 0_u8 }, false)` and 1 more not covered + //~^ ERROR non-exhaustive patterns: `(U8AsBool { n: 0_u8 }, false)`, `(U8AsBool { b: true }, false)`, `(U8AsBool { n: 0_u8 }, false)` and 1 more not covered (U8AsBool { b: true }, true) => {} (U8AsBool { b: false }, true) => {} (U8AsBool { n: 1.. }, true) => {} diff --git a/tests/ui/pattern/usefulness/unions.stderr b/tests/ui/pattern/usefulness/unions.stderr index 4b397dc25db8..98fb6a33ae41 100644 --- a/tests/ui/pattern/usefulness/unions.stderr +++ b/tests/ui/pattern/usefulness/unions.stderr @@ -16,11 +16,11 @@ LL ~ U8AsBool { n: 1.. } => {}, LL + U8AsBool { n: 0_u8 } | U8AsBool { b: false } => todo!() | -error[E0004]: non-exhaustive patterns: `(U8AsBool { n: 0_u8 }, false)`, `(U8AsBool { b: false }, false)`, `(U8AsBool { n: 0_u8 }, false)` and 1 more not covered +error[E0004]: non-exhaustive patterns: `(U8AsBool { n: 0_u8 }, false)`, `(U8AsBool { b: true }, false)`, `(U8AsBool { n: 0_u8 }, false)` and 1 more not covered --> $DIR/unions.rs:28:15 | LL | match (x, true) { - | ^^^^^^^^^ patterns `(U8AsBool { n: 0_u8 }, false)`, `(U8AsBool { b: false }, false)`, `(U8AsBool { n: 0_u8 }, false)` and 1 more not covered + | ^^^^^^^^^ patterns `(U8AsBool { n: 0_u8 }, false)`, `(U8AsBool { b: true }, false)`, `(U8AsBool { n: 0_u8 }, false)` and 1 more not covered | = note: the matched value is of type `(U8AsBool, bool)` help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern as shown, or multiple match arms From 3e6f950d66008a7a15f38d10d5b19707c06602c7 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Thu, 17 Jul 2025 06:09:15 +0200 Subject: [PATCH 0169/1134] avoid the need to specify if toc should be generated - this removes one external dependency, mdbook-toc - this steals code from rustc book --- .../rustc-dev-guide/.github/workflows/ci.yml | 4 +- src/doc/rustc-dev-guide/README.md | 6 +- src/doc/rustc-dev-guide/book.toml | 11 +- src/doc/rustc-dev-guide/pagetoc.css | 84 ++++++++++++++ src/doc/rustc-dev-guide/pagetoc.js | 104 ++++++++++++++++++ 5 files changed, 198 insertions(+), 11 deletions(-) create mode 100644 src/doc/rustc-dev-guide/pagetoc.css create mode 100644 src/doc/rustc-dev-guide/pagetoc.js diff --git a/src/doc/rustc-dev-guide/.github/workflows/ci.yml b/src/doc/rustc-dev-guide/.github/workflows/ci.yml index daf5223cbd4a..6eabb999fb01 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/ci.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/ci.yml @@ -17,7 +17,6 @@ jobs: MDBOOK_VERSION: 0.4.48 MDBOOK_LINKCHECK2_VERSION: 0.9.1 MDBOOK_MERMAID_VERSION: 0.12.6 - MDBOOK_TOC_VERSION: 0.11.2 MDBOOK_OUTPUT__LINKCHECK__FOLLOW_WEB_LINKS: ${{ github.event_name != 'pull_request' }} DEPLOY_DIR: book/html BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -34,7 +33,7 @@ jobs: with: path: | ~/.cargo/bin - key: ${{ runner.os }}-${{ env.MDBOOK_VERSION }}--${{ env.MDBOOK_LINKCHECK2_VERSION }}--${{ env.MDBOOK_TOC_VERSION }}--${{ env.MDBOOK_MERMAID_VERSION }} + key: ${{ runner.os }}-${{ env.MDBOOK_VERSION }}--${{ env.MDBOOK_LINKCHECK2_VERSION }}--${{ env.MDBOOK_MERMAID_VERSION }} - name: Restore cached Linkcheck if: github.event_name == 'schedule' @@ -57,7 +56,6 @@ jobs: run: | cargo install mdbook --version ${{ env.MDBOOK_VERSION }} cargo install mdbook-linkcheck2 --version ${{ env.MDBOOK_LINKCHECK2_VERSION }} - cargo install mdbook-toc --version ${{ env.MDBOOK_TOC_VERSION }} cargo install mdbook-mermaid --version ${{ env.MDBOOK_MERMAID_VERSION }} - name: Check build diff --git a/src/doc/rustc-dev-guide/README.md b/src/doc/rustc-dev-guide/README.md index 5932da467ab2..1ad895aeda2e 100644 --- a/src/doc/rustc-dev-guide/README.md +++ b/src/doc/rustc-dev-guide/README.md @@ -43,7 +43,7 @@ rustdocs][rustdocs]. To build a local static HTML site, install [`mdbook`](https://github.com/rust-lang/mdBook) with: ``` -cargo install mdbook mdbook-linkcheck2 mdbook-toc mdbook-mermaid +cargo install mdbook mdbook-linkcheck2 mdbook-mermaid ``` and execute the following command in the root of the repository: @@ -67,8 +67,8 @@ ENABLE_LINKCHECK=1 mdbook serve ### Table of Contents -We use `mdbook-toc` to auto-generate TOCs for long sections. You can invoke the preprocessor by -including the `` marker at the place where you want the TOC. +Each page has a TOC that is automatically generated by `pagetoc.js`. +There is an associated `pagetoc.css`, for styling. ## Synchronizing josh subtree with rustc diff --git a/src/doc/rustc-dev-guide/book.toml b/src/doc/rustc-dev-guide/book.toml index b84b1e7548a8..daf237ed9081 100644 --- a/src/doc/rustc-dev-guide/book.toml +++ b/src/doc/rustc-dev-guide/book.toml @@ -6,17 +6,18 @@ description = "A guide to developing the Rust compiler (rustc)" [build] create-missing = false -[preprocessor.toc] -command = "mdbook-toc" -renderer = ["html"] - [preprocessor.mermaid] command = "mdbook-mermaid" [output.html] git-repository-url = "https://github.com/rust-lang/rustc-dev-guide" edit-url-template = "https://github.com/rust-lang/rustc-dev-guide/edit/master/{path}" -additional-js = ["mermaid.min.js", "mermaid-init.js"] +additional-js = [ + "mermaid.min.js", + "mermaid-init.js", + "pagetoc.js", +] +additional-css = ["pagetoc.css"] [output.html.search] use-boolean-and = true diff --git a/src/doc/rustc-dev-guide/pagetoc.css b/src/doc/rustc-dev-guide/pagetoc.css new file mode 100644 index 000000000000..fa709194f375 --- /dev/null +++ b/src/doc/rustc-dev-guide/pagetoc.css @@ -0,0 +1,84 @@ +/* Inspired by https://github.com/JorelAli/mdBook-pagetoc/tree/98ee241 (under WTFPL) */ + +:root { + --toc-width: 270px; + --center-content-toc-shift: calc(-1 * var(--toc-width) / 2); +} + +.nav-chapters { + /* adjust width of buttons that bring to the previous or the next page */ + min-width: 50px; +} + +@media only screen { + @media (max-width: 1179px) { + .sidebar-hidden #sidetoc { + display: none; + } + } + + @media (max-width: 1439px) { + .sidebar-visible #sidetoc { + display: none; + } + } + + @media (1180px <= width <= 1439px) { + .sidebar-hidden main { + position: relative; + left: var(--center-content-toc-shift); + } + } + + @media (1440px <= width <= 1700px) { + .sidebar-visible main { + position: relative; + left: var(--center-content-toc-shift); + } + } + + #sidetoc { + margin-left: calc(100% + 20px); + } + #pagetoc { + position: fixed; + /* adjust TOC width */ + width: var(--toc-width); + height: calc(100vh - var(--menu-bar-height) - 0.67em * 4); + overflow: auto; + } + #pagetoc a { + border-left: 1px solid var(--sidebar-bg); + color: var(--fg); + display: block; + padding-bottom: 5px; + padding-top: 5px; + padding-left: 10px; + text-align: left; + text-decoration: none; + } + #pagetoc a:hover, + #pagetoc a.active { + background: var(--sidebar-bg); + color: var(--sidebar-active) !important; + } + #pagetoc .active { + background: var(--sidebar-bg); + color: var(--sidebar-active); + } + #pagetoc .pagetoc-H2 { + padding-left: 20px; + } + #pagetoc .pagetoc-H3 { + padding-left: 40px; + } + #pagetoc .pagetoc-H4 { + padding-left: 60px; + } +} + +@media print { + #sidetoc { + display: none; + } +} diff --git a/src/doc/rustc-dev-guide/pagetoc.js b/src/doc/rustc-dev-guide/pagetoc.js new file mode 100644 index 000000000000..927a5b10749b --- /dev/null +++ b/src/doc/rustc-dev-guide/pagetoc.js @@ -0,0 +1,104 @@ +// Inspired by https://github.com/JorelAli/mdBook-pagetoc/tree/98ee241 (under WTFPL) + +let activeHref = location.href; +function updatePageToc(elem = undefined) { + let selectedPageTocElem = elem; + const pagetoc = document.getElementById("pagetoc"); + + function getRect(element) { + return element.getBoundingClientRect(); + } + + function overflowTop(container, element) { + return getRect(container).top - getRect(element).top; + } + + function overflowBottom(container, element) { + return getRect(container).bottom - getRect(element).bottom; + } + + // We've not selected a heading to highlight, and the URL needs updating + // so we need to find a heading based on the URL + if (selectedPageTocElem === undefined && location.href !== activeHref) { + activeHref = location.href; + for (const pageTocElement of pagetoc.children) { + if (pageTocElement.href === activeHref) { + selectedPageTocElem = pageTocElement; + } + } + } + + // We still don't have a selected heading, let's try and find the most + // suitable heading based on the scroll position + if (selectedPageTocElem === undefined) { + const margin = window.innerHeight / 3; + + const headers = document.getElementsByClassName("header"); + for (let i = 0; i < headers.length; i++) { + const header = headers[i]; + if (selectedPageTocElem === undefined && getRect(header).top >= 0) { + if (getRect(header).top < margin) { + selectedPageTocElem = header; + } else { + selectedPageTocElem = headers[Math.max(0, i - 1)]; + } + } + // a very long last section's heading is over the screen + if (selectedPageTocElem === undefined && i === headers.length - 1) { + selectedPageTocElem = header; + } + } + } + + // Remove the active flag from all pagetoc elements + for (const pageTocElement of pagetoc.children) { + pageTocElement.classList.remove("active"); + } + + // If we have a selected heading, set it to active and scroll to it + if (selectedPageTocElem !== undefined) { + for (const pageTocElement of pagetoc.children) { + if (selectedPageTocElem.href.localeCompare(pageTocElement.href) === 0) { + pageTocElement.classList.add("active"); + if (overflowTop(pagetoc, pageTocElement) > 0) { + pagetoc.scrollTop = pageTocElement.offsetTop; + } + if (overflowBottom(pagetoc, pageTocElement) < 0) { + pagetoc.scrollTop -= overflowBottom(pagetoc, pageTocElement); + } + } + } + } +} + +if (document.getElementById("sidetoc") === null && + document.getElementsByClassName("header").length > 0) { + // The sidetoc element doesn't exist yet, let's create it + + // Create the empty sidetoc and pagetoc elements + const sidetoc = document.createElement("div"); + const pagetoc = document.createElement("div"); + sidetoc.id = "sidetoc"; + pagetoc.id = "pagetoc"; + sidetoc.appendChild(pagetoc); + + // And append them to the current DOM + const main = document.querySelector('main'); + main.insertBefore(sidetoc, main.firstChild); + + // Populate sidebar on load + window.addEventListener("load", () => { + for (const header of document.getElementsByClassName("header")) { + const link = document.createElement("a"); + link.innerHTML = header.innerHTML; + link.href = header.hash; + link.classList.add("pagetoc-" + header.parentElement.tagName); + document.getElementById("pagetoc").appendChild(link); + link.onclick = () => updatePageToc(link); + } + updatePageToc(); + }); + + // Update page table of contents selected heading on scroll + window.addEventListener("scroll", () => updatePageToc()); +} From 65589ad33f544003e49cabeb0b76f6b1f0d3ce30 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Mon, 28 Jul 2025 11:45:21 +0200 Subject: [PATCH 0170/1134] remove the markers --- src/doc/rustc-dev-guide/src/asm.md | 2 -- src/doc/rustc-dev-guide/src/backend/backend-agnostic.md | 2 -- src/doc/rustc-dev-guide/src/backend/implicit-caller-location.md | 2 -- src/doc/rustc-dev-guide/src/backend/monomorph.md | 2 -- src/doc/rustc-dev-guide/src/backend/updating-llvm.md | 2 -- .../src/borrow_check/moves_and_initialization/move_paths.md | 2 -- src/doc/rustc-dev-guide/src/borrow_check/region_inference.md | 2 -- .../src/borrow_check/region_inference/constraint_propagation.md | 2 -- .../src/borrow_check/region_inference/lifetime_parameters.md | 2 -- .../src/borrow_check/region_inference/member_constraints.md | 2 -- .../borrow_check/region_inference/placeholders_and_universes.md | 2 -- src/doc/rustc-dev-guide/src/bug-fix-procedure.md | 2 -- .../src/building/bootstrapping/what-bootstrapping-does.md | 2 -- src/doc/rustc-dev-guide/src/building/how-to-build-and-run.md | 2 -- src/doc/rustc-dev-guide/src/building/new-target.md | 2 -- src/doc/rustc-dev-guide/src/building/optimized-build.md | 2 -- src/doc/rustc-dev-guide/src/building/suggested.md | 2 -- src/doc/rustc-dev-guide/src/compiler-debugging.md | 2 -- src/doc/rustc-dev-guide/src/compiler-src.md | 2 -- src/doc/rustc-dev-guide/src/const-eval/interpret.md | 2 -- src/doc/rustc-dev-guide/src/contributing.md | 2 -- src/doc/rustc-dev-guide/src/coroutine-closures.md | 2 -- src/doc/rustc-dev-guide/src/debugging-support-in-rustc.md | 2 -- src/doc/rustc-dev-guide/src/diagnostics.md | 2 -- src/doc/rustc-dev-guide/src/early_late_parameters.md | 2 -- src/doc/rustc-dev-guide/src/getting-started.md | 2 -- src/doc/rustc-dev-guide/src/git.md | 2 -- src/doc/rustc-dev-guide/src/guides/editions.md | 2 -- src/doc/rustc-dev-guide/src/hir.md | 2 -- src/doc/rustc-dev-guide/src/implementing_new_features.md | 2 -- src/doc/rustc-dev-guide/src/llvm-coverage-instrumentation.md | 2 -- src/doc/rustc-dev-guide/src/macro-expansion.md | 2 -- src/doc/rustc-dev-guide/src/mir/construction.md | 2 -- src/doc/rustc-dev-guide/src/mir/dataflow.md | 2 -- src/doc/rustc-dev-guide/src/mir/drop-elaboration.md | 2 -- src/doc/rustc-dev-guide/src/mir/index.md | 2 -- src/doc/rustc-dev-guide/src/name-resolution.md | 2 -- src/doc/rustc-dev-guide/src/normalization.md | 2 -- src/doc/rustc-dev-guide/src/overview.md | 2 -- src/doc/rustc-dev-guide/src/panic-implementation.md | 2 -- src/doc/rustc-dev-guide/src/profile-guided-optimization.md | 2 -- .../src/queries/incremental-compilation-in-detail.md | 2 -- src/doc/rustc-dev-guide/src/queries/incremental-compilation.md | 2 -- .../src/queries/query-evaluation-model-in-detail.md | 2 -- src/doc/rustc-dev-guide/src/queries/salsa.md | 2 -- src/doc/rustc-dev-guide/src/query.md | 2 -- src/doc/rustc-dev-guide/src/rustdoc-internals.md | 2 -- src/doc/rustc-dev-guide/src/rustdoc-internals/search.md | 2 -- src/doc/rustc-dev-guide/src/rustdoc.md | 2 -- src/doc/rustc-dev-guide/src/stability.md | 2 -- src/doc/rustc-dev-guide/src/stabilization_guide.md | 2 -- src/doc/rustc-dev-guide/src/test-implementation.md | 2 -- src/doc/rustc-dev-guide/src/tests/adding.md | 2 -- src/doc/rustc-dev-guide/src/tests/compiletest.md | 2 -- src/doc/rustc-dev-guide/src/tests/directives.md | 2 -- src/doc/rustc-dev-guide/src/tests/intro.md | 2 -- src/doc/rustc-dev-guide/src/tests/running.md | 2 -- src/doc/rustc-dev-guide/src/tests/ui.md | 2 -- src/doc/rustc-dev-guide/src/thir.md | 2 -- src/doc/rustc-dev-guide/src/tracing.md | 2 -- src/doc/rustc-dev-guide/src/traits/goals-and-clauses.md | 2 -- src/doc/rustc-dev-guide/src/traits/lowering-to-logic.md | 2 -- src/doc/rustc-dev-guide/src/traits/resolution.md | 2 -- src/doc/rustc-dev-guide/src/ty.md | 2 -- src/doc/rustc-dev-guide/src/type-inference.md | 2 -- src/doc/rustc-dev-guide/src/typing_parameter_envs.md | 2 -- src/doc/rustc-dev-guide/src/variance.md | 2 -- src/doc/rustc-dev-guide/src/walkthrough.md | 2 -- 68 files changed, 136 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/asm.md b/src/doc/rustc-dev-guide/src/asm.md index 1bb493e73d58..b5857d5465e1 100644 --- a/src/doc/rustc-dev-guide/src/asm.md +++ b/src/doc/rustc-dev-guide/src/asm.md @@ -1,7 +1,5 @@ # Inline assembly - - ## Overview Inline assembly in rustc mostly revolves around taking an `asm!` macro invocation and plumbing it diff --git a/src/doc/rustc-dev-guide/src/backend/backend-agnostic.md b/src/doc/rustc-dev-guide/src/backend/backend-agnostic.md index 0f81d3cb48a1..2fdda4eda99a 100644 --- a/src/doc/rustc-dev-guide/src/backend/backend-agnostic.md +++ b/src/doc/rustc-dev-guide/src/backend/backend-agnostic.md @@ -1,7 +1,5 @@ # Backend Agnostic Codegen - - [`rustc_codegen_ssa`] provides an abstract interface for all backends to implement, namely LLVM, [Cranelift], and [GCC]. diff --git a/src/doc/rustc-dev-guide/src/backend/implicit-caller-location.md b/src/doc/rustc-dev-guide/src/backend/implicit-caller-location.md index c5ee00813a34..9ca4bcab078e 100644 --- a/src/doc/rustc-dev-guide/src/backend/implicit-caller-location.md +++ b/src/doc/rustc-dev-guide/src/backend/implicit-caller-location.md @@ -1,7 +1,5 @@ # Implicit caller location - - Approved in [RFC 2091], this feature enables the accurate reporting of caller location during panics initiated from functions like `Option::unwrap`, `Result::expect`, and `Index::index`. This feature adds the [`#[track_caller]`][attr-reference] attribute for functions, the diff --git a/src/doc/rustc-dev-guide/src/backend/monomorph.md b/src/doc/rustc-dev-guide/src/backend/monomorph.md index 7ebb4d2b1e81..e9d98597ee0d 100644 --- a/src/doc/rustc-dev-guide/src/backend/monomorph.md +++ b/src/doc/rustc-dev-guide/src/backend/monomorph.md @@ -1,7 +1,5 @@ # Monomorphization - - As you probably know, Rust has a very expressive type system that has extensive support for generic types. But of course, assembly is not generic, so we need to figure out the concrete types of all the generics before the code can diff --git a/src/doc/rustc-dev-guide/src/backend/updating-llvm.md b/src/doc/rustc-dev-guide/src/backend/updating-llvm.md index 18c822aad790..ebef15d40baf 100644 --- a/src/doc/rustc-dev-guide/src/backend/updating-llvm.md +++ b/src/doc/rustc-dev-guide/src/backend/updating-llvm.md @@ -1,7 +1,5 @@ # Updating LLVM - - Rust supports building against multiple LLVM versions: diff --git a/src/doc/rustc-dev-guide/src/borrow_check/moves_and_initialization/move_paths.md b/src/doc/rustc-dev-guide/src/borrow_check/moves_and_initialization/move_paths.md index ad9c75d62960..95518fbc0184 100644 --- a/src/doc/rustc-dev-guide/src/borrow_check/moves_and_initialization/move_paths.md +++ b/src/doc/rustc-dev-guide/src/borrow_check/moves_and_initialization/move_paths.md @@ -1,7 +1,5 @@ # Move paths - - In reality, it's not enough to track initialization at the granularity of local variables. Rust also allows us to do moves and initialization at the field granularity: diff --git a/src/doc/rustc-dev-guide/src/borrow_check/region_inference.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference.md index 85e71b4fa429..0d55ab955836 100644 --- a/src/doc/rustc-dev-guide/src/borrow_check/region_inference.md +++ b/src/doc/rustc-dev-guide/src/borrow_check/region_inference.md @@ -1,7 +1,5 @@ # Region inference (NLL) - - The MIR-based region checking code is located in [the `rustc_mir::borrow_check` module][nll]. diff --git a/src/doc/rustc-dev-guide/src/borrow_check/region_inference/constraint_propagation.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/constraint_propagation.md index 4c30d25e0406..c3f8c03cb29f 100644 --- a/src/doc/rustc-dev-guide/src/borrow_check/region_inference/constraint_propagation.md +++ b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/constraint_propagation.md @@ -1,7 +1,5 @@ # Constraint propagation - - The main work of the region inference is **constraint propagation**, which is done in the [`propagate_constraints`] function. There are three sorts of constraints that are used in NLL, and we'll explain how diff --git a/src/doc/rustc-dev-guide/src/borrow_check/region_inference/lifetime_parameters.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/lifetime_parameters.md index fadfac404569..2d337dbc020f 100644 --- a/src/doc/rustc-dev-guide/src/borrow_check/region_inference/lifetime_parameters.md +++ b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/lifetime_parameters.md @@ -1,7 +1,5 @@ # Universal regions - - "Universal regions" is the name that the code uses to refer to "named lifetimes" -- e.g., lifetime parameters and `'static`. The name derives from the fact that such lifetimes are "universally quantified" diff --git a/src/doc/rustc-dev-guide/src/borrow_check/region_inference/member_constraints.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/member_constraints.md index fd7c87ffcea7..2804c97724f5 100644 --- a/src/doc/rustc-dev-guide/src/borrow_check/region_inference/member_constraints.md +++ b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/member_constraints.md @@ -1,7 +1,5 @@ # Member constraints - - A member constraint `'m member of ['c_1..'c_N]` expresses that the region `'m` must be *equal* to some **choice regions** `'c_i` (for some `i`). These constraints cannot be expressed by users, but they diff --git a/src/doc/rustc-dev-guide/src/borrow_check/region_inference/placeholders_and_universes.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/placeholders_and_universes.md index 91c8c4526119..11fd2a5fc7db 100644 --- a/src/doc/rustc-dev-guide/src/borrow_check/region_inference/placeholders_and_universes.md +++ b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/placeholders_and_universes.md @@ -1,7 +1,5 @@ # Placeholders and universes - - From time to time we have to reason about regions that we can't concretely know. For example, consider this program: diff --git a/src/doc/rustc-dev-guide/src/bug-fix-procedure.md b/src/doc/rustc-dev-guide/src/bug-fix-procedure.md index 55436261fdef..6b13c97023f5 100644 --- a/src/doc/rustc-dev-guide/src/bug-fix-procedure.md +++ b/src/doc/rustc-dev-guide/src/bug-fix-procedure.md @@ -1,7 +1,5 @@ # Procedures for breaking changes - - This page defines the best practices procedure for making bug fixes or soundness corrections in the compiler that can cause existing code to stop compiling. This text is based on diff --git a/src/doc/rustc-dev-guide/src/building/bootstrapping/what-bootstrapping-does.md b/src/doc/rustc-dev-guide/src/building/bootstrapping/what-bootstrapping-does.md index 2793ad438152..da425d8d39bb 100644 --- a/src/doc/rustc-dev-guide/src/building/bootstrapping/what-bootstrapping-does.md +++ b/src/doc/rustc-dev-guide/src/building/bootstrapping/what-bootstrapping-does.md @@ -1,7 +1,5 @@ # What Bootstrapping does - - [*Bootstrapping*][boot] is the process of using a compiler to compile itself. More accurately, it means using an older compiler to compile a newer version of the same compiler. diff --git a/src/doc/rustc-dev-guide/src/building/how-to-build-and-run.md b/src/doc/rustc-dev-guide/src/building/how-to-build-and-run.md index d29cd1448102..b07d3533f59b 100644 --- a/src/doc/rustc-dev-guide/src/building/how-to-build-and-run.md +++ b/src/doc/rustc-dev-guide/src/building/how-to-build-and-run.md @@ -1,7 +1,5 @@ # How to build and run the compiler - -
For `profile = "library"` users, or users who use `download-rustc = true | "if-unchanged"`, please be advised that diff --git a/src/doc/rustc-dev-guide/src/building/new-target.md b/src/doc/rustc-dev-guide/src/building/new-target.md index e11a2cd8ee57..436aec8ee265 100644 --- a/src/doc/rustc-dev-guide/src/building/new-target.md +++ b/src/doc/rustc-dev-guide/src/building/new-target.md @@ -6,8 +6,6 @@ relevant to your desired goal. See also the associated documentation in the [target tier policy]. - - [target tier policy]: https://doc.rust-lang.org/rustc/target-tier-policy.html#adding-a-new-target ## Specifying a new LLVM diff --git a/src/doc/rustc-dev-guide/src/building/optimized-build.md b/src/doc/rustc-dev-guide/src/building/optimized-build.md index 62dfaca89d24..863ed9749fb7 100644 --- a/src/doc/rustc-dev-guide/src/building/optimized-build.md +++ b/src/doc/rustc-dev-guide/src/building/optimized-build.md @@ -1,7 +1,5 @@ # Optimized build of the compiler - - There are multiple additional build configuration options and techniques that can be used to compile a build of `rustc` that is as optimized as possible (for example when building `rustc` for a Linux distribution). The status of these configuration options for various Rust targets is tracked [here]. diff --git a/src/doc/rustc-dev-guide/src/building/suggested.md b/src/doc/rustc-dev-guide/src/building/suggested.md index c046161e77f2..35c7e935b568 100644 --- a/src/doc/rustc-dev-guide/src/building/suggested.md +++ b/src/doc/rustc-dev-guide/src/building/suggested.md @@ -3,8 +3,6 @@ The full bootstrapping process takes quite a while. Here are some suggestions to make your life easier. - - ## Installing a pre-push hook CI will automatically fail your build if it doesn't pass `tidy`, our internal diff --git a/src/doc/rustc-dev-guide/src/compiler-debugging.md b/src/doc/rustc-dev-guide/src/compiler-debugging.md index 102e20207792..edd2aa6c5f64 100644 --- a/src/doc/rustc-dev-guide/src/compiler-debugging.md +++ b/src/doc/rustc-dev-guide/src/compiler-debugging.md @@ -1,7 +1,5 @@ # Debugging the compiler - - This chapter contains a few tips to debug the compiler. These tips aim to be useful no matter what you are working on. Some of the other chapters have advice about specific parts of the compiler (e.g. the [Queries Debugging and diff --git a/src/doc/rustc-dev-guide/src/compiler-src.md b/src/doc/rustc-dev-guide/src/compiler-src.md index 00aa96226849..d67bacb1b339 100644 --- a/src/doc/rustc-dev-guide/src/compiler-src.md +++ b/src/doc/rustc-dev-guide/src/compiler-src.md @@ -1,7 +1,5 @@ # High-level overview of the compiler source - - Now that we have [seen what the compiler does][orgch], let's take a look at the structure of the [`rust-lang/rust`] repository, where the rustc source code lives. diff --git a/src/doc/rustc-dev-guide/src/const-eval/interpret.md b/src/doc/rustc-dev-guide/src/const-eval/interpret.md index 51a539de5cb6..08382b12ff00 100644 --- a/src/doc/rustc-dev-guide/src/const-eval/interpret.md +++ b/src/doc/rustc-dev-guide/src/const-eval/interpret.md @@ -1,7 +1,5 @@ # Interpreter - - The interpreter is a virtual machine for executing MIR without compiling to machine code. It is usually invoked via `tcx.const_eval_*` functions. The interpreter is shared between the compiler (for compile-time function diff --git a/src/doc/rustc-dev-guide/src/contributing.md b/src/doc/rustc-dev-guide/src/contributing.md index b3fcd79ec818..963bef3af8de 100644 --- a/src/doc/rustc-dev-guide/src/contributing.md +++ b/src/doc/rustc-dev-guide/src/contributing.md @@ -1,7 +1,5 @@ # Contribution procedures - - ## Bug reports While bugs are unfortunate, they're a reality in software. We can't fix what we diff --git a/src/doc/rustc-dev-guide/src/coroutine-closures.md b/src/doc/rustc-dev-guide/src/coroutine-closures.md index 48cdba44a9f5..2617c824a391 100644 --- a/src/doc/rustc-dev-guide/src/coroutine-closures.md +++ b/src/doc/rustc-dev-guide/src/coroutine-closures.md @@ -1,7 +1,5 @@ # Async closures/"coroutine-closures" - - Please read [RFC 3668](https://rust-lang.github.io/rfcs/3668-async-closures.html) to understand the general motivation of the feature. This is a very technical and somewhat "vertical" chapter; ideally we'd split this and sprinkle it across all the relevant chapters, but for the purposes of understanding async closures *holistically*, I've put this together all here in one chapter. ## Coroutine-closures -- a technical deep dive diff --git a/src/doc/rustc-dev-guide/src/debugging-support-in-rustc.md b/src/doc/rustc-dev-guide/src/debugging-support-in-rustc.md index ac629934e0a4..bd4f795ce03b 100644 --- a/src/doc/rustc-dev-guide/src/debugging-support-in-rustc.md +++ b/src/doc/rustc-dev-guide/src/debugging-support-in-rustc.md @@ -1,7 +1,5 @@ # Debugging support in the Rust compiler - - This document explains the state of debugging tools support in the Rust compiler (rustc). It gives an overview of GDB, LLDB, WinDbg/CDB, as well as infrastructure around Rust compiler to debug Rust code. diff --git a/src/doc/rustc-dev-guide/src/diagnostics.md b/src/doc/rustc-dev-guide/src/diagnostics.md index 33f5441d36e4..82191e0a6eaf 100644 --- a/src/doc/rustc-dev-guide/src/diagnostics.md +++ b/src/doc/rustc-dev-guide/src/diagnostics.md @@ -1,7 +1,5 @@ # Errors and lints - - A lot of effort has been put into making `rustc` have great error messages. This chapter is about how to emit compile errors and lints from the compiler. diff --git a/src/doc/rustc-dev-guide/src/early_late_parameters.md b/src/doc/rustc-dev-guide/src/early_late_parameters.md index 3f94b0905668..c472bdc2c481 100644 --- a/src/doc/rustc-dev-guide/src/early_late_parameters.md +++ b/src/doc/rustc-dev-guide/src/early_late_parameters.md @@ -1,8 +1,6 @@ # Early vs Late bound parameters - - > **NOTE**: This chapter largely talks about early/late bound as being solely relevant when discussing function item types/function definitions. This is potentially not completely true, async blocks and closures should likely be discussed somewhat in this chapter. ## What does it mean to be "early" bound or "late" bound diff --git a/src/doc/rustc-dev-guide/src/getting-started.md b/src/doc/rustc-dev-guide/src/getting-started.md index d6c5c3ac8521..04d2e37732fa 100644 --- a/src/doc/rustc-dev-guide/src/getting-started.md +++ b/src/doc/rustc-dev-guide/src/getting-started.md @@ -3,8 +3,6 @@ Thank you for your interest in contributing to Rust! There are many ways to contribute, and we appreciate all of them. - - If this is your first time contributing, the [walkthrough] chapter can give you a good example of how a typical contribution would go. diff --git a/src/doc/rustc-dev-guide/src/git.md b/src/doc/rustc-dev-guide/src/git.md index 8726ddfce20c..447c6fd45467 100644 --- a/src/doc/rustc-dev-guide/src/git.md +++ b/src/doc/rustc-dev-guide/src/git.md @@ -1,7 +1,5 @@ # Using Git - - The Rust project uses [Git] to manage its source code. In order to contribute, you'll need some familiarity with its features so that your changes can be incorporated into the compiler. diff --git a/src/doc/rustc-dev-guide/src/guides/editions.md b/src/doc/rustc-dev-guide/src/guides/editions.md index 9a92d4ebcb51..b65fbb13cd18 100644 --- a/src/doc/rustc-dev-guide/src/guides/editions.md +++ b/src/doc/rustc-dev-guide/src/guides/editions.md @@ -1,7 +1,5 @@ # Editions - - This chapter gives an overview of how Edition support works in rustc. This assumes that you are familiar with what Editions are (see the [Edition Guide]). diff --git a/src/doc/rustc-dev-guide/src/hir.md b/src/doc/rustc-dev-guide/src/hir.md index 72fb10701574..38ba33112f2e 100644 --- a/src/doc/rustc-dev-guide/src/hir.md +++ b/src/doc/rustc-dev-guide/src/hir.md @@ -1,7 +1,5 @@ # The HIR - - The HIR – "High-Level Intermediate Representation" – is the primary IR used in most of rustc. It is a compiler-friendly representation of the abstract syntax tree (AST) that is generated after parsing, macro expansion, and name diff --git a/src/doc/rustc-dev-guide/src/implementing_new_features.md b/src/doc/rustc-dev-guide/src/implementing_new_features.md index 76cf2386c826..00bce8599e43 100644 --- a/src/doc/rustc-dev-guide/src/implementing_new_features.md +++ b/src/doc/rustc-dev-guide/src/implementing_new_features.md @@ -1,7 +1,5 @@ # Implementing new language features - - When you want to implement a new significant feature in the compiler, you need to go through this process to make sure everything goes smoothly. **NOTE: This section is for *language* features, not *library* features, which use [a different process].** diff --git a/src/doc/rustc-dev-guide/src/llvm-coverage-instrumentation.md b/src/doc/rustc-dev-guide/src/llvm-coverage-instrumentation.md index 880363b94bf2..288b90f33c3d 100644 --- a/src/doc/rustc-dev-guide/src/llvm-coverage-instrumentation.md +++ b/src/doc/rustc-dev-guide/src/llvm-coverage-instrumentation.md @@ -1,7 +1,5 @@ # LLVM source-based code coverage - - `rustc` supports detailed source-based code and test coverage analysis with a command line option (`-C instrument-coverage`) that instruments Rust libraries and binaries with additional instructions and data, at compile time. diff --git a/src/doc/rustc-dev-guide/src/macro-expansion.md b/src/doc/rustc-dev-guide/src/macro-expansion.md index a90f717004f0..54d6d2b4e813 100644 --- a/src/doc/rustc-dev-guide/src/macro-expansion.md +++ b/src/doc/rustc-dev-guide/src/macro-expansion.md @@ -1,7 +1,5 @@ # Macro expansion - - Rust has a very powerful macro system. In the previous chapter, we saw how the parser sets aside macros to be expanded (using temporary [placeholders]). This chapter is about the process of expanding those macros iteratively until diff --git a/src/doc/rustc-dev-guide/src/mir/construction.md b/src/doc/rustc-dev-guide/src/mir/construction.md index f2559a22b955..8360d9ff1a8b 100644 --- a/src/doc/rustc-dev-guide/src/mir/construction.md +++ b/src/doc/rustc-dev-guide/src/mir/construction.md @@ -1,7 +1,5 @@ # MIR construction - - The lowering of [HIR] to [MIR] occurs for the following (probably incomplete) list of items: diff --git a/src/doc/rustc-dev-guide/src/mir/dataflow.md b/src/doc/rustc-dev-guide/src/mir/dataflow.md index 85e57dd839b8..970e61196c12 100644 --- a/src/doc/rustc-dev-guide/src/mir/dataflow.md +++ b/src/doc/rustc-dev-guide/src/mir/dataflow.md @@ -1,7 +1,5 @@ # Dataflow Analysis - - If you work on the MIR, you will frequently come across various flavors of [dataflow analysis][wiki]. `rustc` uses dataflow to find uninitialized variables, determine what variables are live across a generator `yield` diff --git a/src/doc/rustc-dev-guide/src/mir/drop-elaboration.md b/src/doc/rustc-dev-guide/src/mir/drop-elaboration.md index 3b321fd44d1d..4da612c83f0f 100644 --- a/src/doc/rustc-dev-guide/src/mir/drop-elaboration.md +++ b/src/doc/rustc-dev-guide/src/mir/drop-elaboration.md @@ -1,7 +1,5 @@ # Drop elaboration - - ## Dynamic drops According to the [reference][reference-drop]: diff --git a/src/doc/rustc-dev-guide/src/mir/index.md b/src/doc/rustc-dev-guide/src/mir/index.md index f355875aa156..8ba5f3ac8b78 100644 --- a/src/doc/rustc-dev-guide/src/mir/index.md +++ b/src/doc/rustc-dev-guide/src/mir/index.md @@ -1,7 +1,5 @@ # The MIR (Mid-level IR) - - MIR is Rust's _Mid-level Intermediate Representation_. It is constructed from [HIR](../hir.html). MIR was introduced in [RFC 1211]. It is a radically simplified form of Rust that is used for diff --git a/src/doc/rustc-dev-guide/src/name-resolution.md b/src/doc/rustc-dev-guide/src/name-resolution.md index 719ebce85536..2e96382f7797 100644 --- a/src/doc/rustc-dev-guide/src/name-resolution.md +++ b/src/doc/rustc-dev-guide/src/name-resolution.md @@ -1,7 +1,5 @@ # Name resolution - - In the previous chapters, we saw how the [*Abstract Syntax Tree* (`AST`)][ast] is built with all macros expanded. We saw how doing that requires doing some name resolution to resolve imports and macro names. In this chapter, we show diff --git a/src/doc/rustc-dev-guide/src/normalization.md b/src/doc/rustc-dev-guide/src/normalization.md index eb0962a41223..53e20f1c0db7 100644 --- a/src/doc/rustc-dev-guide/src/normalization.md +++ b/src/doc/rustc-dev-guide/src/normalization.md @@ -1,7 +1,5 @@ # Aliases and Normalization - - ## Aliases In Rust there are a number of types that are considered equal to some "underlying" type, for example inherent associated types, trait associated types, free type aliases (`type Foo = u32`), and opaque types (`-> impl RPIT`). We consider such types to be "aliases", alias types are represented by the [`TyKind::Alias`][tykind_alias] variant, with the kind of alias tracked by the [`AliasTyKind`][aliaskind] enum. diff --git a/src/doc/rustc-dev-guide/src/overview.md b/src/doc/rustc-dev-guide/src/overview.md index 8a1a22fad660..12b76828b5c3 100644 --- a/src/doc/rustc-dev-guide/src/overview.md +++ b/src/doc/rustc-dev-guide/src/overview.md @@ -1,7 +1,5 @@ # Overview of the compiler - - This chapter is about the overall process of compiling a program -- how everything fits together. diff --git a/src/doc/rustc-dev-guide/src/panic-implementation.md b/src/doc/rustc-dev-guide/src/panic-implementation.md index 468190ffccd5..dba3f2146d23 100644 --- a/src/doc/rustc-dev-guide/src/panic-implementation.md +++ b/src/doc/rustc-dev-guide/src/panic-implementation.md @@ -1,7 +1,5 @@ # Panicking in Rust - - ## Step 1: Invocation of the `panic!` macro. There are actually two panic macros - one defined in `core`, and one defined in `std`. diff --git a/src/doc/rustc-dev-guide/src/profile-guided-optimization.md b/src/doc/rustc-dev-guide/src/profile-guided-optimization.md index 2fa810210451..4e3dadd406ec 100644 --- a/src/doc/rustc-dev-guide/src/profile-guided-optimization.md +++ b/src/doc/rustc-dev-guide/src/profile-guided-optimization.md @@ -1,7 +1,5 @@ # Profile-guided optimization - - `rustc` supports doing profile-guided optimization (PGO). This chapter describes what PGO is and how the support for it is implemented in `rustc`. diff --git a/src/doc/rustc-dev-guide/src/queries/incremental-compilation-in-detail.md b/src/doc/rustc-dev-guide/src/queries/incremental-compilation-in-detail.md index 18e0e25c5315..46e38832e64d 100644 --- a/src/doc/rustc-dev-guide/src/queries/incremental-compilation-in-detail.md +++ b/src/doc/rustc-dev-guide/src/queries/incremental-compilation-in-detail.md @@ -1,7 +1,5 @@ # Incremental compilation in detail - - The incremental compilation scheme is, in essence, a surprisingly simple extension to the overall query system. It relies on the fact that: diff --git a/src/doc/rustc-dev-guide/src/queries/incremental-compilation.md b/src/doc/rustc-dev-guide/src/queries/incremental-compilation.md index 6e5b4e8cc499..731ff3287d9f 100644 --- a/src/doc/rustc-dev-guide/src/queries/incremental-compilation.md +++ b/src/doc/rustc-dev-guide/src/queries/incremental-compilation.md @@ -1,7 +1,5 @@ # Incremental compilation - - The incremental compilation scheme is, in essence, a surprisingly simple extension to the overall query system. We'll start by describing a slightly simplified variant of the real thing – the "basic algorithm" – diff --git a/src/doc/rustc-dev-guide/src/queries/query-evaluation-model-in-detail.md b/src/doc/rustc-dev-guide/src/queries/query-evaluation-model-in-detail.md index 444e20bc580e..c1a4373f7dac 100644 --- a/src/doc/rustc-dev-guide/src/queries/query-evaluation-model-in-detail.md +++ b/src/doc/rustc-dev-guide/src/queries/query-evaluation-model-in-detail.md @@ -1,7 +1,5 @@ # The Query Evaluation Model in detail - - This chapter provides a deeper dive into the abstract model queries are built on. It does not go into implementation details but tries to explain the underlying logic. The examples here, therefore, have been stripped down and diff --git a/src/doc/rustc-dev-guide/src/queries/salsa.md b/src/doc/rustc-dev-guide/src/queries/salsa.md index 1a7b7fa9a683..dc7160edc22c 100644 --- a/src/doc/rustc-dev-guide/src/queries/salsa.md +++ b/src/doc/rustc-dev-guide/src/queries/salsa.md @@ -1,7 +1,5 @@ # How Salsa works - - This chapter is based on the explanation given by Niko Matsakis in this [video](https://www.youtube.com/watch?v=_muY4HjSqVw) about [Salsa](https://github.com/salsa-rs/salsa). To find out more you may diff --git a/src/doc/rustc-dev-guide/src/query.md b/src/doc/rustc-dev-guide/src/query.md index 0ca1b360a701..8377a7b2f31a 100644 --- a/src/doc/rustc-dev-guide/src/query.md +++ b/src/doc/rustc-dev-guide/src/query.md @@ -1,7 +1,5 @@ # Queries: demand-driven compilation - - As described in [Overview of the compiler], the Rust compiler is still (as of July 2021) transitioning from a traditional "pass-based" setup to a "demand-driven" system. The compiler query diff --git a/src/doc/rustc-dev-guide/src/rustdoc-internals.md b/src/doc/rustc-dev-guide/src/rustdoc-internals.md index 0234d4a920ed..4affbafe4777 100644 --- a/src/doc/rustc-dev-guide/src/rustdoc-internals.md +++ b/src/doc/rustc-dev-guide/src/rustdoc-internals.md @@ -1,7 +1,5 @@ # Rustdoc Internals - - This page describes [`rustdoc`]'s passes and modes. For an overview of `rustdoc`, see the ["Rustdoc overview" chapter](./rustdoc.md). diff --git a/src/doc/rustc-dev-guide/src/rustdoc-internals/search.md b/src/doc/rustc-dev-guide/src/rustdoc-internals/search.md index 3506431118ba..beff0a94c1ec 100644 --- a/src/doc/rustc-dev-guide/src/rustdoc-internals/search.md +++ b/src/doc/rustc-dev-guide/src/rustdoc-internals/search.md @@ -7,8 +7,6 @@ in the crates in the doc bundle, and the second reads it, turns it into some in-memory structures, and scans them linearly to search. - - ## Search index format `search.js` calls this Raw, because it turns it into diff --git a/src/doc/rustc-dev-guide/src/rustdoc.md b/src/doc/rustc-dev-guide/src/rustdoc.md index 52ae48c3735c..9290fcd3b41c 100644 --- a/src/doc/rustc-dev-guide/src/rustdoc.md +++ b/src/doc/rustc-dev-guide/src/rustdoc.md @@ -9,8 +9,6 @@ For more details about how rustdoc works, see the [Rustdoc internals]: ./rustdoc-internals.md - - `rustdoc` uses `rustc` internals (and, of course, the standard library), so you will have to build the compiler and `std` once before you can build `rustdoc`. diff --git a/src/doc/rustc-dev-guide/src/stability.md b/src/doc/rustc-dev-guide/src/stability.md index 230925252bac..d0cee54adb6a 100644 --- a/src/doc/rustc-dev-guide/src/stability.md +++ b/src/doc/rustc-dev-guide/src/stability.md @@ -6,8 +6,6 @@ APIs to use unstable APIs internally in the rustc standard library. **NOTE**: this section is for *library* features, not *language* features. For instructions on stabilizing a language feature see [Stabilizing Features](./stabilization_guide.md). - - ## unstable The `#[unstable(feature = "foo", issue = "1234", reason = "lorem ipsum")]` diff --git a/src/doc/rustc-dev-guide/src/stabilization_guide.md b/src/doc/rustc-dev-guide/src/stabilization_guide.md index f155272e5a2c..e399930fc523 100644 --- a/src/doc/rustc-dev-guide/src/stabilization_guide.md +++ b/src/doc/rustc-dev-guide/src/stabilization_guide.md @@ -6,8 +6,6 @@ Once an unstable feature has been well-tested with no outstanding concerns, anyone may push for its stabilization, though involving the people who have worked on it is prudent. Follow these steps: - - ## Write an RFC, if needed If the feature was part of a [lang experiment], the lang team generally will want to first accept an RFC before stabilization. diff --git a/src/doc/rustc-dev-guide/src/test-implementation.md b/src/doc/rustc-dev-guide/src/test-implementation.md index e906dd29f25f..f09d73631998 100644 --- a/src/doc/rustc-dev-guide/src/test-implementation.md +++ b/src/doc/rustc-dev-guide/src/test-implementation.md @@ -1,7 +1,5 @@ # The `#[test]` attribute - - Many Rust programmers rely on a built-in attribute called `#[test]`. All diff --git a/src/doc/rustc-dev-guide/src/tests/adding.md b/src/doc/rustc-dev-guide/src/tests/adding.md index 895eabfbd56a..e5c26bef11d0 100644 --- a/src/doc/rustc-dev-guide/src/tests/adding.md +++ b/src/doc/rustc-dev-guide/src/tests/adding.md @@ -1,7 +1,5 @@ # Adding new tests - - **In general, we expect every PR that fixes a bug in rustc to come accompanied by a regression test of some kind.** This test should fail in master but pass after the PR. These tests are really useful for preventing us from repeating the diff --git a/src/doc/rustc-dev-guide/src/tests/compiletest.md b/src/doc/rustc-dev-guide/src/tests/compiletest.md index a108dfdef9b3..4980ed845d6d 100644 --- a/src/doc/rustc-dev-guide/src/tests/compiletest.md +++ b/src/doc/rustc-dev-guide/src/tests/compiletest.md @@ -1,7 +1,5 @@ # Compiletest - - ## Introduction `compiletest` is the main test harness of the Rust test suite. It allows test diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index 5c3ae359ba0b..a16be9b48255 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -1,7 +1,5 @@ # Compiletest directives - - diff --git a/src/doc/rustc-dev-guide/src/tests/intro.md b/src/doc/rustc-dev-guide/src/tests/intro.md index 79b96c450a8d..b90c16d602c3 100644 --- a/src/doc/rustc-dev-guide/src/tests/intro.md +++ b/src/doc/rustc-dev-guide/src/tests/intro.md @@ -1,7 +1,5 @@ # Testing the compiler - - The Rust project runs a wide variety of different tests, orchestrated by the build system (`./x test`). This section gives a brief overview of the different testing tools. Subsequent chapters dive into [running tests](running.md) and diff --git a/src/doc/rustc-dev-guide/src/tests/running.md b/src/doc/rustc-dev-guide/src/tests/running.md index 6526fe9c2357..f6e313062cda 100644 --- a/src/doc/rustc-dev-guide/src/tests/running.md +++ b/src/doc/rustc-dev-guide/src/tests/running.md @@ -1,7 +1,5 @@ # Running tests - - You can run the entire test collection using `x`. But note that running the *entire* test collection is almost never what you want to do during local development because it takes a really long time. For local development, see the diff --git a/src/doc/rustc-dev-guide/src/tests/ui.md b/src/doc/rustc-dev-guide/src/tests/ui.md index 782f78d76148..c1e67e1b755c 100644 --- a/src/doc/rustc-dev-guide/src/tests/ui.md +++ b/src/doc/rustc-dev-guide/src/tests/ui.md @@ -1,7 +1,5 @@ # UI tests - - UI tests are a particular [test suite](compiletest.md#test-suites) of compiletest. diff --git a/src/doc/rustc-dev-guide/src/thir.md b/src/doc/rustc-dev-guide/src/thir.md index 73d09ad80bf9..3d3dafaef49b 100644 --- a/src/doc/rustc-dev-guide/src/thir.md +++ b/src/doc/rustc-dev-guide/src/thir.md @@ -1,7 +1,5 @@ # The THIR - - The THIR ("Typed High-Level Intermediate Representation"), previously called HAIR for "High-Level Abstract IR", is another IR used by rustc that is generated after [type checking]. It is (as of January 2024) used for diff --git a/src/doc/rustc-dev-guide/src/tracing.md b/src/doc/rustc-dev-guide/src/tracing.md index 0cfdf306e92d..5e5b81fc65b2 100644 --- a/src/doc/rustc-dev-guide/src/tracing.md +++ b/src/doc/rustc-dev-guide/src/tracing.md @@ -1,7 +1,5 @@ # Using tracing to debug the compiler - - The compiler has a lot of [`debug!`] (or `trace!`) calls, which print out logging information at many points. These are very useful to at least narrow down the location of a bug if not to find it entirely, or just to orient yourself as to why the diff --git a/src/doc/rustc-dev-guide/src/traits/goals-and-clauses.md b/src/doc/rustc-dev-guide/src/traits/goals-and-clauses.md index 40fd4581bf3e..2884ca5a05a1 100644 --- a/src/doc/rustc-dev-guide/src/traits/goals-and-clauses.md +++ b/src/doc/rustc-dev-guide/src/traits/goals-and-clauses.md @@ -1,7 +1,5 @@ # Goals and clauses - - In logic programming terms, a **goal** is something that you must prove and a **clause** is something that you know is true. As described in the [lowering to logic](./lowering-to-logic.html) diff --git a/src/doc/rustc-dev-guide/src/traits/lowering-to-logic.md b/src/doc/rustc-dev-guide/src/traits/lowering-to-logic.md index 1248d434610b..cc8b3bf800cb 100644 --- a/src/doc/rustc-dev-guide/src/traits/lowering-to-logic.md +++ b/src/doc/rustc-dev-guide/src/traits/lowering-to-logic.md @@ -1,7 +1,5 @@ # Lowering to logic - - The key observation here is that the Rust trait system is basically a kind of logic, and it can be mapped onto standard logical inference rules. We can then look for solutions to those inference rules in a diff --git a/src/doc/rustc-dev-guide/src/traits/resolution.md b/src/doc/rustc-dev-guide/src/traits/resolution.md index c62b0593694f..ccb2b04268e8 100644 --- a/src/doc/rustc-dev-guide/src/traits/resolution.md +++ b/src/doc/rustc-dev-guide/src/traits/resolution.md @@ -1,7 +1,5 @@ # Trait resolution (old-style) - - This chapter describes the general process of _trait resolution_ and points out some non-obvious things. diff --git a/src/doc/rustc-dev-guide/src/ty.md b/src/doc/rustc-dev-guide/src/ty.md index 767ac3fdba21..4055f475e992 100644 --- a/src/doc/rustc-dev-guide/src/ty.md +++ b/src/doc/rustc-dev-guide/src/ty.md @@ -1,7 +1,5 @@ # The `ty` module: representing types - - The `ty` module defines how the Rust compiler represents types internally. It also defines the *typing context* (`tcx` or `TyCtxt`), which is the central data structure in the compiler. diff --git a/src/doc/rustc-dev-guide/src/type-inference.md b/src/doc/rustc-dev-guide/src/type-inference.md index 888eb2439c5b..2243205f129b 100644 --- a/src/doc/rustc-dev-guide/src/type-inference.md +++ b/src/doc/rustc-dev-guide/src/type-inference.md @@ -1,7 +1,5 @@ # Type inference - - Type inference is the process of automatic detection of the type of an expression. diff --git a/src/doc/rustc-dev-guide/src/typing_parameter_envs.md b/src/doc/rustc-dev-guide/src/typing_parameter_envs.md index e21bc5155da1..db15467a47a0 100644 --- a/src/doc/rustc-dev-guide/src/typing_parameter_envs.md +++ b/src/doc/rustc-dev-guide/src/typing_parameter_envs.md @@ -1,7 +1,5 @@ # Typing/Parameter Environments - - ## Typing Environments When interacting with the type system there are a few variables to consider that can affect the results of trait solving. The set of in-scope where clauses, and what phase of the compiler type system operations are being performed in (the [`ParamEnv`][penv] and [`TypingMode`][tmode] structs respectively). diff --git a/src/doc/rustc-dev-guide/src/variance.md b/src/doc/rustc-dev-guide/src/variance.md index ad4fa4adfddb..7aa014071551 100644 --- a/src/doc/rustc-dev-guide/src/variance.md +++ b/src/doc/rustc-dev-guide/src/variance.md @@ -1,7 +1,5 @@ # Variance of type and lifetime parameters - - For a more general background on variance, see the [background] appendix. [background]: ./appendix/background.html diff --git a/src/doc/rustc-dev-guide/src/walkthrough.md b/src/doc/rustc-dev-guide/src/walkthrough.md index 48b3f8bb15d3..b4c3379347ed 100644 --- a/src/doc/rustc-dev-guide/src/walkthrough.md +++ b/src/doc/rustc-dev-guide/src/walkthrough.md @@ -1,7 +1,5 @@ # Walkthrough: a typical contribution - - There are _a lot_ of ways to contribute to the Rust compiler, including fixing bugs, improving performance, helping design features, providing feedback on existing features, etc. This chapter does not claim to scratch the surface. From 91bccd6ba8861fd91bcf0f682f50f78fdb38a450 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Thu, 24 Jul 2025 14:06:58 +0200 Subject: [PATCH 0171/1134] use `minicore` for fortanix assembly tests --- ...4-fortanix-unknown-sgx-lvi-generic-load.rs | 31 ++++++++++++------- ...64-fortanix-unknown-sgx-lvi-generic-ret.rs | 14 +++++++-- ...ortanix-unknown-sgx-lvi-inline-assembly.rs | 28 ++++++++++------- 3 files changed, 46 insertions(+), 27 deletions(-) diff --git a/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-generic-load.rs b/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-generic-load.rs index f5e2f18e68e4..2892ff2882a7 100644 --- a/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-generic-load.rs +++ b/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-generic-load.rs @@ -1,17 +1,24 @@ -// Test LVI load hardening on SGX enclave code +// Test LVI load hardening on SGX enclave code, specifically that `ret` is rewritten. +//@ add-core-stubs //@ assembly-output: emit-asm -//@ compile-flags: --crate-type staticlib -//@ only-x86_64-fortanix-unknown-sgx +//@ compile-flags: --target x86_64-fortanix-unknown-sgx -Copt-level=0 +//@ needs-llvm-components: x86 + +#![feature(no_core, lang_items, f16)] +#![crate_type = "lib"] +#![no_core] + +extern crate minicore; +use minicore::*; #[no_mangle] -pub extern "C" fn plus_one(r: &mut u64) { - *r = *r + 1; +pub extern "C" fn dereference(a: &mut u64) -> u64 { + // CHECK-LABEL: dereference + // CHECK: lfence + // CHECK: mov + // CHECK: popq [[REGISTER:%[a-z]+]] + // CHECK-NEXT: lfence + // CHECK-NEXT: jmpq *[[REGISTER]] + *a } - -// CHECK: plus_one -// CHECK: lfence -// CHECK-NEXT: incq -// CHECK: popq [[REGISTER:%[a-z]+]] -// CHECK-NEXT: lfence -// CHECK-NEXT: jmpq *[[REGISTER]] diff --git a/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-generic-ret.rs b/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-generic-ret.rs index f16d68fa2554..a0cedc3bc2da 100644 --- a/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-generic-ret.rs +++ b/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-generic-ret.rs @@ -1,12 +1,20 @@ // Test LVI ret hardening on generic rust code +//@ add-core-stubs //@ assembly-output: emit-asm -//@ compile-flags: --crate-type staticlib -//@ only-x86_64-fortanix-unknown-sgx +//@ compile-flags: --target x86_64-fortanix-unknown-sgx +//@ needs-llvm-components: x86 + +#![feature(no_core, lang_items, f16)] +#![crate_type = "lib"] +#![no_core] + +extern crate minicore; +use minicore::*; #[no_mangle] pub extern "C" fn myret() {} -// CHECK: myret: +// CHECK-LABEL: myret: // CHECK: popq [[REGISTER:%[a-z]+]] // CHECK-NEXT: lfence // CHECK-NEXT: jmpq *[[REGISTER]] diff --git a/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-inline-assembly.rs b/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-inline-assembly.rs index a729df8e1660..215fb4b804ac 100644 --- a/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-inline-assembly.rs +++ b/tests/assembly-llvm/x86_64-fortanix-unknown-sgx-lvi-inline-assembly.rs @@ -1,13 +1,22 @@ // Test LVI load hardening on SGX inline assembly code +//@ add-core-stubs //@ assembly-output: emit-asm -//@ compile-flags: --crate-type staticlib -//@ only-x86_64-fortanix-unknown-sgx +//@ compile-flags: --target x86_64-fortanix-unknown-sgx +//@ needs-llvm-components: x86 -use std::arch::asm; +#![feature(no_core, lang_items, f16)] +#![crate_type = "lib"] +#![no_core] + +extern crate minicore; +use minicore::*; #[no_mangle] pub extern "C" fn get(ptr: *const u64) -> u64 { + // CHECK-LABEL: get + // CHECK: movq + // CHECK-NEXT: lfence let value: u64; unsafe { asm!("mov {}, [{}]", @@ -17,18 +26,13 @@ pub extern "C" fn get(ptr: *const u64) -> u64 { value } -// CHECK: get -// CHECK: movq -// CHECK-NEXT: lfence - #[no_mangle] pub extern "C" fn myret() { + // CHECK-LABEL: myret + // CHECK: shlq $0, (%rsp) + // CHECK-NEXT: lfence + // CHECK-NEXT: retq unsafe { asm!("ret"); } } - -// CHECK: myret -// CHECK: shlq $0, (%rsp) -// CHECK-NEXT: lfence -// CHECK-NEXT: retq From 8b90847416d5678d784942b46c05f8c97caef83d Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Thu, 24 Jul 2025 14:07:32 +0200 Subject: [PATCH 0172/1134] update fortanix run-make test Make it more idiomatic with the new run-make infra --- .../x86_64-fortanix-unknown-sgx-lvi/rmake.rs | 43 ++++++++++++------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/rmake.rs b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/rmake.rs index e58762aeb6db..89754cdaf905 100644 --- a/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/rmake.rs +++ b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/rmake.rs @@ -13,42 +13,56 @@ //@ only-x86_64-fortanix-unknown-sgx -use run_make_support::{cmd, cwd, llvm_filecheck, llvm_objdump, regex, set_current_dir, target}; +use run_make_support::{ + cargo, cwd, llvm_filecheck, llvm_objdump, regex, run, set_current_dir, target, +}; fn main() { - let main_dir = cwd(); - set_current_dir("enclave"); - // HACK(eddyb) sets `RUSTC_BOOTSTRAP=1` so Cargo can accept nightly features. - // These come from the top-level Rust workspace, that this crate is not a - // member of, but Cargo tries to load the workspace `Cargo.toml` anyway. - cmd("cargo") - .env("RUSTC_BOOTSTRAP", "1") + cargo() .arg("-v") - .arg("run") + .arg("build") .arg("--target") .arg(target()) + .current_dir("enclave") + .env("CC_x86_64_fortanix_unknown_sgx", "clang") + .env( + "CFLAGS_x86_64_fortanix_unknown_sgx", + "-D__ELF__ -isystem/usr/include/x86_64-linux-gnu -mlvi-hardening -mllvm -x86-experimental-lvi-inline-asm-hardening", + ) + .env("CXX_x86_64_fortanix_unknown_sgx", "clang++") + .env( + "CXXFLAGS_x86_64_fortanix_unknown_sgx", + "-D__ELF__ -isystem/usr/include/x86_64-linux-gnu -mlvi-hardening -mllvm -x86-experimental-lvi-inline-asm-hardening", + ) .run(); - set_current_dir(&main_dir); - // Rust has various ways of adding code to a binary: + + // Rust has several ways of including machine code into a binary: + // // - Rust code // - Inline assembly // - Global assembly // - C/C++ code compiled as part of Rust crates - // For those different kinds, we do have very small code examples that should be - // mitigated in some way. Mostly we check that ret instructions should no longer be present. + // + // For each of those, check that the mitigations are applied. Mostly we check + // that ret instructions are no longer present. + + // Check that normal rust code has the right mitigations. check("unw_getcontext", "unw_getcontext.checks"); check("__libunwind_Registers_x86_64_jumpto", "jumpto.checks"); check("std::io::stdio::_print::[[:alnum:]]+", "print.with_frame_pointers.checks"); + // Check that rust global assembly has the right mitigations. check("rust_plus_one_global_asm", "rust_plus_one_global_asm.checks"); + // Check that C code compiled using the `cc` crate has the right mitigations. check("cc_plus_one_c", "cc_plus_one_c.checks"); check("cc_plus_one_c_asm", "cc_plus_one_c_asm.checks"); check("cc_plus_one_cxx", "cc_plus_one_cxx.checks"); check("cc_plus_one_cxx_asm", "cc_plus_one_cxx_asm.checks"); check("cc_plus_one_asm", "cc_plus_one_asm.checks"); + // Check that C++ code compiled using the `cc` crate has the right mitigations. check("cmake_plus_one_c", "cmake_plus_one_c.checks"); check("cmake_plus_one_c_asm", "cmake_plus_one_c_asm.checks"); check("cmake_plus_one_c_global_asm", "cmake_plus_one_c_global_asm.checks"); @@ -71,8 +85,7 @@ fn check(func_re: &str, mut checks: &str) { .input("enclave/target/x86_64-fortanix-unknown-sgx/debug/enclave") .args(&["--demangle", &format!("--disassemble-symbols={func}")]) .run() - .stdout_utf8(); - let dump = dump.as_bytes(); + .stdout(); // Unique case, must succeed at one of two possible tests. // This is because frame pointers are optional, and them being enabled requires From 6c7dc05f7d1f000cdb7de2390c8532545129e32d Mon Sep 17 00:00:00 2001 From: Caiweiran Date: Mon, 28 Jul 2025 11:58:38 +0000 Subject: [PATCH 0173/1134] Fix tests/codegen-llvm/simd/extract-insert-dyn.rs test failure on riscv64 --- tests/codegen-llvm/simd/extract-insert-dyn.rs | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/tests/codegen-llvm/simd/extract-insert-dyn.rs b/tests/codegen-llvm/simd/extract-insert-dyn.rs index 729f0145314a..9c17b82e5535 100644 --- a/tests/codegen-llvm/simd/extract-insert-dyn.rs +++ b/tests/codegen-llvm/simd/extract-insert-dyn.rs @@ -5,7 +5,8 @@ repr_simd, arm_target_feature, mips_target_feature, - s390x_target_feature + s390x_target_feature, + riscv_target_feature )] #![no_std] #![crate_type = "lib"] @@ -25,97 +26,105 @@ pub struct u32x16([u32; 16]); pub struct i8x16([i8; 16]); // CHECK-LABEL: dyn_simd_extract -// CHECK: extractelement <16 x i8> %x, i32 %idx +// CHECK: extractelement <16 x i8> %[[TEMP:.+]], i32 %idx #[no_mangle] #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] #[cfg_attr(target_arch = "x86", target_feature(enable = "sse"))] #[cfg_attr(target_arch = "mips", target_feature(enable = "msa"))] #[cfg_attr(target_arch = "s390x", target_feature(enable = "vector"))] +#[cfg_attr(target_arch = "riscv64", target_feature(enable = "v"))] unsafe extern "C" fn dyn_simd_extract(x: i8x16, idx: u32) -> i8 { simd_extract_dyn(x, idx) } // CHECK-LABEL: literal_dyn_simd_extract -// CHECK: extractelement <16 x i8> %x, i32 7 +// CHECK: extractelement <16 x i8> %[[TEMP:.+]], i32 7 #[no_mangle] #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] #[cfg_attr(target_arch = "x86", target_feature(enable = "sse"))] #[cfg_attr(target_arch = "mips", target_feature(enable = "msa"))] #[cfg_attr(target_arch = "s390x", target_feature(enable = "vector"))] +#[cfg_attr(target_arch = "riscv64", target_feature(enable = "v"))] unsafe extern "C" fn literal_dyn_simd_extract(x: i8x16) -> i8 { simd_extract_dyn(x, 7) } // CHECK-LABEL: const_dyn_simd_extract -// CHECK: extractelement <16 x i8> %x, i32 7 +// CHECK: extractelement <16 x i8> %[[TEMP:.+]], i32 7 #[no_mangle] #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] #[cfg_attr(target_arch = "x86", target_feature(enable = "sse"))] #[cfg_attr(target_arch = "mips", target_feature(enable = "msa"))] #[cfg_attr(target_arch = "s390x", target_feature(enable = "vector"))] +#[cfg_attr(target_arch = "riscv64", target_feature(enable = "v"))] unsafe extern "C" fn const_dyn_simd_extract(x: i8x16) -> i8 { simd_extract_dyn(x, const { 3 + 4 }) } // CHECK-LABEL: const_simd_extract -// CHECK: extractelement <16 x i8> %x, i32 7 +// CHECK: extractelement <16 x i8> %[[TEMP:.+]], i32 7 #[no_mangle] #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] #[cfg_attr(target_arch = "x86", target_feature(enable = "sse"))] #[cfg_attr(target_arch = "mips", target_feature(enable = "msa"))] #[cfg_attr(target_arch = "s390x", target_feature(enable = "vector"))] +#[cfg_attr(target_arch = "riscv64", target_feature(enable = "v"))] unsafe extern "C" fn const_simd_extract(x: i8x16) -> i8 { simd_extract(x, const { 3 + 4 }) } // CHECK-LABEL: dyn_simd_insert -// CHECK: insertelement <16 x i8> %x, i8 %e, i32 %idx +// CHECK: insertelement <16 x i8> %[[TEMP:.+]], i8 %e, i32 %idx #[no_mangle] #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] #[cfg_attr(target_arch = "x86", target_feature(enable = "sse"))] #[cfg_attr(target_arch = "mips", target_feature(enable = "msa"))] #[cfg_attr(target_arch = "s390x", target_feature(enable = "vector"))] +#[cfg_attr(target_arch = "riscv64", target_feature(enable = "v"))] unsafe extern "C" fn dyn_simd_insert(x: i8x16, e: i8, idx: u32) -> i8x16 { simd_insert_dyn(x, idx, e) } // CHECK-LABEL: literal_dyn_simd_insert -// CHECK: insertelement <16 x i8> %x, i8 %e, i32 7 +// CHECK: insertelement <16 x i8> %[[TEMP:.+]], i8 %e, i32 7 #[no_mangle] #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] #[cfg_attr(target_arch = "x86", target_feature(enable = "sse"))] #[cfg_attr(target_arch = "mips", target_feature(enable = "msa"))] #[cfg_attr(target_arch = "s390x", target_feature(enable = "vector"))] +#[cfg_attr(target_arch = "riscv64", target_feature(enable = "v"))] unsafe extern "C" fn literal_dyn_simd_insert(x: i8x16, e: i8) -> i8x16 { simd_insert_dyn(x, 7, e) } // CHECK-LABEL: const_dyn_simd_insert -// CHECK: insertelement <16 x i8> %x, i8 %e, i32 7 +// CHECK: insertelement <16 x i8> %[[TEMP:.+]], i8 %e, i32 7 #[no_mangle] #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] #[cfg_attr(target_arch = "x86", target_feature(enable = "sse"))] #[cfg_attr(target_arch = "mips", target_feature(enable = "msa"))] #[cfg_attr(target_arch = "s390x", target_feature(enable = "vector"))] +#[cfg_attr(target_arch = "riscv64", target_feature(enable = "v"))] unsafe extern "C" fn const_dyn_simd_insert(x: i8x16, e: i8) -> i8x16 { simd_insert_dyn(x, const { 3 + 4 }, e) } // CHECK-LABEL: const_simd_insert -// CHECK: insertelement <16 x i8> %x, i8 %e, i32 7 +// CHECK: insertelement <16 x i8> %[[TEMP:.+]], i8 %e, i32 7 #[no_mangle] #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] #[cfg_attr(target_arch = "x86", target_feature(enable = "sse"))] #[cfg_attr(target_arch = "mips", target_feature(enable = "msa"))] #[cfg_attr(target_arch = "s390x", target_feature(enable = "vector"))] +#[cfg_attr(target_arch = "riscv64", target_feature(enable = "v"))] unsafe extern "C" fn const_simd_insert(x: i8x16, e: i8) -> i8x16 { simd_insert(x, const { 3 + 4 }, e) } From 18a13b15fe1ebac207eb9efe789dfa717b4c4a97 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 28 Jul 2025 15:20:27 +0200 Subject: [PATCH 0174/1134] Do not treat NixOS as a Pascal-cased identifier --- book/src/lint_configuration.md | 2 +- clippy_config/src/conf.rs | 2 +- tests/ui/doc/doc-fixable.fixed | 2 +- tests/ui/doc/doc-fixable.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/book/src/lint_configuration.md b/book/src/lint_configuration.md index 992ed2c6aaaa..7f16f3a98105 100644 --- a/book/src/lint_configuration.md +++ b/book/src/lint_configuration.md @@ -555,7 +555,7 @@ default configuration of Clippy. By default, any configuration will replace the * `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`. * `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list. -**Default Value:** `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "MHz", "GHz", "THz", "AccessKit", "CoAP", "CoreFoundation", "CoreGraphics", "CoreText", "DevOps", "Direct2D", "Direct3D", "DirectWrite", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PostScript", "PureScript", "TypeScript", "WebAssembly", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenAL", "OpenDNS", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenTelemetry", "OpenType", "WebGL", "WebGL2", "WebGPU", "WebRTC", "WebSocket", "WebTransport", "WebP", "OpenExr", "YCbCr", "sRGB", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "NetBSD", "OpenBSD", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]` +**Default Value:** `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "MHz", "GHz", "THz", "AccessKit", "CoAP", "CoreFoundation", "CoreGraphics", "CoreText", "DevOps", "Direct2D", "Direct3D", "DirectWrite", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PostScript", "PureScript", "TypeScript", "WebAssembly", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenAL", "OpenDNS", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenTelemetry", "OpenType", "WebGL", "WebGL2", "WebGPU", "WebRTC", "WebSocket", "WebTransport", "WebP", "OpenExr", "YCbCr", "sRGB", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "NetBSD", "OpenBSD", "NixOS", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]` --- **Affected lints:** diff --git a/clippy_config/src/conf.rs b/clippy_config/src/conf.rs index 555f54bcfb8b..8167d75583ee 100644 --- a/clippy_config/src/conf.rs +++ b/clippy_config/src/conf.rs @@ -44,7 +44,7 @@ const DEFAULT_DOC_VALID_IDENTS: &[&str] = &[ "WebP", "OpenExr", "YCbCr", "sRGB", "TensorFlow", "TrueType", - "iOS", "macOS", "FreeBSD", "NetBSD", "OpenBSD", + "iOS", "macOS", "FreeBSD", "NetBSD", "OpenBSD", "NixOS", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase", diff --git a/tests/ui/doc/doc-fixable.fixed b/tests/ui/doc/doc-fixable.fixed index 8cf20d8b1a11..bbbd5973036e 100644 --- a/tests/ui/doc/doc-fixable.fixed +++ b/tests/ui/doc/doc-fixable.fixed @@ -83,7 +83,7 @@ fn test_units() { /// WebGL WebGL2 WebGPU WebRTC WebSocket WebTransport /// TensorFlow /// TrueType -/// iOS macOS FreeBSD NetBSD OpenBSD +/// iOS macOS FreeBSD NetBSD OpenBSD NixOS /// TeX LaTeX BibTeX BibLaTeX /// MinGW /// CamelCase (see also #2395) diff --git a/tests/ui/doc/doc-fixable.rs b/tests/ui/doc/doc-fixable.rs index 5b6f2bd8330c..1077d3580d3c 100644 --- a/tests/ui/doc/doc-fixable.rs +++ b/tests/ui/doc/doc-fixable.rs @@ -83,7 +83,7 @@ fn test_units() { /// WebGL WebGL2 WebGPU WebRTC WebSocket WebTransport /// TensorFlow /// TrueType -/// iOS macOS FreeBSD NetBSD OpenBSD +/// iOS macOS FreeBSD NetBSD OpenBSD NixOS /// TeX LaTeX BibTeX BibLaTeX /// MinGW /// CamelCase (see also #2395) From 938e79fdac508c1cca01743b85cff11ed5f7aab6 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Sun, 27 Jul 2025 22:11:36 +0800 Subject: [PATCH 0175/1134] fix: `cast-lossless` should not suggest when casting type is from macro input --- clippy_lints/src/casts/cast_lossless.rs | 6 ++++++ tests/ui/cast_lossless_integer_unfixable.rs | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 tests/ui/cast_lossless_integer_unfixable.rs diff --git a/clippy_lints/src/casts/cast_lossless.rs b/clippy_lints/src/casts/cast_lossless.rs index c1d6cec1b62e..c924fba6b5c8 100644 --- a/clippy_lints/src/casts/cast_lossless.rs +++ b/clippy_lints/src/casts/cast_lossless.rs @@ -25,6 +25,12 @@ pub(super) fn check( return; } + // If the `as` is from a macro and the casting type is from macro input, whether it is lossless is + // dependent on the input + if expr.span.from_expansion() && !cast_to_hir.span.eq_ctxt(expr.span) { + return; + } + span_lint_and_then( cx, CAST_LOSSLESS, diff --git a/tests/ui/cast_lossless_integer_unfixable.rs b/tests/ui/cast_lossless_integer_unfixable.rs new file mode 100644 index 000000000000..db9cbbb5b663 --- /dev/null +++ b/tests/ui/cast_lossless_integer_unfixable.rs @@ -0,0 +1,17 @@ +//@check-pass +#![warn(clippy::cast_lossless)] + +fn issue15348() { + macro_rules! zero { + ($int:ty) => {{ + let data: [u8; 3] = [0, 0, 0]; + data[0] as $int + }}; + } + + let _ = zero!(u8); + let _ = zero!(u16); + let _ = zero!(u32); + let _ = zero!(u64); + let _ = zero!(u128); +} From b0740198ae5fe909d814a6fb4eb25c300cfb311a Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 19:05:31 -0500 Subject: [PATCH 0176/1134] Rename trait_of_item -> trait_of_assoc --- clippy_lints/src/dereference.rs | 2 +- clippy_lints/src/loops/needless_range_loop.rs | 2 +- clippy_lints/src/methods/clone_on_copy.rs | 2 +- clippy_lints/src/methods/iter_overeager_cloned.rs | 4 ++-- clippy_lints/src/methods/manual_str_repeat.rs | 2 +- clippy_lints/src/methods/map_clone.rs | 2 +- clippy_lints/src/methods/open_options.rs | 2 +- clippy_lints/src/methods/str_splitn.rs | 6 +++--- .../src/methods/unnecessary_fallible_conversions.rs | 2 +- clippy_lints/src/methods/unnecessary_to_owned.rs | 2 +- clippy_lints/src/methods/useless_asref.rs | 2 +- clippy_lints/src/operators/cmp_owned.rs | 2 +- clippy_lints/src/ranges.rs | 2 +- clippy_lints/src/unconditional_recursion.rs | 8 ++++---- clippy_lints/src/unused_io_amount.rs | 2 +- clippy_utils/src/lib.rs | 4 ++-- clippy_utils/src/qualify_min_const_fn.rs | 2 +- 17 files changed, 24 insertions(+), 24 deletions(-) diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index 5099df3fa023..995a1209595e 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -364,7 +364,7 @@ impl<'tcx> LateLintPass<'tcx> for Dereferencing<'tcx> { // * `&self` methods on `&T` can have auto-borrow, but `&self` methods on `T` will take // priority. if let Some(fn_id) = typeck.type_dependent_def_id(hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && let arg_ty = cx.tcx.erase_regions(adjusted_ty) && let ty::Ref(_, sub_ty, _) = *arg_ty.kind() && let args = diff --git a/clippy_lints/src/loops/needless_range_loop.rs b/clippy_lints/src/loops/needless_range_loop.rs index 972b0b110e0e..7bb684d65bb4 100644 --- a/clippy_lints/src/loops/needless_range_loop.rs +++ b/clippy_lints/src/loops/needless_range_loop.rs @@ -317,7 +317,7 @@ impl<'tcx> Visitor<'tcx> for VarVisitor<'_, 'tcx> { .cx .typeck_results() .type_dependent_def_id(expr.hir_id) - .and_then(|def_id| self.cx.tcx.trait_of_item(def_id)) + .and_then(|def_id| self.cx.tcx.trait_of_assoc(def_id)) && ((meth.ident.name == sym::index && self.cx.tcx.lang_items().index_trait() == Some(trait_id)) || (meth.ident.name == sym::index_mut && self.cx.tcx.lang_items().index_mut_trait() == Some(trait_id))) && !self.check(args_1, args_0, expr) diff --git a/clippy_lints/src/methods/clone_on_copy.rs b/clippy_lints/src/methods/clone_on_copy.rs index 2ecf3eb89798..0a456d1057ad 100644 --- a/clippy_lints/src/methods/clone_on_copy.rs +++ b/clippy_lints/src/methods/clone_on_copy.rs @@ -28,7 +28,7 @@ pub(super) fn check( if cx .typeck_results() .type_dependent_def_id(expr.hir_id) - .and_then(|id| cx.tcx.trait_of_item(id)) + .and_then(|id| cx.tcx.trait_of_assoc(id)) .zip(cx.tcx.lang_items().clone_trait()) .is_none_or(|(x, y)| x != y) { diff --git a/clippy_lints/src/methods/iter_overeager_cloned.rs b/clippy_lints/src/methods/iter_overeager_cloned.rs index f5fe4316eb0d..f851ebe91f37 100644 --- a/clippy_lints/src/methods/iter_overeager_cloned.rs +++ b/clippy_lints/src/methods/iter_overeager_cloned.rs @@ -44,9 +44,9 @@ pub(super) fn check<'tcx>( let typeck = cx.typeck_results(); if let Some(iter_id) = cx.tcx.get_diagnostic_item(sym::Iterator) && let Some(method_id) = typeck.type_dependent_def_id(expr.hir_id) - && cx.tcx.trait_of_item(method_id) == Some(iter_id) + && cx.tcx.trait_of_assoc(method_id) == Some(iter_id) && let Some(method_id) = typeck.type_dependent_def_id(cloned_call.hir_id) - && cx.tcx.trait_of_item(method_id) == Some(iter_id) + && cx.tcx.trait_of_assoc(method_id) == Some(iter_id) && let cloned_recv_ty = typeck.expr_ty_adjusted(cloned_recv) && let Some(iter_assoc_ty) = cx.get_associated_type(cloned_recv_ty, iter_id, sym::Item) && matches!(*iter_assoc_ty.kind(), ty::Ref(_, ty, _) if !is_copy(cx, ty)) diff --git a/clippy_lints/src/methods/manual_str_repeat.rs b/clippy_lints/src/methods/manual_str_repeat.rs index 8167e4f96053..a811dd1cee18 100644 --- a/clippy_lints/src/methods/manual_str_repeat.rs +++ b/clippy_lints/src/methods/manual_str_repeat.rs @@ -59,7 +59,7 @@ pub(super) fn check( && is_type_lang_item(cx, cx.typeck_results().expr_ty(collect_expr), LangItem::String) && let Some(take_id) = cx.typeck_results().type_dependent_def_id(take_expr.hir_id) && let Some(iter_trait_id) = cx.tcx.get_diagnostic_item(sym::Iterator) - && cx.tcx.trait_of_item(take_id) == Some(iter_trait_id) + && cx.tcx.trait_of_assoc(take_id) == Some(iter_trait_id) && let Some(repeat_kind) = parse_repeat_arg(cx, repeat_arg) && let ctxt = collect_expr.span.ctxt() && ctxt == take_expr.span.ctxt() diff --git a/clippy_lints/src/methods/map_clone.rs b/clippy_lints/src/methods/map_clone.rs index 333a33f7527d..d016ace28bd4 100644 --- a/clippy_lints/src/methods/map_clone.rs +++ b/clippy_lints/src/methods/map_clone.rs @@ -69,7 +69,7 @@ pub(super) fn check(cx: &LateContext<'_>, e: &hir::Expr<'_>, recv: &hir::Expr<'_ hir::ExprKind::MethodCall(method, obj, [], _) => { if ident_eq(name, obj) && method.ident.name == sym::clone && let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && cx.tcx.lang_items().clone_trait() == Some(trait_id) // no autoderefs && !cx.typeck_results().expr_adjustments(obj).iter() diff --git a/clippy_lints/src/methods/open_options.rs b/clippy_lints/src/methods/open_options.rs index 9b5f138295c3..87e6cf021023 100644 --- a/clippy_lints/src/methods/open_options.rs +++ b/clippy_lints/src/methods/open_options.rs @@ -111,7 +111,7 @@ fn get_open_options( // This might be a user defined extension trait with a method like `truncate_write` // which would be a false positive if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(argument.hir_id) - && cx.tcx.trait_of_item(method_def_id).is_some() + && cx.tcx.trait_of_assoc(method_def_id).is_some() { return false; } diff --git a/clippy_lints/src/methods/str_splitn.rs b/clippy_lints/src/methods/str_splitn.rs index 6f78d6c61281..51dd4ac313a6 100644 --- a/clippy_lints/src/methods/str_splitn.rs +++ b/clippy_lints/src/methods/str_splitn.rs @@ -286,7 +286,7 @@ fn parse_iter_usage<'tcx>( let iter_id = cx.tcx.get_diagnostic_item(sym::Iterator)?; match (name.ident.name, args) { - (sym::next, []) if cx.tcx.trait_of_item(did) == Some(iter_id) => (IterUsageKind::Nth(0), e.span), + (sym::next, []) if cx.tcx.trait_of_assoc(did) == Some(iter_id) => (IterUsageKind::Nth(0), e.span), (sym::next_tuple, []) => { return if paths::ITERTOOLS_NEXT_TUPLE.matches(cx, did) && let ty::Adt(adt_def, subs) = cx.typeck_results().expr_ty(e).kind() @@ -303,7 +303,7 @@ fn parse_iter_usage<'tcx>( None }; }, - (sym::nth | sym::skip, [idx_expr]) if cx.tcx.trait_of_item(did) == Some(iter_id) => { + (sym::nth | sym::skip, [idx_expr]) if cx.tcx.trait_of_assoc(did) == Some(iter_id) => { if let Some(Constant::Int(idx)) = ConstEvalCtxt::new(cx).eval(idx_expr) { let span = if name.ident.as_str() == "nth" { e.span @@ -312,7 +312,7 @@ fn parse_iter_usage<'tcx>( && next_name.ident.name == sym::next && next_expr.span.ctxt() == ctxt && let Some(next_id) = cx.typeck_results().type_dependent_def_id(next_expr.hir_id) - && cx.tcx.trait_of_item(next_id) == Some(iter_id) + && cx.tcx.trait_of_assoc(next_id) == Some(iter_id) { next_expr.span } else { diff --git a/clippy_lints/src/methods/unnecessary_fallible_conversions.rs b/clippy_lints/src/methods/unnecessary_fallible_conversions.rs index ce81282ddfeb..0ec2d8b4fc31 100644 --- a/clippy_lints/src/methods/unnecessary_fallible_conversions.rs +++ b/clippy_lints/src/methods/unnecessary_fallible_conversions.rs @@ -165,7 +165,7 @@ pub(super) fn check_method(cx: &LateContext<'_>, expr: &Expr<'_>) { pub(super) fn check_function(cx: &LateContext<'_>, expr: &Expr<'_>, callee: &Expr<'_>) { if let ExprKind::Path(ref qpath) = callee.kind && let Some(item_def_id) = cx.qpath_res(qpath, callee.hir_id).opt_def_id() - && let Some(trait_def_id) = cx.tcx.trait_of_item(item_def_id) + && let Some(trait_def_id) = cx.tcx.trait_of_assoc(item_def_id) { let qpath_spans = match qpath { QPath::Resolved(_, path) => { diff --git a/clippy_lints/src/methods/unnecessary_to_owned.rs b/clippy_lints/src/methods/unnecessary_to_owned.rs index 769526d131bf..a86428808216 100644 --- a/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -734,7 +734,7 @@ fn check_if_applicable_to_argument<'tcx>(cx: &LateContext<'tcx>, arg: &Expr<'tcx fn check_borrow_predicate<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { if let ExprKind::MethodCall(_, caller, &[arg], _) = expr.kind && let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && cx.tcx.trait_of_item(method_def_id).is_none() + && cx.tcx.trait_of_assoc(method_def_id).is_none() && let Some(borrow_id) = cx.tcx.get_diagnostic_item(sym::Borrow) && cx.tcx.predicates_of(method_def_id).predicates.iter().any(|(pred, _)| { if let ClauseKind::Trait(trait_pred) = pred.kind().skip_binder() diff --git a/clippy_lints/src/methods/useless_asref.rs b/clippy_lints/src/methods/useless_asref.rs index d30c12e0c483..d9cf8273fada 100644 --- a/clippy_lints/src/methods/useless_asref.rs +++ b/clippy_lints/src/methods/useless_asref.rs @@ -131,7 +131,7 @@ fn is_calling_clone(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool { hir::ExprKind::MethodCall(method, obj, [], _) => { if method.ident.name == sym::clone && let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) // We check it's the `Clone` trait. && cx.tcx.lang_items().clone_trait().is_some_and(|id| id == trait_id) // no autoderefs diff --git a/clippy_lints/src/operators/cmp_owned.rs b/clippy_lints/src/operators/cmp_owned.rs index 9b2cfd91b853..22ec4fe60fb0 100644 --- a/clippy_lints/src/operators/cmp_owned.rs +++ b/clippy_lints/src/operators/cmp_owned.rs @@ -41,7 +41,7 @@ fn check_op(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: bool) ExprKind::MethodCall(_, arg, [], _) if typeck .type_dependent_def_id(expr.hir_id) - .and_then(|id| cx.tcx.trait_of_item(id)) + .and_then(|id| cx.tcx.trait_of_assoc(id)) .is_some_and(|id| matches!(cx.tcx.get_diagnostic_name(id), Some(sym::ToString | sym::ToOwned))) => { (arg, arg.span) diff --git a/clippy_lints/src/ranges.rs b/clippy_lints/src/ranges.rs index 9281678b3d83..03d00ba849f3 100644 --- a/clippy_lints/src/ranges.rs +++ b/clippy_lints/src/ranges.rs @@ -380,7 +380,7 @@ fn can_switch_ranges<'tcx>( if let ExprKind::MethodCall(_, receiver, _, _) = parent_expr.kind && receiver.hir_id == use_ctxt.child_id && let Some(method_did) = cx.typeck_results().type_dependent_def_id(parent_expr.hir_id) - && let Some(trait_did) = cx.tcx.trait_of_item(method_did) + && let Some(trait_did) = cx.tcx.trait_of_assoc(method_did) && matches!( cx.tcx.get_diagnostic_name(trait_did), Some(sym::Iterator | sym::IntoIterator | sym::RangeBounds) diff --git a/clippy_lints/src/unconditional_recursion.rs b/clippy_lints/src/unconditional_recursion.rs index d321c48f6aff..dcddff557d1c 100644 --- a/clippy_lints/src/unconditional_recursion.rs +++ b/clippy_lints/src/unconditional_recursion.rs @@ -206,7 +206,7 @@ fn check_partial_eq(cx: &LateContext<'_>, method_span: Span, method_def_id: Loca let arg_ty = cx.typeck_results().expr_ty_adjusted(arg); if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && trait_id == trait_def_id && matches_ty(receiver_ty, arg_ty, self_arg, other_arg) { @@ -250,7 +250,7 @@ fn check_to_string(cx: &LateContext<'_>, method_span: Span, method_def_id: Local let is_bad = match expr.kind { ExprKind::MethodCall(segment, _receiver, &[_arg], _) if segment.ident.name == name.name => { if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && trait_id == trait_def_id { true @@ -318,7 +318,7 @@ where && let ExprKind::Path(qpath) = f.kind && is_default_method_on_current_ty(self.cx.tcx, qpath, self.implemented_ty_id) && let Some(method_def_id) = path_def_id(self.cx, f) - && let Some(trait_def_id) = self.cx.tcx.trait_of_item(method_def_id) + && let Some(trait_def_id) = self.cx.tcx.trait_of_assoc(method_def_id) && self.cx.tcx.is_diagnostic_item(sym::Default, trait_def_id) { span_error(self.cx, self.method_span, expr); @@ -426,7 +426,7 @@ fn check_from(cx: &LateContext<'_>, method_span: Span, method_def_id: LocalDefId if let Some((fn_def_id, node_args)) = fn_def_id_with_node_args(cx, expr) && let [s1, s2] = **node_args && let (Some(s1), Some(s2)) = (s1.as_type(), s2.as_type()) - && let Some(trait_def_id) = cx.tcx.trait_of_item(fn_def_id) + && let Some(trait_def_id) = cx.tcx.trait_of_assoc(fn_def_id) && cx.tcx.is_diagnostic_item(sym::Into, trait_def_id) && get_impl_trait_def_id(cx, method_def_id) == cx.tcx.get_diagnostic_item(sym::From) && s1 == sig.inputs()[0] diff --git a/clippy_lints/src/unused_io_amount.rs b/clippy_lints/src/unused_io_amount.rs index 12cc10938993..bed5c0fc0150 100644 --- a/clippy_lints/src/unused_io_amount.rs +++ b/clippy_lints/src/unused_io_amount.rs @@ -300,7 +300,7 @@ fn check_io_mode(cx: &LateContext<'_>, call: &hir::Expr<'_>) -> Option { }; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(call.hir_id) - && let Some(trait_def_id) = cx.tcx.trait_of_item(method_def_id) + && let Some(trait_def_id) = cx.tcx.trait_of_assoc(method_def_id) { if let Some(diag_name) = cx.tcx.get_diagnostic_name(trait_def_id) { match diag_name { diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index ce5af4d2f482..211af4d5b089 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -349,7 +349,7 @@ pub fn is_ty_alias(qpath: &QPath<'_>) -> bool { /// Checks if the given method call expression calls an inherent method. pub fn is_inherent_method_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) { - cx.tcx.trait_of_item(method_id).is_none() + cx.tcx.trait_of_assoc(method_id).is_none() } else { false } @@ -367,7 +367,7 @@ pub fn is_diag_item_method(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbo /// Checks if a method is in a diagnostic item trait pub fn is_diag_trait_item(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbol) -> bool { - if let Some(trait_did) = cx.tcx.trait_of_item(def_id) { + if let Some(trait_did) = cx.tcx.trait_of_assoc(def_id) { return cx.tcx.is_diagnostic_item(diag_item, trait_did); } false diff --git a/clippy_utils/src/qualify_min_const_fn.rs b/clippy_utils/src/qualify_min_const_fn.rs index b3356450d387..11c17a77b154 100644 --- a/clippy_utils/src/qualify_min_const_fn.rs +++ b/clippy_utils/src/qualify_min_const_fn.rs @@ -420,7 +420,7 @@ pub fn is_stable_const_fn(cx: &LateContext<'_>, def_id: DefId, msrv: Msrv) -> bo .lookup_const_stability(def_id) .or_else(|| { cx.tcx - .trait_of_item(def_id) + .trait_of_assoc(def_id) .and_then(|trait_def_id| cx.tcx.lookup_const_stability(trait_def_id)) }) .is_none_or(|const_stab| { From 86ff11e729e780f533030208f1c0ab25e52e6f47 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 19:09:05 -0500 Subject: [PATCH 0177/1134] Rename impl_of_method -> impl_of_assoc --- clippy_lints/src/assigning_clones.rs | 2 +- clippy_lints/src/casts/cast_ptr_alignment.rs | 2 +- clippy_lints/src/casts/confusing_method_to_numeric_cast.rs | 2 +- clippy_lints/src/implicit_saturating_sub.rs | 4 ++-- clippy_lints/src/methods/bytes_count_to_len.rs | 2 +- .../src/methods/case_sensitive_file_extension_comparisons.rs | 2 +- clippy_lints/src/methods/get_first.rs | 2 +- clippy_lints/src/methods/implicit_clone.rs | 2 +- clippy_lints/src/methods/manual_ok_or.rs | 2 +- clippy_lints/src/methods/map_clone.rs | 2 +- clippy_lints/src/methods/map_err_ignore.rs | 2 +- clippy_lints/src/methods/mut_mutex_lock.rs | 2 +- clippy_lints/src/methods/open_options.rs | 2 +- clippy_lints/src/methods/path_buf_push_overwrite.rs | 2 +- clippy_lints/src/methods/stable_sort_primitive.rs | 2 +- clippy_lints/src/methods/suspicious_splitn.rs | 2 +- clippy_lints/src/methods/unnecessary_sort_by.rs | 2 +- clippy_lints/src/methods/unnecessary_to_owned.rs | 2 +- clippy_lints/src/methods/useless_asref.rs | 2 +- clippy_lints/src/methods/vec_resize_to_zero.rs | 2 +- clippy_lints/src/operators/op_ref.rs | 2 +- clippy_lints/src/return_self_not_must_use.rs | 2 +- clippy_lints/src/unused_io_amount.rs | 2 +- clippy_utils/src/eager_or_lazy.rs | 2 +- clippy_utils/src/lib.rs | 4 ++-- 25 files changed, 27 insertions(+), 27 deletions(-) diff --git a/clippy_lints/src/assigning_clones.rs b/clippy_lints/src/assigning_clones.rs index 8b8b42bbf722..52287be34c78 100644 --- a/clippy_lints/src/assigning_clones.rs +++ b/clippy_lints/src/assigning_clones.rs @@ -98,7 +98,7 @@ impl<'tcx> LateLintPass<'tcx> for AssigningClones { // That is overly conservative - the lint should fire even if there was no initializer, // but the variable has been initialized before `lhs` was evaluated. && path_to_local(lhs).is_none_or(|lhs| local_is_initialized(cx, lhs)) - && let Some(resolved_impl) = cx.tcx.impl_of_method(resolved_fn.def_id()) + && let Some(resolved_impl) = cx.tcx.impl_of_assoc(resolved_fn.def_id()) // Derived forms don't implement `clone_from`/`clone_into`. // See https://github.com/rust-lang/rust/pull/98445#issuecomment-1190681305 && !cx.tcx.is_builtin_derived(resolved_impl) diff --git a/clippy_lints/src/casts/cast_ptr_alignment.rs b/clippy_lints/src/casts/cast_ptr_alignment.rs index e4dafde0f9df..a1543cabd2f9 100644 --- a/clippy_lints/src/casts/cast_ptr_alignment.rs +++ b/clippy_lints/src/casts/cast_ptr_alignment.rs @@ -63,7 +63,7 @@ fn is_used_as_unaligned(cx: &LateContext<'_>, e: &Expr<'_>) -> bool { ExprKind::MethodCall(name, self_arg, ..) if self_arg.hir_id == e.hir_id => { if matches!(name.ident.name, sym::read_unaligned | sym::write_unaligned) && let Some(def_id) = cx.typeck_results().type_dependent_def_id(parent.hir_id) - && let Some(def_id) = cx.tcx.impl_of_method(def_id) + && let Some(def_id) = cx.tcx.impl_of_assoc(def_id) && cx.tcx.type_of(def_id).instantiate_identity().is_raw_ptr() { true diff --git a/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs b/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs index 849de22cfbaa..73347e7141eb 100644 --- a/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs +++ b/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs @@ -37,7 +37,7 @@ fn get_const_name_and_ty_name( } else { return None; } - } else if let Some(impl_id) = cx.tcx.impl_of_method(method_def_id) + } else if let Some(impl_id) = cx.tcx.impl_of_assoc(method_def_id) && let Some(ty_name) = get_primitive_ty_name(cx.tcx.type_of(impl_id).instantiate_identity()) && matches!( method_name, diff --git a/clippy_lints/src/implicit_saturating_sub.rs b/clippy_lints/src/implicit_saturating_sub.rs index c743501da253..c634c12e1877 100644 --- a/clippy_lints/src/implicit_saturating_sub.rs +++ b/clippy_lints/src/implicit_saturating_sub.rs @@ -339,7 +339,7 @@ fn check_with_condition<'tcx>( ExprKind::Path(QPath::TypeRelative(_, name)) => { if name.ident.name == sym::MIN && let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(const_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(const_id) && let None = cx.tcx.impl_trait_ref(impl_id) // An inherent impl && cx.tcx.type_of(impl_id).instantiate_identity().is_integral() { @@ -350,7 +350,7 @@ fn check_with_condition<'tcx>( if let ExprKind::Path(QPath::TypeRelative(_, name)) = func.kind && name.ident.name == sym::min_value && let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(func_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(func_id) && let None = cx.tcx.impl_trait_ref(impl_id) // An inherent impl && cx.tcx.type_of(impl_id).instantiate_identity().is_integral() { diff --git a/clippy_lints/src/methods/bytes_count_to_len.rs b/clippy_lints/src/methods/bytes_count_to_len.rs index a9f6a41c2357..b8cc5ddd845c 100644 --- a/clippy_lints/src/methods/bytes_count_to_len.rs +++ b/clippy_lints/src/methods/bytes_count_to_len.rs @@ -14,7 +14,7 @@ pub(super) fn check<'tcx>( bytes_recv: &'tcx hir::Expr<'_>, ) { if let Some(bytes_id) = cx.typeck_results().type_dependent_def_id(count_recv.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(bytes_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(bytes_id) && cx.tcx.type_of(impl_id).instantiate_identity().is_str() && let ty = cx.typeck_results().expr_ty(bytes_recv).peel_refs() && (ty.is_str() || is_type_lang_item(cx, ty, hir::LangItem::String)) diff --git a/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs b/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs index 292fa08b5984..6f9702f6c6c3 100644 --- a/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs +++ b/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs @@ -30,7 +30,7 @@ pub(super) fn check<'tcx>( } if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && cx.tcx.type_of(impl_id).instantiate_identity().is_str() && let ExprKind::Lit(Spanned { node: LitKind::Str(ext_literal, ..), diff --git a/clippy_lints/src/methods/get_first.rs b/clippy_lints/src/methods/get_first.rs index f4465e654c2e..2e1d71ce284d 100644 --- a/clippy_lints/src/methods/get_first.rs +++ b/clippy_lints/src/methods/get_first.rs @@ -18,7 +18,7 @@ pub(super) fn check<'tcx>( arg: &'tcx hir::Expr<'_>, ) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && let identity = cx.tcx.type_of(impl_id).instantiate_identity() && let hir::ExprKind::Lit(Spanned { node: LitKind::Int(Pu128(0), _), diff --git a/clippy_lints/src/methods/implicit_clone.rs b/clippy_lints/src/methods/implicit_clone.rs index 9724463f0c08..efa8cee58df7 100644 --- a/clippy_lints/src/methods/implicit_clone.rs +++ b/clippy_lints/src/methods/implicit_clone.rs @@ -50,7 +50,7 @@ pub fn is_clone_like(cx: &LateContext<'_>, method_name: Symbol, method_def_id: h sym::to_path_buf => is_diag_item_method(cx, method_def_id, sym::Path), sym::to_vec => cx .tcx - .impl_of_method(method_def_id) + .impl_of_assoc(method_def_id) .filter(|&impl_did| { cx.tcx.type_of(impl_did).instantiate_identity().is_slice() && cx.tcx.impl_trait_ref(impl_did).is_none() }) diff --git a/clippy_lints/src/methods/manual_ok_or.rs b/clippy_lints/src/methods/manual_ok_or.rs index c286c5faaed3..077957fa44dc 100644 --- a/clippy_lints/src/methods/manual_ok_or.rs +++ b/clippy_lints/src/methods/manual_ok_or.rs @@ -18,7 +18,7 @@ pub(super) fn check<'tcx>( map_expr: &'tcx Expr<'_>, ) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Option) && let ExprKind::Call(err_path, [err_arg]) = or_expr.kind && is_res_lang_ctor(cx, path_res(cx, err_path), ResultErr) diff --git a/clippy_lints/src/methods/map_clone.rs b/clippy_lints/src/methods/map_clone.rs index d016ace28bd4..748be9bfcc62 100644 --- a/clippy_lints/src/methods/map_clone.rs +++ b/clippy_lints/src/methods/map_clone.rs @@ -23,7 +23,7 @@ fn should_run_lint(cx: &LateContext<'_>, e: &hir::Expr<'_>, method_id: DefId) -> return true; } // We check if it's an `Option` or a `Result`. - if let Some(id) = cx.tcx.impl_of_method(method_id) { + if let Some(id) = cx.tcx.impl_of_assoc(method_id) { let identity = cx.tcx.type_of(id).instantiate_identity(); if !is_type_diagnostic_item(cx, identity, sym::Option) && !is_type_diagnostic_item(cx, identity, sym::Result) { return false; diff --git a/clippy_lints/src/methods/map_err_ignore.rs b/clippy_lints/src/methods/map_err_ignore.rs index 5d0d4dae35fa..41beda9c5cb4 100644 --- a/clippy_lints/src/methods/map_err_ignore.rs +++ b/clippy_lints/src/methods/map_err_ignore.rs @@ -8,7 +8,7 @@ use super::MAP_ERR_IGNORE; pub(super) fn check(cx: &LateContext<'_>, e: &Expr<'_>, arg: &Expr<'_>) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Result) && let ExprKind::Closure(&Closure { capture_clause: CaptureBy::Ref, diff --git a/clippy_lints/src/methods/mut_mutex_lock.rs b/clippy_lints/src/methods/mut_mutex_lock.rs index 320523aceb67..4235af882b0c 100644 --- a/clippy_lints/src/methods/mut_mutex_lock.rs +++ b/clippy_lints/src/methods/mut_mutex_lock.rs @@ -13,7 +13,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>, recv: &' && let (_, ref_depth, Mutability::Mut) = peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(recv)) && ref_depth >= 1 && let Some(method_id) = cx.typeck_results().type_dependent_def_id(ex.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Mutex) { span_lint_and_sugg( diff --git a/clippy_lints/src/methods/open_options.rs b/clippy_lints/src/methods/open_options.rs index 87e6cf021023..37a8e25bef96 100644 --- a/clippy_lints/src/methods/open_options.rs +++ b/clippy_lints/src/methods/open_options.rs @@ -18,7 +18,7 @@ fn is_open_options(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, recv: &'tcx Expr<'_>) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && is_open_options(cx, cx.tcx.type_of(impl_id).instantiate_identity()) { let mut options = Vec::new(); diff --git a/clippy_lints/src/methods/path_buf_push_overwrite.rs b/clippy_lints/src/methods/path_buf_push_overwrite.rs index 38d9c5f16778..32752ef7435f 100644 --- a/clippy_lints/src/methods/path_buf_push_overwrite.rs +++ b/clippy_lints/src/methods/path_buf_push_overwrite.rs @@ -11,7 +11,7 @@ use super::PATH_BUF_PUSH_OVERWRITE; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arg: &'tcx Expr<'_>) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::PathBuf) && let ExprKind::Lit(lit) = arg.kind && let LitKind::Str(ref path_lit, _) = lit.node diff --git a/clippy_lints/src/methods/stable_sort_primitive.rs b/clippy_lints/src/methods/stable_sort_primitive.rs index aef14435d8af..17d1a6abde0a 100644 --- a/clippy_lints/src/methods/stable_sort_primitive.rs +++ b/clippy_lints/src/methods/stable_sort_primitive.rs @@ -9,7 +9,7 @@ use super::STABLE_SORT_PRIMITIVE; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, recv: &'tcx Expr<'_>) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && cx.tcx.type_of(impl_id).instantiate_identity().is_slice() && let Some(slice_type) = is_slice_of_primitives(cx, recv) { diff --git a/clippy_lints/src/methods/suspicious_splitn.rs b/clippy_lints/src/methods/suspicious_splitn.rs index f8b6d4349fbe..9876681ddbb3 100644 --- a/clippy_lints/src/methods/suspicious_splitn.rs +++ b/clippy_lints/src/methods/suspicious_splitn.rs @@ -10,7 +10,7 @@ use super::SUSPICIOUS_SPLITN; pub(super) fn check(cx: &LateContext<'_>, method_name: Symbol, expr: &Expr<'_>, self_arg: &Expr<'_>, count: u128) { if count <= 1 && let Some(call_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(call_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(call_id) && cx.tcx.impl_trait_ref(impl_id).is_none() && let self_ty = cx.tcx.type_of(impl_id).instantiate_identity() && (self_ty.is_slice() || self_ty.is_str()) diff --git a/clippy_lints/src/methods/unnecessary_sort_by.rs b/clippy_lints/src/methods/unnecessary_sort_by.rs index dbff08bc51c9..1de9f6ab4970 100644 --- a/clippy_lints/src/methods/unnecessary_sort_by.rs +++ b/clippy_lints/src/methods/unnecessary_sort_by.rs @@ -114,7 +114,7 @@ fn mirrored_exprs(a_expr: &Expr<'_>, a_ident: &Ident, b_expr: &Expr<'_>, b_ident fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, arg: &Expr<'_>) -> Option { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && cx.tcx.type_of(impl_id).instantiate_identity().is_slice() && let ExprKind::Closure(&Closure { body, .. }) = arg.kind && let closure_body = cx.tcx.hir_body(body) diff --git a/clippy_lints/src/methods/unnecessary_to_owned.rs b/clippy_lints/src/methods/unnecessary_to_owned.rs index a86428808216..54f45263275c 100644 --- a/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -694,7 +694,7 @@ fn check_if_applicable_to_argument<'tcx>(cx: &LateContext<'tcx>, arg: &Expr<'tcx sym::to_string => cx.tcx.is_diagnostic_item(sym::to_string_method, method_def_id), sym::to_vec => cx .tcx - .impl_of_method(method_def_id) + .impl_of_assoc(method_def_id) .filter(|&impl_did| cx.tcx.type_of(impl_did).instantiate_identity().is_slice()) .is_some(), _ => false, diff --git a/clippy_lints/src/methods/useless_asref.rs b/clippy_lints/src/methods/useless_asref.rs index d9cf8273fada..38fad239f679 100644 --- a/clippy_lints/src/methods/useless_asref.rs +++ b/clippy_lints/src/methods/useless_asref.rs @@ -79,7 +79,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: Symbo applicability, ); } - } else if let Some(impl_id) = cx.tcx.impl_of_method(def_id) + } else if let Some(impl_id) = cx.tcx.impl_of_assoc(def_id) && let Some(adt) = cx.tcx.type_of(impl_id).instantiate_identity().ty_adt_def() && matches!(cx.tcx.get_diagnostic_name(adt.did()), Some(sym::Option | sym::Result)) { diff --git a/clippy_lints/src/methods/vec_resize_to_zero.rs b/clippy_lints/src/methods/vec_resize_to_zero.rs index 5ea4ada128a2..bfb481f4fc09 100644 --- a/clippy_lints/src/methods/vec_resize_to_zero.rs +++ b/clippy_lints/src/methods/vec_resize_to_zero.rs @@ -18,7 +18,7 @@ pub(super) fn check<'tcx>( name_span: Span, ) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + && let Some(impl_id) = cx.tcx.impl_of_assoc(method_id) && is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Vec) && let ExprKind::Lit(Spanned { node: LitKind::Int(Pu128(0), _), diff --git a/clippy_lints/src/operators/op_ref.rs b/clippy_lints/src/operators/op_ref.rs index 21e1ab0f4f27..0a1f2625f4cf 100644 --- a/clippy_lints/src/operators/op_ref.rs +++ b/clippy_lints/src/operators/op_ref.rs @@ -179,7 +179,7 @@ fn in_impl<'tcx>( bin_op: DefId, ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, &'tcx rustc_hir::Ty<'tcx>)> { if let Some(block) = get_enclosing_block(cx, e.hir_id) - && let Some(impl_def_id) = cx.tcx.impl_of_method(block.hir_id.owner.to_def_id()) + && let Some(impl_def_id) = cx.tcx.impl_of_assoc(block.hir_id.owner.to_def_id()) && let item = cx.tcx.hir_expect_item(impl_def_id.expect_local()) && let ItemKind::Impl(item) = &item.kind && let Some(of_trait) = &item.of_trait diff --git a/clippy_lints/src/return_self_not_must_use.rs b/clippy_lints/src/return_self_not_must_use.rs index 25929b853af8..3497216d1c56 100644 --- a/clippy_lints/src/return_self_not_must_use.rs +++ b/clippy_lints/src/return_self_not_must_use.rs @@ -113,7 +113,7 @@ impl<'tcx> LateLintPass<'tcx> for ReturnSelfNotMustUse { ) { if matches!(kind, FnKind::Method(_, _)) // We are only interested in methods, not in functions or associated functions. - && let Some(impl_def) = cx.tcx.impl_of_method(fn_def.to_def_id()) + && let Some(impl_def) = cx.tcx.impl_of_assoc(fn_def.to_def_id()) // We don't want this method to be te implementation of a trait because the // `#[must_use]` should be put on the trait definition directly. && cx.tcx.trait_id_of_impl(impl_def).is_none() diff --git a/clippy_lints/src/unused_io_amount.rs b/clippy_lints/src/unused_io_amount.rs index bed5c0fc0150..f3cd3f1bb286 100644 --- a/clippy_lints/src/unused_io_amount.rs +++ b/clippy_lints/src/unused_io_amount.rs @@ -84,7 +84,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedIoAmount { /// get desugared to match. fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'tcx>) { let fn_def_id = block.hir_id.owner.to_def_id(); - if let Some(impl_id) = cx.tcx.impl_of_method(fn_def_id) + if let Some(impl_id) = cx.tcx.impl_of_assoc(fn_def_id) && let Some(trait_id) = cx.tcx.trait_id_of_impl(impl_id) { // We don't want to lint inside io::Read or io::Write implementations, as the author has more diff --git a/clippy_utils/src/eager_or_lazy.rs b/clippy_utils/src/eager_or_lazy.rs index 9d38672efada..eb3f442ac754 100644 --- a/clippy_utils/src/eager_or_lazy.rs +++ b/clippy_utils/src/eager_or_lazy.rs @@ -51,7 +51,7 @@ impl ops::BitOrAssign for EagernessSuggestion { fn fn_eagerness(cx: &LateContext<'_>, fn_id: DefId, name: Symbol, have_one_arg: bool) -> EagernessSuggestion { use EagernessSuggestion::{Eager, Lazy, NoChange}; - let ty = match cx.tcx.impl_of_method(fn_id) { + let ty = match cx.tcx.impl_of_assoc(fn_id) { Some(id) => cx.tcx.type_of(id).instantiate_identity(), None => return Lazy, }; diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 211af4d5b089..67e09e772a77 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -357,7 +357,7 @@ pub fn is_inherent_method_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { /// Checks if a method is defined in an impl of a diagnostic item pub fn is_diag_item_method(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbol) -> bool { - if let Some(impl_did) = cx.tcx.impl_of_method(def_id) + if let Some(impl_did) = cx.tcx.impl_of_assoc(def_id) && let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().ty_adt_def() { return cx.tcx.is_diagnostic_item(diag_item, adt.did()); @@ -620,7 +620,7 @@ fn is_default_equivalent_ctor(cx: &LateContext<'_>, def_id: DefId, path: &QPath< if let QPath::TypeRelative(_, method) = path && method.ident.name == sym::new - && let Some(impl_did) = cx.tcx.impl_of_method(def_id) + && let Some(impl_did) = cx.tcx.impl_of_assoc(def_id) && let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().ty_adt_def() { return std_types_symbols.iter().any(|&symbol| { From 4f1044a5a6c7b9ea1c9a46f61a4a20c8e8761fec Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 28 Jul 2025 17:09:20 +0200 Subject: [PATCH 0178/1134] Do not specialize for `if_chain` any longer Now that `if let` chains have been introduced, the `if_chain` external crate is no longer necessary. Dropping special support for it also alleviates the need to keep the crate as a dependency in tests. --- clippy_lints/src/index_refutable_slice.rs | 4 ++-- clippy_test_deps/Cargo.lock | 7 ------- clippy_test_deps/Cargo.toml | 1 - clippy_utils/src/sym.rs | 1 - tests/compile-test.rs | 3 +-- .../slice_indexing_in_macro.fixed | 12 +++--------- .../index_refutable_slice/slice_indexing_in_macro.rs | 12 +++--------- .../slice_indexing_in_macro.stderr | 11 +++++------ 8 files changed, 14 insertions(+), 37 deletions(-) diff --git a/clippy_lints/src/index_refutable_slice.rs b/clippy_lints/src/index_refutable_slice.rs index 3d131a7825af..8f9f71a14769 100644 --- a/clippy_lints/src/index_refutable_slice.rs +++ b/clippy_lints/src/index_refutable_slice.rs @@ -4,7 +4,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::higher::IfLet; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::ty::is_copy; -use clippy_utils::{is_expn_of, is_lint_allowed, path_to_local, sym}; +use clippy_utils::{is_lint_allowed, path_to_local}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_errors::Applicability; use rustc_hir as hir; @@ -71,7 +71,7 @@ impl_lint_pass!(IndexRefutableSlice => [INDEX_REFUTABLE_SLICE]); impl<'tcx> LateLintPass<'tcx> for IndexRefutableSlice { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { if let Some(IfLet { let_pat, if_then, .. }) = IfLet::hir(cx, expr) - && (!expr.span.from_expansion() || is_expn_of(expr.span, sym::if_chain).is_some()) + && !expr.span.from_expansion() && !is_lint_allowed(cx, INDEX_REFUTABLE_SLICE, expr.hir_id) && let found_slices = find_slice_values(cx, let_pat) && !found_slices.is_empty() diff --git a/clippy_test_deps/Cargo.lock b/clippy_test_deps/Cargo.lock index 5be404f24e6f..2f987c0137c9 100644 --- a/clippy_test_deps/Cargo.lock +++ b/clippy_test_deps/Cargo.lock @@ -70,7 +70,6 @@ name = "clippy_test_deps" version = "0.1.0" dependencies = [ "futures", - "if_chain", "itertools", "libc", "parking_lot", @@ -182,12 +181,6 @@ version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" -[[package]] -name = "if_chain" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" - [[package]] name = "io-uring" version = "0.7.8" diff --git a/clippy_test_deps/Cargo.toml b/clippy_test_deps/Cargo.toml index fcedc5d4843c..e449b48bc460 100644 --- a/clippy_test_deps/Cargo.toml +++ b/clippy_test_deps/Cargo.toml @@ -9,7 +9,6 @@ edition = "2021" libc = "0.2" regex = "1.5.5" serde = { version = "1.0.145", features = ["derive"] } -if_chain = "1.0" quote = "1.0.25" syn = { version = "2.0", features = ["full"] } futures = "0.3" diff --git a/clippy_utils/src/sym.rs b/clippy_utils/src/sym.rs index 934be97d94e5..ce7cc9348fbd 100644 --- a/clippy_utils/src/sym.rs +++ b/clippy_utils/src/sym.rs @@ -171,7 +171,6 @@ generate! { has_significant_drop, hidden_glob_reexports, hygiene, - if_chain, insert, inspect, int_roundings, diff --git a/tests/compile-test.rs b/tests/compile-test.rs index 464efc45c6b4..664a748ee21e 100644 --- a/tests/compile-test.rs +++ b/tests/compile-test.rs @@ -73,8 +73,7 @@ fn internal_extern_flags() -> Vec { && INTERNAL_TEST_DEPENDENCIES.contains(&name) { // A dependency may be listed twice if it is available in sysroot, - // and the sysroot dependencies are listed first. As of the writing, - // this only seems to apply to if_chain. + // and the sysroot dependencies are listed first. crates.insert(name, path); } } diff --git a/tests/ui/index_refutable_slice/slice_indexing_in_macro.fixed b/tests/ui/index_refutable_slice/slice_indexing_in_macro.fixed index 72edc539f043..edf6f014d3d0 100644 --- a/tests/ui/index_refutable_slice/slice_indexing_in_macro.fixed +++ b/tests/ui/index_refutable_slice/slice_indexing_in_macro.fixed @@ -1,8 +1,5 @@ #![deny(clippy::index_refutable_slice)] -extern crate if_chain; -use if_chain::if_chain; - macro_rules! if_let_slice_macro { () => { // This would normally be linted @@ -18,12 +15,9 @@ fn main() { if_let_slice_macro!(); // Do lint this - if_chain! { - let slice: Option<&[u32]> = Some(&[1, 2, 3]); - if let Some([slice_0, ..]) = slice; + let slice: Option<&[u32]> = Some(&[1, 2, 3]); + if let Some([slice_0, ..]) = slice { //~^ ERROR: this binding can be a slice pattern to avoid indexing - then { - println!("{}", slice_0); - } + println!("{}", slice_0); } } diff --git a/tests/ui/index_refutable_slice/slice_indexing_in_macro.rs b/tests/ui/index_refutable_slice/slice_indexing_in_macro.rs index 7b474ba423b9..76d4a2350f50 100644 --- a/tests/ui/index_refutable_slice/slice_indexing_in_macro.rs +++ b/tests/ui/index_refutable_slice/slice_indexing_in_macro.rs @@ -1,8 +1,5 @@ #![deny(clippy::index_refutable_slice)] -extern crate if_chain; -use if_chain::if_chain; - macro_rules! if_let_slice_macro { () => { // This would normally be linted @@ -18,12 +15,9 @@ fn main() { if_let_slice_macro!(); // Do lint this - if_chain! { - let slice: Option<&[u32]> = Some(&[1, 2, 3]); - if let Some(slice) = slice; + let slice: Option<&[u32]> = Some(&[1, 2, 3]); + if let Some(slice) = slice { //~^ ERROR: this binding can be a slice pattern to avoid indexing - then { - println!("{}", slice[0]); - } + println!("{}", slice[0]); } } diff --git a/tests/ui/index_refutable_slice/slice_indexing_in_macro.stderr b/tests/ui/index_refutable_slice/slice_indexing_in_macro.stderr index 64741abb9114..635e6d19aef2 100644 --- a/tests/ui/index_refutable_slice/slice_indexing_in_macro.stderr +++ b/tests/ui/index_refutable_slice/slice_indexing_in_macro.stderr @@ -1,8 +1,8 @@ error: this binding can be a slice pattern to avoid indexing - --> tests/ui/index_refutable_slice/slice_indexing_in_macro.rs:23:21 + --> tests/ui/index_refutable_slice/slice_indexing_in_macro.rs:19:17 | -LL | if let Some(slice) = slice; - | ^^^^^ +LL | if let Some(slice) = slice { + | ^^^^^ | note: the lint level is defined here --> tests/ui/index_refutable_slice/slice_indexing_in_macro.rs:1:9 @@ -11,10 +11,9 @@ LL | #![deny(clippy::index_refutable_slice)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace the binding and indexed access with a slice pattern | -LL ~ if let Some([slice_0, ..]) = slice; +LL ~ if let Some([slice_0, ..]) = slice { LL | -LL | then { -LL ~ println!("{}", slice_0); +LL ~ println!("{}", slice_0); | error: aborting due to 1 previous error From 431f95ec85c92ff7ae1b9d54ce94a8d1411fb166 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 28 Jul 2025 17:31:21 +0200 Subject: [PATCH 0179/1134] Fix typo in internal error message --- tests/symbols-used.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/symbols-used.rs b/tests/symbols-used.rs index bc0456711fb2..a1049ba64d54 100644 --- a/tests/symbols-used.rs +++ b/tests/symbols-used.rs @@ -75,7 +75,7 @@ fn all_symbols_are_used() -> Result<()> { for sym in extra { eprintln!(" - {sym}"); } - Err(format!("extra symbols found — remove them {SYM_FILE}"))?; + Err(format!("extra symbols found — remove them from {SYM_FILE}"))?; } Ok(()) } From 081b5654789f60d7303e05a26f86c80d0594f531 Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 28 Jul 2025 19:50:53 +0100 Subject: [PATCH 0180/1134] Allow `cargo fix` to partially apply `mismatched_lifetime_syntaxes` --- compiler/rustc_lint/src/lifetime_syntax.rs | 9 ++-- compiler/rustc_lint/src/lints.rs | 60 ++++++++++++++-------- 2 files changed, 45 insertions(+), 24 deletions(-) diff --git a/compiler/rustc_lint/src/lifetime_syntax.rs b/compiler/rustc_lint/src/lifetime_syntax.rs index 2a5a34cdc6e9..464f4fc34b96 100644 --- a/compiler/rustc_lint/src/lifetime_syntax.rs +++ b/compiler/rustc_lint/src/lifetime_syntax.rs @@ -434,7 +434,7 @@ fn emit_mismatch_diagnostic<'tcx>( lints::MismatchedLifetimeSyntaxesSuggestion::Mixed { implicit_suggestions, explicit_anonymous_suggestions, - tool_only: false, + optional_alternative: false, } }); @@ -455,7 +455,10 @@ fn emit_mismatch_diagnostic<'tcx>( let implicit_suggestion = should_suggest_implicit.then(|| { let suggestions = make_implicit_suggestions(&suggest_change_to_implicit); - lints::MismatchedLifetimeSyntaxesSuggestion::Implicit { suggestions, tool_only: false } + lints::MismatchedLifetimeSyntaxesSuggestion::Implicit { + suggestions, + optional_alternative: false, + } }); tracing::debug!( @@ -508,7 +511,7 @@ fn build_mismatch_suggestion( lints::MismatchedLifetimeSyntaxesSuggestion::Explicit { lifetime_name, suggestions, - tool_only: false, + optional_alternative: false, } } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index fd8d0f832aa4..a5f9255e7709 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -3276,7 +3276,7 @@ impl<'a, G: EmissionGuarantee> LintDiagnostic<'a, G> for MismatchedLifetimeSynta diag.subdiagnostic(s); for mut s in suggestions { - s.make_tool_only(); + s.make_optional_alternative(); diag.subdiagnostic(s); } } @@ -3287,33 +3287,33 @@ impl<'a, G: EmissionGuarantee> LintDiagnostic<'a, G> for MismatchedLifetimeSynta pub(crate) enum MismatchedLifetimeSyntaxesSuggestion { Implicit { suggestions: Vec, - tool_only: bool, + optional_alternative: bool, }, Mixed { implicit_suggestions: Vec, explicit_anonymous_suggestions: Vec<(Span, String)>, - tool_only: bool, + optional_alternative: bool, }, Explicit { lifetime_name: String, suggestions: Vec<(Span, String)>, - tool_only: bool, + optional_alternative: bool, }, } impl MismatchedLifetimeSyntaxesSuggestion { - fn make_tool_only(&mut self) { + fn make_optional_alternative(&mut self) { use MismatchedLifetimeSyntaxesSuggestion::*; - let tool_only = match self { - Implicit { tool_only, .. } | Mixed { tool_only, .. } | Explicit { tool_only, .. } => { - tool_only - } + let optional_alternative = match self { + Implicit { optional_alternative, .. } + | Mixed { optional_alternative, .. } + | Explicit { optional_alternative, .. } => optional_alternative, }; - *tool_only = true; + *optional_alternative = true; } } @@ -3321,22 +3321,40 @@ impl Subdiagnostic for MismatchedLifetimeSyntaxesSuggestion { fn add_to_diag(self, diag: &mut Diag<'_, G>) { use MismatchedLifetimeSyntaxesSuggestion::*; - let style = |tool_only| { - if tool_only { SuggestionStyle::CompletelyHidden } else { SuggestionStyle::ShowAlways } + let style = |optional_alternative| { + if optional_alternative { + SuggestionStyle::CompletelyHidden + } else { + SuggestionStyle::ShowAlways + } + }; + + let applicability = |optional_alternative| { + // `cargo fix` can't handle more than one fix for the same issue, + // so hide alternative suggestions from it by marking them as maybe-incorrect + if optional_alternative { + Applicability::MaybeIncorrect + } else { + Applicability::MachineApplicable + } }; match self { - Implicit { suggestions, tool_only } => { + Implicit { suggestions, optional_alternative } => { let suggestions = suggestions.into_iter().map(|s| (s, String::new())).collect(); diag.multipart_suggestion_with_style( fluent::lint_mismatched_lifetime_syntaxes_suggestion_implicit, suggestions, - Applicability::MaybeIncorrect, - style(tool_only), + applicability(optional_alternative), + style(optional_alternative), ); } - Mixed { implicit_suggestions, explicit_anonymous_suggestions, tool_only } => { + Mixed { + implicit_suggestions, + explicit_anonymous_suggestions, + optional_alternative, + } => { let message = if implicit_suggestions.is_empty() { fluent::lint_mismatched_lifetime_syntaxes_suggestion_mixed_only_paths } else { @@ -3352,12 +3370,12 @@ impl Subdiagnostic for MismatchedLifetimeSyntaxesSuggestion { diag.multipart_suggestion_with_style( message, suggestions, - Applicability::MaybeIncorrect, - style(tool_only), + applicability(optional_alternative), + style(optional_alternative), ); } - Explicit { lifetime_name, suggestions, tool_only } => { + Explicit { lifetime_name, suggestions, optional_alternative } => { diag.arg("lifetime_name", lifetime_name); let msg = diag.eagerly_translate( fluent::lint_mismatched_lifetime_syntaxes_suggestion_explicit, @@ -3366,8 +3384,8 @@ impl Subdiagnostic for MismatchedLifetimeSyntaxesSuggestion { diag.multipart_suggestion_with_style( msg, suggestions, - Applicability::MaybeIncorrect, - style(tool_only), + applicability(optional_alternative), + style(optional_alternative), ); } } From ca58013caab2ce7855468177df579bb99ac49fdb Mon Sep 17 00:00:00 2001 From: Philip Woolford Date: Tue, 29 Jul 2025 09:48:59 +0930 Subject: [PATCH 0181/1134] Enable features that are always available in a live system. While some neon and crypto features may not be supported on the switch at boot (e.g. on the a53 cores), the features will _always_ be available if running as a sysmodule or homebrew application under Horizon/Atmosphere. --- .../src/spec/targets/aarch64_nintendo_switch_freestanding.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/spec/targets/aarch64_nintendo_switch_freestanding.rs b/compiler/rustc_target/src/spec/targets/aarch64_nintendo_switch_freestanding.rs index 9b81362b27db..8d5390f57718 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_nintendo_switch_freestanding.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_nintendo_switch_freestanding.rs @@ -19,7 +19,7 @@ pub(crate) fn target() -> Target { data_layout: "e-m:e-p270:32:32-p271:32:32-p272:64:64-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128-Fn32".into(), arch: "aarch64".into(), options: TargetOptions { - features: "+v8a".into(), + features: "+v8a,+neon,+crypto".into(), linker_flavor: LinkerFlavor::Gnu(Cc::No, Lld::Yes), linker: Some("rust-lld".into()), link_script: Some(LINKER_SCRIPT.into()), From 0e53d8533bf0bb8d6bc59bb000fe7cc7a361902e Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 16 Jun 2025 15:25:31 +0000 Subject: [PATCH 0182/1134] Fortify RemoveUnneededDrops test. --- ...annot_opt_generic.RemoveUnneededDrops.diff | 15 +++++++ ...neric.RemoveUnneededDrops.panic-abort.diff | 26 ------------ ...eric.RemoveUnneededDrops.panic-unwind.diff | 30 -------------- ...ed_drops.dont_opt.RemoveUnneededDrops.diff | 15 +++++++ ...t_opt.RemoveUnneededDrops.panic-abort.diff | 26 ------------ ..._opt.RemoveUnneededDrops.panic-unwind.diff | 30 -------------- ...nneeded_drops.opt.RemoveUnneededDrops.diff | 15 +++++++ ...s.opt.RemoveUnneededDrops.panic-abort.diff | 26 ------------ ....opt.RemoveUnneededDrops.panic-unwind.diff | 26 ------------ ....opt_generic_copy.RemoveUnneededDrops.diff | 15 +++++++ ..._copy.RemoveUnneededDrops.panic-abort.diff | 26 ------------ ...copy.RemoveUnneededDrops.panic-unwind.diff | 26 ------------ tests/mir-opt/remove_unneeded_drops.rs | 40 ++++++++++++++++--- 13 files changed, 94 insertions(+), 222 deletions(-) create mode 100644 tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.diff delete mode 100644 tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.panic-abort.diff delete mode 100644 tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.panic-unwind.diff create mode 100644 tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.diff delete mode 100644 tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.panic-abort.diff delete mode 100644 tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.panic-unwind.diff create mode 100644 tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.diff delete mode 100644 tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.panic-abort.diff delete mode 100644 tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.panic-unwind.diff create mode 100644 tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.diff delete mode 100644 tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.panic-abort.diff delete mode 100644 tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.panic-unwind.diff diff --git a/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.diff b/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.diff new file mode 100644 index 000000000000..52832e739051 --- /dev/null +++ b/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.diff @@ -0,0 +1,15 @@ +- // MIR for `cannot_opt_generic` before RemoveUnneededDrops ++ // MIR for `cannot_opt_generic` after RemoveUnneededDrops + + fn cannot_opt_generic(_1: T) -> () { + let mut _0: (); + + bb0: { + drop(_1) -> [return: bb1, unwind unreachable]; + } + + bb1: { + return; + } + } + diff --git a/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.panic-abort.diff b/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.panic-abort.diff deleted file mode 100644 index 0c73602bec84..000000000000 --- a/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.panic-abort.diff +++ /dev/null @@ -1,26 +0,0 @@ -- // MIR for `cannot_opt_generic` before RemoveUnneededDrops -+ // MIR for `cannot_opt_generic` after RemoveUnneededDrops - - fn cannot_opt_generic(_1: T) -> () { - debug x => _1; - let mut _0: (); - let _2: (); - let mut _3: T; - scope 1 (inlined std::mem::drop::) { - } - - bb0: { - nop; - StorageLive(_3); - _3 = move _1; - drop(_3) -> [return: bb1, unwind unreachable]; - } - - bb1: { - StorageDead(_3); - nop; - nop; - return; - } - } - diff --git a/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.panic-unwind.diff b/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.panic-unwind.diff deleted file mode 100644 index 59cce9fbcdd0..000000000000 --- a/tests/mir-opt/remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.panic-unwind.diff +++ /dev/null @@ -1,30 +0,0 @@ -- // MIR for `cannot_opt_generic` before RemoveUnneededDrops -+ // MIR for `cannot_opt_generic` after RemoveUnneededDrops - - fn cannot_opt_generic(_1: T) -> () { - debug x => _1; - let mut _0: (); - let _2: (); - let mut _3: T; - scope 1 (inlined std::mem::drop::) { - } - - bb0: { - nop; - StorageLive(_3); - _3 = move _1; - drop(_3) -> [return: bb2, unwind: bb1]; - } - - bb1 (cleanup): { - resume; - } - - bb2: { - StorageDead(_3); - nop; - nop; - return; - } - } - diff --git a/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.diff b/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.diff new file mode 100644 index 000000000000..3d67cada5ddf --- /dev/null +++ b/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.diff @@ -0,0 +1,15 @@ +- // MIR for `dont_opt` before RemoveUnneededDrops ++ // MIR for `dont_opt` after RemoveUnneededDrops + + fn dont_opt(_1: Vec) -> () { + let mut _0: (); + + bb0: { + drop(_1) -> [return: bb1, unwind unreachable]; + } + + bb1: { + return; + } + } + diff --git a/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.panic-abort.diff b/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.panic-abort.diff deleted file mode 100644 index 428b366b5a68..000000000000 --- a/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.panic-abort.diff +++ /dev/null @@ -1,26 +0,0 @@ -- // MIR for `dont_opt` before RemoveUnneededDrops -+ // MIR for `dont_opt` after RemoveUnneededDrops - - fn dont_opt(_1: Vec) -> () { - debug x => _1; - let mut _0: (); - let _2: (); - let mut _3: std::vec::Vec; - scope 1 (inlined std::mem::drop::>) { - } - - bb0: { - nop; - StorageLive(_3); - _3 = move _1; - drop(_3) -> [return: bb1, unwind unreachable]; - } - - bb1: { - StorageDead(_3); - nop; - nop; - return; - } - } - diff --git a/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.panic-unwind.diff b/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.panic-unwind.diff deleted file mode 100644 index 445c1f82a96f..000000000000 --- a/tests/mir-opt/remove_unneeded_drops.dont_opt.RemoveUnneededDrops.panic-unwind.diff +++ /dev/null @@ -1,30 +0,0 @@ -- // MIR for `dont_opt` before RemoveUnneededDrops -+ // MIR for `dont_opt` after RemoveUnneededDrops - - fn dont_opt(_1: Vec) -> () { - debug x => _1; - let mut _0: (); - let _2: (); - let mut _3: std::vec::Vec; - scope 1 (inlined std::mem::drop::>) { - } - - bb0: { - nop; - StorageLive(_3); - _3 = move _1; - drop(_3) -> [return: bb2, unwind: bb1]; - } - - bb1 (cleanup): { - resume; - } - - bb2: { - StorageDead(_3); - nop; - nop; - return; - } - } - diff --git a/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.diff b/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.diff new file mode 100644 index 000000000000..cb7e58ca1a1f --- /dev/null +++ b/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.diff @@ -0,0 +1,15 @@ +- // MIR for `opt` before RemoveUnneededDrops ++ // MIR for `opt` after RemoveUnneededDrops + + fn opt(_1: bool) -> () { + let mut _0: (); + + bb0: { +- drop(_1) -> [return: bb1, unwind unreachable]; +- } +- +- bb1: { + return; + } + } + diff --git a/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.panic-abort.diff b/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.panic-abort.diff deleted file mode 100644 index 01eb6d4901f7..000000000000 --- a/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.panic-abort.diff +++ /dev/null @@ -1,26 +0,0 @@ -- // MIR for `opt` before RemoveUnneededDrops -+ // MIR for `opt` after RemoveUnneededDrops - - fn opt(_1: bool) -> () { - debug x => _1; - let mut _0: (); - let _2: (); - let mut _3: bool; - scope 1 (inlined std::mem::drop::) { - } - - bb0: { -- nop; - StorageLive(_3); - _3 = copy _1; -- drop(_3) -> [return: bb1, unwind unreachable]; -- } -- -- bb1: { - StorageDead(_3); -- nop; -- nop; - return; - } - } - diff --git a/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.panic-unwind.diff b/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.panic-unwind.diff deleted file mode 100644 index c2c3cb76e832..000000000000 --- a/tests/mir-opt/remove_unneeded_drops.opt.RemoveUnneededDrops.panic-unwind.diff +++ /dev/null @@ -1,26 +0,0 @@ -- // MIR for `opt` before RemoveUnneededDrops -+ // MIR for `opt` after RemoveUnneededDrops - - fn opt(_1: bool) -> () { - debug x => _1; - let mut _0: (); - let _2: (); - let mut _3: bool; - scope 1 (inlined std::mem::drop::) { - } - - bb0: { -- nop; - StorageLive(_3); - _3 = copy _1; -- drop(_3) -> [return: bb1, unwind continue]; -- } -- -- bb1: { - StorageDead(_3); -- nop; -- nop; - return; - } - } - diff --git a/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.diff b/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.diff new file mode 100644 index 000000000000..1e166eee9fb0 --- /dev/null +++ b/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.diff @@ -0,0 +1,15 @@ +- // MIR for `opt_generic_copy` before RemoveUnneededDrops ++ // MIR for `opt_generic_copy` after RemoveUnneededDrops + + fn opt_generic_copy(_1: T) -> () { + let mut _0: (); + + bb0: { +- drop(_1) -> [return: bb1, unwind unreachable]; +- } +- +- bb1: { + return; + } + } + diff --git a/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.panic-abort.diff b/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.panic-abort.diff deleted file mode 100644 index a82ede6196ed..000000000000 --- a/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.panic-abort.diff +++ /dev/null @@ -1,26 +0,0 @@ -- // MIR for `opt_generic_copy` before RemoveUnneededDrops -+ // MIR for `opt_generic_copy` after RemoveUnneededDrops - - fn opt_generic_copy(_1: T) -> () { - debug x => _1; - let mut _0: (); - let _2: (); - let mut _3: T; - scope 1 (inlined std::mem::drop::) { - } - - bb0: { -- nop; - StorageLive(_3); - _3 = copy _1; -- drop(_3) -> [return: bb1, unwind unreachable]; -- } -- -- bb1: { - StorageDead(_3); -- nop; -- nop; - return; - } - } - diff --git a/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.panic-unwind.diff b/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.panic-unwind.diff deleted file mode 100644 index 6e7c9ead740f..000000000000 --- a/tests/mir-opt/remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.panic-unwind.diff +++ /dev/null @@ -1,26 +0,0 @@ -- // MIR for `opt_generic_copy` before RemoveUnneededDrops -+ // MIR for `opt_generic_copy` after RemoveUnneededDrops - - fn opt_generic_copy(_1: T) -> () { - debug x => _1; - let mut _0: (); - let _2: (); - let mut _3: T; - scope 1 (inlined std::mem::drop::) { - } - - bb0: { -- nop; - StorageLive(_3); - _3 = copy _1; -- drop(_3) -> [return: bb1, unwind continue]; -- } -- -- bb1: { - StorageDead(_3); -- nop; -- nop; - return; - } - } - diff --git a/tests/mir-opt/remove_unneeded_drops.rs b/tests/mir-opt/remove_unneeded_drops.rs index cad79e0aa0cb..49dc611838e3 100644 --- a/tests/mir-opt/remove_unneeded_drops.rs +++ b/tests/mir-opt/remove_unneeded_drops.rs @@ -1,28 +1,56 @@ -// skip-filecheck -// EMIT_MIR_FOR_EACH_PANIC_STRATEGY +//@ test-mir-pass: RemoveUnneededDrops + +#![feature(custom_mir, core_intrinsics)] +use std::intrinsics::mir::*; + // EMIT_MIR remove_unneeded_drops.opt.RemoveUnneededDrops.diff +#[custom_mir(dialect = "runtime")] fn opt(x: bool) { - drop(x); + // CHECK-LABEL: fn opt( + // CHECK-NOT: drop( + mir! { + { Drop(x, ReturnTo(bb1), UnwindUnreachable()) } + bb1 = { Return() } + } } // EMIT_MIR remove_unneeded_drops.dont_opt.RemoveUnneededDrops.diff +#[custom_mir(dialect = "runtime")] fn dont_opt(x: Vec) { - drop(x); + // CHECK-LABEL: fn dont_opt( + // CHECK: drop( + mir! { + { Drop(x, ReturnTo(bb1), UnwindUnreachable()) } + bb1 = { Return() } + } } // EMIT_MIR remove_unneeded_drops.opt_generic_copy.RemoveUnneededDrops.diff +#[custom_mir(dialect = "runtime")] fn opt_generic_copy(x: T) { - drop(x); + // CHECK-LABEL: fn opt_generic_copy( + // CHECK-NOT: drop( + mir! { + { Drop(x, ReturnTo(bb1), UnwindUnreachable()) } + bb1 = { Return() } + } } // EMIT_MIR remove_unneeded_drops.cannot_opt_generic.RemoveUnneededDrops.diff // since the pass is not running on monomorphisized code, // we can't (but probably should) optimize this +#[custom_mir(dialect = "runtime")] fn cannot_opt_generic(x: T) { - drop(x); + // CHECK-LABEL: fn cannot_opt_generic( + // CHECK: drop( + mir! { + { Drop(x, ReturnTo(bb1), UnwindUnreachable()) } + bb1 = { Return() } + } } fn main() { + // CHECK-LABEL: fn main( opt(true); opt_generic_copy(42); cannot_opt_generic(42); From 05cd6e854b09ce803b72443f94f3e58e71c24db6 Mon Sep 17 00:00:00 2001 From: Philip Woolford Date: Tue, 29 Jul 2025 11:01:22 +0930 Subject: [PATCH 0183/1134] Add the CRC instructions. --- .../src/spec/targets/aarch64_nintendo_switch_freestanding.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/spec/targets/aarch64_nintendo_switch_freestanding.rs b/compiler/rustc_target/src/spec/targets/aarch64_nintendo_switch_freestanding.rs index 8d5390f57718..61e4cad3fa20 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_nintendo_switch_freestanding.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_nintendo_switch_freestanding.rs @@ -19,7 +19,7 @@ pub(crate) fn target() -> Target { data_layout: "e-m:e-p270:32:32-p271:32:32-p272:64:64-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128-Fn32".into(), arch: "aarch64".into(), options: TargetOptions { - features: "+v8a,+neon,+crypto".into(), + features: "+v8a,+neon,+crypto,+crc".into(), linker_flavor: LinkerFlavor::Gnu(Cc::No, Lld::Yes), linker: Some("rust-lld".into()), link_script: Some(LINKER_SCRIPT.into()), From 8b214fbf17d4e6f8e3ba38a26cffd741ac53adb8 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 29 Jul 2025 08:31:08 +0200 Subject: [PATCH 0184/1134] fix: Do not require all rename definitions to be renameable --- src/tools/rust-analyzer/crates/ide/src/rename.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/rename.rs b/src/tools/rust-analyzer/crates/ide/src/rename.rs index a07c647c2cb8..6c1d142c3b05 100644 --- a/src/tools/rust-analyzer/crates/ide/src/rename.rs +++ b/src/tools/rust-analyzer/crates/ide/src/rename.rs @@ -35,13 +35,8 @@ pub(crate) fn prepare_rename( let syntax = source_file.syntax(); let res = find_definitions(&sema, syntax, position, &Name::new_symbol_root(sym::underscore))? - .map(|(frange, kind, def, _, _)| { - // ensure all ranges are valid - - if def.range_for_rename(&sema).is_none() { - bail!("No references found at position") - } - + .filter(|(_, _, def, _, _)| def.range_for_rename(&sema).is_some()) + .map(|(frange, kind, _, _, _)| { always!( frange.range.contains_inclusive(position.offset) && frange.file_id == position.file_id From c72bb70ffd284538519242663fa9443037f4d41e Mon Sep 17 00:00:00 2001 From: gewitternacht <60887951+gewitternacht@users.noreply.github.com> Date: Tue, 29 Jul 2025 08:39:28 +0200 Subject: [PATCH 0185/1134] clearer wording for `unsafe` code --- library/core/src/clone.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index c4778edf0fcc..6fcba298a432 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -160,8 +160,8 @@ mod uninit; /// /// Violating this property is a logic error. The behavior resulting from a logic error is not /// specified, but users of the trait must ensure that such logic errors do *not* result in -/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these -/// methods. +/// undefined behavior. This means that `unsafe` code **must not** rely on this property +/// being satisfied. /// /// ## Additional implementors /// From ede338cd8f2353cfef3c3b8d51ae185ed5c45f40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 09:35:50 +0200 Subject: [PATCH 0186/1134] WIP: auth using GitHub app --- src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml index ad570ee4595d..ea4d7532a9f2 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml @@ -9,12 +9,13 @@ on: jobs: pull: if: github.repository == 'rust-lang/rustc-dev-guide' - uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@main + uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@ci-gh-app with: + github-app-id: ${{ vars.APP_CLIENT_ID }} zulip-stream-id: 196385 zulip-bot-email: "rustc-dev-guide-gha-notif-bot@rust-lang.zulipchat.com" pr-base-branch: master branch-name: rustc-pull secrets: zulip-api-token: ${{ secrets.ZULIP_API_TOKEN }} - token: ${{ secrets.GITHUB_TOKEN }} + github-app-secret: ${{ secrets.APP_PRIVATE_KEY }} From 7e4ded41694c4f812efbcb207f21a3fa2ed649d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 09:53:04 +0200 Subject: [PATCH 0187/1134] Remove `bot-pull-requests` triagebot config --- src/doc/rustc-dev-guide/triagebot.toml | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/doc/rustc-dev-guide/triagebot.toml b/src/doc/rustc-dev-guide/triagebot.toml index b3f4c2d281cd..3ac5d57a52b0 100644 --- a/src/doc/rustc-dev-guide/triagebot.toml +++ b/src/doc/rustc-dev-guide/triagebot.toml @@ -62,9 +62,6 @@ allow-unauthenticated = [ # Documentation at: https://forge.rust-lang.org/triagebot/issue-links.html [issue-links] -# Automatically close and reopen PRs made by bots to run CI on them -[bot-pull-requests] - [behind-upstream] days-threshold = 7 From 6a40a17051d38855b1a98bbce0021ec33ea29711 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 10:02:50 +0200 Subject: [PATCH 0188/1134] Use main branch of josh-sync for CI workflow --- src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml index ea4d7532a9f2..04d6469aeaa4 100644 --- a/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml +++ b/src/doc/rustc-dev-guide/.github/workflows/rustc-pull.yml @@ -9,7 +9,7 @@ on: jobs: pull: if: github.repository == 'rust-lang/rustc-dev-guide' - uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@ci-gh-app + uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@main with: github-app-id: ${{ vars.APP_CLIENT_ID }} zulip-stream-id: 196385 From e6c0136b6837da91d99e2ea7b987b0d6db48b33d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 10:03:52 +0200 Subject: [PATCH 0189/1134] Use GitHub app for authenticating sync workflows --- library/stdarch/.github/workflows/rustc-pull.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/stdarch/.github/workflows/rustc-pull.yml b/library/stdarch/.github/workflows/rustc-pull.yml index 6b90d8a500f0..1379bd06b0e9 100644 --- a/library/stdarch/.github/workflows/rustc-pull.yml +++ b/library/stdarch/.github/workflows/rustc-pull.yml @@ -12,6 +12,7 @@ jobs: if: github.repository == 'rust-lang/stdarch' uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@main with: + github-app-id: ${{ vars.APP_CLIENT_ID }} # https://rust-lang.zulipchat.com/#narrow/channel/208962-t-libs.2Fstdarch/topic/Subtree.20sync.20automation/with/528461782 zulip-stream-id: 208962 zulip-bot-email: "stdarch-ci-bot@rust-lang.zulipchat.com" @@ -19,4 +20,4 @@ jobs: branch-name: rustc-pull secrets: zulip-api-token: ${{ secrets.ZULIP_API_TOKEN }} - token: ${{ secrets.GITHUB_TOKEN }} + github-app-secret: ${{ secrets.APP_PRIVATE_KEY }} From 1532b37010624c7657d6c9179cd6f01413bf7b56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 10:07:27 +0200 Subject: [PATCH 0190/1134] Use GH app for authenticating sync PRs --- src/tools/rust-analyzer/.github/workflows/rustc-pull.yml | 3 ++- src/tools/rust-analyzer/triagebot.toml | 3 --- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/rustc-pull.yml b/src/tools/rust-analyzer/.github/workflows/rustc-pull.yml index 2a842f3b3114..37cf5f3726b2 100644 --- a/src/tools/rust-analyzer/.github/workflows/rustc-pull.yml +++ b/src/tools/rust-analyzer/.github/workflows/rustc-pull.yml @@ -11,10 +11,11 @@ jobs: if: github.repository == 'rust-lang/rust-analyzer' uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@main with: + github-app-id: ${{ vars.APP_CLIENT_ID }} zulip-stream-id: 185405 zulip-bot-email: "rust-analyzer-ci-bot@rust-lang.zulipchat.com" pr-base-branch: master branch-name: rustc-pull secrets: zulip-api-token: ${{ secrets.ZULIP_API_TOKEN }} - token: ${{ secrets.GITHUB_TOKEN }} + github-app-secret: ${{ secrets.APP_PRIVATE_KEY }} diff --git a/src/tools/rust-analyzer/triagebot.toml b/src/tools/rust-analyzer/triagebot.toml index 27fdb672455b..c9862495bc0c 100644 --- a/src/tools/rust-analyzer/triagebot.toml +++ b/src/tools/rust-analyzer/triagebot.toml @@ -28,6 +28,3 @@ labels = ["has-merge-commits", "S-waiting-on-author"] # Prevents mentions in commits to avoid users being spammed [no-mentions] - -# Automatically close and reopen PRs made by bots to run CI on them -[bot-pull-requests] From 0ed3ef4ea48c7587a164572a7bda3290beb3a81f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 10:16:28 +0200 Subject: [PATCH 0191/1134] Use GH app for authenticating pull PRs --- src/tools/miri/.github/workflows/ci.yml | 7 ++++++- src/tools/miri/triagebot.toml | 3 --- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index c47f9695624b..668caef8f7f5 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -169,6 +169,11 @@ jobs: run: rustup toolchain install nightly --profile minimal - name: Install rustup-toolchain-install-master run: cargo install -f rustup-toolchain-install-master + - uses: actions/create-github-app-token@v2 + id: app-token + with: + app-id: ${{ vars.APP_CLIENT_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} - name: Push changes to a branch and create PR run: | # Make it easier to see what happens. @@ -200,7 +205,7 @@ jobs: git push -u origin $BRANCH gh pr create -B master --title 'Automatic Rustup' --body 'Please close and re-open this PR to trigger CI, then enable auto-merge.' env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} cron-fail-notify: name: cronjob failure notification diff --git a/src/tools/miri/triagebot.toml b/src/tools/miri/triagebot.toml index a0ce9f800242..5d6b596ea54c 100644 --- a/src/tools/miri/triagebot.toml +++ b/src/tools/miri/triagebot.toml @@ -50,9 +50,6 @@ new_pr = true [autolabel."S-waiting-on-author"] new_draft = true -# Automatically close and reopen PRs made by bots to run CI on them -[bot-pull-requests] - # Canonicalize issue numbers to avoid closing the wrong issue when upstreaming this subtree [canonicalize-issue-links] From 54f6ab73b1befefe2bc3af2b46e9cba8e06086c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 10:20:22 +0200 Subject: [PATCH 0192/1134] Switch to using a GH app for authenticating sync PRs So there will no longer be the need to close and reopen sync PRs in order for CI to run. --- library/compiler-builtins/.github/workflows/rustc-pull.yml | 5 +++-- library/compiler-builtins/triagebot.toml | 3 --- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/library/compiler-builtins/.github/workflows/rustc-pull.yml b/library/compiler-builtins/.github/workflows/rustc-pull.yml index ba698492e42a..ad7693e17b0e 100644 --- a/library/compiler-builtins/.github/workflows/rustc-pull.yml +++ b/library/compiler-builtins/.github/workflows/rustc-pull.yml @@ -12,12 +12,13 @@ jobs: if: github.repository == 'rust-lang/compiler-builtins' uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@main with: + github-app-id: ${{ vars.APP_CLIENT_ID }} # https://rust-lang.zulipchat.com/#narrow/channel/219381-t-libs/topic/compiler-builtins.20subtree.20sync.20automation/with/528482375 zulip-stream-id: 219381 zulip-topic: 'compiler-builtins subtree sync automation' - zulip-bot-email: "compiler-builtins-ci-bot@rust-lang.zulipchat.com" + zulip-bot-email: "compiler-builtins-ci-bot@rust-lang.zulipchat.com" pr-base-branch: master branch-name: rustc-pull secrets: zulip-api-token: ${{ secrets.ZULIP_API_TOKEN }} - token: ${{ secrets.GITHUB_TOKEN }} + github-app-secret: ${{ secrets.APP_PRIVATE_KEY }} diff --git a/library/compiler-builtins/triagebot.toml b/library/compiler-builtins/triagebot.toml index 8a2356c2b1c0..eba5cdd88b94 100644 --- a/library/compiler-builtins/triagebot.toml +++ b/library/compiler-builtins/triagebot.toml @@ -19,6 +19,3 @@ check-commits = false # Enable issue transfers within the org # Documentation at: https://forge.rust-lang.org/triagebot/transfer.html [transfer] - -# Automatically close and reopen PRs made by bots to run CI on them -[bot-pull-requests] From bad05ff4ffa5a61dcc8787d40796f9533b33b750 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Tue, 29 Jul 2025 12:37:06 +0300 Subject: [PATCH 0193/1134] In generate_mut_trait_impl, don't add a tabstop if the client does not support snippets --- .../src/handlers/generate_mut_trait_impl.rs | 51 ++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_mut_trait_impl.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_mut_trait_impl.rs index 9c4bcdd40304..ae1ae24d1ec1 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_mut_trait_impl.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_mut_trait_impl.rs @@ -104,7 +104,14 @@ pub(crate) fn generate_mut_trait_impl(acc: &mut Assists, ctx: &AssistContext<'_> format!("Generate `{trait_new}` impl from this `{trait_name}` trait"), target, |edit| { - edit.insert(target.start(), format!("$0{impl_def}\n\n{indent}")); + edit.insert( + target.start(), + if ctx.config.snippet_cap.is_some() { + format!("$0{impl_def}\n\n{indent}") + } else { + format!("{impl_def}\n\n{indent}") + }, + ); }, ) } @@ -161,7 +168,10 @@ fn process_ret_type(ref_ty: &ast::RetType) -> Option { #[cfg(test)] mod tests { - use crate::tests::{check_assist, check_assist_not_applicable}; + use crate::{ + AssistConfig, + tests::{TEST_CONFIG, check_assist, check_assist_not_applicable, check_assist_with_config}, + }; use super::*; @@ -402,6 +412,43 @@ impl Index$0 for [T; 3] {} pub trait AsRef {} impl AsRef$0 for [T; 3] {} +"#, + ); + } + + #[test] + fn no_snippets() { + check_assist_with_config( + generate_mut_trait_impl, + AssistConfig { snippet_cap: None, ..TEST_CONFIG }, + r#" +//- minicore: index +pub enum Axis { X = 0, Y = 1, Z = 2 } + +impl core::ops::Index$0 for [T; 3] { + type Output = T; + + fn index(&self, index: Axis) -> &Self::Output { + &self[index as usize] + } +} +"#, + r#" +pub enum Axis { X = 0, Y = 1, Z = 2 } + +impl core::ops::IndexMut for [T; 3] { + fn index_mut(&mut self, index: Axis) -> &mut Self::Output { + &mut self[index as usize] + } +} + +impl core::ops::Index for [T; 3] { + type Output = T; + + fn index(&self, index: Axis) -> &Self::Output { + &self[index as usize] + } +} "#, ); } From 1fd183ea920bbe20718a4c45315fe2b30bbf4b2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 12:28:46 +0200 Subject: [PATCH 0194/1134] Apply suggestions from code review Co-authored-by: Ralf Jung --- src/tools/miri/.github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index 668caef8f7f5..ba496d767129 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -169,12 +169,13 @@ jobs: run: rustup toolchain install nightly --profile minimal - name: Install rustup-toolchain-install-master run: cargo install -f rustup-toolchain-install-master + # Create a token for the next step so it can create a PR that actually runs CI. - uses: actions/create-github-app-token@v2 id: app-token with: app-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - - name: Push changes to a branch and create PR + - name: pull changes from rustc and create PR run: | # Make it easier to see what happens. set -x From ea1e24a989721a1d285d6de913be2be2b5101439 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Tue, 29 Jul 2025 14:40:14 +0300 Subject: [PATCH 0195/1134] When displaying a projection into a type parameter that has bounds as `impl Trait`, collect only the bounds of this projection It used to collect the bounds of them all. --- .../crates/hir-ty/src/display.rs | 26 ++++++++-------- .../crates/ide/src/inlay_hints.rs | 30 +++++++++++++++++++ 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs index b3760e3a3822..f0e31ebd020c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs @@ -620,19 +620,19 @@ impl HirDisplay for ProjectionTy { .generic_predicates(id.parent) .iter() .map(|pred| pred.clone().substitute(Interner, &substs)) - .filter(|wc| match wc.skip_binders() { - WhereClause::Implemented(tr) => { - matches!( - tr.self_type_parameter(Interner).kind(Interner), - TyKind::Alias(_) - ) - } - WhereClause::TypeOutlives(t) => { - matches!(t.ty.kind(Interner), TyKind::Alias(_)) - } - // We shouldn't be here if these exist - WhereClause::AliasEq(_) => false, - WhereClause::LifetimeOutlives(_) => false, + .filter(|wc| { + let ty = match wc.skip_binders() { + WhereClause::Implemented(tr) => tr.self_type_parameter(Interner), + WhereClause::TypeOutlives(t) => t.ty.clone(), + // We shouldn't be here if these exist + WhereClause::AliasEq(_) | WhereClause::LifetimeOutlives(_) => { + return false; + } + }; + let TyKind::Alias(AliasTy::Projection(proj)) = ty.kind(Interner) else { + return false; + }; + proj == self }) .collect::>(); if !bounds.is_empty() { diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs index 19e5509681aa..671fddb43630 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs @@ -1065,4 +1065,34 @@ fn bar() { "#, ); } + + #[test] + fn regression_20239() { + check_with_config( + InlayHintsConfig { parameter_hints: true, type_hints: true, ..DISABLED_CONFIG }, + r#" +//- minicore: fn +trait Iterator { + type Item; + fn map B>(self, f: F); +} +trait ToString { + fn to_string(&self); +} + +fn check_tostr_eq(left: L, right: R) +where + L: Iterator, + L::Item: ToString, + R: Iterator, + R::Item: ToString, +{ + left.map(|s| s.to_string()); + // ^ impl ToString + right.map(|s| s.to_string()); + // ^ impl ToString +} + "#, + ); + } } From cca89bcb7d54b4117c12ac17928c77f59aba37c5 Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Tue, 29 Jul 2025 20:59:50 +0900 Subject: [PATCH 0196/1134] add `SyntaxFactory::record_expr` to hide clone_for_update --- .../convert_tuple_struct_to_named_struct.rs | 20 +++++++++++-------- .../src/ast/syntax_factory/constructors.rs | 18 +++++++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs index f4041f49419a..b27ebcaa4edf 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs @@ -4,7 +4,9 @@ use ide_db::defs::{Definition, NameRefClass}; use std::ops::RangeInclusive; use syntax::{ SyntaxElement, SyntaxKind, SyntaxNode, T, TextSize, - ast::{self, AstNode, HasAttrs, HasGenericParams, HasVisibility}, + ast::{ + self, AstNode, HasAttrs, HasGenericParams, HasVisibility, syntax_factory::SyntaxFactory, + }, match_ast, syntax_editor::{Element, Position, SyntaxEditor}, }; @@ -105,7 +107,8 @@ fn edit_struct_def( ); ast::RecordField::cast(field_editor.finish().new_root().clone()) }); - let record_fields = ast::make::record_field_list(record_fields).clone_for_update(); + let make = SyntaxFactory::without_mappings(); + let record_fields = make.record_field_list(record_fields); let tuple_fields_before = Position::before(tuple_fields.syntax()); if let Either::Left(strukt) = strukt { @@ -145,10 +148,11 @@ fn edit_struct_references( let usages = strukt_def.usages(&ctx.sema).include_self_refs().all(); let edit_node = |node: SyntaxNode| -> Option { + let make = SyntaxFactory::without_mappings(); match_ast! { match node { ast::TupleStructPat(tuple_struct_pat) => { - Some(ast::make::record_pat_with_fields( + Some(make.record_pat_with_fields( tuple_struct_pat.path()?, ast::make::record_pat_field_list(tuple_struct_pat.fields().zip(names).map( |(pat, name)| { @@ -158,7 +162,7 @@ fn edit_struct_references( ) }, ), None), - ).syntax().clone_for_update()) + ).syntax().clone()) }, // for tuple struct creations like Foo(42) ast::CallExpr(call_expr) => { @@ -174,9 +178,8 @@ fn edit_struct_references( } let arg_list = call_expr.syntax().descendants().find_map(ast::ArgList::cast)?; - Some( - ast::make::record_expr( + make.record_expr( path, ast::make::record_expr_field_list(arg_list.args().zip(names).map( |(expr, name)| { @@ -186,7 +189,7 @@ fn edit_struct_references( ) }, )), - ).syntax().clone_for_update() + ).syntax().clone() ) }, _ => return None, @@ -271,11 +274,12 @@ fn edit_field_references( } fn generate_names(fields: impl Iterator) -> Vec { + let make = SyntaxFactory::without_mappings(); fields .enumerate() .map(|(i, _)| { let idx = i + 1; - ast::make::name(&format!("field{idx}")).clone_for_update() + make.name(&format!("field{idx}")) }) .collect() } diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/syntax_factory/constructors.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/syntax_factory/constructors.rs index 1ba610731512..738a26fed5d8 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/syntax_factory/constructors.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/syntax_factory/constructors.rs @@ -939,6 +939,24 @@ impl SyntaxFactory { ast } + pub fn record_expr( + &self, + path: ast::Path, + fields: ast::RecordExprFieldList, + ) -> ast::RecordExpr { + let ast = make::record_expr(path.clone(), fields.clone()).clone_for_update(); + if let Some(mut mapping) = self.mappings() { + let mut builder = SyntaxMappingBuilder::new(ast.syntax().clone()); + builder.map_node(path.syntax().clone(), ast.path().unwrap().syntax().clone()); + builder.map_node( + fields.syntax().clone(), + ast.record_expr_field_list().unwrap().syntax().clone(), + ); + builder.finish(&mut mapping); + } + ast + } + pub fn record_expr_field( &self, name: ast::NameRef, From 08c6768190176719c3d85b177579a96a8e7d01c5 Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Tue, 29 Jul 2025 23:09:59 +0900 Subject: [PATCH 0197/1134] replace `make::` to `SyntaxFactory::` in `inline_type_alias` --- .../src/handlers/inline_type_alias.rs | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs index 62535531435d..ae8d130df23c 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_type_alias.rs @@ -9,10 +9,11 @@ use ide_db::{ search::FileReference, }; use itertools::Itertools; +use syntax::ast::syntax_factory::SyntaxFactory; use syntax::syntax_editor::SyntaxEditor; use syntax::{ AstNode, NodeOrToken, SyntaxNode, - ast::{self, HasGenericParams, HasName, make}, + ast::{self, HasGenericParams, HasName}, }; use crate::{ @@ -206,8 +207,8 @@ impl LifetimeMap { alias_generics: &ast::GenericParamList, ) -> Option { let mut inner = FxHashMap::default(); - - let wildcard_lifetime = make::lifetime("'_"); + let make = SyntaxFactory::without_mappings(); + let wildcard_lifetime = make.lifetime("'_"); let lifetimes = alias_generics .lifetime_params() .filter_map(|lp| lp.lifetime()) @@ -334,9 +335,10 @@ fn create_replacement( }; let new_string = replacement_syntax.to_string(); let new = if new_string == "_" { - make::wildcard_pat().syntax().clone_for_update() + let make = SyntaxFactory::without_mappings(); + make.wildcard_pat().syntax().clone() } else { - replacement_syntax.clone_for_update() + replacement_syntax.clone() }; replacements.push((syntax.clone(), new)); @@ -385,12 +387,15 @@ impl ConstOrTypeGeneric { } fn replacement_value(&self) -> Option { - Some(match self { - ConstOrTypeGeneric::ConstArg(ca) => ca.expr()?.syntax().clone(), - ConstOrTypeGeneric::TypeArg(ta) => ta.syntax().clone(), - ConstOrTypeGeneric::ConstParam(cp) => cp.default_val()?.syntax().clone(), - ConstOrTypeGeneric::TypeParam(tp) => tp.default_type()?.syntax().clone(), - }) + Some( + match self { + ConstOrTypeGeneric::ConstArg(ca) => ca.expr()?.syntax().clone(), + ConstOrTypeGeneric::TypeArg(ta) => ta.syntax().clone(), + ConstOrTypeGeneric::ConstParam(cp) => cp.default_val()?.syntax().clone(), + ConstOrTypeGeneric::TypeParam(tp) => tp.default_type()?.syntax().clone(), + } + .clone_for_update(), + ) } } From 54a4f867f8144203b802fb2c5ae454e0dcb24c6a Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Tue, 29 Jul 2025 18:56:46 +0000 Subject: [PATCH 0198/1134] cleanup: Trim trailing whitespace --- library/compiler-builtins/.github/workflows/main.yaml | 4 ++-- library/compiler-builtins/ci/run.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/compiler-builtins/.github/workflows/main.yaml b/library/compiler-builtins/.github/workflows/main.yaml index 6c98a60d25b5..0c4b49cd9c88 100644 --- a/library/compiler-builtins/.github/workflows/main.yaml +++ b/library/compiler-builtins/.github/workflows/main.yaml @@ -166,7 +166,7 @@ jobs: shell: bash - run: echo "RUST_COMPILER_RT_ROOT=$(realpath ./compiler-rt)" >> "$GITHUB_ENV" shell: bash - + - name: Download musl source run: ./ci/update-musl.sh shell: bash @@ -278,7 +278,7 @@ jobs: with: name: ${{ env.BASELINE_NAME }} path: ${{ env.BASELINE_NAME }}.tar.xz - + - name: Run wall time benchmarks run: | # Always use the same seed for benchmarks. Ideally we should switch to a diff --git a/library/compiler-builtins/ci/run.sh b/library/compiler-builtins/ci/run.sh index 8b7965bb2056..4b43536d3b31 100755 --- a/library/compiler-builtins/ci/run.sh +++ b/library/compiler-builtins/ci/run.sh @@ -161,7 +161,7 @@ else mflags+=(--workspace --target "$target") cmd=(cargo test "${mflags[@]}") profile_flag="--profile" - + # If nextest is available, use that command -v cargo-nextest && nextest=1 || nextest=0 if [ "$nextest" = "1" ]; then @@ -204,7 +204,7 @@ else "${cmd[@]}" "$profile_flag" release-checked --features unstable-intrinsics --benches # Ensure that the routines do not panic. - # + # # `--tests` must be passed because no-panic is only enabled as a dev # dependency. The `release-opt` profile must be used to enable LTO and a # single CGU. From 97c35d3aed40f23fb3ba9e2c0b6bd8a3acb4868d Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Tue, 29 Jul 2025 19:04:32 +0000 Subject: [PATCH 0199/1134] ci: Simplify tests for verbatim paths Rather than setting an environment variable in the workflow job based on whether or not the environment is non-MinGW Windows, we can just check this in the ci script. This was originally added in b0f19660f0 ("Add tests for UNC paths on windows builds") and its followup commits. --- library/compiler-builtins/.github/workflows/main.yaml | 4 ---- library/compiler-builtins/ci/run.sh | 5 ++++- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/library/compiler-builtins/.github/workflows/main.yaml b/library/compiler-builtins/.github/workflows/main.yaml index 0c4b49cd9c88..94b519e3c2d3 100644 --- a/library/compiler-builtins/.github/workflows/main.yaml +++ b/library/compiler-builtins/.github/workflows/main.yaml @@ -50,7 +50,6 @@ jobs: os: ubuntu-24.04-arm - target: aarch64-pc-windows-msvc os: windows-2025 - test_verbatim: 1 build_only: 1 - target: arm-unknown-linux-gnueabi os: ubuntu-24.04 @@ -92,10 +91,8 @@ jobs: os: macos-13 - target: i686-pc-windows-msvc os: windows-2025 - test_verbatim: 1 - target: x86_64-pc-windows-msvc os: windows-2025 - test_verbatim: 1 - target: i686-pc-windows-gnu os: windows-2025 channel: nightly-i686-gnu @@ -106,7 +103,6 @@ jobs: needs: [calculate_vars] env: BUILD_ONLY: ${{ matrix.build_only }} - TEST_VERBATIM: ${{ matrix.test_verbatim }} MAY_SKIP_LIBM_CI: ${{ needs.calculate_vars.outputs.may_skip_libm_ci }} steps: - name: Print $HOME diff --git a/library/compiler-builtins/ci/run.sh b/library/compiler-builtins/ci/run.sh index 4b43536d3b31..bc94d42fe837 100755 --- a/library/compiler-builtins/ci/run.sh +++ b/library/compiler-builtins/ci/run.sh @@ -41,7 +41,10 @@ else "${test_builtins[@]}" --benches "${test_builtins[@]}" --benches --release - if [ "${TEST_VERBATIM:-}" = "1" ]; then + # Validate that having a verbatim path for the target directory works + # (trivial to regress using `/` in paths to build artifacts rather than + # `Path::join`). MinGW does not currently support these paths. + if [[ "$target" = *"windows"* ]] && [[ "$target" != *"gnu"* ]]; then verb_path=$(cmd.exe //C echo \\\\?\\%cd%\\builtins-test\\target2) "${test_builtins[@]}" --target-dir "$verb_path" --features c fi From 642bec7617b8ad2cb1d3a036991e130166c4ffaf Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 28 Jul 2025 18:35:23 +0200 Subject: [PATCH 0200/1134] Optimize some usages of double unary operators in suggestions When an expression is made of a `!` or `-` unary operator which does not change the type of the expression, use a new variant in `Sugg` to denote it. This allows replacing an extra application of the same operator by the removal of the original operator instead. Also, when adding a unary operator to a suggestion, do not enclose the operator argument in parentheses if it starts with a unary operator itself unless it is a binary operation (including `as`), because in this case parentheses are required to not bind the lhs only. Some suggestions will now be shown as `x` instead of `!!x`. Right now, no suggestion seems to produce `--x`. --- clippy_lints/src/floating_point_arithmetic.rs | 2 +- clippy_utils/src/sugg.rs | 103 ++++++++++++------ tests/ui/nonminimal_bool.rs | 18 +++ tests/ui/nonminimal_bool.stderr | 18 ++- 4 files changed, 101 insertions(+), 40 deletions(-) diff --git a/clippy_lints/src/floating_point_arithmetic.rs b/clippy_lints/src/floating_point_arithmetic.rs index d5abaa547e8e..84d39dd81c91 100644 --- a/clippy_lints/src/floating_point_arithmetic.rs +++ b/clippy_lints/src/floating_point_arithmetic.rs @@ -148,7 +148,7 @@ fn prepare_receiver_sugg<'a>(cx: &LateContext<'_>, mut expr: &'a Expr<'a>) -> Su .into(); suggestion = match suggestion { - Sugg::MaybeParen(_) => Sugg::MaybeParen(op), + Sugg::MaybeParen(_) | Sugg::UnOp(UnOp::Neg, _) => Sugg::MaybeParen(op), _ => Sugg::NonParen(op), }; } diff --git a/clippy_utils/src/sugg.rs b/clippy_utils/src/sugg.rs index 88f313c5f7e5..a63333c9b48f 100644 --- a/clippy_utils/src/sugg.rs +++ b/clippy_utils/src/sugg.rs @@ -4,8 +4,8 @@ use crate::source::{snippet, snippet_opt, snippet_with_applicability, snippet_with_context}; use crate::ty::expr_sig; use crate::{get_parent_expr_for_hir, higher}; -use rustc_ast::ast; use rustc_ast::util::parser::AssocOp; +use rustc_ast::{UnOp, ast}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{self as hir, Closure, ExprKind, HirId, MutTy, Node, TyKind}; @@ -29,6 +29,11 @@ pub enum Sugg<'a> { /// A binary operator expression, including `as`-casts and explicit type /// coercion. BinOp(AssocOp, Cow<'a, str>, Cow<'a, str>), + /// A unary operator expression. This is used to sometimes represent `!` + /// or `-`, but only if the type with and without the operator is kept identical. + /// It means that doubling the operator can be used to remove it instead, in + /// order to provide better suggestions. + UnOp(UnOp, Box>), } /// Literal constant `0`, for convenience. @@ -40,9 +45,10 @@ pub const EMPTY: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("")); impl Display for Sugg<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - match *self { - Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) => s.fmt(f), - Sugg::BinOp(op, ref lhs, ref rhs) => binop_to_string(op, lhs, rhs).fmt(f), + match self { + Sugg::NonParen(s) | Sugg::MaybeParen(s) => s.fmt(f), + Sugg::BinOp(op, lhs, rhs) => binop_to_string(*op, lhs, rhs).fmt(f), + Sugg::UnOp(op, inner) => write!(f, "{}{}", op.as_str(), inner.clone().maybe_inner_paren()), } } } @@ -100,9 +106,19 @@ impl<'a> Sugg<'a> { applicability: &mut Applicability, ) -> Self { if expr.span.ctxt() == ctxt { - Self::hir_from_snippet(expr, |span| { - snippet_with_context(cx, span, ctxt, default, applicability).0 - }) + if let ExprKind::Unary(op, inner) = expr.kind + && matches!(op, UnOp::Neg | UnOp::Not) + && cx.typeck_results().expr_ty(expr) == cx.typeck_results().expr_ty(inner) + { + Sugg::UnOp( + op, + Box::new(Self::hir_with_context(cx, inner, ctxt, default, applicability)), + ) + } else { + Self::hir_from_snippet(expr, |span| { + snippet_with_context(cx, span, ctxt, default, applicability).0 + }) + } } else { let (snip, _) = snippet_with_context(cx, expr.span, ctxt, default, applicability); Sugg::NonParen(snip) @@ -341,6 +357,7 @@ impl<'a> Sugg<'a> { let sugg = binop_to_string(op, &lhs, &rhs); Sugg::NonParen(format!("({sugg})").into()) }, + Sugg::UnOp(op, inner) => Sugg::NonParen(format!("({}{})", op.as_str(), inner.maybe_inner_paren()).into()), } } @@ -348,6 +365,26 @@ impl<'a> Sugg<'a> { match self { Sugg::NonParen(p) | Sugg::MaybeParen(p) => p.into_owned(), Sugg::BinOp(b, l, r) => binop_to_string(b, &l, &r), + Sugg::UnOp(op, inner) => format!("{}{}", op.as_str(), inner.maybe_inner_paren()), + } + } + + /// Checks if `self` starts with a unary operator. + fn starts_with_unary_op(&self) -> bool { + match self { + Sugg::UnOp(..) => true, + Sugg::BinOp(..) => false, + Sugg::MaybeParen(s) | Sugg::NonParen(s) => s.starts_with(['*', '!', '-', '&']), + } + } + + /// Call `maybe_paren` on `self` if it doesn't start with a unary operator, + /// don't touch it otherwise. + fn maybe_inner_paren(self) -> Self { + if self.starts_with_unary_op() { + self + } else { + self.maybe_paren() } } } @@ -430,10 +467,11 @@ impl Sub for &Sugg<'_> { forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>); forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>); -impl Neg for Sugg<'_> { - type Output = Sugg<'static>; - fn neg(self) -> Sugg<'static> { - match &self { +impl<'a> Neg for Sugg<'a> { + type Output = Sugg<'a>; + fn neg(self) -> Self::Output { + match self { + Self::UnOp(UnOp::Neg, sugg) => *sugg, Self::BinOp(AssocOp::Cast, ..) => Sugg::MaybeParen(format!("-({self})").into()), _ => make_unop("-", self), } @@ -446,19 +484,21 @@ impl<'a> Not for Sugg<'a> { use AssocOp::Binary; use ast::BinOpKind::{Eq, Ge, Gt, Le, Lt, Ne}; - if let Sugg::BinOp(op, lhs, rhs) = self { - let to_op = match op { - Binary(Eq) => Binary(Ne), - Binary(Ne) => Binary(Eq), - Binary(Lt) => Binary(Ge), - Binary(Ge) => Binary(Lt), - Binary(Gt) => Binary(Le), - Binary(Le) => Binary(Gt), - _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)), - }; - Sugg::BinOp(to_op, lhs, rhs) - } else { - make_unop("!", self) + match self { + Sugg::BinOp(op, lhs, rhs) => { + let to_op = match op { + Binary(Eq) => Binary(Ne), + Binary(Ne) => Binary(Eq), + Binary(Lt) => Binary(Ge), + Binary(Ge) => Binary(Lt), + Binary(Gt) => Binary(Le), + Binary(Le) => Binary(Gt), + _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)), + }; + Sugg::BinOp(to_op, lhs, rhs) + }, + Sugg::UnOp(UnOp::Not, expr) => *expr, + _ => make_unop("!", self), } } } @@ -491,20 +531,11 @@ impl Display for ParenHelper { /// Builds the string for `` adding parenthesis when necessary. /// /// For convenience, the operator is taken as a string because all unary -/// operators have the same -/// precedence. +/// operators have the same precedence. pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> { - // If the `expr` starts with `op` already, do not add wrap it in + // If the `expr` starts with a unary operator already, do not wrap it in // parentheses. - let expr = if let Sugg::MaybeParen(ref sugg) = expr - && !has_enclosing_paren(sugg) - && sugg.starts_with(op) - { - expr - } else { - expr.maybe_paren() - }; - Sugg::MaybeParen(format!("{op}{expr}").into()) + Sugg::MaybeParen(format!("{op}{}", expr.maybe_inner_paren()).into()) } /// Builds the string for ` ` adding parenthesis when necessary. diff --git a/tests/ui/nonminimal_bool.rs b/tests/ui/nonminimal_bool.rs index 1eecc3dee3dc..cacce9a7d1cb 100644 --- a/tests/ui/nonminimal_bool.rs +++ b/tests/ui/nonminimal_bool.rs @@ -236,3 +236,21 @@ mod issue14404 { } } } + +fn dont_simplify_double_not_if_types_differ() { + struct S; + + impl std::ops::Not for S { + type Output = bool; + fn not(self) -> bool { + true + } + } + + // The lint must propose `if !!S`, not `if S`. + // FIXME: `bool_comparison` will propose to use `S == true` + // which is invalid. + if !S != true {} + //~^ nonminimal_bool + //~| bool_comparison +} diff --git a/tests/ui/nonminimal_bool.stderr b/tests/ui/nonminimal_bool.stderr index ecb82a23da03..c20412974b20 100644 --- a/tests/ui/nonminimal_bool.stderr +++ b/tests/ui/nonminimal_bool.stderr @@ -179,7 +179,7 @@ error: inequality checks against true can be replaced by a negation --> tests/ui/nonminimal_bool.rs:186:8 | LL | if !b != true {} - | ^^^^^^^^^^ help: try simplifying it as shown: `!!b` + | ^^^^^^^^^^ help: try simplifying it as shown: `b` error: this boolean expression can be simplified --> tests/ui/nonminimal_bool.rs:189:8 @@ -209,7 +209,7 @@ error: inequality checks against true can be replaced by a negation --> tests/ui/nonminimal_bool.rs:193:8 | LL | if true != !b {} - | ^^^^^^^^^^ help: try simplifying it as shown: `!!b` + | ^^^^^^^^^^ help: try simplifying it as shown: `b` error: this boolean expression can be simplified --> tests/ui/nonminimal_bool.rs:196:8 @@ -235,5 +235,17 @@ error: this boolean expression can be simplified LL | if !(matches!(ty, TyKind::Ref(_, _, _)) && !is_mutable(&expr)) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `!matches!(ty, TyKind::Ref(_, _, _)) || is_mutable(&expr)` -error: aborting due to 31 previous errors +error: this boolean expression can be simplified + --> tests/ui/nonminimal_bool.rs:253:8 + | +LL | if !S != true {} + | ^^^^^^^^^^ help: try: `S == true` + +error: inequality checks against true can be replaced by a negation + --> tests/ui/nonminimal_bool.rs:253:8 + | +LL | if !S != true {} + | ^^^^^^^^^^ help: try simplifying it as shown: `!!S` + +error: aborting due to 33 previous errors From 987a49ba38e29f8c8b8dde4aab71dfad0f28f3fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= Date: Tue, 29 Jul 2025 17:47:03 +0200 Subject: [PATCH 0201/1134] bootstrap: extract `cc` query into a new function --- src/bootstrap/src/core/build_steps/dist.rs | 49 +++++++++++++--------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index c8a54ad250cb..819fae468aec 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -184,26 +184,7 @@ fn make_win_dist( return; } - //Ask gcc where it keeps its stuff - let mut cmd = command(builder.cc(target)); - cmd.arg("-print-search-dirs"); - let gcc_out = cmd.run_capture_stdout(builder).stdout(); - - let mut bin_path: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect(); - let mut lib_path = Vec::new(); - - for line in gcc_out.lines() { - let idx = line.find(':').unwrap(); - let key = &line[..idx]; - let trim_chars: &[_] = &[' ', '=']; - let value = env::split_paths(line[(idx + 1)..].trim_start_matches(trim_chars)); - - if key == "programs" { - bin_path.extend(value); - } else if key == "libraries" { - lib_path.extend(value); - } - } + let (bin_path, lib_path) = get_cc_search_dirs(target, builder); let compiler = if target == "i686-pc-windows-gnu" { "i686-w64-mingw32-gcc.exe" @@ -320,6 +301,34 @@ fn make_win_dist( } } + +fn get_cc_search_dirs( + target: TargetSelection, + builder: &Builder<'_>, +) -> (Vec, Vec) { + //Ask gcc where it keeps its stuff + let mut cmd = command(builder.cc(target)); + cmd.arg("-print-search-dirs"); + let gcc_out = cmd.run_capture_stdout(builder).stdout(); + + let mut bin_path: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect(); + let mut lib_path = Vec::new(); + + for line in gcc_out.lines() { + let idx = line.find(':').unwrap(); + let key = &line[..idx]; + let trim_chars: &[_] = &[' ', '=']; + let value = env::split_paths(line[(idx + 1)..].trim_start_matches(trim_chars)); + + if key == "programs" { + bin_path.extend(value); + } else if key == "libraries" { + lib_path.extend(value); + } + } + (bin_path, lib_path) +} + #[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] pub struct Mingw { pub host: TargetSelection, From 9cfe5f61ab66fb8fba8907ff45dfb9d0dee617ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= Date: Tue, 29 Jul 2025 17:56:00 +0200 Subject: [PATCH 0202/1134] bootstrap: split runtime DLL part out of `make_win_dist` --- src/bootstrap/src/core/build_steps/dist.rs | 74 ++++++++++------------ 1 file changed, 35 insertions(+), 39 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 819fae468aec..88b668e1936e 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -174,12 +174,7 @@ fn find_files(files: &[&str], path: &[PathBuf]) -> Vec { found } -fn make_win_dist( - rust_root: &Path, - plat_root: &Path, - target: TargetSelection, - builder: &Builder<'_>, -) { +fn make_win_dist(plat_root: &Path, target: TargetSelection, builder: &Builder<'_>) { if builder.config.dry_run() { return; } @@ -194,12 +189,6 @@ fn make_win_dist( "gcc.exe" }; let target_tools = [compiler, "ld.exe", "dlltool.exe", "libwinpthread-1.dll"]; - let mut rustc_dlls = vec!["libwinpthread-1.dll"]; - if target.starts_with("i686-") { - rustc_dlls.push("libgcc_s_dw2-1.dll"); - } else { - rustc_dlls.push("libgcc_s_seh-1.dll"); - } // Libraries necessary to link the windows-gnu toolchains. // System libraries will be preferred if they are available (see #67429). @@ -255,25 +244,8 @@ fn make_win_dist( //Find mingw artifacts we want to bundle let target_tools = find_files(&target_tools, &bin_path); - let rustc_dlls = find_files(&rustc_dlls, &bin_path); let target_libs = find_files(&target_libs, &lib_path); - // Copy runtime dlls next to rustc.exe - let rust_bin_dir = rust_root.join("bin/"); - fs::create_dir_all(&rust_bin_dir).expect("creating rust_bin_dir failed"); - for src in &rustc_dlls { - builder.copy_link_to_folder(src, &rust_bin_dir); - } - - if builder.config.lld_enabled { - // rust-lld.exe also needs runtime dlls - let rust_target_bin_dir = rust_root.join("lib/rustlib").join(target).join("bin"); - fs::create_dir_all(&rust_target_bin_dir).expect("creating rust_target_bin_dir failed"); - for src in &rustc_dlls { - builder.copy_link_to_folder(src, &rust_target_bin_dir); - } - } - //Copy platform tools to platform-specific bin directory let plat_target_bin_self_contained_dir = plat_root.join("lib/rustlib").join(target).join("bin/self-contained"); @@ -301,6 +273,37 @@ fn make_win_dist( } } +fn runtime_dll_dist(rust_root: &Path, target: TargetSelection, builder: &Builder<'_>) { + if builder.config.dry_run() { + return; + } + + let (bin_path, _) = get_cc_search_dirs(target, builder); + + let mut rustc_dlls = vec!["libwinpthread-1.dll"]; + if target.starts_with("i686-") { + rustc_dlls.push("libgcc_s_dw2-1.dll"); + } else { + rustc_dlls.push("libgcc_s_seh-1.dll"); + } + let rustc_dlls = find_files(&rustc_dlls, &bin_path); + + // Copy runtime dlls next to rustc.exe + let rust_bin_dir = rust_root.join("bin/"); + fs::create_dir_all(&rust_bin_dir).expect("creating rust_bin_dir failed"); + for src in &rustc_dlls { + builder.copy_link_to_folder(src, &rust_bin_dir); + } + + if builder.config.lld_enabled { + // rust-lld.exe also needs runtime dlls + let rust_target_bin_dir = rust_root.join("lib/rustlib").join(target).join("bin"); + fs::create_dir_all(&rust_target_bin_dir).expect("creating rust_target_bin_dir failed"); + for src in &rustc_dlls { + builder.copy_link_to_folder(src, &rust_target_bin_dir); + } + } +} fn get_cc_search_dirs( target: TargetSelection, @@ -359,11 +362,7 @@ impl Step for Mingw { let mut tarball = Tarball::new(builder, "rust-mingw", &host.triple); tarball.set_product_name("Rust MinGW"); - // The first argument is a "temporary directory" which is just - // thrown away (this contains the runtime DLLs included in the rustc package - // above) and the second argument is where to place all the MinGW components - // (which is what we want). - make_win_dist(&tmpdir(builder), tarball.image_dir(), host, builder); + make_win_dist(tarball.image_dir(), host, builder); Some(tarball.generate()) } @@ -403,17 +402,14 @@ impl Step for Rustc { prepare_image(builder, compiler, tarball.image_dir()); // On MinGW we've got a few runtime DLL dependencies that we need to - // include. The first argument to this script is where to put these DLLs - // (the image we're creating), and the second argument is a junk directory - // to ignore all other MinGW stuff the script creates. - // + // include. // On 32-bit MinGW we're always including a DLL which needs some extra // licenses to distribute. On 64-bit MinGW we don't actually distribute // anything requiring us to distribute a license, but it's likely the // install will *also* include the rust-mingw package, which also needs // licenses, so to be safe we just include it here in all MinGW packages. if host.ends_with("pc-windows-gnu") && builder.config.dist_include_mingw_linker { - make_win_dist(tarball.image_dir(), &tmpdir(builder), host, builder); + runtime_dll_dist(tarball.image_dir(), host, builder); tarball.add_dir(builder.src.join("src/etc/third-party"), "share/doc"); } From e8db4aa4706a4fdfc9a2cbf32a3cbbd11a6d14d1 Mon Sep 17 00:00:00 2001 From: Tom Webber Date: Mon, 14 Jul 2025 20:24:54 +0200 Subject: [PATCH 0203/1134] Fix min_ident_chars: add trait/impl awareness --- clippy_lints/src/min_ident_chars.rs | 79 +++++++++++++++++++++++++++- tests/ui/min_ident_chars.rs | 49 ++++++++++++++++++ tests/ui/min_ident_chars.stderr | 80 ++++++++++++++++++++++++++++- 3 files changed, 205 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/min_ident_chars.rs b/clippy_lints/src/min_ident_chars.rs index 99f01c8001a5..dbce29a86318 100644 --- a/clippy_lints/src/min_ident_chars.rs +++ b/clippy_lints/src/min_ident_chars.rs @@ -4,10 +4,14 @@ use clippy_utils::is_from_proc_macro; use rustc_data_structures::fx::FxHashSet; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::{Visitor, walk_item, walk_trait_item}; -use rustc_hir::{GenericParamKind, HirId, Item, ItemKind, ItemLocalId, Node, Pat, PatKind, TraitItem, UsePath}; +use rustc_hir::{ + GenericParamKind, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, ItemLocalId, Node, Pat, PatKind, TraitItem, + UsePath, +}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::impl_lint_pass; -use rustc_span::Span; +use rustc_span::symbol::Ident; +use rustc_span::{Span, Symbol}; use std::borrow::Cow; declare_clippy_lint! { @@ -32,6 +36,10 @@ declare_clippy_lint! { /// let title = movie.title; /// } /// ``` + /// + /// ### Limitations + /// Trait implementations which use the same function or parameter name as the trait declaration will + /// not be warned about, even if the name is below the configured limit. #[clippy::version = "1.72.0"] pub MIN_IDENT_CHARS, restriction, @@ -76,6 +84,18 @@ impl LateLintPass<'_> for MinIdentChars { return; } + // If the function is declared but not defined in a trait, check_pat isn't called so we need to + // check this explicitly + if matches!(&item.kind, rustc_hir::TraitItemKind::Fn(_, _)) { + let param_names = cx.tcx.fn_arg_idents(item.owner_id.to_def_id()); + for ident in param_names.iter().flatten() { + let str = ident.as_str(); + if self.is_ident_too_short(cx, str, ident.span) { + emit_min_ident_chars(self, cx, str, ident.span); + } + } + } + walk_trait_item(&mut IdentVisitor { conf: self, cx }, item); } @@ -84,6 +104,7 @@ impl LateLintPass<'_> for MinIdentChars { if let PatKind::Binding(_, _, ident, ..) = pat.kind && let str = ident.as_str() && self.is_ident_too_short(cx, str, ident.span) + && is_not_in_trait_impl(cx, pat, ident) { emit_min_ident_chars(self, cx, str, ident.span); } @@ -118,6 +139,11 @@ impl Visitor<'_> for IdentVisitor<'_, '_> { let str = ident.as_str(); if conf.is_ident_too_short(cx, str, ident.span) { + // Check whether the node is part of a `impl` for a trait. + if matches!(cx.tcx.parent_hir_node(hir_id), Node::TraitRef(_)) { + return; + } + // Check whether the node is part of a `use` statement. We don't want to emit a warning if the user // has no control over the type. let usenode = opt_as_use_node(node).or_else(|| { @@ -201,3 +227,52 @@ fn opt_as_use_node(node: Node<'_>) -> Option<&'_ UsePath<'_>> { None } } + +/// Check if a pattern is a function param in an impl block for a trait and that the param name is +/// the same than in the trait definition. +fn is_not_in_trait_impl(cx: &LateContext<'_>, pat: &Pat<'_>, ident: Ident) -> bool { + let parent_node = cx.tcx.parent_hir_node(pat.hir_id); + if !matches!(parent_node, Node::Param(_)) { + return true; + } + + for (_, parent_node) in cx.tcx.hir_parent_iter(pat.hir_id) { + if let Node::ImplItem(impl_item) = parent_node + && matches!(impl_item.kind, ImplItemKind::Fn(_, _)) + { + let impl_parent_node = cx.tcx.parent_hir_node(impl_item.hir_id()); + if let Node::Item(parent_item) = impl_parent_node + && let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = &parent_item.kind + && let Some(name) = get_param_name(impl_item, cx, ident) + { + return name != ident.name; + } + + return true; + } + } + + true +} + +fn get_param_name(impl_item: &ImplItem<'_>, cx: &LateContext<'_>, ident: Ident) -> Option { + if let Some(trait_item_def_id) = impl_item.trait_item_def_id { + let trait_param_names = cx.tcx.fn_arg_idents(trait_item_def_id); + + let ImplItemKind::Fn(_, body_id) = impl_item.kind else { + return None; + }; + + if let Some(param_index) = cx + .tcx + .hir_body_param_idents(body_id) + .position(|param_ident| param_ident.is_some_and(|param_ident| param_ident.span == ident.span)) + && let Some(trait_param_name) = trait_param_names.get(param_index) + && let Some(trait_param_ident) = trait_param_name + { + return Some(trait_param_ident.name); + } + } + + None +} diff --git a/tests/ui/min_ident_chars.rs b/tests/ui/min_ident_chars.rs index f473ac848a8e..e2f82e2a182f 100644 --- a/tests/ui/min_ident_chars.rs +++ b/tests/ui/min_ident_chars.rs @@ -124,3 +124,52 @@ fn wrong_pythagoras(a: f32, b: f32) -> f32 { mod issue_11163 { struct Array([T; N]); } + +struct Issue13396; + +impl core::fmt::Display for Issue13396 { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "Issue13396") + } +} + +impl core::fmt::Debug for Issue13396 { + fn fmt(&self, g: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + //~^ min_ident_chars + write!(g, "Issue13396") + } +} + +fn issue13396() { + let a = |f: i8| f; + //~^ min_ident_chars + //~| min_ident_chars +} + +trait D { + //~^ min_ident_chars + fn f(g: i32); + //~^ min_ident_chars + //~| min_ident_chars + fn long(long: i32); + + fn g(arg: i8) { + //~^ min_ident_chars + fn c(d: u8) {} + //~^ min_ident_chars + //~| min_ident_chars + } +} + +impl D for Issue13396 { + fn f(g: i32) { + fn h() {} + //~^ min_ident_chars + fn inner(a: i32) {} + //~^ min_ident_chars + let a = |f: String| f; + //~^ min_ident_chars + //~| min_ident_chars + } + fn long(long: i32) {} +} diff --git a/tests/ui/min_ident_chars.stderr b/tests/ui/min_ident_chars.stderr index bd6c45cf648e..36bf89e79f00 100644 --- a/tests/ui/min_ident_chars.stderr +++ b/tests/ui/min_ident_chars.stderr @@ -193,5 +193,83 @@ error: this ident consists of a single char LL | fn wrong_pythagoras(a: f32, b: f32) -> f32 { | ^ -error: aborting due to 32 previous errors +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:137:19 + | +LL | fn fmt(&self, g: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:144:14 + | +LL | let a = |f: i8| f; + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:144:9 + | +LL | let a = |f: i8| f; + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:149:7 + | +LL | trait D { + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:151:10 + | +LL | fn f(g: i32); + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:151:8 + | +LL | fn f(g: i32); + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:156:8 + | +LL | fn g(arg: i8) { + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:158:12 + | +LL | fn c(d: u8) {} + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:158:14 + | +LL | fn c(d: u8) {} + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:166:12 + | +LL | fn h() {} + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:168:18 + | +LL | fn inner(a: i32) {} + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:170:18 + | +LL | let a = |f: String| f; + | ^ + +error: this ident consists of a single char + --> tests/ui/min_ident_chars.rs:170:13 + | +LL | let a = |f: String| f; + | ^ + +error: aborting due to 45 previous errors From 951a6f792de1861a271af2bc0b2adf46085f5972 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 30 Jul 2025 08:11:01 +0200 Subject: [PATCH 0204/1134] Remove outdated ci.py reference --- src/doc/rustc-dev-guide/src/tests/docker.md | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/tests/docker.md b/src/doc/rustc-dev-guide/src/tests/docker.md index 032da1ca1e8d..ae0939842237 100644 --- a/src/doc/rustc-dev-guide/src/tests/docker.md +++ b/src/doc/rustc-dev-guide/src/tests/docker.md @@ -6,12 +6,12 @@ need to install Docker on a Linux, Windows, or macOS system (typically Linux will be much faster than Windows or macOS because the latter use virtual machines to emulate a Linux environment). -Jobs running in CI are configured through a set of bash scripts, and it is not always trivial to reproduce their behavior locally. If you want to run a CI job locally in the simplest way possible, you can use a provided helper Python script that tries to replicate what happens on CI as closely as possible: +Jobs running in CI are configured through a set of bash scripts, and it is not always trivial to reproduce their behavior locally. If you want to run a CI job locally in the simplest way possible, you can use a provided helper `citool` that tries to replicate what happens on CI as closely as possible: ```bash -python3 src/ci/github-actions/ci.py run-local +cargo run --manifest-path src/ci/citool/Cargo.toml run-local # For example: -python3 src/ci/github-actions/ci.py run-local dist-x86_64-linux-alt +cargo run --manifest-path src/ci/citool/Cargo.toml run-local dist-x86_64-linux-alt ``` If the above script does not work for you, you would like to have more control of the Docker image execution, or you want to understand what exactly happens during Docker job execution, then continue reading below. @@ -53,15 +53,6 @@ Some additional notes about using the interactive mode: containers. With the container name, run `docker exec -it /bin/bash` where `` is the container name like `4ba195e95cef`. -The approach described above is a relatively low-level interface for running the Docker images -directly. If you want to run a full CI Linux job locally with Docker, in a way that is as close to CI as possible, you can use the following command: - -```bash -cargo run --manifest-path src/ci/citool/Cargo.toml run-local -# For example: -cargo run --manifest-path src/ci/citool/Cargo.toml run-local dist-x86_64-linux-alt -``` - [Docker]: https://www.docker.com/ [`src/ci/docker`]: https://github.com/rust-lang/rust/tree/master/src/ci/docker [`src/ci/docker/run.sh`]: https://github.com/rust-lang/rust/blob/master/src/ci/docker/run.sh From ba5b6b9ec472dc32bdaa8b18c22d30bd6abf7ebc Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 17 Jul 2025 20:00:19 +0200 Subject: [PATCH 0205/1134] const-eval: full support for pointer fragments --- compiler/rustc_const_eval/messages.ftl | 11 +- .../src/const_eval/eval_queries.rs | 7 + compiler/rustc_const_eval/src/errors.rs | 16 +- .../rustc_const_eval/src/interpret/intern.rs | 97 +++++++----- .../rustc_const_eval/src/interpret/memory.rs | 44 ++---- .../rustc_const_eval/src/interpret/place.rs | 8 +- .../src/interpret/validity.rs | 4 +- .../src/mir/interpret/allocation.rs | 84 ++++++----- .../interpret/allocation/provenance_map.rs | 142 +++++++++--------- .../rustc_middle/src/mir/interpret/error.rs | 3 - .../rustc_middle/src/mir/interpret/pointer.rs | 12 +- compiler/rustc_middle/src/mir/pretty.rs | 4 +- library/core/src/ptr/mod.rs | 38 +---- library/coretests/tests/ptr.rs | 12 +- src/tools/miri/src/machine.rs | 10 +- src/tools/miri/src/shims/native_lib/mod.rs | 2 +- .../miri/tests/fail/provenance/mix-ptrs1.rs | 21 +++ .../tests/fail/provenance/mix-ptrs1.stderr | 16 ++ .../miri/tests/fail/provenance/mix-ptrs2.rs | 37 +++++ .../tests/fail/provenance/mix-ptrs2.stderr | 16 ++ ...uninit_alloc_diagnostic_with_provenance.rs | 11 +- ...it_alloc_diagnostic_with_provenance.stderr | 2 +- .../fail/tracing/partial_init.stderr | 2 +- src/tools/miri/tests/pass/provenance.rs | 35 ----- src/tools/miri/tests/pass/transmute_ptr.rs | 21 +-- .../heap/ptr_not_made_global.stderr | 4 +- .../heap/ptr_not_made_global_mut.stderr | 2 +- .../const-eval/partial_ptr_overwrite.rs | 12 -- .../const-eval/partial_ptr_overwrite.stderr | 12 -- tests/ui/consts/const-eval/ptr_fragments.rs | 63 ++++++++ .../const-eval/ptr_fragments_in_final.rs | 25 +++ .../const-eval/ptr_fragments_in_final.stderr | 10 ++ .../ui/consts/const-eval/read_partial_ptr.rs | 49 ++++++ .../consts/const-eval/read_partial_ptr.stderr | 39 +++++ tests/ui/consts/missing_span_in_backtrace.rs | 13 +- .../consts/missing_span_in_backtrace.stderr | 16 +- 36 files changed, 542 insertions(+), 358 deletions(-) create mode 100644 src/tools/miri/tests/fail/provenance/mix-ptrs1.rs create mode 100644 src/tools/miri/tests/fail/provenance/mix-ptrs1.stderr create mode 100644 src/tools/miri/tests/fail/provenance/mix-ptrs2.rs create mode 100644 src/tools/miri/tests/fail/provenance/mix-ptrs2.stderr delete mode 100644 tests/ui/consts/const-eval/partial_ptr_overwrite.rs delete mode 100644 tests/ui/consts/const-eval/partial_ptr_overwrite.stderr create mode 100644 tests/ui/consts/const-eval/ptr_fragments.rs create mode 100644 tests/ui/consts/const-eval/ptr_fragments_in_final.rs create mode 100644 tests/ui/consts/const-eval/ptr_fragments_in_final.stderr create mode 100644 tests/ui/consts/const-eval/read_partial_ptr.rs create mode 100644 tests/ui/consts/const-eval/read_partial_ptr.stderr diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index aa0bc42d4485..10cdc372ddd4 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -57,7 +57,7 @@ const_eval_const_context = {$kind -> } const_eval_const_heap_ptr_in_final = encountered `const_allocate` pointer in final value that was not made global - .note = use `const_make_global` to make allocated pointers immutable before returning + .note = use `const_make_global` to turn allocated pointers into immutable globals before returning const_eval_const_make_global_ptr_already_made_global = attempting to call `const_make_global` twice on the same allocation {$alloc} @@ -231,6 +231,9 @@ const_eval_mutable_borrow_escaping = const_eval_mutable_ptr_in_final = encountered mutable pointer in final value of {const_eval_intern_kind} +const_eval_partial_pointer_in_final = encountered partial pointer in final value of {const_eval_intern_kind} + .note = while pointers can be broken apart into individual bytes during const-evaluation, only complete pointers (with all their bytes in the right order) are supported in the final value + const_eval_nested_static_in_thread_local = #[thread_local] does not support implicit nested statics, please create explicit static items and refer to them instead const_eval_non_const_await = @@ -299,10 +302,8 @@ const_eval_panic = evaluation panicked: {$msg} const_eval_panic_non_str = argument to `panic!()` in a const context must have type `&str` -const_eval_partial_pointer_copy = - unable to copy parts of a pointer from memory at {$ptr} -const_eval_partial_pointer_overwrite = - unable to overwrite parts of a pointer in memory at {$ptr} +const_eval_partial_pointer_read = + unable to read parts of a pointer from memory at {$ptr} const_eval_pointer_arithmetic_overflow = overflowing pointer arithmetic: the total offset in bytes does not fit in an `isize` diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 5835660e1c38..4da2663319c3 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -117,6 +117,13 @@ fn eval_body_using_ecx<'tcx, R: InterpretationResult<'tcx>>( ecx.tcx.dcx().emit_err(errors::ConstHeapPtrInFinal { span: ecx.tcx.span }), ))); } + Err(InternError::PartialPointer) => { + throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error( + ecx.tcx + .dcx() + .emit_err(errors::PartialPtrInFinal { span: ecx.tcx.span, kind: intern_kind }), + ))); + } } interp_ok(R::make_result(ret, ecx)) diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index b6a64035261e..322fd8e9363a 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -51,6 +51,15 @@ pub(crate) struct ConstHeapPtrInFinal { pub span: Span, } +#[derive(Diagnostic)] +#[diag(const_eval_partial_pointer_in_final)] +#[note] +pub(crate) struct PartialPtrInFinal { + #[primary_span] + pub span: Span, + pub kind: InternKind, +} + #[derive(Diagnostic)] #[diag(const_eval_unstable_in_stable_exposed)] pub(crate) struct UnstableInStableExposed { @@ -832,8 +841,7 @@ impl ReportErrorExt for UnsupportedOpInfo { UnsupportedOpInfo::Unsupported(s) => s.clone().into(), UnsupportedOpInfo::ExternTypeField => const_eval_extern_type_field, UnsupportedOpInfo::UnsizedLocal => const_eval_unsized_local, - UnsupportedOpInfo::OverwritePartialPointer(_) => const_eval_partial_pointer_overwrite, - UnsupportedOpInfo::ReadPartialPointer(_) => const_eval_partial_pointer_copy, + UnsupportedOpInfo::ReadPartialPointer(_) => const_eval_partial_pointer_read, UnsupportedOpInfo::ReadPointerAsInt(_) => const_eval_read_pointer_as_int, UnsupportedOpInfo::ThreadLocalStatic(_) => const_eval_thread_local_static, UnsupportedOpInfo::ExternStatic(_) => const_eval_extern_static, @@ -844,7 +852,7 @@ impl ReportErrorExt for UnsupportedOpInfo { use UnsupportedOpInfo::*; use crate::fluent_generated::*; - if let ReadPointerAsInt(_) | OverwritePartialPointer(_) | ReadPartialPointer(_) = self { + if let ReadPointerAsInt(_) | ReadPartialPointer(_) = self { diag.help(const_eval_ptr_as_bytes_1); diag.help(const_eval_ptr_as_bytes_2); } @@ -856,7 +864,7 @@ impl ReportErrorExt for UnsupportedOpInfo { | UnsupportedOpInfo::ExternTypeField | Unsupported(_) | ReadPointerAsInt(_) => {} - OverwritePartialPointer(ptr) | ReadPartialPointer(ptr) => { + ReadPartialPointer(ptr) => { diag.arg("ptr", ptr); } ThreadLocalStatic(did) | ExternStatic(did) => rustc_middle::ty::tls::with(|tcx| { diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index bb59b9f54186..5d510a983526 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -19,9 +19,12 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_hir as hir; use rustc_hir::definitions::{DefPathData, DisambiguatorState}; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; -use rustc_middle::mir::interpret::{ConstAllocation, CtfeProvenance, InterpResult}; +use rustc_middle::mir::interpret::{ + AllocBytes, ConstAllocation, CtfeProvenance, InterpResult, Provenance, +}; use rustc_middle::query::TyCtxtAt; use rustc_middle::span_bug; +use rustc_middle::ty::TyCtxt; use rustc_middle::ty::layout::TyAndLayout; use rustc_span::def_id::LocalDefId; use tracing::{instrument, trace}; @@ -52,39 +55,30 @@ impl HasStaticRootDefId for const_eval::CompileTimeMachine<'_> { } } -/// Intern an allocation. Returns `Err` if the allocation does not exist in the local memory. -/// -/// `mutability` can be used to force immutable interning: if it is `Mutability::Not`, the -/// allocation is interned immutably; if it is `Mutability::Mut`, then the allocation *must be* -/// already mutable (as a sanity check). -/// -/// Returns an iterator over all relocations referred to by this allocation. -fn intern_shallow<'tcx, M: CompileTimeMachine<'tcx>>( - ecx: &mut InterpCx<'tcx, M>, - alloc_id: AllocId, +fn prepare_alloc<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( + tcx: TyCtxt<'tcx>, + kind: MemoryKind, + alloc: &mut Allocation, mutability: Mutability, - disambiguator: Option<&mut DisambiguatorState>, -) -> Result + 'tcx, InternError> { - trace!("intern_shallow {:?}", alloc_id); - // remove allocation - // FIXME(#120456) - is `swap_remove` correct? - let Some((kind, mut alloc)) = ecx.memory.alloc_map.swap_remove(&alloc_id) else { - return Err(InternError::DanglingPointer); - }; - +) -> Result<(), InternError> { match kind { MemoryKind::Machine(const_eval::MemoryKind::Heap { was_made_global }) => { if !was_made_global { // Attempting to intern a `const_allocate`d pointer that was not made global via - // `const_make_global`. We want to error here, but we have to first put the - // allocation back into the `alloc_map` to keep things in a consistent state. - ecx.memory.alloc_map.insert(alloc_id, (kind, alloc)); + // `const_make_global`. + tcx.dcx().delayed_bug("non-global heap allocation in const value"); return Err(InternError::ConstAllocNotGlobal); } } MemoryKind::Stack | MemoryKind::CallerLocation => {} } + if !alloc.provenance_merge_bytes(&tcx) { + // Per-byte provenance is not supported by backends, so we cannot accept it here. + tcx.dcx().delayed_bug("partial pointer in const value"); + return Err(InternError::PartialPointer); + } + // Set allocation mutability as appropriate. This is used by LLVM to put things into // read-only memory, and also by Miri when evaluating other globals that // access this one. @@ -97,6 +91,36 @@ fn intern_shallow<'tcx, M: CompileTimeMachine<'tcx>>( assert_eq!(alloc.mutability, Mutability::Mut); } } + Ok(()) +} + +/// Intern an allocation. Returns `Err` if the allocation does not exist in the local memory. +/// +/// `mutability` can be used to force immutable interning: if it is `Mutability::Not`, the +/// allocation is interned immutably; if it is `Mutability::Mut`, then the allocation *must be* +/// already mutable (as a sanity check). +/// +/// Returns an iterator over all relocations referred to by this allocation. +fn intern_shallow<'tcx, M: CompileTimeMachine<'tcx>>( + ecx: &mut InterpCx<'tcx, M>, + alloc_id: AllocId, + mutability: Mutability, + disambiguator: Option<&mut DisambiguatorState>, +) -> Result + 'tcx, InternError> { + trace!("intern_shallow {:?}", alloc_id); + // remove allocation + // FIXME(#120456) - is `swap_remove` correct? + let Some((kind, mut alloc)) = ecx.memory.alloc_map.swap_remove(&alloc_id) else { + return Err(InternError::DanglingPointer); + }; + + if let Err(err) = prepare_alloc(*ecx.tcx, kind, &mut alloc, mutability) { + // We want to error here, but we have to first put the + // allocation back into the `alloc_map` to keep things in a consistent state. + ecx.memory.alloc_map.insert(alloc_id, (kind, alloc)); + return Err(err); + } + // link the alloc id to the actual allocation let alloc = ecx.tcx.mk_const_alloc(alloc); if let Some(static_id) = ecx.machine.static_def_id() { @@ -166,6 +190,7 @@ pub enum InternError { BadMutablePointer, DanglingPointer, ConstAllocNotGlobal, + PartialPointer, } /// Intern `ret` and everything it references. @@ -221,13 +246,11 @@ pub fn intern_const_alloc_recursive<'tcx, M: CompileTimeMachine<'tcx>>( let mut todo: Vec<_> = if is_static { // Do not steal the root allocation, we need it later to create the return value of `eval_static_initializer`. // But still change its mutability to match the requested one. - let alloc = ecx.memory.alloc_map.get_mut(&base_alloc_id).unwrap(); - alloc.1.mutability = base_mutability; - alloc.1.provenance().ptrs().iter().map(|&(_, prov)| prov).collect() + let (kind, alloc) = ecx.memory.alloc_map.get_mut(&base_alloc_id).unwrap(); + prepare_alloc(*ecx.tcx, *kind, alloc, base_mutability)?; + alloc.provenance().ptrs().iter().map(|&(_, prov)| prov).collect() } else { - intern_shallow(ecx, base_alloc_id, base_mutability, Some(&mut disambiguator)) - .unwrap() - .collect() + intern_shallow(ecx, base_alloc_id, base_mutability, Some(&mut disambiguator))?.collect() }; // We need to distinguish "has just been interned" from "was already in `tcx`", // so we track this in a separate set. @@ -235,7 +258,6 @@ pub fn intern_const_alloc_recursive<'tcx, M: CompileTimeMachine<'tcx>>( // Whether we encountered a bad mutable pointer. // We want to first report "dangling" and then "mutable", so we need to delay reporting these // errors. - let mut result = Ok(()); let mut found_bad_mutable_ptr = false; // Keep interning as long as there are things to intern. @@ -310,20 +332,15 @@ pub fn intern_const_alloc_recursive<'tcx, M: CompileTimeMachine<'tcx>>( // okay with losing some potential for immutability here. This can anyway only affect // `static mut`. just_interned.insert(alloc_id); - match intern_shallow(ecx, alloc_id, inner_mutability, Some(&mut disambiguator)) { - Ok(nested) => todo.extend(nested), - Err(err) => { - ecx.tcx.dcx().delayed_bug("error during const interning"); - result = Err(err); - } - } + let next = intern_shallow(ecx, alloc_id, inner_mutability, Some(&mut disambiguator))?; + todo.extend(next); } - if found_bad_mutable_ptr && result.is_ok() { + if found_bad_mutable_ptr { // We found a mutable pointer inside a const where inner allocations should be immutable, // and there was no other error. This should usually never happen! However, this can happen // in unleash-miri mode, so report it as a normal error then. if ecx.tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you { - result = Err(InternError::BadMutablePointer); + return Err(InternError::BadMutablePointer); } else { span_bug!( ecx.tcx.span, @@ -331,7 +348,7 @@ pub fn intern_const_alloc_recursive<'tcx, M: CompileTimeMachine<'tcx>>( ); } } - result + Ok(()) } /// Intern `ret`. This function assumes that `ret` references no other allocation. diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 47bebf5371a9..b5703e789ff4 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -1310,29 +1310,20 @@ impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> } /// Mark the given sub-range (relative to this allocation reference) as uninitialized. - pub fn write_uninit(&mut self, range: AllocRange) -> InterpResult<'tcx> { + pub fn write_uninit(&mut self, range: AllocRange) { let range = self.range.subrange(range); - self.alloc - .write_uninit(&self.tcx, range) - .map_err(|e| e.to_interp_error(self.alloc_id)) - .into() + self.alloc.write_uninit(&self.tcx, range); } /// Mark the entire referenced range as uninitialized - pub fn write_uninit_full(&mut self) -> InterpResult<'tcx> { - self.alloc - .write_uninit(&self.tcx, self.range) - .map_err(|e| e.to_interp_error(self.alloc_id)) - .into() + pub fn write_uninit_full(&mut self) { + self.alloc.write_uninit(&self.tcx, self.range); } /// Remove all provenance in the reference range. - pub fn clear_provenance(&mut self) -> InterpResult<'tcx> { - self.alloc - .clear_provenance(&self.tcx, self.range) - .map_err(|e| e.to_interp_error(self.alloc_id)) - .into() + pub fn clear_provenance(&mut self) { + self.alloc.clear_provenance(&self.tcx, self.range); } } @@ -1423,11 +1414,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Side-step AllocRef and directly access the underlying bytes more efficiently. // (We are staying inside the bounds here and all bytes do get overwritten so all is good.) - let alloc_id = alloc_ref.alloc_id; - let bytes = alloc_ref - .alloc - .get_bytes_unchecked_for_overwrite(&alloc_ref.tcx, alloc_ref.range) - .map_err(move |e| e.to_interp_error(alloc_id))?; + let bytes = + alloc_ref.alloc.get_bytes_unchecked_for_overwrite(&alloc_ref.tcx, alloc_ref.range); // `zip` would stop when the first iterator ends; we want to definitely // cover all of `bytes`. for dest in bytes { @@ -1509,10 +1497,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // `get_bytes_mut` will clear the provenance, which is correct, // since we don't want to keep any provenance at the target. // This will also error if copying partial provenance is not supported. - let provenance = src_alloc - .provenance() - .prepare_copy(src_range, dest_offset, num_copies, self) - .map_err(|e| e.to_interp_error(src_alloc_id))?; + let provenance = + src_alloc.provenance().prepare_copy(src_range, dest_offset, num_copies, self); // Prepare a copy of the initialization mask. let init = src_alloc.init_mask().prepare_copy(src_range); @@ -1530,10 +1516,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { dest_range, )?; // Yes we do overwrite all bytes in `dest_bytes`. - let dest_bytes = dest_alloc - .get_bytes_unchecked_for_overwrite_ptr(&tcx, dest_range) - .map_err(|e| e.to_interp_error(dest_alloc_id))? - .as_mut_ptr(); + let dest_bytes = + dest_alloc.get_bytes_unchecked_for_overwrite_ptr(&tcx, dest_range).as_mut_ptr(); if init.no_bytes_init() { // Fast path: If all bytes are `uninit` then there is nothing to copy. The target range @@ -1542,9 +1526,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // This also avoids writing to the target bytes so that the backing allocation is never // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary // operating system this can avoid physically allocating the page. - dest_alloc - .write_uninit(&tcx, dest_range) - .map_err(|e| e.to_interp_error(dest_alloc_id))?; + dest_alloc.write_uninit(&tcx, dest_range); // `write_uninit` also resets the provenance, so we are done. return interp_ok(()); } diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index e2284729efdc..afd96a7c0c9e 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -700,7 +700,7 @@ where match value { Immediate::Scalar(scalar) => { - alloc.write_scalar(alloc_range(Size::ZERO, scalar.size()), scalar) + alloc.write_scalar(alloc_range(Size::ZERO, scalar.size()), scalar)?; } Immediate::ScalarPair(a_val, b_val) => { let BackendRepr::ScalarPair(a, b) = layout.backend_repr else { @@ -720,10 +720,10 @@ where alloc.write_scalar(alloc_range(Size::ZERO, a_val.size()), a_val)?; alloc.write_scalar(alloc_range(b_offset, b_val.size()), b_val)?; // We don't have to reset padding here, `write_immediate` will anyway do a validation run. - interp_ok(()) } Immediate::Uninit => alloc.write_uninit_full(), } + interp_ok(()) } pub fn write_uninit( @@ -743,7 +743,7 @@ where // Zero-sized access return interp_ok(()); }; - alloc.write_uninit_full()?; + alloc.write_uninit_full(); } } interp_ok(()) @@ -767,7 +767,7 @@ where // Zero-sized access return interp_ok(()); }; - alloc.clear_provenance()?; + alloc.clear_provenance(); } } interp_ok(()) diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 693b37829600..f8d9ebcafa76 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -949,7 +949,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { let padding_size = offset - padding_cleared_until; let range = alloc_range(padding_start, padding_size); trace!("reset_padding on {}: resetting padding range {range:?}", mplace.layout.ty); - alloc.write_uninit(range)?; + alloc.write_uninit(range); } padding_cleared_until = offset + size; } @@ -1239,7 +1239,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValueVisitor<'tcx, M> for ValidityVisitor<'rt, if self.reset_provenance_and_padding { // We can't share this with above as above, we might be looking at read-only memory. let mut alloc = self.ecx.get_ptr_alloc_mut(mplace.ptr(), size)?.expect("we already excluded size 0"); - alloc.clear_provenance()?; + alloc.clear_provenance(); // Also, mark this as containing data, not padding. self.add_data_range(mplace.ptr(), size); } diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index 27ead5145319..2ea92a39d482 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -306,8 +306,6 @@ pub enum AllocError { ScalarSizeMismatch(ScalarSizeMismatch), /// Encountered a pointer where we needed raw bytes. ReadPointerAsInt(Option), - /// Partially overwriting a pointer. - OverwritePartialPointer(Size), /// Partially copying a pointer. ReadPartialPointer(Size), /// Using uninitialized data where it is not allowed. @@ -331,9 +329,6 @@ impl AllocError { ReadPointerAsInt(info) => InterpErrorKind::Unsupported( UnsupportedOpInfo::ReadPointerAsInt(info.map(|b| (alloc_id, b))), ), - OverwritePartialPointer(offset) => InterpErrorKind::Unsupported( - UnsupportedOpInfo::OverwritePartialPointer(Pointer::new(alloc_id, offset)), - ), ReadPartialPointer(offset) => InterpErrorKind::Unsupported( UnsupportedOpInfo::ReadPartialPointer(Pointer::new(alloc_id, offset)), ), @@ -633,11 +628,11 @@ impl Allocation &mut self, cx: &impl HasDataLayout, range: AllocRange, - ) -> AllocResult<&mut [u8]> { + ) -> &mut [u8] { self.mark_init(range, true); - self.provenance.clear(range, cx)?; + self.provenance.clear(range, cx); - Ok(&mut self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) + &mut self.bytes[range.start.bytes_usize()..range.end().bytes_usize()] } /// A raw pointer variant of `get_bytes_unchecked_for_overwrite` that avoids invalidating existing immutable aliases @@ -646,15 +641,15 @@ impl Allocation &mut self, cx: &impl HasDataLayout, range: AllocRange, - ) -> AllocResult<*mut [u8]> { + ) -> *mut [u8] { self.mark_init(range, true); - self.provenance.clear(range, cx)?; + self.provenance.clear(range, cx); assert!(range.end().bytes_usize() <= self.bytes.len()); // need to do our own bounds-check // Crucially, we go via `AllocBytes::as_mut_ptr`, not `AllocBytes::deref_mut`. let begin_ptr = self.bytes.as_mut_ptr().wrapping_add(range.start.bytes_usize()); let len = range.end().bytes_usize() - range.start.bytes_usize(); - Ok(ptr::slice_from_raw_parts_mut(begin_ptr, len)) + ptr::slice_from_raw_parts_mut(begin_ptr, len) } /// This gives direct mutable access to the entire buffer, just exposing their internal state @@ -723,26 +718,45 @@ impl Allocation let ptr = Pointer::new(prov, Size::from_bytes(bits)); return Ok(Scalar::from_pointer(ptr, cx)); } - - // If we can work on pointers byte-wise, join the byte-wise provenances. - if Prov::OFFSET_IS_ADDR { - let mut prov = self.provenance.get(range.start, cx); + // The other easy case is total absence of provenance. + if self.provenance.range_empty(range, cx) { + return Ok(Scalar::from_uint(bits, range.size)); + } + // If we get here, we have to check per-byte provenance, and join them together. + let prov = 'prov: { + // Initialize with first fragment. Must have index 0. + let Some((mut joint_prov, 0)) = self.provenance.get_byte(range.start, cx) else { + break 'prov None; + }; + // Update with the remaining fragments. for offset in Size::from_bytes(1)..range.size { - let this_prov = self.provenance.get(range.start + offset, cx); - prov = Prov::join(prov, this_prov); + // Ensure there is provenance here and it has the right index. + let Some((frag_prov, frag_idx)) = + self.provenance.get_byte(range.start + offset, cx) + else { + break 'prov None; + }; + // Wildcard provenance is allowed to come with any index (this is needed + // for Miri's native-lib mode to work). + if u64::from(frag_idx) != offset.bytes() && Some(frag_prov) != Prov::WILDCARD { + break 'prov None; + } + // Merge this byte's provenance with the previous ones. + joint_prov = match Prov::join(joint_prov, frag_prov) { + Some(prov) => prov, + None => break 'prov None, + }; } - // Now use this provenance. - let ptr = Pointer::new(prov, Size::from_bytes(bits)); - return Ok(Scalar::from_maybe_pointer(ptr, cx)); - } else { - // Without OFFSET_IS_ADDR, the only remaining case we can handle is total absence of - // provenance. - if self.provenance.range_empty(range, cx) { - return Ok(Scalar::from_uint(bits, range.size)); - } - // Else we have mixed provenance, that doesn't work. + break 'prov Some(joint_prov); + }; + if prov.is_none() && !Prov::OFFSET_IS_ADDR { + // There are some bytes with provenance here but overall the provenance does not add up. + // We need `OFFSET_IS_ADDR` to fall back to no-provenance here; without that option, we must error. return Err(AllocError::ReadPartialPointer(range.start)); } + // We can use this provenance. + let ptr = Pointer::new(prov, Size::from_bytes(bits)); + return Ok(Scalar::from_maybe_pointer(ptr, cx)); } else { // We are *not* reading a pointer. // If we can just ignore provenance or there is none, that's easy. @@ -782,7 +796,7 @@ impl Allocation let endian = cx.data_layout().endian; // Yes we do overwrite all the bytes in `dst`. - let dst = self.get_bytes_unchecked_for_overwrite(cx, range)?; + let dst = self.get_bytes_unchecked_for_overwrite(cx, range); write_target_uint(endian, dst, bytes).unwrap(); // See if we have to also store some provenance. @@ -795,10 +809,9 @@ impl Allocation } /// Write "uninit" to the given memory range. - pub fn write_uninit(&mut self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { + pub fn write_uninit(&mut self, cx: &impl HasDataLayout, range: AllocRange) { self.mark_init(range, false); - self.provenance.clear(range, cx)?; - Ok(()) + self.provenance.clear(range, cx); } /// Mark all bytes in the given range as initialised and reset the provenance @@ -817,9 +830,12 @@ impl Allocation } /// Remove all provenance in the given memory range. - pub fn clear_provenance(&mut self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { - self.provenance.clear(range, cx)?; - return Ok(()); + pub fn clear_provenance(&mut self, cx: &impl HasDataLayout, range: AllocRange) { + self.provenance.clear(range, cx); + } + + pub fn provenance_merge_bytes(&mut self, cx: &impl HasDataLayout) -> bool { + self.provenance.merge_bytes(cx) } /// Applies a previously prepared provenance copy. diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs index 119d4be64e6a..ea8596ea2865 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs @@ -10,7 +10,7 @@ use rustc_macros::HashStable; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use tracing::trace; -use super::{AllocError, AllocRange, AllocResult, CtfeProvenance, Provenance, alloc_range}; +use super::{AllocRange, CtfeProvenance, Provenance, alloc_range}; /// Stores the provenance information of pointers stored in memory. #[derive(Clone, PartialEq, Eq, Hash, Debug)] @@ -19,25 +19,25 @@ pub struct ProvenanceMap { /// `Provenance` in this map applies from the given offset for an entire pointer-size worth of /// bytes. Two entries in this map are always at least a pointer size apart. ptrs: SortedMap, - /// Provenance in this map only applies to the given single byte. - /// This map is disjoint from the previous. It will always be empty when - /// `Prov::OFFSET_IS_ADDR` is false. - bytes: Option>>, + /// This stores byte-sized provenance fragments. + /// The `u8` indicates the position of this byte inside its original pointer. + /// If the bytes are re-assembled in their original order, the pointer can be used again. + /// Wildcard provenance is allowed to have index 0 everywhere. + bytes: Option>>, } // These impls are generic over `Prov` since `CtfeProvenance` is only decodable/encodable // for some particular `D`/`S`. impl> Decodable for ProvenanceMap { fn decode(d: &mut D) -> Self { - assert!(!Prov::OFFSET_IS_ADDR); // only `CtfeProvenance` is ever serialized + // `bytes` is not in the serialized format Self { ptrs: Decodable::decode(d), bytes: None } } } impl> Encodable for ProvenanceMap { fn encode(&self, s: &mut S) { let Self { ptrs, bytes } = self; - assert!(!Prov::OFFSET_IS_ADDR); // only `CtfeProvenance` is ever serialized - debug_assert!(bytes.is_none()); // without `OFFSET_IS_ADDR`, this is always empty + assert!(bytes.is_none()); // interning refuses allocations with pointer fragments ptrs.encode(s) } } @@ -58,10 +58,10 @@ impl ProvenanceMap { /// Give access to the ptr-sized provenances (which can also be thought of as relocations, and /// indeed that is how codegen treats them). /// - /// Only exposed with `CtfeProvenance` provenance, since it panics if there is bytewise provenance. + /// Only use on interned allocations, as other allocations may have per-byte provenance! #[inline] pub fn ptrs(&self) -> &SortedMap { - debug_assert!(self.bytes.is_none()); // `CtfeProvenance::OFFSET_IS_ADDR` is false so this cannot fail + assert!(self.bytes.is_none(), "`ptrs()` called on non-interned allocation"); &self.ptrs } } @@ -88,12 +88,12 @@ impl ProvenanceMap { } /// `pm.range_ptrs_is_empty(r, cx)` == `pm.range_ptrs_get(r, cx).is_empty()`, but is faster. - pub(super) fn range_ptrs_is_empty(&self, range: AllocRange, cx: &impl HasDataLayout) -> bool { + fn range_ptrs_is_empty(&self, range: AllocRange, cx: &impl HasDataLayout) -> bool { self.ptrs.range_is_empty(Self::adjusted_range_ptrs(range, cx)) } /// Returns all byte-wise provenance in the given range. - fn range_bytes_get(&self, range: AllocRange) -> &[(Size, Prov)] { + fn range_bytes_get(&self, range: AllocRange) -> &[(Size, (Prov, u8))] { if let Some(bytes) = self.bytes.as_ref() { bytes.range(range.start..range.end()) } else { @@ -107,19 +107,47 @@ impl ProvenanceMap { } /// Get the provenance of a single byte. - pub fn get(&self, offset: Size, cx: &impl HasDataLayout) -> Option { + pub fn get_byte(&self, offset: Size, cx: &impl HasDataLayout) -> Option<(Prov, u8)> { let prov = self.range_ptrs_get(alloc_range(offset, Size::from_bytes(1)), cx); debug_assert!(prov.len() <= 1); if let Some(entry) = prov.first() { // If it overlaps with this byte, it is on this byte. debug_assert!(self.bytes.as_ref().is_none_or(|b| !b.contains_key(&offset))); - Some(entry.1) + Some((entry.1, (offset - entry.0).bytes() as u8)) } else { // Look up per-byte provenance. self.bytes.as_ref().and_then(|b| b.get(&offset).copied()) } } + /// Attempt to merge per-byte provenance back into ptr chunks, if the right fragments + /// sit next to each other. Return `false` is that is not possible due to partial pointers. + pub fn merge_bytes(&mut self, cx: &impl HasDataLayout) -> bool { + let Some(bytes) = self.bytes.as_deref_mut() else { + return true; + }; + let ptr_size = cx.data_layout().pointer_size(); + while let Some((offset, (prov, _))) = bytes.iter().next().copied() { + // Check if this fragment starts a pointer. + let range = offset..offset + ptr_size; + let frags = bytes.range(range.clone()); + if frags.len() != ptr_size.bytes_usize() { + return false; + } + for (idx, (_offset, (frag_prov, frag_idx))) in frags.iter().copied().enumerate() { + if frag_prov != prov || frag_idx != idx as u8 { + return false; + } + } + // Looks like a pointer! Move it over to the ptr provenance map. + bytes.remove_range(range); + self.ptrs.insert(offset, prov); + } + // We managed to convert everything into whole pointers. + self.bytes = None; + true + } + /// Check if there is ptr-sized provenance at the given index. /// Does not mean anything for bytewise provenance! But can be useful as an optimization. pub fn get_ptr(&self, offset: Size) -> Option { @@ -137,7 +165,7 @@ impl ProvenanceMap { /// Yields all the provenances stored in this map. pub fn provenances(&self) -> impl Iterator { - let bytes = self.bytes.iter().flat_map(|b| b.values()); + let bytes = self.bytes.iter().flat_map(|b| b.values().map(|(p, _i)| p)); self.ptrs.values().chain(bytes).copied() } @@ -148,16 +176,12 @@ impl ProvenanceMap { /// Removes all provenance inside the given range. /// If there is provenance overlapping with the edges, might result in an error. - pub fn clear(&mut self, range: AllocRange, cx: &impl HasDataLayout) -> AllocResult { + pub fn clear(&mut self, range: AllocRange, cx: &impl HasDataLayout) { let start = range.start; let end = range.end(); // Clear the bytewise part -- this is easy. - if Prov::OFFSET_IS_ADDR { - if let Some(bytes) = self.bytes.as_mut() { - bytes.remove_range(start..end); - } - } else { - debug_assert!(self.bytes.is_none()); + if let Some(bytes) = self.bytes.as_mut() { + bytes.remove_range(start..end); } let pointer_size = cx.data_layout().pointer_size(); @@ -168,7 +192,7 @@ impl ProvenanceMap { // Find all provenance overlapping the given range. if self.range_ptrs_is_empty(range, cx) { // No provenance in this range, we are done. This is the common case. - return Ok(()); + return; } // This redoes some of the work of `range_get_ptrs_is_empty`, but this path is much @@ -179,28 +203,20 @@ impl ProvenanceMap { // We need to handle clearing the provenance from parts of a pointer. if first < start { - if !Prov::OFFSET_IS_ADDR { - // We can't split up the provenance into less than a pointer. - return Err(AllocError::OverwritePartialPointer(first)); - } // Insert the remaining part in the bytewise provenance. let prov = self.ptrs[&first]; let bytes = self.bytes.get_or_insert_with(Box::default); for offset in first..start { - bytes.insert(offset, prov); + bytes.insert(offset, (prov, (offset - first).bytes() as u8)); } } if last > end { let begin_of_last = last - pointer_size; - if !Prov::OFFSET_IS_ADDR { - // We can't split up the provenance into less than a pointer. - return Err(AllocError::OverwritePartialPointer(begin_of_last)); - } // Insert the remaining part in the bytewise provenance. let prov = self.ptrs[&begin_of_last]; let bytes = self.bytes.get_or_insert_with(Box::default); for offset in end..last { - bytes.insert(offset, prov); + bytes.insert(offset, (prov, (offset - begin_of_last).bytes() as u8)); } } @@ -208,8 +224,6 @@ impl ProvenanceMap { // Since provenance do not overlap, we know that removing until `last` (exclusive) is fine, // i.e., this will not remove any other provenance just after the ones we care about. self.ptrs.remove_range(first..last); - - Ok(()) } /// Overwrites all provenance in the given range with wildcard provenance. @@ -218,10 +232,6 @@ impl ProvenanceMap { /// /// Provided for usage in Miri and panics otherwise. pub fn write_wildcards(&mut self, cx: &impl HasDataLayout, range: AllocRange) { - assert!( - Prov::OFFSET_IS_ADDR, - "writing wildcard provenance is not supported when `OFFSET_IS_ADDR` is false" - ); let wildcard = Prov::WILDCARD.unwrap(); let bytes = self.bytes.get_or_insert_with(Box::default); @@ -229,21 +239,22 @@ impl ProvenanceMap { // Remove pointer provenances that overlap with the range, then readd the edge ones bytewise. let ptr_range = Self::adjusted_range_ptrs(range, cx); let ptrs = self.ptrs.range(ptr_range.clone()); - if let Some((offset, prov)) = ptrs.first() { - for byte_ofs in *offset..range.start { - bytes.insert(byte_ofs, *prov); + if let Some((offset, prov)) = ptrs.first().copied() { + for byte_ofs in offset..range.start { + bytes.insert(byte_ofs, (prov, (byte_ofs - offset).bytes() as u8)); } } - if let Some((offset, prov)) = ptrs.last() { - for byte_ofs in range.end()..*offset + cx.data_layout().pointer_size() { - bytes.insert(byte_ofs, *prov); + if let Some((offset, prov)) = ptrs.last().copied() { + for byte_ofs in range.end()..offset + cx.data_layout().pointer_size() { + bytes.insert(byte_ofs, (prov, (byte_ofs - offset).bytes() as u8)); } } self.ptrs.remove_range(ptr_range); // Overwrite bytewise provenance. for offset in range.start..range.end() { - bytes.insert(offset, wildcard); + // The fragment index does not matter for wildcard provenance. + bytes.insert(offset, (wildcard, 0)); } } } @@ -253,7 +264,7 @@ impl ProvenanceMap { /// Offsets are already adjusted to the destination allocation. pub struct ProvenanceCopy { dest_ptrs: Option>, - dest_bytes: Option>, + dest_bytes: Option>, } impl ProvenanceMap { @@ -263,7 +274,7 @@ impl ProvenanceMap { dest: Size, count: u64, cx: &impl HasDataLayout, - ) -> AllocResult> { + ) -> ProvenanceCopy { let shift_offset = move |idx, offset| { // compute offset for current repetition let dest_offset = dest + src.size * idx; // `Size` operations @@ -301,24 +312,16 @@ impl ProvenanceMap { let mut dest_bytes_box = None; let begin_overlap = self.range_ptrs_get(alloc_range(src.start, Size::ZERO), cx).first(); let end_overlap = self.range_ptrs_get(alloc_range(src.end(), Size::ZERO), cx).first(); - if !Prov::OFFSET_IS_ADDR { - // There can't be any bytewise provenance, and we cannot split up the begin/end overlap. - if let Some(entry) = begin_overlap { - return Err(AllocError::ReadPartialPointer(entry.0)); - } - if let Some(entry) = end_overlap { - return Err(AllocError::ReadPartialPointer(entry.0)); - } - debug_assert!(self.bytes.is_none()); - } else { - let mut bytes = Vec::new(); + // We only need to go here if there is some overlap or some bytewise provenance. + if begin_overlap.is_some() || end_overlap.is_some() || self.bytes.is_some() { + let mut bytes: Vec<(Size, (Prov, u8))> = Vec::new(); // First, if there is a part of a pointer at the start, add that. if let Some(entry) = begin_overlap { trace!("start overlapping entry: {entry:?}"); // For really small copies, make sure we don't run off the end of the `src` range. let entry_end = cmp::min(entry.0 + ptr_size, src.end()); for offset in src.start..entry_end { - bytes.push((offset, entry.1)); + bytes.push((offset, (entry.1, (offset - entry.0).bytes() as u8))); } } else { trace!("no start overlapping entry"); @@ -334,8 +337,9 @@ impl ProvenanceMap { let entry_start = cmp::max(entry.0, src.start); for offset in entry_start..src.end() { if bytes.last().is_none_or(|bytes_entry| bytes_entry.0 < offset) { - // The last entry, if it exists, has a lower offset than us. - bytes.push((offset, entry.1)); + // The last entry, if it exists, has a lower offset than us, so we + // can add it at the end and remain sorted. + bytes.push((offset, (entry.1, (offset - entry.0).bytes() as u8))); } else { // There already is an entry for this offset in there! This can happen when the // start and end range checks actually end up hitting the same pointer, so we @@ -358,7 +362,7 @@ impl ProvenanceMap { dest_bytes_box = Some(dest_bytes.into_boxed_slice()); } - Ok(ProvenanceCopy { dest_ptrs: dest_ptrs_box, dest_bytes: dest_bytes_box }) + ProvenanceCopy { dest_ptrs: dest_ptrs_box, dest_bytes: dest_bytes_box } } /// Applies a provenance copy. @@ -368,14 +372,10 @@ impl ProvenanceMap { if let Some(dest_ptrs) = copy.dest_ptrs { self.ptrs.insert_presorted(dest_ptrs.into()); } - if Prov::OFFSET_IS_ADDR { - if let Some(dest_bytes) = copy.dest_bytes - && !dest_bytes.is_empty() - { - self.bytes.get_or_insert_with(Box::default).insert_presorted(dest_bytes.into()); - } - } else { - debug_assert!(copy.dest_bytes.is_none()); + if let Some(dest_bytes) = copy.dest_bytes + && !dest_bytes.is_empty() + { + self.bytes.get_or_insert_with(Box::default).insert_presorted(dest_bytes.into()); } } } diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 2b0cfb865645..d8168697b4ae 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -577,9 +577,6 @@ pub enum UnsupportedOpInfo { // // The variants below are only reachable from CTFE/const prop, miri will never emit them. // - /// Overwriting parts of a pointer; without knowing absolute addresses, the resulting state - /// cannot be represented by the CTFE interpreter. - OverwritePartialPointer(Pointer), /// Attempting to read or copy parts of a pointer to somewhere else; without knowing absolute /// addresses, the resulting state cannot be represented by the CTFE interpreter. ReadPartialPointer(Pointer), diff --git a/compiler/rustc_middle/src/mir/interpret/pointer.rs b/compiler/rustc_middle/src/mir/interpret/pointer.rs index e25ff7651f65..c581b2ebf092 100644 --- a/compiler/rustc_middle/src/mir/interpret/pointer.rs +++ b/compiler/rustc_middle/src/mir/interpret/pointer.rs @@ -56,7 +56,7 @@ impl PointerArithmetic for T {} /// mostly opaque; the `Machine` trait extends it with some more operations that also have access to /// some global state. /// The `Debug` rendering is used to display bare provenance, and for the default impl of `fmt`. -pub trait Provenance: Copy + fmt::Debug + 'static { +pub trait Provenance: Copy + PartialEq + fmt::Debug + 'static { /// Says whether the `offset` field of `Pointer`s with this provenance is the actual physical address. /// - If `false`, the offset *must* be relative. This means the bytes representing a pointer are /// different from what the Abstract Machine prescribes, so the interpreter must prevent any @@ -79,7 +79,7 @@ pub trait Provenance: Copy + fmt::Debug + 'static { fn get_alloc_id(self) -> Option; /// Defines the 'join' of provenance: what happens when doing a pointer load and different bytes have different provenance. - fn join(left: Option, right: Option) -> Option; + fn join(left: Self, right: Self) -> Option; } /// The type of provenance in the compile-time interpreter. @@ -192,8 +192,8 @@ impl Provenance for CtfeProvenance { Some(self.alloc_id()) } - fn join(_left: Option, _right: Option) -> Option { - panic!("merging provenance is not supported when `OFFSET_IS_ADDR` is false") + fn join(left: Self, right: Self) -> Option { + if left == right { Some(left) } else { None } } } @@ -224,8 +224,8 @@ impl Provenance for AllocId { Some(self) } - fn join(_left: Option, _right: Option) -> Option { - panic!("merging provenance is not supported when `OFFSET_IS_ADDR` is false") + fn join(_left: Self, _right: Self) -> Option { + unreachable!() } } diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 809cdb329f79..c0dd9a58f85a 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -1826,7 +1826,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( ascii.push('╼'); i += ptr_size; } - } else if let Some(prov) = alloc.provenance().get(i, &tcx) { + } else if let Some((prov, idx)) = alloc.provenance().get_byte(i, &tcx) { // Memory with provenance must be defined assert!( alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok() @@ -1836,7 +1836,7 @@ pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>( // Format is similar to "oversized" above. let j = i.bytes_usize(); let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0]; - write!(w, "╾{c:02x}{prov:#?} (1 ptr byte)╼")?; + write!(w, "╾{c:02x}{prov:#?} (ptr fragment {idx})╼")?; i += Size::from_bytes(1); } else if alloc .init_mask() diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index dbe3999b4a43..7339ccd40488 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -1345,40 +1345,6 @@ pub const unsafe fn swap(x: *mut T, y: *mut T) { /// assert_eq!(x, [7, 8, 3, 4]); /// assert_eq!(y, [1, 2, 9]); /// ``` -/// -/// # Const evaluation limitations -/// -/// If this function is invoked during const-evaluation, the current implementation has a small (and -/// rarely relevant) limitation: if `count` is at least 2 and the data pointed to by `x` or `y` -/// contains a pointer that crosses the boundary of two `T`-sized chunks of memory, the function may -/// fail to evaluate (similar to a panic during const-evaluation). This behavior may change in the -/// future. -/// -/// The limitation is illustrated by the following example: -/// -/// ``` -/// use std::mem::size_of; -/// use std::ptr; -/// -/// const { unsafe { -/// const PTR_SIZE: usize = size_of::<*const i32>(); -/// let mut data1 = [0u8; PTR_SIZE]; -/// let mut data2 = [0u8; PTR_SIZE]; -/// // Store a pointer in `data1`. -/// data1.as_mut_ptr().cast::<*const i32>().write_unaligned(&42); -/// // Swap the contents of `data1` and `data2` by swapping `PTR_SIZE` many `u8`-sized chunks. -/// // This call will fail, because the pointer in `data1` crosses the boundary -/// // between several of the 1-byte chunks that are being swapped here. -/// //ptr::swap_nonoverlapping(data1.as_mut_ptr(), data2.as_mut_ptr(), PTR_SIZE); -/// // Swap the contents of `data1` and `data2` by swapping a single chunk of size -/// // `[u8; PTR_SIZE]`. That works, as there is no pointer crossing the boundary between -/// // two chunks. -/// ptr::swap_nonoverlapping(&mut data1, &mut data2, 1); -/// // Read the pointer from `data2` and dereference it. -/// let ptr = data2.as_ptr().cast::<*const i32>().read_unaligned(); -/// assert!(*ptr == 42); -/// } } -/// ``` #[inline] #[stable(feature = "swap_nonoverlapping", since = "1.27.0")] #[rustc_const_stable(feature = "const_swap_nonoverlapping", since = "1.88.0")] @@ -1407,9 +1373,7 @@ pub const unsafe fn swap_nonoverlapping(x: *mut T, y: *mut T, count: usize) { const_eval_select!( @capture[T] { x: *mut T, y: *mut T, count: usize }: if const { - // At compile-time we want to always copy this in chunks of `T`, to ensure that if there - // are pointers inside `T` we will copy them in one go rather than trying to copy a part - // of a pointer (which would not work). + // At compile-time we don't need all the special code below. // SAFETY: Same preconditions as this function unsafe { swap_nonoverlapping_const(x, y, count) } } else { diff --git a/library/coretests/tests/ptr.rs b/library/coretests/tests/ptr.rs index 197a14423b59..c13fb96a67f9 100644 --- a/library/coretests/tests/ptr.rs +++ b/library/coretests/tests/ptr.rs @@ -936,22 +936,18 @@ fn test_const_swap_ptr() { assert!(*s1.0.ptr == 666); assert!(*s2.0.ptr == 1); - // Swap them back, again as an array. + // Swap them back, byte-for-byte unsafe { ptr::swap_nonoverlapping( - ptr::from_mut(&mut s1).cast::(), - ptr::from_mut(&mut s2).cast::(), - 1, + ptr::from_mut(&mut s1).cast::(), + ptr::from_mut(&mut s2).cast::(), + size_of::(), ); } // Make sure they still work. assert!(*s1.0.ptr == 1); assert!(*s2.0.ptr == 666); - - // This is where we'd swap again using a `u8` type and a `count` of `size_of::()` if it - // were not for the limitation of `swap_nonoverlapping` around pointers crossing multiple - // elements. }; } diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 7271d3f619c7..b8a187fed7c0 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -285,16 +285,16 @@ impl interpret::Provenance for Provenance { Ok(()) } - fn join(left: Option, right: Option) -> Option { + fn join(left: Self, right: Self) -> Option { match (left, right) { // If both are the *same* concrete tag, that is the result. ( - Some(Provenance::Concrete { alloc_id: left_alloc, tag: left_tag }), - Some(Provenance::Concrete { alloc_id: right_alloc, tag: right_tag }), - ) if left_alloc == right_alloc && left_tag == right_tag => left, + Provenance::Concrete { alloc_id: left_alloc, tag: left_tag }, + Provenance::Concrete { alloc_id: right_alloc, tag: right_tag }, + ) if left_alloc == right_alloc && left_tag == right_tag => Some(left), // If one side is a wildcard, the best possible outcome is that it is equal to the other // one, and we use that. - (Some(Provenance::Wildcard), o) | (o, Some(Provenance::Wildcard)) => o, + (Provenance::Wildcard, o) | (o, Provenance::Wildcard) => Some(o), // Otherwise, fall back to `None`. _ => None, } diff --git a/src/tools/miri/src/shims/native_lib/mod.rs b/src/tools/miri/src/shims/native_lib/mod.rs index 2827ed997a7c..36c18379cb86 100644 --- a/src/tools/miri/src/shims/native_lib/mod.rs +++ b/src/tools/miri/src/shims/native_lib/mod.rs @@ -246,7 +246,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { let p_map = alloc.provenance(); for idx in overlap { // If a provenance was read by the foreign code, expose it. - if let Some(prov) = p_map.get(Size::from_bytes(idx), this) { + if let Some((prov, _idx)) = p_map.get_byte(Size::from_bytes(idx), this) { this.expose_provenance(prov)?; } } diff --git a/src/tools/miri/tests/fail/provenance/mix-ptrs1.rs b/src/tools/miri/tests/fail/provenance/mix-ptrs1.rs new file mode 100644 index 000000000000..0b7266a4da6d --- /dev/null +++ b/src/tools/miri/tests/fail/provenance/mix-ptrs1.rs @@ -0,0 +1,21 @@ +use std::{mem, ptr}; + +const PTR_SIZE: usize = mem::size_of::<&i32>(); + +fn main() { + unsafe { + let ptr = &0 as *const i32; + let arr = [ptr; 2]; + // We want to do a scalar read of a pointer at offset PTR_SIZE/2 into this array. But we + // cannot use a packed struct or `read_unaligned`, as those use the memcpy code path in + // Miri. So instead we shift the entire array by a bit and then the actual read we want to + // do is perfectly aligned. + let mut target_arr = [ptr::null::(); 3]; + let target = target_arr.as_mut_ptr().cast::(); + target.add(PTR_SIZE / 2).cast::<[*const i32; 2]>().write_unaligned(arr); + // Now target_arr[1] is a mix of the two `ptr` we had stored in `arr`. + // They all have the same provenance, but not in the right order, so we reject this. + let strange_ptr = target_arr[1]; + assert_eq!(*strange_ptr.with_addr(ptr.addr()), 0); //~ERROR: no provenance + } +} diff --git a/src/tools/miri/tests/fail/provenance/mix-ptrs1.stderr b/src/tools/miri/tests/fail/provenance/mix-ptrs1.stderr new file mode 100644 index 000000000000..88d75135a763 --- /dev/null +++ b/src/tools/miri/tests/fail/provenance/mix-ptrs1.stderr @@ -0,0 +1,16 @@ +error: Undefined Behavior: pointer not dereferenceable: pointer must be dereferenceable for 4 bytes, but got $HEX[noalloc] which is a dangling pointer (it has no provenance) + --> tests/fail/provenance/mix-ptrs1.rs:LL:CC + | +LL | assert_eq!(*strange_ptr.with_addr(ptr.addr()), 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: BACKTRACE: + = note: inside `main` at RUSTLIB/core/src/macros/mod.rs:LL:CC + = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail/provenance/mix-ptrs2.rs b/src/tools/miri/tests/fail/provenance/mix-ptrs2.rs new file mode 100644 index 000000000000..9ef40c194abd --- /dev/null +++ b/src/tools/miri/tests/fail/provenance/mix-ptrs2.rs @@ -0,0 +1,37 @@ +use std::mem; + +const PTR_SIZE: usize = mem::size_of::<&i32>(); + +/// Overwrite one byte of a pointer, then restore it. +fn main() { + unsafe fn ptr_bytes<'x>(ptr: &'x mut *const i32) -> &'x mut [mem::MaybeUninit; PTR_SIZE] { + mem::transmute(ptr) + } + + // Returns a value with the same provenance as `x` but 0 for the integer value. + // `x` must be initialized. + unsafe fn zero_with_provenance(x: mem::MaybeUninit) -> mem::MaybeUninit { + let ptr = [x; PTR_SIZE]; + let ptr: *const i32 = mem::transmute(ptr); + let mut ptr = ptr.with_addr(0); + ptr_bytes(&mut ptr)[0] + } + + unsafe { + let ptr = &42; + let mut ptr = ptr as *const i32; + // Get a bytewise view of the pointer. + let ptr_bytes = ptr_bytes(&mut ptr); + + // The highest bytes must be 0 for this to work. + let hi = if cfg!(target_endian = "little") { ptr_bytes.len() - 1 } else { 0 }; + assert_eq!(*ptr_bytes[hi].as_ptr().cast::(), 0); + // Overwrite provenance on the last byte. + ptr_bytes[hi] = mem::MaybeUninit::new(0); + // Restore it from the another byte. + ptr_bytes[hi] = zero_with_provenance(ptr_bytes[1]); + + // Now ptr is almost good, except the provenance fragment indices do not work out... + assert_eq!(*ptr, 42); //~ERROR: no provenance + } +} diff --git a/src/tools/miri/tests/fail/provenance/mix-ptrs2.stderr b/src/tools/miri/tests/fail/provenance/mix-ptrs2.stderr new file mode 100644 index 000000000000..636378952ba5 --- /dev/null +++ b/src/tools/miri/tests/fail/provenance/mix-ptrs2.stderr @@ -0,0 +1,16 @@ +error: Undefined Behavior: pointer not dereferenceable: pointer must be dereferenceable for 4 bytes, but got $HEX[noalloc] which is a dangling pointer (it has no provenance) + --> tests/fail/provenance/mix-ptrs2.rs:LL:CC + | +LL | assert_eq!(*ptr, 42); + | ^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: BACKTRACE: + = note: inside `main` at RUSTLIB/core/src/macros/mod.rs:LL:CC + = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail/uninit/uninit_alloc_diagnostic_with_provenance.rs b/src/tools/miri/tests/fail/uninit/uninit_alloc_diagnostic_with_provenance.rs index 1cf70d9d9a34..78a5098d21a1 100644 --- a/src/tools/miri/tests/fail/uninit/uninit_alloc_diagnostic_with_provenance.rs +++ b/src/tools/miri/tests/fail/uninit/uninit_alloc_diagnostic_with_provenance.rs @@ -9,11 +9,10 @@ use std::alloc::{Layout, alloc, dealloc}; use std::mem::{self, MaybeUninit}; use std::slice::from_raw_parts; -fn byte_with_provenance(val: u8, prov: *const T) -> MaybeUninit { - let ptr = prov.with_addr(val as usize); +fn byte_with_provenance(val: u8, prov: *const T, frag_idx: usize) -> MaybeUninit { + let ptr = prov.with_addr(usize::from_ne_bytes([val; _])); let bytes: [MaybeUninit; mem::size_of::<*const ()>()] = unsafe { mem::transmute(ptr) }; - let lsb = if cfg!(target_endian = "little") { 0 } else { bytes.len() - 1 }; - bytes[lsb] + bytes[frag_idx] } fn main() { @@ -21,10 +20,10 @@ fn main() { unsafe { let ptr = alloc(layout); let ptr_raw = ptr.cast::>(); - *ptr_raw.add(0) = byte_with_provenance(0x42, &42u8); + *ptr_raw.add(0) = byte_with_provenance(0x42, &42u8, 0); *ptr.add(1) = 0x12; *ptr.add(2) = 0x13; - *ptr_raw.add(3) = byte_with_provenance(0x43, &0u8); + *ptr_raw.add(3) = byte_with_provenance(0x43, &0u8, 1); let slice1 = from_raw_parts(ptr, 8); let slice2 = from_raw_parts(ptr.add(8), 8); drop(slice1.cmp(slice2)); diff --git a/src/tools/miri/tests/fail/uninit/uninit_alloc_diagnostic_with_provenance.stderr b/src/tools/miri/tests/fail/uninit/uninit_alloc_diagnostic_with_provenance.stderr index d3253317faee..305d8d4fbede 100644 --- a/src/tools/miri/tests/fail/uninit/uninit_alloc_diagnostic_with_provenance.stderr +++ b/src/tools/miri/tests/fail/uninit/uninit_alloc_diagnostic_with_provenance.stderr @@ -17,7 +17,7 @@ LL | drop(slice1.cmp(slice2)); Uninitialized memory occurred at ALLOC[0x4..0x8], in this allocation: ALLOC (Rust heap, size: 16, align: 8) { - ╾42[ALLOC] (1 ptr byte)╼ 12 13 ╾43[ALLOC] (1 ptr byte)╼ __ __ __ __ __ __ __ __ __ __ __ __ │ ━..━░░░░░░░░░░░░ + ╾42[ALLOC] (ptr fragment 0)╼ 12 13 ╾43[ALLOC] (ptr fragment 1)╼ __ __ __ __ __ __ __ __ __ __ __ __ │ ━..━░░░░░░░░░░░░ } ALLOC (global (static or const), size: 1, align: 1) { 2a │ * diff --git a/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr b/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr index 74a599ede5c3..1c0ad2f0dc91 100644 --- a/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr +++ b/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr @@ -35,7 +35,7 @@ LL | partial_init(); Uninitialized memory occurred at ALLOC[0x2..0x3], in this allocation: ALLOC (stack variable, size: 3, align: 1) { - ╾00[wildcard] (1 ptr byte)╼ ╾00[wildcard] (1 ptr byte)╼ __ │ ━━░ + ╾00[wildcard] (ptr fragment 0)╼ ╾00[wildcard] (ptr fragment 0)╼ __ │ ━━░ } note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace diff --git a/src/tools/miri/tests/pass/provenance.rs b/src/tools/miri/tests/pass/provenance.rs index 8c52b703190d..46f5bd73d55b 100644 --- a/src/tools/miri/tests/pass/provenance.rs +++ b/src/tools/miri/tests/pass/provenance.rs @@ -6,7 +6,6 @@ const PTR_SIZE: usize = mem::size_of::<&i32>(); fn main() { basic(); - partial_overwrite_then_restore(); bytewise_ptr_methods(); bytewise_custom_memcpy(); bytewise_custom_memcpy_chunked(); @@ -29,40 +28,6 @@ fn basic() { assert_eq!(unsafe { *ptr_back }, 42); } -/// Overwrite one byte of a pointer, then restore it. -fn partial_overwrite_then_restore() { - unsafe fn ptr_bytes<'x>(ptr: &'x mut *const i32) -> &'x mut [mem::MaybeUninit; PTR_SIZE] { - mem::transmute(ptr) - } - - // Returns a value with the same provenance as `x` but 0 for the integer value. - // `x` must be initialized. - unsafe fn zero_with_provenance(x: mem::MaybeUninit) -> mem::MaybeUninit { - let ptr = [x; PTR_SIZE]; - let ptr: *const i32 = mem::transmute(ptr); - let mut ptr = ptr.with_addr(0); - ptr_bytes(&mut ptr)[0] - } - - unsafe { - let ptr = &42; - let mut ptr = ptr as *const i32; - // Get a bytewise view of the pointer. - let ptr_bytes = ptr_bytes(&mut ptr); - - // The highest bytes must be 0 for this to work. - let hi = if cfg!(target_endian = "little") { ptr_bytes.len() - 1 } else { 0 }; - assert_eq!(*ptr_bytes[hi].as_ptr().cast::(), 0); - // Overwrite provenance on the last byte. - ptr_bytes[hi] = mem::MaybeUninit::new(0); - // Restore it from the another byte. - ptr_bytes[hi] = zero_with_provenance(ptr_bytes[1]); - - // Now ptr should be good again. - assert_eq!(*ptr, 42); - } -} - fn bytewise_ptr_methods() { let mut ptr1 = &1; let mut ptr2 = &2; diff --git a/src/tools/miri/tests/pass/transmute_ptr.rs b/src/tools/miri/tests/pass/transmute_ptr.rs index 0944781c6def..0a53b7782947 100644 --- a/src/tools/miri/tests/pass/transmute_ptr.rs +++ b/src/tools/miri/tests/pass/transmute_ptr.rs @@ -1,6 +1,6 @@ //@revisions: stack tree //@[tree]compile-flags: -Zmiri-tree-borrows -use std::{mem, ptr}; +use std::mem; fn t1() { // If we are careful, we can exploit data layout... @@ -27,27 +27,8 @@ fn ptr_integer_array() { let _x: [u8; PTR_SIZE] = unsafe { mem::transmute(&0) }; } -fn ptr_in_two_halves() { - unsafe { - let ptr = &0 as *const i32; - let arr = [ptr; 2]; - // We want to do a scalar read of a pointer at offset PTR_SIZE/2 into this array. But we - // cannot use a packed struct or `read_unaligned`, as those use the memcpy code path in - // Miri. So instead we shift the entire array by a bit and then the actual read we want to - // do is perfectly aligned. - let mut target_arr = [ptr::null::(); 3]; - let target = target_arr.as_mut_ptr().cast::(); - target.add(PTR_SIZE / 2).cast::<[*const i32; 2]>().write_unaligned(arr); - // Now target_arr[1] is a mix of the two `ptr` we had stored in `arr`. - let strange_ptr = target_arr[1]; - // Check that the provenance works out. - assert_eq!(*strange_ptr.with_addr(ptr.addr()), 0); - } -} - fn main() { t1(); t2(); ptr_integer_array(); - ptr_in_two_halves(); } diff --git a/tests/ui/consts/const-eval/heap/ptr_not_made_global.stderr b/tests/ui/consts/const-eval/heap/ptr_not_made_global.stderr index cb2bb1e8cd85..e5b108df2982 100644 --- a/tests/ui/consts/const-eval/heap/ptr_not_made_global.stderr +++ b/tests/ui/consts/const-eval/heap/ptr_not_made_global.stderr @@ -4,7 +4,7 @@ error: encountered `const_allocate` pointer in final value that was not made glo LL | const FOO: &i32 = foo(); | ^^^^^^^^^^^^^^^ | - = note: use `const_make_global` to make allocated pointers immutable before returning + = note: use `const_make_global` to turn allocated pointers into immutable globals before returning error: encountered `const_allocate` pointer in final value that was not made global --> $DIR/ptr_not_made_global.rs:12:1 @@ -12,7 +12,7 @@ error: encountered `const_allocate` pointer in final value that was not made glo LL | const FOO_RAW: *const i32 = foo(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: use `const_make_global` to make allocated pointers immutable before returning + = note: use `const_make_global` to turn allocated pointers into immutable globals before returning error: aborting due to 2 previous errors diff --git a/tests/ui/consts/const-eval/heap/ptr_not_made_global_mut.stderr b/tests/ui/consts/const-eval/heap/ptr_not_made_global_mut.stderr index 2445ce633d6f..2d1993f96d37 100644 --- a/tests/ui/consts/const-eval/heap/ptr_not_made_global_mut.stderr +++ b/tests/ui/consts/const-eval/heap/ptr_not_made_global_mut.stderr @@ -4,7 +4,7 @@ error: encountered `const_allocate` pointer in final value that was not made glo LL | const BAR: *mut i32 = unsafe { intrinsics::const_allocate(4, 4) as *mut i32 }; | ^^^^^^^^^^^^^^^^^^^ | - = note: use `const_make_global` to make allocated pointers immutable before returning + = note: use `const_make_global` to turn allocated pointers into immutable globals before returning error: aborting due to 1 previous error diff --git a/tests/ui/consts/const-eval/partial_ptr_overwrite.rs b/tests/ui/consts/const-eval/partial_ptr_overwrite.rs deleted file mode 100644 index bd97bec0f71a..000000000000 --- a/tests/ui/consts/const-eval/partial_ptr_overwrite.rs +++ /dev/null @@ -1,12 +0,0 @@ -// Test for the behavior described in . - -const PARTIAL_OVERWRITE: () = { - let mut p = &42; - unsafe { - let ptr: *mut _ = &mut p; - *(ptr as *mut u8) = 123; //~ ERROR unable to overwrite parts of a pointer - } - let x = *p; -}; - -fn main() {} diff --git a/tests/ui/consts/const-eval/partial_ptr_overwrite.stderr b/tests/ui/consts/const-eval/partial_ptr_overwrite.stderr deleted file mode 100644 index 6ef1cfd35c8c..000000000000 --- a/tests/ui/consts/const-eval/partial_ptr_overwrite.stderr +++ /dev/null @@ -1,12 +0,0 @@ -error[E0080]: unable to overwrite parts of a pointer in memory at ALLOC0 - --> $DIR/partial_ptr_overwrite.rs:7:9 - | -LL | *(ptr as *mut u8) = 123; - | ^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `PARTIAL_OVERWRITE` failed here - | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/const-eval/ptr_fragments.rs b/tests/ui/consts/const-eval/ptr_fragments.rs new file mode 100644 index 000000000000..04dcbe55590e --- /dev/null +++ b/tests/ui/consts/const-eval/ptr_fragments.rs @@ -0,0 +1,63 @@ +//! Test that various operations involving pointer fragments work as expected. +//@ run-pass + +use std::mem::{self, MaybeUninit, transmute}; +use std::ptr; + +type Byte = MaybeUninit; + +const unsafe fn memcpy(dst: *mut Byte, src: *const Byte, n: usize) { + let mut i = 0; + while i < n { + *dst.add(i) = *src.add(i); + i += 1; + } +} + +const _MEMCPY: () = unsafe { + let ptr = &42; + let mut ptr2 = ptr::null::(); + memcpy(&mut ptr2 as *mut _ as *mut _, &ptr as *const _ as *const _, mem::size_of::<&i32>()); + assert!(*ptr2 == 42); +}; +const _MEMCPY_OFFSET: () = unsafe { + // Same as above, but the pointer has a non-zero offset so not all the data bytes are the same. + let ptr = &(42, 18); + let ptr = &ptr.1; + let mut ptr2 = ptr::null::(); + memcpy(&mut ptr2 as *mut _ as *mut _, &ptr as *const _ as *const _, mem::size_of::<&i32>()); + assert!(*ptr2 == 18); +}; + +const MEMCPY_RET: MaybeUninit<*const i32> = unsafe { + let ptr = &42; + let mut ptr2 = MaybeUninit::new(ptr::null::()); + memcpy(&mut ptr2 as *mut _ as *mut _, &ptr as *const _ as *const _, mem::size_of::<&i32>()); + // Return in a MaybeUninit so it does not get treated as a scalar. + ptr2 +}; + +#[allow(dead_code)] +fn reassemble_ptr_fragments_in_static() { + static DATA: i32 = 1i32; + + #[cfg(target_pointer_width = "64")] + struct Thing { + x: MaybeUninit, + y: MaybeUninit, + } + #[cfg(target_pointer_width = "32")] + struct Thing { + x: MaybeUninit, + y: MaybeUninit, + } + + static X: Thing = unsafe { + let Thing { x, y } = transmute(&raw const DATA); + Thing { x, y } + }; +} + +fn main() { + assert_eq!(unsafe { MEMCPY_RET.assume_init().read() }, 42); +} diff --git a/tests/ui/consts/const-eval/ptr_fragments_in_final.rs b/tests/ui/consts/const-eval/ptr_fragments_in_final.rs new file mode 100644 index 000000000000..e2f3f51b0863 --- /dev/null +++ b/tests/ui/consts/const-eval/ptr_fragments_in_final.rs @@ -0,0 +1,25 @@ +//! Test that we properly error when there is a pointer fragment in the final value. + +use std::{mem::{self, MaybeUninit}, ptr}; + +type Byte = MaybeUninit; + +const unsafe fn memcpy(dst: *mut Byte, src: *const Byte, n: usize) { + let mut i = 0; + while i < n { + dst.add(i).write(src.add(i).read()); + i += 1; + } +} + +const MEMCPY_RET: MaybeUninit<*const i32> = unsafe { //~ERROR: partial pointer in final value + let ptr = &42; + let mut ptr2 = MaybeUninit::new(ptr::null::()); + memcpy(&mut ptr2 as *mut _ as *mut _, &ptr as *const _ as *const _, mem::size_of::<&i32>() / 2); + // Return in a MaybeUninit so it does not get treated as a scalar. + ptr2 +}; + +fn main() { + assert_eq!(unsafe { MEMCPY_RET.assume_init().read() }, 42); +} diff --git a/tests/ui/consts/const-eval/ptr_fragments_in_final.stderr b/tests/ui/consts/const-eval/ptr_fragments_in_final.stderr new file mode 100644 index 000000000000..628bf2566e59 --- /dev/null +++ b/tests/ui/consts/const-eval/ptr_fragments_in_final.stderr @@ -0,0 +1,10 @@ +error: encountered partial pointer in final value of constant + --> $DIR/ptr_fragments_in_final.rs:15:1 + | +LL | const MEMCPY_RET: MaybeUninit<*const i32> = unsafe { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: while pointers can be broken apart into individual bytes during const-evaluation, only complete pointers (with all their bytes in the right order) are supported in the final value + +error: aborting due to 1 previous error + diff --git a/tests/ui/consts/const-eval/read_partial_ptr.rs b/tests/ui/consts/const-eval/read_partial_ptr.rs new file mode 100644 index 000000000000..bccef9c0bc6c --- /dev/null +++ b/tests/ui/consts/const-eval/read_partial_ptr.rs @@ -0,0 +1,49 @@ +//! Ensure we error when trying to load from a pointer whose provenance has been messed with. + +const PARTIAL_OVERWRITE: () = { + let mut p = &42; + // Overwrite one byte with a no-provenance value. + unsafe { + let ptr: *mut _ = &mut p; + *(ptr as *mut u8) = 123; + } + let x = *p; //~ ERROR: unable to read parts of a pointer +}; + +const PTR_BYTES_SWAP: () = { + let mut p = &42; + // Swap the first two bytes. + unsafe { + let ptr = &mut p as *mut _ as *mut std::mem::MaybeUninit; + let byte0 = ptr.read(); + let byte1 = ptr.add(1).read(); + ptr.write(byte1); + ptr.add(1).write(byte0); + } + let x = *p; //~ ERROR: unable to read parts of a pointer +}; + +const PTR_BYTES_REPEAT: () = { + let mut p = &42; + // Duplicate the first byte over the second. + unsafe { + let ptr = &mut p as *mut _ as *mut std::mem::MaybeUninit; + let byte0 = ptr.read(); + ptr.add(1).write(byte0); + } + let x = *p; //~ ERROR: unable to read parts of a pointer +}; + +const PTR_BYTES_MIX: () = { + let mut p = &42; + let q = &43; + // Overwrite the first byte of p with the first byte of q. + unsafe { + let ptr = &mut p as *mut _ as *mut std::mem::MaybeUninit; + let qtr = &q as *const _ as *const std::mem::MaybeUninit; + ptr.write(qtr.read()); + } + let x = *p; //~ ERROR: unable to read parts of a pointer +}; + +fn main() {} diff --git a/tests/ui/consts/const-eval/read_partial_ptr.stderr b/tests/ui/consts/const-eval/read_partial_ptr.stderr new file mode 100644 index 000000000000..196606c77a37 --- /dev/null +++ b/tests/ui/consts/const-eval/read_partial_ptr.stderr @@ -0,0 +1,39 @@ +error[E0080]: unable to read parts of a pointer from memory at ALLOC0 + --> $DIR/read_partial_ptr.rs:10:13 + | +LL | let x = *p; + | ^^ evaluation of `PARTIAL_OVERWRITE` failed here + | + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported + +error[E0080]: unable to read parts of a pointer from memory at ALLOC1 + --> $DIR/read_partial_ptr.rs:23:13 + | +LL | let x = *p; + | ^^ evaluation of `PTR_BYTES_SWAP` failed here + | + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported + +error[E0080]: unable to read parts of a pointer from memory at ALLOC2 + --> $DIR/read_partial_ptr.rs:34:13 + | +LL | let x = *p; + | ^^ evaluation of `PTR_BYTES_REPEAT` failed here + | + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported + +error[E0080]: unable to read parts of a pointer from memory at ALLOC3 + --> $DIR/read_partial_ptr.rs:46:13 + | +LL | let x = *p; + | ^^ evaluation of `PTR_BYTES_MIX` failed here + | + = help: this code performed an operation that depends on the underlying bytes representing a pointer + = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/missing_span_in_backtrace.rs b/tests/ui/consts/missing_span_in_backtrace.rs index 4f3f9aa6adac..09a11c75fd7b 100644 --- a/tests/ui/consts/missing_span_in_backtrace.rs +++ b/tests/ui/consts/missing_span_in_backtrace.rs @@ -1,3 +1,4 @@ +//! Check what happens when the error occurs inside a std function that we can't print the span of. //@ ignore-backends: gcc //@ compile-flags: -Z ui-testing=no @@ -7,15 +8,15 @@ use std::{ }; const X: () = { - let mut ptr1 = &1; - let mut ptr2 = &2; + let mut x1 = 1; + let mut x2 = 2; // Swap them, bytewise. unsafe { - ptr::swap_nonoverlapping( //~ ERROR unable to copy parts of a pointer - &mut ptr1 as *mut _ as *mut MaybeUninit, - &mut ptr2 as *mut _ as *mut MaybeUninit, - mem::size_of::<&i32>(), + ptr::swap_nonoverlapping( //~ ERROR beyond the end of the allocation + &mut x1 as *mut _ as *mut MaybeUninit, + &mut x2 as *mut _ as *mut MaybeUninit, + 10, ); } }; diff --git a/tests/ui/consts/missing_span_in_backtrace.stderr b/tests/ui/consts/missing_span_in_backtrace.stderr index 0ac1e281107d..55dde6358286 100644 --- a/tests/ui/consts/missing_span_in_backtrace.stderr +++ b/tests/ui/consts/missing_span_in_backtrace.stderr @@ -1,15 +1,13 @@ -error[E0080]: unable to copy parts of a pointer from memory at ALLOC0 - --> $DIR/missing_span_in_backtrace.rs:15:9 +error[E0080]: memory access failed: attempting to access 1 byte, but got ALLOC0+0x4 which is at or beyond the end of the allocation of size 4 bytes + --> $DIR/missing_span_in_backtrace.rs:16:9 | -15 | / ptr::swap_nonoverlapping( -16 | | &mut ptr1 as *mut _ as *mut MaybeUninit, -17 | | &mut ptr2 as *mut _ as *mut MaybeUninit, -18 | | mem::size_of::<&i32>(), -19 | | ); +16 | / ptr::swap_nonoverlapping( +17 | | &mut x1 as *mut _ as *mut MaybeUninit, +18 | | &mut x2 as *mut _ as *mut MaybeUninit, +19 | | 10, +20 | | ); | |_________^ evaluation of `X` failed inside this call | - = help: this code performed an operation that depends on the underlying bytes representing a pointer - = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported note: inside `swap_nonoverlapping::compiletime::>` --> $SRC_DIR/core/src/ptr/mod.rs:LL:COL note: inside `std::ptr::swap_nonoverlapping_const::>` From 4220587c2232e237a0c39a2c64b0bf046799434a Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Tue, 29 Jul 2025 18:30:48 -0700 Subject: [PATCH 0206/1134] `AlignmentEnum` should just be `repr(usize)` now Since it's cfg'd instead of type-aliased --- library/core/src/ptr/alignment.rs | 8 +++++--- ...c_in_place.PreCodegen.after.32bit.panic-abort.mir | 12 ++++-------- ..._in_place.PreCodegen.after.32bit.panic-unwind.mir | 12 ++++-------- ...c_in_place.PreCodegen.after.64bit.panic-abort.mir | 12 ++++-------- ..._in_place.PreCodegen.after.64bit.panic-unwind.mir | 12 ++++-------- tests/mir-opt/pre-codegen/drop_boxed_slice.rs | 3 +-- 6 files changed, 22 insertions(+), 37 deletions(-) diff --git a/library/core/src/ptr/alignment.rs b/library/core/src/ptr/alignment.rs index bd5b4e21baa0..402634e49b37 100644 --- a/library/core/src/ptr/alignment.rs +++ b/library/core/src/ptr/alignment.rs @@ -1,3 +1,5 @@ +#![allow(clippy::enum_clike_unportable_variant)] + use crate::num::NonZero; use crate::ub_checks::assert_unsafe_precondition; use crate::{cmp, fmt, hash, mem, num}; @@ -241,7 +243,7 @@ impl const Default for Alignment { #[cfg(target_pointer_width = "16")] #[derive(Copy, Clone, PartialEq, Eq)] -#[repr(u16)] +#[repr(usize)] enum AlignmentEnum { _Align1Shl0 = 1 << 0, _Align1Shl1 = 1 << 1, @@ -263,7 +265,7 @@ enum AlignmentEnum { #[cfg(target_pointer_width = "32")] #[derive(Copy, Clone, PartialEq, Eq)] -#[repr(u32)] +#[repr(usize)] enum AlignmentEnum { _Align1Shl0 = 1 << 0, _Align1Shl1 = 1 << 1, @@ -301,7 +303,7 @@ enum AlignmentEnum { #[cfg(target_pointer_width = "64")] #[derive(Copy, Clone, PartialEq, Eq)] -#[repr(u64)] +#[repr(usize)] enum AlignmentEnum { _Align1Shl0 = 1 << 0, _Align1Shl1 = 1 << 1, diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir index 2777bba893bb..ba6ce0ee5286 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir @@ -8,7 +8,7 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { let _2: std::ptr::NonNull<[T]>; let mut _3: *mut [T]; let mut _4: *const [T]; - let _12: (); + let _11: (); scope 3 { let _8: std::ptr::alignment::AlignmentEnum; scope 4 { @@ -31,12 +31,11 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { scope 20 (inlined NonNull::::as_ptr) { } scope 21 (inlined std::alloc::dealloc) { - let mut _11: usize; + let mut _10: usize; scope 22 (inlined Layout::size) { } scope 23 (inlined Layout::align) { scope 24 (inlined std::ptr::Alignment::as_usize) { - let mut _10: u32; } } } @@ -87,16 +86,13 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { bb2: { StorageLive(_9); _9 = copy _3 as *mut u8 (PtrToPtr); - StorageLive(_11); StorageLive(_10); _10 = discriminant(_8); - _11 = move _10 as usize (IntToInt); - StorageDead(_10); - _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb3, unwind unreachable]; + _11 = alloc::alloc::__rust_dealloc(move _9, move _5, move _10) -> [return: bb3, unwind unreachable]; } bb3: { - StorageDead(_11); + StorageDead(_10); StorageDead(_9); goto -> bb4; } diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir index 2777bba893bb..ba6ce0ee5286 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir @@ -8,7 +8,7 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { let _2: std::ptr::NonNull<[T]>; let mut _3: *mut [T]; let mut _4: *const [T]; - let _12: (); + let _11: (); scope 3 { let _8: std::ptr::alignment::AlignmentEnum; scope 4 { @@ -31,12 +31,11 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { scope 20 (inlined NonNull::::as_ptr) { } scope 21 (inlined std::alloc::dealloc) { - let mut _11: usize; + let mut _10: usize; scope 22 (inlined Layout::size) { } scope 23 (inlined Layout::align) { scope 24 (inlined std::ptr::Alignment::as_usize) { - let mut _10: u32; } } } @@ -87,16 +86,13 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { bb2: { StorageLive(_9); _9 = copy _3 as *mut u8 (PtrToPtr); - StorageLive(_11); StorageLive(_10); _10 = discriminant(_8); - _11 = move _10 as usize (IntToInt); - StorageDead(_10); - _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb3, unwind unreachable]; + _11 = alloc::alloc::__rust_dealloc(move _9, move _5, move _10) -> [return: bb3, unwind unreachable]; } bb3: { - StorageDead(_11); + StorageDead(_10); StorageDead(_9); goto -> bb4; } diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir index 2be0a478c852..ba6ce0ee5286 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir @@ -8,7 +8,7 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { let _2: std::ptr::NonNull<[T]>; let mut _3: *mut [T]; let mut _4: *const [T]; - let _12: (); + let _11: (); scope 3 { let _8: std::ptr::alignment::AlignmentEnum; scope 4 { @@ -31,12 +31,11 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { scope 20 (inlined NonNull::::as_ptr) { } scope 21 (inlined std::alloc::dealloc) { - let mut _11: usize; + let mut _10: usize; scope 22 (inlined Layout::size) { } scope 23 (inlined Layout::align) { scope 24 (inlined std::ptr::Alignment::as_usize) { - let mut _10: u64; } } } @@ -87,16 +86,13 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { bb2: { StorageLive(_9); _9 = copy _3 as *mut u8 (PtrToPtr); - StorageLive(_11); StorageLive(_10); _10 = discriminant(_8); - _11 = move _10 as usize (IntToInt); - StorageDead(_10); - _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb3, unwind unreachable]; + _11 = alloc::alloc::__rust_dealloc(move _9, move _5, move _10) -> [return: bb3, unwind unreachable]; } bb3: { - StorageDead(_11); + StorageDead(_10); StorageDead(_9); goto -> bb4; } diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir index 2be0a478c852..ba6ce0ee5286 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir @@ -8,7 +8,7 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { let _2: std::ptr::NonNull<[T]>; let mut _3: *mut [T]; let mut _4: *const [T]; - let _12: (); + let _11: (); scope 3 { let _8: std::ptr::alignment::AlignmentEnum; scope 4 { @@ -31,12 +31,11 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { scope 20 (inlined NonNull::::as_ptr) { } scope 21 (inlined std::alloc::dealloc) { - let mut _11: usize; + let mut _10: usize; scope 22 (inlined Layout::size) { } scope 23 (inlined Layout::align) { scope 24 (inlined std::ptr::Alignment::as_usize) { - let mut _10: u64; } } } @@ -87,16 +86,13 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { bb2: { StorageLive(_9); _9 = copy _3 as *mut u8 (PtrToPtr); - StorageLive(_11); StorageLive(_10); _10 = discriminant(_8); - _11 = move _10 as usize (IntToInt); - StorageDead(_10); - _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb3, unwind unreachable]; + _11 = alloc::alloc::__rust_dealloc(move _9, move _5, move _10) -> [return: bb3, unwind unreachable]; } bb3: { - StorageDead(_11); + StorageDead(_10); StorageDead(_9); goto -> bb4; } diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.rs b/tests/mir-opt/pre-codegen/drop_boxed_slice.rs index 11fb7afef0fb..9ceba9444b8d 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.rs +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.rs @@ -13,7 +13,6 @@ pub unsafe fn generic_in_place(ptr: *mut Box<[T]>) { // CHECK: [[B:_.+]] = copy [[ALIGN]] as std::ptr::Alignment (Transmute); // CHECK: [[C:_.+]] = move ([[B]].0: std::ptr::alignment::AlignmentEnum); // CHECK: [[D:_.+]] = discriminant([[C]]); - // CHECK: [[E:_.+]] = move [[D]] as usize (IntToInt); - // CHECK: = alloc::alloc::__rust_dealloc({{.+}}, move [[SIZE]], move [[E]]) -> + // CHECK: = alloc::alloc::__rust_dealloc({{.+}}, move [[SIZE]], move [[D]]) -> std::ptr::drop_in_place(ptr) } From c57876242df63e33e2ccb268e386de1ee38c70dd Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Wed, 30 Jul 2025 09:44:31 +0200 Subject: [PATCH 0207/1134] Output lintcheck summary HTML markdown in order The data in the table needs to be in the same order as the headings. --- lintcheck/src/json.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lintcheck/src/json.rs b/lintcheck/src/json.rs index 808997ff0220..79c1255c5ffe 100644 --- a/lintcheck/src/json.rs +++ b/lintcheck/src/json.rs @@ -66,7 +66,7 @@ impl fmt::Display for Summary { } in &self.0 { let html_id = to_html_id(name); - writeln!(f, "| [`{name}`](#{html_id}) | {added} | {changed} | {removed} |")?; + writeln!(f, "| [`{name}`](#{html_id}) | {added} | {removed} | {changed} |")?; } Ok(()) From 64276e688c464c4d02a9be6357ca0157167ea075 Mon Sep 17 00:00:00 2001 From: houpo-bob Date: Wed, 30 Jul 2025 15:49:56 +0800 Subject: [PATCH 0208/1134] chore: fix some minor issues in comments Signed-off-by: houpo-bob --- clippy_lints/src/infallible_try_from.rs | 2 +- tests/ui/manual_strip.rs | 2 +- tests/ui/manual_unwrap_or_default.fixed | 2 +- tests/ui/manual_unwrap_or_default.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/infallible_try_from.rs b/clippy_lints/src/infallible_try_from.rs index f7cdf05359a3..fba11adcd627 100644 --- a/clippy_lints/src/infallible_try_from.rs +++ b/clippy_lints/src/infallible_try_from.rs @@ -13,7 +13,7 @@ declare_clippy_lint! { /// /// ### Why is this bad? /// - /// Infalliable conversions should be implemented via `From` with the blanket conversion. + /// Infallible conversions should be implemented via `From` with the blanket conversion. /// /// ### Example /// ```no_run diff --git a/tests/ui/manual_strip.rs b/tests/ui/manual_strip.rs index 086b75a39875..0fdaa1c045e0 100644 --- a/tests/ui/manual_strip.rs +++ b/tests/ui/manual_strip.rs @@ -75,7 +75,7 @@ fn main() { s4[2..].to_string(); } - // Don't propose to reuse the `stripped` identifier as it is overriden + // Don't propose to reuse the `stripped` identifier as it is overridden if s.starts_with("ab") { let stripped = &s["ab".len()..]; //~^ ERROR: stripping a prefix manually diff --git a/tests/ui/manual_unwrap_or_default.fixed b/tests/ui/manual_unwrap_or_default.fixed index 41ca44ceef4e..189fe876aa5d 100644 --- a/tests/ui/manual_unwrap_or_default.fixed +++ b/tests/ui/manual_unwrap_or_default.fixed @@ -102,7 +102,7 @@ fn issue_12928() { let y = if let Some(Y(a, ..)) = x { a } else { 0 }; } -// For symetry with `manual_unwrap_or` test +// For symmetry with `manual_unwrap_or` test fn allowed_manual_unwrap_or_zero() -> u32 { Some(42).unwrap_or_default() } diff --git a/tests/ui/manual_unwrap_or_default.rs b/tests/ui/manual_unwrap_or_default.rs index 343fbc4879ce..ca87926763c9 100644 --- a/tests/ui/manual_unwrap_or_default.rs +++ b/tests/ui/manual_unwrap_or_default.rs @@ -138,7 +138,7 @@ fn issue_12928() { let y = if let Some(Y(a, ..)) = x { a } else { 0 }; } -// For symetry with `manual_unwrap_or` test +// For symmetry with `manual_unwrap_or` test fn allowed_manual_unwrap_or_zero() -> u32 { if let Some(x) = Some(42) { //~^ manual_unwrap_or_default From ab8a2e1cb24517b43ba8b1e7bbdabe8ced0675b8 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 30 Jul 2025 08:26:59 +0000 Subject: [PATCH 0209/1134] ci: Switch to strongly typed directives Replace the current system with something that is more structured and will also catch unknown directives. --- library/compiler-builtins/ci/ci-util.py | 79 +++++++++++++++++-------- 1 file changed, 54 insertions(+), 25 deletions(-) diff --git a/library/compiler-builtins/ci/ci-util.py b/library/compiler-builtins/ci/ci-util.py index 3437d304f48c..1a9c83d23844 100755 --- a/library/compiler-builtins/ci/ci-util.py +++ b/library/compiler-builtins/ci/ci-util.py @@ -7,6 +7,7 @@ import json import os +import pprint import re import subprocess as sp import sys @@ -50,15 +51,6 @@ DEFAULT_BRANCH = "master" WORKFLOW_NAME = "CI" # Workflow that generates the benchmark artifacts ARTIFACT_PREFIX = "baseline-icount*" -# Place this in a PR body to skip regression checks (must be at the start of a line). -REGRESSION_DIRECTIVE = "ci: allow-regressions" -# Place this in a PR body to skip extensive tests -SKIP_EXTENSIVE_DIRECTIVE = "ci: skip-extensive" -# Place this in a PR body to allow running a large number of extensive tests. If not -# set, this script will error out if a threshold is exceeded in order to avoid -# accidentally spending huge amounts of CI time. -ALLOW_MANY_EXTENSIVE_DIRECTIVE = "ci: allow-many-extensive" -MANY_EXTENSIVE_THRESHOLD = 20 # Don't run exhaustive tests if these files change, even if they contaiin a function # definition. @@ -80,6 +72,48 @@ def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) +@dataclass(init=False) +class PrCfg: + """Directives that we allow in the commit body to control test behavior. + + These are of the form `ci: foo`, at the start of a line. + """ + + # Skip regression checks (must be at the start of a line). + allow_regressions: bool = False + # Don't run extensive tests + skip_extensive: bool = False + + # Allow running a large number of extensive tests. If not set, this script + # will error out if a threshold is exceeded in order to avoid accidentally + # spending huge amounts of CI time. + allow_many_extensive: bool = False + + # Max number of extensive tests to run by default + MANY_EXTENSIVE_THRESHOLD: int = 20 + + # String values of directive names + DIR_ALLOW_REGRESSIONS: str = "allow-regressions" + DIR_SKIP_EXTENSIVE: str = "skip-extensive" + DIR_ALLOW_MANY_EXTENSIVE: str = "allow-many-extensive" + + def __init__(self, body: str): + directives = re.finditer(r"^\s*ci:\s*(?P\S*)", body, re.MULTILINE) + for dir in directives: + name = dir.group("dir_name") + if name == self.DIR_ALLOW_REGRESSIONS: + self.allow_regressions = True + elif name == self.DIR_SKIP_EXTENSIVE: + self.skip_extensive = True + elif name == self.DIR_ALLOW_MANY_EXTENSIVE: + self.allow_many_extensive = True + else: + eprint(f"Found unexpected directive `{name}`") + exit(1) + + pprint.pp(self) + + @dataclass class PrInfo: """GitHub response for PR query""" @@ -88,6 +122,7 @@ class PrInfo: commits: list[str] created_at: str number: int + cfg: PrCfg @classmethod def load(cls, pr_number: int | str) -> Self: @@ -104,13 +139,9 @@ def load(cls, pr_number: int | str) -> Self: ], text=True, ) - eprint("PR info:", json.dumps(pr_info, indent=4)) - return cls(**json.loads(pr_info)) - - def contains_directive(self, directive: str) -> bool: - """Return true if the provided directive is on a line in the PR body""" - lines = self.body.splitlines() - return any(line.startswith(directive) for line in lines) + pr_json = json.loads(pr_info) + eprint("PR info:", json.dumps(pr_json, indent=4)) + return cls(**json.loads(pr_info), cfg=PrCfg(pr_json["body"])) class FunctionDef(TypedDict): @@ -223,10 +254,8 @@ def emit_workflow_output(self): if pr_number is not None and len(pr_number) > 0: pr = PrInfo.load(pr_number) - skip_tests = pr.contains_directive(SKIP_EXTENSIVE_DIRECTIVE) - error_on_many_tests = not pr.contains_directive( - ALLOW_MANY_EXTENSIVE_DIRECTIVE - ) + skip_tests = pr.cfg.skip_extensive + error_on_many_tests = not pr.cfg.allow_many_extensive if skip_tests: eprint("Skipping all extensive tests") @@ -257,12 +286,12 @@ def emit_workflow_output(self): eprint(f"may_skip_libm_ci={may_skip}") eprint(f"total extensive tests: {total_to_test}") - if error_on_many_tests and total_to_test > MANY_EXTENSIVE_THRESHOLD: + if error_on_many_tests and total_to_test > PrCfg.MANY_EXTENSIVE_THRESHOLD: eprint( - f"More than {MANY_EXTENSIVE_THRESHOLD} tests would be run; add" - f" `{ALLOW_MANY_EXTENSIVE_DIRECTIVE}` to the PR body if this is" + f"More than {PrCfg.MANY_EXTENSIVE_THRESHOLD} tests would be run; add" + f" `{PrCfg.DIR_ALLOW_MANY_EXTENSIVE}` to the PR body if this is" " intentional. If this is refactoring that happens to touch a lot of" - f" files, `{SKIP_EXTENSIVE_DIRECTIVE}` can be used instead." + f" files, `{PrCfg.DIR_SKIP_EXTENSIVE}` can be used instead." ) exit(1) @@ -372,7 +401,7 @@ def handle_bench_regressions(args: list[str]): exit(1) pr = PrInfo.load(pr_number) - if pr.contains_directive(REGRESSION_DIRECTIVE): + if pr.cfg.allow_regressions: eprint("PR allows regressions") return From eafafc44ab1c1279a4b0b5c4ee341d645628a5da Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 30 Jul 2025 08:30:47 +0000 Subject: [PATCH 0210/1134] ci: Don't print output twice in `ci-util` Use `tee` rather than printing to both stdout and stderr. --- library/compiler-builtins/.github/workflows/main.yaml | 2 +- library/compiler-builtins/ci/ci-util.py | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/library/compiler-builtins/.github/workflows/main.yaml b/library/compiler-builtins/.github/workflows/main.yaml index 94b519e3c2d3..939bc34c264e 100644 --- a/library/compiler-builtins/.github/workflows/main.yaml +++ b/library/compiler-builtins/.github/workflows/main.yaml @@ -34,7 +34,7 @@ jobs: - name: Fetch pull request ref run: git fetch origin "$GITHUB_REF:$GITHUB_REF" if: github.event_name == 'pull_request' - - run: python3 ci/ci-util.py generate-matrix >> "$GITHUB_OUTPUT" + - run: set -e; python3 ci/ci-util.py generate-matrix | tee "$GITHUB_OUTPUT" id: script test: diff --git a/library/compiler-builtins/ci/ci-util.py b/library/compiler-builtins/ci/ci-util.py index 1a9c83d23844..8f74ecfdb8a5 100755 --- a/library/compiler-builtins/ci/ci-util.py +++ b/library/compiler-builtins/ci/ci-util.py @@ -282,8 +282,6 @@ def emit_workflow_output(self): may_skip = str(self.may_skip_libm_ci()).lower() print(f"extensive_matrix={ext_matrix}") print(f"may_skip_libm_ci={may_skip}") - eprint(f"extensive_matrix={ext_matrix}") - eprint(f"may_skip_libm_ci={may_skip}") eprint(f"total extensive tests: {total_to_test}") if error_on_many_tests and total_to_test > PrCfg.MANY_EXTENSIVE_THRESHOLD: From c045c9b1ca4def434584dfb43cc83bd2eac059de Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 30 Jul 2025 08:32:28 +0000 Subject: [PATCH 0211/1134] ci: Commonize the way `PrInfo` is loaded from env --- library/compiler-builtins/ci/ci-util.py | 32 +++++++++++++++++-------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/library/compiler-builtins/ci/ci-util.py b/library/compiler-builtins/ci/ci-util.py index 8f74ecfdb8a5..f43409c5e20d 100755 --- a/library/compiler-builtins/ci/ci-util.py +++ b/library/compiler-builtins/ci/ci-util.py @@ -12,6 +12,7 @@ import subprocess as sp import sys from dataclasses import dataclass +from functools import cache from glob import glob from inspect import cleandoc from os import getenv @@ -62,7 +63,7 @@ # libm PR CI takes a long time and doesn't need to run unless relevant files have been # changed. Anything matching this regex pattern will trigger a run. -TRIGGER_LIBM_PR_CI = ".*(libm|musl).*" +TRIGGER_LIBM_CI_FILE_PAT = ".*(libm|musl).*" TYPES = ["f16", "f32", "f64", "f128"] @@ -125,8 +126,18 @@ class PrInfo: cfg: PrCfg @classmethod - def load(cls, pr_number: int | str) -> Self: - """For a given PR number, query the body and commit list""" + def from_env(cls) -> Self | None: + """Create a PR object from the PR_NUMBER environment if set, `None` otherwise.""" + pr_env = os.environ.get("PR_NUMBER") + if pr_env is not None and len(pr_env) > 0: + return cls.from_pr(pr_env) + + return None + + @classmethod + @cache # Cache so we don't print info messages multiple times + def from_pr(cls, pr_number: int | str) -> Self: + """For a given PR number, query the body and commit list.""" pr_info = sp.check_output( [ "gh", @@ -238,22 +249,23 @@ def may_skip_libm_ci(self) -> bool: """If this is a PR and no libm files were changed, allow skipping libm jobs.""" - if self.is_pr(): - return all(not re.match(TRIGGER_LIBM_PR_CI, str(f)) for f in self.changed) + # Always run on merge CI + if not self.is_pr(): + return False - return False + # By default, run if there are any changed files matching the pattern + return all(not re.match(TRIGGER_LIBM_CI_FILE_PAT, str(f)) for f in self.changed) def emit_workflow_output(self): """Create a JSON object a list items for each type's changed files, if any did change, and the routines that were affected by the change. """ - pr_number = os.environ.get("PR_NUMBER") skip_tests = False error_on_many_tests = False - if pr_number is not None and len(pr_number) > 0: - pr = PrInfo.load(pr_number) + pr = PrInfo.from_env() + if pr is not None: skip_tests = pr.cfg.skip_extensive error_on_many_tests = not pr.cfg.allow_many_extensive @@ -398,7 +410,7 @@ def handle_bench_regressions(args: list[str]): eprint(USAGE) exit(1) - pr = PrInfo.load(pr_number) + pr = PrInfo.from_pr(pr_number) if pr.cfg.allow_regressions: eprint("PR allows regressions") return From 4ebfdf74dbd29acc442cd91ab43483260e9ce668 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 30 Jul 2025 08:33:37 +0000 Subject: [PATCH 0212/1134] ci: Add a way to run `libm` tests that would otherwise be skipped Introduce a new directive `ci: test-libm` to ensure tests run. --- library/compiler-builtins/ci/ci-util.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/library/compiler-builtins/ci/ci-util.py b/library/compiler-builtins/ci/ci-util.py index f43409c5e20d..c1db17c6c901 100755 --- a/library/compiler-builtins/ci/ci-util.py +++ b/library/compiler-builtins/ci/ci-util.py @@ -93,10 +93,14 @@ class PrCfg: # Max number of extensive tests to run by default MANY_EXTENSIVE_THRESHOLD: int = 20 + # Run tests for `libm` that may otherwise be skipped due to no changed files. + always_test_libm: bool = False + # String values of directive names DIR_ALLOW_REGRESSIONS: str = "allow-regressions" DIR_SKIP_EXTENSIVE: str = "skip-extensive" DIR_ALLOW_MANY_EXTENSIVE: str = "allow-many-extensive" + DIR_TEST_LIBM: str = "test-libm" def __init__(self, body: str): directives = re.finditer(r"^\s*ci:\s*(?P\S*)", body, re.MULTILINE) @@ -108,6 +112,8 @@ def __init__(self, body: str): self.skip_extensive = True elif name == self.DIR_ALLOW_MANY_EXTENSIVE: self.allow_many_extensive = True + elif name == self.DIR_TEST_LIBM: + self.always_test_libm = True else: eprint(f"Found unexpected directive `{name}`") exit(1) @@ -253,6 +259,13 @@ def may_skip_libm_ci(self) -> bool: if not self.is_pr(): return False + pr = PrInfo.from_env() + assert pr is not None, "Is a PR but couldn't load PrInfo" + + # Allow opting in to libm tests + if pr.cfg.always_test_libm: + return False + # By default, run if there are any changed files matching the pattern return all(not re.match(TRIGGER_LIBM_CI_FILE_PAT, str(f)) for f in self.changed) From ec40ee4c4eb6b105e67b7fb6a7a488d89a64fafb Mon Sep 17 00:00:00 2001 From: tiif Date: Wed, 30 Jul 2025 09:30:10 +0000 Subject: [PATCH 0213/1134] Add documentation for unstable_feature_bound --- src/doc/rustc-dev-guide/src/stability.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/doc/rustc-dev-guide/src/stability.md b/src/doc/rustc-dev-guide/src/stability.md index 230925252bac..7a5efdb8ad72 100644 --- a/src/doc/rustc-dev-guide/src/stability.md +++ b/src/doc/rustc-dev-guide/src/stability.md @@ -183,4 +183,7 @@ the `deprecated_in_future` lint is triggered which is default `allow`, but most of the standard library raises it to a warning with `#![warn(deprecated_in_future)]`. +## unstable_feature_bound +The `#[unstable_feature_bound(foo)]` attribute can be used together with `#[unstable]` attribute to mark an `impl` of stable type and stable trait as unstable. In std/core , an item annotated with `#[unstable_feature_bound(foo)]` can only be used by another item that is also annotated with `#[unstable_feature_bound(foo)]`. Outside of std/core, using an item with `#[unstable_feature_bound(foo)]` requires the feature to be enabled with `#![feature(foo)]` attribute on the crate. Currently, only `impl`s and free functions can be annotated with `#[unstable_feature_bound]`. + [blog]: https://www.ralfj.de/blog/2018/07/19/const.html From 712c28e8324fc507c986f982755b8bfde919b5dc Mon Sep 17 00:00:00 2001 From: tiif Date: Wed, 30 Jul 2025 11:54:32 +0200 Subject: [PATCH 0214/1134] Remove space Co-authored-by: Tshepang Mbambo --- src/doc/rustc-dev-guide/src/stability.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/src/stability.md b/src/doc/rustc-dev-guide/src/stability.md index 7a5efdb8ad72..e8589b7f4310 100644 --- a/src/doc/rustc-dev-guide/src/stability.md +++ b/src/doc/rustc-dev-guide/src/stability.md @@ -184,6 +184,6 @@ of the standard library raises it to a warning with `#![warn(deprecated_in_future)]`. ## unstable_feature_bound -The `#[unstable_feature_bound(foo)]` attribute can be used together with `#[unstable]` attribute to mark an `impl` of stable type and stable trait as unstable. In std/core , an item annotated with `#[unstable_feature_bound(foo)]` can only be used by another item that is also annotated with `#[unstable_feature_bound(foo)]`. Outside of std/core, using an item with `#[unstable_feature_bound(foo)]` requires the feature to be enabled with `#![feature(foo)]` attribute on the crate. Currently, only `impl`s and free functions can be annotated with `#[unstable_feature_bound]`. +The `#[unstable_feature_bound(foo)]` attribute can be used together with `#[unstable]` attribute to mark an `impl` of stable type and stable trait as unstable. In std/core, an item annotated with `#[unstable_feature_bound(foo)]` can only be used by another item that is also annotated with `#[unstable_feature_bound(foo)]`. Outside of std/core, using an item with `#[unstable_feature_bound(foo)]` requires the feature to be enabled with `#![feature(foo)]` attribute on the crate. Currently, only `impl`s and free functions can be annotated with `#[unstable_feature_bound]`. [blog]: https://www.ralfj.de/blog/2018/07/19/const.html From 02ac116e53f525a929d251bf9dc4f2ea1cacd3c8 Mon Sep 17 00:00:00 2001 From: Eduard Stefes Date: Tue, 29 Jul 2025 11:27:07 +0200 Subject: [PATCH 0215/1134] Fix tests for big-endian The tests fail on s390x and presumably other big-endian systems, due to print of raw values and padding bytes. To fix the tests remove the raw output values in the error note with `normalize-stderr`. --- tests/ui/consts/const-eval/union-const-eval-field.rs | 1 + tests/ui/consts/const-eval/union-const-eval-field.stderr | 8 ++++---- tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs | 1 + tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr | 8 ++++---- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/ui/consts/const-eval/union-const-eval-field.rs b/tests/ui/consts/const-eval/union-const-eval-field.rs index 719e59b007c0..2c9061a7a50f 100644 --- a/tests/ui/consts/const-eval/union-const-eval-field.rs +++ b/tests/ui/consts/const-eval/union-const-eval-field.rs @@ -1,5 +1,6 @@ //@ dont-require-annotations: NOTE //@ normalize-stderr: "(the raw bytes of the constant) \(size: [0-9]*, align: [0-9]*\)" -> "$1 (size: $$SIZE, align: $$ALIGN)" +//@ normalize-stderr: "([[:xdigit:]]{2}\s){4}(__\s){4}\s+│\s+([?|\.]){4}\W{4}" -> "HEX_DUMP" type Field1 = i32; type Field2 = f32; diff --git a/tests/ui/consts/const-eval/union-const-eval-field.stderr b/tests/ui/consts/const-eval/union-const-eval-field.stderr index 1843ce273ac0..3b7e5508d56c 100644 --- a/tests/ui/consts/const-eval/union-const-eval-field.stderr +++ b/tests/ui/consts/const-eval/union-const-eval-field.stderr @@ -1,21 +1,21 @@ error[E0080]: reading memory at ALLOC0[0x0..0x8], but memory is uninitialized at [0x4..0x8], and this operation requires initialized memory - --> $DIR/union-const-eval-field.rs:29:37 + --> $DIR/union-const-eval-field.rs:30:37 | LL | const FIELD3: Field3 = unsafe { UNION.field3 }; | ^^^^^^^^^^^^ evaluation of `read_field3::FIELD3` failed here | = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { - 00 00 80 3f __ __ __ __ │ ...?░░░░ + HEX_DUMP } note: erroneous constant encountered - --> $DIR/union-const-eval-field.rs:31:5 + --> $DIR/union-const-eval-field.rs:32:5 | LL | FIELD3 | ^^^^^^ note: erroneous constant encountered - --> $DIR/union-const-eval-field.rs:31:5 + --> $DIR/union-const-eval-field.rs:32:5 | LL | FIELD3 | ^^^^^^ diff --git a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs index 15f4a9a778ed..ed15f5bba962 100644 --- a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs +++ b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs @@ -1,3 +1,4 @@ +//@ normalize-stderr: "[[:xdigit:]]{2} __ ([[:xdigit:]]{2}\s){2}" -> "HEX_DUMP" #![feature(core_intrinsics)] const RAW_EQ_PADDING: bool = unsafe { diff --git a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr index 5f4ef14d5869..329da35297e1 100644 --- a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr +++ b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr @@ -1,15 +1,15 @@ error[E0080]: reading memory at ALLOC0[0x0..0x4], but memory is uninitialized at [0x1..0x2], and this operation requires initialized memory - --> $DIR/intrinsic-raw_eq-const-bad.rs:4:5 + --> $DIR/intrinsic-raw_eq-const-bad.rs:5:5 | LL | std::intrinsics::raw_eq(&(1_u8, 2_u16), &(1_u8, 2_u16)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `RAW_EQ_PADDING` failed here | = note: the raw bytes of the constant (size: 4, align: 2) { - 01 __ 02 00 │ .░.. + HEX_DUMP │ .░.. } error[E0080]: unable to turn pointer into integer - --> $DIR/intrinsic-raw_eq-const-bad.rs:9:5 + --> $DIR/intrinsic-raw_eq-const-bad.rs:10:5 | LL | std::intrinsics::raw_eq(&(&0), &(&1)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `RAW_EQ_PTR` failed here @@ -18,7 +18,7 @@ LL | std::intrinsics::raw_eq(&(&0), &(&1)) = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: accessing memory with alignment 1, but alignment 4 is required - --> $DIR/intrinsic-raw_eq-const-bad.rs:16:5 + --> $DIR/intrinsic-raw_eq-const-bad.rs:17:5 | LL | std::intrinsics::raw_eq(aref, aref) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `RAW_EQ_NOT_ALIGNED` failed here From 4f8d4ca1908e6179c4094d5843db6a29cb323d4d Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 30 Jul 2025 16:27:33 +0800 Subject: [PATCH 0216/1134] Update `codegen_{cranelift,gcc}` and `opt-dist` to use `build.compiletest-allow-stage0` --- build_system/src/test.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/build_system/src/test.rs b/build_system/src/test.rs index bc0fdd40b6e8..2c8271c36a94 100644 --- a/build_system/src/test.rs +++ b/build_system/src/test.rs @@ -561,8 +561,6 @@ fn asm_tests(env: &Env, args: &TestArg) -> Result<(), String> { // FIXME: create a function "display_if_not_quiet" or something along the line. println!("[TEST] rustc asm test suite"); - env.insert("COMPILETEST_FORCE_STAGE0".to_string(), "1".to_string()); - let codegen_backend_path = format!( "{pwd}/target/{channel}/librustc_codegen_gcc.{dylib_ext}", pwd = std::env::current_dir() @@ -588,6 +586,8 @@ fn asm_tests(env: &Env, args: &TestArg) -> Result<(), String> { &"always", &"--stage", &"0", + &"--set", + &"build.compiletest-allow-stage0=true", &"tests/assembly-llvm/asm", &"--compiletest-rustc-args", &rustc_args, @@ -1047,7 +1047,6 @@ where // FIXME: create a function "display_if_not_quiet" or something along the line. println!("[TEST] rustc {test_type} test suite"); - env.insert("COMPILETEST_FORCE_STAGE0".to_string(), "1".to_string()); let extra = if args.is_using_gcc_master_branch() { "" } else { " -Csymbol-mangling-version=v0" }; @@ -1070,6 +1069,8 @@ where &"always", &"--stage", &"0", + &"--set", + &"build.compiletest-allow-stage0=true", &format!("tests/{test_type}"), &"--compiletest-rustc-args", &rustc_args, From 9fb99109b66626b51343ba6adee61274b0a67a50 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 30 Jul 2025 15:45:20 +0200 Subject: [PATCH 0217/1134] Regenerate intrinsics mapping --- src/intrinsic/archs.rs | 60 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/src/intrinsic/archs.rs b/src/intrinsic/archs.rs index 915ed875e32f..d1b2a93243d2 100644 --- a/src/intrinsic/archs.rs +++ b/src/intrinsic/archs.rs @@ -95,8 +95,11 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "cubema" => "__builtin_amdgcn_cubema", "cubesc" => "__builtin_amdgcn_cubesc", "cubetc" => "__builtin_amdgcn_cubetc", + "cvt.f16.bf8" => "__builtin_amdgcn_cvt_f16_bf8", + "cvt.f16.fp8" => "__builtin_amdgcn_cvt_f16_fp8", "cvt.f32.bf8" => "__builtin_amdgcn_cvt_f32_bf8", "cvt.f32.fp8" => "__builtin_amdgcn_cvt_f32_fp8", + "cvt.f32.fp8.e5m3" => "__builtin_amdgcn_cvt_f32_fp8_e5m3", "cvt.off.f32.i4" => "__builtin_amdgcn_cvt_off_f32_i4", "cvt.pk.bf8.f32" => "__builtin_amdgcn_cvt_pk_bf8_f32", "cvt.pk.f16.bf8" => "__builtin_amdgcn_cvt_pk_f16_bf8", @@ -181,6 +184,12 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "dot4.f32.fp8.bf8" => "__builtin_amdgcn_dot4_f32_fp8_bf8", "dot4.f32.fp8.fp8" => "__builtin_amdgcn_dot4_f32_fp8_fp8", "ds.add.gs.reg.rtn" => "__builtin_amdgcn_ds_add_gs_reg_rtn", + "ds.atomic.async.barrier.arrive.b64" => { + "__builtin_amdgcn_ds_atomic_async_barrier_arrive_b64" + } + "ds.atomic.barrier.arrive.rtn.b64" => { + "__builtin_amdgcn_ds_atomic_barrier_arrive_rtn_b64" + } "ds.bpermute" => "__builtin_amdgcn_ds_bpermute", "ds.bpermute.fi.b32" => "__builtin_amdgcn_ds_bpermute_fi_b32", "ds.gws.barrier" => "__builtin_amdgcn_ds_gws_barrier", @@ -198,8 +207,32 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "fdot2.f16.f16" => "__builtin_amdgcn_fdot2_f16_f16", "fdot2.f32.bf16" => "__builtin_amdgcn_fdot2_f32_bf16", "fdot2c.f32.bf16" => "__builtin_amdgcn_fdot2c_f32_bf16", + "flat.prefetch" => "__builtin_amdgcn_flat_prefetch", "fmul.legacy" => "__builtin_amdgcn_fmul_legacy", + "global.load.async.to.lds.b128" => { + "__builtin_amdgcn_global_load_async_to_lds_b128" + } + "global.load.async.to.lds.b32" => { + "__builtin_amdgcn_global_load_async_to_lds_b32" + } + "global.load.async.to.lds.b64" => { + "__builtin_amdgcn_global_load_async_to_lds_b64" + } + "global.load.async.to.lds.b8" => "__builtin_amdgcn_global_load_async_to_lds_b8", "global.load.lds" => "__builtin_amdgcn_global_load_lds", + "global.prefetch" => "__builtin_amdgcn_global_prefetch", + "global.store.async.from.lds.b128" => { + "__builtin_amdgcn_global_store_async_from_lds_b128" + } + "global.store.async.from.lds.b32" => { + "__builtin_amdgcn_global_store_async_from_lds_b32" + } + "global.store.async.from.lds.b64" => { + "__builtin_amdgcn_global_store_async_from_lds_b64" + } + "global.store.async.from.lds.b8" => { + "__builtin_amdgcn_global_store_async_from_lds_b8" + } "groupstaticsize" => "__builtin_amdgcn_groupstaticsize", "iglp.opt" => "__builtin_amdgcn_iglp_opt", "implicit.buffer.ptr" => "__builtin_amdgcn_implicit_buffer_ptr", @@ -291,6 +324,7 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "s.incperflevel" => "__builtin_amdgcn_s_incperflevel", "s.memrealtime" => "__builtin_amdgcn_s_memrealtime", "s.memtime" => "__builtin_amdgcn_s_memtime", + "s.monitor.sleep" => "__builtin_amdgcn_s_monitor_sleep", "s.sendmsg" => "__builtin_amdgcn_s_sendmsg", "s.sendmsghalt" => "__builtin_amdgcn_s_sendmsghalt", "s.setprio" => "__builtin_amdgcn_s_setprio", @@ -300,11 +334,15 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "s.sleep.var" => "__builtin_amdgcn_s_sleep_var", "s.ttracedata" => "__builtin_amdgcn_s_ttracedata", "s.ttracedata.imm" => "__builtin_amdgcn_s_ttracedata_imm", + "s.wait.asynccnt" => "__builtin_amdgcn_s_wait_asynccnt", "s.wait.event.export.ready" => "__builtin_amdgcn_s_wait_event_export_ready", + "s.wait.tensorcnt" => "__builtin_amdgcn_s_wait_tensorcnt", "s.waitcnt" => "__builtin_amdgcn_s_waitcnt", "sad.hi.u8" => "__builtin_amdgcn_sad_hi_u8", "sad.u16" => "__builtin_amdgcn_sad_u16", "sad.u8" => "__builtin_amdgcn_sad_u8", + "sat.pk4.i4.i8" => "__builtin_amdgcn_sat_pk4_i4_i8", + "sat.pk4.u4.u8" => "__builtin_amdgcn_sat_pk4_u4_u8", "sched.barrier" => "__builtin_amdgcn_sched_barrier", "sched.group.barrier" => "__builtin_amdgcn_sched_group_barrier", "sdot2" => "__builtin_amdgcn_sdot2", @@ -346,8 +384,13 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { "smfmac.i32.16x16x64.i8" => "__builtin_amdgcn_smfmac_i32_16x16x64_i8", "smfmac.i32.32x32x32.i8" => "__builtin_amdgcn_smfmac_i32_32x32x32_i8", "smfmac.i32.32x32x64.i8" => "__builtin_amdgcn_smfmac_i32_32x32x64_i8", + "struct.ptr.buffer.load.lds" => "__builtin_amdgcn_struct_ptr_buffer_load_lds", "sudot4" => "__builtin_amdgcn_sudot4", "sudot8" => "__builtin_amdgcn_sudot8", + "tensor.load.to.lds" => "__builtin_amdgcn_tensor_load_to_lds", + "tensor.load.to.lds.d2" => "__builtin_amdgcn_tensor_load_to_lds_d2", + "tensor.store.from.lds" => "__builtin_amdgcn_tensor_store_from_lds", + "tensor.store.from.lds.d2" => "__builtin_amdgcn_tensor_store_from_lds_d2", "udot2" => "__builtin_amdgcn_udot2", "udot4" => "__builtin_amdgcn_udot4", "udot8" => "__builtin_amdgcn_udot8", @@ -6326,6 +6369,23 @@ fn map_arch_intrinsic(full_name: &str) -> &'static str { } s390(name, full_name) } + "spv" => { + #[allow(non_snake_case)] + fn spv(name: &str, full_name: &str) -> &'static str { + match name { + // spv + "num.subgroups" => "__builtin_spirv_num_subgroups", + "subgroup.id" => "__builtin_spirv_subgroup_id", + "subgroup.local.invocation.id" => { + "__builtin_spirv_subgroup_local_invocation_id" + } + "subgroup.max.size" => "__builtin_spirv_subgroup_max_size", + "subgroup.size" => "__builtin_spirv_subgroup_size", + _ => unimplemented!("***** unsupported LLVM intrinsic {full_name}"), + } + } + spv(name, full_name) + } "ve" => { #[allow(non_snake_case)] fn ve(name: &str, full_name: &str) -> &'static str { From 2918a2b5505299e0d4164a776c0bdc745bb69736 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 30 Jul 2025 15:31:18 +0200 Subject: [PATCH 0218/1134] Abtract away json protocol for proc-macro-srv --- src/tools/rust-analyzer/Cargo.lock | 32 ++++ .../crates/load-cargo/src/lib.rs | 2 +- .../proc-macro-api/src/legacy_protocol.rs | 172 ++++++++++++++++++ .../proc-macro-api/src/legacy_protocol/msg.rs | 25 +-- .../src/legacy_protocol/msg/flat.rs | 105 ++++++----- .../crates/proc-macro-api/src/lib.rs | 93 +++------- .../crates/proc-macro-api/src/process.rs | 113 +++++------- .../crates/proc-macro-srv-cli/Cargo.toml | 1 + .../crates/proc-macro-srv-cli/src/main.rs | 39 +++- .../proc-macro-srv-cli/src/main_loop.rs | 63 +++++-- .../crates/proc-macro-srv/src/lib.rs | 8 +- .../src/server_impl/token_id.rs | 53 +++--- .../crates/proc-macro-srv/src/tests/utils.rs | 14 +- .../rust-analyzer/crates/span/src/lib.rs | 12 -- 14 files changed, 472 insertions(+), 260 deletions(-) create mode 100644 src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol.rs diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index c19e8471647f..0cbbb5dd6de7 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -23,6 +23,12 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "anstyle" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" + [[package]] name = "anyhow" version = "1.0.98" @@ -287,6 +293,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "clap" +version = "4.5.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed87a9d530bb41a67537289bafcac159cb3ee28460e0a4571123d2a778a6a882" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.5.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f4f3f3c77c94aff3c7e9aac9a2ca1974a5adf392a8bb751e827d6d127ab966" +dependencies = [ + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" + [[package]] name = "countme" version = "3.0.1" @@ -1615,6 +1646,7 @@ dependencies = [ name = "proc-macro-srv-cli" version = "0.0.0" dependencies = [ + "clap", "proc-macro-api", "proc-macro-srv", "tt", diff --git a/src/tools/rust-analyzer/crates/load-cargo/src/lib.rs b/src/tools/rust-analyzer/crates/load-cargo/src/lib.rs index 26ee698af081..98f415a522cb 100644 --- a/src/tools/rust-analyzer/crates/load-cargo/src/lib.rs +++ b/src/tools/rust-analyzer/crates/load-cargo/src/lib.rs @@ -533,7 +533,7 @@ impl ProcMacroExpander for Expander { current_dir, ) { Ok(Ok(subtree)) => Ok(subtree), - Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err.0)), + Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err)), Err(err) => Err(ProcMacroExpansionError::System(err.to_string())), } } diff --git a/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol.rs b/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol.rs new file mode 100644 index 000000000000..ee96b899fe57 --- /dev/null +++ b/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol.rs @@ -0,0 +1,172 @@ +//! The initial proc-macro-srv protocol, soon to be deprecated. + +pub mod json; +pub mod msg; + +use std::{ + io::{BufRead, Write}, + sync::Arc, +}; + +use paths::AbsPath; +use span::Span; + +use crate::{ + ProcMacro, ProcMacroKind, ServerError, + legacy_protocol::{ + json::{read_json, write_json}, + msg::{ + ExpandMacro, ExpandMacroData, ExpnGlobals, FlatTree, Message, Request, Response, + ServerConfig, SpanDataIndexMap, deserialize_span_data_index_map, + flat::serialize_span_data_index_map, + }, + }, + process::ProcMacroServerProcess, + version, +}; + +pub(crate) use crate::legacy_protocol::msg::SpanMode; + +/// Legacy span type, only defined here as it is still used by the proc-macro server. +/// While rust-analyzer doesn't use this anymore at all, RustRover relies on the legacy type for +/// proc-macro expansion. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct SpanId(pub u32); + +impl std::fmt::Debug for SpanId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +pub(crate) fn version_check(srv: &ProcMacroServerProcess) -> Result { + let request = Request::ApiVersionCheck {}; + let response = send_task(srv, request)?; + + match response { + Response::ApiVersionCheck(version) => Ok(version), + _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), + } +} + +/// Enable support for rust-analyzer span mode if the server supports it. +pub(crate) fn enable_rust_analyzer_spans( + srv: &ProcMacroServerProcess, +) -> Result { + let request = Request::SetConfig(ServerConfig { span_mode: SpanMode::RustAnalyzer }); + let response = send_task(srv, request)?; + + match response { + Response::SetConfig(ServerConfig { span_mode }) => Ok(span_mode), + _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), + } +} + +/// Finds proc-macros in a given dynamic library. +pub(crate) fn find_proc_macros( + srv: &ProcMacroServerProcess, + dylib_path: &AbsPath, +) -> Result, String>, ServerError> { + let request = Request::ListMacros { dylib_path: dylib_path.to_path_buf().into() }; + + let response = send_task(srv, request)?; + + match response { + Response::ListMacros(it) => Ok(it), + _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), + } +} + +pub(crate) fn expand( + proc_macro: &ProcMacro, + subtree: tt::SubtreeView<'_, Span>, + attr: Option>, + env: Vec<(String, String)>, + def_site: Span, + call_site: Span, + mixed_site: Span, + current_dir: String, +) -> Result>, String>, crate::ServerError> +{ + let version = proc_macro.process.version(); + let mut span_data_table = SpanDataIndexMap::default(); + let def_site = span_data_table.insert_full(def_site).0; + let call_site = span_data_table.insert_full(call_site).0; + let mixed_site = span_data_table.insert_full(mixed_site).0; + let task = ExpandMacro { + data: ExpandMacroData { + macro_body: FlatTree::new(subtree, version, &mut span_data_table), + macro_name: proc_macro.name.to_string(), + attributes: attr.map(|subtree| FlatTree::new(subtree, version, &mut span_data_table)), + has_global_spans: ExpnGlobals { + serialize: version >= version::HAS_GLOBAL_SPANS, + def_site, + call_site, + mixed_site, + }, + span_data_table: if proc_macro.process.rust_analyzer_spans() { + serialize_span_data_index_map(&span_data_table) + } else { + Vec::new() + }, + }, + lib: proc_macro.dylib_path.to_path_buf().into(), + env, + current_dir: Some(current_dir), + }; + + let response = send_task(&proc_macro.process, Request::ExpandMacro(Box::new(task)))?; + + match response { + Response::ExpandMacro(it) => Ok(it + .map(|tree| { + let mut expanded = FlatTree::to_subtree_resolved(tree, version, &span_data_table); + if proc_macro.needs_fixup_change() { + proc_macro.change_fixup_to_match_old_server(&mut expanded); + } + expanded + }) + .map_err(|msg| msg.0)), + Response::ExpandMacroExtended(it) => Ok(it + .map(|resp| { + let mut expanded = FlatTree::to_subtree_resolved( + resp.tree, + version, + &deserialize_span_data_index_map(&resp.span_data_table), + ); + if proc_macro.needs_fixup_change() { + proc_macro.change_fixup_to_match_old_server(&mut expanded); + } + expanded + }) + .map_err(|msg| msg.0)), + _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), + } +} + +/// Sends a request to the proc-macro server and waits for a response. +fn send_task(srv: &ProcMacroServerProcess, req: Request) -> Result { + if let Some(server_error) = srv.exited() { + return Err(server_error.clone()); + } + + srv.send_task(send_request, req) +} + +/// Sends a request to the server and reads the response. +fn send_request( + mut writer: &mut dyn Write, + mut reader: &mut dyn BufRead, + req: Request, + buf: &mut String, +) -> Result, ServerError> { + req.write(write_json, &mut writer).map_err(|err| ServerError { + message: "failed to write request".into(), + io: Some(Arc::new(err)), + })?; + let res = Response::read(read_json, &mut reader, buf).map_err(|err| ServerError { + message: "failed to read response".into(), + io: Some(Arc::new(err)), + })?; + Ok(res) +} diff --git a/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol/msg.rs b/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol/msg.rs index 165936269d35..b795c4558956 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol/msg.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol/msg.rs @@ -1,5 +1,6 @@ //! Defines messages for cross-process message passing based on `ndjson` wire protocol pub(crate) mod flat; +pub use self::flat::*; use std::io::{self, BufRead, Write}; @@ -9,24 +10,6 @@ use serde_derive::{Deserialize, Serialize}; use crate::ProcMacroKind; -pub use self::flat::{ - FlatTree, SpanDataIndexMap, deserialize_span_data_index_map, serialize_span_data_index_map, -}; -pub use span::TokenId; - -// The versions of the server protocol -pub const NO_VERSION_CHECK_VERSION: u32 = 0; -pub const VERSION_CHECK_VERSION: u32 = 1; -pub const ENCODE_CLOSE_SPAN_VERSION: u32 = 2; -pub const HAS_GLOBAL_SPANS: u32 = 3; -pub const RUST_ANALYZER_SPAN_SUPPORT: u32 = 4; -/// Whether literals encode their kind as an additional u32 field and idents their rawness as a u32 field. -pub const EXTENDED_LEAF_DATA: u32 = 5; -pub const HASHED_AST_ID: u32 = 6; - -/// Current API version of the proc-macro protocol. -pub const CURRENT_API_VERSION: u32 = HASHED_AST_ID; - /// Represents requests sent from the client to the proc-macro-srv. #[derive(Debug, Serialize, Deserialize)] pub enum Request { @@ -48,7 +31,7 @@ pub enum Request { } /// Defines the mode used for handling span data. -#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize)] +#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq)] pub enum SpanMode { /// Default mode, where spans are identified by an ID. #[default] @@ -210,6 +193,8 @@ mod tests { TopSubtreeBuilder, }; + use crate::version; + use super::*; fn fixture_token_tree() -> TopSubtree { @@ -308,7 +293,7 @@ mod tests { #[test] fn test_proc_macro_rpc_works() { let tt = fixture_token_tree(); - for v in RUST_ANALYZER_SPAN_SUPPORT..=CURRENT_API_VERSION { + for v in version::RUST_ANALYZER_SPAN_SUPPORT..=version::CURRENT_API_VERSION { let mut span_data_table = Default::default(); let task = ExpandMacro { data: ExpandMacroData { diff --git a/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol/msg/flat.rs b/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol/msg/flat.rs index 597ffa05d203..fb3542d24f46 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol/msg/flat.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-api/src/legacy_protocol/msg/flat.rs @@ -40,9 +40,12 @@ use std::collections::VecDeque; use intern::Symbol; use rustc_hash::FxHashMap; use serde_derive::{Deserialize, Serialize}; -use span::{EditionedFileId, ErasedFileAstId, Span, SpanAnchor, SyntaxContext, TextRange, TokenId}; +use span::{EditionedFileId, ErasedFileAstId, Span, SpanAnchor, SyntaxContext, TextRange}; -use crate::legacy_protocol::msg::{ENCODE_CLOSE_SPAN_VERSION, EXTENDED_LEAF_DATA}; +use crate::{ + legacy_protocol::SpanId, + version::{ENCODE_CLOSE_SPAN_VERSION, EXTENDED_LEAF_DATA}, +}; pub type SpanDataIndexMap = indexmap::IndexSet>; @@ -62,7 +65,7 @@ pub fn serialize_span_data_index_map(map: &SpanDataIndexMap) -> Vec { } pub fn deserialize_span_data_index_map(map: &[u32]) -> SpanDataIndexMap { - debug_assert!(map.len() % 5 == 0); + debug_assert!(map.len().is_multiple_of(5)); map.chunks_exact(5) .map(|span| { let &[file_id, ast_id, start, end, e] = span else { unreachable!() }; @@ -91,27 +94,27 @@ pub struct FlatTree { } struct SubtreeRepr { - open: TokenId, - close: TokenId, + open: SpanId, + close: SpanId, kind: tt::DelimiterKind, tt: [u32; 2], } struct LiteralRepr { - id: TokenId, + id: SpanId, text: u32, suffix: u32, kind: u16, } struct PunctRepr { - id: TokenId, + id: SpanId, char: char, spacing: tt::Spacing, } struct IdentRepr { - id: TokenId, + id: SpanId, text: u32, is_raw: bool, } @@ -122,7 +125,7 @@ impl FlatTree { version: u32, span_data_table: &mut SpanDataIndexMap, ) -> FlatTree { - let mut w = Writer { + let mut w = Writer:: { string_table: FxHashMap::default(), work: VecDeque::new(), span_data_table, @@ -159,8 +162,11 @@ impl FlatTree { } } - pub fn new_raw(subtree: tt::SubtreeView<'_, TokenId>, version: u32) -> FlatTree { - let mut w = Writer { + pub fn new_raw>( + subtree: tt::SubtreeView<'_, T::Span>, + version: u32, + ) -> FlatTree { + let mut w = Writer:: { string_table: FxHashMap::default(), work: VecDeque::new(), span_data_table: &mut (), @@ -202,7 +208,7 @@ impl FlatTree { version: u32, span_data_table: &SpanDataIndexMap, ) -> tt::TopSubtree { - Reader { + Reader:: { subtree: if version >= ENCODE_CLOSE_SPAN_VERSION { read_vec(self.subtree, SubtreeRepr::read_with_close_span) } else { @@ -227,8 +233,11 @@ impl FlatTree { .read() } - pub fn to_subtree_unresolved(self, version: u32) -> tt::TopSubtree { - Reader { + pub fn to_subtree_unresolved>( + self, + version: u32, + ) -> tt::TopSubtree { + Reader:: { subtree: if version >= ENCODE_CLOSE_SPAN_VERSION { read_vec(self.subtree, SubtreeRepr::read_with_close_span) } else { @@ -283,7 +292,7 @@ impl SubtreeRepr { 3 => tt::DelimiterKind::Bracket, other => panic!("bad kind {other}"), }; - SubtreeRepr { open: TokenId(open), close: TokenId(!0), kind, tt: [lo, len] } + SubtreeRepr { open: SpanId(open), close: SpanId(!0), kind, tt: [lo, len] } } fn write_with_close_span(self) -> [u32; 5] { let kind = match self.kind { @@ -302,7 +311,7 @@ impl SubtreeRepr { 3 => tt::DelimiterKind::Bracket, other => panic!("bad kind {other}"), }; - SubtreeRepr { open: TokenId(open), close: TokenId(close), kind, tt: [lo, len] } + SubtreeRepr { open: SpanId(open), close: SpanId(close), kind, tt: [lo, len] } } } @@ -311,13 +320,13 @@ impl LiteralRepr { [self.id.0, self.text] } fn read([id, text]: [u32; 2]) -> LiteralRepr { - LiteralRepr { id: TokenId(id), text, kind: 0, suffix: !0 } + LiteralRepr { id: SpanId(id), text, kind: 0, suffix: !0 } } fn write_with_kind(self) -> [u32; 4] { [self.id.0, self.text, self.kind as u32, self.suffix] } fn read_with_kind([id, text, kind, suffix]: [u32; 4]) -> LiteralRepr { - LiteralRepr { id: TokenId(id), text, kind: kind as u16, suffix } + LiteralRepr { id: SpanId(id), text, kind: kind as u16, suffix } } } @@ -335,7 +344,7 @@ impl PunctRepr { 1 => tt::Spacing::Joint, other => panic!("bad spacing {other}"), }; - PunctRepr { id: TokenId(id), char: char.try_into().unwrap(), spacing } + PunctRepr { id: SpanId(id), char: char.try_into().unwrap(), spacing } } } @@ -344,44 +353,46 @@ impl IdentRepr { [self.id.0, self.text] } fn read(data: [u32; 2]) -> IdentRepr { - IdentRepr { id: TokenId(data[0]), text: data[1], is_raw: false } + IdentRepr { id: SpanId(data[0]), text: data[1], is_raw: false } } fn write_with_rawness(self) -> [u32; 3] { [self.id.0, self.text, self.is_raw as u32] } fn read_with_rawness([id, text, is_raw]: [u32; 3]) -> IdentRepr { - IdentRepr { id: TokenId(id), text, is_raw: is_raw == 1 } + IdentRepr { id: SpanId(id), text, is_raw: is_raw == 1 } } } -trait InternableSpan: Copy { +pub trait SpanTransformer { type Table; - fn token_id_of(table: &mut Self::Table, s: Self) -> TokenId; - fn span_for_token_id(table: &Self::Table, id: TokenId) -> Self; + type Span: Copy; + fn token_id_of(table: &mut Self::Table, s: Self::Span) -> SpanId; + fn span_for_token_id(table: &Self::Table, id: SpanId) -> Self::Span; } - -impl InternableSpan for TokenId { +impl SpanTransformer for SpanId { type Table = (); - fn token_id_of((): &mut Self::Table, token_id: Self) -> TokenId { + type Span = Self; + fn token_id_of((): &mut Self::Table, token_id: Self::Span) -> SpanId { token_id } - fn span_for_token_id((): &Self::Table, id: TokenId) -> Self { + fn span_for_token_id((): &Self::Table, id: SpanId) -> Self::Span { id } } -impl InternableSpan for Span { +impl SpanTransformer for Span { type Table = SpanDataIndexMap; - fn token_id_of(table: &mut Self::Table, span: Self) -> TokenId { - TokenId(table.insert_full(span).0 as u32) + type Span = Self; + fn token_id_of(table: &mut Self::Table, span: Self::Span) -> SpanId { + SpanId(table.insert_full(span).0 as u32) } - fn span_for_token_id(table: &Self::Table, id: TokenId) -> Self { + fn span_for_token_id(table: &Self::Table, id: SpanId) -> Self::Span { *table.get_index(id.0 as usize).unwrap_or_else(|| &table[0]) } } -struct Writer<'a, 'span, S: InternableSpan> { - work: VecDeque<(usize, tt::iter::TtIter<'a, S>)>, +struct Writer<'a, 'span, S: SpanTransformer> { + work: VecDeque<(usize, tt::iter::TtIter<'a, S::Span>)>, string_table: FxHashMap, u32>, span_data_table: &'span mut S::Table, version: u32, @@ -394,8 +405,8 @@ struct Writer<'a, 'span, S: InternableSpan> { text: Vec, } -impl<'a, S: InternableSpan> Writer<'a, '_, S> { - fn write(&mut self, root: tt::SubtreeView<'a, S>) { +impl<'a, T: SpanTransformer> Writer<'a, '_, T> { + fn write(&mut self, root: tt::SubtreeView<'a, T::Span>) { let subtree = root.top_subtree(); self.enqueue(subtree, root.iter()); while let Some((idx, subtree)) = self.work.pop_front() { @@ -403,11 +414,11 @@ impl<'a, S: InternableSpan> Writer<'a, '_, S> { } } - fn token_id_of(&mut self, span: S) -> TokenId { - S::token_id_of(self.span_data_table, span) + fn token_id_of(&mut self, span: T::Span) -> SpanId { + T::token_id_of(self.span_data_table, span) } - fn subtree(&mut self, idx: usize, subtree: tt::iter::TtIter<'a, S>) { + fn subtree(&mut self, idx: usize, subtree: tt::iter::TtIter<'a, T::Span>) { let mut first_tt = self.token_tree.len(); let n_tt = subtree.clone().count(); // FIXME: `count()` walks over the entire iterator. self.token_tree.resize(first_tt + n_tt, !0); @@ -478,7 +489,11 @@ impl<'a, S: InternableSpan> Writer<'a, '_, S> { } } - fn enqueue(&mut self, subtree: &'a tt::Subtree, contents: tt::iter::TtIter<'a, S>) -> u32 { + fn enqueue( + &mut self, + subtree: &'a tt::Subtree, + contents: tt::iter::TtIter<'a, T::Span>, + ) -> u32 { let idx = self.subtree.len(); let open = self.token_id_of(subtree.delimiter.open); let close = self.token_id_of(subtree.delimiter.close); @@ -507,7 +522,7 @@ impl<'a, S: InternableSpan> Writer<'a, '_, S> { } } -struct Reader<'span, S: InternableSpan> { +struct Reader<'span, S: SpanTransformer> { version: u32, subtree: Vec, literal: Vec, @@ -518,11 +533,11 @@ struct Reader<'span, S: InternableSpan> { span_data_table: &'span S::Table, } -impl Reader<'_, S> { - pub(crate) fn read(self) -> tt::TopSubtree { - let mut res: Vec, Vec>)>> = +impl Reader<'_, T> { + pub(crate) fn read(self) -> tt::TopSubtree { + let mut res: Vec, Vec>)>> = vec![None; self.subtree.len()]; - let read_span = |id| S::span_for_token_id(self.span_data_table, id); + let read_span = |id| T::span_for_token_id(self.span_data_table, id); for i in (0..self.subtree.len()).rev() { let repr = &self.subtree[i]; let token_trees = &self.token_tree[repr.tt[0] as usize..repr.tt[1] as usize]; diff --git a/src/tools/rust-analyzer/crates/proc-macro-api/src/lib.rs b/src/tools/rust-analyzer/crates/proc-macro-api/src/lib.rs index 516c7418bde8..97919b85b513 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-api/src/lib.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-api/src/lib.rs @@ -5,24 +5,29 @@ //! is used to provide basic infrastructure for communication between two //! processes: Client (RA itself), Server (the external program) -pub mod legacy_protocol { - pub mod json; - pub mod msg; -} +pub mod legacy_protocol; mod process; use paths::{AbsPath, AbsPathBuf}; use span::{ErasedFileAstId, FIXUP_ERASED_FILE_AST_ID_MARKER, Span}; use std::{fmt, io, sync::Arc, time::SystemTime}; -use crate::{ - legacy_protocol::msg::{ - ExpandMacro, ExpandMacroData, ExpnGlobals, FlatTree, HAS_GLOBAL_SPANS, HASHED_AST_ID, - PanicMessage, RUST_ANALYZER_SPAN_SUPPORT, Request, Response, SpanDataIndexMap, - deserialize_span_data_index_map, flat::serialize_span_data_index_map, - }, - process::ProcMacroServerProcess, -}; +use crate::process::ProcMacroServerProcess; + +/// The versions of the server protocol +pub mod version { + pub const NO_VERSION_CHECK_VERSION: u32 = 0; + pub const VERSION_CHECK_VERSION: u32 = 1; + pub const ENCODE_CLOSE_SPAN_VERSION: u32 = 2; + pub const HAS_GLOBAL_SPANS: u32 = 3; + pub const RUST_ANALYZER_SPAN_SUPPORT: u32 = 4; + /// Whether literals encode their kind as an additional u32 field and idents their rawness as a u32 field. + pub const EXTENDED_LEAF_DATA: u32 = 5; + pub const HASHED_AST_ID: u32 = 6; + + /// Current API version of the proc-macro protocol. + pub const CURRENT_API_VERSION: u32 = HASHED_AST_ID; +} /// Represents different kinds of procedural macros that can be expanded by the external server. #[derive(Copy, Clone, Eq, PartialEq, Debug, serde_derive::Serialize, serde_derive::Deserialize)] @@ -163,7 +168,7 @@ impl ProcMacro { fn needs_fixup_change(&self) -> bool { let version = self.process.version(); - (RUST_ANALYZER_SPAN_SUPPORT..HASHED_AST_ID).contains(&version) + (version::RUST_ANALYZER_SPAN_SUPPORT..version::HASHED_AST_ID).contains(&version) } /// On some server versions, the fixup ast id is different than ours. So change it to match. @@ -204,7 +209,7 @@ impl ProcMacro { call_site: Span, mixed_site: Span, current_dir: String, - ) -> Result, PanicMessage>, ServerError> { + ) -> Result, String>, ServerError> { let (mut subtree, mut attr) = (subtree, attr); let (mut subtree_changed, mut attr_changed); if self.needs_fixup_change() { @@ -219,57 +224,15 @@ impl ProcMacro { } } - let version = self.process.version(); - - let mut span_data_table = SpanDataIndexMap::default(); - let def_site = span_data_table.insert_full(def_site).0; - let call_site = span_data_table.insert_full(call_site).0; - let mixed_site = span_data_table.insert_full(mixed_site).0; - let task = ExpandMacro { - data: ExpandMacroData { - macro_body: FlatTree::new(subtree, version, &mut span_data_table), - macro_name: self.name.to_string(), - attributes: attr - .map(|subtree| FlatTree::new(subtree, version, &mut span_data_table)), - has_global_spans: ExpnGlobals { - serialize: version >= HAS_GLOBAL_SPANS, - def_site, - call_site, - mixed_site, - }, - span_data_table: if version >= RUST_ANALYZER_SPAN_SUPPORT { - serialize_span_data_index_map(&span_data_table) - } else { - Vec::new() - }, - }, - lib: self.dylib_path.to_path_buf().into(), + legacy_protocol::expand( + self, + subtree, + attr, env, - current_dir: Some(current_dir), - }; - - let response = self.process.send_task(Request::ExpandMacro(Box::new(task)))?; - - match response { - Response::ExpandMacro(it) => Ok(it.map(|tree| { - let mut expanded = FlatTree::to_subtree_resolved(tree, version, &span_data_table); - if self.needs_fixup_change() { - self.change_fixup_to_match_old_server(&mut expanded); - } - expanded - })), - Response::ExpandMacroExtended(it) => Ok(it.map(|resp| { - let mut expanded = FlatTree::to_subtree_resolved( - resp.tree, - version, - &deserialize_span_data_index_map(&resp.span_data_table), - ); - if self.needs_fixup_change() { - self.change_fixup_to_match_old_server(&mut expanded); - } - expanded - })), - _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), - } + def_site, + call_site, + mixed_site, + current_dir, + ) } } diff --git a/src/tools/rust-analyzer/crates/proc-macro-api/src/process.rs b/src/tools/rust-analyzer/crates/proc-macro-api/src/process.rs index fcea75ef672a..278d9cbcda46 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-api/src/process.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-api/src/process.rs @@ -12,13 +12,8 @@ use stdx::JodChild; use crate::{ ProcMacroKind, ServerError, - legacy_protocol::{ - json::{read_json, write_json}, - msg::{ - CURRENT_API_VERSION, Message, RUST_ANALYZER_SPAN_SUPPORT, Request, Response, - ServerConfig, SpanMode, - }, - }, + legacy_protocol::{self, SpanMode}, + version, }; /// Represents a process handling proc-macro communication. @@ -28,11 +23,16 @@ pub(crate) struct ProcMacroServerProcess { /// hence the lock on the state. state: Mutex, version: u32, - mode: SpanMode, + protocol: Protocol, /// Populated when the server exits. exited: OnceLock>, } +#[derive(Debug)] +enum Protocol { + LegacyJson { mode: SpanMode }, +} + /// Maintains the state of the proc-macro server process. #[derive(Debug)] struct ProcessSrvState { @@ -56,27 +56,26 @@ impl ProcMacroServerProcess { io::Result::Ok(ProcMacroServerProcess { state: Mutex::new(ProcessSrvState { process, stdin, stdout }), version: 0, - mode: SpanMode::Id, + protocol: Protocol::LegacyJson { mode: SpanMode::Id }, exited: OnceLock::new(), }) }; let mut srv = create_srv()?; tracing::info!("sending proc-macro server version check"); match srv.version_check() { - Ok(v) if v > CURRENT_API_VERSION => Err(io::Error::other( - format!( "The version of the proc-macro server ({v}) in your Rust toolchain is newer than the version supported by your rust-analyzer ({CURRENT_API_VERSION}). - This will prevent proc-macro expansion from working. Please consider updating your rust-analyzer to ensure compatibility with your current toolchain." - ), - )), + Ok(v) if v > version::CURRENT_API_VERSION => Err(io::Error::other( + format!( "The version of the proc-macro server ({v}) in your Rust toolchain is newer than the version supported by your rust-analyzer ({}). + This will prevent proc-macro expansion from working. Please consider updating your rust-analyzer to ensure compatibility with your current toolchain." + ,version::CURRENT_API_VERSION + ), + )), Ok(v) => { tracing::info!("Proc-macro server version: {v}"); srv.version = v; - if srv.version >= RUST_ANALYZER_SPAN_SUPPORT { - if let Ok(mode) = srv.enable_rust_analyzer_spans() { - srv.mode = mode; - } + if srv.version >= version::RUST_ANALYZER_SPAN_SUPPORT && let Ok(mode) = srv.enable_rust_analyzer_spans() { + srv.protocol = Protocol::LegacyJson { mode }; } - tracing::info!("Proc-macro server span mode: {:?}", srv.mode); + tracing::info!("Proc-macro server protocol: {:?}", srv.protocol); Ok(srv) } Err(e) => { @@ -98,25 +97,24 @@ impl ProcMacroServerProcess { self.version } + /// Enable support for rust-analyzer span mode if the server supports it. + pub(crate) fn rust_analyzer_spans(&self) -> bool { + match self.protocol { + Protocol::LegacyJson { mode } => mode == SpanMode::RustAnalyzer, + } + } + /// Checks the API version of the running proc-macro server. fn version_check(&self) -> Result { - let request = Request::ApiVersionCheck {}; - let response = self.send_task(request)?; - - match response { - Response::ApiVersionCheck(version) => Ok(version), - _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), + match self.protocol { + Protocol::LegacyJson { .. } => legacy_protocol::version_check(self), } } /// Enable support for rust-analyzer span mode if the server supports it. fn enable_rust_analyzer_spans(&self) -> Result { - let request = Request::SetConfig(ServerConfig { span_mode: SpanMode::RustAnalyzer }); - let response = self.send_task(request)?; - - match response { - Response::SetConfig(ServerConfig { span_mode }) => Ok(span_mode), - _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), + match self.protocol { + Protocol::LegacyJson { .. } => legacy_protocol::enable_rust_analyzer_spans(self), } } @@ -125,25 +123,24 @@ impl ProcMacroServerProcess { &self, dylib_path: &AbsPath, ) -> Result, String>, ServerError> { - let request = Request::ListMacros { dylib_path: dylib_path.to_path_buf().into() }; - - let response = self.send_task(request)?; - - match response { - Response::ListMacros(it) => Ok(it), - _ => Err(ServerError { message: "unexpected response".to_owned(), io: None }), + match self.protocol { + Protocol::LegacyJson { .. } => legacy_protocol::find_proc_macros(self, dylib_path), } } - /// Sends a request to the proc-macro server and waits for a response. - pub(crate) fn send_task(&self, req: Request) -> Result { - if let Some(server_error) = self.exited.get() { - return Err(server_error.0.clone()); - } - + pub(crate) fn send_task( + &self, + serialize_req: impl FnOnce( + &mut dyn Write, + &mut dyn BufRead, + Request, + &mut String, + ) -> Result, ServerError>, + req: Request, + ) -> Result { let state = &mut *self.state.lock().unwrap(); let mut buf = String::new(); - send_request(&mut state.stdin, &mut state.stdout, req, &mut buf) + serialize_req(&mut state.stdin, &mut state.stdout, req, &mut buf) .and_then(|res| { res.ok_or_else(|| { let message = "proc-macro server did not respond with data".to_owned(); @@ -162,10 +159,10 @@ impl ProcMacroServerProcess { Ok(None) | Err(_) => e, Ok(Some(status)) => { let mut msg = String::new(); - if !status.success() { - if let Some(stderr) = state.process.child.stderr.as_mut() { - _ = stderr.read_to_string(&mut msg); - } + if !status.success() + && let Some(stderr) = state.process.child.stderr.as_mut() + { + _ = stderr.read_to_string(&mut msg); } let server_error = ServerError { message: format!( @@ -242,21 +239,3 @@ fn mk_child<'a>( } cmd.spawn() } - -/// Sends a request to the server and reads the response. -fn send_request( - mut writer: &mut impl Write, - mut reader: &mut impl BufRead, - req: Request, - buf: &mut String, -) -> Result, ServerError> { - req.write(write_json, &mut writer).map_err(|err| ServerError { - message: "failed to write request".into(), - io: Some(Arc::new(err)), - })?; - let res = Response::read(read_json, &mut reader, buf).map_err(|err| ServerError { - message: "failed to read response".into(), - io: Some(Arc::new(err)), - })?; - Ok(res) -} diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/Cargo.toml b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/Cargo.toml index ab421021b8bf..16ec3b0e2b2a 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/Cargo.toml +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/Cargo.toml @@ -14,6 +14,7 @@ publish = false proc-macro-srv.workspace = true proc-macro-api.workspace = true tt.workspace = true +clap = {version = "4.5.42", default-features = false, features = ["std"]} [features] sysroot-abi = ["proc-macro-srv/sysroot-abi"] diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs index c47ed053254b..b6ebc562eac9 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs @@ -9,6 +9,7 @@ extern crate rustc_driver as _; #[cfg(any(feature = "sysroot-abi", rust_analyzer))] mod main_loop; +use clap::{Command, ValueEnum}; #[cfg(any(feature = "sysroot-abi", rust_analyzer))] use main_loop::run; @@ -23,12 +24,46 @@ fn main() -> std::io::Result<()> { ); std::process::exit(122); } + let matches = Command::new("proc-macro-srv") + .args(&[clap::Arg::new("format") + .long("format") + .action(clap::ArgAction::Set) + .default_value("json") + .value_parser(clap::builder::EnumValueParser::::new())]) + .get_matches(); + let &format = + matches.get_one::("format").expect("format value should always be present"); + run(format) +} + +#[derive(Copy, Clone)] +enum ProtocolFormat { + Json, + Postcard, +} - run() +impl ValueEnum for ProtocolFormat { + fn value_variants<'a>() -> &'a [Self] { + &[ProtocolFormat::Json] + } + + fn to_possible_value(&self) -> Option { + match self { + ProtocolFormat::Json => Some(clap::builder::PossibleValue::new("json")), + ProtocolFormat::Postcard => Some(clap::builder::PossibleValue::new("postcard")), + } + } + fn from_str(input: &str, _ignore_case: bool) -> Result { + match input { + "json" => Ok(ProtocolFormat::Json), + "postcard" => Ok(ProtocolFormat::Postcard), + _ => Err(format!("unknown protocol format: {input}")), + } + } } #[cfg(not(any(feature = "sysroot-abi", rust_analyzer)))] -fn run() -> std::io::Result<()> { +fn run(_: ProtocolFormat) -> std::io::Result<()> { Err(std::io::Error::new( std::io::ErrorKind::Unsupported, "proc-macro-srv-cli needs to be compiled with the `sysroot-abi` feature to function" diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs index f54dff1f2d82..6bf58eef3bb9 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs @@ -1,16 +1,47 @@ //! The main loop of the proc-macro server. use std::io; -use proc_macro_api::legacy_protocol::{ - json::{read_json, write_json}, - msg::{ - self, CURRENT_API_VERSION, ExpandMacroData, ExpnGlobals, Message, SpanMode, TokenId, - deserialize_span_data_index_map, serialize_span_data_index_map, +use proc_macro_api::{ + legacy_protocol::{ + json::{read_json, write_json}, + msg::{ + self, ExpandMacroData, ExpnGlobals, Message, SpanMode, SpanTransformer, + deserialize_span_data_index_map, serialize_span_data_index_map, + }, }, + version::CURRENT_API_VERSION, }; -use proc_macro_srv::EnvSnapshot; +use proc_macro_srv::{EnvSnapshot, SpanId}; -pub(crate) fn run() -> io::Result<()> { +use crate::ProtocolFormat; + +struct SpanTrans; + +impl SpanTransformer for SpanTrans { + type Table = (); + type Span = SpanId; + fn token_id_of( + _: &mut Self::Table, + span: Self::Span, + ) -> proc_macro_api::legacy_protocol::SpanId { + proc_macro_api::legacy_protocol::SpanId(span.0 as u32) + } + fn span_for_token_id( + _: &Self::Table, + id: proc_macro_api::legacy_protocol::SpanId, + ) -> Self::Span { + SpanId(id.0 as u32) + } +} + +pub(crate) fn run(format: ProtocolFormat) -> io::Result<()> { + match format { + ProtocolFormat::Json => run_json(), + ProtocolFormat::Postcard => unimplemented!(), + } +} + +fn run_json() -> io::Result<()> { fn macro_kind_to_api(kind: proc_macro_srv::ProcMacroKind) -> proc_macro_api::ProcMacroKind { match kind { proc_macro_srv::ProcMacroKind::CustomDerive => { @@ -54,13 +85,14 @@ pub(crate) fn run() -> io::Result<()> { } = *task; match span_mode { SpanMode::Id => msg::Response::ExpandMacro({ - let def_site = TokenId(def_site as u32); - let call_site = TokenId(call_site as u32); - let mixed_site = TokenId(mixed_site as u32); + let def_site = SpanId(def_site as u32); + let call_site = SpanId(call_site as u32); + let mixed_site = SpanId(mixed_site as u32); - let macro_body = macro_body.to_subtree_unresolved(CURRENT_API_VERSION); - let attributes = - attributes.map(|it| it.to_subtree_unresolved(CURRENT_API_VERSION)); + let macro_body = + macro_body.to_subtree_unresolved::(CURRENT_API_VERSION); + let attributes = attributes + .map(|it| it.to_subtree_unresolved::(CURRENT_API_VERSION)); srv.expand( lib, @@ -74,7 +106,10 @@ pub(crate) fn run() -> io::Result<()> { mixed_site, ) .map(|it| { - msg::FlatTree::new_raw(tt::SubtreeView::new(&it), CURRENT_API_VERSION) + msg::FlatTree::new_raw::( + tt::SubtreeView::new(&it), + CURRENT_API_VERSION, + ) }) .map_err(msg::PanicMessage) }), diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs index 223c5a54b703..0f7c83979d56 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs @@ -41,10 +41,12 @@ use std::{ }; use paths::{Utf8Path, Utf8PathBuf}; -use span::{Span, TokenId}; +use span::Span; use crate::server_impl::TokenStream; +pub use crate::server_impl::token_id::SpanId; + #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum ProcMacroKind { CustomDerive, @@ -159,8 +161,8 @@ pub trait ProcMacroSrvSpan: Copy + Send { fn make_server(call_site: Self, def_site: Self, mixed_site: Self) -> Self::Server; } -impl ProcMacroSrvSpan for TokenId { - type Server = server_impl::token_id::TokenIdServer; +impl ProcMacroSrvSpan for SpanId { + type Server = server_impl::token_id::SpanIdServer; fn make_server(call_site: Self, def_site: Self, mixed_site: Self) -> Self::Server { Self::Server { call_site, def_site, mixed_site } diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/token_id.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/token_id.rs index b493b325e830..91e70ea243ae 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/token_id.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/token_id.rs @@ -1,4 +1,4 @@ -//! proc-macro server backend based on [`proc_macro_api::msg::TokenId`] as the backing span. +//! proc-macro server backend based on [`proc_macro_api::msg::SpanId`] as the backing span. //! This backend is rather inflexible, used by RustRover and older rust-analyzer versions. use std::ops::{Bound, Range}; @@ -7,25 +7,34 @@ use proc_macro::bridge::{self, server}; use crate::server_impl::{from_token_tree, literal_from_str, token_stream::TokenStreamBuilder}; -type Span = span::TokenId; +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct SpanId(pub u32); + +impl std::fmt::Debug for SpanId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +type Span = SpanId; type TokenStream = crate::server_impl::TokenStream; pub struct FreeFunctions; -pub struct TokenIdServer { +pub struct SpanIdServer { pub call_site: Span, pub def_site: Span, pub mixed_site: Span, } -impl server::Types for TokenIdServer { +impl server::Types for SpanIdServer { type FreeFunctions = FreeFunctions; type TokenStream = TokenStream; type Span = Span; type Symbol = Symbol; } -impl server::FreeFunctions for TokenIdServer { +impl server::FreeFunctions for SpanIdServer { fn injected_env_var(&mut self, _: &str) -> Option { None } @@ -41,7 +50,7 @@ impl server::FreeFunctions for TokenIdServer { fn emit_diagnostic(&mut self, _: bridge::Diagnostic) {} } -impl server::TokenStream for TokenIdServer { +impl server::TokenStream for SpanIdServer { fn is_empty(&mut self, stream: &Self::TokenStream) -> bool { stream.is_empty() } @@ -102,12 +111,12 @@ impl server::TokenStream for TokenIdServer { &mut self, stream: Self::TokenStream, ) -> Vec> { - // Can't join with `TokenId`. + // Can't join with `SpanId`. stream.into_bridge(&mut |first, _second| first) } } -impl server::Span for TokenIdServer { +impl server::Span for SpanIdServer { fn debug(&mut self, span: Self::Span) -> String { format!("{:?}", span.0) } @@ -174,14 +183,14 @@ impl server::Span for TokenIdServer { } } -impl server::Symbol for TokenIdServer { +impl server::Symbol for SpanIdServer { fn normalize_and_validate_ident(&mut self, string: &str) -> Result { // FIXME: nfc-normalize and validate idents Ok(::intern_symbol(string)) } } -impl server::Server for TokenIdServer { +impl server::Server for SpanIdServer { fn globals(&mut self) -> bridge::ExpnGlobals { bridge::ExpnGlobals { def_site: self.def_site, @@ -201,8 +210,6 @@ impl server::Server for TokenIdServer { #[cfg(test)] mod tests { - use span::TokenId; - use super::*; #[test] @@ -211,18 +218,18 @@ mod tests { token_trees: vec![ tt::TokenTree::Leaf(tt::Leaf::Ident(tt::Ident { sym: Symbol::intern("struct"), - span: TokenId(0), + span: SpanId(0), is_raw: tt::IdentIsRaw::No, })), tt::TokenTree::Leaf(tt::Leaf::Ident(tt::Ident { sym: Symbol::intern("T"), - span: TokenId(0), + span: SpanId(0), is_raw: tt::IdentIsRaw::No, })), tt::TokenTree::Subtree(tt::Subtree { delimiter: tt::Delimiter { - open: TokenId(0), - close: TokenId(0), + open: SpanId(0), + close: SpanId(0), kind: tt::DelimiterKind::Brace, }, len: 0, @@ -238,8 +245,8 @@ mod tests { let subtree_paren_a = vec![ tt::TokenTree::Subtree(tt::Subtree { delimiter: tt::Delimiter { - open: TokenId(0), - close: TokenId(0), + open: SpanId(0), + close: SpanId(0), kind: tt::DelimiterKind::Parenthesis, }, len: 1, @@ -247,24 +254,24 @@ mod tests { tt::TokenTree::Leaf(tt::Leaf::Ident(tt::Ident { is_raw: tt::IdentIsRaw::No, sym: Symbol::intern("a"), - span: TokenId(0), + span: SpanId(0), })), ]; - let t1 = TokenStream::from_str("(a)", TokenId(0)).unwrap(); + let t1 = TokenStream::from_str("(a)", SpanId(0)).unwrap(); assert_eq!(t1.token_trees.len(), 2); assert!(t1.token_trees[0..2] == subtree_paren_a); - let t2 = TokenStream::from_str("(a);", TokenId(0)).unwrap(); + let t2 = TokenStream::from_str("(a);", SpanId(0)).unwrap(); assert_eq!(t2.token_trees.len(), 3); assert!(t2.token_trees[0..2] == subtree_paren_a); - let underscore = TokenStream::from_str("_", TokenId(0)).unwrap(); + let underscore = TokenStream::from_str("_", SpanId(0)).unwrap(); assert!( underscore.token_trees[0] == tt::TokenTree::Leaf(tt::Leaf::Ident(tt::Ident { sym: Symbol::intern("_"), - span: TokenId(0), + span: SpanId(0), is_raw: tt::IdentIsRaw::No, })) ); diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/tests/utils.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/tests/utils.rs index 10af5662b5c0..7aa38576bb52 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/tests/utils.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/tests/utils.rs @@ -1,14 +1,12 @@ //! utils used in proc-macro tests use expect_test::Expect; -use span::{ - EditionedFileId, FileId, ROOT_ERASED_FILE_AST_ID, Span, SpanAnchor, SyntaxContext, TokenId, -}; +use span::{EditionedFileId, FileId, ROOT_ERASED_FILE_AST_ID, Span, SpanAnchor, SyntaxContext}; use tt::TextRange; -use crate::{EnvSnapshot, ProcMacroSrv, dylib, proc_macro_test_dylib_path}; +use crate::{EnvSnapshot, ProcMacroSrv, SpanId, dylib, proc_macro_test_dylib_path}; -fn parse_string(call_site: TokenId, src: &str) -> crate::server_impl::TokenStream { +fn parse_string(call_site: SpanId, src: &str) -> crate::server_impl::TokenStream { crate::server_impl::TokenStream::with_subtree(crate::server_impl::TopSubtree( syntax_bridge::parse_to_token_tree_static_span(span::Edition::CURRENT, call_site, src) .unwrap() @@ -59,9 +57,9 @@ fn assert_expand_impl( let path = proc_macro_test_dylib_path(); let expander = dylib::Expander::new(&path).unwrap(); - let def_site = TokenId(0); - let call_site = TokenId(1); - let mixed_site = TokenId(2); + let def_site = SpanId(0); + let call_site = SpanId(1); + let mixed_site = SpanId(2); let input_ts = parse_string(call_site, input).into_subtree(call_site); let attr_ts = attr.map(|attr| parse_string(call_site, attr).into_subtree(call_site)); let input_ts_string = format!("{input_ts:?}"); diff --git a/src/tools/rust-analyzer/crates/span/src/lib.rs b/src/tools/rust-analyzer/crates/span/src/lib.rs index b81d08eed6d8..ae9e038459e5 100644 --- a/src/tools/rust-analyzer/crates/span/src/lib.rs +++ b/src/tools/rust-analyzer/crates/span/src/lib.rs @@ -203,15 +203,3 @@ pub struct HirFileId(pub salsa::Id); /// `println!("Hello, {}", world)`. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct MacroCallId(pub salsa::Id); - -/// Legacy span type, only defined here as it is still used by the proc-macro server. -/// While rust-analyzer doesn't use this anymore at all, RustRover relies on the legacy type for -/// proc-macro expansion. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub struct TokenId(pub u32); - -impl std::fmt::Debug for TokenId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } -} From d71e972414b8a1fe188a31ed96fecbd157c3ddcf Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Wed, 30 Jul 2025 00:03:53 +0900 Subject: [PATCH 0219/1134] add `SyntaxEditor::delete_all` to migrate utils.rs `add_trait_assoc_items_to_impl` --- .../crates/ide-assists/src/utils.rs | 57 ++++++++++--------- .../crates/syntax/src/syntax_editor.rs | 10 ++++ .../crates/syntax/src/syntax_editor/edits.rs | 26 +++++++++ 3 files changed, 67 insertions(+), 26 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs b/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs index 15c7a6a3fc26..c81a3a6f08d5 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs @@ -23,12 +23,11 @@ use syntax::{ ast::{ self, HasArgList, HasAttrs, HasGenericParams, HasName, HasTypeBounds, Whitespace, edit::{AstNodeEdit, IndentLevel}, - edit_in_place::{AttrsOwnerEdit, Removable}, + edit_in_place::AttrsOwnerEdit, make, syntax_factory::SyntaxFactory, }, - syntax_editor::SyntaxEditor, - ted, + syntax_editor::{Removable, SyntaxEditor}, }; use crate::{ @@ -207,7 +206,7 @@ pub fn add_trait_assoc_items_to_impl( stdx::never!("formatted `AssocItem` could not be cast back to `AssocItem`"); } } - original_item.clone_for_update() + original_item } .reset_indent(); @@ -221,31 +220,37 @@ pub fn add_trait_assoc_items_to_impl( cloned_item.remove_attrs_and_docs(); cloned_item }) - .map(|item| { - match &item { - ast::AssocItem::Fn(fn_) if fn_.body().is_none() => { - let body = AstNodeEdit::indent( - &make::block_expr( - None, - Some(match config.expr_fill_default { - ExprFillDefaultMode::Todo => make::ext::expr_todo(), - ExprFillDefaultMode::Underscore => make::ext::expr_underscore(), - ExprFillDefaultMode::Default => make::ext::expr_todo(), - }), - ), - IndentLevel::single(), - ); - ted::replace(fn_.get_or_create_body().syntax(), body.syntax()); - } - ast::AssocItem::TypeAlias(type_alias) => { - if let Some(type_bound_list) = type_alias.type_bound_list() { - type_bound_list.remove() - } + .filter_map(|item| match item { + ast::AssocItem::Fn(fn_) if fn_.body().is_none() => { + let fn_ = fn_.clone_subtree(); + let new_body = &make::block_expr( + None, + Some(match config.expr_fill_default { + ExprFillDefaultMode::Todo => make::ext::expr_todo(), + ExprFillDefaultMode::Underscore => make::ext::expr_underscore(), + ExprFillDefaultMode::Default => make::ext::expr_todo(), + }), + ); + let new_body = AstNodeEdit::indent(new_body, IndentLevel::single()); + let mut fn_editor = SyntaxEditor::new(fn_.syntax().clone()); + fn_.replace_or_insert_body(&mut fn_editor, new_body); + let new_fn_ = fn_editor.finish().new_root().clone(); + ast::AssocItem::cast(new_fn_) + } + ast::AssocItem::TypeAlias(type_alias) => { + let type_alias = type_alias.clone_subtree(); + if let Some(type_bound_list) = type_alias.type_bound_list() { + let mut type_alias_editor = SyntaxEditor::new(type_alias.syntax().clone()); + type_bound_list.remove(&mut type_alias_editor); + let type_alias = type_alias_editor.finish().new_root().clone(); + ast::AssocItem::cast(type_alias) + } else { + Some(ast::AssocItem::TypeAlias(type_alias)) } - _ => {} } - AstNodeEdit::indent(&item, new_indent_level) + item => Some(item), }) + .map(|item| AstNodeEdit::indent(&item, new_indent_level)) .collect() } diff --git a/src/tools/rust-analyzer/crates/syntax/src/syntax_editor.rs b/src/tools/rust-analyzer/crates/syntax/src/syntax_editor.rs index 5107754b1825..147b54c21a5f 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/syntax_editor.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/syntax_editor.rs @@ -83,6 +83,16 @@ impl SyntaxEditor { self.changes.push(Change::Replace(element.syntax_element(), None)); } + pub fn delete_all(&mut self, range: RangeInclusive) { + if range.start() == range.end() { + self.delete(range.start()); + return; + } + + debug_assert!(is_ancestor_or_self_of_element(range.start(), &self.root)); + self.changes.push(Change::ReplaceAll(range, Vec::new())) + } + pub fn replace(&mut self, old: impl Element, new: impl Element) { let old = old.syntax_element(); debug_assert!(is_ancestor_or_self_of_element(&old, &self.root)); diff --git a/src/tools/rust-analyzer/crates/syntax/src/syntax_editor/edits.rs b/src/tools/rust-analyzer/crates/syntax/src/syntax_editor/edits.rs index 840e76979792..9090f7c9eb14 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/syntax_editor/edits.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/syntax_editor/edits.rs @@ -153,6 +153,23 @@ impl ast::VariantList { } } +impl ast::Fn { + pub fn replace_or_insert_body(&self, editor: &mut SyntaxEditor, body: ast::BlockExpr) { + if let Some(old_body) = self.body() { + editor.replace(old_body.syntax(), body.syntax()); + } else { + let single_space = make::tokens::single_space(); + let elements = vec![single_space.into(), body.syntax().clone().into()]; + + if let Some(semicolon) = self.semicolon_token() { + editor.replace_with_many(semicolon, elements); + } else { + editor.insert_all(Position::last_child_of(self.syntax()), elements); + } + } + } +} + fn normalize_ws_between_braces(editor: &mut SyntaxEditor, node: &SyntaxNode) -> Option<()> { let make = SyntaxFactory::without_mappings(); let l = node @@ -184,6 +201,15 @@ pub trait Removable: AstNode { fn remove(&self, editor: &mut SyntaxEditor); } +impl Removable for ast::TypeBoundList { + fn remove(&self, editor: &mut SyntaxEditor) { + match self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:]) { + Some(colon) => editor.delete_all(colon..=self.syntax().clone().into()), + None => editor.delete(self.syntax()), + } + } +} + impl Removable for ast::Use { fn remove(&self, editor: &mut SyntaxEditor) { let make = SyntaxFactory::without_mappings(); From 3cbd088ee4e453eeab2d3cfae3e047b7e12bece8 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 30 Jul 2025 09:56:11 -0500 Subject: [PATCH 0220/1134] ci: Set pipefail before running ci-util Currently, a failure in `ci-util.py` does not cause the job to fail because the pipe eats the failure status . Set pipefail to fix this. Fixes: ff2cc0e38e3e ("ci: Don't print output twice in `ci-util`") --- library/compiler-builtins/.github/workflows/main.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/library/compiler-builtins/.github/workflows/main.yaml b/library/compiler-builtins/.github/workflows/main.yaml index 939bc34c264e..c54df2e90b79 100644 --- a/library/compiler-builtins/.github/workflows/main.yaml +++ b/library/compiler-builtins/.github/workflows/main.yaml @@ -34,7 +34,9 @@ jobs: - name: Fetch pull request ref run: git fetch origin "$GITHUB_REF:$GITHUB_REF" if: github.event_name == 'pull_request' - - run: set -e; python3 ci/ci-util.py generate-matrix | tee "$GITHUB_OUTPUT" + - run: | + set -eo pipefail # Needed to actually fail the job if ci-util fails + python3 ci/ci-util.py generate-matrix | tee "$GITHUB_OUTPUT" id: script test: From ecf6d3c6ced41d71a09248fdc679309e39bae318 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 30 Jul 2025 09:45:53 -0500 Subject: [PATCH 0221/1134] Simplify the configuration for no-panic Currently, attributes for `no-panic` are gated behind both the `test` config and `assert_no_panic`, because `no-panic` is a dev dependency (so only available with test configuration). However, we only emit `assert_no_panic` when the test config is also set anyway, so there isn't any need to gate on both. Replace gates on `all(test, assert_no_panic)` with only `assert_no_panic`. This is simpler, and also has the benefit that attempting to check for panics without `--test` errors. --- library/compiler-builtins/libm/src/math/acos.rs | 2 +- library/compiler-builtins/libm/src/math/acosf.rs | 2 +- library/compiler-builtins/libm/src/math/acosh.rs | 2 +- .../compiler-builtins/libm/src/math/acoshf.rs | 2 +- library/compiler-builtins/libm/src/math/asin.rs | 2 +- library/compiler-builtins/libm/src/math/asinf.rs | 2 +- library/compiler-builtins/libm/src/math/asinh.rs | 2 +- .../compiler-builtins/libm/src/math/asinhf.rs | 2 +- library/compiler-builtins/libm/src/math/atan.rs | 2 +- library/compiler-builtins/libm/src/math/atan2.rs | 2 +- .../compiler-builtins/libm/src/math/atan2f.rs | 2 +- library/compiler-builtins/libm/src/math/atanf.rs | 2 +- library/compiler-builtins/libm/src/math/atanh.rs | 2 +- .../compiler-builtins/libm/src/math/atanhf.rs | 2 +- library/compiler-builtins/libm/src/math/cbrt.rs | 2 +- library/compiler-builtins/libm/src/math/cbrtf.rs | 2 +- library/compiler-builtins/libm/src/math/ceil.rs | 8 ++++---- .../compiler-builtins/libm/src/math/copysign.rs | 8 ++++---- library/compiler-builtins/libm/src/math/cos.rs | 2 +- library/compiler-builtins/libm/src/math/cosf.rs | 2 +- library/compiler-builtins/libm/src/math/cosh.rs | 2 +- library/compiler-builtins/libm/src/math/coshf.rs | 2 +- library/compiler-builtins/libm/src/math/erf.rs | 2 +- library/compiler-builtins/libm/src/math/erff.rs | 2 +- library/compiler-builtins/libm/src/math/exp.rs | 2 +- library/compiler-builtins/libm/src/math/exp10.rs | 2 +- .../compiler-builtins/libm/src/math/exp10f.rs | 2 +- library/compiler-builtins/libm/src/math/exp2.rs | 2 +- library/compiler-builtins/libm/src/math/exp2f.rs | 2 +- library/compiler-builtins/libm/src/math/expf.rs | 2 +- library/compiler-builtins/libm/src/math/expm1.rs | 2 +- .../compiler-builtins/libm/src/math/expm1f.rs | 2 +- library/compiler-builtins/libm/src/math/expo2.rs | 2 +- library/compiler-builtins/libm/src/math/fabs.rs | 8 ++++---- library/compiler-builtins/libm/src/math/fdim.rs | 8 ++++---- library/compiler-builtins/libm/src/math/floor.rs | 8 ++++---- library/compiler-builtins/libm/src/math/fma.rs | 8 ++++---- .../compiler-builtins/libm/src/math/fmin_fmax.rs | 16 ++++++++-------- .../libm/src/math/fminimum_fmaximum.rs | 16 ++++++++-------- .../libm/src/math/fminimum_fmaximum_num.rs | 16 ++++++++-------- library/compiler-builtins/libm/src/math/fmod.rs | 8 ++++---- library/compiler-builtins/libm/src/math/frexp.rs | 2 +- .../compiler-builtins/libm/src/math/frexpf.rs | 2 +- library/compiler-builtins/libm/src/math/hypot.rs | 2 +- .../compiler-builtins/libm/src/math/hypotf.rs | 2 +- library/compiler-builtins/libm/src/math/ilogb.rs | 2 +- .../compiler-builtins/libm/src/math/ilogbf.rs | 2 +- library/compiler-builtins/libm/src/math/j0.rs | 4 ++-- library/compiler-builtins/libm/src/math/j0f.rs | 4 ++-- library/compiler-builtins/libm/src/math/j1.rs | 4 ++-- library/compiler-builtins/libm/src/math/j1f.rs | 4 ++-- library/compiler-builtins/libm/src/math/jn.rs | 4 ++-- library/compiler-builtins/libm/src/math/jnf.rs | 4 ++-- library/compiler-builtins/libm/src/math/k_cos.rs | 2 +- .../compiler-builtins/libm/src/math/k_cosf.rs | 2 +- .../compiler-builtins/libm/src/math/k_expo2.rs | 2 +- .../compiler-builtins/libm/src/math/k_expo2f.rs | 2 +- library/compiler-builtins/libm/src/math/k_sin.rs | 2 +- .../compiler-builtins/libm/src/math/k_sinf.rs | 2 +- library/compiler-builtins/libm/src/math/k_tan.rs | 2 +- .../compiler-builtins/libm/src/math/k_tanf.rs | 2 +- library/compiler-builtins/libm/src/math/ldexp.rs | 8 ++++---- .../compiler-builtins/libm/src/math/lgamma.rs | 2 +- .../compiler-builtins/libm/src/math/lgamma_r.rs | 2 +- .../compiler-builtins/libm/src/math/lgammaf.rs | 2 +- .../compiler-builtins/libm/src/math/lgammaf_r.rs | 2 +- library/compiler-builtins/libm/src/math/log.rs | 2 +- library/compiler-builtins/libm/src/math/log10.rs | 2 +- .../compiler-builtins/libm/src/math/log10f.rs | 2 +- library/compiler-builtins/libm/src/math/log1p.rs | 2 +- .../compiler-builtins/libm/src/math/log1pf.rs | 2 +- library/compiler-builtins/libm/src/math/log2.rs | 2 +- library/compiler-builtins/libm/src/math/log2f.rs | 2 +- library/compiler-builtins/libm/src/math/logf.rs | 2 +- library/compiler-builtins/libm/src/math/modf.rs | 2 +- library/compiler-builtins/libm/src/math/modff.rs | 2 +- .../compiler-builtins/libm/src/math/nextafter.rs | 2 +- .../libm/src/math/nextafterf.rs | 2 +- library/compiler-builtins/libm/src/math/pow.rs | 2 +- library/compiler-builtins/libm/src/math/powf.rs | 2 +- .../compiler-builtins/libm/src/math/rem_pio2.rs | 2 +- .../libm/src/math/rem_pio2_large.rs | 2 +- .../compiler-builtins/libm/src/math/rem_pio2f.rs | 2 +- .../compiler-builtins/libm/src/math/remainder.rs | 2 +- .../libm/src/math/remainderf.rs | 2 +- .../compiler-builtins/libm/src/math/remquo.rs | 2 +- .../compiler-builtins/libm/src/math/remquof.rs | 2 +- library/compiler-builtins/libm/src/math/rint.rs | 8 ++++---- library/compiler-builtins/libm/src/math/round.rs | 8 ++++---- .../compiler-builtins/libm/src/math/roundeven.rs | 8 ++++---- .../compiler-builtins/libm/src/math/scalbn.rs | 8 ++++---- library/compiler-builtins/libm/src/math/sin.rs | 2 +- .../compiler-builtins/libm/src/math/sincos.rs | 2 +- .../compiler-builtins/libm/src/math/sincosf.rs | 2 +- library/compiler-builtins/libm/src/math/sinf.rs | 2 +- library/compiler-builtins/libm/src/math/sinh.rs | 2 +- library/compiler-builtins/libm/src/math/sinhf.rs | 2 +- library/compiler-builtins/libm/src/math/sqrt.rs | 8 ++++---- library/compiler-builtins/libm/src/math/tan.rs | 2 +- library/compiler-builtins/libm/src/math/tanf.rs | 2 +- library/compiler-builtins/libm/src/math/tanh.rs | 2 +- library/compiler-builtins/libm/src/math/tanhf.rs | 2 +- .../compiler-builtins/libm/src/math/tgamma.rs | 2 +- .../compiler-builtins/libm/src/math/tgammaf.rs | 2 +- library/compiler-builtins/libm/src/math/trunc.rs | 8 ++++---- 105 files changed, 174 insertions(+), 174 deletions(-) diff --git a/library/compiler-builtins/libm/src/math/acos.rs b/library/compiler-builtins/libm/src/math/acos.rs index 23b13251ee23..89b2e7c5f30e 100644 --- a/library/compiler-builtins/libm/src/math/acos.rs +++ b/library/compiler-builtins/libm/src/math/acos.rs @@ -59,7 +59,7 @@ fn r(z: f64) -> f64 { /// Computes the inverse cosine (arc cosine) of the input value. /// Arguments must be in the range -1 to 1. /// Returns values in radians, in the range of 0 to pi. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn acos(x: f64) -> f64 { let x1p_120f = f64::from_bits(0x3870000000000000); // 0x1p-120 === 2 ^ -120 let z: f64; diff --git a/library/compiler-builtins/libm/src/math/acosf.rs b/library/compiler-builtins/libm/src/math/acosf.rs index dd88eea5b13a..d263b3f2ce33 100644 --- a/library/compiler-builtins/libm/src/math/acosf.rs +++ b/library/compiler-builtins/libm/src/math/acosf.rs @@ -33,7 +33,7 @@ fn r(z: f32) -> f32 { /// Computes the inverse cosine (arc cosine) of the input value. /// Arguments must be in the range -1 to 1. /// Returns values in radians, in the range of 0 to pi. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn acosf(x: f32) -> f32 { let x1p_120 = f32::from_bits(0x03800000); // 0x1p-120 === 2 ^ (-120) diff --git a/library/compiler-builtins/libm/src/math/acosh.rs b/library/compiler-builtins/libm/src/math/acosh.rs index d1f5b9fa9372..8737bad012c8 100644 --- a/library/compiler-builtins/libm/src/math/acosh.rs +++ b/library/compiler-builtins/libm/src/math/acosh.rs @@ -7,7 +7,7 @@ const LN2: f64 = 0.693147180559945309417232121458176568; /* 0x3fe62e42, 0xfefa3 /// Calculates the inverse hyperbolic cosine of `x`. /// Is defined as `log(x + sqrt(x*x-1))`. /// `x` must be a number greater than or equal to 1. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn acosh(x: f64) -> f64 { let u = x.to_bits(); let e = ((u >> 52) as usize) & 0x7ff; diff --git a/library/compiler-builtins/libm/src/math/acoshf.rs b/library/compiler-builtins/libm/src/math/acoshf.rs index ad3455fdd48c..432fa03f1163 100644 --- a/library/compiler-builtins/libm/src/math/acoshf.rs +++ b/library/compiler-builtins/libm/src/math/acoshf.rs @@ -7,7 +7,7 @@ const LN2: f32 = 0.693147180559945309417232121458176568; /// Calculates the inverse hyperbolic cosine of `x`. /// Is defined as `log(x + sqrt(x*x-1))`. /// `x` must be a number greater than or equal to 1. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn acoshf(x: f32) -> f32 { let u = x.to_bits(); let a = u & 0x7fffffff; diff --git a/library/compiler-builtins/libm/src/math/asin.rs b/library/compiler-builtins/libm/src/math/asin.rs index 12d0cd35fa58..9554a3eacc24 100644 --- a/library/compiler-builtins/libm/src/math/asin.rs +++ b/library/compiler-builtins/libm/src/math/asin.rs @@ -66,7 +66,7 @@ fn comp_r(z: f64) -> f64 { /// Computes the inverse sine (arc sine) of the argument `x`. /// Arguments to asin must be in the range -1 to 1. /// Returns values in radians, in the range of -pi/2 to pi/2. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn asin(mut x: f64) -> f64 { let z: f64; let r: f64; diff --git a/library/compiler-builtins/libm/src/math/asinf.rs b/library/compiler-builtins/libm/src/math/asinf.rs index ed685556730e..2dfe2a6d486d 100644 --- a/library/compiler-builtins/libm/src/math/asinf.rs +++ b/library/compiler-builtins/libm/src/math/asinf.rs @@ -35,7 +35,7 @@ fn r(z: f32) -> f32 { /// Computes the inverse sine (arc sine) of the argument `x`. /// Arguments to asin must be in the range -1 to 1. /// Returns values in radians, in the range of -pi/2 to pi/2. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn asinf(mut x: f32) -> f32 { let x1p_120 = f64::from_bits(0x3870000000000000); // 0x1p-120 === 2 ^ (-120) diff --git a/library/compiler-builtins/libm/src/math/asinh.rs b/library/compiler-builtins/libm/src/math/asinh.rs index 75d3c3ad462a..d63bc0aa9c35 100644 --- a/library/compiler-builtins/libm/src/math/asinh.rs +++ b/library/compiler-builtins/libm/src/math/asinh.rs @@ -7,7 +7,7 @@ const LN2: f64 = 0.693147180559945309417232121458176568; /* 0x3fe62e42, 0xfefa3 /// /// Calculates the inverse hyperbolic sine of `x`. /// Is defined as `sgn(x)*log(|x|+sqrt(x*x+1))`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn asinh(mut x: f64) -> f64 { let mut u = x.to_bits(); let e = ((u >> 52) as usize) & 0x7ff; diff --git a/library/compiler-builtins/libm/src/math/asinhf.rs b/library/compiler-builtins/libm/src/math/asinhf.rs index 27ed9dd372da..3ca2d44894db 100644 --- a/library/compiler-builtins/libm/src/math/asinhf.rs +++ b/library/compiler-builtins/libm/src/math/asinhf.rs @@ -7,7 +7,7 @@ const LN2: f32 = 0.693147180559945309417232121458176568; /// /// Calculates the inverse hyperbolic sine of `x`. /// Is defined as `sgn(x)*log(|x|+sqrt(x*x+1))`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn asinhf(mut x: f32) -> f32 { let u = x.to_bits(); let i = u & 0x7fffffff; diff --git a/library/compiler-builtins/libm/src/math/atan.rs b/library/compiler-builtins/libm/src/math/atan.rs index 4ca5cc91a1e4..0590ba87cf85 100644 --- a/library/compiler-builtins/libm/src/math/atan.rs +++ b/library/compiler-builtins/libm/src/math/atan.rs @@ -65,7 +65,7 @@ const AT: [f64; 11] = [ /// /// Computes the inverse tangent (arc tangent) of the input value. /// Returns a value in radians, in the range of -pi/2 to pi/2. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn atan(x: f64) -> f64 { let mut x = x; let mut ix = (x.to_bits() >> 32) as u32; diff --git a/library/compiler-builtins/libm/src/math/atan2.rs b/library/compiler-builtins/libm/src/math/atan2.rs index c668731cf376..51456e409b8c 100644 --- a/library/compiler-builtins/libm/src/math/atan2.rs +++ b/library/compiler-builtins/libm/src/math/atan2.rs @@ -47,7 +47,7 @@ const PI_LO: f64 = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */ /// Computes the inverse tangent (arc tangent) of `y/x`. /// Produces the correct result even for angles near pi/2 or -pi/2 (that is, when `x` is near 0). /// Returns a value in radians, in the range of -pi to pi. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn atan2(y: f64, x: f64) -> f64 { if x.is_nan() || y.is_nan() { return x + y; diff --git a/library/compiler-builtins/libm/src/math/atan2f.rs b/library/compiler-builtins/libm/src/math/atan2f.rs index 95b466fff4e4..0f46c9f3906b 100644 --- a/library/compiler-builtins/libm/src/math/atan2f.rs +++ b/library/compiler-builtins/libm/src/math/atan2f.rs @@ -23,7 +23,7 @@ const PI_LO: f32 = -8.7422776573e-08; /* 0xb3bbbd2e */ /// Computes the inverse tangent (arc tangent) of `y/x`. /// Produces the correct result even for angles near pi/2 or -pi/2 (that is, when `x` is near 0). /// Returns a value in radians, in the range of -pi to pi. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn atan2f(y: f32, x: f32) -> f32 { if x.is_nan() || y.is_nan() { return x + y; diff --git a/library/compiler-builtins/libm/src/math/atanf.rs b/library/compiler-builtins/libm/src/math/atanf.rs index da8daa41a010..58568d9a81f2 100644 --- a/library/compiler-builtins/libm/src/math/atanf.rs +++ b/library/compiler-builtins/libm/src/math/atanf.rs @@ -41,7 +41,7 @@ const A_T: [f32; 5] = [ /// /// Computes the inverse tangent (arc tangent) of the input value. /// Returns a value in radians, in the range of -pi/2 to pi/2. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn atanf(mut x: f32) -> f32 { let x1p_120 = f32::from_bits(0x03800000); // 0x1p-120 === 2 ^ (-120) diff --git a/library/compiler-builtins/libm/src/math/atanh.rs b/library/compiler-builtins/libm/src/math/atanh.rs index 9dc826f5605b..883ff150fd6c 100644 --- a/library/compiler-builtins/libm/src/math/atanh.rs +++ b/library/compiler-builtins/libm/src/math/atanh.rs @@ -5,7 +5,7 @@ use super::log1p; /// /// Calculates the inverse hyperbolic tangent of `x`. /// Is defined as `log((1+x)/(1-x))/2 = log1p(2x/(1-x))/2`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn atanh(x: f64) -> f64 { let u = x.to_bits(); let e = ((u >> 52) as usize) & 0x7ff; diff --git a/library/compiler-builtins/libm/src/math/atanhf.rs b/library/compiler-builtins/libm/src/math/atanhf.rs index 80ccec1f67fe..e4e356d18d83 100644 --- a/library/compiler-builtins/libm/src/math/atanhf.rs +++ b/library/compiler-builtins/libm/src/math/atanhf.rs @@ -5,7 +5,7 @@ use super::log1pf; /// /// Calculates the inverse hyperbolic tangent of `x`. /// Is defined as `log((1+x)/(1-x))/2 = log1p(2x/(1-x))/2`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn atanhf(mut x: f32) -> f32 { let mut u = x.to_bits(); let sign = (u >> 31) != 0; diff --git a/library/compiler-builtins/libm/src/math/cbrt.rs b/library/compiler-builtins/libm/src/math/cbrt.rs index cf56f7a9792a..e905e15f13fb 100644 --- a/library/compiler-builtins/libm/src/math/cbrt.rs +++ b/library/compiler-builtins/libm/src/math/cbrt.rs @@ -8,7 +8,7 @@ use super::Float; use super::support::{FpResult, Round, cold_path}; /// Compute the cube root of the argument. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn cbrt(x: f64) -> f64 { cbrt_round(x, Round::Nearest).val } diff --git a/library/compiler-builtins/libm/src/math/cbrtf.rs b/library/compiler-builtins/libm/src/math/cbrtf.rs index 9d70305c6472..9d69584834a3 100644 --- a/library/compiler-builtins/libm/src/math/cbrtf.rs +++ b/library/compiler-builtins/libm/src/math/cbrtf.rs @@ -25,7 +25,7 @@ const B2: u32 = 642849266; /* B2 = (127-127.0/3-24/3-0.03306235651)*2**23 */ /// Cube root (f32) /// /// Computes the cube root of the argument. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn cbrtf(x: f32) -> f32 { let x1p24 = f32::from_bits(0x4b800000); // 0x1p24f === 2 ^ 24 diff --git a/library/compiler-builtins/libm/src/math/ceil.rs b/library/compiler-builtins/libm/src/math/ceil.rs index 4e103545727a..2cac49f29ba9 100644 --- a/library/compiler-builtins/libm/src/math/ceil.rs +++ b/library/compiler-builtins/libm/src/math/ceil.rs @@ -2,7 +2,7 @@ /// /// Finds the nearest integer greater than or equal to `x`. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ceilf16(x: f16) -> f16 { super::generic::ceil(x) } @@ -10,7 +10,7 @@ pub fn ceilf16(x: f16) -> f16 { /// Ceil (f32) /// /// Finds the nearest integer greater than or equal to `x`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ceilf(x: f32) -> f32 { select_implementation! { name: ceilf, @@ -24,7 +24,7 @@ pub fn ceilf(x: f32) -> f32 { /// Ceil (f64) /// /// Finds the nearest integer greater than or equal to `x`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ceil(x: f64) -> f64 { select_implementation! { name: ceil, @@ -40,7 +40,7 @@ pub fn ceil(x: f64) -> f64 { /// /// Finds the nearest integer greater than or equal to `x`. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ceilf128(x: f128) -> f128 { super::generic::ceil(x) } diff --git a/library/compiler-builtins/libm/src/math/copysign.rs b/library/compiler-builtins/libm/src/math/copysign.rs index d093d6107273..591a87a940e2 100644 --- a/library/compiler-builtins/libm/src/math/copysign.rs +++ b/library/compiler-builtins/libm/src/math/copysign.rs @@ -3,7 +3,7 @@ /// Constructs a number with the magnitude (absolute value) of its /// first argument, `x`, and the sign of its second argument, `y`. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn copysignf16(x: f16, y: f16) -> f16 { super::generic::copysign(x, y) } @@ -12,7 +12,7 @@ pub fn copysignf16(x: f16, y: f16) -> f16 { /// /// Constructs a number with the magnitude (absolute value) of its /// first argument, `x`, and the sign of its second argument, `y`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn copysignf(x: f32, y: f32) -> f32 { super::generic::copysign(x, y) } @@ -21,7 +21,7 @@ pub fn copysignf(x: f32, y: f32) -> f32 { /// /// Constructs a number with the magnitude (absolute value) of its /// first argument, `x`, and the sign of its second argument, `y`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn copysign(x: f64, y: f64) -> f64 { super::generic::copysign(x, y) } @@ -31,7 +31,7 @@ pub fn copysign(x: f64, y: f64) -> f64 { /// Constructs a number with the magnitude (absolute value) of its /// first argument, `x`, and the sign of its second argument, `y`. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn copysignf128(x: f128, y: f128) -> f128 { super::generic::copysign(x, y) } diff --git a/library/compiler-builtins/libm/src/math/cos.rs b/library/compiler-builtins/libm/src/math/cos.rs index de99cd4c5e45..b2f786323f4d 100644 --- a/library/compiler-builtins/libm/src/math/cos.rs +++ b/library/compiler-builtins/libm/src/math/cos.rs @@ -45,7 +45,7 @@ use super::{k_cos, k_sin, rem_pio2}; /// The cosine of `x` (f64). /// /// `x` is specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn cos(x: f64) -> f64 { let ix = (f64::to_bits(x) >> 32) as u32 & 0x7fffffff; diff --git a/library/compiler-builtins/libm/src/math/cosf.rs b/library/compiler-builtins/libm/src/math/cosf.rs index 27c2fc3b9945..bf5cb9196a36 100644 --- a/library/compiler-builtins/libm/src/math/cosf.rs +++ b/library/compiler-builtins/libm/src/math/cosf.rs @@ -27,7 +27,7 @@ const C4_PIO2: f64 = 4. * FRAC_PI_2; /* 0x401921FB, 0x54442D18 */ /// The cosine of `x` (f32). /// /// `x` is specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn cosf(x: f32) -> f32 { let x64 = x as f64; diff --git a/library/compiler-builtins/libm/src/math/cosh.rs b/library/compiler-builtins/libm/src/math/cosh.rs index d2e43fd6cb69..01081cfc77e0 100644 --- a/library/compiler-builtins/libm/src/math/cosh.rs +++ b/library/compiler-builtins/libm/src/math/cosh.rs @@ -5,7 +5,7 @@ use super::{exp, expm1, k_expo2}; /// Computes the hyperbolic cosine of the argument x. /// Is defined as `(exp(x) + exp(-x))/2` /// Angles are specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn cosh(mut x: f64) -> f64 { /* |x| */ let mut ix = x.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/coshf.rs b/library/compiler-builtins/libm/src/math/coshf.rs index 567a24410e79..dc039a3117cb 100644 --- a/library/compiler-builtins/libm/src/math/coshf.rs +++ b/library/compiler-builtins/libm/src/math/coshf.rs @@ -5,7 +5,7 @@ use super::{expf, expm1f, k_expo2f}; /// Computes the hyperbolic cosine of the argument x. /// Is defined as `(exp(x) + exp(-x))/2` /// Angles are specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn coshf(mut x: f32) -> f32 { let x1p120 = f32::from_bits(0x7b800000); // 0x1p120f === 2 ^ 120 diff --git a/library/compiler-builtins/libm/src/math/erf.rs b/library/compiler-builtins/libm/src/math/erf.rs index 5d82228a05fd..6c78440afcf5 100644 --- a/library/compiler-builtins/libm/src/math/erf.rs +++ b/library/compiler-builtins/libm/src/math/erf.rs @@ -219,7 +219,7 @@ fn erfc2(ix: u32, mut x: f64) -> f64 { /// Calculates an approximation to the “error function”, which estimates /// the probability that an observation will fall within x standard /// deviations of the mean (assuming a normal distribution). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn erf(x: f64) -> f64 { let r: f64; let s: f64; diff --git a/library/compiler-builtins/libm/src/math/erff.rs b/library/compiler-builtins/libm/src/math/erff.rs index fe15f01082e4..2a7680275b9f 100644 --- a/library/compiler-builtins/libm/src/math/erff.rs +++ b/library/compiler-builtins/libm/src/math/erff.rs @@ -130,7 +130,7 @@ fn erfc2(mut ix: u32, mut x: f32) -> f32 { /// Calculates an approximation to the “error function”, which estimates /// the probability that an observation will fall within x standard /// deviations of the mean (assuming a normal distribution). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn erff(x: f32) -> f32 { let r: f32; let s: f32; diff --git a/library/compiler-builtins/libm/src/math/exp.rs b/library/compiler-builtins/libm/src/math/exp.rs index 782042b62cd3..78ce5dd134ac 100644 --- a/library/compiler-builtins/libm/src/math/exp.rs +++ b/library/compiler-builtins/libm/src/math/exp.rs @@ -81,7 +81,7 @@ const P5: f64 = 4.13813679705723846039e-08; /* 0x3E663769, 0x72BEA4D0 */ /// /// Calculate the exponential of `x`, that is, *e* raised to the power `x` /// (where *e* is the base of the natural system of logarithms, approximately 2.71828). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn exp(mut x: f64) -> f64 { let x1p1023 = f64::from_bits(0x7fe0000000000000); // 0x1p1023 === 2 ^ 1023 let x1p_149 = f64::from_bits(0x36a0000000000000); // 0x1p-149 === 2 ^ -149 diff --git a/library/compiler-builtins/libm/src/math/exp10.rs b/library/compiler-builtins/libm/src/math/exp10.rs index 7c33c92b6032..1f49f5e96979 100644 --- a/library/compiler-builtins/libm/src/math/exp10.rs +++ b/library/compiler-builtins/libm/src/math/exp10.rs @@ -7,7 +7,7 @@ const P10: &[f64] = &[ ]; /// Calculates 10 raised to the power of `x` (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn exp10(x: f64) -> f64 { let (mut y, n) = modf(x); let u: u64 = n.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/exp10f.rs b/library/compiler-builtins/libm/src/math/exp10f.rs index 303045b33132..22a264211d03 100644 --- a/library/compiler-builtins/libm/src/math/exp10f.rs +++ b/library/compiler-builtins/libm/src/math/exp10f.rs @@ -7,7 +7,7 @@ const P10: &[f32] = &[ ]; /// Calculates 10 raised to the power of `x` (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn exp10f(x: f32) -> f32 { let (mut y, n) = modff(x); let u = n.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/exp2.rs b/library/compiler-builtins/libm/src/math/exp2.rs index 6e98d066cbfc..6e4cbc29dcc9 100644 --- a/library/compiler-builtins/libm/src/math/exp2.rs +++ b/library/compiler-builtins/libm/src/math/exp2.rs @@ -322,7 +322,7 @@ static TBL: [u64; TBLSIZE * 2] = [ /// Exponential, base 2 (f64) /// /// Calculate `2^x`, that is, 2 raised to the power `x`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn exp2(mut x: f64) -> f64 { let redux = f64::from_bits(0x4338000000000000) / TBLSIZE as f64; let p1 = f64::from_bits(0x3fe62e42fefa39ef); diff --git a/library/compiler-builtins/libm/src/math/exp2f.rs b/library/compiler-builtins/libm/src/math/exp2f.rs index f452b6a20f80..733d2f1a8473 100644 --- a/library/compiler-builtins/libm/src/math/exp2f.rs +++ b/library/compiler-builtins/libm/src/math/exp2f.rs @@ -73,7 +73,7 @@ static EXP2FT: [u64; TBLSIZE] = [ /// Exponential, base 2 (f32) /// /// Calculate `2^x`, that is, 2 raised to the power `x`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn exp2f(mut x: f32) -> f32 { let redux = f32::from_bits(0x4b400000) / TBLSIZE as f32; let p1 = f32::from_bits(0x3f317218); diff --git a/library/compiler-builtins/libm/src/math/expf.rs b/library/compiler-builtins/libm/src/math/expf.rs index 8dc067ab0846..dbbfdbba9253 100644 --- a/library/compiler-builtins/libm/src/math/expf.rs +++ b/library/compiler-builtins/libm/src/math/expf.rs @@ -30,7 +30,7 @@ const P2: f32 = -2.7667332906e-3; /* -0xb55215.0p-32 */ /// /// Calculate the exponential of `x`, that is, *e* raised to the power `x` /// (where *e* is the base of the natural system of logarithms, approximately 2.71828). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn expf(mut x: f32) -> f32 { let x1p127 = f32::from_bits(0x7f000000); // 0x1p127f === 2 ^ 127 let x1p_126 = f32::from_bits(0x800000); // 0x1p-126f === 2 ^ -126 /*original 0x1p-149f ??????????? */ diff --git a/library/compiler-builtins/libm/src/math/expm1.rs b/library/compiler-builtins/libm/src/math/expm1.rs index f25153f32a34..3714bf3afc93 100644 --- a/library/compiler-builtins/libm/src/math/expm1.rs +++ b/library/compiler-builtins/libm/src/math/expm1.rs @@ -30,7 +30,7 @@ const Q5: f64 = -2.01099218183624371326e-07; /* BE8AFDB7 6E09C32D */ /// system of logarithms, approximately 2.71828). /// The result is accurate even for small values of `x`, /// where using `exp(x)-1` would lose many significant digits. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn expm1(mut x: f64) -> f64 { let hi: f64; let lo: f64; diff --git a/library/compiler-builtins/libm/src/math/expm1f.rs b/library/compiler-builtins/libm/src/math/expm1f.rs index 63dc86e37c8c..f77515a4b99b 100644 --- a/library/compiler-builtins/libm/src/math/expm1f.rs +++ b/library/compiler-builtins/libm/src/math/expm1f.rs @@ -32,7 +32,7 @@ const Q2: f32 = 1.5807170421e-3; /* 0xcf3010.0p-33 */ /// system of logarithms, approximately 2.71828). /// The result is accurate even for small values of `x`, /// where using `exp(x)-1` would lose many significant digits. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn expm1f(mut x: f32) -> f32 { let x1p127 = f32::from_bits(0x7f000000); // 0x1p127f === 2 ^ 127 diff --git a/library/compiler-builtins/libm/src/math/expo2.rs b/library/compiler-builtins/libm/src/math/expo2.rs index 82e9b360a764..ce90858ec070 100644 --- a/library/compiler-builtins/libm/src/math/expo2.rs +++ b/library/compiler-builtins/libm/src/math/expo2.rs @@ -1,7 +1,7 @@ use super::{combine_words, exp}; /* exp(x)/2 for x >= log(DBL_MAX), slightly better than 0.5*exp(x/2)*exp(x/2) */ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn expo2(x: f64) -> f64 { /* k is such that k*ln2 has minimal relative error and x - kln2 > log(DBL_MIN) */ const K: i32 = 2043; diff --git a/library/compiler-builtins/libm/src/math/fabs.rs b/library/compiler-builtins/libm/src/math/fabs.rs index 0050a309fee5..7344e21a18bd 100644 --- a/library/compiler-builtins/libm/src/math/fabs.rs +++ b/library/compiler-builtins/libm/src/math/fabs.rs @@ -3,7 +3,7 @@ /// Calculates the absolute value (magnitude) of the argument `x`, /// by direct manipulation of the bit representation of `x`. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fabsf16(x: f16) -> f16 { super::generic::fabs(x) } @@ -12,7 +12,7 @@ pub fn fabsf16(x: f16) -> f16 { /// /// Calculates the absolute value (magnitude) of the argument `x`, /// by direct manipulation of the bit representation of `x`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fabsf(x: f32) -> f32 { select_implementation! { name: fabsf, @@ -27,7 +27,7 @@ pub fn fabsf(x: f32) -> f32 { /// /// Calculates the absolute value (magnitude) of the argument `x`, /// by direct manipulation of the bit representation of `x`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fabs(x: f64) -> f64 { select_implementation! { name: fabs, @@ -43,7 +43,7 @@ pub fn fabs(x: f64) -> f64 { /// Calculates the absolute value (magnitude) of the argument `x`, /// by direct manipulation of the bit representation of `x`. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fabsf128(x: f128) -> f128 { super::generic::fabs(x) } diff --git a/library/compiler-builtins/libm/src/math/fdim.rs b/library/compiler-builtins/libm/src/math/fdim.rs index 082c5478b2aa..dac409e86b13 100644 --- a/library/compiler-builtins/libm/src/math/fdim.rs +++ b/library/compiler-builtins/libm/src/math/fdim.rs @@ -7,7 +7,7 @@ /// /// A range error may occur. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fdimf16(x: f16, y: f16) -> f16 { super::generic::fdim(x, y) } @@ -20,7 +20,7 @@ pub fn fdimf16(x: f16, y: f16) -> f16 { /// * NAN if either argument is NAN. /// /// A range error may occur. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fdimf(x: f32, y: f32) -> f32 { super::generic::fdim(x, y) } @@ -33,7 +33,7 @@ pub fn fdimf(x: f32, y: f32) -> f32 { /// * NAN if either argument is NAN. /// /// A range error may occur. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fdim(x: f64, y: f64) -> f64 { super::generic::fdim(x, y) } @@ -47,7 +47,7 @@ pub fn fdim(x: f64, y: f64) -> f64 { /// /// A range error may occur. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fdimf128(x: f128, y: f128) -> f128 { super::generic::fdim(x, y) } diff --git a/library/compiler-builtins/libm/src/math/floor.rs b/library/compiler-builtins/libm/src/math/floor.rs index 3c5eab101d18..7241c427f646 100644 --- a/library/compiler-builtins/libm/src/math/floor.rs +++ b/library/compiler-builtins/libm/src/math/floor.rs @@ -2,7 +2,7 @@ /// /// Finds the nearest integer less than or equal to `x`. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn floorf16(x: f16) -> f16 { return super::generic::floor(x); } @@ -10,7 +10,7 @@ pub fn floorf16(x: f16) -> f16 { /// Floor (f64) /// /// Finds the nearest integer less than or equal to `x`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn floor(x: f64) -> f64 { select_implementation! { name: floor, @@ -25,7 +25,7 @@ pub fn floor(x: f64) -> f64 { /// Floor (f32) /// /// Finds the nearest integer less than or equal to `x`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn floorf(x: f32) -> f32 { select_implementation! { name: floorf, @@ -40,7 +40,7 @@ pub fn floorf(x: f32) -> f32 { /// /// Finds the nearest integer less than or equal to `x`. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn floorf128(x: f128) -> f128 { return super::generic::floor(x); } diff --git a/library/compiler-builtins/libm/src/math/fma.rs b/library/compiler-builtins/libm/src/math/fma.rs index 5bf473cfe063..70e6de768fab 100644 --- a/library/compiler-builtins/libm/src/math/fma.rs +++ b/library/compiler-builtins/libm/src/math/fma.rs @@ -7,7 +7,7 @@ use crate::support::Round; // Placeholder so we can have `fmaf16` in the `Float` trait. #[allow(unused)] #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn fmaf16(_x: f16, _y: f16, _z: f16) -> f16 { unimplemented!() } @@ -15,7 +15,7 @@ pub(crate) fn fmaf16(_x: f16, _y: f16, _z: f16) -> f16 { /// Floating multiply add (f32) /// /// Computes `(x*y)+z`, rounded as one ternary operation (i.e. calculated with infinite precision). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaf(x: f32, y: f32, z: f32) -> f32 { select_implementation! { name: fmaf, @@ -32,7 +32,7 @@ pub fn fmaf(x: f32, y: f32, z: f32) -> f32 { /// Fused multiply add (f64) /// /// Computes `(x*y)+z`, rounded as one ternary operation (i.e. calculated with infinite precision). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fma(x: f64, y: f64, z: f64) -> f64 { select_implementation! { name: fma, @@ -50,7 +50,7 @@ pub fn fma(x: f64, y: f64, z: f64) -> f64 { /// /// Computes `(x*y)+z`, rounded as one ternary operation (i.e. calculated with infinite precision). #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaf128(x: f128, y: f128, z: f128) -> f128 { generic::fma_round(x, y, z, Round::Nearest).val } diff --git a/library/compiler-builtins/libm/src/math/fmin_fmax.rs b/library/compiler-builtins/libm/src/math/fmin_fmax.rs index 481301994e99..c4c1b0435dd2 100644 --- a/library/compiler-builtins/libm/src/math/fmin_fmax.rs +++ b/library/compiler-builtins/libm/src/math/fmin_fmax.rs @@ -3,7 +3,7 @@ /// This coincides with IEEE 754-2011 `minNum`. The result disregards signed zero (meaning if /// the inputs are -0.0 and +0.0, either may be returned). #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminf16(x: f16, y: f16) -> f16 { super::generic::fmin(x, y) } @@ -12,7 +12,7 @@ pub fn fminf16(x: f16, y: f16) -> f16 { /// /// This coincides with IEEE 754-2011 `minNum`. The result disregards signed zero (meaning if /// the inputs are -0.0 and +0.0, either may be returned). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminf(x: f32, y: f32) -> f32 { super::generic::fmin(x, y) } @@ -21,7 +21,7 @@ pub fn fminf(x: f32, y: f32) -> f32 { /// /// This coincides with IEEE 754-2011 `minNum`. The result disregards signed zero (meaning if /// the inputs are -0.0 and +0.0, either may be returned). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmin(x: f64, y: f64) -> f64 { super::generic::fmin(x, y) } @@ -31,7 +31,7 @@ pub fn fmin(x: f64, y: f64) -> f64 { /// This coincides with IEEE 754-2011 `minNum`. The result disregards signed zero (meaning if /// the inputs are -0.0 and +0.0, either may be returned). #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminf128(x: f128, y: f128) -> f128 { super::generic::fmin(x, y) } @@ -41,7 +41,7 @@ pub fn fminf128(x: f128, y: f128) -> f128 { /// This coincides with IEEE 754-2011 `maxNum`. The result disregards signed zero (meaning if /// the inputs are -0.0 and +0.0, either may be returned). #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaxf16(x: f16, y: f16) -> f16 { super::generic::fmax(x, y) } @@ -50,7 +50,7 @@ pub fn fmaxf16(x: f16, y: f16) -> f16 { /// /// This coincides with IEEE 754-2011 `maxNum`. The result disregards signed zero (meaning if /// the inputs are -0.0 and +0.0, either may be returned). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaxf(x: f32, y: f32) -> f32 { super::generic::fmax(x, y) } @@ -59,7 +59,7 @@ pub fn fmaxf(x: f32, y: f32) -> f32 { /// /// This coincides with IEEE 754-2011 `maxNum`. The result disregards signed zero (meaning if /// the inputs are -0.0 and +0.0, either may be returned). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmax(x: f64, y: f64) -> f64 { super::generic::fmax(x, y) } @@ -69,7 +69,7 @@ pub fn fmax(x: f64, y: f64) -> f64 { /// This coincides with IEEE 754-2011 `maxNum`. The result disregards signed zero (meaning if /// the inputs are -0.0 and +0.0, either may be returned). #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaxf128(x: f128, y: f128) -> f128 { super::generic::fmax(x, y) } diff --git a/library/compiler-builtins/libm/src/math/fminimum_fmaximum.rs b/library/compiler-builtins/libm/src/math/fminimum_fmaximum.rs index 8f1308670511..a3c9c9c3991b 100644 --- a/library/compiler-builtins/libm/src/math/fminimum_fmaximum.rs +++ b/library/compiler-builtins/libm/src/math/fminimum_fmaximum.rs @@ -2,7 +2,7 @@ /// /// This coincides with IEEE 754-2019 `minimum`. The result orders -0.0 < 0.0. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminimumf16(x: f16, y: f16) -> f16 { super::generic::fminimum(x, y) } @@ -10,7 +10,7 @@ pub fn fminimumf16(x: f16, y: f16) -> f16 { /// Return the lesser of two arguments or, if either argument is NaN, the other argument. /// /// This coincides with IEEE 754-2019 `minimum`. The result orders -0.0 < 0.0. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminimum(x: f64, y: f64) -> f64 { super::generic::fminimum(x, y) } @@ -18,7 +18,7 @@ pub fn fminimum(x: f64, y: f64) -> f64 { /// Return the lesser of two arguments or, if either argument is NaN, the other argument. /// /// This coincides with IEEE 754-2019 `minimum`. The result orders -0.0 < 0.0. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminimumf(x: f32, y: f32) -> f32 { super::generic::fminimum(x, y) } @@ -27,7 +27,7 @@ pub fn fminimumf(x: f32, y: f32) -> f32 { /// /// This coincides with IEEE 754-2019 `minimum`. The result orders -0.0 < 0.0. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminimumf128(x: f128, y: f128) -> f128 { super::generic::fminimum(x, y) } @@ -36,7 +36,7 @@ pub fn fminimumf128(x: f128, y: f128) -> f128 { /// /// This coincides with IEEE 754-2019 `maximum`. The result orders -0.0 < 0.0. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaximumf16(x: f16, y: f16) -> f16 { super::generic::fmaximum(x, y) } @@ -44,7 +44,7 @@ pub fn fmaximumf16(x: f16, y: f16) -> f16 { /// Return the greater of two arguments or, if either argument is NaN, the other argument. /// /// This coincides with IEEE 754-2019 `maximum`. The result orders -0.0 < 0.0. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaximumf(x: f32, y: f32) -> f32 { super::generic::fmaximum(x, y) } @@ -52,7 +52,7 @@ pub fn fmaximumf(x: f32, y: f32) -> f32 { /// Return the greater of two arguments or, if either argument is NaN, the other argument. /// /// This coincides with IEEE 754-2019 `maximum`. The result orders -0.0 < 0.0. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaximum(x: f64, y: f64) -> f64 { super::generic::fmaximum(x, y) } @@ -61,7 +61,7 @@ pub fn fmaximum(x: f64, y: f64) -> f64 { /// /// This coincides with IEEE 754-2019 `maximum`. The result orders -0.0 < 0.0. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaximumf128(x: f128, y: f128) -> f128 { super::generic::fmaximum(x, y) } diff --git a/library/compiler-builtins/libm/src/math/fminimum_fmaximum_num.rs b/library/compiler-builtins/libm/src/math/fminimum_fmaximum_num.rs index fadf934180a0..612cefe756e3 100644 --- a/library/compiler-builtins/libm/src/math/fminimum_fmaximum_num.rs +++ b/library/compiler-builtins/libm/src/math/fminimum_fmaximum_num.rs @@ -2,7 +2,7 @@ /// /// This coincides with IEEE 754-2019 `minimumNumber`. The result orders -0.0 < 0.0. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminimum_numf16(x: f16, y: f16) -> f16 { super::generic::fminimum_num(x, y) } @@ -10,7 +10,7 @@ pub fn fminimum_numf16(x: f16, y: f16) -> f16 { /// Return the lesser of two arguments or, if either argument is NaN, NaN. /// /// This coincides with IEEE 754-2019 `minimumNumber`. The result orders -0.0 < 0.0. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminimum_numf(x: f32, y: f32) -> f32 { super::generic::fminimum_num(x, y) } @@ -18,7 +18,7 @@ pub fn fminimum_numf(x: f32, y: f32) -> f32 { /// Return the lesser of two arguments or, if either argument is NaN, NaN. /// /// This coincides with IEEE 754-2019 `minimumNumber`. The result orders -0.0 < 0.0. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminimum_num(x: f64, y: f64) -> f64 { super::generic::fminimum_num(x, y) } @@ -27,7 +27,7 @@ pub fn fminimum_num(x: f64, y: f64) -> f64 { /// /// This coincides with IEEE 754-2019 `minimumNumber`. The result orders -0.0 < 0.0. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fminimum_numf128(x: f128, y: f128) -> f128 { super::generic::fminimum_num(x, y) } @@ -36,7 +36,7 @@ pub fn fminimum_numf128(x: f128, y: f128) -> f128 { /// /// This coincides with IEEE 754-2019 `maximumNumber`. The result orders -0.0 < 0.0. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaximum_numf16(x: f16, y: f16) -> f16 { super::generic::fmaximum_num(x, y) } @@ -44,7 +44,7 @@ pub fn fmaximum_numf16(x: f16, y: f16) -> f16 { /// Return the greater of two arguments or, if either argument is NaN, NaN. /// /// This coincides with IEEE 754-2019 `maximumNumber`. The result orders -0.0 < 0.0. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaximum_numf(x: f32, y: f32) -> f32 { super::generic::fmaximum_num(x, y) } @@ -52,7 +52,7 @@ pub fn fmaximum_numf(x: f32, y: f32) -> f32 { /// Return the greater of two arguments or, if either argument is NaN, NaN. /// /// This coincides with IEEE 754-2019 `maximumNumber`. The result orders -0.0 < 0.0. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaximum_num(x: f64, y: f64) -> f64 { super::generic::fmaximum_num(x, y) } @@ -61,7 +61,7 @@ pub fn fmaximum_num(x: f64, y: f64) -> f64 { /// /// This coincides with IEEE 754-2019 `maximumNumber`. The result orders -0.0 < 0.0. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmaximum_numf128(x: f128, y: f128) -> f128 { super::generic::fmaximum_num(x, y) } diff --git a/library/compiler-builtins/libm/src/math/fmod.rs b/library/compiler-builtins/libm/src/math/fmod.rs index c4752b92578f..6ae1be560835 100644 --- a/library/compiler-builtins/libm/src/math/fmod.rs +++ b/library/compiler-builtins/libm/src/math/fmod.rs @@ -1,25 +1,25 @@ /// Calculate the remainder of `x / y`, the precise result of `x - trunc(x / y) * y`. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmodf16(x: f16, y: f16) -> f16 { super::generic::fmod(x, y) } /// Calculate the remainder of `x / y`, the precise result of `x - trunc(x / y) * y`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmodf(x: f32, y: f32) -> f32 { super::generic::fmod(x, y) } /// Calculate the remainder of `x / y`, the precise result of `x - trunc(x / y) * y`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmod(x: f64, y: f64) -> f64 { super::generic::fmod(x, y) } /// Calculate the remainder of `x / y`, the precise result of `x - trunc(x / y) * y`. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn fmodf128(x: f128, y: f128) -> f128 { super::generic::fmod(x, y) } diff --git a/library/compiler-builtins/libm/src/math/frexp.rs b/library/compiler-builtins/libm/src/math/frexp.rs index de7a64fdae1a..932111eebc95 100644 --- a/library/compiler-builtins/libm/src/math/frexp.rs +++ b/library/compiler-builtins/libm/src/math/frexp.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn frexp(x: f64) -> (f64, i32) { let mut y = x.to_bits(); let ee = ((y >> 52) & 0x7ff) as i32; diff --git a/library/compiler-builtins/libm/src/math/frexpf.rs b/library/compiler-builtins/libm/src/math/frexpf.rs index 0ec91c2d3507..904bf14f7b8e 100644 --- a/library/compiler-builtins/libm/src/math/frexpf.rs +++ b/library/compiler-builtins/libm/src/math/frexpf.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn frexpf(x: f32) -> (f32, i32) { let mut y = x.to_bits(); let ee: i32 = ((y >> 23) & 0xff) as i32; diff --git a/library/compiler-builtins/libm/src/math/hypot.rs b/library/compiler-builtins/libm/src/math/hypot.rs index da458ea1d05f..b92ee18ca110 100644 --- a/library/compiler-builtins/libm/src/math/hypot.rs +++ b/library/compiler-builtins/libm/src/math/hypot.rs @@ -17,7 +17,7 @@ fn sq(x: f64) -> (f64, f64) { (hi, lo) } -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn hypot(mut x: f64, mut y: f64) -> f64 { let x1p700 = f64::from_bits(0x6bb0000000000000); // 0x1p700 === 2 ^ 700 let x1p_700 = f64::from_bits(0x1430000000000000); // 0x1p-700 === 2 ^ -700 diff --git a/library/compiler-builtins/libm/src/math/hypotf.rs b/library/compiler-builtins/libm/src/math/hypotf.rs index 576eebb33431..e7635ffc9a0b 100644 --- a/library/compiler-builtins/libm/src/math/hypotf.rs +++ b/library/compiler-builtins/libm/src/math/hypotf.rs @@ -2,7 +2,7 @@ use core::f32; use super::sqrtf; -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn hypotf(mut x: f32, mut y: f32) -> f32 { let x1p90 = f32::from_bits(0x6c800000); // 0x1p90f === 2 ^ 90 let x1p_90 = f32::from_bits(0x12800000); // 0x1p-90f === 2 ^ -90 diff --git a/library/compiler-builtins/libm/src/math/ilogb.rs b/library/compiler-builtins/libm/src/math/ilogb.rs index 5b41f7b1dc0b..ef774f6ad3a6 100644 --- a/library/compiler-builtins/libm/src/math/ilogb.rs +++ b/library/compiler-builtins/libm/src/math/ilogb.rs @@ -1,7 +1,7 @@ const FP_ILOGBNAN: i32 = -1 - 0x7fffffff; const FP_ILOGB0: i32 = FP_ILOGBNAN; -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ilogb(x: f64) -> i32 { let mut i: u64 = x.to_bits(); let e = ((i >> 52) & 0x7ff) as i32; diff --git a/library/compiler-builtins/libm/src/math/ilogbf.rs b/library/compiler-builtins/libm/src/math/ilogbf.rs index 3585d6d36f16..5b0cb46ec558 100644 --- a/library/compiler-builtins/libm/src/math/ilogbf.rs +++ b/library/compiler-builtins/libm/src/math/ilogbf.rs @@ -1,7 +1,7 @@ const FP_ILOGBNAN: i32 = -1 - 0x7fffffff; const FP_ILOGB0: i32 = FP_ILOGBNAN; -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ilogbf(x: f32) -> i32 { let mut i = x.to_bits(); let e = ((i >> 23) & 0xff) as i32; diff --git a/library/compiler-builtins/libm/src/math/j0.rs b/library/compiler-builtins/libm/src/math/j0.rs index 99d656f0d08a..7b0800477b3c 100644 --- a/library/compiler-builtins/libm/src/math/j0.rs +++ b/library/compiler-builtins/libm/src/math/j0.rs @@ -110,7 +110,7 @@ const S03: f64 = 5.13546550207318111446e-07; /* 0x3EA13B54, 0xCE84D5A9 */ const S04: f64 = 1.16614003333790000205e-09; /* 0x3E1408BC, 0xF4745D8F */ /// Zeroth order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the first kind (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn j0(mut x: f64) -> f64 { let z: f64; let r: f64; @@ -165,7 +165,7 @@ const V03: f64 = 2.59150851840457805467e-07; /* 0x3E91642D, 0x7FF202FD */ const V04: f64 = 4.41110311332675467403e-10; /* 0x3DFE5018, 0x3BD6D9EF */ /// Zeroth order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the second kind (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn y0(x: f64) -> f64 { let z: f64; let u: f64; diff --git a/library/compiler-builtins/libm/src/math/j0f.rs b/library/compiler-builtins/libm/src/math/j0f.rs index 25e5b325c8cc..1c6a7c344623 100644 --- a/library/compiler-builtins/libm/src/math/j0f.rs +++ b/library/compiler-builtins/libm/src/math/j0f.rs @@ -63,7 +63,7 @@ const S03: f32 = 5.1354652442e-07; /* 0x3509daa6 */ const S04: f32 = 1.1661400734e-09; /* 0x30a045e8 */ /// Zeroth order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the first kind (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn j0f(mut x: f32) -> f32 { let z: f32; let r: f32; @@ -110,7 +110,7 @@ const V03: f32 = 2.5915085189e-07; /* 0x348b216c */ const V04: f32 = 4.4111031494e-10; /* 0x2ff280c2 */ /// Zeroth order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the second kind (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn y0f(x: f32) -> f32 { let z: f32; let u: f32; diff --git a/library/compiler-builtins/libm/src/math/j1.rs b/library/compiler-builtins/libm/src/math/j1.rs index 9b604d9e46e0..7d304ba10b7b 100644 --- a/library/compiler-builtins/libm/src/math/j1.rs +++ b/library/compiler-builtins/libm/src/math/j1.rs @@ -114,7 +114,7 @@ const S04: f64 = 5.04636257076217042715e-09; /* 0x3E35AC88, 0xC97DFF2C */ const S05: f64 = 1.23542274426137913908e-11; /* 0x3DAB2ACF, 0xCFB97ED8 */ /// First order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the first kind (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn j1(x: f64) -> f64 { let mut z: f64; let r: f64; @@ -161,7 +161,7 @@ const V0: [f64; 5] = [ ]; /// First order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the second kind (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn y1(x: f64) -> f64 { let z: f64; let u: f64; diff --git a/library/compiler-builtins/libm/src/math/j1f.rs b/library/compiler-builtins/libm/src/math/j1f.rs index da5413ac2f5b..cd829c1aa121 100644 --- a/library/compiler-builtins/libm/src/math/j1f.rs +++ b/library/compiler-builtins/libm/src/math/j1f.rs @@ -64,7 +64,7 @@ const S04: f32 = 5.0463624390e-09; /* 0x31ad6446 */ const S05: f32 = 1.2354227016e-11; /* 0x2d59567e */ /// First order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the first kind (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn j1f(x: f32) -> f32 { let mut z: f32; let r: f32; @@ -110,7 +110,7 @@ const V0: [f32; 5] = [ ]; /// First order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the second kind (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn y1f(x: f32) -> f32 { let z: f32; let u: f32; diff --git a/library/compiler-builtins/libm/src/math/jn.rs b/library/compiler-builtins/libm/src/math/jn.rs index 31f8d9c53829..b87aeaf1cc3d 100644 --- a/library/compiler-builtins/libm/src/math/jn.rs +++ b/library/compiler-builtins/libm/src/math/jn.rs @@ -39,7 +39,7 @@ use super::{cos, fabs, get_high_word, get_low_word, j0, j1, log, sin, sqrt, y0, const INVSQRTPI: f64 = 5.64189583547756279280e-01; /* 0x3FE20DD7, 0x50429B6D */ /// Integer order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the first kind (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn jn(n: i32, mut x: f64) -> f64 { let mut ix: u32; let lx: u32; @@ -249,7 +249,7 @@ pub fn jn(n: i32, mut x: f64) -> f64 { } /// Integer order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the second kind (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn yn(n: i32, x: f64) -> f64 { let mut ix: u32; let lx: u32; diff --git a/library/compiler-builtins/libm/src/math/jnf.rs b/library/compiler-builtins/libm/src/math/jnf.rs index 52cf7d8a8bda..34fdc5112dce 100644 --- a/library/compiler-builtins/libm/src/math/jnf.rs +++ b/library/compiler-builtins/libm/src/math/jnf.rs @@ -16,7 +16,7 @@ use super::{fabsf, j0f, j1f, logf, y0f, y1f}; /// Integer order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the first kind (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn jnf(n: i32, mut x: f32) -> f32 { let mut ix: u32; let mut nm1: i32; @@ -192,7 +192,7 @@ pub fn jnf(n: i32, mut x: f32) -> f32 { } /// Integer order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the second kind (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ynf(n: i32, x: f32) -> f32 { let mut ix: u32; let mut ib: u32; diff --git a/library/compiler-builtins/libm/src/math/k_cos.rs b/library/compiler-builtins/libm/src/math/k_cos.rs index 49b2fc64d864..1a2ebabe3343 100644 --- a/library/compiler-builtins/libm/src/math/k_cos.rs +++ b/library/compiler-builtins/libm/src/math/k_cos.rs @@ -51,7 +51,7 @@ const C6: f64 = -1.13596475577881948265e-11; /* 0xBDA8FAE9, 0xBE8838D4 */ // expression for cos(). Retention happens in all cases tested // under FreeBSD, so don't pessimize things by forcibly clipping // any extra precision in w. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn k_cos(x: f64, y: f64) -> f64 { let z = x * x; let w = z * z; diff --git a/library/compiler-builtins/libm/src/math/k_cosf.rs b/library/compiler-builtins/libm/src/math/k_cosf.rs index e99f2348c00d..68f568c24257 100644 --- a/library/compiler-builtins/libm/src/math/k_cosf.rs +++ b/library/compiler-builtins/libm/src/math/k_cosf.rs @@ -20,7 +20,7 @@ const C1: f64 = 0.0416666233237390631894; /* 0x155553e1053a42.0p-57 */ const C2: f64 = -0.00138867637746099294692; /* -0x16c087e80f1e27.0p-62 */ const C3: f64 = 0.0000243904487962774090654; /* 0x199342e0ee5069.0p-68 */ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn k_cosf(x: f64) -> f32 { let z = x * x; let w = z * z; diff --git a/library/compiler-builtins/libm/src/math/k_expo2.rs b/library/compiler-builtins/libm/src/math/k_expo2.rs index 7345075f3768..7b63952d255f 100644 --- a/library/compiler-builtins/libm/src/math/k_expo2.rs +++ b/library/compiler-builtins/libm/src/math/k_expo2.rs @@ -4,7 +4,7 @@ use super::exp; const K: i32 = 2043; /* expf(x)/2 for x >= log(FLT_MAX), slightly better than 0.5f*expf(x/2)*expf(x/2) */ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn k_expo2(x: f64) -> f64 { let k_ln2 = f64::from_bits(0x40962066151add8b); /* note that k is odd and scale*scale overflows */ diff --git a/library/compiler-builtins/libm/src/math/k_expo2f.rs b/library/compiler-builtins/libm/src/math/k_expo2f.rs index fbd7b27d5832..02213cec4549 100644 --- a/library/compiler-builtins/libm/src/math/k_expo2f.rs +++ b/library/compiler-builtins/libm/src/math/k_expo2f.rs @@ -4,7 +4,7 @@ use super::expf; const K: i32 = 235; /* expf(x)/2 for x >= log(FLT_MAX), slightly better than 0.5f*expf(x/2)*expf(x/2) */ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn k_expo2f(x: f32) -> f32 { let k_ln2 = f32::from_bits(0x4322e3bc); /* note that k is odd and scale*scale overflows */ diff --git a/library/compiler-builtins/libm/src/math/k_sin.rs b/library/compiler-builtins/libm/src/math/k_sin.rs index 9dd96c944744..2f8542945136 100644 --- a/library/compiler-builtins/libm/src/math/k_sin.rs +++ b/library/compiler-builtins/libm/src/math/k_sin.rs @@ -43,7 +43,7 @@ const S6: f64 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */ // r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6)))) // then 3 2 // sin(x) = x + (S1*x + (x *(r-y/2)+y)) -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn k_sin(x: f64, y: f64, iy: i32) -> f64 { let z = x * x; let w = z * z; diff --git a/library/compiler-builtins/libm/src/math/k_sinf.rs b/library/compiler-builtins/libm/src/math/k_sinf.rs index 88d10cababc5..297d88bbbbe1 100644 --- a/library/compiler-builtins/libm/src/math/k_sinf.rs +++ b/library/compiler-builtins/libm/src/math/k_sinf.rs @@ -20,7 +20,7 @@ const S2: f64 = 0.0083333293858894631756; /* 0x111110896efbb2.0p-59 */ const S3: f64 = -0.000198393348360966317347; /* -0x1a00f9e2cae774.0p-65 */ const S4: f64 = 0.0000027183114939898219064; /* 0x16cd878c3b46a7.0p-71 */ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn k_sinf(x: f64) -> f32 { let z = x * x; let w = z * z; diff --git a/library/compiler-builtins/libm/src/math/k_tan.rs b/library/compiler-builtins/libm/src/math/k_tan.rs index d177010bb0a0..ac48d661fd62 100644 --- a/library/compiler-builtins/libm/src/math/k_tan.rs +++ b/library/compiler-builtins/libm/src/math/k_tan.rs @@ -58,7 +58,7 @@ static T: [f64; 13] = [ const PIO4: f64 = 7.85398163397448278999e-01; /* 3FE921FB, 54442D18 */ const PIO4_LO: f64 = 3.06161699786838301793e-17; /* 3C81A626, 33145C07 */ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn k_tan(mut x: f64, mut y: f64, odd: i32) -> f64 { let hx = (f64::to_bits(x) >> 32) as u32; let big = (hx & 0x7fffffff) >= 0x3FE59428; /* |x| >= 0.6744 */ diff --git a/library/compiler-builtins/libm/src/math/k_tanf.rs b/library/compiler-builtins/libm/src/math/k_tanf.rs index af8db539dad4..79382f57bf68 100644 --- a/library/compiler-builtins/libm/src/math/k_tanf.rs +++ b/library/compiler-builtins/libm/src/math/k_tanf.rs @@ -19,7 +19,7 @@ const T: [f64; 6] = [ 0.00946564784943673166728, /* 0x1362b9bf971bcd.0p-59 */ ]; -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn k_tanf(x: f64, odd: bool) -> f32 { let z = x * x; /* diff --git a/library/compiler-builtins/libm/src/math/ldexp.rs b/library/compiler-builtins/libm/src/math/ldexp.rs index 24899ba306af..b32b8d5241b1 100644 --- a/library/compiler-builtins/libm/src/math/ldexp.rs +++ b/library/compiler-builtins/libm/src/math/ldexp.rs @@ -1,21 +1,21 @@ #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ldexpf16(x: f16, n: i32) -> f16 { super::scalbnf16(x, n) } -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ldexpf(x: f32, n: i32) -> f32 { super::scalbnf(x, n) } -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ldexp(x: f64, n: i32) -> f64 { super::scalbn(x, n) } #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn ldexpf128(x: f128, n: i32) -> f128 { super::scalbnf128(x, n) } diff --git a/library/compiler-builtins/libm/src/math/lgamma.rs b/library/compiler-builtins/libm/src/math/lgamma.rs index 8312dc18648e..da7ce5c983b9 100644 --- a/library/compiler-builtins/libm/src/math/lgamma.rs +++ b/library/compiler-builtins/libm/src/math/lgamma.rs @@ -2,7 +2,7 @@ use super::lgamma_r; /// The natural logarithm of the /// [Gamma function](https://en.wikipedia.org/wiki/Gamma_function) (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn lgamma(x: f64) -> f64 { lgamma_r(x).0 } diff --git a/library/compiler-builtins/libm/src/math/lgamma_r.rs b/library/compiler-builtins/libm/src/math/lgamma_r.rs index 6becaad2ce91..38eb270f6839 100644 --- a/library/compiler-builtins/libm/src/math/lgamma_r.rs +++ b/library/compiler-builtins/libm/src/math/lgamma_r.rs @@ -165,7 +165,7 @@ fn sin_pi(mut x: f64) -> f64 { } } -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn lgamma_r(mut x: f64) -> (f64, i32) { let u: u64 = x.to_bits(); let mut t: f64; diff --git a/library/compiler-builtins/libm/src/math/lgammaf.rs b/library/compiler-builtins/libm/src/math/lgammaf.rs index d37512397cb3..920acfed2a05 100644 --- a/library/compiler-builtins/libm/src/math/lgammaf.rs +++ b/library/compiler-builtins/libm/src/math/lgammaf.rs @@ -2,7 +2,7 @@ use super::lgammaf_r; /// The natural logarithm of the /// [Gamma function](https://en.wikipedia.org/wiki/Gamma_function) (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn lgammaf(x: f32) -> f32 { lgammaf_r(x).0 } diff --git a/library/compiler-builtins/libm/src/math/lgammaf_r.rs b/library/compiler-builtins/libm/src/math/lgammaf_r.rs index 10cecee541cc..a0b6a678a670 100644 --- a/library/compiler-builtins/libm/src/math/lgammaf_r.rs +++ b/library/compiler-builtins/libm/src/math/lgammaf_r.rs @@ -100,7 +100,7 @@ fn sin_pi(mut x: f32) -> f32 { } } -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn lgammaf_r(mut x: f32) -> (f32, i32) { let u = x.to_bits(); let mut t: f32; diff --git a/library/compiler-builtins/libm/src/math/log.rs b/library/compiler-builtins/libm/src/math/log.rs index f2dc47ec5ccf..9499c56d8ade 100644 --- a/library/compiler-builtins/libm/src/math/log.rs +++ b/library/compiler-builtins/libm/src/math/log.rs @@ -71,7 +71,7 @@ const LG6: f64 = 1.531383769920937332e-01; /* 3FC39A09 D078C69F */ const LG7: f64 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ /// The natural logarithm of `x` (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn log(mut x: f64) -> f64 { let x1p54 = f64::from_bits(0x4350000000000000); // 0x1p54 === 2 ^ 54 diff --git a/library/compiler-builtins/libm/src/math/log10.rs b/library/compiler-builtins/libm/src/math/log10.rs index 8c9d68c492db..29f25d944af9 100644 --- a/library/compiler-builtins/libm/src/math/log10.rs +++ b/library/compiler-builtins/libm/src/math/log10.rs @@ -32,7 +32,7 @@ const LG6: f64 = 1.531383769920937332e-01; /* 3FC39A09 D078C69F */ const LG7: f64 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ /// The base 10 logarithm of `x` (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn log10(mut x: f64) -> f64 { let x1p54 = f64::from_bits(0x4350000000000000); // 0x1p54 === 2 ^ 54 diff --git a/library/compiler-builtins/libm/src/math/log10f.rs b/library/compiler-builtins/libm/src/math/log10f.rs index 18bf8fcc8320..f89584bf9c99 100644 --- a/library/compiler-builtins/libm/src/math/log10f.rs +++ b/library/compiler-builtins/libm/src/math/log10f.rs @@ -26,7 +26,7 @@ const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */ const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */ /// The base 10 logarithm of `x` (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn log10f(mut x: f32) -> f32 { let x1p25f = f32::from_bits(0x4c000000); // 0x1p25f === 2 ^ 25 diff --git a/library/compiler-builtins/libm/src/math/log1p.rs b/library/compiler-builtins/libm/src/math/log1p.rs index 65142c0d622c..c991cce60df0 100644 --- a/library/compiler-builtins/libm/src/math/log1p.rs +++ b/library/compiler-builtins/libm/src/math/log1p.rs @@ -66,7 +66,7 @@ const LG6: f64 = 1.531383769920937332e-01; /* 3FC39A09 D078C69F */ const LG7: f64 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ /// The natural logarithm of 1+`x` (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn log1p(x: f64) -> f64 { let mut ui: u64 = x.to_bits(); let hfsq: f64; diff --git a/library/compiler-builtins/libm/src/math/log1pf.rs b/library/compiler-builtins/libm/src/math/log1pf.rs index 23978e61c3c4..89a92fac98ee 100644 --- a/library/compiler-builtins/libm/src/math/log1pf.rs +++ b/library/compiler-builtins/libm/src/math/log1pf.rs @@ -21,7 +21,7 @@ const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */ const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */ /// The natural logarithm of 1+`x` (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn log1pf(x: f32) -> f32 { let mut ui: u32 = x.to_bits(); let hfsq: f32; diff --git a/library/compiler-builtins/libm/src/math/log2.rs b/library/compiler-builtins/libm/src/math/log2.rs index 701f63c25e72..9b750c9a2a6c 100644 --- a/library/compiler-builtins/libm/src/math/log2.rs +++ b/library/compiler-builtins/libm/src/math/log2.rs @@ -30,7 +30,7 @@ const LG6: f64 = 1.531383769920937332e-01; /* 3FC39A09 D078C69F */ const LG7: f64 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ /// The base 2 logarithm of `x` (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn log2(mut x: f64) -> f64 { let x1p54 = f64::from_bits(0x4350000000000000); // 0x1p54 === 2 ^ 54 diff --git a/library/compiler-builtins/libm/src/math/log2f.rs b/library/compiler-builtins/libm/src/math/log2f.rs index 5ba2427d1d46..0e5177d7afa8 100644 --- a/library/compiler-builtins/libm/src/math/log2f.rs +++ b/library/compiler-builtins/libm/src/math/log2f.rs @@ -24,7 +24,7 @@ const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */ const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */ /// The base 2 logarithm of `x` (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn log2f(mut x: f32) -> f32 { let x1p25f = f32::from_bits(0x4c000000); // 0x1p25f === 2 ^ 25 diff --git a/library/compiler-builtins/libm/src/math/logf.rs b/library/compiler-builtins/libm/src/math/logf.rs index 68d1943025e3..cd7a7b0ba00d 100644 --- a/library/compiler-builtins/libm/src/math/logf.rs +++ b/library/compiler-builtins/libm/src/math/logf.rs @@ -22,7 +22,7 @@ const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */ const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */ /// The natural logarithm of `x` (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn logf(mut x: f32) -> f32 { let x1p25 = f32::from_bits(0x4c000000); // 0x1p25f === 2 ^ 25 diff --git a/library/compiler-builtins/libm/src/math/modf.rs b/library/compiler-builtins/libm/src/math/modf.rs index 6541862cdd98..a92a83dc5d10 100644 --- a/library/compiler-builtins/libm/src/math/modf.rs +++ b/library/compiler-builtins/libm/src/math/modf.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn modf(x: f64) -> (f64, f64) { let rv2: f64; let mut u = x.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/modff.rs b/library/compiler-builtins/libm/src/math/modff.rs index 90c6bca7d8da..691f351ca8d7 100644 --- a/library/compiler-builtins/libm/src/math/modff.rs +++ b/library/compiler-builtins/libm/src/math/modff.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn modff(x: f32) -> (f32, f32) { let rv2: f32; let mut u: u32 = x.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/nextafter.rs b/library/compiler-builtins/libm/src/math/nextafter.rs index c991ff6f2330..f4408468cc92 100644 --- a/library/compiler-builtins/libm/src/math/nextafter.rs +++ b/library/compiler-builtins/libm/src/math/nextafter.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn nextafter(x: f64, y: f64) -> f64 { if x.is_nan() || y.is_nan() { return x + y; diff --git a/library/compiler-builtins/libm/src/math/nextafterf.rs b/library/compiler-builtins/libm/src/math/nextafterf.rs index 8ba3833562fb..c15eb9de2818 100644 --- a/library/compiler-builtins/libm/src/math/nextafterf.rs +++ b/library/compiler-builtins/libm/src/math/nextafterf.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn nextafterf(x: f32, y: f32) -> f32 { if x.is_nan() || y.is_nan() { return x + y; diff --git a/library/compiler-builtins/libm/src/math/pow.rs b/library/compiler-builtins/libm/src/math/pow.rs index 94ae31cf0dab..914d68cfce1a 100644 --- a/library/compiler-builtins/libm/src/math/pow.rs +++ b/library/compiler-builtins/libm/src/math/pow.rs @@ -90,7 +90,7 @@ const IVLN2_H: f64 = 1.44269502162933349609e+00; /* 0x3ff71547_60000000 =24b 1/l const IVLN2_L: f64 = 1.92596299112661746887e-08; /* 0x3e54ae0b_f85ddf44 =1/ln2 tail*/ /// Returns `x` to the power of `y` (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn pow(x: f64, y: f64) -> f64 { let t1: f64; let t2: f64; diff --git a/library/compiler-builtins/libm/src/math/powf.rs b/library/compiler-builtins/libm/src/math/powf.rs index 11c7a7cbd94d..17772ae872d3 100644 --- a/library/compiler-builtins/libm/src/math/powf.rs +++ b/library/compiler-builtins/libm/src/math/powf.rs @@ -46,7 +46,7 @@ const IVLN2_H: f32 = 1.4426879883e+00; const IVLN2_L: f32 = 7.0526075433e-06; /// Returns `x` to the power of `y` (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn powf(x: f32, y: f32) -> f32 { let mut z: f32; let mut ax: f32; diff --git a/library/compiler-builtins/libm/src/math/rem_pio2.rs b/library/compiler-builtins/libm/src/math/rem_pio2.rs index 648dca170ec4..61b1030275a2 100644 --- a/library/compiler-builtins/libm/src/math/rem_pio2.rs +++ b/library/compiler-builtins/libm/src/math/rem_pio2.rs @@ -41,7 +41,7 @@ const PIO2_3T: f64 = 8.47842766036889956997e-32; /* 0x397B839A, 0x252049C1 */ // use rem_pio2_large() for large x // // caller must handle the case when reduction is not needed: |x| ~<= pi/4 */ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn rem_pio2(x: f64) -> (i32, f64, f64) { let x1p24 = f64::from_bits(0x4170000000000000); diff --git a/library/compiler-builtins/libm/src/math/rem_pio2_large.rs b/library/compiler-builtins/libm/src/math/rem_pio2_large.rs index 792c09fb17eb..f1fdf3673a8d 100644 --- a/library/compiler-builtins/libm/src/math/rem_pio2_large.rs +++ b/library/compiler-builtins/libm/src/math/rem_pio2_large.rs @@ -221,7 +221,7 @@ const PIO2: [f64; 8] = [ /// skip the part of the product that are known to be a huge integer ( /// more accurately, = 0 mod 8 ). Thus the number of operations are /// independent of the exponent of the input. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn rem_pio2_large(x: &[f64], y: &mut [f64], e0: i32, prec: usize) -> i32 { // FIXME(rust-lang/rust#144518): Inline assembly would cause `no_panic` to fail // on the callers of this function. As a workaround, avoid inlining `floor` here diff --git a/library/compiler-builtins/libm/src/math/rem_pio2f.rs b/library/compiler-builtins/libm/src/math/rem_pio2f.rs index 3c658fe3dbce..0472a10355a0 100644 --- a/library/compiler-builtins/libm/src/math/rem_pio2f.rs +++ b/library/compiler-builtins/libm/src/math/rem_pio2f.rs @@ -31,7 +31,7 @@ const PIO2_1T: f64 = 1.58932547735281966916e-08; /* 0x3E5110b4, 0x611A6263 */ /// /// use double precision for everything except passing x /// use __rem_pio2_large() for large x -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub(crate) fn rem_pio2f(x: f32) -> (i32, f64) { let x64 = x as f64; diff --git a/library/compiler-builtins/libm/src/math/remainder.rs b/library/compiler-builtins/libm/src/math/remainder.rs index 9e966c9ed7f4..54152df32f15 100644 --- a/library/compiler-builtins/libm/src/math/remainder.rs +++ b/library/compiler-builtins/libm/src/math/remainder.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn remainder(x: f64, y: f64) -> f64 { let (result, _) = super::remquo(x, y); result diff --git a/library/compiler-builtins/libm/src/math/remainderf.rs b/library/compiler-builtins/libm/src/math/remainderf.rs index b1407cf2ace3..21f629214280 100644 --- a/library/compiler-builtins/libm/src/math/remainderf.rs +++ b/library/compiler-builtins/libm/src/math/remainderf.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn remainderf(x: f32, y: f32) -> f32 { let (result, _) = super::remquof(x, y); result diff --git a/library/compiler-builtins/libm/src/math/remquo.rs b/library/compiler-builtins/libm/src/math/remquo.rs index 4c11e848746b..f13b092373e5 100644 --- a/library/compiler-builtins/libm/src/math/remquo.rs +++ b/library/compiler-builtins/libm/src/math/remquo.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn remquo(mut x: f64, mut y: f64) -> (f64, i32) { let ux: u64 = x.to_bits(); let mut uy: u64 = y.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/remquof.rs b/library/compiler-builtins/libm/src/math/remquof.rs index b0e85ca66116..cc7863a096f9 100644 --- a/library/compiler-builtins/libm/src/math/remquof.rs +++ b/library/compiler-builtins/libm/src/math/remquof.rs @@ -1,4 +1,4 @@ -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn remquof(mut x: f32, mut y: f32) -> (f32, i32) { let ux: u32 = x.to_bits(); let mut uy: u32 = y.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/rint.rs b/library/compiler-builtins/libm/src/math/rint.rs index e1c32c943552..011a7ae3d60a 100644 --- a/library/compiler-builtins/libm/src/math/rint.rs +++ b/library/compiler-builtins/libm/src/math/rint.rs @@ -2,7 +2,7 @@ use super::support::Round; /// Round `x` to the nearest integer, breaking ties toward even. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn rintf16(x: f16) -> f16 { select_implementation! { name: rintf16, @@ -14,7 +14,7 @@ pub fn rintf16(x: f16) -> f16 { } /// Round `x` to the nearest integer, breaking ties toward even. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn rintf(x: f32) -> f32 { select_implementation! { name: rintf, @@ -29,7 +29,7 @@ pub fn rintf(x: f32) -> f32 { } /// Round `x` to the nearest integer, breaking ties toward even. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn rint(x: f64) -> f64 { select_implementation! { name: rint, @@ -45,7 +45,7 @@ pub fn rint(x: f64) -> f64 { /// Round `x` to the nearest integer, breaking ties toward even. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn rintf128(x: f128) -> f128 { super::generic::rint_round(x, Round::Nearest).val } diff --git a/library/compiler-builtins/libm/src/math/round.rs b/library/compiler-builtins/libm/src/math/round.rs index 6cd091cd73cd..256197e6ccbe 100644 --- a/library/compiler-builtins/libm/src/math/round.rs +++ b/library/compiler-builtins/libm/src/math/round.rs @@ -1,25 +1,25 @@ /// Round `x` to the nearest integer, breaking ties away from zero. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn roundf16(x: f16) -> f16 { super::generic::round(x) } /// Round `x` to the nearest integer, breaking ties away from zero. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn roundf(x: f32) -> f32 { super::generic::round(x) } /// Round `x` to the nearest integer, breaking ties away from zero. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn round(x: f64) -> f64 { super::generic::round(x) } /// Round `x` to the nearest integer, breaking ties away from zero. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn roundf128(x: f128) -> f128 { super::generic::round(x) } diff --git a/library/compiler-builtins/libm/src/math/roundeven.rs b/library/compiler-builtins/libm/src/math/roundeven.rs index 6e621d7628f2..f0d67d41076e 100644 --- a/library/compiler-builtins/libm/src/math/roundeven.rs +++ b/library/compiler-builtins/libm/src/math/roundeven.rs @@ -3,21 +3,21 @@ use super::support::{Float, Round}; /// Round `x` to the nearest integer, breaking ties toward even. This is IEEE 754 /// `roundToIntegralTiesToEven`. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn roundevenf16(x: f16) -> f16 { roundeven_impl(x) } /// Round `x` to the nearest integer, breaking ties toward even. This is IEEE 754 /// `roundToIntegralTiesToEven`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn roundevenf(x: f32) -> f32 { roundeven_impl(x) } /// Round `x` to the nearest integer, breaking ties toward even. This is IEEE 754 /// `roundToIntegralTiesToEven`. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn roundeven(x: f64) -> f64 { roundeven_impl(x) } @@ -25,7 +25,7 @@ pub fn roundeven(x: f64) -> f64 { /// Round `x` to the nearest integer, breaking ties toward even. This is IEEE 754 /// `roundToIntegralTiesToEven`. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn roundevenf128(x: f128) -> f128 { roundeven_impl(x) } diff --git a/library/compiler-builtins/libm/src/math/scalbn.rs b/library/compiler-builtins/libm/src/math/scalbn.rs index ed73c3f94f00..f1a67cb7f82f 100644 --- a/library/compiler-builtins/libm/src/math/scalbn.rs +++ b/library/compiler-builtins/libm/src/math/scalbn.rs @@ -1,21 +1,21 @@ #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn scalbnf16(x: f16, n: i32) -> f16 { super::generic::scalbn(x, n) } -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn scalbnf(x: f32, n: i32) -> f32 { super::generic::scalbn(x, n) } -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn scalbn(x: f64, n: i32) -> f64 { super::generic::scalbn(x, n) } #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn scalbnf128(x: f128, n: i32) -> f128 { super::generic::scalbn(x, n) } diff --git a/library/compiler-builtins/libm/src/math/sin.rs b/library/compiler-builtins/libm/src/math/sin.rs index 229fa4bef083..5378a7bc3874 100644 --- a/library/compiler-builtins/libm/src/math/sin.rs +++ b/library/compiler-builtins/libm/src/math/sin.rs @@ -44,7 +44,7 @@ use super::{k_cos, k_sin, rem_pio2}; /// The sine of `x` (f64). /// /// `x` is specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sin(x: f64) -> f64 { let x1p120 = f64::from_bits(0x4770000000000000); // 0x1p120f === 2 ^ 120 diff --git a/library/compiler-builtins/libm/src/math/sincos.rs b/library/compiler-builtins/libm/src/math/sincos.rs index ebf482f2df35..a364f73759d5 100644 --- a/library/compiler-builtins/libm/src/math/sincos.rs +++ b/library/compiler-builtins/libm/src/math/sincos.rs @@ -15,7 +15,7 @@ use super::{get_high_word, k_cos, k_sin, rem_pio2}; /// Both the sine and cosine of `x` (f64). /// /// `x` is specified in radians and the return value is (sin(x), cos(x)). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sincos(x: f64) -> (f64, f64) { let s: f64; let c: f64; diff --git a/library/compiler-builtins/libm/src/math/sincosf.rs b/library/compiler-builtins/libm/src/math/sincosf.rs index f3360767683e..c4beb5267f28 100644 --- a/library/compiler-builtins/libm/src/math/sincosf.rs +++ b/library/compiler-builtins/libm/src/math/sincosf.rs @@ -26,7 +26,7 @@ const S4PIO2: f64 = 4.0 * PI_2; /* 0x401921FB, 0x54442D18 */ /// Both the sine and cosine of `x` (f32). /// /// `x` is specified in radians and the return value is (sin(x), cos(x)). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sincosf(x: f32) -> (f32, f32) { let s: f32; let c: f32; diff --git a/library/compiler-builtins/libm/src/math/sinf.rs b/library/compiler-builtins/libm/src/math/sinf.rs index 709b63fcf297..b4edf6769d30 100644 --- a/library/compiler-builtins/libm/src/math/sinf.rs +++ b/library/compiler-builtins/libm/src/math/sinf.rs @@ -27,7 +27,7 @@ const S4_PIO2: f64 = 4. * FRAC_PI_2; /* 0x401921FB, 0x54442D18 */ /// The sine of `x` (f32). /// /// `x` is specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sinf(x: f32) -> f32 { let x64 = x as f64; diff --git a/library/compiler-builtins/libm/src/math/sinh.rs b/library/compiler-builtins/libm/src/math/sinh.rs index 79184198263c..900dd6ca4d8e 100644 --- a/library/compiler-builtins/libm/src/math/sinh.rs +++ b/library/compiler-builtins/libm/src/math/sinh.rs @@ -6,7 +6,7 @@ use super::{expm1, expo2}; // /// The hyperbolic sine of `x` (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sinh(x: f64) -> f64 { // union {double f; uint64_t i;} u = {.f = x}; // uint32_t w; diff --git a/library/compiler-builtins/libm/src/math/sinhf.rs b/library/compiler-builtins/libm/src/math/sinhf.rs index 44d2e3560d57..501acea30287 100644 --- a/library/compiler-builtins/libm/src/math/sinhf.rs +++ b/library/compiler-builtins/libm/src/math/sinhf.rs @@ -1,7 +1,7 @@ use super::{expm1f, k_expo2f}; /// The hyperbolic sine of `x` (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sinhf(x: f32) -> f32 { let mut h = 0.5f32; let mut ix = x.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/sqrt.rs b/library/compiler-builtins/libm/src/math/sqrt.rs index 76bc240cf01c..7ba1bc9b32b2 100644 --- a/library/compiler-builtins/libm/src/math/sqrt.rs +++ b/library/compiler-builtins/libm/src/math/sqrt.rs @@ -1,6 +1,6 @@ /// The square root of `x` (f16). #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sqrtf16(x: f16) -> f16 { select_implementation! { name: sqrtf16, @@ -12,7 +12,7 @@ pub fn sqrtf16(x: f16) -> f16 { } /// The square root of `x` (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sqrtf(x: f32) -> f32 { select_implementation! { name: sqrtf, @@ -28,7 +28,7 @@ pub fn sqrtf(x: f32) -> f32 { } /// The square root of `x` (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sqrt(x: f64) -> f64 { select_implementation! { name: sqrt, @@ -45,7 +45,7 @@ pub fn sqrt(x: f64) -> f64 { /// The square root of `x` (f128). #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn sqrtf128(x: f128) -> f128 { return super::generic::sqrt(x); } diff --git a/library/compiler-builtins/libm/src/math/tan.rs b/library/compiler-builtins/libm/src/math/tan.rs index a072bdec56e0..79c1bad563e2 100644 --- a/library/compiler-builtins/libm/src/math/tan.rs +++ b/library/compiler-builtins/libm/src/math/tan.rs @@ -43,7 +43,7 @@ use super::{k_tan, rem_pio2}; /// The tangent of `x` (f64). /// /// `x` is specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn tan(x: f64) -> f64 { let x1p120 = f32::from_bits(0x7b800000); // 0x1p120f === 2 ^ 120 diff --git a/library/compiler-builtins/libm/src/math/tanf.rs b/library/compiler-builtins/libm/src/math/tanf.rs index 8bcf9581ff60..a615573d87a5 100644 --- a/library/compiler-builtins/libm/src/math/tanf.rs +++ b/library/compiler-builtins/libm/src/math/tanf.rs @@ -27,7 +27,7 @@ const T4_PIO2: f64 = 4. * FRAC_PI_2; /* 0x401921FB, 0x54442D18 */ /// The tangent of `x` (f32). /// /// `x` is specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn tanf(x: f32) -> f32 { let x64 = x as f64; diff --git a/library/compiler-builtins/libm/src/math/tanh.rs b/library/compiler-builtins/libm/src/math/tanh.rs index cc0abe4fcb2d..c99cc2a70b15 100644 --- a/library/compiler-builtins/libm/src/math/tanh.rs +++ b/library/compiler-builtins/libm/src/math/tanh.rs @@ -8,7 +8,7 @@ use super::expm1; /// The hyperbolic tangent of `x` (f64). /// /// `x` is specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn tanh(mut x: f64) -> f64 { let mut uf: f64 = x; let mut ui: u64 = f64::to_bits(uf); diff --git a/library/compiler-builtins/libm/src/math/tanhf.rs b/library/compiler-builtins/libm/src/math/tanhf.rs index fffbba6c6ec4..3cbd5917f07a 100644 --- a/library/compiler-builtins/libm/src/math/tanhf.rs +++ b/library/compiler-builtins/libm/src/math/tanhf.rs @@ -3,7 +3,7 @@ use super::expm1f; /// The hyperbolic tangent of `x` (f32). /// /// `x` is specified in radians. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn tanhf(mut x: f32) -> f32 { /* x = |x| */ let mut ix = x.to_bits(); diff --git a/library/compiler-builtins/libm/src/math/tgamma.rs b/library/compiler-builtins/libm/src/math/tgamma.rs index 3059860646a5..41415d9d1258 100644 --- a/library/compiler-builtins/libm/src/math/tgamma.rs +++ b/library/compiler-builtins/libm/src/math/tgamma.rs @@ -131,7 +131,7 @@ fn s(x: f64) -> f64 { } /// The [Gamma function](https://en.wikipedia.org/wiki/Gamma_function) (f64). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn tgamma(mut x: f64) -> f64 { let u: u64 = x.to_bits(); let absx: f64; diff --git a/library/compiler-builtins/libm/src/math/tgammaf.rs b/library/compiler-builtins/libm/src/math/tgammaf.rs index fe178f7a3c0e..a63a2a31862c 100644 --- a/library/compiler-builtins/libm/src/math/tgammaf.rs +++ b/library/compiler-builtins/libm/src/math/tgammaf.rs @@ -1,7 +1,7 @@ use super::tgamma; /// The [Gamma function](https://en.wikipedia.org/wiki/Gamma_function) (f32). -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn tgammaf(x: f32) -> f32 { tgamma(x as f64) as f32 } diff --git a/library/compiler-builtins/libm/src/math/trunc.rs b/library/compiler-builtins/libm/src/math/trunc.rs index fa50d55e1368..20d52a111a12 100644 --- a/library/compiler-builtins/libm/src/math/trunc.rs +++ b/library/compiler-builtins/libm/src/math/trunc.rs @@ -2,7 +2,7 @@ /// /// This effectively removes the decimal part of the number, leaving the integral part. #[cfg(f16_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn truncf16(x: f16) -> f16 { super::generic::trunc(x) } @@ -10,7 +10,7 @@ pub fn truncf16(x: f16) -> f16 { /// Rounds the number toward 0 to the closest integral value (f32). /// /// This effectively removes the decimal part of the number, leaving the integral part. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn truncf(x: f32) -> f32 { select_implementation! { name: truncf, @@ -24,7 +24,7 @@ pub fn truncf(x: f32) -> f32 { /// Rounds the number toward 0 to the closest integral value (f64). /// /// This effectively removes the decimal part of the number, leaving the integral part. -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn trunc(x: f64) -> f64 { select_implementation! { name: trunc, @@ -39,7 +39,7 @@ pub fn trunc(x: f64) -> f64 { /// /// This effectively removes the decimal part of the number, leaving the integral part. #[cfg(f128_enabled)] -#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] +#[cfg_attr(assert_no_panic, no_panic::no_panic)] pub fn truncf128(x: f128) -> f128 { super::generic::trunc(x) } From 2ae048e1df765e0ba4c9638149552ea1eba82834 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 30 Jul 2025 17:48:24 +0000 Subject: [PATCH 0222/1134] Distinguish appending and replacing self ty in predicates --- compiler/rustc_hir_analysis/src/check/mod.rs | 2 +- .../src/hir_ty_lowering/errors.rs | 4 +-- compiler/rustc_hir_typeck/src/coercion.rs | 10 ++++--- .../rustc_hir_typeck/src/method/suggest.rs | 8 +++--- .../rustc_hir_typeck/src/typeck_root_ctxt.rs | 2 +- .../src/solve/assembly/mod.rs | 6 ++--- .../src/solve/effect_goals.rs | 4 +-- .../src/solve/normalizes_to/mod.rs | 4 +-- .../src/solve/trait_goals.rs | 8 +++--- .../src/error_reporting/infer/region.rs | 2 +- .../traits/fulfillment_errors.rs | 6 ++--- .../src/error_reporting/traits/suggestions.rs | 9 ++++--- compiler/rustc_type_ir/src/predicate.rs | 26 ++++++++++++------- compiler/rustc_type_ir/src/ty_kind.rs | 2 +- .../src/needless_borrows_for_generic_args.rs | 2 +- 15 files changed, 53 insertions(+), 42 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index b2cfab37c1f6..85445cb3c004 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -493,7 +493,7 @@ fn suggestion_signature<'tcx>( let args = ty::GenericArgs::identity_for_item(tcx, assoc.def_id).rebase_onto( tcx, assoc.container_id(tcx), - impl_trait_ref.with_self_ty(tcx, tcx.types.self_param).args, + impl_trait_ref.with_replaced_self_ty(tcx, tcx.types.self_param).args, ); match assoc.kind { diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index f73442fdebd4..3e446b7c656f 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -888,8 +888,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => { // `::Item = String`. let projection_term = pred.projection_term; - let quiet_projection_term = - projection_term.with_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO)); + let quiet_projection_term = projection_term + .with_replaced_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO)); let term = pred.term; let obligation = format!("{projection_term} = {term}"); diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 6d67535da5fb..1737de02094c 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1800,11 +1800,13 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { .kind() .map_bound(|clause| match clause { ty::ClauseKind::Trait(trait_pred) => Some(ty::ClauseKind::Trait( - trait_pred.with_self_ty(fcx.tcx, ty), + trait_pred.with_replaced_self_ty(fcx.tcx, ty), )), - ty::ClauseKind::Projection(proj_pred) => Some( - ty::ClauseKind::Projection(proj_pred.with_self_ty(fcx.tcx, ty)), - ), + ty::ClauseKind::Projection(proj_pred) => { + Some(ty::ClauseKind::Projection( + proj_pred.with_replaced_self_ty(fcx.tcx, ty), + )) + } _ => None, }) .transpose()?; diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index e64af8fb7b38..468ad5744489 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -1053,8 +1053,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let pred = bound_predicate.rebind(pred); // `::Item = String`. let projection_term = pred.skip_binder().projection_term; - let quiet_projection_term = - projection_term.with_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO)); + let quiet_projection_term = projection_term + .with_replaced_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO)); let term = pred.skip_binder().term; @@ -2157,7 +2157,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx, self.fresh_args_for_item(sugg_span, impl_did), ) - .with_self_ty(self.tcx, rcvr_ty), + .with_replaced_self_ty(self.tcx, rcvr_ty), idx, sugg_span, item, @@ -2196,7 +2196,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { trait_did, self.fresh_args_for_item(sugg_span, trait_did), ) - .with_self_ty(self.tcx, rcvr_ty), + .with_replaced_self_ty(self.tcx, rcvr_ty), idx, sugg_span, item, diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index 6a985fc91e7d..b6afe184d07a 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -151,7 +151,7 @@ impl<'tcx> TypeckRootCtxt<'tcx> { obligation.predicate.kind().rebind( // (*) binder moved here ty::PredicateKind::Clause(ty::ClauseKind::Trait( - tpred.with_self_ty(self.tcx, new_self_ty), + tpred.with_replaced_self_ty(self.tcx, new_self_ty), )), ), ); diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index b2d401463485..ad0811f5c6c7 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -50,7 +50,7 @@ where fn trait_ref(self, cx: I) -> ty::TraitRef; - fn with_self_ty(self, cx: I, self_ty: I::Ty) -> Self; + fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self; fn trait_def_id(self, cx: I) -> I::DefId; @@ -376,8 +376,8 @@ where return self.forced_ambiguity(MaybeCause::Ambiguity).into_iter().collect(); } - let goal: Goal = - goal.with(self.cx(), goal.predicate.with_self_ty(self.cx(), normalized_self_ty)); + let goal: Goal = goal + .with(self.cx(), goal.predicate.with_replaced_self_ty(self.cx(), normalized_self_ty)); // Vars that show up in the rest of the goal substs may have been constrained by // normalizing the self type as well, since type variables are not uniquified. let goal = self.resolve_vars_if_possible(goal); diff --git a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs index 61f3f9367f04..9a22bf58c035 100644 --- a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs @@ -29,8 +29,8 @@ where self.trait_ref } - fn with_self_ty(self, cx: I, self_ty: I::Ty) -> Self { - self.with_self_ty(cx, self_ty) + fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self { + self.with_replaced_self_ty(cx, self_ty) } fn trait_def_id(self, _: I) -> I::DefId { diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index 1e0a90eb2eef..93434dce79fd 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -99,8 +99,8 @@ where self.alias.trait_ref(cx) } - fn with_self_ty(self, cx: I, self_ty: I::Ty) -> Self { - self.with_self_ty(cx, self_ty) + fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self { + self.with_replaced_self_ty(cx, self_ty) } fn trait_def_id(self, cx: I) -> I::DefId { diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 650b85d99d2c..43c123f55dbe 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -33,8 +33,8 @@ where self.trait_ref } - fn with_self_ty(self, cx: I, self_ty: I::Ty) -> Self { - self.with_self_ty(cx, self_ty) + fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self { + self.with_replaced_self_ty(cx, self_ty) } fn trait_def_id(self, _: I) -> I::DefId { @@ -1263,7 +1263,9 @@ where let goals = ecx.enter_forall(constituent_tys(ecx, goal.predicate.self_ty())?, |ecx, tys| { tys.into_iter() - .map(|ty| goal.with(ecx.cx(), goal.predicate.with_self_ty(ecx.cx(), ty))) + .map(|ty| { + goal.with(ecx.cx(), goal.predicate.with_replaced_self_ty(ecx.cx(), ty)) + }) .collect::>() }); ecx.add_goals(GoalSource::ImplWhereBound, goals); diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs index f3441a8d72aa..7369134420c6 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs @@ -581,7 +581,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let trait_args = trait_ref .instantiate_identity() // Replace the explicit self type with `Self` for better suggestion rendering - .with_self_ty(self.tcx, Ty::new_param(self.tcx, 0, kw::SelfUpper)) + .with_replaced_self_ty(self.tcx, Ty::new_param(self.tcx, 0, kw::SelfUpper)) .args; let trait_item_args = ty::GenericArgs::identity_for_item(self.tcx, impl_item_def_id) .rebase_onto(self.tcx, impl_def_id, trait_args); diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 1ac309da101f..a9e346a5cdb0 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -512,7 +512,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { && self.fallback_has_occurred { let predicate = leaf_trait_predicate.map_bound(|trait_pred| { - trait_pred.with_self_ty(self.tcx, tcx.types.unit) + trait_pred.with_replaced_self_ty(self.tcx, tcx.types.unit) }); let unit_obligation = obligation.with(tcx, predicate); if self.predicate_may_hold(&unit_obligation) { @@ -2364,8 +2364,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { param_env: ty::ParamEnv<'tcx>, trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>, ) -> PredicateObligation<'tcx> { - let trait_pred = - trait_ref_and_ty.map_bound(|(tr, new_self_ty)| tr.with_self_ty(self.tcx, new_self_ty)); + let trait_pred = trait_ref_and_ty + .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty)); Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred) } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index c182fd99b17b..718cff6d135b 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -3942,7 +3942,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id) && let Some(failed_pred) = failed_pred.as_trait_clause() - && let pred = failed_pred.map_bound(|pred| pred.with_self_ty(tcx, ty)) + && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty)) && self.predicate_must_hold_modulo_regions(&Obligation::misc( tcx, expr.span, body_id, param_env, pred, )) @@ -4624,9 +4624,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return }; let trait_ref = root_pred.map_bound(|root_pred| { - root_pred - .trait_ref - .with_self_ty(self.tcx, Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()])) + root_pred.trait_ref.with_replaced_self_ty( + self.tcx, + Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]), + ) }); let obligation = diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index 4643cd0ab850..c9489c98ccea 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -97,7 +97,7 @@ impl TraitRef { ) } - pub fn with_self_ty(self, interner: I, self_ty: I::Ty) -> Self { + pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> Self { TraitRef::new( interner, self.def_id, @@ -146,8 +146,11 @@ pub struct TraitPredicate { } impl TraitPredicate { - pub fn with_self_ty(self, interner: I, self_ty: I::Ty) -> Self { - Self { trait_ref: self.trait_ref.with_self_ty(interner, self_ty), polarity: self.polarity } + pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> Self { + Self { + trait_ref: self.trait_ref.with_replaced_self_ty(interner, self_ty), + polarity: self.polarity, + } } pub fn def_id(self) -> I::DefId { @@ -645,7 +648,7 @@ impl AliasTerm { self.args.type_at(0) } - pub fn with_self_ty(self, interner: I, self_ty: I::Ty) -> Self { + pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> Self { AliasTerm::new( interner, self.def_id, @@ -756,8 +759,11 @@ impl ProjectionPredicate { self.projection_term.self_ty() } - pub fn with_self_ty(self, interner: I, self_ty: I::Ty) -> ProjectionPredicate { - Self { projection_term: self.projection_term.with_self_ty(interner, self_ty), ..self } + pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> ProjectionPredicate { + Self { + projection_term: self.projection_term.with_replaced_self_ty(interner, self_ty), + ..self + } } pub fn trait_def_id(self, interner: I) -> I::DefId { @@ -814,8 +820,8 @@ impl NormalizesTo { self.alias.self_ty() } - pub fn with_self_ty(self, interner: I, self_ty: I::Ty) -> NormalizesTo { - Self { alias: self.alias.with_self_ty(interner, self_ty), ..self } + pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> NormalizesTo { + Self { alias: self.alias.with_replaced_self_ty(interner, self_ty), ..self } } pub fn trait_def_id(self, interner: I) -> I::DefId { @@ -849,8 +855,8 @@ impl HostEffectPredicate { self.trait_ref.self_ty() } - pub fn with_self_ty(self, interner: I, self_ty: I::Ty) -> Self { - Self { trait_ref: self.trait_ref.with_self_ty(interner, self_ty), ..self } + pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> Self { + Self { trait_ref: self.trait_ref.with_replaced_self_ty(interner, self_ty), ..self } } pub fn def_id(self) -> I::DefId { diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 7c6654247505..a4be01e9eb51 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -475,7 +475,7 @@ impl AliasTy { self.args.type_at(0) } - pub fn with_self_ty(self, interner: I, self_ty: I::Ty) -> Self { + pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> Self { AliasTy::new( interner, self.def_id, diff --git a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs index 17d251a7bbb9..120a4b98a65a 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs @@ -417,7 +417,7 @@ fn replace_types<'tcx>( { let projection = projection_predicate .projection_term - .with_self_ty(cx.tcx, new_ty) + .with_replaced_self_ty(cx.tcx, new_ty) .expect_ty(cx.tcx) .to_ty(cx.tcx); From 7d662eeb935fae3a6c33670ef68ed12eba71fc88 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 30 Jul 2025 17:48:24 +0000 Subject: [PATCH 0223/1134] Distinguish appending and replacing self ty in predicates --- clippy_lints/src/needless_borrows_for_generic_args.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/needless_borrows_for_generic_args.rs b/clippy_lints/src/needless_borrows_for_generic_args.rs index 17d251a7bbb9..120a4b98a65a 100644 --- a/clippy_lints/src/needless_borrows_for_generic_args.rs +++ b/clippy_lints/src/needless_borrows_for_generic_args.rs @@ -417,7 +417,7 @@ fn replace_types<'tcx>( { let projection = projection_predicate .projection_term - .with_self_ty(cx.tcx, new_ty) + .with_replaced_self_ty(cx.tcx, new_ty) .expect_ty(cx.tcx) .to_ty(cx.tcx); From e295a7d9f9bd87ab5cae8f9959c3122e30eadf1a Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 28 Jul 2025 18:35:23 +0200 Subject: [PATCH 0224/1134] Simplify boolean expression in `manual_assert` --- clippy_lints/src/manual_assert.rs | 16 +++++----------- tests/ui/manual_assert.edition2018.stderr | 4 ++-- tests/ui/manual_assert.edition2021.stderr | 4 ++-- 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/clippy_lints/src/manual_assert.rs b/clippy_lints/src/manual_assert.rs index ea6b01a053a3..76cb22864779 100644 --- a/clippy_lints/src/manual_assert.rs +++ b/clippy_lints/src/manual_assert.rs @@ -1,8 +1,8 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::macros::{is_panic, root_macro_call}; -use clippy_utils::{is_else_clause, is_parent_stmt, peel_blocks_with_stmt, span_extract_comment, sugg}; +use clippy_utils::{higher, is_else_clause, is_parent_stmt, peel_blocks_with_stmt, span_extract_comment, sugg}; use rustc_errors::Applicability; -use rustc_hir::{Expr, ExprKind, UnOp}; +use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::declare_lint_pass; @@ -35,7 +35,7 @@ declare_lint_pass!(ManualAssert => [MANUAL_ASSERT]); impl<'tcx> LateLintPass<'tcx> for ManualAssert { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { - if let ExprKind::If(cond, then, None) = expr.kind + if let Some(higher::If { cond, then, r#else: None }) = higher::If::hir(expr) && !matches!(cond.kind, ExprKind::Let(_)) && !expr.span.from_expansion() && let then = peel_blocks_with_stmt(then) @@ -51,19 +51,13 @@ impl<'tcx> LateLintPass<'tcx> for ManualAssert { && !is_else_clause(cx.tcx, expr) { let mut applicability = Applicability::MachineApplicable; - let cond = cond.peel_drop_temps(); let mut comments = span_extract_comment(cx.sess().source_map(), expr.span); if !comments.is_empty() { comments += "\n"; } - let (cond, not) = match cond.kind { - ExprKind::Unary(UnOp::Not, e) => (e, ""), - _ => (cond, "!"), - }; - let cond_sugg = - sugg::Sugg::hir_with_context(cx, cond, expr.span.ctxt(), "..", &mut applicability).maybe_paren(); + let cond_sugg = !sugg::Sugg::hir_with_context(cx, cond, expr.span.ctxt(), "..", &mut applicability); let semicolon = if is_parent_stmt(cx, expr.hir_id) { ";" } else { "" }; - let sugg = format!("assert!({not}{cond_sugg}, {format_args_snip}){semicolon}"); + let sugg = format!("assert!({cond_sugg}, {format_args_snip}){semicolon}"); // we show to the user the suggestion without the comments, but when applying the fix, include the // comments in the block span_lint_and_then( diff --git a/tests/ui/manual_assert.edition2018.stderr b/tests/ui/manual_assert.edition2018.stderr index 221cddf069db..2e9c9045caae 100644 --- a/tests/ui/manual_assert.edition2018.stderr +++ b/tests/ui/manual_assert.edition2018.stderr @@ -167,7 +167,7 @@ LL - comment */ LL - /// Doc comment LL - panic!("panic with comment") // comment after `panic!` LL - } -LL + assert!(!(a > 2), "panic with comment"); +LL + assert!(a <= 2, "panic with comment"); | error: only a `panic!` in `if`-then statement @@ -186,7 +186,7 @@ LL - const BAR: () = if N == 0 { LL - LL - panic!() LL - }; -LL + const BAR: () = assert!(!(N == 0), ); +LL + const BAR: () = assert!(N != 0, ); | error: only a `panic!` in `if`-then statement diff --git a/tests/ui/manual_assert.edition2021.stderr b/tests/ui/manual_assert.edition2021.stderr index 221cddf069db..2e9c9045caae 100644 --- a/tests/ui/manual_assert.edition2021.stderr +++ b/tests/ui/manual_assert.edition2021.stderr @@ -167,7 +167,7 @@ LL - comment */ LL - /// Doc comment LL - panic!("panic with comment") // comment after `panic!` LL - } -LL + assert!(!(a > 2), "panic with comment"); +LL + assert!(a <= 2, "panic with comment"); | error: only a `panic!` in `if`-then statement @@ -186,7 +186,7 @@ LL - const BAR: () = if N == 0 { LL - LL - panic!() LL - }; -LL + const BAR: () = assert!(!(N == 0), ); +LL + const BAR: () = assert!(N != 0, ); | error: only a `panic!` in `if`-then statement From 3ff3a1ee0000c7a47cae866fcb086072eeb3f476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nurzhan=20Sak=C3=A9n?= Date: Wed, 30 Jul 2025 23:39:35 +0400 Subject: [PATCH 0225/1134] Stabilize strict_overflow_ops --- compiler/rustc_const_eval/src/lib.rs | 2 +- library/core/src/num/int_macros.rs | 74 +++++++++++----------------- library/core/src/num/uint_macros.rs | 67 ++++++++++--------------- src/tools/miri/src/lib.rs | 2 +- 4 files changed, 56 insertions(+), 89 deletions(-) diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index bf7a79dcb20f..8a387a8835ba 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -1,6 +1,7 @@ // tidy-alphabetical-start #![allow(internal_features)] #![allow(rustc::diagnostic_outside_of_impl)] +#![cfg_attr(bootstrap, feature(strict_overflow_ops))] #![doc(rust_logo)] #![feature(assert_matches)] #![feature(box_patterns)] @@ -9,7 +10,6 @@ #![feature(never_type)] #![feature(rustdoc_internals)] #![feature(slice_ptr_get)] -#![feature(strict_overflow_ops)] #![feature(trait_alias)] #![feature(try_blocks)] #![feature(unqualified_local_imports)] diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 5683d5ec92dc..37ff1997a8a9 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -469,17 +469,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).strict_add(1), ", stringify!($SelfT), "::MAX - 1);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add(3);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -560,17 +559,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_add_unsigned(2), 3);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add_unsigned(3);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -611,17 +609,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).strict_sub(1), ", stringify!($SelfT), "::MIN + 1);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (", stringify!($SelfT), "::MIN + 2).strict_sub(3);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -702,17 +699,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_sub_unsigned(2), -1);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (", stringify!($SelfT), "::MIN + 2).strict_sub_unsigned(3);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -753,17 +749,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.strict_mul(1), ", stringify!($SelfT), "::MAX);")] /// ``` /// /// The following panics because of overflow: /// /// ``` should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_mul(2);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -855,24 +850,22 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).strict_div(-1), ", stringify!($Max), ");")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.strict_div(-1);")] /// ``` /// /// The following panics because of division by zero: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div(0);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -924,24 +917,22 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).strict_div_euclid(-1), ", stringify!($Max), ");")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.strict_div_euclid(-1);")] /// ``` /// /// The following panics because of division by zero: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div_euclid(0);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1092,24 +1083,22 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".strict_rem(2), 1);")] /// ``` /// /// The following panics because of division by zero: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem(0);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.strict_rem(-1);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1160,24 +1149,22 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".strict_rem_euclid(2), 1);")] /// ``` /// /// The following panics because of division by zero: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem_euclid(0);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.strict_rem_euclid(-1);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1249,17 +1236,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".strict_neg(), -5);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.strict_neg();")] /// - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1306,17 +1292,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".strict_shl(4), 0x10);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 0x1", stringify!($SelfT), ".strict_shl(129);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1422,17 +1407,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".strict_shr(4), 0x1);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shr(128);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1542,17 +1526,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").strict_abs(), 5);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.strict_abs();")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1612,17 +1595,16 @@ macro_rules! int_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".strict_pow(2), 64);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_pow(2);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 584cd60fbe5c..9598665cb48f 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -538,17 +538,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).strict_add(1), ", stringify!($SelfT), "::MAX - 1);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add(3);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -630,22 +629,20 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_add_signed(2), 3);")] /// ``` /// /// The following panic because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_add_signed(-2);")] /// ``` /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add_signed(3);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -695,17 +692,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_sub(1), 0);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 0", stringify!($SelfT), ".strict_sub(1);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -817,22 +813,20 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".strict_sub_signed(2), 1);")] /// ``` /// /// The following panic because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_sub_signed(2);")] /// ``` /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX).strict_sub_signed(-1);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -932,17 +926,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".strict_mul(1), 5);")] /// ``` /// /// The following panics because of overflow: /// /// ``` should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_mul(2);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1029,17 +1022,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div(10), 10);")] /// ``` /// /// The following panics because of division by zero: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div(0);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline(always)] @@ -1085,16 +1077,15 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div_euclid(10), 10);")] /// ``` /// The following panics because of division by zero: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div_euclid(0);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline(always)] @@ -1239,17 +1230,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem(10), 0);")] /// ``` /// /// The following panics because of division by zero: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem(0);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline(always)] @@ -1296,17 +1286,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem_euclid(10), 0);")] /// ``` /// /// The following panics because of division by zero: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem_euclid(0);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline(always)] @@ -1568,17 +1557,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".strict_neg(), 0);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_neg();")] /// - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1625,17 +1613,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".strict_shl(4), 0x10);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shl(129);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1741,17 +1728,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".strict_shr(4), 0x1);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shr(129);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] @@ -1867,17 +1853,16 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(strict_overflow_ops)] #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".strict_pow(5), 32);")] /// ``` /// /// The following panics because of overflow: /// /// ```should_panic - /// #![feature(strict_overflow_ops)] #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_pow(2);")] /// ``` - #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "strict_overflow_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index 507d4f7b4289..8d6796644e52 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -1,3 +1,4 @@ +#![cfg_attr(bootstrap, feature(strict_overflow_ops))] #![feature(abort_unwind)] #![feature(cfg_select)] #![feature(rustc_private)] @@ -11,7 +12,6 @@ #![feature(variant_count)] #![feature(yeet_expr)] #![feature(nonzero_ops)] -#![feature(strict_overflow_ops)] #![feature(pointer_is_aligned_to)] #![feature(ptr_metadata)] #![feature(unqualified_local_imports)] From ee0118f8a1dbfcad06b8c09644553a3fc3e070d4 Mon Sep 17 00:00:00 2001 From: David Tenty Date: Wed, 30 Jul 2025 16:45:17 -0400 Subject: [PATCH 0226/1134] [test][AIX] ignore extern_weak linkage test The AIX linkage model doesn't support ELF style extern_weak semantic, so just skip this test, like other platforms that don't have it. --- tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs b/tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs index 8c194ec50df4..ad7b06744781 100644 --- a/tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs +++ b/tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs @@ -4,6 +4,7 @@ //@ ignore-emscripten no weak symbol support //@ ignore-apple no extern_weak linkage +//@ ignore-aix no extern_weak linkage //@ aux-build:lib.rs From 170ccbf434112f25f596898b1117942b4bafbd22 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 30 Jul 2025 20:57:00 +0000 Subject: [PATCH 0227/1134] expand WF obligations when checking method calls --- .../src/check/compare_impl_item.rs | 16 +++++------ .../rustc_hir_typeck/src/method/confirm.rs | 28 ++++++++----------- compiler/rustc_hir_typeck/src/method/mod.rs | 21 +++++++------- 3 files changed, 30 insertions(+), 35 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index e24426f9fedc..daf5f6e7bb5b 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -356,14 +356,14 @@ fn compare_method_predicate_entailment<'tcx>( } if !(impl_sig, trait_sig).references_error() { - ocx.register_obligation(traits::Obligation::new( - infcx.tcx, - cause, - param_env, - ty::ClauseKind::WellFormed( - Ty::new_fn_ptr(tcx, ty::Binder::dummy(unnormalized_impl_sig)).into(), - ), - )); + for ty in unnormalized_impl_sig.inputs_and_output { + ocx.register_obligation(traits::Obligation::new( + infcx.tcx, + cause.clone(), + param_env, + ty::ClauseKind::WellFormed(ty.into()), + )); + } } // Check that all obligations are satisfied by the implementation's diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 8d9f7eaf1774..79996ff482e8 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -142,7 +142,6 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { let (method_sig, method_predicates) = self.normalize(self.span, (method_sig, method_predicates)); - let method_sig = ty::Binder::dummy(method_sig); // Make sure nobody calls `drop()` explicitly. self.check_for_illegal_method_calls(pick); @@ -154,20 +153,11 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // We won't add these if we encountered an illegal sized bound, so that we can use // a custom error in that case. if illegal_sized_bound.is_none() { - self.add_obligations( - Ty::new_fn_ptr(self.tcx, method_sig), - all_args, - method_predicates, - pick.item.def_id, - ); + self.add_obligations(method_sig, all_args, method_predicates, pick.item.def_id); } // Create the final `MethodCallee`. - let callee = MethodCallee { - def_id: pick.item.def_id, - args: all_args, - sig: method_sig.skip_binder(), - }; + let callee = MethodCallee { def_id: pick.item.def_id, args: all_args, sig: method_sig }; ConfirmResult { callee, illegal_sized_bound } } @@ -601,14 +591,14 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn add_obligations( &mut self, - fty: Ty<'tcx>, + sig: ty::FnSig<'tcx>, all_args: GenericArgsRef<'tcx>, method_predicates: ty::InstantiatedPredicates<'tcx>, def_id: DefId, ) { debug!( - "add_obligations: fty={:?} all_args={:?} method_predicates={:?} def_id={:?}", - fty, all_args, method_predicates, def_id + "add_obligations: sig={:?} all_args={:?} method_predicates={:?} def_id={:?}", + sig, all_args, method_predicates, def_id ); // FIXME: could replace with the following, but we already calculated `method_predicates`, @@ -637,7 +627,13 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // the function type must also be well-formed (this is not // implied by the args being well-formed because of inherent // impls and late-bound regions - see issue #28609). - self.register_wf_obligation(fty.into(), self.span, ObligationCauseCode::WellFormed(None)); + for ty in sig.inputs_and_output { + self.register_wf_obligation( + ty.into(), + self.span, + ObligationCauseCode::WellFormed(None), + ); + } } /////////////////////////////////////////////////////////////////////////// diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index 316468b0a5d1..e37ea0316726 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -428,19 +428,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { )); // Also add an obligation for the method type being well-formed. - let method_ty = Ty::new_fn_ptr(tcx, ty::Binder::dummy(fn_sig)); debug!( - "lookup_method_in_trait: matched method method_ty={:?} obligation={:?}", - method_ty, obligation + "lookup_method_in_trait: matched method fn_sig={:?} obligation={:?}", + fn_sig, obligation ); - obligations.push(traits::Obligation::new( - tcx, - obligation.cause, - self.param_env, - ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed( - method_ty.into(), - ))), - )); + for ty in fn_sig.inputs_and_output { + obligations.push(traits::Obligation::new( + tcx, + obligation.cause.clone(), + self.param_env, + ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty.into()))), + )); + } let callee = MethodCallee { def_id, args, sig: fn_sig }; debug!("callee = {:?}", callee); From b3f369d9252e4c0d5dd9bd28b950c7730fcd2c3d Mon Sep 17 00:00:00 2001 From: Haowei Wu Date: Thu, 17 Jul 2025 16:12:28 -0700 Subject: [PATCH 0228/1134] Address some rustc inconsistency issues We noticed when building rustc multiple time in a roll, some files will not be consistent across the build despite the fact that they are built from same source under the same environment. This patch addresses the inconsistency issue we found on libunwind.a by sorting the order of the files passed to the linker. --- src/bootstrap/src/core/build_steps/compile.rs | 10 +++++++--- src/bootstrap/src/core/build_steps/llvm.rs | 8 ++++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 09bb2e35bdaa..11a5554691db 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -2376,15 +2376,19 @@ pub fn run_cargo( let mut deps = Vec::new(); let mut toplevel = Vec::new(); let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| { - let (filenames, crate_types) = match msg { + let (filenames_vec, crate_types) = match msg { CargoMessage::CompilerArtifact { filenames, target: CargoTarget { crate_types }, .. - } => (filenames, crate_types), + } => { + let mut f: Vec = filenames.into_iter().map(|s| s.into_owned()).collect(); + f.sort(); // Sort the filenames + (f, crate_types) + } _ => return, }; - for filename in filenames { + for filename in filenames_vec { // Skip files like executables let mut keep = false; if filename.ends_with(".lib") diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index b2056f5cf378..721ba6ca459e 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -1528,8 +1528,12 @@ impl Step for Libunwind { // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845 let mut count = 0; - for entry in fs::read_dir(&out_dir).unwrap() { - let file = entry.unwrap().path().canonicalize().unwrap(); + let mut files = fs::read_dir(&out_dir) + .unwrap() + .map(|entry| entry.unwrap().path().canonicalize().unwrap()) + .collect::>(); + files.sort(); + for file in files { if file.is_file() && file.extension() == Some(OsStr::new("o")) { // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind". let base_name = unhashed_basename(&file); From 7d378192a7d0c7829b7ee32e292d24bd89d7ca3d Mon Sep 17 00:00:00 2001 From: The rustc-josh-sync Cronjob Bot Date: Thu, 31 Jul 2025 04:16:57 +0000 Subject: [PATCH 0229/1134] Prepare for merging from rust-lang/rust This updates the rust-version file to 32e7a4b92b109c24e9822c862a7c74436b50e564. --- src/doc/rustc-dev-guide/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/rust-version b/src/doc/rustc-dev-guide/rust-version index b631041b6bfa..1ced6098acf4 100644 --- a/src/doc/rustc-dev-guide/rust-version +++ b/src/doc/rustc-dev-guide/rust-version @@ -1 +1 @@ -2b5e239c6b86cde974b0ef0f8e23754fb08ff3c5 +32e7a4b92b109c24e9822c862a7c74436b50e564 From 8926d9cc0325f87dfc1959043097204bca49a1d9 Mon Sep 17 00:00:00 2001 From: The rustc-josh-sync Cronjob Bot Date: Thu, 31 Jul 2025 04:20:34 +0000 Subject: [PATCH 0230/1134] Prepare for merging from rust-lang/rust This updates the rust-version file to 32e7a4b92b109c24e9822c862a7c74436b50e564. --- library/stdarch/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/stdarch/rust-version b/library/stdarch/rust-version index 622dce1c1215..1ced6098acf4 100644 --- a/library/stdarch/rust-version +++ b/library/stdarch/rust-version @@ -1 +1 @@ -5a30e4307f0506bed87eeecd171f8366fdbda1dc +32e7a4b92b109c24e9822c862a7c74436b50e564 From c78d589243cede0605a4ba26b452c50f4a09ccc3 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 09:08:46 +1000 Subject: [PATCH 0231/1134] Remove `TyCtxt::get_attrs_unchecked`. It's identical to `TyCtxt::get_all_attrs` except it takes `DefId` instead of `impl Into`. --- clippy_lints/src/matches/significant_drop_in_scrutinee.rs | 2 +- clippy_lints/src/significant_drop_tightening.rs | 2 +- clippy_utils/src/macros.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/matches/significant_drop_in_scrutinee.rs b/clippy_lints/src/matches/significant_drop_in_scrutinee.rs index 88b4d9b7d544..027dd7ce0534 100644 --- a/clippy_lints/src/matches/significant_drop_in_scrutinee.rs +++ b/clippy_lints/src/matches/significant_drop_in_scrutinee.rs @@ -185,7 +185,7 @@ impl<'a, 'tcx> SigDropChecker<'a, 'tcx> { if let Some(adt) = ty.ty_adt_def() && get_attr( self.cx.sess(), - self.cx.tcx.get_attrs_unchecked(adt.did()), + self.cx.tcx.get_all_attrs(adt.did()), sym::has_significant_drop, ) .count() diff --git a/clippy_lints/src/significant_drop_tightening.rs b/clippy_lints/src/significant_drop_tightening.rs index 521754f7bab7..9110f684bd10 100644 --- a/clippy_lints/src/significant_drop_tightening.rs +++ b/clippy_lints/src/significant_drop_tightening.rs @@ -168,7 +168,7 @@ impl<'cx, 'others, 'tcx> AttrChecker<'cx, 'others, 'tcx> { if let Some(adt) = ty.ty_adt_def() { let mut iter = get_attr( self.cx.sess(), - self.cx.tcx.get_attrs_unchecked(adt.did()), + self.cx.tcx.get_all_attrs(adt.did()), sym::has_significant_drop, ); if iter.next().is_some() { diff --git a/clippy_utils/src/macros.rs b/clippy_utils/src/macros.rs index ba126fcd05de..60473a26493d 100644 --- a/clippy_utils/src/macros.rs +++ b/clippy_utils/src/macros.rs @@ -42,7 +42,7 @@ pub fn is_format_macro(cx: &LateContext<'_>, macro_def_id: DefId) -> bool { } else { // Allow users to tag any macro as being format!-like // TODO: consider deleting FORMAT_MACRO_DIAG_ITEMS and using just this method - get_unique_attr(cx.sess(), cx.tcx.get_attrs_unchecked(macro_def_id), sym::format_args).is_some() + get_unique_attr(cx.sess(), cx.tcx.get_all_attrs(macro_def_id), sym::format_args).is_some() } } From d7b7e236e74f45bdef7e082ac361b699abac20a2 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Thu, 31 Jul 2025 00:44:22 +0800 Subject: [PATCH 0232/1134] Extend `is_case_difference` to handle digit-letter confusables Signed-off-by: xizheyin --- tests/ui/match_str_case_mismatch.stderr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/ui/match_str_case_mismatch.stderr b/tests/ui/match_str_case_mismatch.stderr index 8068edfff947..c2b58b952aaa 100644 --- a/tests/ui/match_str_case_mismatch.stderr +++ b/tests/ui/match_str_case_mismatch.stderr @@ -18,7 +18,7 @@ error: this `match` arm has a differing case than its expression LL | "~!@#$%^&*()-_=+Foo" => {}, | ^^^^^^^^^^^^^^^^^^^^ | -help: consider changing the case of this arm to respect `to_ascii_lowercase` (notice the capitalization difference) +help: consider changing the case of this arm to respect `to_ascii_lowercase` (notice the capitalization) | LL - "~!@#$%^&*()-_=+Foo" => {}, LL + "~!@#$%^&*()-_=+foo" => {}, From 64ed2b5f3d0d13cbb3206c02cd28a7a527657071 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 31 Jul 2025 07:58:56 +0200 Subject: [PATCH 0233/1134] rustup --- src/tools/miri/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index 2178caf63968..1ced6098acf4 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -733dab558992d902d6d17576de1da768094e2cf3 +32e7a4b92b109c24e9822c862a7c74436b50e564 From 76a213bb18497b17e2e753c6bfb4e08c9fc36d9a Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 31 Jul 2025 08:12:43 +0200 Subject: [PATCH 0234/1134] rely on preinstalled rustup on windows-arm --- src/tools/miri/.github/workflows/ci.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index ba496d767129..4e55200cddf0 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -69,12 +69,6 @@ jobs: sudo apt update # Install needed packages sudo apt install $(echo "libatomic1: zlib1g-dev:" | sed 's/:/:${{ matrix.multiarch }}/g') - - name: Install rustup on Windows ARM - if: ${{ matrix.os == 'windows-11-arm' }} - run: | - curl -LOs https://static.rust-lang.org/rustup/dist/aarch64-pc-windows-msvc/rustup-init.exe - ./rustup-init.exe -y --no-modify-path - echo "$USERPROFILE/.cargo/bin" >> "$GITHUB_PATH" - uses: ./.github/workflows/setup with: toolchain_flags: "--host ${{ matrix.host_target }}" From 897168169d3372056988ba5f37f2210855bc7c4a Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 31 Jul 2025 09:26:05 +0200 Subject: [PATCH 0235/1134] Properly clean proc-macro-srv proc-macro temp dir --- src/tools/rust-analyzer/Cargo.lock | 84 +++++++++++++++++++ .../crates/proc-macro-srv-cli/Cargo.toml | 3 + .../crates/proc-macro-srv-cli/src/main.rs | 3 + .../proc-macro-srv-cli/src/main_loop.rs | 5 +- .../crates/proc-macro-srv/Cargo.toml | 2 + .../crates/proc-macro-srv/src/dylib.rs | 22 +++-- .../crates/proc-macro-srv/src/lib.rs | 22 +++-- .../crates/proc-macro-srv/src/tests/utils.rs | 2 +- 8 files changed, 125 insertions(+), 18 deletions(-) diff --git a/src/tools/rust-analyzer/Cargo.lock b/src/tools/rust-analyzer/Cargo.lock index 0cbbb5dd6de7..53c2d044bbd2 100644 --- a/src/tools/rust-analyzer/Cargo.lock +++ b/src/tools/rust-analyzer/Cargo.lock @@ -50,6 +50,15 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +[[package]] +name = "atomic-polyfill" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" +dependencies = [ + "critical-section", +] + [[package]] name = "autocfg" version = "1.4.0" @@ -125,6 +134,12 @@ version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26c4925bc979b677330a8c7fe7a8c94af2dbb4a2d37b4a20a80d884400f46baa" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "camino" version = "1.1.10" @@ -318,6 +333,15 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.12", +] + [[package]] name = "countme" version = "3.0.1" @@ -339,6 +363,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + [[package]] name = "crossbeam-channel" version = "0.5.15" @@ -596,6 +626,15 @@ version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +[[package]] +name = "hash32" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" +dependencies = [ + "byteorder", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -622,6 +661,20 @@ dependencies = [ "hashbrown 0.15.4", ] +[[package]] +name = "heapless" +version = "0.7.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" +dependencies = [ + "atomic-polyfill", + "hash32", + "rustc_version", + "serde", + "spin", + "stable_deref_trait", +] + [[package]] name = "hermit-abi" version = "0.5.2" @@ -1592,6 +1645,17 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "heapless", + "serde", +] + [[package]] name = "potential_utf" version = "0.1.2" @@ -1639,6 +1703,7 @@ dependencies = [ "ra-ap-rustc_lexer 0.122.0", "span", "syntax-bridge", + "temp-dir", "tt", ] @@ -1647,6 +1712,7 @@ name = "proc-macro-srv-cli" version = "0.0.0" dependencies = [ "clap", + "postcard", "proc-macro-api", "proc-macro-srv", "tt", @@ -2023,6 +2089,15 @@ dependencies = [ "smallvec", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "ryu" version = "1.0.20" @@ -2240,6 +2315,15 @@ dependencies = [ "vfs", ] +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] + [[package]] name = "stable_deref_trait" version = "1.2.0" diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/Cargo.toml b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/Cargo.toml index 16ec3b0e2b2a..91e9e62b084b 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/Cargo.toml +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/Cargo.toml @@ -15,10 +15,13 @@ proc-macro-srv.workspace = true proc-macro-api.workspace = true tt.workspace = true clap = {version = "4.5.42", default-features = false, features = ["std"]} +postcard = { version = "1.1.3", optional = true } [features] +default = ["postcard"] sysroot-abi = ["proc-macro-srv/sysroot-abi"] in-rust-tree = ["proc-macro-srv/in-rust-tree", "sysroot-abi"] +postcard = ["dep:postcard"] [[bin]] diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs index b6ebc562eac9..97a622e453dd 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs @@ -39,6 +39,7 @@ fn main() -> std::io::Result<()> { #[derive(Copy, Clone)] enum ProtocolFormat { Json, + #[cfg(feature = "postcard")] Postcard, } @@ -50,12 +51,14 @@ impl ValueEnum for ProtocolFormat { fn to_possible_value(&self) -> Option { match self { ProtocolFormat::Json => Some(clap::builder::PossibleValue::new("json")), + #[cfg(feature = "postcard")] ProtocolFormat::Postcard => Some(clap::builder::PossibleValue::new("postcard")), } } fn from_str(input: &str, _ignore_case: bool) -> Result { match input { "json" => Ok(ProtocolFormat::Json), + #[cfg(feature = "postcard")] "postcard" => Ok(ProtocolFormat::Postcard), _ => Err(format!("unknown protocol format: {input}")), } diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs index 6bf58eef3bb9..46be8a21004d 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs @@ -37,6 +37,7 @@ impl SpanTransformer for SpanTrans { pub(crate) fn run(format: ProtocolFormat) -> io::Result<()> { match format { ProtocolFormat::Json => run_json(), + #[cfg(feature = "postcard")] ProtocolFormat::Postcard => unimplemented!(), } } @@ -96,7 +97,7 @@ fn run_json() -> io::Result<()> { srv.expand( lib, - env, + &env, current_dir, macro_name, macro_body, @@ -127,7 +128,7 @@ fn run_json() -> io::Result<()> { }); srv.expand( lib, - env, + &env, current_dir, macro_name, macro_body, diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/Cargo.toml b/src/tools/rust-analyzer/crates/proc-macro-srv/Cargo.toml index 4034f244393b..d037e715e703 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/Cargo.toml +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/Cargo.toml @@ -16,6 +16,7 @@ doctest = false object.workspace = true libloading.workspace = true memmap2.workspace = true +temp-dir.workspace = true tt.workspace = true syntax-bridge.workspace = true @@ -26,6 +27,7 @@ intern.workspace = true ra-ap-rustc_lexer.workspace = true + [target.'cfg(unix)'.dependencies] libc.workspace = true diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs index c49159df9916..095e9fa2e98e 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs @@ -4,6 +4,7 @@ mod version; use proc_macro::bridge; use std::{fmt, fs, io, time::SystemTime}; +use temp_dir::TempDir; use libloading::Library; use object::Object; @@ -141,13 +142,16 @@ pub(crate) struct Expander { } impl Expander { - pub(crate) fn new(lib: &Utf8Path) -> Result { + pub(crate) fn new( + temp_dir: &TempDir, + lib: &Utf8Path, + ) -> Result { // Some libraries for dynamic loading require canonicalized path even when it is // already absolute let lib = lib.canonicalize_utf8()?; let modified_time = fs::metadata(&lib).and_then(|it| it.modified())?; - let path = ensure_file_with_lock_free_access(&lib)?; + let path = ensure_file_with_lock_free_access(temp_dir, &lib)?; let library = ProcMacroLibrary::open(path.as_ref())?; Ok(Expander { inner: library, _remove_on_drop: RemoveFileOnDrop(path), modified_time }) @@ -221,7 +225,10 @@ impl Drop for RemoveFileOnDrop { /// Copy the dylib to temp directory to prevent locking in Windows #[cfg(windows)] -fn ensure_file_with_lock_free_access(path: &Utf8Path) -> io::Result { +fn ensure_file_with_lock_free_access( + temp_dir: &TempDir, + path: &Utf8Path, +) -> io::Result { use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hasher}; @@ -229,9 +236,7 @@ fn ensure_file_with_lock_free_access(path: &Utf8Path) -> io::Result return Ok(path.to_path_buf()); } - let mut to = Utf8PathBuf::from_path_buf(std::env::temp_dir()).unwrap(); - to.push("rust-analyzer-proc-macros"); - _ = fs::create_dir(&to); + let mut to = Utf8Path::from_path(temp_dir.path()).unwrap().to_owned(); let file_name = path.file_stem().ok_or_else(|| { io::Error::new(io::ErrorKind::InvalidInput, format!("File path is invalid: {path}")) @@ -248,6 +253,9 @@ fn ensure_file_with_lock_free_access(path: &Utf8Path) -> io::Result } #[cfg(unix)] -fn ensure_file_with_lock_free_access(path: &Utf8Path) -> io::Result { +fn ensure_file_with_lock_free_access( + _temp_dir: &TempDir, + path: &Utf8Path, +) -> io::Result { Ok(path.to_owned()) } diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs index 0f7c83979d56..29fe5aed2b1f 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs @@ -42,6 +42,7 @@ use std::{ use paths::{Utf8Path, Utf8PathBuf}; use span::Span; +use temp_dir::TempDir; use crate::server_impl::TokenStream; @@ -59,11 +60,16 @@ pub const RUSTC_VERSION_STRING: &str = env!("RUSTC_VERSION"); pub struct ProcMacroSrv<'env> { expanders: Mutex>>, env: &'env EnvSnapshot, + temp_dir: TempDir, } impl<'env> ProcMacroSrv<'env> { pub fn new(env: &'env EnvSnapshot) -> Self { - Self { expanders: Default::default(), env } + Self { + expanders: Default::default(), + env, + temp_dir: TempDir::with_prefix("proc-macro-srv").unwrap(), + } } } @@ -73,7 +79,7 @@ impl ProcMacroSrv<'_> { pub fn expand( &self, lib: impl AsRef, - env: Vec<(String, String)>, + env: &[(String, String)], current_dir: Option>, macro_name: String, macro_body: tt::TopSubtree, @@ -131,7 +137,7 @@ impl ProcMacroSrv<'_> { fn expander(&self, path: &Utf8Path) -> Result, String> { let expander = || { - let expander = dylib::Expander::new(path) + let expander = dylib::Expander::new(&self.temp_dir, path) .map_err(|err| format!("Cannot create expander for {path}: {err}",)); expander.map(Arc::new) }; @@ -203,7 +209,7 @@ impl Default for EnvSnapshot { static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); struct EnvChange<'snap> { - changed_vars: Vec, + changed_vars: Vec<&'snap str>, prev_working_dir: Option, snap: &'snap EnvSnapshot, _guard: std::sync::MutexGuard<'snap, ()>, @@ -212,7 +218,7 @@ struct EnvChange<'snap> { impl<'snap> EnvChange<'snap> { fn apply( snap: &'snap EnvSnapshot, - new_vars: Vec<(String, String)>, + new_vars: &'snap [(String, String)], current_dir: Option<&Path>, ) -> EnvChange<'snap> { let guard = ENV_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -232,11 +238,11 @@ impl<'snap> EnvChange<'snap> { EnvChange { snap, changed_vars: new_vars - .into_iter() + .iter() .map(|(k, v)| { // SAFETY: We have acquired the environment lock - unsafe { env::set_var(&k, v) }; - k + unsafe { env::set_var(k, v) }; + &**k }) .collect(), prev_working_dir, diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/tests/utils.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/tests/utils.rs index 7aa38576bb52..f5a76e30bbcb 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/tests/utils.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/tests/utils.rs @@ -55,7 +55,7 @@ fn assert_expand_impl( expect_spanned: Expect, ) { let path = proc_macro_test_dylib_path(); - let expander = dylib::Expander::new(&path).unwrap(); + let expander = dylib::Expander::new(&temp_dir::TempDir::new().unwrap(), &path).unwrap(); let def_site = SpanId(0); let call_site = SpanId(1); From 1975c98b73fd8ed79792557605f76ce053710dd8 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 31 Jul 2025 09:53:26 +0200 Subject: [PATCH 0236/1134] Reorganize proc-macro-srv --- .../proc-macro-srv-cli/src/main_loop.rs | 10 +- .../crates/proc-macro-srv/src/dylib.rs | 203 +++++++++--------- .../src/{ => dylib}/proc_macros.rs | 23 +- .../crates/proc-macro-srv/src/lib.rs | 41 ++-- .../crates/proc-macro-srv/src/server_impl.rs | 2 +- 5 files changed, 131 insertions(+), 148 deletions(-) rename src/tools/rust-analyzer/crates/proc-macro-srv/src/{ => dylib}/proc_macros.rs (81%) diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs index 46be8a21004d..703bc965db25 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main_loop.rs @@ -24,13 +24,13 @@ impl SpanTransformer for SpanTrans { _: &mut Self::Table, span: Self::Span, ) -> proc_macro_api::legacy_protocol::SpanId { - proc_macro_api::legacy_protocol::SpanId(span.0 as u32) + proc_macro_api::legacy_protocol::SpanId(span.0) } fn span_for_token_id( _: &Self::Table, id: proc_macro_api::legacy_protocol::SpanId, ) -> Self::Span { - SpanId(id.0 as u32) + SpanId(id.0) } } @@ -99,7 +99,7 @@ fn run_json() -> io::Result<()> { lib, &env, current_dir, - macro_name, + ¯o_name, macro_body, attributes, def_site, @@ -112,6 +112,7 @@ fn run_json() -> io::Result<()> { CURRENT_API_VERSION, ) }) + .map_err(|e| e.into_string().unwrap_or_default()) .map_err(msg::PanicMessage) }), SpanMode::RustAnalyzer => msg::Response::ExpandMacroExtended({ @@ -130,7 +131,7 @@ fn run_json() -> io::Result<()> { lib, &env, current_dir, - macro_name, + ¯o_name, macro_body, attributes, def_site, @@ -151,6 +152,7 @@ fn run_json() -> io::Result<()> { tree, span_data_table, }) + .map_err(|e| e.into_string().unwrap_or_default()) .map_err(msg::PanicMessage) }), } diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs index 095e9fa2e98e..c8513a10675d 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs @@ -1,5 +1,6 @@ //! Handles dynamic library loading for proc macro +mod proc_macros; mod version; use proc_macro::bridge; @@ -10,57 +11,56 @@ use libloading::Library; use object::Object; use paths::{Utf8Path, Utf8PathBuf}; -use crate::{ProcMacroKind, ProcMacroSrvSpan, proc_macros::ProcMacros, server_impl::TopSubtree}; +use crate::{ + PanicMessage, ProcMacroKind, ProcMacroSrvSpan, dylib::proc_macros::ProcMacros, + server_impl::TopSubtree, +}; -/// Loads dynamic library in platform dependent manner. -/// -/// For unix, you have to use RTLD_DEEPBIND flag to escape problems described -/// [here](https://github.com/fedochet/rust-proc-macro-panic-inside-panic-expample) -/// and [here](https://github.com/rust-lang/rust/issues/60593). -/// -/// Usage of RTLD_DEEPBIND -/// [here](https://github.com/fedochet/rust-proc-macro-panic-inside-panic-expample/issues/1) -/// -/// It seems that on Windows that behaviour is default, so we do nothing in that case. -/// -/// # Safety -/// -/// The caller is responsible for ensuring that the path is valid proc-macro library -#[cfg(windows)] -unsafe fn load_library(file: &Utf8Path) -> Result { - // SAFETY: The caller is responsible for ensuring that the path is valid proc-macro library - unsafe { Library::new(file) } +pub(crate) struct Expander { + inner: ProcMacroLibrary, + modified_time: SystemTime, } -/// Loads dynamic library in platform dependent manner. -/// -/// For unix, you have to use RTLD_DEEPBIND flag to escape problems described -/// [here](https://github.com/fedochet/rust-proc-macro-panic-inside-panic-expample) -/// and [here](https://github.com/rust-lang/rust/issues/60593). -/// -/// Usage of RTLD_DEEPBIND -/// [here](https://github.com/fedochet/rust-proc-macro-panic-inside-panic-expample/issues/1) -/// -/// It seems that on Windows that behaviour is default, so we do nothing in that case. -/// -/// # Safety -/// -/// The caller is responsible for ensuring that the path is valid proc-macro library -#[cfg(unix)] -unsafe fn load_library(file: &Utf8Path) -> Result { - // not defined by POSIX, different values on mips vs other targets - #[cfg(target_env = "gnu")] - use libc::RTLD_DEEPBIND; - use libloading::os::unix::Library as UnixLibrary; - // defined by POSIX - use libloading::os::unix::RTLD_NOW; +impl Expander { + pub(crate) fn new( + temp_dir: &TempDir, + lib: &Utf8Path, + ) -> Result { + // Some libraries for dynamic loading require canonicalized path even when it is + // already absolute + let lib = lib.canonicalize_utf8()?; + let modified_time = fs::metadata(&lib).and_then(|it| it.modified())?; - // MUSL and bionic don't have it.. - #[cfg(not(target_env = "gnu"))] - const RTLD_DEEPBIND: std::os::raw::c_int = 0x0; + let path = ensure_file_with_lock_free_access(temp_dir, &lib)?; + let library = ProcMacroLibrary::open(path.as_ref())?; - // SAFETY: The caller is responsible for ensuring that the path is valid proc-macro library - unsafe { UnixLibrary::open(Some(file), RTLD_NOW | RTLD_DEEPBIND).map(|lib| lib.into()) } + Ok(Expander { inner: library, modified_time }) + } + + pub(crate) fn expand( + &self, + macro_name: &str, + macro_body: TopSubtree, + attributes: Option>, + def_site: S, + call_site: S, + mixed_site: S, + ) -> Result, PanicMessage> + where + ::TokenStream: Default, + { + self.inner + .proc_macros + .expand(macro_name, macro_body, attributes, def_site, call_site, mixed_site) + } + + pub(crate) fn list_macros(&self) -> impl Iterator { + self.inner.proc_macros.list_macros() + } + + pub(crate) fn modified_time(&self) -> SystemTime { + self.modified_time + } } #[derive(Debug)] @@ -134,57 +134,6 @@ impl ProcMacroLibrary { } } -// Drop order matters as we can't remove the dylib before the library is unloaded -pub(crate) struct Expander { - inner: ProcMacroLibrary, - _remove_on_drop: RemoveFileOnDrop, - modified_time: SystemTime, -} - -impl Expander { - pub(crate) fn new( - temp_dir: &TempDir, - lib: &Utf8Path, - ) -> Result { - // Some libraries for dynamic loading require canonicalized path even when it is - // already absolute - let lib = lib.canonicalize_utf8()?; - let modified_time = fs::metadata(&lib).and_then(|it| it.modified())?; - - let path = ensure_file_with_lock_free_access(temp_dir, &lib)?; - let library = ProcMacroLibrary::open(path.as_ref())?; - - Ok(Expander { inner: library, _remove_on_drop: RemoveFileOnDrop(path), modified_time }) - } - - pub(crate) fn expand( - &self, - macro_name: &str, - macro_body: TopSubtree, - attributes: Option>, - def_site: S, - call_site: S, - mixed_site: S, - ) -> Result, String> - where - ::TokenStream: Default, - { - let result = self - .inner - .proc_macros - .expand(macro_name, macro_body, attributes, def_site, call_site, mixed_site); - result.map_err(|e| e.into_string().unwrap_or_default()) - } - - pub(crate) fn list_macros(&self) -> Vec<(String, ProcMacroKind)> { - self.inner.proc_macros.list_macros() - } - - pub(crate) fn modified_time(&self) -> SystemTime { - self.modified_time - } -} - fn invalid_data_err(e: impl Into>) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, e) } @@ -214,15 +163,6 @@ fn find_registrar_symbol(obj: &object::File<'_>) -> object::Result io::Result { Ok(path.to_owned()) } + +/// Loads dynamic library in platform dependent manner. +/// +/// For unix, you have to use RTLD_DEEPBIND flag to escape problems described +/// [here](https://github.com/fedochet/rust-proc-macro-panic-inside-panic-expample) +/// and [here](https://github.com/rust-lang/rust/issues/60593). +/// +/// Usage of RTLD_DEEPBIND +/// [here](https://github.com/fedochet/rust-proc-macro-panic-inside-panic-expample/issues/1) +/// +/// It seems that on Windows that behaviour is default, so we do nothing in that case. +/// +/// # Safety +/// +/// The caller is responsible for ensuring that the path is valid proc-macro library +#[cfg(windows)] +unsafe fn load_library(file: &Utf8Path) -> Result { + // SAFETY: The caller is responsible for ensuring that the path is valid proc-macro library + unsafe { Library::new(file) } +} + +/// Loads dynamic library in platform dependent manner. +/// +/// For unix, you have to use RTLD_DEEPBIND flag to escape problems described +/// [here](https://github.com/fedochet/rust-proc-macro-panic-inside-panic-expample) +/// and [here](https://github.com/rust-lang/rust/issues/60593). +/// +/// Usage of RTLD_DEEPBIND +/// [here](https://github.com/fedochet/rust-proc-macro-panic-inside-panic-expample/issues/1) +/// +/// It seems that on Windows that behaviour is default, so we do nothing in that case. +/// +/// # Safety +/// +/// The caller is responsible for ensuring that the path is valid proc-macro library +#[cfg(unix)] +unsafe fn load_library(file: &Utf8Path) -> Result { + // not defined by POSIX, different values on mips vs other targets + #[cfg(target_env = "gnu")] + use libc::RTLD_DEEPBIND; + use libloading::os::unix::Library as UnixLibrary; + // defined by POSIX + use libloading::os::unix::RTLD_NOW; + + // MUSL and bionic don't have it.. + #[cfg(not(target_env = "gnu"))] + const RTLD_DEEPBIND: std::os::raw::c_int = 0x0; + + // SAFETY: The caller is responsible for ensuring that the path is valid proc-macro library + unsafe { UnixLibrary::open(Some(file), RTLD_NOW | RTLD_DEEPBIND).map(|lib| lib.into()) } +} diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/proc_macros.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib/proc_macros.rs similarity index 81% rename from src/tools/rust-analyzer/crates/proc-macro-srv/src/proc_macros.rs rename to src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib/proc_macros.rs index 18532706c4aa..9b5721e370ac 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/proc_macros.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib/proc_macros.rs @@ -75,20 +75,13 @@ impl ProcMacros { Err(bridge::PanicMessage::String(format!("proc-macro `{macro_name}` is missing")).into()) } - pub(crate) fn list_macros(&self) -> Vec<(String, ProcMacroKind)> { - self.0 - .iter() - .map(|proc_macro| match proc_macro { - bridge::client::ProcMacro::CustomDerive { trait_name, .. } => { - (trait_name.to_string(), ProcMacroKind::CustomDerive) - } - bridge::client::ProcMacro::Bang { name, .. } => { - (name.to_string(), ProcMacroKind::Bang) - } - bridge::client::ProcMacro::Attr { name, .. } => { - (name.to_string(), ProcMacroKind::Attr) - } - }) - .collect() + pub(crate) fn list_macros(&self) -> impl Iterator { + self.0.iter().map(|proc_macro| match *proc_macro { + bridge::client::ProcMacro::CustomDerive { trait_name, .. } => { + (trait_name, ProcMacroKind::CustomDerive) + } + bridge::client::ProcMacro::Bang { name, .. } => (name, ProcMacroKind::Bang), + bridge::client::ProcMacro::Attr { name, .. } => (name, ProcMacroKind::Attr), + }) } } diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs index 29fe5aed2b1f..cb97882c5854 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs @@ -27,7 +27,6 @@ extern crate ra_ap_rustc_lexer as rustc_lexer; extern crate rustc_lexer; mod dylib; -mod proc_macros; mod server_impl; use std::{ @@ -81,16 +80,17 @@ impl ProcMacroSrv<'_> { lib: impl AsRef, env: &[(String, String)], current_dir: Option>, - macro_name: String, + macro_name: &str, macro_body: tt::TopSubtree, attribute: Option>, def_site: S, call_site: S, mixed_site: S, - ) -> Result>, String> { + ) -> Result>, PanicMessage> { let snapped_env = self.env; - let expander = - self.expander(lib.as_ref()).map_err(|err| format!("failed to load macro: {err}"))?; + let expander = self.expander(lib.as_ref()).map_err(|err| PanicMessage { + message: Some(format!("failed to load macro: {err}")), + })?; let prev_env = EnvChange::apply(snapped_env, env, current_dir.as_ref().map(<_>::as_ref)); @@ -99,11 +99,11 @@ impl ProcMacroSrv<'_> { let result = thread::scope(|s| { let thread = thread::Builder::new() .stack_size(EXPANDER_STACK_SIZE) - .name(macro_name.clone()) + .name(macro_name.to_owned()) .spawn_scoped(s, move || { expander .expand( - ¯o_name, + macro_name, server_impl::TopSubtree(macro_body.0.into_vec()), attribute.map(|it| server_impl::TopSubtree(it.0.into_vec())), def_site, @@ -112,12 +112,7 @@ impl ProcMacroSrv<'_> { ) .map(|tt| tt.0) }); - let res = match thread { - Ok(handle) => handle.join(), - Err(e) => return Err(e.to_string()), - }; - - match res { + match thread.unwrap().join() { Ok(res) => res, Err(e) => std::panic::resume_unwind(e), } @@ -132,7 +127,7 @@ impl ProcMacroSrv<'_> { dylib_path: &Utf8Path, ) -> Result, String> { let expander = self.expander(dylib_path)?; - Ok(expander.list_macros()) + Ok(expander.list_macros().map(|(k, v)| (k.to_owned(), v)).collect()) } fn expander(&self, path: &Utf8Path) -> Result, String> { @@ -186,6 +181,8 @@ impl ProcMacroSrvSpan for Span { } } } + +#[derive(Debug, Clone)] pub struct PanicMessage { message: Option, } @@ -265,14 +262,14 @@ impl Drop for EnvChange<'_> { } } - if let Some(dir) = &self.prev_working_dir { - if let Err(err) = std::env::set_current_dir(dir) { - eprintln!( - "Failed to set the current working dir to {}. Error: {:?}", - dir.display(), - err - ) - } + if let Some(dir) = &self.prev_working_dir + && let Err(err) = std::env::set_current_dir(dir) + { + eprintln!( + "Failed to set the current working dir to {}. Error: {:?}", + dir.display(), + err + ) } } } diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl.rs index 662f6257642f..32ad32731ba6 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl.rs @@ -209,7 +209,7 @@ pub(super) fn from_token_tree( token_trees.push(tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { spacing: tt::Spacing::Alone, span: literal.span, - char: '-' as char, + char: '-', }))); symbol = Symbol::intern(&symbol.as_str()[1..]); } From 431fc2a7ea59ec16c5ffc6464b31b33745b4c32e Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 31 Jul 2025 08:06:10 +0200 Subject: [PATCH 0237/1134] bless cargo miri doctest execution --- src/tools/miri/test-cargo-miri/run-test.py | 2 +- src/tools/miri/test-cargo-miri/test.default.stdout.ref | 1 + src/tools/miri/test-cargo-miri/test.filter.stdout.ref | 1 + src/tools/miri/test-cargo-miri/test.multiple_targets.stdout.ref | 2 ++ 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/tools/miri/test-cargo-miri/run-test.py b/src/tools/miri/test-cargo-miri/run-test.py index 40bfe7f845fe..6b3b6343b825 100755 --- a/src/tools/miri/test-cargo-miri/run-test.py +++ b/src/tools/miri/test-cargo-miri/run-test.py @@ -37,7 +37,7 @@ def cargo_miri(cmd, quiet = True, targets = None): def normalize_stdout(str): str = str.replace("src\\", "src/") # normalize paths across platforms - str = re.sub("finished in \\d+\\.\\d\\ds", "finished in $TIME", str) # the time keeps changing, obviously + str = re.sub("\\b\\d+\\.\\d+s\\b", "$TIME", str) # the time keeps changing, obviously return str def check_output(actual, path, name): diff --git a/src/tools/miri/test-cargo-miri/test.default.stdout.ref b/src/tools/miri/test-cargo-miri/test.default.stdout.ref index 2d74d82f769b..ef092ef703bb 100644 --- a/src/tools/miri/test-cargo-miri/test.default.stdout.ref +++ b/src/tools/miri/test-cargo-miri/test.default.stdout.ref @@ -14,3 +14,4 @@ running 5 tests ..... test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/src/tools/miri/test-cargo-miri/test.filter.stdout.ref b/src/tools/miri/test-cargo-miri/test.filter.stdout.ref index b68bc983276f..071aa5691c1a 100644 --- a/src/tools/miri/test-cargo-miri/test.filter.stdout.ref +++ b/src/tools/miri/test-cargo-miri/test.filter.stdout.ref @@ -15,3 +15,4 @@ running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 5 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/src/tools/miri/test-cargo-miri/test.multiple_targets.stdout.ref b/src/tools/miri/test-cargo-miri/test.multiple_targets.stdout.ref index a376530a8cfb..20139e9ffe62 100644 --- a/src/tools/miri/test-cargo-miri/test.multiple_targets.stdout.ref +++ b/src/tools/miri/test-cargo-miri/test.multiple_targets.stdout.ref @@ -25,8 +25,10 @@ running 5 tests ..... test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME running 5 tests ..... test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME From 7543395f9540a1d6f9e1f9e390b457e3cfe5ee04 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 31 Jul 2025 10:04:42 +0200 Subject: [PATCH 0238/1134] Add version command to proc-macro-srv --- .../crates/proc-macro-api/src/process.rs | 27 +++++---- .../crates/proc-macro-srv-cli/build.rs | 48 ++++++++++++++- .../crates/proc-macro-srv-cli/src/main.rs | 24 ++++++-- .../crates/proc-macro-srv-cli/src/version.rs | 58 +++++++++++++++++++ 4 files changed, 139 insertions(+), 18 deletions(-) create mode 100644 src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/version.rs diff --git a/src/tools/rust-analyzer/crates/proc-macro-api/src/process.rs b/src/tools/rust-analyzer/crates/proc-macro-api/src/process.rs index 278d9cbcda46..fe274a027a80 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-api/src/process.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-api/src/process.rs @@ -63,16 +63,25 @@ impl ProcMacroServerProcess { let mut srv = create_srv()?; tracing::info!("sending proc-macro server version check"); match srv.version_check() { - Ok(v) if v > version::CURRENT_API_VERSION => Err(io::Error::other( - format!( "The version of the proc-macro server ({v}) in your Rust toolchain is newer than the version supported by your rust-analyzer ({}). - This will prevent proc-macro expansion from working. Please consider updating your rust-analyzer to ensure compatibility with your current toolchain." - ,version::CURRENT_API_VERSION - ), - )), + Ok(v) if v > version::CURRENT_API_VERSION => { + #[allow(clippy::disallowed_methods)] + let process_version = Command::new(process_path) + .arg("--version") + .output() + .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned()) + .unwrap_or_else(|_| "unknown version".to_owned()); + Err(io::Error::other(format!( + "Your installed proc-macro server is too new for your rust-analyzer. API version: {}, server version: {process_version}. \ + This will prevent proc-macro expansion from working. Please consider updating your rust-analyzer to ensure compatibility with your current toolchain.", + version::CURRENT_API_VERSION + ))) + } Ok(v) => { tracing::info!("Proc-macro server version: {v}"); srv.version = v; - if srv.version >= version::RUST_ANALYZER_SPAN_SUPPORT && let Ok(mode) = srv.enable_rust_analyzer_spans() { + if srv.version >= version::RUST_ANALYZER_SPAN_SUPPORT + && let Ok(mode) = srv.enable_rust_analyzer_spans() + { srv.protocol = Protocol::LegacyJson { mode }; } tracing::info!("Proc-macro server protocol: {:?}", srv.protocol); @@ -80,9 +89,7 @@ impl ProcMacroServerProcess { } Err(e) => { tracing::info!(%e, "proc-macro version check failed"); - Err( - io::Error::other(format!("proc-macro server version check failed: {e}")), - ) + Err(io::Error::other(format!("proc-macro server version check failed: {e}"))) } } } diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/build.rs b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/build.rs index 07f914fece0e..12e7c8b05bac 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/build.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/build.rs @@ -1,5 +1,49 @@ -//! This teaches cargo about our cfg(rust_analyzer) +//! Construct version in the `commit-hash date channel` format + +use std::{env, path::PathBuf, process::Command}; fn main() { - println!("cargo:rustc-check-cfg=cfg(rust_analyzer)"); + set_rerun(); + set_commit_info(); + println!("cargo::rustc-check-cfg=cfg(rust_analyzer)"); +} + +fn set_rerun() { + println!("cargo:rerun-if-env-changed=CFG_RELEASE"); + + let mut manifest_dir = PathBuf::from( + env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is always set by cargo."), + ); + + while manifest_dir.parent().is_some() { + let head_ref = manifest_dir.join(".git/HEAD"); + if head_ref.exists() { + println!("cargo:rerun-if-changed={}", head_ref.display()); + return; + } + + manifest_dir.pop(); + } + + println!("cargo:warning=Could not find `.git/HEAD` from manifest dir!"); +} + +fn set_commit_info() { + #[allow(clippy::disallowed_methods)] + let output = match Command::new("git") + .arg("log") + .arg("-1") + .arg("--date=short") + .arg("--format=%H %h %cd") + .output() + { + Ok(output) if output.status.success() => output, + _ => return, + }; + let stdout = String::from_utf8(output.stdout).unwrap(); + let mut parts = stdout.split_whitespace(); + let mut next = || parts.next().unwrap(); + println!("cargo:rustc-env=RA_COMMIT_HASH={}", next()); + println!("cargo:rustc-env=RA_COMMIT_SHORT_HASH={}", next()); + println!("cargo:rustc-env=RA_COMMIT_DATE={}", next()) } diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs index 97a622e453dd..662d34865eff 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/main.rs @@ -2,11 +2,13 @@ //! Driver for proc macro server #![cfg_attr(feature = "in-rust-tree", feature(rustc_private))] #![cfg_attr(not(feature = "sysroot-abi"), allow(unused_crate_dependencies))] -#![allow(clippy::print_stderr)] +#![allow(clippy::print_stdout, clippy::print_stderr)] #[cfg(feature = "in-rust-tree")] extern crate rustc_driver as _; +mod version; + #[cfg(any(feature = "sysroot-abi", rust_analyzer))] mod main_loop; use clap::{Command, ValueEnum}; @@ -25,12 +27,22 @@ fn main() -> std::io::Result<()> { std::process::exit(122); } let matches = Command::new("proc-macro-srv") - .args(&[clap::Arg::new("format") - .long("format") - .action(clap::ArgAction::Set) - .default_value("json") - .value_parser(clap::builder::EnumValueParser::::new())]) + .args(&[ + clap::Arg::new("format") + .long("format") + .action(clap::ArgAction::Set) + .default_value("json") + .value_parser(clap::builder::EnumValueParser::::new()), + clap::Arg::new("version") + .long("version") + .action(clap::ArgAction::SetTrue) + .help("Prints the version of the proc-macro-srv"), + ]) .get_matches(); + if matches.get_flag("version") { + println!("rust-analyzer-proc-macro-srv {}", version::version()); + return Ok(()); + } let &format = matches.get_one::("format").expect("format value should always be present"); run(format) diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/version.rs b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/version.rs new file mode 100644 index 000000000000..32499d055d1e --- /dev/null +++ b/src/tools/rust-analyzer/crates/proc-macro-srv-cli/src/version.rs @@ -0,0 +1,58 @@ +//! Code for representing rust-analyzer's release version number. +#![expect(dead_code)] + +use std::fmt; + +/// Information about the git repository where rust-analyzer was built from. +pub(crate) struct CommitInfo { + pub(crate) short_commit_hash: &'static str, + pub(crate) commit_hash: &'static str, + pub(crate) commit_date: &'static str, +} + +/// Cargo's version. +pub(crate) struct VersionInfo { + /// rust-analyzer's version, such as "1.57.0", "1.58.0-beta.1", "1.59.0-nightly", etc. + pub(crate) version: &'static str, + /// The release channel we were built for (stable/beta/nightly/dev). + /// + /// `None` if not built via bootstrap. + pub(crate) release_channel: Option<&'static str>, + /// Information about the Git repository we may have been built from. + /// + /// `None` if not built from a git repo. + pub(crate) commit_info: Option, +} + +impl fmt::Display for VersionInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.version)?; + + if let Some(ci) = &self.commit_info { + write!(f, " ({} {})", ci.short_commit_hash, ci.commit_date)?; + }; + Ok(()) + } +} + +/// Returns information about cargo's version. +pub(crate) const fn version() -> VersionInfo { + let version = match option_env!("CFG_RELEASE") { + Some(x) => x, + None => "0.0.0", + }; + + let release_channel = option_env!("CFG_RELEASE_CHANNEL"); + let commit_info = match ( + option_env!("RA_COMMIT_SHORT_HASH"), + option_env!("RA_COMMIT_HASH"), + option_env!("RA_COMMIT_DATE"), + ) { + (Some(short_commit_hash), Some(commit_hash), Some(commit_date)) => { + Some(CommitInfo { short_commit_hash, commit_hash, commit_date }) + } + _ => None, + }; + + VersionInfo { version, release_channel, commit_info } +} From a7b01aa04867ba0ee10f767f3819d47c45d9cc30 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 31 Jul 2025 10:30:22 +0200 Subject: [PATCH 0239/1134] `cargo clippy --fix` --- .../rust-analyzer/crates/cfg/src/cfg_expr.rs | 8 +- .../rust-analyzer/crates/hir-def/src/attr.rs | 8 +- .../crates/hir-def/src/expr_store/lower.rs | 39 +++-- .../hir-def/src/expr_store/lower/asm.rs | 8 +- .../hir-def/src/expr_store/lower/path.rs | 21 +-- .../crates/hir-def/src/expr_store/pretty.rs | 12 +- .../crates/hir-def/src/find_path.rs | 72 ++++---- .../crates/hir-def/src/item_scope.rs | 9 +- .../crates/hir-def/src/item_tree/lower.rs | 23 ++- .../crates/hir-def/src/lang_item.rs | 8 +- .../hir-def/src/macro_expansion_tests/mod.rs | 64 ++++---- .../crates/hir-def/src/nameres/collector.rs | 154 ++++++++---------- .../crates/hir-def/src/resolver.rs | 94 +++++------ .../crates/hir-expand/src/builtin/fn_macro.rs | 11 +- .../crates/hir-expand/src/cfg_process.rs | 8 +- .../crates/hir-expand/src/fixup.rs | 10 +- .../crates/hir-expand/src/lib.rs | 22 ++- .../crates/hir-expand/src/mod_path.rs | 21 +-- .../crates/hir-ty/src/autoderef.rs | 9 +- .../crates/hir-ty/src/builder.rs | 10 +- .../crates/hir-ty/src/chalk_db.rs | 64 ++++---- .../crates/hir-ty/src/consteval.rs | 8 +- .../hir-ty/src/diagnostics/decl_check.rs | 8 +- .../crates/hir-ty/src/diagnostics/expr.rs | 18 +- .../hir-ty/src/diagnostics/match_check.rs | 8 +- .../hir-ty/src/diagnostics/unsafe_check.rs | 17 +- .../crates/hir-ty/src/display.rs | 123 +++++++------- .../crates/hir-ty/src/dyn_compatibility.rs | 25 ++- .../rust-analyzer/crates/hir-ty/src/infer.rs | 47 +++--- .../crates/hir-ty/src/infer/cast.rs | 37 ++--- .../crates/hir-ty/src/infer/closure.rs | 154 ++++++++---------- .../crates/hir-ty/src/infer/coerce.rs | 46 +++--- .../crates/hir-ty/src/infer/expr.rs | 75 ++++----- .../crates/hir-ty/src/infer/mutability.rs | 119 ++++++-------- .../crates/hir-ty/src/infer/pat.rs | 31 ++-- .../rust-analyzer/crates/hir-ty/src/lower.rs | 8 +- .../crates/hir-ty/src/lower/path.rs | 120 +++++++------- .../crates/hir-ty/src/method_resolution.rs | 38 ++--- .../crates/hir-ty/src/mir/borrowck.rs | 5 +- .../crates/hir-ty/src/mir/eval.rs | 73 ++++----- .../crates/hir-ty/src/mir/eval/shim.rs | 76 +++++---- .../crates/hir-ty/src/mir/eval/shim/simd.rs | 11 +- .../crates/hir-ty/src/mir/lower.rs | 60 +++---- .../crates/hir-ty/src/mir/lower/as_place.rs | 17 +- .../hir-ty/src/mir/lower/pattern_matching.rs | 49 +++--- .../rust-analyzer/crates/hir-ty/src/traits.rs | 7 +- .../rust-analyzer/crates/hir-ty/src/utils.rs | 14 +- .../crates/hir/src/diagnostics.rs | 14 +- src/tools/rust-analyzer/crates/hir/src/lib.rs | 80 +++++---- .../rust-analyzer/crates/hir/src/semantics.rs | 93 +++++------ .../crates/hir/src/source_analyzer.rs | 83 +++++----- .../crates/hir/src/term_search.rs | 16 +- .../crates/hir/src/term_search/expr.rs | 8 +- .../src/handlers/add_lifetime_to_type.rs | 24 +-- .../src/handlers/add_missing_impl_members.rs | 14 +- .../src/handlers/apply_demorgan.rs | 8 +- .../src/handlers/convert_bool_then.rs | 23 ++- .../src/handlers/convert_closure_to_fn.rs | 57 ++++--- .../src/handlers/convert_from_to_tryfrom.rs | 19 +-- .../src/handlers/convert_into_to_from.rs | 8 +- .../convert_tuple_return_type_to_struct.rs | 8 +- .../convert_tuple_struct_to_named_struct.rs | 2 +- ...ert_two_arm_bool_match_to_matches_macro.rs | 8 +- .../src/handlers/desugar_try_expr.rs | 130 +++++++-------- .../src/handlers/expand_glob_import.rs | 10 +- .../src/handlers/extract_function.rs | 101 ++++++------ .../src/handlers/extract_module.rs | 81 +++++---- .../extract_struct_from_enum_variant.rs | 12 +- .../src/handlers/extract_type_alias.rs | 42 +++-- .../src/handlers/extract_variable.rs | 15 +- .../generate_documentation_template.rs | 18 +- .../src/handlers/generate_fn_type_alias.rs | 8 +- .../src/handlers/generate_function.rs | 8 +- .../src/handlers/generate_getter_or_setter.rs | 11 +- .../ide-assists/src/handlers/generate_impl.rs | 10 +- .../src/handlers/generate_trait_from_impl.rs | 22 +-- .../ide-assists/src/handlers/inline_call.rs | 49 +++--- .../src/handlers/move_const_to_impl.rs | 8 +- .../src/handlers/pull_assignment_up.rs | 16 +- .../ide-assists/src/handlers/raw_string.rs | 18 +- .../replace_qualified_name_with_use.rs | 8 +- .../src/handlers/unnecessary_async.rs | 8 +- .../src/handlers/unwrap_return_type.rs | 24 +-- .../ide-assists/src/handlers/unwrap_tuple.rs | 8 +- .../src/handlers/wrap_return_type.rs | 40 ++--- .../src/handlers/wrap_unwrap_cfg_attr.rs | 22 ++- .../crates/ide-assists/src/utils.rs | 48 +++--- .../crates/ide-completion/src/completions.rs | 17 +- .../ide-completion/src/completions/dot.rs | 11 +- .../src/completions/fn_param.rs | 8 +- .../src/completions/item_list/trait_impl.rs | 92 +++++------ .../ide-completion/src/completions/mod_.rs | 17 +- .../ide-completion/src/completions/pattern.rs | 21 ++- .../ide-completion/src/completions/postfix.rs | 153 ++++++++--------- .../ide-completion/src/completions/use_.rs | 8 +- .../ide-completion/src/completions/vis.rs | 10 +- .../ide-completion/src/context/analysis.rs | 140 +++++++--------- .../crates/ide-completion/src/item.rs | 8 +- .../crates/ide-completion/src/lib.rs | 14 +- .../crates/ide-completion/src/render.rs | 108 ++++++------ .../ide-completion/src/render/const_.rs | 8 +- .../ide-completion/src/render/function.rs | 34 ++-- .../ide-completion/src/render/type_alias.rs | 8 +- .../rust-analyzer/crates/ide-db/src/defs.rs | 64 ++++---- .../crates/ide-db/src/helpers.rs | 10 +- .../crates/ide-db/src/imports/insert_use.rs | 45 +++-- .../crates/ide-db/src/path_transform.rs | 100 ++++++------ .../rust-analyzer/crates/ide-db/src/rename.rs | 22 +-- .../rust-analyzer/crates/ide-db/src/search.rs | 83 +++++----- .../crates/ide-db/src/symbol_index.rs | 16 +- .../src/syntax_helpers/format_string.rs | 10 +- .../ide-db/src/syntax_helpers/node_ext.rs | 23 ++- .../ide-db/src/use_trivial_constructor.rs | 20 +-- .../src/handlers/json_is_not_rust.rs | 50 +++--- .../src/handlers/missing_fields.rs | 11 +- .../src/handlers/mutability_errors.rs | 24 +-- .../src/handlers/unlinked_file.rs | 14 +- .../crates/ide-diagnostics/src/lib.rs | 54 +++--- .../rust-analyzer/crates/ide-ssr/src/lib.rs | 21 ++- .../crates/ide-ssr/src/matching.rs | 101 ++++++------ .../crates/ide-ssr/src/replacing.rs | 28 ++-- .../crates/ide-ssr/src/resolving.rs | 61 +++---- .../crates/ide-ssr/src/search.rs | 27 ++- .../crates/ide/src/annotations.rs | 8 +- .../crates/ide/src/expand_macro.rs | 16 +- .../crates/ide/src/extend_selection.rs | 54 +++--- .../crates/ide/src/folding_ranges.rs | 88 +++++----- .../crates/ide/src/goto_definition.rs | 28 ++-- .../crates/ide/src/highlight_related.rs | 45 +++-- .../rust-analyzer/crates/ide/src/hover.rs | 13 +- .../crates/ide/src/hover/render.rs | 116 ++++++------- .../crates/ide/src/inlay_hints.rs | 12 +- .../crates/ide/src/inlay_hints/adjustment.rs | 8 +- .../crates/ide/src/inlay_hints/bind_pat.rs | 8 +- .../crates/ide/src/inlay_hints/chaining.rs | 11 +- .../ide/src/inlay_hints/closing_brace.rs | 10 +- .../crates/ide/src/inlay_hints/closure_ret.rs | 8 +- .../ide/src/inlay_hints/extern_block.rs | 8 +- .../ide/src/inlay_hints/generic_param.rs | 8 +- .../ide/src/inlay_hints/implicit_static.rs | 43 ++--- .../crates/ide/src/inlay_hints/lifetime.rs | 50 +++--- .../crates/ide/src/inlay_hints/param_name.rs | 8 +- .../crates/ide/src/join_lines.rs | 26 +-- .../crates/ide/src/parent_module.rs | 11 +- .../rust-analyzer/crates/ide/src/rename.rs | 8 +- .../rust-analyzer/crates/ide/src/runnables.rs | 34 ++-- .../crates/ide/src/signature_help.rs | 19 +-- .../crates/ide/src/static_index.rs | 8 +- .../ide/src/syntax_highlighting/highlight.rs | 39 +++-- .../crates/load-cargo/src/lib.rs | 8 +- .../rust-analyzer/crates/mbe/src/benchmark.rs | 32 ++-- .../crates/mbe/src/expander/matcher.rs | 12 +- .../crates/parser/src/grammar/expressions.rs | 69 ++++---- .../rust-analyzer/crates/parser/src/input.rs | 2 +- .../crates/parser/src/shortcuts.rs | 8 +- .../crates/query-group-macro/src/lib.rs | 18 +- .../crates/rust-analyzer/src/bin/main.rs | 12 +- .../rust-analyzer/src/cli/analysis_stats.rs | 111 ++++++------- .../rust-analyzer/src/cli/progress_report.rs | 10 +- .../rust-analyzer/src/cli/rustc_tests.rs | 8 +- .../crates/rust-analyzer/src/config.rs | 21 ++- .../src/config/patch_old_style.rs | 24 +-- .../rust-analyzer/src/diagnostics/to_proto.rs | 14 +- .../crates/rust-analyzer/src/flycheck.rs | 11 +- .../crates/rust-analyzer/src/global_state.rs | 26 +-- .../rust-analyzer/src/handlers/dispatch.rs | 8 +- .../src/handlers/notification.rs | 37 ++--- .../rust-analyzer/src/handlers/request.rs | 150 ++++++++--------- .../crates/rust-analyzer/src/main_loop.rs | 64 ++++---- .../crates/rust-analyzer/src/reload.rs | 14 +- .../rust-analyzer/crates/span/src/map.rs | 14 +- .../crates/syntax-bridge/src/lib.rs | 22 +-- .../src/prettify_macro_expansion.rs | 9 +- .../crates/syntax-bridge/src/tests.rs | 9 +- .../syntax-bridge/src/to_parser_input.rs | 20 +-- .../crates/syntax/src/ast/edit.rs | 24 +-- .../crates/syntax/src/ast/edit_in_place.rs | 41 +++-- .../crates/syntax/src/ast/prec.rs | 24 +-- .../crates/syntax/src/syntax_editor.rs | 8 +- .../rust-analyzer/crates/syntax/src/ted.rs | 42 ++--- .../crates/syntax/src/validation.rs | 92 +++++------ .../crates/test-fixture/src/lib.rs | 12 +- src/tools/rust-analyzer/crates/tt/src/lib.rs | 16 +- .../crates/vfs-notify/src/lib.rs | 85 +++++----- src/tools/rust-analyzer/xtask/src/codegen.rs | 10 +- .../rust-analyzer/xtask/src/publish/notes.rs | 138 ++++++++-------- 186 files changed, 3073 insertions(+), 3331 deletions(-) diff --git a/src/tools/rust-analyzer/crates/cfg/src/cfg_expr.rs b/src/tools/rust-analyzer/crates/cfg/src/cfg_expr.rs index aed00aa9fc44..f83c21eb8d64 100644 --- a/src/tools/rust-analyzer/crates/cfg/src/cfg_expr.rs +++ b/src/tools/rust-analyzer/crates/cfg/src/cfg_expr.rs @@ -134,10 +134,10 @@ fn next_cfg_expr(it: &mut tt::iter::TtIter<'_, S>) -> Option { }; // Eat comma separator - if let Some(TtElement::Leaf(tt::Leaf::Punct(punct))) = it.peek() { - if punct.char == ',' { - it.next(); - } + if let Some(TtElement::Leaf(tt::Leaf::Punct(punct))) = it.peek() + && punct.char == ',' + { + it.next(); } Some(ret) } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/attr.rs b/src/tools/rust-analyzer/crates/hir-def/src/attr.rs index b509e69b0d37..53250510f875 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/attr.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/attr.rs @@ -377,10 +377,10 @@ fn parse_repr_tt(tt: &crate::tt::TopSubtree) -> Option { let mut align = None; if let Some(TtElement::Subtree(_, mut tt_iter)) = tts.peek() { tts.next(); - if let Some(TtElement::Leaf(tt::Leaf::Literal(lit))) = tt_iter.next() { - if let Ok(a) = lit.symbol.as_str().parse() { - align = Align::from_bytes(a).ok(); - } + if let Some(TtElement::Leaf(tt::Leaf::Literal(lit))) = tt_iter.next() + && let Ok(a) = lit.symbol.as_str().parse() + { + align = Align::from_bytes(a).ok(); } } ReprOptions { align, ..Default::default() } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower.rs index abd1382801dd..3b9281ffb9c1 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower.rs @@ -1487,13 +1487,13 @@ impl ExprCollector<'_> { ast::Expr::UnderscoreExpr(_) => self.alloc_pat_from_expr(Pat::Wild, syntax_ptr), ast::Expr::ParenExpr(e) => { // We special-case `(..)` for consistency with patterns. - if let Some(ast::Expr::RangeExpr(range)) = e.expr() { - if range.is_range_full() { - return Some(self.alloc_pat_from_expr( - Pat::Tuple { args: Box::default(), ellipsis: Some(0) }, - syntax_ptr, - )); - } + if let Some(ast::Expr::RangeExpr(range)) = e.expr() + && range.is_range_full() + { + return Some(self.alloc_pat_from_expr( + Pat::Tuple { args: Box::default(), ellipsis: Some(0) }, + syntax_ptr, + )); } return e.expr().and_then(|expr| self.maybe_collect_expr_as_pat(&expr)); } @@ -2569,19 +2569,18 @@ impl ExprCollector<'_> { } } RibKind::MacroDef(macro_id) => { - if let Some((parent_ctx, label_macro_id)) = hygiene_info { - if label_macro_id == **macro_id { - // A macro is allowed to refer to labels from before its declaration. - // Therefore, if we got to the rib of its declaration, give up its hygiene - // and use its parent expansion. - - hygiene_id = - HygieneId::new(parent_ctx.opaque_and_semitransparent(self.db)); - hygiene_info = parent_ctx.outer_expn(self.db).map(|expansion| { - let expansion = self.db.lookup_intern_macro_call(expansion.into()); - (parent_ctx.parent(self.db), expansion.def) - }); - } + if let Some((parent_ctx, label_macro_id)) = hygiene_info + && label_macro_id == **macro_id + { + // A macro is allowed to refer to labels from before its declaration. + // Therefore, if we got to the rib of its declaration, give up its hygiene + // and use its parent expansion. + + hygiene_id = HygieneId::new(parent_ctx.opaque_and_semitransparent(self.db)); + hygiene_info = parent_ctx.outer_expn(self.db).map(|expansion| { + let expansion = self.db.lookup_intern_macro_call(expansion.into()); + (parent_ctx.parent(self.db), expansion.def) + }); } } _ => {} diff --git a/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower/asm.rs b/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower/asm.rs index 3bc4afb5c8ac..230d1c934636 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower/asm.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower/asm.rs @@ -259,10 +259,10 @@ impl ExprCollector<'_> { } }; - if let Some(operand_idx) = operand_idx { - if let Some(position_span) = to_span(arg.position_span) { - mappings.push((position_span, operand_idx)); - } + if let Some(operand_idx) = operand_idx + && let Some(position_span) = to_span(arg.position_span) + { + mappings.push((position_span, operand_idx)); } } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower/path.rs b/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower/path.rs index be006c98a582..579465e10f93 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower/path.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/expr_store/lower/path.rs @@ -211,16 +211,17 @@ pub(super) fn lower_path( // Basically, even in rustc it is quite hacky: // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456 // We follow what it did anyway :) - if segments.len() == 1 && kind == PathKind::Plain { - if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) { - let syn_ctxt = collector.expander.ctx_for_range(path.segment()?.syntax().text_range()); - if let Some(macro_call_id) = syn_ctxt.outer_expn(collector.db) { - if collector.db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner { - kind = match resolve_crate_root(collector.db, syn_ctxt) { - Some(crate_root) => PathKind::DollarCrate(crate_root), - None => PathKind::Crate, - } - } + if segments.len() == 1 + && kind == PathKind::Plain + && let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) + { + let syn_ctxt = collector.expander.ctx_for_range(path.segment()?.syntax().text_range()); + if let Some(macro_call_id) = syn_ctxt.outer_expn(collector.db) + && collector.db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner + { + kind = match resolve_crate_root(collector.db, syn_ctxt) { + Some(crate_root) => PathKind::DollarCrate(crate_root), + None => PathKind::Crate, } } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/expr_store/pretty.rs b/src/tools/rust-analyzer/crates/hir-def/src/expr_store/pretty.rs index f1b011333d94..b81dcc1fe96d 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/expr_store/pretty.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/expr_store/pretty.rs @@ -900,14 +900,12 @@ impl Printer<'_> { let field_name = arg.name.display(self.db, edition).to_string(); let mut same_name = false; - if let Pat::Bind { id, subpat: None } = &self.store[arg.pat] { - if let Binding { name, mode: BindingAnnotation::Unannotated, .. } = + if let Pat::Bind { id, subpat: None } = &self.store[arg.pat] + && let Binding { name, mode: BindingAnnotation::Unannotated, .. } = &self.store.assert_expr_only().bindings[*id] - { - if name.as_str() == field_name { - same_name = true; - } - } + && name.as_str() == field_name + { + same_name = true; } w!(p, "{}", field_name); diff --git a/src/tools/rust-analyzer/crates/hir-def/src/find_path.rs b/src/tools/rust-analyzer/crates/hir-def/src/find_path.rs index dccfff002f23..faa0ef8ceec7 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/find_path.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/find_path.rs @@ -107,11 +107,11 @@ struct FindPathCtx<'db> { /// Attempts to find a path to refer to the given `item` visible from the `from` ModuleId fn find_path_inner(ctx: &FindPathCtx<'_>, item: ItemInNs, max_len: usize) -> Option { // - if the item is a module, jump straight to module search - if !ctx.is_std_item { - if let ItemInNs::Types(ModuleDefId::ModuleId(module_id)) = item { - return find_path_for_module(ctx, &mut FxHashSet::default(), module_id, true, max_len) - .map(|choice| choice.path); - } + if !ctx.is_std_item + && let ItemInNs::Types(ModuleDefId::ModuleId(module_id)) = item + { + return find_path_for_module(ctx, &mut FxHashSet::default(), module_id, true, max_len) + .map(|choice| choice.path); } let may_be_in_scope = match ctx.prefix { @@ -226,15 +226,15 @@ fn find_path_for_module( } // - if the module can be referenced as self, super or crate, do that - if let Some(kind) = is_kw_kind_relative_to_from(ctx.from_def_map, module_id, ctx.from) { - if ctx.prefix != PrefixKind::ByCrate || kind == PathKind::Crate { - return Some(Choice { - path: ModPath::from_segments(kind, None), - path_text_len: path_kind_len(kind), - stability: Stable, - prefer_due_to_prelude: false, - }); - } + if let Some(kind) = is_kw_kind_relative_to_from(ctx.from_def_map, module_id, ctx.from) + && (ctx.prefix != PrefixKind::ByCrate || kind == PathKind::Crate) + { + return Some(Choice { + path: ModPath::from_segments(kind, None), + path_text_len: path_kind_len(kind), + stability: Stable, + prefer_due_to_prelude: false, + }); } // - if the module is in the prelude, return it by that path @@ -604,29 +604,29 @@ fn find_local_import_locations( &def_map[module.local_id] }; - if let Some((name, vis, declared)) = data.scope.name_of(item) { - if vis.is_visible_from(db, from) { - let is_pub_or_explicit = match vis { - Visibility::Module(_, VisibilityExplicitness::Explicit) => { - cov_mark::hit!(explicit_private_imports); - true - } - Visibility::Module(_, VisibilityExplicitness::Implicit) => { - cov_mark::hit!(discount_private_imports); - false - } - Visibility::PubCrate(_) => true, - Visibility::Public => true, - }; - - // Ignore private imports unless they are explicit. these could be used if we are - // in a submodule of this module, but that's usually not - // what the user wants; and if this module can import - // the item and we're a submodule of it, so can we. - // Also this keeps the cached data smaller. - if declared || is_pub_or_explicit { - cb(visited_modules, name, module); + if let Some((name, vis, declared)) = data.scope.name_of(item) + && vis.is_visible_from(db, from) + { + let is_pub_or_explicit = match vis { + Visibility::Module(_, VisibilityExplicitness::Explicit) => { + cov_mark::hit!(explicit_private_imports); + true } + Visibility::Module(_, VisibilityExplicitness::Implicit) => { + cov_mark::hit!(discount_private_imports); + false + } + Visibility::PubCrate(_) => true, + Visibility::Public => true, + }; + + // Ignore private imports unless they are explicit. these could be used if we are + // in a submodule of this module, but that's usually not + // what the user wants; and if this module can import + // the item and we're a submodule of it, so can we. + // Also this keeps the cached data smaller. + if declared || is_pub_or_explicit { + cb(visited_modules, name, module); } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_scope.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_scope.rs index efa439946850..8f526d1a2369 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_scope.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_scope.rs @@ -510,12 +510,11 @@ impl ItemScope { id: AttrId, idx: usize, ) { - if let Some(derives) = self.derive_macros.get_mut(&adt) { - if let Some(DeriveMacroInvocation { derive_call_ids, .. }) = + if let Some(derives) = self.derive_macros.get_mut(&adt) + && let Some(DeriveMacroInvocation { derive_call_ids, .. }) = derives.iter_mut().find(|&&mut DeriveMacroInvocation { attr_id, .. }| id == attr_id) - { - derive_call_ids[idx] = Some(call); - } + { + derive_call_ids[idx] = Some(call); } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs index 5ab61c89394b..032b287cd6a8 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs @@ -83,12 +83,12 @@ impl<'a> Ctx<'a> { .flat_map(|item| self.lower_mod_item(&item)) .collect(); - if let Some(ast::Expr::MacroExpr(tail_macro)) = stmts.expr() { - if let Some(call) = tail_macro.macro_call() { - cov_mark::hit!(macro_stmt_with_trailing_macro_expr); - if let Some(mod_item) = self.lower_mod_item(&call.into()) { - self.top_level.push(mod_item); - } + if let Some(ast::Expr::MacroExpr(tail_macro)) = stmts.expr() + && let Some(call) = tail_macro.macro_call() + { + cov_mark::hit!(macro_stmt_with_trailing_macro_expr); + if let Some(mod_item) = self.lower_mod_item(&call.into()) { + self.top_level.push(mod_item); } } @@ -112,12 +112,11 @@ impl<'a> Ctx<'a> { _ => None, }) .collect(); - if let Some(ast::Expr::MacroExpr(expr)) = block.tail_expr() { - if let Some(call) = expr.macro_call() { - if let Some(mod_item) = self.lower_mod_item(&call.into()) { - self.top_level.push(mod_item); - } - } + if let Some(ast::Expr::MacroExpr(expr)) = block.tail_expr() + && let Some(call) = expr.macro_call() + && let Some(mod_item) = self.lower_mod_item(&call.into()) + { + self.top_level.push(mod_item); } self.tree.vis.arena = self.visibilities.into_iter().collect(); self.tree.top_level = self.top_level.into_boxed_slice(); diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs index 750308026eec..d431f2140165 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs @@ -218,10 +218,10 @@ pub(crate) fn crate_notable_traits(db: &dyn DefDatabase, krate: Crate) -> Option for (_, module_data) in crate_def_map.modules() { for def in module_data.scope.declarations() { - if let ModuleDefId::TraitId(trait_) = def { - if db.attrs(trait_.into()).has_doc_notable_trait() { - traits.push(trait_); - } + if let ModuleDefId::TraitId(trait_) = def + && db.attrs(trait_.into()).has_doc_notable_trait() + { + traits.push(trait_); } } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/macro_expansion_tests/mod.rs b/src/tools/rust-analyzer/crates/hir-def/src/macro_expansion_tests/mod.rs index 5e95b061399a..e8ae499d27b2 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/macro_expansion_tests/mod.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/macro_expansion_tests/mod.rs @@ -221,46 +221,42 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream _ => None, }; - if let Some(src) = src { - if let Some(file_id) = src.file_id.macro_file() { - if let MacroKind::Derive - | MacroKind::DeriveBuiltIn - | MacroKind::Attr - | MacroKind::AttrBuiltIn = file_id.kind(&db) - { - let call = file_id.call_node(&db); - let mut show_spans = false; - let mut show_ctxt = false; - for comment in - call.value.children_with_tokens().filter(|it| it.kind() == COMMENT) - { - show_spans |= comment.to_string().contains("+spans"); - show_ctxt |= comment.to_string().contains("+syntaxctxt"); - } - let pp = pretty_print_macro_expansion( - src.value, - db.span_map(src.file_id).as_ref(), - show_spans, - show_ctxt, - ); - format_to!(expanded_text, "\n{}", pp) - } + if let Some(src) = src + && let Some(file_id) = src.file_id.macro_file() + && let MacroKind::Derive + | MacroKind::DeriveBuiltIn + | MacroKind::Attr + | MacroKind::AttrBuiltIn = file_id.kind(&db) + { + let call = file_id.call_node(&db); + let mut show_spans = false; + let mut show_ctxt = false; + for comment in call.value.children_with_tokens().filter(|it| it.kind() == COMMENT) { + show_spans |= comment.to_string().contains("+spans"); + show_ctxt |= comment.to_string().contains("+syntaxctxt"); } + let pp = pretty_print_macro_expansion( + src.value, + db.span_map(src.file_id).as_ref(), + show_spans, + show_ctxt, + ); + format_to!(expanded_text, "\n{}", pp) } } for impl_id in def_map[local_id].scope.impls() { let src = impl_id.lookup(&db).source(&db); - if let Some(macro_file) = src.file_id.macro_file() { - if let MacroKind::DeriveBuiltIn | MacroKind::Derive = macro_file.kind(&db) { - let pp = pretty_print_macro_expansion( - src.value.syntax().clone(), - db.span_map(macro_file.into()).as_ref(), - false, - false, - ); - format_to!(expanded_text, "\n{}", pp) - } + if let Some(macro_file) = src.file_id.macro_file() + && let MacroKind::DeriveBuiltIn | MacroKind::Derive = macro_file.kind(&db) + { + let pp = pretty_print_macro_expansion( + src.value.syntax().clone(), + db.span_map(macro_file.into()).as_ref(), + false, + false, + ); + format_to!(expanded_text, "\n{}", pp) } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs index 0c3274d849ad..267c4451b9d7 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs @@ -261,20 +261,20 @@ impl<'db> DefCollector<'db> { // Process other crate-level attributes. for attr in &*attrs { - if let Some(cfg) = attr.cfg() { - if self.cfg_options.check(&cfg) == Some(false) { - process = false; - break; - } + if let Some(cfg) = attr.cfg() + && self.cfg_options.check(&cfg) == Some(false) + { + process = false; + break; } let Some(attr_name) = attr.path.as_ident() else { continue }; match () { () if *attr_name == sym::recursion_limit => { - if let Some(limit) = attr.string_value() { - if let Ok(limit) = limit.as_str().parse() { - crate_data.recursion_limit = Some(limit); - } + if let Some(limit) = attr.string_value() + && let Ok(limit) = limit.as_str().parse() + { + crate_data.recursion_limit = Some(limit); } } () if *attr_name == sym::crate_type => { @@ -1188,56 +1188,44 @@ impl<'db> DefCollector<'db> { // Multiple globs may import the same item and they may override visibility from // previously resolved globs. Handle overrides here and leave the rest to // `ItemScope::push_res_with_import()`. - if let Some(def) = defs.types { - if let Some(prev_def) = prev_defs.types { - if def.def == prev_def.def - && self.from_glob_import.contains_type(module_id, name.clone()) - && def.vis != prev_def.vis - && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) - { - changed = true; - // This import is being handled here, don't pass it down to - // `ItemScope::push_res_with_import()`. - defs.types = None; - self.def_map.modules[module_id] - .scope - .update_visibility_types(name, def.vis); - } - } + if let Some(def) = defs.types + && let Some(prev_def) = prev_defs.types + && def.def == prev_def.def + && self.from_glob_import.contains_type(module_id, name.clone()) + && def.vis != prev_def.vis + && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) + { + changed = true; + // This import is being handled here, don't pass it down to + // `ItemScope::push_res_with_import()`. + defs.types = None; + self.def_map.modules[module_id].scope.update_visibility_types(name, def.vis); } - if let Some(def) = defs.values { - if let Some(prev_def) = prev_defs.values { - if def.def == prev_def.def - && self.from_glob_import.contains_value(module_id, name.clone()) - && def.vis != prev_def.vis - && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) - { - changed = true; - // See comment above. - defs.values = None; - self.def_map.modules[module_id] - .scope - .update_visibility_values(name, def.vis); - } - } + if let Some(def) = defs.values + && let Some(prev_def) = prev_defs.values + && def.def == prev_def.def + && self.from_glob_import.contains_value(module_id, name.clone()) + && def.vis != prev_def.vis + && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) + { + changed = true; + // See comment above. + defs.values = None; + self.def_map.modules[module_id].scope.update_visibility_values(name, def.vis); } - if let Some(def) = defs.macros { - if let Some(prev_def) = prev_defs.macros { - if def.def == prev_def.def - && self.from_glob_import.contains_macro(module_id, name.clone()) - && def.vis != prev_def.vis - && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) - { - changed = true; - // See comment above. - defs.macros = None; - self.def_map.modules[module_id] - .scope - .update_visibility_macros(name, def.vis); - } - } + if let Some(def) = defs.macros + && let Some(prev_def) = prev_defs.macros + && def.def == prev_def.def + && self.from_glob_import.contains_macro(module_id, name.clone()) + && def.vis != prev_def.vis + && def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis) + { + changed = true; + // See comment above. + defs.macros = None; + self.def_map.modules[module_id].scope.update_visibility_macros(name, def.vis); } } @@ -1392,15 +1380,14 @@ impl<'db> DefCollector<'db> { Resolved::Yes }; - if let Some(ident) = path.as_ident() { - if let Some(helpers) = self.def_map.derive_helpers_in_scope.get(&ast_id) { - if helpers.iter().any(|(it, ..)| it == ident) { - cov_mark::hit!(resolved_derive_helper); - // Resolved to derive helper. Collect the item's attributes again, - // starting after the derive helper. - return recollect_without(self); - } - } + if let Some(ident) = path.as_ident() + && let Some(helpers) = self.def_map.derive_helpers_in_scope.get(&ast_id) + && helpers.iter().any(|(it, ..)| it == ident) + { + cov_mark::hit!(resolved_derive_helper); + // Resolved to derive helper. Collect the item's attributes again, + // starting after the derive helper. + return recollect_without(self); } let def = match resolver_def_id(path) { @@ -1729,12 +1716,12 @@ impl ModCollector<'_, '_> { let mut process_mod_item = |item: ModItemId| { let attrs = self.item_tree.attrs(db, krate, item.ast_id()); - if let Some(cfg) = attrs.cfg() { - if !self.is_cfg_enabled(&cfg) { - let ast_id = item.ast_id().erase(); - self.emit_unconfigured_diagnostic(InFile::new(self.file_id(), ast_id), &cfg); - return; - } + if let Some(cfg) = attrs.cfg() + && !self.is_cfg_enabled(&cfg) + { + let ast_id = item.ast_id().erase(); + self.emit_unconfigured_diagnostic(InFile::new(self.file_id(), ast_id), &cfg); + return; } if let Err(()) = self.resolve_attributes(&attrs, item, container) { @@ -1871,14 +1858,13 @@ impl ModCollector<'_, '_> { if self.def_collector.def_map.block.is_none() && self.def_collector.is_proc_macro && self.module_id == DefMap::ROOT + && let Some(proc_macro) = attrs.parse_proc_macro_decl(&it.name) { - if let Some(proc_macro) = attrs.parse_proc_macro_decl(&it.name) { - self.def_collector.export_proc_macro( - proc_macro, - InFile::new(self.file_id(), id), - fn_id, - ); - } + self.def_collector.export_proc_macro( + proc_macro, + InFile::new(self.file_id(), id), + fn_id, + ); } update_def(self.def_collector, fn_id.into(), &it.name, vis, false); @@ -2419,13 +2405,13 @@ impl ModCollector<'_, '_> { macro_id, &self.item_tree[mac.visibility], ); - if let Some(helpers) = helpers_opt { - if self.def_collector.def_map.block.is_none() { - Arc::get_mut(&mut self.def_collector.def_map.data) - .unwrap() - .exported_derives - .insert(macro_id.into(), helpers); - } + if let Some(helpers) = helpers_opt + && self.def_collector.def_map.block.is_none() + { + Arc::get_mut(&mut self.def_collector.def_map.data) + .unwrap() + .exported_derives + .insert(macro_id.into(), helpers); } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs index 316ad5dae69d..a10990e6a8f9 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/resolver.rs @@ -228,15 +228,15 @@ impl<'db> Resolver<'db> { ResolvePathResultPrefixInfo::default(), )); } - } else if let &GenericDefId::AdtId(adt) = def { - if *first_name == sym::Self_ { - return Some(( - TypeNs::AdtSelfType(adt), - remaining_idx(), - None, - ResolvePathResultPrefixInfo::default(), - )); - } + } else if let &GenericDefId::AdtId(adt) = def + && *first_name == sym::Self_ + { + return Some(( + TypeNs::AdtSelfType(adt), + remaining_idx(), + None, + ResolvePathResultPrefixInfo::default(), + )); } if let Some(id) = params.find_type_by_name(first_name, *def) { return Some(( @@ -401,13 +401,13 @@ impl<'db> Resolver<'db> { handle_macro_def_scope(db, &mut hygiene_id, &mut hygiene_info, macro_id) } Scope::GenericParams { params, def } => { - if let &GenericDefId::ImplId(impl_) = def { - if *first_name == sym::Self_ { - return Some(( - ResolveValueResult::ValueNs(ValueNs::ImplSelf(impl_), None), - ResolvePathResultPrefixInfo::default(), - )); - } + if let &GenericDefId::ImplId(impl_) = def + && *first_name == sym::Self_ + { + return Some(( + ResolveValueResult::ValueNs(ValueNs::ImplSelf(impl_), None), + ResolvePathResultPrefixInfo::default(), + )); } if let Some(id) = params.find_const_by_name(first_name, *def) { let val = ValueNs::GenericParam(id); @@ -436,14 +436,14 @@ impl<'db> Resolver<'db> { ResolvePathResultPrefixInfo::default(), )); } - } else if let &GenericDefId::AdtId(adt) = def { - if *first_name == sym::Self_ { - let ty = TypeNs::AdtSelfType(adt); - return Some(( - ResolveValueResult::Partial(ty, 1, None), - ResolvePathResultPrefixInfo::default(), - )); - } + } else if let &GenericDefId::AdtId(adt) = def + && *first_name == sym::Self_ + { + let ty = TypeNs::AdtSelfType(adt); + return Some(( + ResolveValueResult::Partial(ty, 1, None), + ResolvePathResultPrefixInfo::default(), + )); } if let Some(id) = params.find_type_by_name(first_name, *def) { let ty = TypeNs::GenericParam(id); @@ -469,13 +469,14 @@ impl<'db> Resolver<'db> { // If a path of the shape `u16::from_le_bytes` failed to resolve at all, then we fall back // to resolving to the primitive type, to allow this to still work in the presence of // `use core::u16;`. - if path.kind == PathKind::Plain && n_segments > 1 { - if let Some(builtin) = BuiltinType::by_name(first_name) { - return Some(( - ResolveValueResult::Partial(TypeNs::BuiltinType(builtin), 1, None), - ResolvePathResultPrefixInfo::default(), - )); - } + if path.kind == PathKind::Plain + && n_segments > 1 + && let Some(builtin) = BuiltinType::by_name(first_name) + { + return Some(( + ResolveValueResult::Partial(TypeNs::BuiltinType(builtin), 1, None), + ResolvePathResultPrefixInfo::default(), + )); } None @@ -660,12 +661,11 @@ impl<'db> Resolver<'db> { Scope::BlockScope(m) => traits.extend(m.def_map[m.module_id].scope.traits()), &Scope::GenericParams { def: GenericDefId::ImplId(impl_), .. } => { let impl_data = db.impl_signature(impl_); - if let Some(target_trait) = impl_data.target_trait { - if let Some(TypeNs::TraitId(trait_)) = self + if let Some(target_trait) = impl_data.target_trait + && let Some(TypeNs::TraitId(trait_)) = self .resolve_path_in_type_ns_fully(db, &impl_data.store[target_trait.path]) - { - traits.insert(trait_); - } + { + traits.insert(trait_); } } _ => (), @@ -918,17 +918,17 @@ fn handle_macro_def_scope( hygiene_info: &mut Option<(SyntaxContext, MacroDefId)>, macro_id: &MacroDefId, ) { - if let Some((parent_ctx, label_macro_id)) = hygiene_info { - if label_macro_id == macro_id { - // A macro is allowed to refer to variables from before its declaration. - // Therefore, if we got to the rib of its declaration, give up its hygiene - // and use its parent expansion. - *hygiene_id = HygieneId::new(parent_ctx.opaque_and_semitransparent(db)); - *hygiene_info = parent_ctx.outer_expn(db).map(|expansion| { - let expansion = db.lookup_intern_macro_call(expansion.into()); - (parent_ctx.parent(db), expansion.def) - }); - } + if let Some((parent_ctx, label_macro_id)) = hygiene_info + && label_macro_id == macro_id + { + // A macro is allowed to refer to variables from before its declaration. + // Therefore, if we got to the rib of its declaration, give up its hygiene + // and use its parent expansion. + *hygiene_id = HygieneId::new(parent_ctx.opaque_and_semitransparent(db)); + *hygiene_info = parent_ctx.outer_expn(db).map(|expansion| { + let expansion = db.lookup_intern_macro_call(expansion.into()); + (parent_ctx.parent(db), expansion.def) + }); } } diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs b/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs index 4a9af01091f2..58ab7f470c40 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs @@ -555,12 +555,11 @@ fn concat_expand( // FIXME: hack on top of a hack: `$e:expr` captures get surrounded in parentheses // to ensure the right parsing order, so skip the parentheses here. Ideally we'd // implement rustc's model. cc https://github.com/rust-lang/rust-analyzer/pull/10623 - if let TtElement::Subtree(subtree, subtree_iter) = &t { - if let [tt::TokenTree::Leaf(tt)] = subtree_iter.remaining().flat_tokens() { - if subtree.delimiter.kind == tt::DelimiterKind::Parenthesis { - t = TtElement::Leaf(tt); - } - } + if let TtElement::Subtree(subtree, subtree_iter) = &t + && let [tt::TokenTree::Leaf(tt)] = subtree_iter.remaining().flat_tokens() + && subtree.delimiter.kind == tt::DelimiterKind::Parenthesis + { + t = TtElement::Leaf(tt); } match t { TtElement::Leaf(tt::Leaf::Literal(it)) if i % 2 == 0 => { diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/cfg_process.rs b/src/tools/rust-analyzer/crates/hir-expand/src/cfg_process.rs index c6ea4a3a33db..d5ebd6ee19f5 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/cfg_process.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/cfg_process.rs @@ -334,10 +334,10 @@ where _ => Some(CfgExpr::Atom(CfgAtom::Flag(name))), }, }; - if let Some(NodeOrToken::Token(element)) = iter.peek() { - if element.kind() == syntax::T![,] { - iter.next(); - } + if let Some(NodeOrToken::Token(element)) = iter.peek() + && element.kind() == syntax::T![,] + { + iter.next(); } result } diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/fixup.rs b/src/tools/rust-analyzer/crates/hir-expand/src/fixup.rs index 4a4a3e52aea4..fe77e1565987 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/fixup.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/fixup.rs @@ -280,8 +280,8 @@ pub(crate) fn fixup_syntax( } }, ast::RecordExprField(it) => { - if let Some(colon) = it.colon_token() { - if it.name_ref().is_some() && it.expr().is_none() { + if let Some(colon) = it.colon_token() + && it.name_ref().is_some() && it.expr().is_none() { append.insert(colon.into(), vec![ Leaf::Ident(Ident { sym: sym::__ra_fixup, @@ -290,11 +290,10 @@ pub(crate) fn fixup_syntax( }) ]); } - } }, ast::Path(it) => { - if let Some(colon) = it.coloncolon_token() { - if it.segment().is_none() { + if let Some(colon) = it.coloncolon_token() + && it.segment().is_none() { append.insert(colon.into(), vec![ Leaf::Ident(Ident { sym: sym::__ra_fixup, @@ -303,7 +302,6 @@ pub(crate) fn fixup_syntax( }) ]); } - } }, ast::ClosureExpr(it) => { if it.body().is_none() { diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs b/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs index ac61b2200970..472ec83ffef5 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs @@ -365,12 +365,11 @@ impl HirFileId { HirFileId::FileId(id) => break id, HirFileId::MacroFile(file) => { let loc = db.lookup_intern_macro_call(file); - if loc.def.is_include() { - if let MacroCallKind::FnLike { eager: Some(eager), .. } = &loc.kind { - if let Ok(it) = include_input_to_file_id(db, file, &eager.arg) { - break it; - } - } + if loc.def.is_include() + && let MacroCallKind::FnLike { eager: Some(eager), .. } = &loc.kind + && let Ok(it) = include_input_to_file_id(db, file, &eager.arg) + { + break it; } self = loc.kind.file_id(); } @@ -648,12 +647,11 @@ impl MacroCallLoc { db: &dyn ExpandDatabase, macro_call_id: MacroCallId, ) -> Option { - if self.def.is_include() { - if let MacroCallKind::FnLike { eager: Some(eager), .. } = &self.kind { - if let Ok(it) = include_input_to_file_id(db, macro_call_id, &eager.arg) { - return Some(it); - } - } + if self.def.is_include() + && let MacroCallKind::FnLike { eager: Some(eager), .. } = &self.kind + && let Ok(it) = include_input_to_file_id(db, macro_call_id, &eager.arg) + { + return Some(it); } None diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/mod_path.rs b/src/tools/rust-analyzer/crates/hir-expand/src/mod_path.rs index 9f1e3879e1ee..d84d978cdb7e 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/mod_path.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/mod_path.rs @@ -273,16 +273,17 @@ fn convert_path( // Basically, even in rustc it is quite hacky: // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456 // We follow what it did anyway :) - if mod_path.segments.len() == 1 && mod_path.kind == PathKind::Plain { - if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) { - let syn_ctx = span_for_range(segment.syntax().text_range()); - if let Some(macro_call_id) = syn_ctx.outer_expn(db) { - if db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner { - mod_path.kind = match resolve_crate_root(db, syn_ctx) { - Some(crate_root) => PathKind::DollarCrate(crate_root), - None => PathKind::Crate, - } - } + if mod_path.segments.len() == 1 + && mod_path.kind == PathKind::Plain + && let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) + { + let syn_ctx = span_for_range(segment.syntax().text_range()); + if let Some(macro_call_id) = syn_ctx.outer_expn(db) + && db.lookup_intern_macro_call(macro_call_id.into()).def.local_inner + { + mod_path.kind = match resolve_crate_root(db, syn_ctx) { + Some(crate_root) => PathKind::DollarCrate(crate_root), + None => PathKind::Crate, } } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/autoderef.rs b/src/tools/rust-analyzer/crates/hir-ty/src/autoderef.rs index cc8f7bf04a5c..26ca7fb9a15e 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/autoderef.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/autoderef.rs @@ -197,10 +197,11 @@ pub(crate) fn deref_by_trait( // effectively bump the MSRV of rust-analyzer to 1.84 due to 1.83 and below lacking the // blanked impl on `Deref`. #[expect(clippy::overly_complex_bool_expr)] - if use_receiver_trait && false { - if let Some(receiver) = LangItem::Receiver.resolve_trait(db, table.trait_env.krate) { - return Some(receiver); - } + if use_receiver_trait + && false + && let Some(receiver) = LangItem::Receiver.resolve_trait(db, table.trait_env.krate) + { + return Some(receiver); } // Old rustc versions might not have `Receiver` trait. // Fallback to `Deref` if they don't diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/builder.rs b/src/tools/rust-analyzer/crates/hir-ty/src/builder.rs index 77d15a73af6f..8af8fb73f344 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/builder.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/builder.rs @@ -309,11 +309,11 @@ impl TyBuilder { if let Some(defaults) = defaults.get(self.vec.len()..) { for default_ty in defaults { // NOTE(skip_binders): we only check if the arg type is error type. - if let Some(x) = default_ty.skip_binders().ty(Interner) { - if x.is_unknown() { - self.vec.push(fallback().cast(Interner)); - continue; - } + if let Some(x) = default_ty.skip_binders().ty(Interner) + && x.is_unknown() + { + self.vec.push(fallback().cast(Interner)); + continue; } // Each default can only depend on the previous parameters. self.vec.push(default_ty.clone().substitute(Interner, &*self.vec).cast(Interner)); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs b/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs index 26b635298a65..3ba7c93d4fb7 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/chalk_db.rs @@ -83,34 +83,34 @@ impl chalk_solve::RustIrDatabase for ChalkContext<'_> { Arc::new(rust_ir::AdtRepr { c: false, packed: false, int: None }) } fn discriminant_type(&self, ty: chalk_ir::Ty) -> chalk_ir::Ty { - if let chalk_ir::TyKind::Adt(id, _) = ty.kind(Interner) { - if let hir_def::AdtId::EnumId(e) = id.0 { - let enum_data = self.db.enum_signature(e); - let ty = enum_data.repr.unwrap_or_default().discr_type(); - return chalk_ir::TyKind::Scalar(match ty { - hir_def::layout::IntegerType::Pointer(is_signed) => match is_signed { - true => chalk_ir::Scalar::Int(chalk_ir::IntTy::Isize), - false => chalk_ir::Scalar::Uint(chalk_ir::UintTy::Usize), - }, - hir_def::layout::IntegerType::Fixed(size, is_signed) => match is_signed { - true => chalk_ir::Scalar::Int(match size { - hir_def::layout::Integer::I8 => chalk_ir::IntTy::I8, - hir_def::layout::Integer::I16 => chalk_ir::IntTy::I16, - hir_def::layout::Integer::I32 => chalk_ir::IntTy::I32, - hir_def::layout::Integer::I64 => chalk_ir::IntTy::I64, - hir_def::layout::Integer::I128 => chalk_ir::IntTy::I128, - }), - false => chalk_ir::Scalar::Uint(match size { - hir_def::layout::Integer::I8 => chalk_ir::UintTy::U8, - hir_def::layout::Integer::I16 => chalk_ir::UintTy::U16, - hir_def::layout::Integer::I32 => chalk_ir::UintTy::U32, - hir_def::layout::Integer::I64 => chalk_ir::UintTy::U64, - hir_def::layout::Integer::I128 => chalk_ir::UintTy::U128, - }), - }, - }) - .intern(Interner); - } + if let chalk_ir::TyKind::Adt(id, _) = ty.kind(Interner) + && let hir_def::AdtId::EnumId(e) = id.0 + { + let enum_data = self.db.enum_signature(e); + let ty = enum_data.repr.unwrap_or_default().discr_type(); + return chalk_ir::TyKind::Scalar(match ty { + hir_def::layout::IntegerType::Pointer(is_signed) => match is_signed { + true => chalk_ir::Scalar::Int(chalk_ir::IntTy::Isize), + false => chalk_ir::Scalar::Uint(chalk_ir::UintTy::Usize), + }, + hir_def::layout::IntegerType::Fixed(size, is_signed) => match is_signed { + true => chalk_ir::Scalar::Int(match size { + hir_def::layout::Integer::I8 => chalk_ir::IntTy::I8, + hir_def::layout::Integer::I16 => chalk_ir::IntTy::I16, + hir_def::layout::Integer::I32 => chalk_ir::IntTy::I32, + hir_def::layout::Integer::I64 => chalk_ir::IntTy::I64, + hir_def::layout::Integer::I128 => chalk_ir::IntTy::I128, + }), + false => chalk_ir::Scalar::Uint(match size { + hir_def::layout::Integer::I8 => chalk_ir::UintTy::U8, + hir_def::layout::Integer::I16 => chalk_ir::UintTy::U16, + hir_def::layout::Integer::I32 => chalk_ir::UintTy::U32, + hir_def::layout::Integer::I64 => chalk_ir::UintTy::U64, + hir_def::layout::Integer::I128 => chalk_ir::UintTy::U128, + }), + }, + }) + .intern(Interner); } chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U8)).intern(Interner) } @@ -142,10 +142,10 @@ impl chalk_solve::RustIrDatabase for ChalkContext<'_> { ) -> Option { if let TyKind::BoundVar(bv) = ty.kind(Interner) { let binders = binders.as_slice(Interner); - if bv.debruijn == DebruijnIndex::INNERMOST { - if let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind { - return Some(tk); - } + if bv.debruijn == DebruijnIndex::INNERMOST + && let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind + { + return Some(tk); } } None diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs index 14b9cd203f60..f30ec839a009 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/consteval.rs @@ -342,10 +342,10 @@ pub(crate) fn eval_to_const( return c; } } - if let Ok(mir_body) = lower_to_mir(ctx.db, ctx.owner, ctx.body, &infer, expr) { - if let Ok((Ok(result), _)) = interpret_mir(db, Arc::new(mir_body), true, None) { - return result; - } + if let Ok(mir_body) = lower_to_mir(ctx.db, ctx.owner, ctx.body, &infer, expr) + && let Ok((Ok(result), _)) = interpret_mir(db, Arc::new(mir_body), true, None) + { + return result; } unknown_const(infer[expr].clone()) } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs index 40fe3073cf2c..0815e62f87ee 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs @@ -657,10 +657,10 @@ impl<'a> DeclValidator<'a> { } fn is_trait_impl_container(&self, container_id: ItemContainerId) -> bool { - if let ItemContainerId::ImplId(impl_id) = container_id { - if self.db.impl_trait(impl_id).is_some() { - return true; - } + if let ItemContainerId::ImplId(impl_id) = container_id + && self.db.impl_trait(impl_id).is_some() + { + return true; } false } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs index cc531f076dd1..b26bd2b8fa9c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/expr.rs @@ -528,15 +528,15 @@ impl FilterMapNextChecker { return None; } - if *function_id == self.next_function_id? { - if let Some(prev_filter_map_expr_id) = self.prev_filter_map_expr_id { - let is_dyn_trait = self - .prev_receiver_ty - .as_ref() - .is_some_and(|it| it.strip_references().dyn_trait().is_some()); - if *receiver_expr_id == prev_filter_map_expr_id && !is_dyn_trait { - return Some(()); - } + if *function_id == self.next_function_id? + && let Some(prev_filter_map_expr_id) = self.prev_filter_map_expr_id + { + let is_dyn_trait = self + .prev_receiver_ty + .as_ref() + .is_some_and(|it| it.strip_references().dyn_trait().is_some()); + if *receiver_expr_id == prev_filter_map_expr_id && !is_dyn_trait { + return Some(()); } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check.rs index ca132fbdc454..e803b56a1ed8 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check.rs @@ -382,10 +382,10 @@ impl HirDisplay for Pat { let subpats = (0..num_fields).map(|i| { WriteWith(move |f| { let fid = LocalFieldId::from_raw((i as u32).into()); - if let Some(p) = subpatterns.get(i) { - if p.field == fid { - return p.pattern.hir_fmt(f); - } + if let Some(p) = subpatterns.get(i) + && p.field == fid + { + return p.pattern.hir_fmt(f); } if let Some(p) = subpatterns.iter().find(|p| p.field == fid) { p.pattern.hir_fmt(f) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs index f6ad3c7aae2d..827585e50693 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/unsafe_check.rs @@ -272,10 +272,10 @@ impl<'db> UnsafeVisitor<'db> { if let Some(func) = callee.as_fn_def(self.db) { self.check_call(current, func); } - if let TyKind::Function(fn_ptr) = callee.kind(Interner) { - if fn_ptr.sig.safety == chalk_ir::Safety::Unsafe { - self.on_unsafe_op(current.into(), UnsafetyReason::UnsafeFnCall); - } + if let TyKind::Function(fn_ptr) = callee.kind(Interner) + && fn_ptr.sig.safety == chalk_ir::Safety::Unsafe + { + self.on_unsafe_op(current.into(), UnsafetyReason::UnsafeFnCall); } } Expr::Path(path) => { @@ -346,12 +346,11 @@ impl<'db> UnsafeVisitor<'db> { Expr::Cast { .. } => self.inside_assignment = inside_assignment, Expr::Field { .. } => { self.inside_assignment = inside_assignment; - if !inside_assignment { - if let Some(Either::Left(FieldId { parent: VariantId::UnionId(_), .. })) = + if !inside_assignment + && let Some(Either::Left(FieldId { parent: VariantId::UnionId(_), .. })) = self.infer.field_resolution(current) - { - self.on_unsafe_op(current.into(), UnsafetyReason::UnionField); - } + { + self.on_unsafe_op(current.into(), UnsafetyReason::UnionField); } } Expr::Unsafe { statements, .. } => { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs index f0e31ebd020c..8f35a3c21455 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/display.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/display.rs @@ -608,48 +608,46 @@ impl HirDisplay for ProjectionTy { // if we are projection on a type parameter, check if the projection target has bounds // itself, if so, we render them directly as `impl Bound` instead of the less useful // `::Assoc` - if !f.display_kind.is_source_code() { - if let TyKind::Placeholder(idx) = self_ty.kind(Interner) { - if !f.bounds_formatting_ctx.contains(self) { - let db = f.db; - let id = from_placeholder_idx(db, *idx); - let generics = generics(db, id.parent); - - let substs = generics.placeholder_subst(db); - let bounds = db - .generic_predicates(id.parent) - .iter() - .map(|pred| pred.clone().substitute(Interner, &substs)) - .filter(|wc| { - let ty = match wc.skip_binders() { - WhereClause::Implemented(tr) => tr.self_type_parameter(Interner), - WhereClause::TypeOutlives(t) => t.ty.clone(), - // We shouldn't be here if these exist - WhereClause::AliasEq(_) | WhereClause::LifetimeOutlives(_) => { - return false; - } - }; - let TyKind::Alias(AliasTy::Projection(proj)) = ty.kind(Interner) else { - return false; - }; - proj == self - }) - .collect::>(); - if !bounds.is_empty() { - return f.format_bounds_with(self.clone(), |f| { - write_bounds_like_dyn_trait_with_prefix( - f, - "impl", - Either::Left( - &TyKind::Alias(AliasTy::Projection(self.clone())) - .intern(Interner), - ), - &bounds, - SizedByDefault::NotSized, - ) - }); - } - } + if !f.display_kind.is_source_code() + && let TyKind::Placeholder(idx) = self_ty.kind(Interner) + && !f.bounds_formatting_ctx.contains(self) + { + let db = f.db; + let id = from_placeholder_idx(db, *idx); + let generics = generics(db, id.parent); + + let substs = generics.placeholder_subst(db); + let bounds = db + .generic_predicates(id.parent) + .iter() + .map(|pred| pred.clone().substitute(Interner, &substs)) + .filter(|wc| { + let ty = match wc.skip_binders() { + WhereClause::Implemented(tr) => tr.self_type_parameter(Interner), + WhereClause::TypeOutlives(t) => t.ty.clone(), + // We shouldn't be here if these exist + WhereClause::AliasEq(_) | WhereClause::LifetimeOutlives(_) => { + return false; + } + }; + let TyKind::Alias(AliasTy::Projection(proj)) = ty.kind(Interner) else { + return false; + }; + proj == self + }) + .collect::>(); + if !bounds.is_empty() { + return f.format_bounds_with(self.clone(), |f| { + write_bounds_like_dyn_trait_with_prefix( + f, + "impl", + Either::Left( + &TyKind::Alias(AliasTy::Projection(self.clone())).intern(Interner), + ), + &bounds, + SizedByDefault::NotSized, + ) + }); } } @@ -1860,18 +1858,13 @@ fn write_bounds_like_dyn_trait( write!(f, "{}", f.db.trait_signature(trait_).name.display(f.db, f.edition()))?; f.end_location_link(); if is_fn_trait { - if let [self_, params @ ..] = trait_ref.substitution.as_slice(Interner) { - if let Some(args) = + if let [self_, params @ ..] = trait_ref.substitution.as_slice(Interner) + && let Some(args) = params.first().and_then(|it| it.assert_ty_ref(Interner).as_tuple()) - { - write!(f, "(")?; - hir_fmt_generic_arguments( - f, - args.as_slice(Interner), - self_.ty(Interner), - )?; - write!(f, ")")?; - } + { + write!(f, "(")?; + hir_fmt_generic_arguments(f, args.as_slice(Interner), self_.ty(Interner))?; + write!(f, ")")?; } } else { let params = generic_args_sans_defaults( @@ -1879,13 +1872,13 @@ fn write_bounds_like_dyn_trait( Some(trait_.into()), trait_ref.substitution.as_slice(Interner), ); - if let [self_, params @ ..] = params { - if !params.is_empty() { - write!(f, "<")?; - hir_fmt_generic_arguments(f, params, self_.ty(Interner))?; - // there might be assoc type bindings, so we leave the angle brackets open - angle_open = true; - } + if let [self_, params @ ..] = params + && !params.is_empty() + { + write!(f, "<")?; + hir_fmt_generic_arguments(f, params, self_.ty(Interner))?; + // there might be assoc type bindings, so we leave the angle brackets open + angle_open = true; } } } @@ -2443,11 +2436,11 @@ impl HirDisplayWithExpressionStore for Path { generic_args.args[0].hir_fmt(f, store)?; } } - if let Some(ret) = generic_args.bindings[0].type_ref { - if !matches!(&store[ret], TypeRef::Tuple(v) if v.is_empty()) { - write!(f, " -> ")?; - ret.hir_fmt(f, store)?; - } + if let Some(ret) = generic_args.bindings[0].type_ref + && !matches!(&store[ret], TypeRef::Tuple(v) if v.is_empty()) + { + write!(f, " -> ")?; + ret.hir_fmt(f, store)?; } } hir_def::expr_store::path::GenericArgsParentheses::No => { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/dyn_compatibility.rs b/src/tools/rust-analyzer/crates/hir-ty/src/dyn_compatibility.rs index 30949c83bfae..6294d683e6c0 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/dyn_compatibility.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/dyn_compatibility.rs @@ -136,16 +136,15 @@ pub fn generics_require_sized_self(db: &dyn HirDatabase, def: GenericDefId) -> b let predicates = predicates.iter().map(|p| p.skip_binders().skip_binders().clone()); elaborate_clause_supertraits(db, predicates).any(|pred| match pred { WhereClause::Implemented(trait_ref) => { - if from_chalk_trait_id(trait_ref.trait_id) == sized { - if let TyKind::BoundVar(it) = + if from_chalk_trait_id(trait_ref.trait_id) == sized + && let TyKind::BoundVar(it) = *trait_ref.self_type_parameter(Interner).kind(Interner) - { - // Since `generic_predicates` is `Binder>`, the `DebrujinIndex` of - // self-parameter is `1` - return it - .index_if_bound_at(DebruijnIndex::ONE) - .is_some_and(|idx| idx == trait_self_param_idx); - } + { + // Since `generic_predicates` is `Binder>`, the `DebrujinIndex` of + // self-parameter is `1` + return it + .index_if_bound_at(DebruijnIndex::ONE) + .is_some_and(|idx| idx == trait_self_param_idx); } false } @@ -401,10 +400,10 @@ where cb(MethodViolationCode::ReferencesSelfOutput)?; } - if !func_data.is_async() { - if let Some(mvc) = contains_illegal_impl_trait_in_trait(db, &sig) { - cb(mvc)?; - } + if !func_data.is_async() + && let Some(mvc) = contains_illegal_impl_trait_in_trait(db, &sig) + { + cb(mvc)?; } let generic_params = db.generic_params(func.into()); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index 7c39afa0ef89..86345b23364d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -902,12 +902,12 @@ impl<'db> InferenceContext<'db> { return false; } - if let UnresolvedMethodCall { field_with_same_name, .. } = diagnostic { - if let Some(ty) = field_with_same_name { - *ty = table.resolve_completely(ty.clone()); - if ty.contains_unknown() { - *field_with_same_name = None; - } + if let UnresolvedMethodCall { field_with_same_name, .. } = diagnostic + && let Some(ty) = field_with_same_name + { + *ty = table.resolve_completely(ty.clone()); + if ty.contains_unknown() { + *field_with_same_name = None; } } } @@ -1010,12 +1010,12 @@ impl<'db> InferenceContext<'db> { param_tys.push(va_list_ty); } let mut param_tys = param_tys.into_iter().chain(iter::repeat(self.table.new_type_var())); - if let Some(self_param) = self.body.self_param { - if let Some(ty) = param_tys.next() { - let ty = self.insert_type_vars(ty); - let ty = self.normalize_associated_types_in(ty); - self.write_binding_ty(self_param, ty); - } + if let Some(self_param) = self.body.self_param + && let Some(ty) = param_tys.next() + { + let ty = self.insert_type_vars(ty); + let ty = self.normalize_associated_types_in(ty); + self.write_binding_ty(self_param, ty); } let mut tait_candidates = FxHashSet::default(); for (ty, pat) in param_tys.zip(&*self.body.params) { @@ -1199,20 +1199,19 @@ impl<'db> InferenceContext<'db> { ) -> std::ops::ControlFlow { let ty = self.table.resolve_ty_shallow(ty); - if let TyKind::OpaqueType(id, _) = ty.kind(Interner) { - if let ImplTraitId::TypeAliasImplTrait(alias_id, _) = + if let TyKind::OpaqueType(id, _) = ty.kind(Interner) + && let ImplTraitId::TypeAliasImplTrait(alias_id, _) = self.db.lookup_intern_impl_trait_id((*id).into()) - { - let loc = self.db.lookup_intern_type_alias(alias_id); - match loc.container { - ItemContainerId::ImplId(impl_id) => { - self.assocs.insert(*id, (impl_id, ty.clone())); - } - ItemContainerId::ModuleId(..) | ItemContainerId::ExternBlockId(..) => { - self.non_assocs.insert(*id, ty.clone()); - } - _ => {} + { + let loc = self.db.lookup_intern_type_alias(alias_id); + match loc.container { + ItemContainerId::ImplId(impl_id) => { + self.assocs.insert(*id, (impl_id, ty.clone())); + } + ItemContainerId::ModuleId(..) | ItemContainerId::ExternBlockId(..) => { + self.non_assocs.insert(*id, ty.clone()); } + _ => {} } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/cast.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/cast.rs index 4e95eca3f940..f0a4167f8e25 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/cast.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/cast.rs @@ -233,26 +233,25 @@ impl CastCheck { F: FnMut(ExprId, Vec), { // Mutability order is opposite to rustc. `Mut < Not` - if m_expr <= m_cast { - if let TyKind::Array(ety, _) = t_expr.kind(Interner) { - // Coerce to a raw pointer so that we generate RawPtr in MIR. - let array_ptr_type = TyKind::Raw(m_expr, t_expr.clone()).intern(Interner); - if let Ok((adj, _)) = table.coerce(&self.expr_ty, &array_ptr_type, CoerceNever::Yes) - { - apply_adjustments(self.source_expr, adj); - } else { - never!( - "could not cast from reference to array to pointer to array ({:?} to {:?})", - self.expr_ty, - array_ptr_type - ); - } + if m_expr <= m_cast + && let TyKind::Array(ety, _) = t_expr.kind(Interner) + { + // Coerce to a raw pointer so that we generate RawPtr in MIR. + let array_ptr_type = TyKind::Raw(m_expr, t_expr.clone()).intern(Interner); + if let Ok((adj, _)) = table.coerce(&self.expr_ty, &array_ptr_type, CoerceNever::Yes) { + apply_adjustments(self.source_expr, adj); + } else { + never!( + "could not cast from reference to array to pointer to array ({:?} to {:?})", + self.expr_ty, + array_ptr_type + ); + } - // This is a less strict condition than rustc's `demand_eqtype`, - // but false negative is better than false positive - if table.coerce(ety, t_cast, CoerceNever::Yes).is_ok() { - return Ok(()); - } + // This is a less strict condition than rustc's `demand_eqtype`, + // but false negative is better than false positive + if table.coerce(ety, t_cast, CoerceNever::Yes).is_ok() { + return Ok(()); } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs index c3029bf2b59a..8024c1a9a4e9 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure.rs @@ -176,12 +176,12 @@ impl InferenceContext<'_> { } // Deduction based on the expected `dyn Fn` is done separately. - if let TyKind::Dyn(dyn_ty) = expected_ty.kind(Interner) { - if let Some(sig) = self.deduce_sig_from_dyn_ty(dyn_ty) { - let expected_sig_ty = TyKind::Function(sig).intern(Interner); + if let TyKind::Dyn(dyn_ty) = expected_ty.kind(Interner) + && let Some(sig) = self.deduce_sig_from_dyn_ty(dyn_ty) + { + let expected_sig_ty = TyKind::Function(sig).intern(Interner); - self.unify(sig_ty, &expected_sig_ty); - } + self.unify(sig_ty, &expected_sig_ty); } } @@ -208,14 +208,13 @@ impl InferenceContext<'_> { alias: AliasTy::Projection(projection_ty), ty: projected_ty, }) = bound.skip_binders() - { - if let Some(sig) = self.deduce_sig_from_projection( + && let Some(sig) = self.deduce_sig_from_projection( closure_kind, projection_ty, projected_ty, - ) { - return Some(sig); - } + ) + { + return Some(sig); } None }); @@ -254,55 +253,44 @@ impl InferenceContext<'_> { let mut expected_kind = None; for clause in elaborate_clause_supertraits(self.db, clauses.rev()) { - if expected_sig.is_none() { - if let WhereClause::AliasEq(AliasEq { - alias: AliasTy::Projection(projection), - ty, - }) = &clause - { - let inferred_sig = - self.deduce_sig_from_projection(closure_kind, projection, ty); - // Make sure that we didn't infer a signature that mentions itself. - // This can happen when we elaborate certain supertrait bounds that - // mention projections containing the `Self` type. See rust-lang/rust#105401. - struct MentionsTy<'a> { - expected_ty: &'a Ty, - } - impl TypeVisitor for MentionsTy<'_> { - type BreakTy = (); + if expected_sig.is_none() + && let WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection), ty }) = + &clause + { + let inferred_sig = self.deduce_sig_from_projection(closure_kind, projection, ty); + // Make sure that we didn't infer a signature that mentions itself. + // This can happen when we elaborate certain supertrait bounds that + // mention projections containing the `Self` type. See rust-lang/rust#105401. + struct MentionsTy<'a> { + expected_ty: &'a Ty, + } + impl TypeVisitor for MentionsTy<'_> { + type BreakTy = (); - fn interner(&self) -> Interner { - Interner - } + fn interner(&self) -> Interner { + Interner + } - fn as_dyn( - &mut self, - ) -> &mut dyn TypeVisitor - { - self - } + fn as_dyn( + &mut self, + ) -> &mut dyn TypeVisitor + { + self + } - fn visit_ty( - &mut self, - t: &Ty, - db: chalk_ir::DebruijnIndex, - ) -> ControlFlow<()> { - if t == self.expected_ty { - ControlFlow::Break(()) - } else { - t.super_visit_with(self, db) - } + fn visit_ty(&mut self, t: &Ty, db: chalk_ir::DebruijnIndex) -> ControlFlow<()> { + if t == self.expected_ty { + ControlFlow::Break(()) + } else { + t.super_visit_with(self, db) } } - if inferred_sig - .visit_with( - &mut MentionsTy { expected_ty }, - chalk_ir::DebruijnIndex::INNERMOST, - ) - .is_continue() - { - expected_sig = inferred_sig; - } + } + if inferred_sig + .visit_with(&mut MentionsTy { expected_ty }, chalk_ir::DebruijnIndex::INNERMOST) + .is_continue() + { + expected_sig = inferred_sig; } } @@ -617,11 +605,10 @@ impl HirPlace { if let CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhasedBorrow, }) = current_capture + && self.projections[len..].contains(&ProjectionElem::Deref) { - if self.projections[len..].contains(&ProjectionElem::Deref) { - current_capture = - CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }); - } + current_capture = + CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }); } current_capture } @@ -1076,12 +1063,11 @@ impl InferenceContext<'_> { Mutability::Mut => CaptureKind::ByRef(BorrowKind::Mut { kind: MutBorrowKind::Default }), Mutability::Not => CaptureKind::ByRef(BorrowKind::Shared), }; - if let Some(place) = self.place_of_expr_without_adjust(tgt_expr) { - if let Some(place) = + if let Some(place) = self.place_of_expr_without_adjust(tgt_expr) + && let Some(place) = apply_adjusts_to_place(&mut self.current_capture_span_stack, place, rest) - { - self.add_capture(place, capture_kind); - } + { + self.add_capture(place, capture_kind); } self.walk_expr_with_adjust(tgt_expr, rest); } @@ -1169,15 +1155,15 @@ impl InferenceContext<'_> { } } self.walk_expr(*expr); - if let Some(discr_place) = self.place_of_expr(*expr) { - if self.is_upvar(&discr_place) { - let mut capture_mode = None; - for arm in arms.iter() { - self.walk_pat(&mut capture_mode, arm.pat); - } - if let Some(c) = capture_mode { - self.push_capture(discr_place, c); - } + if let Some(discr_place) = self.place_of_expr(*expr) + && self.is_upvar(&discr_place) + { + let mut capture_mode = None; + for arm in arms.iter() { + self.walk_pat(&mut capture_mode, arm.pat); + } + if let Some(c) = capture_mode { + self.push_capture(discr_place, c); } } } @@ -1209,13 +1195,11 @@ impl InferenceContext<'_> { let mutability = 'b: { if let Some(deref_trait) = self.resolve_lang_item(LangItem::DerefMut).and_then(|it| it.as_trait()) - { - if let Some(deref_fn) = deref_trait + && let Some(deref_fn) = deref_trait .trait_items(self.db) .method_by_name(&Name::new_symbol_root(sym::deref_mut)) - { - break 'b deref_fn == f; - } + { + break 'b deref_fn == f; } false }; @@ -1405,10 +1389,10 @@ impl InferenceContext<'_> { fn expr_ty_after_adjustments(&self, e: ExprId) -> Ty { let mut ty = None; - if let Some(it) = self.result.expr_adjustments.get(&e) { - if let Some(it) = it.last() { - ty = Some(it.target.clone()); - } + if let Some(it) = self.result.expr_adjustments.get(&e) + && let Some(it) = it.last() + { + ty = Some(it.target.clone()); } ty.unwrap_or_else(|| self.expr_ty(e)) } @@ -1793,10 +1777,10 @@ impl InferenceContext<'_> { } pub(super) fn add_current_closure_dependency(&mut self, dep: ClosureId) { - if let Some(c) = self.current_closure { - if !dep_creates_cycle(&self.closure_dependencies, &mut FxHashSet::default(), c, dep) { - self.closure_dependencies.entry(c).or_default().push(dep); - } + if let Some(c) = self.current_closure + && !dep_creates_cycle(&self.closure_dependencies, &mut FxHashSet::default(), c, dep) + { + self.closure_dependencies.entry(c).or_default().push(dep); } fn dep_creates_cycle( diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/coerce.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/coerce.rs index 39bd90849fe8..761a2564aa79 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/coerce.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/coerce.rs @@ -164,14 +164,14 @@ impl CoerceMany { // - [Comment from rustc](https://github.com/rust-lang/rust/blob/5ff18d0eaefd1bd9ab8ec33dab2404a44e7631ed/compiler/rustc_hir_typeck/src/coercion.rs#L1334-L1335) // First try to coerce the new expression to the type of the previous ones, // but only if the new expression has no coercion already applied to it. - if expr.is_none_or(|expr| !ctx.result.expr_adjustments.contains_key(&expr)) { - if let Ok(res) = ctx.coerce(expr, &expr_ty, &self.merged_ty(), CoerceNever::Yes) { - self.final_ty = Some(res); - if let Some(expr) = expr { - self.expressions.push(expr); - } - return; + if expr.is_none_or(|expr| !ctx.result.expr_adjustments.contains_key(&expr)) + && let Ok(res) = ctx.coerce(expr, &expr_ty, &self.merged_ty(), CoerceNever::Yes) + { + self.final_ty = Some(res); + if let Some(expr) = expr { + self.expressions.push(expr); } + return; } if let Ok((adjustments, res)) = @@ -322,18 +322,13 @@ impl InferenceTable<'_> { // If we are coercing into a TAIT, coerce into its proxy inference var, instead. let mut to_ty = to_ty; let _to; - if let Some(tait_table) = &self.tait_coercion_table { - if let TyKind::OpaqueType(opaque_ty_id, _) = to_ty.kind(Interner) { - if !matches!( - from_ty.kind(Interner), - TyKind::InferenceVar(..) | TyKind::OpaqueType(..) - ) { - if let Some(ty) = tait_table.get(opaque_ty_id) { - _to = ty.clone(); - to_ty = &_to; - } - } - } + if let Some(tait_table) = &self.tait_coercion_table + && let TyKind::OpaqueType(opaque_ty_id, _) = to_ty.kind(Interner) + && !matches!(from_ty.kind(Interner), TyKind::InferenceVar(..) | TyKind::OpaqueType(..)) + && let Some(ty) = tait_table.get(opaque_ty_id) + { + _to = ty.clone(); + to_ty = &_to; } // Consider coercing the subtype to a DST @@ -594,14 +589,13 @@ impl InferenceTable<'_> { F: FnOnce(Ty) -> Vec, G: FnOnce(Ty) -> Vec, { - if let TyKind::Function(to_fn_ptr) = to_ty.kind(Interner) { - if let (chalk_ir::Safety::Safe, chalk_ir::Safety::Unsafe) = + if let TyKind::Function(to_fn_ptr) = to_ty.kind(Interner) + && let (chalk_ir::Safety::Safe, chalk_ir::Safety::Unsafe) = (from_fn_ptr.sig.safety, to_fn_ptr.sig.safety) - { - let from_unsafe = - TyKind::Function(safe_to_unsafe_fn_ty(from_fn_ptr.clone())).intern(Interner); - return self.unify_and(&from_unsafe, to_ty, to_unsafe); - } + { + let from_unsafe = + TyKind::Function(safe_to_unsafe_fn_ty(from_fn_ptr.clone())).intern(Interner); + return self.unify_and(&from_unsafe, to_ty, to_unsafe); } self.unify_and(&from_ty, to_ty, normal) } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs index d43c99fc2827..16fc2bfc0631 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/expr.rs @@ -653,19 +653,18 @@ impl InferenceContext<'_> { // FIXME: Note down method resolution her match op { UnaryOp::Deref => { - if let Some(deref_trait) = self.resolve_lang_trait(LangItem::Deref) { - if let Some(deref_fn) = deref_trait + if let Some(deref_trait) = self.resolve_lang_trait(LangItem::Deref) + && let Some(deref_fn) = deref_trait .trait_items(self.db) .method_by_name(&Name::new_symbol_root(sym::deref)) - { - // FIXME: this is wrong in multiple ways, subst is empty, and we emit it even for builtin deref (note that - // the mutability is not wrong, and will be fixed in `self.infer_mut`). - self.write_method_resolution( - tgt_expr, - deref_fn, - Substitution::empty(Interner), - ); - } + { + // FIXME: this is wrong in multiple ways, subst is empty, and we emit it even for builtin deref (note that + // the mutability is not wrong, and will be fixed in `self.infer_mut`). + self.write_method_resolution( + tgt_expr, + deref_fn, + Substitution::empty(Interner), + ); } if let Some(derefed) = builtin_deref(self.table.db, &inner_ty, true) { self.resolve_ty_shallow(derefed) @@ -1387,28 +1386,28 @@ impl InferenceContext<'_> { let ret_ty = match method_ty.callable_sig(self.db) { Some(sig) => { let p_left = &sig.params()[0]; - if matches!(op, BinaryOp::CmpOp(..) | BinaryOp::Assignment { .. }) { - if let TyKind::Ref(mtbl, lt, _) = p_left.kind(Interner) { - self.write_expr_adj( - lhs, - Box::new([Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(lt.clone(), *mtbl)), - target: p_left.clone(), - }]), - ); - } + if matches!(op, BinaryOp::CmpOp(..) | BinaryOp::Assignment { .. }) + && let TyKind::Ref(mtbl, lt, _) = p_left.kind(Interner) + { + self.write_expr_adj( + lhs, + Box::new([Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(lt.clone(), *mtbl)), + target: p_left.clone(), + }]), + ); } let p_right = &sig.params()[1]; - if matches!(op, BinaryOp::CmpOp(..)) { - if let TyKind::Ref(mtbl, lt, _) = p_right.kind(Interner) { - self.write_expr_adj( - rhs, - Box::new([Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(lt.clone(), *mtbl)), - target: p_right.clone(), - }]), - ); - } + if matches!(op, BinaryOp::CmpOp(..)) + && let TyKind::Ref(mtbl, lt, _) = p_right.kind(Interner) + { + self.write_expr_adj( + rhs, + Box::new([Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(lt.clone(), *mtbl)), + target: p_right.clone(), + }]), + ); } sig.ret().clone() } @@ -1664,14 +1663,12 @@ impl InferenceContext<'_> { Some((ty, field_id, adjustments, is_public)) => { self.write_expr_adj(receiver, adjustments.into_boxed_slice()); self.result.field_resolutions.insert(tgt_expr, field_id); - if !is_public { - if let Either::Left(field) = field_id { - // FIXME: Merge this diagnostic into UnresolvedField? - self.push_diagnostic(InferenceDiagnostic::PrivateField { - expr: tgt_expr, - field, - }); - } + if !is_public && let Either::Left(field) = field_id { + // FIXME: Merge this diagnostic into UnresolvedField? + self.push_diagnostic(InferenceDiagnostic::PrivateField { + expr: tgt_expr, + field, + }); } ty } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs index 3f7eba9dd18c..c798e9e050a1 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/mutability.rs @@ -124,53 +124,41 @@ impl InferenceContext<'_> { self.infer_mut_not_expr_iter(fields.iter().map(|it| it.expr).chain(*spread)) } &Expr::Index { base, index } => { - if mutability == Mutability::Mut { - if let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) { - if let Some(index_trait) = - LangItem::IndexMut.resolve_trait(self.db, self.table.trait_env.krate) - { - if let Some(index_fn) = index_trait - .trait_items(self.db) - .method_by_name(&Name::new_symbol_root(sym::index_mut)) - { - *f = index_fn; - let mut base_ty = None; - let base_adjustments = self - .result - .expr_adjustments - .get_mut(&base) - .and_then(|it| it.last_mut()); - if let Some(Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(_, mutability)), - target, - }) = base_adjustments - { - if let TyKind::Ref(_, _, ty) = target.kind(Interner) { - base_ty = Some(ty.clone()); - } - *mutability = Mutability::Mut; - } - - // Apply `IndexMut` obligation for non-assignee expr - if let Some(base_ty) = base_ty { - let index_ty = - if let Some(ty) = self.result.type_of_expr.get(index) { - ty.clone() - } else { - self.infer_expr( - index, - &Expectation::none(), - ExprIsRead::Yes, - ) - }; - let trait_ref = TyBuilder::trait_ref(self.db, index_trait) - .push(base_ty) - .fill(|_| index_ty.clone().cast(Interner)) - .build(); - self.push_obligation(trait_ref.cast(Interner)); - } - } + if mutability == Mutability::Mut + && let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) + && let Some(index_trait) = + LangItem::IndexMut.resolve_trait(self.db, self.table.trait_env.krate) + && let Some(index_fn) = index_trait + .trait_items(self.db) + .method_by_name(&Name::new_symbol_root(sym::index_mut)) + { + *f = index_fn; + let mut base_ty = None; + let base_adjustments = + self.result.expr_adjustments.get_mut(&base).and_then(|it| it.last_mut()); + if let Some(Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(_, mutability)), + target, + }) = base_adjustments + { + if let TyKind::Ref(_, _, ty) = target.kind(Interner) { + base_ty = Some(ty.clone()); } + *mutability = Mutability::Mut; + } + + // Apply `IndexMut` obligation for non-assignee expr + if let Some(base_ty) = base_ty { + let index_ty = if let Some(ty) = self.result.type_of_expr.get(index) { + ty.clone() + } else { + self.infer_expr(index, &Expectation::none(), ExprIsRead::Yes) + }; + let trait_ref = TyBuilder::trait_ref(self.db, index_trait) + .push(base_ty) + .fill(|_| index_ty.clone().cast(Interner)) + .build(); + self.push_obligation(trait_ref.cast(Interner)); } } self.infer_mut_expr(base, mutability); @@ -178,28 +166,23 @@ impl InferenceContext<'_> { } Expr::UnaryOp { expr, op: UnaryOp::Deref } => { let mut mutability = mutability; - if let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) { - if mutability == Mutability::Mut { - if let Some(deref_trait) = - LangItem::DerefMut.resolve_trait(self.db, self.table.trait_env.krate) - { - let ty = self.result.type_of_expr.get(*expr); - let is_mut_ptr = ty.is_some_and(|ty| { - let ty = self.table.resolve_ty_shallow(ty); - matches!( - ty.kind(Interner), - chalk_ir::TyKind::Raw(Mutability::Mut, _) - ) - }); - if is_mut_ptr { - mutability = Mutability::Not; - } else if let Some(deref_fn) = deref_trait - .trait_items(self.db) - .method_by_name(&Name::new_symbol_root(sym::deref_mut)) - { - *f = deref_fn; - } - } + if let Some((f, _)) = self.result.method_resolutions.get_mut(&tgt_expr) + && mutability == Mutability::Mut + && let Some(deref_trait) = + LangItem::DerefMut.resolve_trait(self.db, self.table.trait_env.krate) + { + let ty = self.result.type_of_expr.get(*expr); + let is_mut_ptr = ty.is_some_and(|ty| { + let ty = self.table.resolve_ty_shallow(ty); + matches!(ty.kind(Interner), chalk_ir::TyKind::Raw(Mutability::Mut, _)) + }); + if is_mut_ptr { + mutability = Mutability::Not; + } else if let Some(deref_fn) = deref_trait + .trait_items(self.db) + .method_by_name(&Name::new_symbol_root(sym::deref_mut)) + { + *f = deref_fn; } } self.infer_mut_expr(*expr, mutability); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/pat.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/pat.rs index 18288b718f76..707bec0fce4c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/pat.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/pat.rs @@ -498,12 +498,12 @@ impl InferenceContext<'_> { // If `expected` is an infer ty, we try to equate it to an array if the given pattern // allows it. See issue #16609 - if self.pat_is_irrefutable(decl) && expected.is_ty_var() { - if let Some(resolved_array_ty) = + if self.pat_is_irrefutable(decl) + && expected.is_ty_var() + && let Some(resolved_array_ty) = self.try_resolve_slice_ty_to_array_ty(prefix, suffix, slice) - { - self.unify(&expected, &resolved_array_ty); - } + { + self.unify(&expected, &resolved_array_ty); } let expected = self.resolve_ty_shallow(&expected); @@ -539,17 +539,16 @@ impl InferenceContext<'_> { fn infer_lit_pat(&mut self, expr: ExprId, expected: &Ty) -> Ty { // Like slice patterns, byte string patterns can denote both `&[u8; N]` and `&[u8]`. - if let Expr::Literal(Literal::ByteString(_)) = self.body[expr] { - if let Some((inner, ..)) = expected.as_reference() { - let inner = self.resolve_ty_shallow(inner); - if matches!(inner.kind(Interner), TyKind::Slice(_)) { - let elem_ty = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner); - let slice_ty = TyKind::Slice(elem_ty).intern(Interner); - let ty = - TyKind::Ref(Mutability::Not, static_lifetime(), slice_ty).intern(Interner); - self.write_expr_ty(expr, ty.clone()); - return ty; - } + if let Expr::Literal(Literal::ByteString(_)) = self.body[expr] + && let Some((inner, ..)) = expected.as_reference() + { + let inner = self.resolve_ty_shallow(inner); + if matches!(inner.kind(Interner), TyKind::Slice(_)) { + let elem_ty = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner); + let slice_ty = TyKind::Slice(elem_ty).intern(Interner); + let ty = TyKind::Ref(Mutability::Not, static_lifetime(), slice_ty).intern(Interner); + self.write_expr_ty(expr, ty.clone()); + return ty; } } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs index d61e7de6672f..afee9606bd5f 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lower.rs @@ -830,10 +830,10 @@ fn named_associated_type_shorthand_candidates( let data = t.hir_trait_id().trait_items(db); for (name, assoc_id) in &data.items { - if let AssocItemId::TypeAliasId(alias) = assoc_id { - if let Some(result) = cb(name, &t, *alias) { - return Some(result); - } + if let AssocItemId::TypeAliasId(alias) = assoc_id + && let Some(result) = cb(name, &t, *alias) + { + return Some(result); } } None diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs index 5c06234fa077..9519c38eeddf 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs @@ -360,15 +360,14 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { } } - if let Some(enum_segment) = enum_segment { - if segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some()) - && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some()) - { - self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited { - segment: (enum_segment + 1) as u32, - reason: GenericArgsProhibitedReason::EnumVariant, - }); - } + if let Some(enum_segment) = enum_segment + && segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some()) + && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some()) + { + self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited { + segment: (enum_segment + 1) as u32, + reason: GenericArgsProhibitedReason::EnumVariant, + }); } self.handle_type_ns_resolution(&resolution); @@ -417,15 +416,14 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { } } - if let Some(enum_segment) = enum_segment { - if segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some()) - && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some()) - { - self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited { - segment: (enum_segment + 1) as u32, - reason: GenericArgsProhibitedReason::EnumVariant, - }); - } + if let Some(enum_segment) = enum_segment + && segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some()) + && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some()) + { + self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited { + segment: (enum_segment + 1) as u32, + reason: GenericArgsProhibitedReason::EnumVariant, + }); } match &res { @@ -576,13 +574,12 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { // This simplifies the code a bit. let penultimate_idx = self.current_segment_idx.wrapping_sub(1); let penultimate = self.segments.get(penultimate_idx); - if let Some(penultimate) = penultimate { - if self.current_or_prev_segment.args_and_bindings.is_none() - && penultimate.args_and_bindings.is_some() - { - self.current_segment_idx = penultimate_idx; - self.current_or_prev_segment = penultimate; - } + if let Some(penultimate) = penultimate + && self.current_or_prev_segment.args_and_bindings.is_none() + && penultimate.args_and_bindings.is_some() + { + self.current_segment_idx = penultimate_idx; + self.current_or_prev_segment = penultimate; } var.lookup(self.ctx.db).parent.into() } @@ -607,37 +604,36 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { ) -> Substitution { let mut lifetime_elision = self.ctx.lifetime_elision.clone(); - if let Some(args) = self.current_or_prev_segment.args_and_bindings { - if args.parenthesized != GenericArgsParentheses::No { - let prohibit_parens = match def { - GenericDefId::TraitId(trait_) => { - // RTN is prohibited anyways if we got here. - let is_rtn = - args.parenthesized == GenericArgsParentheses::ReturnTypeNotation; - let is_fn_trait = self - .ctx - .db - .trait_signature(trait_) - .flags - .contains(TraitFlags::RUSTC_PAREN_SUGAR); - is_rtn || !is_fn_trait - } - _ => true, - }; - - if prohibit_parens { - let segment = self.current_segment_u32(); - self.on_diagnostic( - PathLoweringDiagnostic::ParenthesizedGenericArgsWithoutFnTrait { segment }, - ); - - return TyBuilder::unknown_subst(self.ctx.db, def); + if let Some(args) = self.current_or_prev_segment.args_and_bindings + && args.parenthesized != GenericArgsParentheses::No + { + let prohibit_parens = match def { + GenericDefId::TraitId(trait_) => { + // RTN is prohibited anyways if we got here. + let is_rtn = args.parenthesized == GenericArgsParentheses::ReturnTypeNotation; + let is_fn_trait = self + .ctx + .db + .trait_signature(trait_) + .flags + .contains(TraitFlags::RUSTC_PAREN_SUGAR); + is_rtn || !is_fn_trait } + _ => true, + }; - // `Fn()`-style generics are treated like functions for the purpose of lifetime elision. - lifetime_elision = - LifetimeElisionKind::AnonymousCreateParameter { report_in_path: false }; + if prohibit_parens { + let segment = self.current_segment_u32(); + self.on_diagnostic( + PathLoweringDiagnostic::ParenthesizedGenericArgsWithoutFnTrait { segment }, + ); + + return TyBuilder::unknown_subst(self.ctx.db, def); } + + // `Fn()`-style generics are treated like functions for the purpose of lifetime elision. + lifetime_elision = + LifetimeElisionKind::AnonymousCreateParameter { report_in_path: false }; } self.substs_from_args_and_bindings( @@ -753,18 +749,20 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> { match param { GenericParamDataRef::LifetimeParamData(_) => error_lifetime().cast(Interner), GenericParamDataRef::TypeParamData(param) => { - if !infer_args && param.default.is_some() { - if let Some(default) = default() { - return default; - } + if !infer_args + && param.default.is_some() + && let Some(default) = default() + { + return default; } TyKind::Error.intern(Interner).cast(Interner) } GenericParamDataRef::ConstParamData(param) => { - if !infer_args && param.default.is_some() { - if let Some(default) = default() { - return default; - } + if !infer_args + && param.default.is_some() + && let Some(default) = default() + { + return default; } let GenericParamId::ConstParamId(const_id) = param_id else { unreachable!("non-const param ID for const param"); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/method_resolution.rs b/src/tools/rust-analyzer/crates/hir-ty/src/method_resolution.rs index a6150a9bc172..b22781e94701 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/method_resolution.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/method_resolution.rs @@ -581,15 +581,15 @@ impl ReceiverAdjustments { } if self.unsize_array { ty = 'it: { - if let TyKind::Ref(m, l, inner) = ty.kind(Interner) { - if let TyKind::Array(inner, _) = inner.kind(Interner) { - break 'it TyKind::Ref( - *m, - l.clone(), - TyKind::Slice(inner.clone()).intern(Interner), - ) - .intern(Interner); - } + if let TyKind::Ref(m, l, inner) = ty.kind(Interner) + && let TyKind::Array(inner, _) = inner.kind(Interner) + { + break 'it TyKind::Ref( + *m, + l.clone(), + TyKind::Slice(inner.clone()).intern(Interner), + ) + .intern(Interner); } // FIXME: report diagnostic if array unsizing happens without indirection. ty @@ -1549,11 +1549,11 @@ fn is_valid_impl_method_candidate( check_that!(receiver_ty.is_none()); check_that!(name.is_none_or(|n| n == item_name)); - if let Some(from_module) = visible_from_module { - if !db.assoc_visibility(c.into()).is_visible_from(db, from_module) { - cov_mark::hit!(const_candidate_not_visible); - return IsValidCandidate::NotVisible; - } + if let Some(from_module) = visible_from_module + && !db.assoc_visibility(c.into()).is_visible_from(db, from_module) + { + cov_mark::hit!(const_candidate_not_visible); + return IsValidCandidate::NotVisible; } let self_ty_matches = table.run_in_snapshot(|table| { let expected_self_ty = @@ -1638,11 +1638,11 @@ fn is_valid_impl_fn_candidate( let db = table.db; let data = db.function_signature(fn_id); - if let Some(from_module) = visible_from_module { - if !db.assoc_visibility(fn_id.into()).is_visible_from(db, from_module) { - cov_mark::hit!(autoderef_candidate_not_visible); - return IsValidCandidate::NotVisible; - } + if let Some(from_module) = visible_from_module + && !db.assoc_visibility(fn_id.into()).is_visible_from(db, from_module) + { + cov_mark::hit!(autoderef_candidate_not_visible); + return IsValidCandidate::NotVisible; } table.run_in_snapshot(|table| { let _p = tracing::info_span!("subst_for_def").entered(); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/borrowck.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/borrowck.rs index fb0c0dee095f..52df851c30d1 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/borrowck.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/borrowck.rs @@ -559,10 +559,9 @@ fn mutability_of_locals( }, p, ) = value + && place_case(db, body, p) != ProjectionCase::Indirect { - if place_case(db, body, p) != ProjectionCase::Indirect { - push_mut_span(p.local, statement.span, &mut result); - } + push_mut_span(p.local, statement.span, &mut result); } } StatementKind::FakeRead(p) => { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs index 9a97bd6dbe29..dfb8ae704b99 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval.rs @@ -1082,18 +1082,18 @@ impl Evaluator<'_> { let stack_size = { let mut stack_ptr = self.stack.len(); for (id, it) in body.locals.iter() { - if id == return_slot() { - if let Some(destination) = destination { - locals.ptr.insert(id, destination); - continue; - } + if id == return_slot() + && let Some(destination) = destination + { + locals.ptr.insert(id, destination); + continue; } let (size, align) = self.size_align_of_sized( &it.ty, &locals, "no unsized local in extending stack", )?; - while stack_ptr % align != 0 { + while !stack_ptr.is_multiple_of(align) { stack_ptr += 1; } let my_ptr = stack_ptr; @@ -1673,14 +1673,14 @@ impl Evaluator<'_> { if let Some(it) = goal(kind) { return Ok(it); } - if let TyKind::Adt(id, subst) = kind { - if let AdtId::StructId(struct_id) = id.0 { - let field_types = self.db.field_types(struct_id.into()); - if let Some(ty) = - field_types.iter().last().map(|it| it.1.clone().substitute(Interner, subst)) - { - return self.coerce_unsized_look_through_fields(&ty, goal); - } + if let TyKind::Adt(id, subst) = kind + && let AdtId::StructId(struct_id) = id.0 + { + let field_types = self.db.field_types(struct_id.into()); + if let Some(ty) = + field_types.iter().last().map(|it| it.1.clone().substitute(Interner, subst)) + { + return self.coerce_unsized_look_through_fields(&ty, goal); } } Err(MirEvalError::CoerceUnsizedError(ty.clone())) @@ -1778,17 +1778,15 @@ impl Evaluator<'_> { locals: &Locals, ) -> Result<(usize, Arc, Option<(usize, usize, i128)>)> { let adt = it.adt_id(self.db); - if let DefWithBodyId::VariantId(f) = locals.body.owner { - if let VariantId::EnumVariantId(it) = it { - if let AdtId::EnumId(e) = adt { - if f.lookup(self.db).parent == e { - // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and - // infinite sized type errors) we use a dummy layout - let i = self.const_eval_discriminant(it)?; - return Ok((16, self.layout(&TyBuilder::unit())?, Some((0, 16, i)))); - } - } - } + if let DefWithBodyId::VariantId(f) = locals.body.owner + && let VariantId::EnumVariantId(it) = it + && let AdtId::EnumId(e) = adt + && f.lookup(self.db).parent == e + { + // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and + // infinite sized type errors) we use a dummy layout + let i = self.const_eval_discriminant(it)?; + return Ok((16, self.layout(&TyBuilder::unit())?, Some((0, 16, i)))); } let layout = self.layout_adt(adt, subst)?; Ok(match &layout.variants { @@ -1909,10 +1907,10 @@ impl Evaluator<'_> { let name = const_id.name(self.db); MirEvalError::ConstEvalError(name, Box::new(e)) })?; - if let chalk_ir::ConstValue::Concrete(c) = &result_owner.data(Interner).value { - if let ConstScalar::Bytes(v, mm) = &c.interned { - break 'b (v, mm); - } + if let chalk_ir::ConstValue::Concrete(c) = &result_owner.data(Interner).value + && let ConstScalar::Bytes(v, mm) = &c.interned + { + break 'b (v, mm); } not_supported!("unevaluatable constant"); } @@ -2055,14 +2053,13 @@ impl Evaluator<'_> { .is_sized() .then(|| (layout.size.bytes_usize(), layout.align.abi.bytes() as usize))); } - if let DefWithBodyId::VariantId(f) = locals.body.owner { - if let Some((AdtId::EnumId(e), _)) = ty.as_adt() { - if f.lookup(self.db).parent == e { - // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and - // infinite sized type errors) we use a dummy size - return Ok(Some((16, 16))); - } - } + if let DefWithBodyId::VariantId(f) = locals.body.owner + && let Some((AdtId::EnumId(e), _)) = ty.as_adt() + && f.lookup(self.db).parent == e + { + // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and + // infinite sized type errors) we use a dummy size + return Ok(Some((16, 16))); } let layout = self.layout(ty); if self.assert_placeholder_ty_is_unused @@ -2103,7 +2100,7 @@ impl Evaluator<'_> { if !align.is_power_of_two() || align > 10000 { return Err(MirEvalError::UndefinedBehavior(format!("Alignment {align} is invalid"))); } - while self.heap.len() % align != 0 { + while !self.heap.len().is_multiple_of(align) { self.heap.push(0); } if size.checked_add(self.heap.len()).is_none_or(|x| x > self.memory_limit) { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval/shim.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval/shim.rs index e9665d5ae9cf..bb4c963a8ae1 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval/shim.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval/shim.rs @@ -119,25 +119,25 @@ impl Evaluator<'_> { destination.write_from_bytes(self, &result)?; return Ok(true); } - if let ItemContainerId::TraitId(t) = def.lookup(self.db).container { - if self.db.lang_attr(t.into()) == Some(LangItem::Clone) { - let [self_ty] = generic_args.as_slice(Interner) else { - not_supported!("wrong generic arg count for clone"); - }; - let Some(self_ty) = self_ty.ty(Interner) else { - not_supported!("wrong generic arg kind for clone"); - }; - // Clone has special impls for tuples and function pointers - if matches!( - self_ty.kind(Interner), - TyKind::Function(_) | TyKind::Tuple(..) | TyKind::Closure(..) - ) { - self.exec_clone(def, args, self_ty.clone(), locals, destination, span)?; - return Ok(true); - } - // Return early to prevent caching clone as non special fn. - return Ok(false); + if let ItemContainerId::TraitId(t) = def.lookup(self.db).container + && self.db.lang_attr(t.into()) == Some(LangItem::Clone) + { + let [self_ty] = generic_args.as_slice(Interner) else { + not_supported!("wrong generic arg count for clone"); + }; + let Some(self_ty) = self_ty.ty(Interner) else { + not_supported!("wrong generic arg kind for clone"); + }; + // Clone has special impls for tuples and function pointers + if matches!( + self_ty.kind(Interner), + TyKind::Function(_) | TyKind::Tuple(..) | TyKind::Closure(..) + ) { + self.exec_clone(def, args, self_ty.clone(), locals, destination, span)?; + return Ok(true); } + // Return early to prevent caching clone as non special fn. + return Ok(false); } self.not_special_fn_cache.borrow_mut().insert(def); Ok(false) @@ -1256,23 +1256,22 @@ impl Evaluator<'_> { let addr = tuple.interval.addr.offset(offset); args.push(IntervalAndTy::new(addr, field, self, locals)?); } - if let Some(target) = LangItem::FnOnce.resolve_trait(self.db, self.crate_id) { - if let Some(def) = target + if let Some(target) = LangItem::FnOnce.resolve_trait(self.db, self.crate_id) + && let Some(def) = target .trait_items(self.db) .method_by_name(&Name::new_symbol_root(sym::call_once)) - { - self.exec_fn_trait( - def, - &args, - // FIXME: wrong for manual impls of `FnOnce` - Substitution::empty(Interner), - locals, - destination, - None, - span, - )?; - return Ok(true); - } + { + self.exec_fn_trait( + def, + &args, + // FIXME: wrong for manual impls of `FnOnce` + Substitution::empty(Interner), + locals, + destination, + None, + span, + )?; + return Ok(true); } not_supported!("FnOnce was not available for executing const_eval_select"); } @@ -1367,12 +1366,11 @@ impl Evaluator<'_> { break; } } - if signed { - if let Some((&l, &r)) = lhs.iter().zip(rhs).next_back() { - if l != r { - result = (l as i8).cmp(&(r as i8)); - } - } + if signed + && let Some((&l, &r)) = lhs.iter().zip(rhs).next_back() + && l != r + { + result = (l as i8).cmp(&(r as i8)); } if let Some(e) = LangItem::Ordering.resolve_enum(self.db, self.crate_id) { let ty = self.db.ty(e.into()); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval/shim/simd.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval/shim/simd.rs index bc331a23d98e..f55477290453 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval/shim/simd.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/eval/shim/simd.rs @@ -114,12 +114,11 @@ impl Evaluator<'_> { break; } } - if is_signed { - if let Some((&l, &r)) = l.iter().zip(r).next_back() { - if l != r { - result = (l as i8).cmp(&(r as i8)); - } - } + if is_signed + && let Some((&l, &r)) = l.iter().zip(r).next_back() + && l != r + { + result = (l as i8).cmp(&(r as i8)); } let result = match result { Ordering::Less => ["lt", "le", "ne"].contains(&name), diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs index 07d814727293..eb80e8706fa0 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower.rs @@ -320,11 +320,11 @@ impl<'ctx> MirLowerCtx<'ctx> { expr_id: ExprId, current: BasicBlockId, ) -> Result> { - if !self.has_adjustments(expr_id) { - if let Expr::Literal(l) = &self.body[expr_id] { - let ty = self.expr_ty_without_adjust(expr_id); - return Ok(Some((self.lower_literal_to_operand(ty, l)?, current))); - } + if !self.has_adjustments(expr_id) + && let Expr::Literal(l) = &self.body[expr_id] + { + let ty = self.expr_ty_without_adjust(expr_id); + return Ok(Some((self.lower_literal_to_operand(ty, l)?, current))); } let Some((p, current)) = self.lower_expr_as_place(current, expr_id, true)? else { return Ok(None); @@ -1039,18 +1039,18 @@ impl<'ctx> MirLowerCtx<'ctx> { && rhs_ty.is_scalar() && (lhs_ty == rhs_ty || builtin_inequal_impls) }; - if !is_builtin { - if let Some((func_id, generic_args)) = self.infer.method_resolution(expr_id) { - let func = Operand::from_fn(self.db, func_id, generic_args); - return self.lower_call_and_args( - func, - [*lhs, *rhs].into_iter(), - place, - current, - self.is_uninhabited(expr_id), - expr_id.into(), - ); - } + if !is_builtin + && let Some((func_id, generic_args)) = self.infer.method_resolution(expr_id) + { + let func = Operand::from_fn(self.db, func_id, generic_args); + return self.lower_call_and_args( + func, + [*lhs, *rhs].into_iter(), + place, + current, + self.is_uninhabited(expr_id), + expr_id.into(), + ); } if let hir_def::hir::BinaryOp::Assignment { op: Some(op) } = op { // last adjustment is `&mut` which we don't want it. @@ -1596,10 +1596,10 @@ impl<'ctx> MirLowerCtx<'ctx> { fn expr_ty_after_adjustments(&self, e: ExprId) -> Ty { let mut ty = None; - if let Some(it) = self.infer.expr_adjustments.get(&e) { - if let Some(it) = it.last() { - ty = Some(it.target.clone()); - } + if let Some(it) = self.infer.expr_adjustments.get(&e) + && let Some(it) = it.last() + { + ty = Some(it.target.clone()); } ty.unwrap_or_else(|| self.expr_ty_without_adjust(e)) } @@ -1848,13 +1848,13 @@ impl<'ctx> MirLowerCtx<'ctx> { self.result.param_locals.extend(params.clone().map(|(it, ty)| { let local_id = self.result.locals.alloc(Local { ty }); self.drop_scopes.last_mut().unwrap().locals.push(local_id); - if let Pat::Bind { id, subpat: None } = self.body[it] { - if matches!( + if let Pat::Bind { id, subpat: None } = self.body[it] + && matches!( self.body[id].mode, BindingAnnotation::Unannotated | BindingAnnotation::Mutable - ) { - self.result.binding_locals.insert(id, local_id); - } + ) + { + self.result.binding_locals.insert(id, local_id); } local_id })); @@ -1887,10 +1887,10 @@ impl<'ctx> MirLowerCtx<'ctx> { .into_iter() .skip(base_param_count + self_binding.is_some() as usize); for ((param, _), local) in params.zip(local_params) { - if let Pat::Bind { id, .. } = self.body[param] { - if local == self.binding_local(id)? { - continue; - } + if let Pat::Bind { id, .. } = self.body[param] + && local == self.binding_local(id)? + { + continue; } let r = self.pattern_match(current, None, local.into(), param)?; if let Some(b) = r.1 { diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs index e074c2d558e8..42a14664626f 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/as_place.rs @@ -189,17 +189,14 @@ impl MirLowerCtx<'_> { self.expr_ty_without_adjust(expr_id), expr_id.into(), 'b: { - if let Some((f, _)) = self.infer.method_resolution(expr_id) { - if let Some(deref_trait) = + if let Some((f, _)) = self.infer.method_resolution(expr_id) + && let Some(deref_trait) = self.resolve_lang_item(LangItem::DerefMut)?.as_trait() - { - if let Some(deref_fn) = deref_trait - .trait_items(self.db) - .method_by_name(&Name::new_symbol_root(sym::deref_mut)) - { - break 'b deref_fn == f; - } - } + && let Some(deref_fn) = deref_trait + .trait_items(self.db) + .method_by_name(&Name::new_symbol_root(sym::deref_mut)) + { + break 'b deref_fn == f; } false }, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs index 3325226b1d36..0440d8502232 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/mir/lower/pattern_matching.rs @@ -317,27 +317,26 @@ impl MirLowerCtx<'_> { (current, current_else) = self.pattern_match_inner(current, current_else, next_place, pat, mode)?; } - if let &Some(slice) = slice { - if mode != MatchingMode::Check { - if let Pat::Bind { id, subpat: _ } = self.body[slice] { - let next_place = cond_place.project( - ProjectionElem::Subslice { - from: prefix.len() as u64, - to: suffix.len() as u64, - }, - &mut self.result.projection_store, - ); - let mode = self.infer.binding_modes[slice]; - (current, current_else) = self.pattern_match_binding( - id, - mode, - next_place, - (slice).into(), - current, - current_else, - )?; - } - } + if let &Some(slice) = slice + && mode != MatchingMode::Check + && let Pat::Bind { id, subpat: _ } = self.body[slice] + { + let next_place = cond_place.project( + ProjectionElem::Subslice { + from: prefix.len() as u64, + to: suffix.len() as u64, + }, + &mut self.result.projection_store, + ); + let mode = self.infer.binding_modes[slice]; + (current, current_else) = self.pattern_match_binding( + id, + mode, + next_place, + (slice).into(), + current, + current_else, + )?; } for (i, &pat) in suffix.iter().enumerate() { let next_place = cond_place.project( @@ -391,10 +390,10 @@ impl MirLowerCtx<'_> { return Ok((current, current_else)); } let (c, subst) = 'b: { - if let Some(x) = self.infer.assoc_resolutions_for_pat(pattern) { - if let AssocItemId::ConstId(c) = x.0 { - break 'b (c, x.1); - } + if let Some(x) = self.infer.assoc_resolutions_for_pat(pattern) + && let AssocItemId::ConstId(c) = x.0 + { + break 'b (c, x.1); } if let ResolveValueResult::ValueNs(ValueNs::ConstId(c), _) = pr { break 'b (c, Substitution::empty(Interner)); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/traits.rs b/src/tools/rust-analyzer/crates/hir-ty/src/traits.rs index 7414b4fc6070..08b9d242e71d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/traits.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/traits.rs @@ -125,11 +125,10 @@ pub(crate) fn trait_solve_query( alias: AliasTy::Projection(projection_ty), .. }))) = &goal.value.goal.data(Interner) + && let TyKind::BoundVar(_) = projection_ty.self_type_parameter(db).kind(Interner) { - if let TyKind::BoundVar(_) = projection_ty.self_type_parameter(db).kind(Interner) { - // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible - return Some(Solution::Ambig(Guidance::Unknown)); - } + // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible + return Some(Solution::Ambig(Guidance::Unknown)); } // Chalk see `UnevaluatedConst` as a unique concrete value, but we see it as an alias for another const. So diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs index d07c1aa33b40..209ec7926e82 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/utils.rs @@ -333,13 +333,13 @@ impl FallibleTypeFolder for UnevaluatedConstEvaluatorFolder<'_> { constant: Const, _outer_binder: DebruijnIndex, ) -> Result { - if let chalk_ir::ConstValue::Concrete(c) = &constant.data(Interner).value { - if let ConstScalar::UnevaluatedConst(id, subst) = &c.interned { - if let Ok(eval) = self.db.const_eval(*id, subst.clone(), None) { - return Ok(eval); - } else { - return Ok(unknown_const(constant.data(Interner).ty.clone())); - } + if let chalk_ir::ConstValue::Concrete(c) = &constant.data(Interner).value + && let ConstScalar::UnevaluatedConst(id, subst) = &c.interned + { + if let Ok(eval) = self.db.const_eval(*id, subst.clone(), None) { + return Ok(eval); + } else { + return Ok(unknown_const(constant.data(Interner).ty.clone())); } } Ok(constant) diff --git a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs index c1e814ec223e..fca0162765ec 100644 --- a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs @@ -604,13 +604,13 @@ impl<'db> AnyDiagnostic<'db> { } } BodyValidationDiagnostic::RemoveUnnecessaryElse { if_expr } => { - if let Ok(source_ptr) = source_map.expr_syntax(if_expr) { - if let Some(ptr) = source_ptr.value.cast::() { - return Some( - RemoveUnnecessaryElse { if_expr: InFile::new(source_ptr.file_id, ptr) } - .into(), - ); - } + if let Ok(source_ptr) = source_map.expr_syntax(if_expr) + && let Some(ptr) = source_ptr.value.cast::() + { + return Some( + RemoveUnnecessaryElse { if_expr: InFile::new(source_ptr.file_id, ptr) } + .into(), + ); } } } diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index 4ddb04b24f7f..a323f97997c6 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -1020,21 +1020,21 @@ fn emit_macro_def_diagnostics<'db>( m: Macro, ) { let id = db.macro_def(m.id); - if let hir_expand::db::TokenExpander::DeclarativeMacro(expander) = db.macro_expander(id) { - if let Some(e) = expander.mac.err() { - let Some(ast) = id.ast_id().left() else { - never!("declarative expander for non decl-macro: {:?}", e); - return; - }; - let krate = HasModule::krate(&m.id, db); - let edition = krate.data(db).edition; - emit_def_diagnostic_( - db, - acc, - &DefDiagnosticKind::MacroDefError { ast, message: e.to_string() }, - edition, - ); - } + if let hir_expand::db::TokenExpander::DeclarativeMacro(expander) = db.macro_expander(id) + && let Some(e) = expander.mac.err() + { + let Some(ast) = id.ast_id().left() else { + never!("declarative expander for non decl-macro: {:?}", e); + return; + }; + let krate = HasModule::krate(&m.id, db); + let edition = krate.data(db).edition; + emit_def_diagnostic_( + db, + acc, + &DefDiagnosticKind::MacroDefError { ast, message: e.to_string() }, + edition, + ); } } @@ -2564,10 +2564,10 @@ impl<'db> Param<'db> { Callee::Closure(closure, _) => { let c = db.lookup_intern_closure(closure.into()); let body = db.body(c.0); - if let Expr::Closure { args, .. } = &body[c.1] { - if let Pat::Bind { id, .. } = &body[args[self.idx]] { - return Some(Local { parent: c.0, binding_id: *id }); - } + if let Expr::Closure { args, .. } = &body[c.1] + && let Pat::Bind { id, .. } = &body[args[self.idx]] + { + return Some(Local { parent: c.0, binding_id: *id }); } None } @@ -2761,26 +2761,20 @@ impl EvaluatedConst { pub fn render_debug(&self, db: &dyn HirDatabase) -> Result { let data = self.const_.data(Interner); - if let TyKind::Scalar(s) = data.ty.kind(Interner) { - if matches!(s, Scalar::Int(_) | Scalar::Uint(_)) { - if let hir_ty::ConstValue::Concrete(c) = &data.value { - if let hir_ty::ConstScalar::Bytes(b, _) = &c.interned { - let value = u128::from_le_bytes(mir::pad16(b, false)); - let value_signed = - i128::from_le_bytes(mir::pad16(b, matches!(s, Scalar::Int(_)))); - let mut result = if let Scalar::Int(_) = s { - value_signed.to_string() - } else { - value.to_string() - }; - if value >= 10 { - format_to!(result, " ({value:#X})"); - return Ok(result); - } else { - return Ok(result); - } - } - } + if let TyKind::Scalar(s) = data.ty.kind(Interner) + && matches!(s, Scalar::Int(_) | Scalar::Uint(_)) + && let hir_ty::ConstValue::Concrete(c) = &data.value + && let hir_ty::ConstScalar::Bytes(b, _) = &c.interned + { + let value = u128::from_le_bytes(mir::pad16(b, false)); + let value_signed = i128::from_le_bytes(mir::pad16(b, matches!(s, Scalar::Int(_)))); + let mut result = + if let Scalar::Int(_) = s { value_signed.to_string() } else { value.to_string() }; + if value >= 10 { + format_to!(result, " ({value:#X})"); + return Ok(result); + } else { + return Ok(result); } } mir::render_const_using_debug_impl(db, self.def, &self.const_) @@ -4421,10 +4415,10 @@ impl Impl { let impls = db.trait_impls_in_crate(id); all.extend(impls.for_trait(trait_.id).map(Self::from)) } - if let Some(block) = module.id.containing_block() { - if let Some(trait_impls) = db.trait_impls_in_block(block) { - all.extend(trait_impls.for_trait(trait_.id).map(Self::from)); - } + if let Some(block) = module.id.containing_block() + && let Some(trait_impls) = db.trait_impls_in_block(block) + { + all.extend(trait_impls.for_trait(trait_.id).map(Self::from)); } all } diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index adba59236a40..d207305b4c61 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -933,19 +933,18 @@ impl<'db> SemanticsImpl<'db> { InFile::new(file.file_id, last), false, &mut |InFile { value: last, file_id: last_fid }, _ctx| { - if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() { - if first_fid == last_fid { - if let Some(p) = first.parent() { - let range = first.text_range().cover(last.text_range()); - let node = find_root(&p) - .covering_element(range) - .ancestors() - .take_while(|it| it.text_range() == range) - .find_map(N::cast); - if let Some(node) = node { - res.push(node); - } - } + if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() + && first_fid == last_fid + && let Some(p) = first.parent() + { + let range = first.text_range().cover(last.text_range()); + let node = find_root(&p) + .covering_element(range) + .ancestors() + .take_while(|it| it.text_range() == range) + .find_map(N::cast); + if let Some(node) = node { + res.push(node); } } }, @@ -1391,10 +1390,10 @@ impl<'db> SemanticsImpl<'db> { } })() .is_none(); - if was_not_remapped { - if let ControlFlow::Break(b) = f(InFile::new(expansion, token), ctx) { - return Some(b); - } + if was_not_remapped + && let ControlFlow::Break(b) = f(InFile::new(expansion, token), ctx) + { + return Some(b); } } } @@ -2068,14 +2067,12 @@ impl<'db> SemanticsImpl<'db> { break false; } - if let Some(parent) = ast::Expr::cast(parent.clone()) { - if let Some(ExprOrPatId::ExprId(expr_id)) = + if let Some(parent) = ast::Expr::cast(parent.clone()) + && let Some(ExprOrPatId::ExprId(expr_id)) = source_map.node_expr(InFile { file_id, value: &parent }) - { - if let Expr::Unsafe { .. } = body[expr_id] { - break true; - } - } + && let Expr::Unsafe { .. } = body[expr_id] + { + break true; } let Some(parent_) = parent.parent() else { break false }; @@ -2354,32 +2351,30 @@ struct RenameConflictsVisitor<'a> { impl RenameConflictsVisitor<'_> { fn resolve_path(&mut self, node: ExprOrPatId, path: &Path) { - if let Path::BarePath(path) = path { - if let Some(name) = path.as_ident() { - if *name.symbol() == self.new_name { - if let Some(conflicting) = self.resolver.rename_will_conflict_with_renamed( - self.db, - name, - path, - self.body.expr_or_pat_path_hygiene(node), - self.to_be_renamed, - ) { - self.conflicts.insert(conflicting); - } - } else if *name.symbol() == self.old_name { - if let Some(conflicting) = - self.resolver.rename_will_conflict_with_another_variable( - self.db, - name, - path, - self.body.expr_or_pat_path_hygiene(node), - &self.new_name, - self.to_be_renamed, - ) - { - self.conflicts.insert(conflicting); - } + if let Path::BarePath(path) = path + && let Some(name) = path.as_ident() + { + if *name.symbol() == self.new_name { + if let Some(conflicting) = self.resolver.rename_will_conflict_with_renamed( + self.db, + name, + path, + self.body.expr_or_pat_path_hygiene(node), + self.to_be_renamed, + ) { + self.conflicts.insert(conflicting); } + } else if *name.symbol() == self.old_name + && let Some(conflicting) = self.resolver.rename_will_conflict_with_another_variable( + self.db, + name, + path, + self.body.expr_or_pat_path_hygiene(node), + &self.new_name, + self.to_be_renamed, + ) + { + self.conflicts.insert(conflicting); } } } diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index 0b554a9d4e37..d25fb1d8cdb7 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -995,11 +995,11 @@ impl<'db> SourceAnalyzer<'db> { // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are // trying to resolve foo::bar. - if let Some(use_tree) = parent().and_then(ast::UseTree::cast) { - if use_tree.coloncolon_token().is_some() { - return resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store) - .map(|it| (it, None)); - } + if let Some(use_tree) = parent().and_then(ast::UseTree::cast) + && use_tree.coloncolon_token().is_some() + { + return resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store) + .map(|it| (it, None)); } let meta_path = path @@ -1035,24 +1035,19 @@ impl<'db> SourceAnalyzer<'db> { // } // ``` Some(it) if matches!(it, PathResolution::Def(ModuleDef::BuiltinType(_))) => { - if let Some(mod_path) = hir_path.mod_path() { - if let Some(ModuleDefId::ModuleId(id)) = + if let Some(mod_path) = hir_path.mod_path() + && let Some(ModuleDefId::ModuleId(id)) = self.resolver.resolve_module_path_in_items(db, mod_path).take_types() + { + let parent_hir_name = parent_hir_path.segments().get(1).map(|it| it.name); + let module = crate::Module { id }; + if module + .scope(db, None) + .into_iter() + .any(|(name, _)| Some(&name) == parent_hir_name) { - let parent_hir_name = - parent_hir_path.segments().get(1).map(|it| it.name); - let module = crate::Module { id }; - if module - .scope(db, None) - .into_iter() - .any(|(name, _)| Some(&name) == parent_hir_name) - { - return Some(( - PathResolution::Def(ModuleDef::Module(module)), - None, - )); - }; - } + return Some((PathResolution::Def(ModuleDef::Module(module)), None)); + }; } Some((it, None)) } @@ -1282,22 +1277,22 @@ impl<'db> SourceAnalyzer<'db> { db: &'db dyn HirDatabase, macro_expr: InFile<&ast::MacroExpr>, ) -> bool { - if let Some((def, body, sm, Some(infer))) = self.body_() { - if let Some(expanded_expr) = sm.macro_expansion_expr(macro_expr) { - let mut is_unsafe = false; - let mut walk_expr = |expr_id| { - unsafe_operations(db, infer, def, body, expr_id, &mut |inside_unsafe_block| { - is_unsafe |= inside_unsafe_block == InsideUnsafeBlock::No - }) - }; - match expanded_expr { - ExprOrPatId::ExprId(expanded_expr) => walk_expr(expanded_expr), - ExprOrPatId::PatId(expanded_pat) => { - body.walk_exprs_in_pat(expanded_pat, &mut walk_expr) - } + if let Some((def, body, sm, Some(infer))) = self.body_() + && let Some(expanded_expr) = sm.macro_expansion_expr(macro_expr) + { + let mut is_unsafe = false; + let mut walk_expr = |expr_id| { + unsafe_operations(db, infer, def, body, expr_id, &mut |inside_unsafe_block| { + is_unsafe |= inside_unsafe_block == InsideUnsafeBlock::No + }) + }; + match expanded_expr { + ExprOrPatId::ExprId(expanded_expr) => walk_expr(expanded_expr), + ExprOrPatId::PatId(expanded_pat) => { + body.walk_exprs_in_pat(expanded_pat, &mut walk_expr) } - return is_unsafe; } + return is_unsafe; } false } @@ -1575,12 +1570,11 @@ fn resolve_hir_path_( // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type // within the trait's associated types. - if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) { - if let Some(type_alias_id) = + if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) + && let Some(type_alias_id) = trait_id.trait_items(db).associated_type_by_name(unresolved.name) - { - return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); - } + { + return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); } let res = match ty { @@ -1726,12 +1720,11 @@ fn resolve_hir_path_qualifier( // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type // within the trait's associated types. - if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) { - if let Some(type_alias_id) = + if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) + && let Some(type_alias_id) = trait_id.trait_items(db).associated_type_by_name(unresolved.name) - { - return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); - } + { + return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); } let res = match ty { diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search.rs b/src/tools/rust-analyzer/crates/hir/src/term_search.rs index 4b354e640628..e4089218305c 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search.rs @@ -122,10 +122,10 @@ impl<'db> LookupTable<'db> { } // Collapse suggestions if there are many - if let Some(res) = &res { - if res.len() > self.many_threshold { - return Some(vec![Expr::Many(ty.clone())]); - } + if let Some(res) = &res + && res.len() > self.many_threshold + { + return Some(vec![Expr::Many(ty.clone())]); } res @@ -160,10 +160,10 @@ impl<'db> LookupTable<'db> { } // Collapse suggestions if there are many - if let Some(res) = &res { - if res.len() > self.many_threshold { - return Some(vec![Expr::Many(ty.clone())]); - } + if let Some(res) = &res + && res.len() > self.many_threshold + { + return Some(vec![Expr::Many(ty.clone())]); } res diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs index 843831948adc..78f534d014b9 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs @@ -336,10 +336,10 @@ impl<'db> Expr<'db> { if let Expr::Method { func, params, .. } = self { res.extend(params.iter().flat_map(|it| it.traits_used(db))); - if let Some(it) = func.as_assoc_item(db) { - if let Some(it) = it.container_or_implemented_trait(db) { - res.push(it); - } + if let Some(it) = func.as_assoc_item(db) + && let Some(it) = it.container_or_implemented_trait(db) + { + res.push(it); } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_lifetime_to_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_lifetime_to_type.rs index dcdc7ea9cdce..27dbdcf2c4d5 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_lifetime_to_type.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_lifetime_to_type.rs @@ -82,10 +82,10 @@ fn fetch_borrowed_types(node: &ast::Adt) -> Option> { record_field_list .fields() .filter_map(|r_field| { - if let ast::Type::RefType(ref_type) = r_field.ty()? { - if ref_type.lifetime().is_none() { - return Some(ref_type); - } + if let ast::Type::RefType(ref_type) = r_field.ty()? + && ref_type.lifetime().is_none() + { + return Some(ref_type); } None @@ -102,10 +102,10 @@ fn find_ref_types_from_field_list(field_list: &ast::FieldList) -> Option record_list .fields() .filter_map(|f| { - if let ast::Type::RefType(ref_type) = f.ty()? { - if ref_type.lifetime().is_none() { - return Some(ref_type); - } + if let ast::Type::RefType(ref_type) = f.ty()? + && ref_type.lifetime().is_none() + { + return Some(ref_type); } None @@ -114,10 +114,10 @@ fn find_ref_types_from_field_list(field_list: &ast::FieldList) -> Option tuple_field_list .fields() .filter_map(|f| { - if let ast::Type::RefType(ref_type) = f.ty()? { - if ref_type.lifetime().is_none() { - return Some(ref_type); - } + if let ast::Type::RefType(ref_type) = f.ty()? + && ref_type.lifetime().is_none() + { + return Some(ref_type); } None diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_impl_members.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_impl_members.rs index ab183ac70895..7f1e7ccb4487 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_impl_members.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_impl_members.rs @@ -201,14 +201,12 @@ fn add_missing_impl_members_inner( if let Some(cap) = ctx.config.snippet_cap { let mut placeholder = None; - if let DefaultMethods::No = mode { - if let Some(ast::AssocItem::Fn(func)) = &first_new_item { - if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) - && m.syntax().text() == "todo!()" - { - placeholder = Some(m); - } - } + if let DefaultMethods::No = mode + && let Some(ast::AssocItem::Fn(func)) = &first_new_item + && let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) + && m.syntax().text() == "todo!()" + { + placeholder = Some(m); } if let Some(macro_call) = placeholder { diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/apply_demorgan.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/apply_demorgan.rs index 3b447d1f6d57..753a9e56c35a 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/apply_demorgan.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/apply_demorgan.rs @@ -207,10 +207,10 @@ pub(crate) fn apply_demorgan_iterator(acc: &mut Assists, ctx: &AssistContext<'_> // negate all tail expressions in the closure body let tail_cb = &mut |e: &_| tail_cb_impl(&mut editor, &make, e); walk_expr(&closure_body, &mut |expr| { - if let ast::Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + if let ast::Expr::ReturnExpr(ret_expr) = expr + && let Some(ret_expr_arg) = &ret_expr.expr() + { + for_each_tail_expr(ret_expr_arg, tail_cb); } }); for_each_tail_expr(&closure_body, tail_cb); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_bool_then.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_bool_then.rs index d7b7e8d9cad0..9d5d3f223707 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_bool_then.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_bool_then.rs @@ -86,12 +86,11 @@ pub(crate) fn convert_if_to_bool_then(acc: &mut Assists, ctx: &AssistContext<'_> e @ ast::Expr::CallExpr(_) => Some(e.clone()), _ => None, }; - if let Some(ast::Expr::CallExpr(call)) = e { - if let Some(arg_list) = call.arg_list() { - if let Some(arg) = arg_list.args().next() { - editor.replace(call.syntax(), arg.syntax()); - } - } + if let Some(ast::Expr::CallExpr(call)) = e + && let Some(arg_list) = call.arg_list() + && let Some(arg) = arg_list.args().next() + { + editor.replace(call.syntax(), arg.syntax()); } }); let edit = editor.finish(); @@ -276,12 +275,12 @@ fn is_invalid_body( e @ ast::Expr::CallExpr(_) => Some(e.clone()), _ => None, }; - if let Some(ast::Expr::CallExpr(call)) = e { - if let Some(ast::Expr::PathExpr(p)) = call.expr() { - let res = p.path().and_then(|p| sema.resolve_path(&p)); - if let Some(hir::PathResolution::Def(hir::ModuleDef::Variant(v))) = res { - return invalid |= v != some_variant; - } + if let Some(ast::Expr::CallExpr(call)) = e + && let Some(ast::Expr::PathExpr(p)) = call.expr() + { + let res = p.path().and_then(|p| sema.resolve_path(&p)); + if let Some(hir::PathResolution::Def(hir::ModuleDef::Variant(v))) = res { + return invalid |= v != some_variant; } } invalid = true diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_closure_to_fn.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_closure_to_fn.rs index 43515de71e20..916bb67ebb40 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_closure_to_fn.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_closure_to_fn.rs @@ -101,21 +101,21 @@ pub(crate) fn convert_closure_to_fn(acc: &mut Assists, ctx: &AssistContext<'_>) // but we need to locate `AstPtr`s inside the body. let mut wrap_body_in_block = true; if let ast::Expr::BlockExpr(block) = &body { - if let Some(async_token) = block.async_token() { - if !is_async { - is_async = true; - ret_ty = ret_ty.future_output(ctx.db())?; - let token_idx = async_token.index(); - let whitespace_tokens_after_count = async_token - .siblings_with_tokens(Direction::Next) - .skip(1) - .take_while(|token| token.kind() == SyntaxKind::WHITESPACE) - .count(); - body.syntax().splice_children( - token_idx..token_idx + whitespace_tokens_after_count + 1, - Vec::new(), - ); - } + if let Some(async_token) = block.async_token() + && !is_async + { + is_async = true; + ret_ty = ret_ty.future_output(ctx.db())?; + let token_idx = async_token.index(); + let whitespace_tokens_after_count = async_token + .siblings_with_tokens(Direction::Next) + .skip(1) + .take_while(|token| token.kind() == SyntaxKind::WHITESPACE) + .count(); + body.syntax().splice_children( + token_idx..token_idx + whitespace_tokens_after_count + 1, + Vec::new(), + ); } if let Some(gen_token) = block.gen_token() { is_gen = true; @@ -513,10 +513,10 @@ fn capture_as_arg(ctx: &AssistContext<'_>, capture: &ClosureCapture) -> ast::Exp CaptureKind::MutableRef | CaptureKind::UniqueSharedRef => true, CaptureKind::Move => return place, }; - if let ast::Expr::PrefixExpr(expr) = &place { - if expr.op_kind() == Some(ast::UnaryOp::Deref) { - return expr.expr().expect("`display_place_source_code()` produced an invalid expr"); - } + if let ast::Expr::PrefixExpr(expr) = &place + && expr.op_kind() == Some(ast::UnaryOp::Deref) + { + return expr.expr().expect("`display_place_source_code()` produced an invalid expr"); } make::expr_ref(place, needs_mut) } @@ -642,11 +642,11 @@ fn peel_blocks_and_refs_and_parens(mut expr: ast::Expr) -> ast::Expr { expr = ast::Expr::cast(parent).unwrap(); continue; } - if let Some(stmt_list) = ast::StmtList::cast(parent) { - if let Some(block) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) { - expr = ast::Expr::BlockExpr(block); - continue; - } + if let Some(stmt_list) = ast::StmtList::cast(parent) + && let Some(block) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) + { + expr = ast::Expr::BlockExpr(block); + continue; } break; } @@ -662,12 +662,11 @@ fn expr_of_pat(pat: ast::Pat) -> Option { if let Some(let_stmt) = ast::LetStmt::cast(ancestor.clone()) { break 'find_expr let_stmt.initializer(); } - if ast::MatchArm::can_cast(ancestor.kind()) { - if let Some(match_) = + if ast::MatchArm::can_cast(ancestor.kind()) + && let Some(match_) = ancestor.parent().and_then(|it| it.parent()).and_then(ast::MatchExpr::cast) - { - break 'find_expr match_.expr(); - } + { + break 'find_expr match_.expr(); } if ast::ExprStmt::can_cast(ancestor.kind()) { break; diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs index db41927f1df2..a4742bc7bded 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs @@ -50,10 +50,10 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_> let associated_items = impl_.assoc_item_list()?; let from_fn = associated_items.assoc_items().find_map(|item| { - if let ast::AssocItem::Fn(f) = item { - if f.name()?.text() == "from" { - return Some(f); - } + if let ast::AssocItem::Fn(f) = item + && f.name()?.text() == "from" + { + return Some(f); }; None })?; @@ -110,12 +110,11 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_> )) .clone_for_update(); - if let Some(cap) = ctx.config.snippet_cap { - if let ast::AssocItem::TypeAlias(type_alias) = &error_type { - if let Some(ty) = type_alias.ty() { - builder.add_placeholder_snippet(cap, ty); - } - } + if let Some(cap) = ctx.config.snippet_cap + && let ast::AssocItem::TypeAlias(type_alias) = &error_type + && let Some(ty) = type_alias.ty() + { + builder.add_placeholder_snippet(cap, ty); } associated_items.add_item_at_start(error_type); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_into_to_from.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_into_to_from.rs index b80276a95fbf..3d9cde0e0a67 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_into_to_from.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_into_to_from.rs @@ -65,10 +65,10 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) - }; let into_fn = impl_.assoc_item_list()?.assoc_items().find_map(|item| { - if let ast::AssocItem::Fn(f) = item { - if f.name()?.text() == "into" { - return Some(f); - } + if let ast::AssocItem::Fn(f) = item + && f.name()?.text() == "into" + { + return Some(f); }; None })?; diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs index cca4cb9d8f77..247c1011589b 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs @@ -265,10 +265,10 @@ fn replace_body_return_values(body: ast::Expr, struct_name: &str) { let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); walk_expr(&body, &mut |expr| { - if let ast::Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + if let ast::Expr::ReturnExpr(ret_expr) = expr + && let Some(ret_expr_arg) = &ret_expr.expr() + { + for_each_tail_expr(ret_expr_arg, tail_cb); } }); for_each_tail_expr(&body, tail_cb); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs index b27ebcaa4edf..3d78895477b3 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs @@ -192,7 +192,7 @@ fn edit_struct_references( ).syntax().clone() ) }, - _ => return None, + _ => None, } } }; diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_two_arm_bool_match_to_matches_macro.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_two_arm_bool_match_to_matches_macro.rs index e582aa814ae1..1af5db17f040 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_two_arm_bool_match_to_matches_macro.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_two_arm_bool_match_to_matches_macro.rs @@ -100,10 +100,10 @@ fn is_bool_literal_expr( sema: &Semantics<'_, RootDatabase>, expr: &ast::Expr, ) -> Option { - if let ast::Expr::Literal(lit) = expr { - if let ast::LiteralKind::Bool(b) = lit.kind() { - return Some(ArmBodyExpression::Literal(b)); - } + if let ast::Expr::Literal(lit) = expr + && let ast::LiteralKind::Bool(b) = lit.kind() + { + return Some(ArmBodyExpression::Literal(b)); } if !sema.type_of_expr(expr)?.original.is_bool() { diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/desugar_try_expr.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/desugar_try_expr.rs index efadde9e3648..9976e34e730c 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/desugar_try_expr.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/desugar_try_expr.rs @@ -106,73 +106,73 @@ pub(crate) fn desugar_try_expr(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op }, ); - if let Some(let_stmt) = try_expr.syntax().parent().and_then(ast::LetStmt::cast) { - if let_stmt.let_else().is_none() { - let pat = let_stmt.pat()?; - acc.add( - AssistId::refactor_rewrite("desugar_try_expr_let_else"), - "Replace try expression with let else", - target, - |builder| { - let make = SyntaxFactory::with_mappings(); - let mut editor = builder.make_editor(let_stmt.syntax()); + if let Some(let_stmt) = try_expr.syntax().parent().and_then(ast::LetStmt::cast) + && let_stmt.let_else().is_none() + { + let pat = let_stmt.pat()?; + acc.add( + AssistId::refactor_rewrite("desugar_try_expr_let_else"), + "Replace try expression with let else", + target, + |builder| { + let make = SyntaxFactory::with_mappings(); + let mut editor = builder.make_editor(let_stmt.syntax()); - let indent_level = IndentLevel::from_node(let_stmt.syntax()); - let new_let_stmt = make.let_else_stmt( - try_enum.happy_pattern(pat), - let_stmt.ty(), - expr, - make.block_expr( - iter::once( - make.expr_stmt( - make.expr_return(Some(match try_enum { - TryEnum::Option => make.expr_path(make.ident_path("None")), - TryEnum::Result => make - .expr_call( - make.expr_path(make.ident_path("Err")), - make.arg_list(iter::once( - match ctx.config.expr_fill_default { - ExprFillDefaultMode::Todo => make - .expr_macro( - make.ident_path("todo"), - make.token_tree( - syntax::SyntaxKind::L_PAREN, - [], - ), - ) - .into(), - ExprFillDefaultMode::Underscore => { - make.expr_underscore().into() - } - ExprFillDefaultMode::Default => make - .expr_macro( - make.ident_path("todo"), - make.token_tree( - syntax::SyntaxKind::L_PAREN, - [], - ), - ) - .into(), - }, - )), - ) - .into(), - })) - .indent(indent_level + 1) - .into(), - ) + let indent_level = IndentLevel::from_node(let_stmt.syntax()); + let new_let_stmt = make.let_else_stmt( + try_enum.happy_pattern(pat), + let_stmt.ty(), + expr, + make.block_expr( + iter::once( + make.expr_stmt( + make.expr_return(Some(match try_enum { + TryEnum::Option => make.expr_path(make.ident_path("None")), + TryEnum::Result => make + .expr_call( + make.expr_path(make.ident_path("Err")), + make.arg_list(iter::once( + match ctx.config.expr_fill_default { + ExprFillDefaultMode::Todo => make + .expr_macro( + make.ident_path("todo"), + make.token_tree( + syntax::SyntaxKind::L_PAREN, + [], + ), + ) + .into(), + ExprFillDefaultMode::Underscore => { + make.expr_underscore().into() + } + ExprFillDefaultMode::Default => make + .expr_macro( + make.ident_path("todo"), + make.token_tree( + syntax::SyntaxKind::L_PAREN, + [], + ), + ) + .into(), + }, + )), + ) + .into(), + })) + .indent(indent_level + 1) .into(), - ), - None, - ) - .indent(indent_level), - ); - editor.replace(let_stmt.syntax(), new_let_stmt.syntax()); - editor.add_mappings(make.finish_with_mappings()); - builder.add_file_edits(ctx.vfs_file_id(), editor); - }, - ); - } + ) + .into(), + ), + None, + ) + .indent(indent_level), + ); + editor.replace(let_stmt.syntax(), new_let_stmt.syntax()); + editor.add_mappings(make.finish_with_mappings()); + builder.add_file_edits(ctx.vfs_file_id(), editor); + }, + ); } Some(()) } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/expand_glob_import.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/expand_glob_import.rs index 307414c79715..66552dd65f56 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/expand_glob_import.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/expand_glob_import.rs @@ -272,16 +272,16 @@ impl Refs { .clone() .into_iter() .filter(|r| { - if let Definition::Trait(tr) = r.def { - if tr.items(ctx.db()).into_iter().any(|ai| { + if let Definition::Trait(tr) = r.def + && tr.items(ctx.db()).into_iter().any(|ai| { if let AssocItem::Function(f) = ai { def_is_referenced_in(Definition::Function(f), ctx) } else { false } - }) { - return true; - } + }) + { + return true; } def_is_referenced_in(r.def, ctx) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_function.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_function.rs index 00cbef1c01c0..890b8dd64126 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_function.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_function.rs @@ -175,10 +175,10 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op let fn_def = format_function(ctx, module, &fun, old_indent).clone_for_update(); - if let Some(cap) = ctx.config.snippet_cap { - if let Some(name) = fn_def.name() { - builder.add_tabstop_before(cap, name); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(name) = fn_def.name() + { + builder.add_tabstop_before(cap, name); } let fn_def = match fun.self_param_adt(ctx) { @@ -289,10 +289,10 @@ fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option { let func = sema.to_def(&fn_)?; let mut ret_ty = func.ret_type(sema.db); - if func.is_async(sema.db) { - if let Some(async_ret) = func.async_ret_type(sema.db) { + if func.is_async(sema.db) + && let Some(async_ret) = func.async_ret_type(sema.db) { ret_ty = async_ret; } - } (fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(ret_ty)) }, ast::Static(statik) => { @@ -1172,19 +1171,19 @@ impl GenericParent { /// Search `parent`'s ancestors for items with potentially applicable generic parameters fn generic_parents(parent: &SyntaxNode) -> Vec { let mut list = Vec::new(); - if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) { - if let ast::Item::Fn(ref fn_) = parent_item { - if let Some(parent_parent) = - parent_item.syntax().parent().and_then(|it| it.parent()).and_then(ast::Item::cast) - { - match parent_parent { - ast::Item::Impl(impl_) => list.push(GenericParent::Impl(impl_)), - ast::Item::Trait(trait_) => list.push(GenericParent::Trait(trait_)), - _ => (), - } + if let Some(parent_item) = parent.ancestors().find_map(ast::Item::cast) + && let ast::Item::Fn(ref fn_) = parent_item + { + if let Some(parent_parent) = + parent_item.syntax().parent().and_then(|it| it.parent()).and_then(ast::Item::cast) + { + match parent_parent { + ast::Item::Impl(impl_) => list.push(GenericParent::Impl(impl_)), + ast::Item::Trait(trait_) => list.push(GenericParent::Trait(trait_)), + _ => (), } - list.push(GenericParent::Fn(fn_.clone())); } + list.push(GenericParent::Fn(fn_.clone())); } list } @@ -1337,10 +1336,10 @@ fn locals_defined_in_body( // see https://github.com/rust-lang/rust-analyzer/pull/7535#discussion_r570048550 let mut res = FxIndexSet::default(); body.walk_pat(&mut |pat| { - if let ast::Pat::IdentPat(pat) = pat { - if let Some(local) = sema.to_def(&pat) { - res.insert(local); - } + if let ast::Pat::IdentPat(pat) = pat + && let Some(local) = sema.to_def(&pat) + { + res.insert(local); } }); res @@ -1445,11 +1444,11 @@ fn impl_type_name(impl_node: &ast::Impl) -> Option { fn fixup_call_site(builder: &mut SourceChangeBuilder, body: &FunctionBody) { let parent_match_arm = body.parent().and_then(ast::MatchArm::cast); - if let Some(parent_match_arm) = parent_match_arm { - if parent_match_arm.comma_token().is_none() { - let parent_match_arm = builder.make_mut(parent_match_arm); - ted::append_child_raw(parent_match_arm.syntax(), make::token(T![,])); - } + if let Some(parent_match_arm) = parent_match_arm + && parent_match_arm.comma_token().is_none() + { + let parent_match_arm = builder.make_mut(parent_match_arm); + ted::append_child_raw(parent_match_arm.syntax(), make::token(T![,])); } } @@ -2120,30 +2119,30 @@ fn update_external_control_flow(handler: &FlowHandler<'_>, syntax: &SyntaxNode) _ => {} }, WalkEvent::Leave(e) => { - if nested_scope.is_none() { - if let Some(expr) = ast::Expr::cast(e.clone()) { - match expr { - ast::Expr::ReturnExpr(return_expr) => { - let expr = return_expr.expr(); - if let Some(replacement) = make_rewritten_flow(handler, expr) { - ted::replace(return_expr.syntax(), replacement.syntax()) - } - } - ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => { - let expr = break_expr.expr(); - if let Some(replacement) = make_rewritten_flow(handler, expr) { - ted::replace(break_expr.syntax(), replacement.syntax()) - } + if nested_scope.is_none() + && let Some(expr) = ast::Expr::cast(e.clone()) + { + match expr { + ast::Expr::ReturnExpr(return_expr) => { + let expr = return_expr.expr(); + if let Some(replacement) = make_rewritten_flow(handler, expr) { + ted::replace(return_expr.syntax(), replacement.syntax()) } - ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => { - if let Some(replacement) = make_rewritten_flow(handler, None) { - ted::replace(continue_expr.syntax(), replacement.syntax()) - } + } + ast::Expr::BreakExpr(break_expr) if nested_loop.is_none() => { + let expr = break_expr.expr(); + if let Some(replacement) = make_rewritten_flow(handler, expr) { + ted::replace(break_expr.syntax(), replacement.syntax()) } - _ => { - // do nothing + } + ast::Expr::ContinueExpr(continue_expr) if nested_loop.is_none() => { + if let Some(replacement) = make_rewritten_flow(handler, None) { + ted::replace(continue_expr.syntax(), replacement.syntax()) } } + _ => { + // do nothing + } } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_module.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_module.rs index b82b7984d4a4..c6a6b97df824 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_module.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_module.rs @@ -69,13 +69,12 @@ pub(crate) fn extract_module(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti let mut impl_parent: Option = None; let mut impl_child_count: usize = 0; - if let Some(parent_assoc_list) = node.parent() { - if let Some(parent_impl) = parent_assoc_list.parent() { - if let Some(impl_) = ast::Impl::cast(parent_impl) { - impl_child_count = parent_assoc_list.children().count(); - impl_parent = Some(impl_); - } - } + if let Some(parent_assoc_list) = node.parent() + && let Some(parent_impl) = parent_assoc_list.parent() + && let Some(impl_) = ast::Impl::cast(parent_impl) + { + impl_child_count = parent_assoc_list.children().count(); + impl_parent = Some(impl_); } let mut curr_parent_module: Option = None; @@ -436,10 +435,10 @@ impl Module { } }) .for_each(|(node, def)| { - if node_set.insert(node.to_string()) { - if let Some(import) = self.process_def_in_sel(def, &node, &module, ctx) { - check_intersection_and_push(&mut imports_to_remove, import); - } + if node_set.insert(node.to_string()) + && let Some(import) = self.process_def_in_sel(def, &node, &module, ctx) + { + check_intersection_and_push(&mut imports_to_remove, import); } }) } @@ -542,15 +541,16 @@ impl Module { import_path_to_be_removed = Some(text_range); } - if def_in_mod && def_out_sel { - if let Some(first_path_in_use_tree) = use_tree_str.last() { - let first_path_in_use_tree_str = first_path_in_use_tree.to_string(); - if !first_path_in_use_tree_str.contains("super") - && !first_path_in_use_tree_str.contains("crate") - { - let super_path = make::ext::ident_path("super"); - use_tree_str.push(super_path); - } + if def_in_mod + && def_out_sel + && let Some(first_path_in_use_tree) = use_tree_str.last() + { + let first_path_in_use_tree_str = first_path_in_use_tree.to_string(); + if !first_path_in_use_tree_str.contains("super") + && !first_path_in_use_tree_str.contains("crate") + { + let super_path = make::ext::ident_path("super"); + use_tree_str.push(super_path); } } @@ -563,12 +563,11 @@ impl Module { if let Some(mut use_tree_paths) = use_tree_paths { use_tree_paths.reverse(); - if uses_exist_out_sel || !uses_exist_in_sel || !def_in_mod || !def_out_sel { - if let Some(first_path_in_use_tree) = use_tree_paths.first() { - if first_path_in_use_tree.to_string().contains("super") { - use_tree_paths.insert(0, make::ext::ident_path("super")); - } - } + if (uses_exist_out_sel || !uses_exist_in_sel || !def_in_mod || !def_out_sel) + && let Some(first_path_in_use_tree) = use_tree_paths.first() + && first_path_in_use_tree.to_string().contains("super") + { + use_tree_paths.insert(0, make::ext::ident_path("super")); } let is_item = matches!( @@ -691,11 +690,9 @@ fn check_def_in_mod_and_out_sel( _ => source.file_id.original_file(ctx.db()).file_id(ctx.db()) == curr_file_id, }; - if have_same_parent { - if let ModuleSource::Module(module_) = source.value { - let in_sel = !selection_range.contains_range(module_.syntax().text_range()); - return (have_same_parent, in_sel); - } + if have_same_parent && let ModuleSource::Module(module_) = source.value { + let in_sel = !selection_range.contains_range(module_.syntax().text_range()); + return (have_same_parent, in_sel); } return (have_same_parent, false); @@ -772,12 +769,12 @@ fn get_use_tree_paths_from_path( .filter(|x| x.to_string() != path.to_string()) .filter_map(ast::UseTree::cast) .find_map(|use_tree| { - if let Some(upper_tree_path) = use_tree.path() { - if upper_tree_path.to_string() != path.to_string() { - use_tree_str.push(upper_tree_path.clone()); - get_use_tree_paths_from_path(upper_tree_path, use_tree_str); - return Some(use_tree); - } + if let Some(upper_tree_path) = use_tree.path() + && upper_tree_path.to_string() != path.to_string() + { + use_tree_str.push(upper_tree_path.clone()); + get_use_tree_paths_from_path(upper_tree_path, use_tree_str); + return Some(use_tree); } None })?; @@ -786,11 +783,11 @@ fn get_use_tree_paths_from_path( } fn add_change_vis(vis: Option, node_or_token_opt: Option) { - if vis.is_none() { - if let Some(node_or_token) = node_or_token_opt { - let pub_crate_vis = make::visibility_pub_crate().clone_for_update(); - ted::insert(ted::Position::before(node_or_token), pub_crate_vis.syntax()); - } + if vis.is_none() + && let Some(node_or_token) = node_or_token_opt + { + let pub_crate_vis = make::visibility_pub_crate().clone_for_update(); + ted::insert(ted::Position::before(node_or_token), pub_crate_vis.syntax()); } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs index 9095b1825f5f..c56d0b3de5d6 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs @@ -215,12 +215,12 @@ fn tag_generics_in_variant(ty: &ast::Type, generics: &mut [(ast::GenericParam, b ast::GenericParam::LifetimeParam(lt) if matches!(token.kind(), T![lifetime_ident]) => { - if let Some(lt) = lt.lifetime() { - if lt.text().as_str() == token.text() { - *tag = true; - tagged_one = true; - break; - } + if let Some(lt) = lt.lifetime() + && lt.text().as_str() == token.text() + { + *tag = true; + tagged_one = true; + break; } } param if matches!(token.kind(), T![ident]) => { diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs index d843ac64567a..79f22381952a 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs @@ -72,10 +72,10 @@ pub(crate) fn extract_type_alias(acc: &mut Assists, ctx: &AssistContext<'_>) -> let ty_alias = make::ty_alias("Type", generic_params, None, None, Some((ty, None))) .clone_for_update(); - if let Some(cap) = ctx.config.snippet_cap { - if let Some(name) = ty_alias.name() { - edit.add_annotation(name.syntax(), builder.make_tabstop_before(cap)); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(name) = ty_alias.name() + { + edit.add_annotation(name.syntax(), builder.make_tabstop_before(cap)); } let indent = IndentLevel::from_node(node); @@ -111,17 +111,17 @@ fn collect_used_generics<'gp>( match ty { ast::Type::PathType(ty) => { if let Some(path) = ty.path() { - if let Some(name_ref) = path.as_single_name_ref() { - if let Some(param) = known_generics.iter().find(|gp| { + if let Some(name_ref) = path.as_single_name_ref() + && let Some(param) = known_generics.iter().find(|gp| { match gp { ast::GenericParam::ConstParam(cp) => cp.name(), ast::GenericParam::TypeParam(tp) => tp.name(), _ => None, } .is_some_and(|n| n.text() == name_ref.text()) - }) { - generics.push(param); - } + }) + { + generics.push(param); } generics.extend( path.segments() @@ -160,20 +160,18 @@ fn collect_used_generics<'gp>( .and_then(|lt| known_generics.iter().find(find_lifetime(<.text()))), ), ast::Type::ArrayType(ar) => { - if let Some(ast::Expr::PathExpr(p)) = ar.const_arg().and_then(|x| x.expr()) { - if let Some(path) = p.path() { - if let Some(name_ref) = path.as_single_name_ref() { - if let Some(param) = known_generics.iter().find(|gp| { - if let ast::GenericParam::ConstParam(cp) = gp { - cp.name().is_some_and(|n| n.text() == name_ref.text()) - } else { - false - } - }) { - generics.push(param); - } + if let Some(ast::Expr::PathExpr(p)) = ar.const_arg().and_then(|x| x.expr()) + && let Some(path) = p.path() + && let Some(name_ref) = path.as_single_name_ref() + && let Some(param) = known_generics.iter().find(|gp| { + if let ast::GenericParam::ConstParam(cp) = gp { + cp.name().is_some_and(|n| n.text() == name_ref.text()) + } else { + false } - } + }) + { + generics.push(param); } } _ => (), diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_variable.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_variable.rs index db2d316d58ee..c9c1969b9e02 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_variable.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_variable.rs @@ -404,11 +404,10 @@ impl Anchor { } if let Some(expr) = node.parent().and_then(ast::StmtList::cast).and_then(|it| it.tail_expr()) + && expr.syntax() == &node { - if expr.syntax() == &node { - cov_mark::hit!(test_extract_var_last_expr); - return Some(Anchor::Before(node)); - } + cov_mark::hit!(test_extract_var_last_expr); + return Some(Anchor::Before(node)); } if let Some(parent) = node.parent() { @@ -427,10 +426,10 @@ impl Anchor { } if let Some(stmt) = ast::Stmt::cast(node.clone()) { - if let ast::Stmt::ExprStmt(stmt) = stmt { - if stmt.expr().as_ref() == Some(to_extract) { - return Some(Anchor::Replace(stmt)); - } + if let ast::Stmt::ExprStmt(stmt) = stmt + && stmt.expr().as_ref() == Some(to_extract) + { + return Some(Anchor::Replace(stmt)); } return Some(Anchor::Before(node)); } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_documentation_template.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_documentation_template.rs index 68587f0cb5bc..77232dfebdfe 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_documentation_template.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_documentation_template.rs @@ -148,11 +148,11 @@ fn make_example_for_fn(ast_func: &ast::Fn, ctx: &AssistContext<'_>) -> Option) -> Option) ], ); - if let Some(cap) = ctx.config.snippet_cap { - if let Some(name) = ty_alias.name() { - edit.add_annotation(name.syntax(), builder.make_placeholder_snippet(cap)); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(name) = ty_alias.name() + { + edit.add_annotation(name.syntax(), builder.make_placeholder_snippet(cap)); } builder.add_file_edits(ctx.vfs_file_id(), edit); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_function.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_function.rs index 3290a70e1c69..613b32fcc165 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_function.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_function.rs @@ -70,10 +70,10 @@ fn gen_fn(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let TargetInfo { target_module, adt_info, target, file } = fn_target_info(ctx, path, &call, fn_name)?; - if let Some(m) = target_module { - if !is_editable_crate(m.krate(), ctx.db()) { - return None; - } + if let Some(m) = target_module + && !is_editable_crate(m.krate(), ctx.db()) + { + return None; } let function_builder = diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_getter_or_setter.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_getter_or_setter.rs index 20ee9253d379..807b9194b2df 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_getter_or_setter.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_getter_or_setter.rs @@ -433,12 +433,11 @@ fn build_source_change( new_fn.indent(1.into()); // Insert a tabstop only for last method we generate - if i == record_fields_count - 1 { - if let Some(cap) = ctx.config.snippet_cap { - if let Some(name) = new_fn.name() { - builder.add_tabstop_before(cap, name); - } - } + if i == record_fields_count - 1 + && let Some(cap) = ctx.config.snippet_cap + && let Some(name) = new_fn.name() + { + builder.add_tabstop_before(cap, name); } assoc_item_list.add_item(new_fn.clone().into()); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_impl.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_impl.rs index 31cadcf5ea86..fcb81d239ff3 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_impl.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_impl.rs @@ -58,11 +58,11 @@ pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> Optio let mut editor = edit.make_editor(nominal.syntax()); // Add a tabstop after the left curly brace - if let Some(cap) = ctx.config.snippet_cap { - if let Some(l_curly) = impl_.assoc_item_list().and_then(|it| it.l_curly_token()) { - let tabstop = edit.make_tabstop_after(cap); - editor.add_annotation(l_curly, tabstop); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(l_curly) = impl_.assoc_item_list().and_then(|it| it.l_curly_token()) + { + let tabstop = edit.make_tabstop_after(cap); + editor.add_annotation(l_curly, tabstop); } insert_impl(&mut editor, &impl_, &nominal); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_trait_from_impl.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_trait_from_impl.rs index 92a4bd35b3e7..dc3dc73701f3 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_trait_from_impl.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_trait_from_impl.rs @@ -175,18 +175,18 @@ fn remove_items_visibility(item: &ast::AssocItem) { } fn strip_body(item: &ast::AssocItem) { - if let ast::AssocItem::Fn(f) = item { - if let Some(body) = f.body() { - // In contrast to function bodies, we want to see no ws before a semicolon. - // So let's remove them if we see any. - if let Some(prev) = body.syntax().prev_sibling_or_token() { - if prev.kind() == SyntaxKind::WHITESPACE { - ted::remove(prev); - } - } - - ted::replace(body.syntax(), make::tokens::semicolon()); + if let ast::AssocItem::Fn(f) = item + && let Some(body) = f.body() + { + // In contrast to function bodies, we want to see no ws before a semicolon. + // So let's remove them if we see any. + if let Some(prev) = body.syntax().prev_sibling_or_token() + && prev.kind() == SyntaxKind::WHITESPACE + { + ted::remove(prev); } + + ted::replace(body.syntax(), make::tokens::semicolon()); }; } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_call.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_call.rs index 1549b414dcc1..5367350052cb 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_call.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/inline_call.rs @@ -393,19 +393,17 @@ fn inline( // `FileReference` incorrect if let Some(imp) = sema.ancestors_with_macros(fn_body.syntax().clone()).find_map(ast::Impl::cast) + && !node.syntax().ancestors().any(|anc| &anc == imp.syntax()) + && let Some(t) = imp.self_ty() { - if !node.syntax().ancestors().any(|anc| &anc == imp.syntax()) { - if let Some(t) = imp.self_ty() { - while let Some(self_tok) = body - .syntax() - .descendants_with_tokens() - .filter_map(NodeOrToken::into_token) - .find(|tok| tok.kind() == SyntaxKind::SELF_TYPE_KW) - { - let replace_with = t.clone_subtree().syntax().clone_for_update(); - ted::replace(self_tok, replace_with); - } - } + while let Some(self_tok) = body + .syntax() + .descendants_with_tokens() + .filter_map(NodeOrToken::into_token) + .find(|tok| tok.kind() == SyntaxKind::SELF_TYPE_KW) + { + let replace_with = t.clone_subtree().syntax().clone_for_update(); + ted::replace(self_tok, replace_with); } } @@ -415,10 +413,10 @@ fn inline( for stmt in fn_body.statements() { if let Some(let_stmt) = ast::LetStmt::cast(stmt.syntax().to_owned()) { for has_token in let_stmt.syntax().children_with_tokens() { - if let Some(node) = has_token.as_node() { - if let Some(ident_pat) = ast::IdentPat::cast(node.to_owned()) { - func_let_vars.insert(ident_pat.syntax().text().to_string()); - } + if let Some(node) = has_token.as_node() + && let Some(ident_pat) = ast::IdentPat::cast(node.to_owned()) + { + func_let_vars.insert(ident_pat.syntax().text().to_string()); } } } @@ -534,16 +532,15 @@ fn inline( } } - if let Some(generic_arg_list) = generic_arg_list.clone() { - if let Some((target, source)) = &sema.scope(node.syntax()).zip(sema.scope(fn_body.syntax())) - { - body.reindent_to(IndentLevel(0)); - if let Some(new_body) = ast::BlockExpr::cast( - PathTransform::function_call(target, source, function, generic_arg_list) - .apply(body.syntax()), - ) { - body = new_body; - } + if let Some(generic_arg_list) = generic_arg_list.clone() + && let Some((target, source)) = &sema.scope(node.syntax()).zip(sema.scope(fn_body.syntax())) + { + body.reindent_to(IndentLevel(0)); + if let Some(new_body) = ast::BlockExpr::cast( + PathTransform::function_call(target, source, function, generic_arg_list) + .apply(body.syntax()), + ) { + body = new_body; } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_const_to_impl.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_const_to_impl.rs index 0c1dc9eb9349..a645c8b90afc 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_const_to_impl.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_const_to_impl.rs @@ -43,10 +43,10 @@ pub(crate) fn move_const_to_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> let db = ctx.db(); let const_: ast::Const = ctx.find_node_at_offset()?; // Don't show the assist when the cursor is at the const's body. - if let Some(body) = const_.body() { - if body.syntax().text_range().contains(ctx.offset()) { - return None; - } + if let Some(body) = const_.body() + && body.syntax().text_range().contains(ctx.offset()) + { + return None; } let parent_fn = const_.syntax().ancestors().find_map(ast::Fn::cast)?; diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/pull_assignment_up.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/pull_assignment_up.rs index 1b0c31393537..21debf6745a6 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/pull_assignment_up.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/pull_assignment_up.rs @@ -62,10 +62,10 @@ pub(crate) fn pull_assignment_up(acc: &mut Assists, ctx: &AssistContext<'_>) -> return None; }; - if let Some(parent) = tgt.syntax().parent() { - if matches!(parent.kind(), syntax::SyntaxKind::BIN_EXPR | syntax::SyntaxKind::LET_STMT) { - return None; - } + if let Some(parent) = tgt.syntax().parent() + && matches!(parent.kind(), syntax::SyntaxKind::BIN_EXPR | syntax::SyntaxKind::LET_STMT) + { + return None; } let target = tgt.syntax().text_range(); @@ -90,10 +90,10 @@ pub(crate) fn pull_assignment_up(acc: &mut Assists, ctx: &AssistContext<'_>) -> let mut editor = SyntaxEditor::new(edit_tgt); for (stmt, rhs) in assignments { let mut stmt = stmt.syntax().clone(); - if let Some(parent) = stmt.parent() { - if ast::ExprStmt::cast(parent.clone()).is_some() { - stmt = parent.clone(); - } + if let Some(parent) = stmt.parent() + && ast::ExprStmt::cast(parent.clone()).is_some() + { + stmt = parent.clone(); } editor.replace(stmt, rhs.syntax()); } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/raw_string.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/raw_string.rs index 94b49c5df091..2cbb24a64fd5 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/raw_string.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/raw_string.rs @@ -80,15 +80,15 @@ pub(crate) fn make_usual_string(acc: &mut Assists, ctx: &AssistContext<'_>) -> O // parse inside string to escape `"` let escaped = value.escape_default().to_string(); let suffix = string_suffix(token.text()).unwrap_or_default(); - if let Some(offsets) = token.quote_offsets() { - if token.text()[offsets.contents - token.syntax().text_range().start()] == escaped { - let end_quote = offsets.quotes.1; - let end_quote = - TextRange::new(end_quote.start(), end_quote.end() - TextSize::of(suffix)); - edit.replace(offsets.quotes.0, "\""); - edit.replace(end_quote, "\""); - return; - } + if let Some(offsets) = token.quote_offsets() + && token.text()[offsets.contents - token.syntax().text_range().start()] == escaped + { + let end_quote = offsets.quotes.1; + let end_quote = + TextRange::new(end_quote.start(), end_quote.end() - TextSize::of(suffix)); + edit.replace(offsets.quotes.0, "\""); + edit.replace(end_quote, "\""); + return; } edit.replace(token.syntax().text_range(), format!("\"{escaped}\"{suffix}")); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs index fa005a411d36..9f742131e5cb 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs @@ -102,10 +102,10 @@ pub(crate) fn replace_qualified_name_with_use( fn drop_generic_args(path: &ast::Path) -> ast::Path { let path = path.clone_for_update(); - if let Some(segment) = path.segment() { - if let Some(generic_args) = segment.generic_arg_list() { - ted::remove(generic_args.syntax()); - } + if let Some(segment) = path.segment() + && let Some(generic_args) = segment.generic_arg_list() + { + ted::remove(generic_args.syntax()); } path } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unnecessary_async.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unnecessary_async.rs index ac10a829bbf1..b9385775b476 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unnecessary_async.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unnecessary_async.rs @@ -41,10 +41,10 @@ pub(crate) fn unnecessary_async(acc: &mut Assists, ctx: &AssistContext<'_>) -> O return None; } // Do nothing if the method is a member of trait. - if let Some(impl_) = function.syntax().ancestors().nth(2).and_then(ast::Impl::cast) { - if impl_.trait_().is_some() { - return None; - } + if let Some(impl_) = function.syntax().ancestors().nth(2).and_then(ast::Impl::cast) + && impl_.trait_().is_some() + { + return None; } // Remove the `async` keyword plus whitespace after it, if any. diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs index cf38262fbf44..eea6c85e8df0 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_return_type.rs @@ -72,20 +72,20 @@ pub(crate) fn unwrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> let mut exprs_to_unwrap = Vec::new(); let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_unwrap, e); walk_expr(&body_expr, &mut |expr| { - if let ast::Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + if let ast::Expr::ReturnExpr(ret_expr) = expr + && let Some(ret_expr_arg) = &ret_expr.expr() + { + for_each_tail_expr(ret_expr_arg, tail_cb); } }); for_each_tail_expr(&body_expr, tail_cb); let is_unit_type = is_unit_type(&happy_type); if is_unit_type { - if let Some(NodeOrToken::Token(token)) = ret_type.syntax().next_sibling_or_token() { - if token.kind() == SyntaxKind::WHITESPACE { - editor.delete(token); - } + if let Some(NodeOrToken::Token(token)) = ret_type.syntax().next_sibling_or_token() + && token.kind() == SyntaxKind::WHITESPACE + { + editor.delete(token); } editor.delete(ret_type.syntax()); @@ -162,10 +162,10 @@ pub(crate) fn unwrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> } } - if let Some(cap) = ctx.config.snippet_cap { - if let Some(final_placeholder) = final_placeholder { - editor.add_annotation(final_placeholder.syntax(), builder.make_tabstop_after(cap)); - } + if let Some(cap) = ctx.config.snippet_cap + && let Some(final_placeholder) = final_placeholder + { + editor.add_annotation(final_placeholder.syntax(), builder.make_tabstop_after(cap)); } editor.add_mappings(make.finish_with_mappings()); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_tuple.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_tuple.rs index ecfecbb04ff2..46f3e85e1234 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_tuple.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/unwrap_tuple.rs @@ -47,10 +47,10 @@ pub(crate) fn unwrap_tuple(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option if tuple_pat.fields().count() != tuple_init.fields().count() { return None; } - if let Some(tys) = &tuple_ty { - if tuple_pat.fields().count() != tys.fields().count() { - return None; - } + if let Some(tys) = &tuple_ty + && tuple_pat.fields().count() != tys.fields().count() + { + return None; } let parent = let_kw.parent()?; diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs index d7189aa5dbbd..0f089c9b66eb 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs @@ -101,24 +101,24 @@ pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op let mut exprs_to_wrap = Vec::new(); let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e); walk_expr(&body_expr, &mut |expr| { - if let Expr::ReturnExpr(ret_expr) = expr { - if let Some(ret_expr_arg) = &ret_expr.expr() { - for_each_tail_expr(ret_expr_arg, tail_cb); - } + if let Expr::ReturnExpr(ret_expr) = expr + && let Some(ret_expr_arg) = &ret_expr.expr() + { + for_each_tail_expr(ret_expr_arg, tail_cb); } }); for_each_tail_expr(&body_expr, tail_cb); for ret_expr_arg in exprs_to_wrap { - if let Some(ty) = ctx.sema.type_of_expr(&ret_expr_arg) { - if ty.adjusted().could_unify_with(ctx.db(), &semantic_new_return_ty) { - // The type is already correct, don't wrap it. - // We deliberately don't use `could_unify_with_deeply()`, because as long as the outer - // enum matches it's okay for us, as we don't trigger the assist if the return type - // is already `Option`/`Result`, so mismatched exact type is more likely a mistake - // than something intended. - continue; - } + if let Some(ty) = ctx.sema.type_of_expr(&ret_expr_arg) + && ty.adjusted().could_unify_with(ctx.db(), &semantic_new_return_ty) + { + // The type is already correct, don't wrap it. + // We deliberately don't use `could_unify_with_deeply()`, because as long as the outer + // enum matches it's okay for us, as we don't trigger the assist if the return type + // is already `Option`/`Result`, so mismatched exact type is more likely a mistake + // than something intended. + continue; } let happy_wrapped = make.expr_call( @@ -147,13 +147,13 @@ pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op ast::GenericArg::LifetimeArg(_) => false, _ => true, }); - if let Some(error_type_arg) = error_type_arg { - if let Some(cap) = ctx.config.snippet_cap { - editor.add_annotation( - error_type_arg.syntax(), - builder.make_placeholder_snippet(cap), - ); - } + if let Some(error_type_arg) = error_type_arg + && let Some(cap) = ctx.config.snippet_cap + { + editor.add_annotation( + error_type_arg.syntax(), + builder.make_placeholder_snippet(cap), + ); } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_unwrap_cfg_attr.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_unwrap_cfg_attr.rs index 5183566d136b..7d5740b748be 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_unwrap_cfg_attr.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_unwrap_cfg_attr.rs @@ -200,13 +200,12 @@ fn wrap_derive( ], ); - if let Some(snippet_cap) = ctx.config.snippet_cap { - if let Some(first_meta) = + if let Some(snippet_cap) = ctx.config.snippet_cap + && let Some(first_meta) = cfg_attr.meta().and_then(|meta| meta.token_tree()).and_then(|tt| tt.l_paren_token()) - { - let tabstop = edit.make_tabstop_after(snippet_cap); - editor.add_annotation(first_meta, tabstop); - } + { + let tabstop = edit.make_tabstop_after(snippet_cap); + editor.add_annotation(first_meta, tabstop); } editor.add_mappings(make.finish_with_mappings()); @@ -256,13 +255,12 @@ fn wrap_cfg_attr(acc: &mut Assists, ctx: &AssistContext<'_>, attr: ast::Attr) -> editor.replace(attr.syntax(), cfg_attr.syntax()); - if let Some(snippet_cap) = ctx.config.snippet_cap { - if let Some(first_meta) = + if let Some(snippet_cap) = ctx.config.snippet_cap + && let Some(first_meta) = cfg_attr.meta().and_then(|meta| meta.token_tree()).and_then(|tt| tt.l_paren_token()) - { - let tabstop = edit.make_tabstop_after(snippet_cap); - editor.add_annotation(first_meta, tabstop); - } + { + let tabstop = edit.make_tabstop_after(snippet_cap); + editor.add_annotation(first_meta, tabstop); } editor.add_mappings(make.finish_with_mappings()); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs b/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs index 15c7a6a3fc26..77d471e5a748 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/utils.rs @@ -131,10 +131,10 @@ pub fn filter_assoc_items( if ignore_items == IgnoreAssocItems::DocHiddenAttrPresent && assoc_item.attrs(sema.db).has_doc_hidden() { - if let hir::AssocItem::Function(f) = assoc_item { - if !f.has_body(sema.db) { - return true; - } + if let hir::AssocItem::Function(f) = assoc_item + && !f.has_body(sema.db) + { + return true; } return false; } @@ -514,10 +514,10 @@ pub(crate) fn find_struct_impl( if !(same_ty && not_trait_impl) { None } else { Some(impl_blk) } }); - if let Some(ref impl_blk) = block { - if has_any_fn(impl_blk, names) { - return None; - } + if let Some(ref impl_blk) = block + && has_any_fn(impl_blk, names) + { + return None; } Some(block) @@ -526,12 +526,11 @@ pub(crate) fn find_struct_impl( fn has_any_fn(imp: &ast::Impl, names: &[String]) -> bool { if let Some(il) = imp.assoc_item_list() { for item in il.assoc_items() { - if let ast::AssocItem::Fn(f) = item { - if let Some(name) = f.name() { - if names.iter().any(|n| n.eq_ignore_ascii_case(&name.text())) { - return true; - } - } + if let ast::AssocItem::Fn(f) = item + && let Some(name) = f.name() + && names.iter().any(|n| n.eq_ignore_ascii_case(&name.text())) + { + return true; } } } @@ -1021,12 +1020,12 @@ pub(crate) fn trimmed_text_range(source_file: &SourceFile, initial_range: TextRa pub(crate) fn convert_param_list_to_arg_list(list: ast::ParamList) -> ast::ArgList { let mut args = vec![]; for param in list.params() { - if let Some(ast::Pat::IdentPat(pat)) = param.pat() { - if let Some(name) = pat.name() { - let name = name.to_string(); - let expr = make::expr_path(make::ext::ident_path(&name)); - args.push(expr); - } + if let Some(ast::Pat::IdentPat(pat)) = param.pat() + && let Some(name) = pat.name() + { + let name = name.to_string(); + let expr = make::expr_path(make::ext::ident_path(&name)); + args.push(expr); } } make::arg_list(args) @@ -1138,12 +1137,11 @@ pub fn is_body_const(sema: &Semantics<'_, RootDatabase>, expr: &ast::Expr) -> bo }; match expr { ast::Expr::CallExpr(call) => { - if let Some(ast::Expr::PathExpr(path_expr)) = call.expr() { - if let Some(PathResolution::Def(ModuleDef::Function(func))) = + if let Some(ast::Expr::PathExpr(path_expr)) = call.expr() + && let Some(PathResolution::Def(ModuleDef::Function(func))) = path_expr.path().and_then(|path| sema.resolve_path(&path)) - { - is_const &= func.is_const(sema.db); - } + { + is_const &= func.is_const(sema.db); } } ast::Expr::MethodCallExpr(call) => { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions.rs index 65072d936f63..11d26228ba20 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions.rs @@ -111,10 +111,11 @@ impl Completions { ctx: &CompletionContext<'_>, super_chain_len: Option, ) { - if let Some(len) = super_chain_len { - if len > 0 && len < ctx.depth_from_crate_root { - self.add_keyword(ctx, "super::"); - } + if let Some(len) = super_chain_len + && len > 0 + && len < ctx.depth_from_crate_root + { + self.add_keyword(ctx, "super::"); } } @@ -643,10 +644,10 @@ fn enum_variants_with_paths( let variants = enum_.variants(ctx.db); - if let Some(impl_) = impl_.as_ref().and_then(|impl_| ctx.sema.to_def(impl_)) { - if impl_.self_ty(ctx.db).as_adt() == Some(hir::Adt::Enum(enum_)) { - variants.iter().for_each(|variant| process_variant(*variant)); - } + if let Some(impl_) = impl_.as_ref().and_then(|impl_| ctx.sema.to_def(impl_)) + && impl_.self_ty(ctx.db).as_adt() == Some(hir::Adt::Enum(enum_)) + { + variants.iter().for_each(|variant| process_variant(*variant)); } for variant in variants { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/dot.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/dot.rs index 5340d65a142d..f75123324f37 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/dot.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/dot.rs @@ -258,12 +258,11 @@ fn complete_methods( fn on_trait_method(&mut self, func: hir::Function) -> ControlFlow<()> { // This needs to come before the `seen_methods` test, so that if we see the same method twice, // once as inherent and once not, we will include it. - if let ItemContainer::Trait(trait_) = func.container(self.ctx.db) { - if self.ctx.exclude_traits.contains(&trait_) - || trait_.complete(self.ctx.db) == Complete::IgnoreMethods - { - return ControlFlow::Continue(()); - } + if let ItemContainer::Trait(trait_) = func.container(self.ctx.db) + && (self.ctx.exclude_traits.contains(&trait_) + || trait_.complete(self.ctx.db) == Complete::IgnoreMethods) + { + return ControlFlow::Continue(()); } if func.self_param(self.ctx.db).is_some() diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/fn_param.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/fn_param.rs index 809e71cc119e..fb78386976d6 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/fn_param.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/fn_param.rs @@ -128,10 +128,10 @@ fn params_from_stmt_list_scope( { let module = scope.module().into(); scope.process_all_names(&mut |name, def| { - if let hir::ScopeDef::Local(local) = def { - if let Ok(ty) = local.ty(ctx.db).display_source_code(ctx.db, module, true) { - cb(name, ty); - } + if let hir::ScopeDef::Local(local) = def + && let Ok(ty) = local.ty(ctx.db).display_source_code(ctx.db, module, true) + { + cb(name, ty); } }); } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list/trait_impl.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list/trait_impl.rs index bcf8c0ec527a..cdd77e79b5cd 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list/trait_impl.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/item_list/trait_impl.rs @@ -228,24 +228,22 @@ fn add_function_impl_( .set_documentation(func.docs(ctx.db)) .set_relevance(CompletionRelevance { exact_name_match: true, ..Default::default() }); - if let Some(source) = ctx.sema.source(func) { - if let Some(transformed_fn) = + if let Some(source) = ctx.sema.source(func) + && let Some(transformed_fn) = get_transformed_fn(ctx, source.value, impl_def, async_sugaring) - { - let function_decl = - function_declaration(ctx, &transformed_fn, source.file_id.macro_file()); - match ctx.config.snippet_cap { - Some(cap) => { - let snippet = format!("{function_decl} {{\n $0\n}}"); - item.snippet_edit(cap, TextEdit::replace(replacement_range, snippet)); - } - None => { - let header = format!("{function_decl} {{"); - item.text_edit(TextEdit::replace(replacement_range, header)); - } - }; - item.add_to(acc, ctx.db); - } + { + let function_decl = function_declaration(ctx, &transformed_fn, source.file_id.macro_file()); + match ctx.config.snippet_cap { + Some(cap) => { + let snippet = format!("{function_decl} {{\n $0\n}}"); + item.snippet_edit(cap, TextEdit::replace(replacement_range, snippet)); + } + None => { + let header = format!("{function_decl} {{"); + item.text_edit(TextEdit::replace(replacement_range, header)); + } + }; + item.add_to(acc, ctx.db); } } @@ -447,36 +445,36 @@ fn add_const_impl( ) { let const_name = const_.name(ctx.db).map(|n| n.display_no_db(ctx.edition).to_smolstr()); - if let Some(const_name) = const_name { - if let Some(source) = ctx.sema.source(const_) { - let assoc_item = ast::AssocItem::Const(source.value); - if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) { - let transformed_const = match transformed_item { - ast::AssocItem::Const(const_) => const_, - _ => unreachable!(), - }; - - let label = - make_const_compl_syntax(ctx, &transformed_const, source.file_id.macro_file()); - let replacement = format!("{label} "); - - let mut item = - CompletionItem::new(SymbolKind::Const, replacement_range, label, ctx.edition); - item.lookup_by(format_smolstr!("const {const_name}")) - .set_documentation(const_.docs(ctx.db)) - .set_relevance(CompletionRelevance { - exact_name_match: true, - ..Default::default() - }); - match ctx.config.snippet_cap { - Some(cap) => item.snippet_edit( - cap, - TextEdit::replace(replacement_range, format!("{replacement}$0;")), - ), - None => item.text_edit(TextEdit::replace(replacement_range, replacement)), - }; - item.add_to(acc, ctx.db); - } + if let Some(const_name) = const_name + && let Some(source) = ctx.sema.source(const_) + { + let assoc_item = ast::AssocItem::Const(source.value); + if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) { + let transformed_const = match transformed_item { + ast::AssocItem::Const(const_) => const_, + _ => unreachable!(), + }; + + let label = + make_const_compl_syntax(ctx, &transformed_const, source.file_id.macro_file()); + let replacement = format!("{label} "); + + let mut item = + CompletionItem::new(SymbolKind::Const, replacement_range, label, ctx.edition); + item.lookup_by(format_smolstr!("const {const_name}")) + .set_documentation(const_.docs(ctx.db)) + .set_relevance(CompletionRelevance { + exact_name_match: true, + ..Default::default() + }); + match ctx.config.snippet_cap { + Some(cap) => item.snippet_edit( + cap, + TextEdit::replace(replacement_range, format!("{replacement}$0;")), + ), + None => item.text_edit(TextEdit::replace(replacement_range, replacement)), + }; + item.add_to(acc, ctx.db); } } } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs index 013747e4d0cc..333330004577 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/mod_.rs @@ -26,18 +26,17 @@ pub(crate) fn complete_mod( let mut current_module = ctx.module; // For `mod $0`, `ctx.module` is its parent, but for `mod f$0`, it's `mod f` itself, but we're // interested in its parent. - if ctx.original_token.kind() == SyntaxKind::IDENT { - if let Some(module) = + if ctx.original_token.kind() == SyntaxKind::IDENT + && let Some(module) = ctx.original_token.parent_ancestors().nth(1).and_then(ast::Module::cast) - { - match ctx.sema.to_def(&module) { - Some(module) if module == current_module => { - if let Some(parent) = current_module.parent(ctx.db) { - current_module = parent; - } + { + match ctx.sema.to_def(&module) { + Some(module) if module == current_module => { + if let Some(parent) = current_module.parent(ctx.db) { + current_module = parent; } - _ => {} } + _ => {} } } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/pattern.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/pattern.rs index 62fae1cb2374..815ce5145dbe 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/pattern.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/pattern.rs @@ -64,18 +64,17 @@ pub(crate) fn complete_pattern( if let Some(hir::Adt::Enum(e)) = ctx.expected_type.as_ref().and_then(|ty| ty.strip_references().as_adt()) + && (refutable || single_variant_enum(e)) { - if refutable || single_variant_enum(e) { - super::enum_variants_with_paths( - acc, - ctx, - e, - &pattern_ctx.impl_, - |acc, ctx, variant, path| { - acc.add_qualified_variant_pat(ctx, pattern_ctx, variant, path); - }, - ); - } + super::enum_variants_with_paths( + acc, + ctx, + e, + &pattern_ctx.impl_, + |acc, ctx, variant, path| { + acc.add_qualified_variant_pat(ctx, pattern_ctx, variant, path); + }, + ); } // FIXME: ideally, we should look at the type we are matching against and diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/postfix.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/postfix.rs index d0023852acf9..0058611a6153 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/postfix.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/postfix.rs @@ -65,26 +65,19 @@ pub(crate) fn complete_postfix( let cfg = ctx.config.import_path_config(ctx.is_nightly); - if let Some(drop_trait) = ctx.famous_defs().core_ops_Drop() { - if receiver_ty.impls_trait(ctx.db, drop_trait, &[]) { - if let Some(drop_fn) = ctx.famous_defs().core_mem_drop() { - if let Some(path) = - ctx.module.find_path(ctx.db, ItemInNs::Values(drop_fn.into()), cfg) - { - cov_mark::hit!(postfix_drop_completion); - let mut item = postfix_snippet( - "drop", - "fn drop(&mut self)", - &format!( - "{path}($0{receiver_text})", - path = path.display(ctx.db, ctx.edition) - ), - ); - item.set_documentation(drop_fn.docs(ctx.db)); - item.add_to(acc, ctx.db); - } - } - } + if let Some(drop_trait) = ctx.famous_defs().core_ops_Drop() + && receiver_ty.impls_trait(ctx.db, drop_trait, &[]) + && let Some(drop_fn) = ctx.famous_defs().core_mem_drop() + && let Some(path) = ctx.module.find_path(ctx.db, ItemInNs::Values(drop_fn.into()), cfg) + { + cov_mark::hit!(postfix_drop_completion); + let mut item = postfix_snippet( + "drop", + "fn drop(&mut self)", + &format!("{path}($0{receiver_text})", path = path.display(ctx.db, ctx.edition)), + ); + item.set_documentation(drop_fn.docs(ctx.db)); + item.add_to(acc, ctx.db); } postfix_snippet("ref", "&expr", &format!("&{receiver_text}")).add_to(acc, ctx.db); @@ -117,56 +110,50 @@ pub(crate) fn complete_postfix( let try_enum = TryEnum::from_ty(&ctx.sema, &receiver_ty.strip_references()); let mut is_in_cond = false; - if let Some(parent) = dot_receiver_including_refs.syntax().parent() { - if let Some(second_ancestor) = parent.parent() { - let sec_ancestor_kind = second_ancestor.kind(); - if let Some(expr) = >::cast(second_ancestor) { - is_in_cond = match expr { - Either::Left(it) => it.condition().is_some_and(|cond| *cond.syntax() == parent), - Either::Right(it) => { - it.condition().is_some_and(|cond| *cond.syntax() == parent) - } - } + if let Some(parent) = dot_receiver_including_refs.syntax().parent() + && let Some(second_ancestor) = parent.parent() + { + let sec_ancestor_kind = second_ancestor.kind(); + if let Some(expr) = >::cast(second_ancestor) { + is_in_cond = match expr { + Either::Left(it) => it.condition().is_some_and(|cond| *cond.syntax() == parent), + Either::Right(it) => it.condition().is_some_and(|cond| *cond.syntax() == parent), } - match &try_enum { - Some(try_enum) if is_in_cond => match try_enum { - TryEnum::Result => { - postfix_snippet( - "let", - "let Ok(_)", - &format!("let Ok($0) = {receiver_text}"), - ) - .add_to(acc, ctx.db); - postfix_snippet( - "letm", - "let Ok(mut _)", - &format!("let Ok(mut $0) = {receiver_text}"), - ) - .add_to(acc, ctx.db); - } - TryEnum::Option => { - postfix_snippet( - "let", - "let Some(_)", - &format!("let Some($0) = {receiver_text}"), - ) - .add_to(acc, ctx.db); - postfix_snippet( - "letm", - "let Some(mut _)", - &format!("let Some(mut $0) = {receiver_text}"), - ) - .add_to(acc, ctx.db); - } - }, - _ if matches!(sec_ancestor_kind, STMT_LIST | EXPR_STMT) => { - postfix_snippet("let", "let", &format!("let $0 = {receiver_text};")) - .add_to(acc, ctx.db); - postfix_snippet("letm", "let mut", &format!("let mut $0 = {receiver_text};")) + } + match &try_enum { + Some(try_enum) if is_in_cond => match try_enum { + TryEnum::Result => { + postfix_snippet("let", "let Ok(_)", &format!("let Ok($0) = {receiver_text}")) .add_to(acc, ctx.db); + postfix_snippet( + "letm", + "let Ok(mut _)", + &format!("let Ok(mut $0) = {receiver_text}"), + ) + .add_to(acc, ctx.db); + } + TryEnum::Option => { + postfix_snippet( + "let", + "let Some(_)", + &format!("let Some($0) = {receiver_text}"), + ) + .add_to(acc, ctx.db); + postfix_snippet( + "letm", + "let Some(mut _)", + &format!("let Some(mut $0) = {receiver_text}"), + ) + .add_to(acc, ctx.db); } - _ => (), + }, + _ if matches!(sec_ancestor_kind, STMT_LIST | EXPR_STMT) => { + postfix_snippet("let", "let", &format!("let $0 = {receiver_text};")) + .add_to(acc, ctx.db); + postfix_snippet("letm", "let mut", &format!("let mut $0 = {receiver_text};")) + .add_to(acc, ctx.db); } + _ => (), } } @@ -258,25 +245,25 @@ pub(crate) fn complete_postfix( ) .add_to(acc, ctx.db); postfix_snippet("not", "!expr", &format!("!{receiver_text}")).add_to(acc, ctx.db); - } else if let Some(trait_) = ctx.famous_defs().core_iter_IntoIterator() { - if receiver_ty.impls_trait(ctx.db, trait_, &[]) { - postfix_snippet( - "for", - "for ele in expr {}", - &format!("for ele in {receiver_text} {{\n $0\n}}"), - ) - .add_to(acc, ctx.db); - } + } else if let Some(trait_) = ctx.famous_defs().core_iter_IntoIterator() + && receiver_ty.impls_trait(ctx.db, trait_, &[]) + { + postfix_snippet( + "for", + "for ele in expr {}", + &format!("for ele in {receiver_text} {{\n $0\n}}"), + ) + .add_to(acc, ctx.db); } } let mut block_should_be_wrapped = true; if dot_receiver.syntax().kind() == BLOCK_EXPR { block_should_be_wrapped = false; - if let Some(parent) = dot_receiver.syntax().parent() { - if matches!(parent.kind(), IF_EXPR | WHILE_EXPR | LOOP_EXPR | FOR_EXPR) { - block_should_be_wrapped = true; - } + if let Some(parent) = dot_receiver.syntax().parent() + && matches!(parent.kind(), IF_EXPR | WHILE_EXPR | LOOP_EXPR | FOR_EXPR) + { + block_should_be_wrapped = true; } }; { @@ -292,10 +279,10 @@ pub(crate) fn complete_postfix( postfix_snippet("const", "const {}", &const_completion_string).add_to(acc, ctx.db); } - if let ast::Expr::Literal(literal) = dot_receiver_including_refs.clone() { - if let Some(literal_text) = ast::String::cast(literal.token()) { - add_format_like_completions(acc, ctx, &dot_receiver_including_refs, cap, &literal_text); - } + if let ast::Expr::Literal(literal) = dot_receiver_including_refs.clone() + && let Some(literal_text) = ast::String::cast(literal.token()) + { + add_format_like_completions(acc, ctx, &dot_receiver_including_refs, cap, &literal_text); } postfix_snippet( diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/use_.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/use_.rs index d2ab193ec3df..f39b64164932 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/use_.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/use_.rs @@ -54,12 +54,10 @@ pub(crate) fn complete_use_path( for (name, def) in module_scope { if let (Some(attrs), Some(defining_crate)) = (def.attrs(ctx.db), def.krate(ctx.db)) + && (!ctx.check_stability(Some(&attrs)) + || ctx.is_doc_hidden(&attrs, defining_crate)) { - if !ctx.check_stability(Some(&attrs)) - || ctx.is_doc_hidden(&attrs, defining_crate) - { - continue; - } + continue; } let is_name_already_imported = already_imported_names.contains(name.as_str()); diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/vis.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/vis.rs index 38761f77a2c5..28d906d91ce5 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/vis.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/vis.rs @@ -20,11 +20,11 @@ pub(crate) fn complete_vis_path( // Try completing next child module of the path that is still a parent of the current module let next_towards_current = ctx.module.path_to_root(ctx.db).into_iter().take_while(|it| it != module).last(); - if let Some(next) = next_towards_current { - if let Some(name) = next.name(ctx.db) { - cov_mark::hit!(visibility_qualified); - acc.add_module(ctx, path_ctx, next, name, vec![]); - } + if let Some(next) = next_towards_current + && let Some(name) = next.name(ctx.db) + { + cov_mark::hit!(visibility_qualified); + acc.add_module(ctx, path_ctx, next, name, vec![]); } acc.add_super_keyword(ctx, *super_chain_len); diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs index ea5fb39338b2..2eabf99fc697 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs @@ -287,24 +287,22 @@ fn expand( &spec_attr, fake_ident_token.clone(), ), - ) { - if let Some((fake_mapped_token, _)) = - fake_mapped_tokens.into_iter().min_by_key(|(_, rank)| *rank) - { - return Some(ExpansionResult { - original_file: original_file.value, - speculative_file, - original_offset, - speculative_offset: fake_ident_token.text_range().start(), - fake_ident_token, - derive_ctx: Some(( - actual_expansion, - fake_expansion, - fake_mapped_token.text_range().start(), - orig_attr, - )), - }); - } + ) && let Some((fake_mapped_token, _)) = + fake_mapped_tokens.into_iter().min_by_key(|(_, rank)| *rank) + { + return Some(ExpansionResult { + original_file: original_file.value, + speculative_file, + original_offset, + speculative_offset: fake_ident_token.text_range().start(), + fake_ident_token, + derive_ctx: Some(( + actual_expansion, + fake_expansion, + fake_mapped_token.text_range().start(), + orig_attr, + )), + }); } if let Some(spec_adt) = @@ -535,14 +533,13 @@ fn analyze<'db>( NameRefKind::Path(PathCompletionCtx { kind: PathKind::Expr { .. }, path, .. }, ..), .. } = &nameref_ctx + && is_in_token_of_for_loop(path) { - if is_in_token_of_for_loop(path) { - // for pat $0 - // there is nothing to complete here except `in` keyword - // don't bother populating the context - // Ideally this special casing wouldn't be needed, but the parser recovers - return None; - } + // for pat $0 + // there is nothing to complete here except `in` keyword + // don't bother populating the context + // Ideally this special casing wouldn't be needed, but the parser recovers + return None; } qual_ctx = qualifier_ctx; @@ -951,29 +948,26 @@ fn classify_name_ref<'db>( let inbetween_body_and_decl_check = |node: SyntaxNode| { if let Some(NodeOrToken::Node(n)) = syntax::algo::non_trivia_sibling(node.into(), syntax::Direction::Prev) + && let Some(item) = ast::Item::cast(n) { - if let Some(item) = ast::Item::cast(n) { - let is_inbetween = match &item { - ast::Item::Const(it) => it.body().is_none() && it.semicolon_token().is_none(), - ast::Item::Enum(it) => it.variant_list().is_none(), - ast::Item::ExternBlock(it) => it.extern_item_list().is_none(), - ast::Item::Fn(it) => it.body().is_none() && it.semicolon_token().is_none(), - ast::Item::Impl(it) => it.assoc_item_list().is_none(), - ast::Item::Module(it) => { - it.item_list().is_none() && it.semicolon_token().is_none() - } - ast::Item::Static(it) => it.body().is_none(), - ast::Item::Struct(it) => { - it.field_list().is_none() && it.semicolon_token().is_none() - } - ast::Item::Trait(it) => it.assoc_item_list().is_none(), - ast::Item::TypeAlias(it) => it.ty().is_none() && it.semicolon_token().is_none(), - ast::Item::Union(it) => it.record_field_list().is_none(), - _ => false, - }; - if is_inbetween { - return Some(item); + let is_inbetween = match &item { + ast::Item::Const(it) => it.body().is_none() && it.semicolon_token().is_none(), + ast::Item::Enum(it) => it.variant_list().is_none(), + ast::Item::ExternBlock(it) => it.extern_item_list().is_none(), + ast::Item::Fn(it) => it.body().is_none() && it.semicolon_token().is_none(), + ast::Item::Impl(it) => it.assoc_item_list().is_none(), + ast::Item::Module(it) => it.item_list().is_none() && it.semicolon_token().is_none(), + ast::Item::Static(it) => it.body().is_none(), + ast::Item::Struct(it) => { + it.field_list().is_none() && it.semicolon_token().is_none() } + ast::Item::Trait(it) => it.assoc_item_list().is_none(), + ast::Item::TypeAlias(it) => it.ty().is_none() && it.semicolon_token().is_none(), + ast::Item::Union(it) => it.record_field_list().is_none(), + _ => false, + }; + if is_inbetween { + return Some(item); } } None @@ -1502,10 +1496,10 @@ fn classify_name_ref<'db>( } }; } - } else if let Some(segment) = path.segment() { - if segment.coloncolon_token().is_some() { - path_ctx.qualified = Qualified::Absolute; - } + } else if let Some(segment) = path.segment() + && segment.coloncolon_token().is_some() + { + path_ctx.qualified = Qualified::Absolute; } let mut qualifier_ctx = QualifierCtx::default(); @@ -1530,38 +1524,30 @@ fn classify_name_ref<'db>( if let Some(top) = top_node { if let Some(NodeOrToken::Node(error_node)) = syntax::algo::non_trivia_sibling(top.clone().into(), syntax::Direction::Prev) + && error_node.kind() == SyntaxKind::ERROR { - if error_node.kind() == SyntaxKind::ERROR { - for token in - error_node.children_with_tokens().filter_map(NodeOrToken::into_token) - { - match token.kind() { - SyntaxKind::UNSAFE_KW => qualifier_ctx.unsafe_tok = Some(token), - SyntaxKind::ASYNC_KW => qualifier_ctx.async_tok = Some(token), - SyntaxKind::SAFE_KW => qualifier_ctx.safe_tok = Some(token), - _ => {} - } + for token in error_node.children_with_tokens().filter_map(NodeOrToken::into_token) { + match token.kind() { + SyntaxKind::UNSAFE_KW => qualifier_ctx.unsafe_tok = Some(token), + SyntaxKind::ASYNC_KW => qualifier_ctx.async_tok = Some(token), + SyntaxKind::SAFE_KW => qualifier_ctx.safe_tok = Some(token), + _ => {} } - qualifier_ctx.vis_node = error_node.children().find_map(ast::Visibility::cast); } + qualifier_ctx.vis_node = error_node.children().find_map(ast::Visibility::cast); } - if let PathKind::Item { .. } = path_ctx.kind { - if qualifier_ctx.none() { - if let Some(t) = top.first_token() { - if let Some(prev) = t - .prev_token() - .and_then(|t| syntax::algo::skip_trivia_token(t, Direction::Prev)) - { - if ![T![;], T!['}'], T!['{']].contains(&prev.kind()) { - // This was inferred to be an item position path, but it seems - // to be part of some other broken node which leaked into an item - // list - return None; - } - } - } - } + if let PathKind::Item { .. } = path_ctx.kind + && qualifier_ctx.none() + && let Some(t) = top.first_token() + && let Some(prev) = + t.prev_token().and_then(|t| syntax::algo::skip_trivia_token(t, Direction::Prev)) + && ![T![;], T!['}'], T!['{']].contains(&prev.kind()) + { + // This was inferred to be an item position path, but it seems + // to be part of some other broken node which leaked into an item + // list + return None; } } } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/item.rs b/src/tools/rust-analyzer/crates/ide-completion/src/item.rs index dcaac3997b27..f27cd0781665 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/item.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/item.rs @@ -636,10 +636,10 @@ impl Builder { } pub(crate) fn set_detail(&mut self, detail: Option>) -> &mut Builder { self.detail = detail.map(Into::into); - if let Some(detail) = &self.detail { - if never!(detail.contains('\n'), "multiline detail:\n{}", detail) { - self.detail = Some(detail.split('\n').next().unwrap().to_owned()); - } + if let Some(detail) = &self.detail + && never!(detail.contains('\n'), "multiline detail:\n{}", detail) + { + self.detail = Some(detail.split('\n').next().unwrap().to_owned()); } self } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/lib.rs b/src/tools/rust-analyzer/crates/ide-completion/src/lib.rs index 1fdd4cdb1c6b..a70a1138d2f4 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/lib.rs @@ -208,9 +208,9 @@ pub fn completions( // when the user types a bare `_` (that is it does not belong to an identifier) // the user might just wanted to type a `_` for type inference or pattern discarding // so try to suppress completions in those cases - if trigger_character == Some('_') && ctx.original_token.kind() == syntax::SyntaxKind::UNDERSCORE - { - if let CompletionAnalysis::NameRef(NameRefContext { + if trigger_character == Some('_') + && ctx.original_token.kind() == syntax::SyntaxKind::UNDERSCORE + && let CompletionAnalysis::NameRef(NameRefContext { kind: NameRefKind::Path( path_ctx @ PathCompletionCtx { @@ -220,11 +220,9 @@ pub fn completions( ), .. }) = analysis - { - if path_ctx.is_trivial_path() { - return None; - } - } + && path_ctx.is_trivial_path() + { + return None; } { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/render.rs b/src/tools/rust-analyzer/crates/ide-completion/src/render.rs index c6b8af3c79a2..3d7a4067c2cd 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/render.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/render.rs @@ -164,19 +164,18 @@ pub(crate) fn render_field( let expected_fn_type = ctx.completion.expected_type.as_ref().is_some_and(|ty| ty.is_fn() || ty.is_closure()); - if !expected_fn_type { - if let Some(receiver) = &dot_access.receiver { - if let Some(receiver) = ctx.completion.sema.original_ast_node(receiver.clone()) { - builder.insert(receiver.syntax().text_range().start(), "(".to_owned()); - builder.insert(ctx.source_range().end(), ")".to_owned()); - - let is_parens_needed = - !matches!(dot_access.kind, DotAccessKind::Method { has_parens: true }); - - if is_parens_needed { - builder.insert(ctx.source_range().end(), "()".to_owned()); - } - } + if !expected_fn_type + && let Some(receiver) = &dot_access.receiver + && let Some(receiver) = ctx.completion.sema.original_ast_node(receiver.clone()) + { + builder.insert(receiver.syntax().text_range().start(), "(".to_owned()); + builder.insert(ctx.source_range().end(), ")".to_owned()); + + let is_parens_needed = + !matches!(dot_access.kind, DotAccessKind::Method { has_parens: true }); + + if is_parens_needed { + builder.insert(ctx.source_range().end(), "()".to_owned()); } } @@ -184,12 +183,11 @@ pub(crate) fn render_field( } else { item.insert_text(field_with_receiver(receiver.as_deref(), &escaped_name)); } - if let Some(receiver) = &dot_access.receiver { - if let Some(original) = ctx.completion.sema.original_ast_node(receiver.clone()) { - if let Some(ref_mode) = compute_ref_match(ctx.completion, ty) { - item.ref_match(ref_mode, original.syntax().text_range().start()); - } - } + if let Some(receiver) = &dot_access.receiver + && let Some(original) = ctx.completion.sema.original_ast_node(receiver.clone()) + && let Some(ref_mode) = compute_ref_match(ctx.completion, ty) + { + item.ref_match(ref_mode, original.syntax().text_range().start()); } item.doc_aliases(ctx.doc_aliases); item.build(db) @@ -437,26 +435,21 @@ fn render_resolution_path( path_ctx, PathCompletionCtx { kind: PathKind::Type { .. }, has_type_args: false, .. } ) && config.callable.is_some(); - if type_path_no_ty_args { - if let Some(cap) = cap { - let has_non_default_type_params = match resolution { - ScopeDef::ModuleDef(hir::ModuleDef::Adt(it)) => it.has_non_default_type_params(db), - ScopeDef::ModuleDef(hir::ModuleDef::TypeAlias(it)) => { - it.has_non_default_type_params(db) - } - _ => false, - }; - - if has_non_default_type_params { - cov_mark::hit!(inserts_angle_brackets_for_generics); - item.lookup_by(name.clone()) - .label(SmolStr::from_iter([&name, "<…>"])) - .trigger_call_info() - .insert_snippet( - cap, - format!("{}<$0>", local_name.display(db, completion.edition)), - ); + if type_path_no_ty_args && let Some(cap) = cap { + let has_non_default_type_params = match resolution { + ScopeDef::ModuleDef(hir::ModuleDef::Adt(it)) => it.has_non_default_type_params(db), + ScopeDef::ModuleDef(hir::ModuleDef::TypeAlias(it)) => { + it.has_non_default_type_params(db) } + _ => false, + }; + + if has_non_default_type_params { + cov_mark::hit!(inserts_angle_brackets_for_generics); + item.lookup_by(name.clone()) + .label(SmolStr::from_iter([&name, "<…>"])) + .trigger_call_info() + .insert_snippet(cap, format!("{}<$0>", local_name.display(db, completion.edition))); } } @@ -634,23 +627,24 @@ fn compute_ref_match( if expected_type.could_unify_with(ctx.db, completion_ty) { return None; } - if let Some(expected_without_ref) = &expected_without_ref { - if completion_ty.autoderef(ctx.db).any(|ty| ty == *expected_without_ref) { - cov_mark::hit!(suggest_ref); - let mutability = if expected_type.is_mutable_reference() { - hir::Mutability::Mut - } else { - hir::Mutability::Shared - }; - return Some(CompletionItemRefMode::Reference(mutability)); - } + if let Some(expected_without_ref) = &expected_without_ref + && completion_ty.autoderef(ctx.db).any(|ty| ty == *expected_without_ref) + { + cov_mark::hit!(suggest_ref); + let mutability = if expected_type.is_mutable_reference() { + hir::Mutability::Mut + } else { + hir::Mutability::Shared + }; + return Some(CompletionItemRefMode::Reference(mutability)); } - if let Some(completion_without_ref) = completion_without_ref { - if completion_without_ref == *expected_type && completion_without_ref.is_copy(ctx.db) { - cov_mark::hit!(suggest_deref); - return Some(CompletionItemRefMode::Dereference); - } + if let Some(completion_without_ref) = completion_without_ref + && completion_without_ref == *expected_type + && completion_without_ref.is_copy(ctx.db) + { + cov_mark::hit!(suggest_deref); + return Some(CompletionItemRefMode::Dereference); } None @@ -664,10 +658,10 @@ fn path_ref_match( ) { if let Some(original_path) = &path_ctx.original_path { // At least one char was typed by the user already, in that case look for the original path - if let Some(original_path) = completion.sema.original_ast_node(original_path.clone()) { - if let Some(ref_mode) = compute_ref_match(completion, ty) { - item.ref_match(ref_mode, original_path.syntax().text_range().start()); - } + if let Some(original_path) = completion.sema.original_ast_node(original_path.clone()) + && let Some(ref_mode) = compute_ref_match(completion, ty) + { + item.ref_match(ref_mode, original_path.syntax().text_range().start()); } } else { // completion requested on an empty identifier, there is no path here yet. diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/render/const_.rs b/src/tools/rust-analyzer/crates/ide-completion/src/render/const_.rs index f11b3023679a..707a8aed4fb9 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/render/const_.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/render/const_.rs @@ -25,10 +25,10 @@ fn render(ctx: RenderContext<'_>, const_: hir::Const) -> Option .detail(detail) .set_relevance(ctx.completion_relevance()); - if let Some(actm) = const_.as_assoc_item(db) { - if let Some(trt) = actm.container_or_implemented_trait(db) { - item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); - } + if let Some(actm) = const_.as_assoc_item(db) + && let Some(trt) = actm.container_or_implemented_trait(db) + { + item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); } item.insert_text(escaped_name); diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs b/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs index 7669aec8f535..c466019f991f 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs @@ -132,10 +132,10 @@ fn render( super::path_ref_match(completion, path_ctx, &ret_type, &mut item); } FuncKind::Method(DotAccess { receiver: Some(receiver), .. }, _) => { - if let Some(original_expr) = completion.sema.original_ast_node(receiver.clone()) { - if let Some(ref_mode) = compute_ref_match(completion, &ret_type) { - item.ref_match(ref_mode, original_expr.syntax().text_range().start()); - } + if let Some(original_expr) = completion.sema.original_ast_node(receiver.clone()) + && let Some(ref_mode) = compute_ref_match(completion, &ret_type) + { + item.ref_match(ref_mode, original_expr.syntax().text_range().start()); } } _ => (), @@ -169,12 +169,10 @@ fn render( item.add_import(import_to_add); } None => { - if let Some(actm) = assoc_item { - if let Some(trt) = actm.container_or_implemented_trait(db) { - item.trait_name( - trt.name(db).display_no_db(ctx.completion.edition).to_smolstr(), - ); - } + if let Some(actm) = assoc_item + && let Some(trt) = actm.container_or_implemented_trait(db) + { + item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); } } } @@ -378,15 +376,13 @@ fn params<'db>( ctx.config.callable.as_ref()?; // Don't add parentheses if the expected type is a function reference with the same signature. - if let Some(expected) = ctx.expected_type.as_ref().filter(|e| e.is_fn()) { - if let Some(expected) = expected.as_callable(ctx.db) { - if let Some(completed) = func.ty(ctx.db).as_callable(ctx.db) { - if expected.sig() == completed.sig() { - cov_mark::hit!(no_call_parens_if_fn_ptr_needed); - return None; - } - } - } + if let Some(expected) = ctx.expected_type.as_ref().filter(|e| e.is_fn()) + && let Some(expected) = expected.as_callable(ctx.db) + && let Some(completed) = func.ty(ctx.db).as_callable(ctx.db) + && expected.sig() == completed.sig() + { + cov_mark::hit!(no_call_parens_if_fn_ptr_needed); + return None; } let self_param = if has_dot_receiver || matches!(func_kind, FuncKind::Method(_, Some(_))) { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/render/type_alias.rs b/src/tools/rust-analyzer/crates/ide-completion/src/render/type_alias.rs index d57feee4fa65..3fc0f369e5ad 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/render/type_alias.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/render/type_alias.rs @@ -51,10 +51,10 @@ fn render( .detail(detail) .set_relevance(ctx.completion_relevance()); - if let Some(actm) = type_alias.as_assoc_item(db) { - if let Some(trt) = actm.container_or_implemented_trait(db) { - item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); - } + if let Some(actm) = type_alias.as_assoc_item(db) + && let Some(trt) = actm.container_or_implemented_trait(db) + { + item.trait_name(trt.name(db).display_no_db(ctx.completion.edition).to_smolstr()); } item.insert_text(escaped_name); diff --git a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs index a4a140ec57aa..2a4fcf6a2e5f 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs @@ -610,18 +610,16 @@ impl<'db> NameClass<'db> { let local = sema.to_def(&ident_pat)?; let pat_parent = ident_pat.syntax().parent(); - if let Some(record_pat_field) = pat_parent.and_then(ast::RecordPatField::cast) { - if record_pat_field.name_ref().is_none() { - if let Some((field, _, adt_subst)) = - sema.resolve_record_pat_field_with_subst(&record_pat_field) - { - return Some(NameClass::PatFieldShorthand { - local_def: local, - field_ref: field, - adt_subst, - }); - } - } + if let Some(record_pat_field) = pat_parent.and_then(ast::RecordPatField::cast) + && record_pat_field.name_ref().is_none() + && let Some((field, _, adt_subst)) = + sema.resolve_record_pat_field_with_subst(&record_pat_field) + { + return Some(NameClass::PatFieldShorthand { + local_def: local, + field_ref: field, + adt_subst, + }); } Some(NameClass::Definition(Definition::Local(local))) } @@ -755,30 +753,27 @@ impl<'db> NameRefClass<'db> { let parent = name_ref.syntax().parent()?; - if let Some(record_field) = ast::RecordExprField::for_field_name(name_ref) { - if let Some((field, local, _, adt_subst)) = + if let Some(record_field) = ast::RecordExprField::for_field_name(name_ref) + && let Some((field, local, _, adt_subst)) = sema.resolve_record_field_with_substitution(&record_field) - { - let res = match local { - None => NameRefClass::Definition(Definition::Field(field), Some(adt_subst)), - Some(local) => NameRefClass::FieldShorthand { - field_ref: field, - local_ref: local, - adt_subst, - }, - }; - return Some(res); - } + { + let res = match local { + None => NameRefClass::Definition(Definition::Field(field), Some(adt_subst)), + Some(local) => { + NameRefClass::FieldShorthand { field_ref: field, local_ref: local, adt_subst } + } + }; + return Some(res); } if let Some(path) = ast::PathSegment::cast(parent.clone()).map(|it| it.parent_path()) { - if path.parent_path().is_none() { - if let Some(macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) { - // Only use this to resolve to macro calls for last segments as qualifiers resolve - // to modules below. - if let Some(macro_def) = sema.resolve_macro_call(¯o_call) { - return Some(NameRefClass::Definition(Definition::Macro(macro_def), None)); - } + if path.parent_path().is_none() + && let Some(macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) + { + // Only use this to resolve to macro calls for last segments as qualifiers resolve + // to modules below. + if let Some(macro_def) = sema.resolve_macro_call(¯o_call) { + return Some(NameRefClass::Definition(Definition::Macro(macro_def), None)); } } return sema @@ -820,8 +815,8 @@ impl<'db> NameRefClass<'db> { // ^^^^^ let containing_path = name_ref.syntax().ancestors().find_map(ast::Path::cast)?; let resolved = sema.resolve_path(&containing_path)?; - if let PathResolution::Def(ModuleDef::Trait(tr)) = resolved { - if let Some(ty) = tr + if let PathResolution::Def(ModuleDef::Trait(tr)) = resolved + && let Some(ty) = tr .items_with_supertraits(sema.db) .iter() .filter_map(|&assoc| match assoc { @@ -833,7 +828,6 @@ impl<'db> NameRefClass<'db> { // No substitution, this can only occur in type position. return Some(NameRefClass::Definition(Definition::TypeAlias(ty), None)); } - } None }, ast::UseBoundGenericArgs(_) => { diff --git a/src/tools/rust-analyzer/crates/ide-db/src/helpers.rs b/src/tools/rust-analyzer/crates/ide-db/src/helpers.rs index 340429037e67..1e54058dd16c 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/helpers.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/helpers.rs @@ -70,11 +70,11 @@ pub fn visit_file_defs( }; let mut defs: VecDeque<_> = module.declarations(db).into(); while let Some(def) = defs.pop_front() { - if let ModuleDef::Module(submodule) = def { - if submodule.is_inline(db) { - defs.extend(submodule.declarations(db)); - submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into())); - } + if let ModuleDef::Module(submodule) = def + && submodule.is_inline(db) + { + defs.extend(submodule.declarations(db)); + submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into())); } cb(def.into()); } diff --git a/src/tools/rust-analyzer/crates/ide-db/src/imports/insert_use.rs b/src/tools/rust-analyzer/crates/ide-db/src/imports/insert_use.rs index 813f38380f69..08cd8f28608c 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/imports/insert_use.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/imports/insert_use.rs @@ -97,12 +97,11 @@ impl ImportScope { .map(ImportScopeKind::Module) .map(|kind| ImportScope { kind, required_cfgs }); } else if let Some(has_attrs) = ast::AnyHasAttrs::cast(syntax) { - if block.is_none() { - if let Some(b) = ast::BlockExpr::cast(has_attrs.syntax().clone()) { - if let Some(b) = sema.original_ast_node(b) { - block = b.stmt_list(); - } - } + if block.is_none() + && let Some(b) = ast::BlockExpr::cast(has_attrs.syntax().clone()) + && let Some(b) = sema.original_ast_node(b) + { + block = b.stmt_list(); } if has_attrs .attrs() @@ -349,26 +348,24 @@ fn guess_granularity_from_scope(scope: &ImportScope) -> ImportGranularityGuess { seen_one_style_groups.push((curr_vis.clone(), curr_attrs.clone())); } else if eq_visibility(prev_vis, curr_vis.clone()) && eq_attrs(prev_attrs, curr_attrs.clone()) + && let Some((prev_path, curr_path)) = prev.path().zip(curr.path()) + && let Some((prev_prefix, _)) = common_prefix(&prev_path, &curr_path) { - if let Some((prev_path, curr_path)) = prev.path().zip(curr.path()) { - if let Some((prev_prefix, _)) = common_prefix(&prev_path, &curr_path) { - if prev.use_tree_list().is_none() && curr.use_tree_list().is_none() { - let prefix_c = prev_prefix.qualifiers().count(); - let curr_c = curr_path.qualifiers().count() - prefix_c; - let prev_c = prev_path.qualifiers().count() - prefix_c; - if curr_c == 1 && prev_c == 1 { - // Same prefix, only differing in the last segment and no use tree lists so this has to be of item style. - break ImportGranularityGuess::Item; - } else { - // Same prefix and no use tree list but differs in more than one segment at the end. This might be module style still. - res = ImportGranularityGuess::ModuleOrItem; - } - } else { - // Same prefix with item tree lists, has to be module style as it - // can't be crate style since the trees wouldn't share a prefix then. - break ImportGranularityGuess::Module; - } + if prev.use_tree_list().is_none() && curr.use_tree_list().is_none() { + let prefix_c = prev_prefix.qualifiers().count(); + let curr_c = curr_path.qualifiers().count() - prefix_c; + let prev_c = prev_path.qualifiers().count() - prefix_c; + if curr_c == 1 && prev_c == 1 { + // Same prefix, only differing in the last segment and no use tree lists so this has to be of item style. + break ImportGranularityGuess::Item; + } else { + // Same prefix and no use tree list but differs in more than one segment at the end. This might be module style still. + res = ImportGranularityGuess::ModuleOrItem; } + } else { + // Same prefix with item tree lists, has to be module style as it + // can't be crate style since the trees wouldn't share a prefix then. + break ImportGranularityGuess::Module; } } prev = curr; diff --git a/src/tools/rust-analyzer/crates/ide-db/src/path_transform.rs b/src/tools/rust-analyzer/crates/ide-db/src/path_transform.rs index b7432d89c7b7..5d88afec5095 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/path_transform.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/path_transform.rs @@ -193,13 +193,12 @@ impl<'a> PathTransform<'a> { } } (Either::Right(k), None) => { - if let Some(default) = k.default(db) { - if let Some(default) = + if let Some(default) = k.default(db) + && let Some(default) = &default.display_source_code(db, source_module.into(), false).ok() - { - type_substs.insert(k, make::ty(default).clone_for_update()); - defaulted_params.push(Either::Left(k)); - } + { + type_substs.insert(k, make::ty(default).clone_for_update()); + defaulted_params.push(Either::Left(k)); } } (Either::Left(k), Some(TypeOrConst::Either(v))) => { @@ -221,11 +220,10 @@ impl<'a> PathTransform<'a> { (Either::Left(k), None) => { if let Some(default) = k.default(db, target_module.krate().to_display_target(db)) + && let Some(default) = default.expr() { - if let Some(default) = default.expr() { - const_substs.insert(k, default.syntax().clone_for_update()); - defaulted_params.push(Either::Right(k)); - } + const_substs.insert(k, default.syntax().clone_for_update()); + defaulted_params.push(Either::Right(k)); } } _ => (), // ignore mismatching params @@ -427,14 +425,14 @@ impl Ctx<'_> { } } hir::PathResolution::Def(def) if def.as_assoc_item(self.source_scope.db).is_none() => { - if let hir::ModuleDef::Trait(_) = def { - if matches!(path.segment()?.kind()?, ast::PathSegmentKind::Type { .. }) { - // `speculative_resolve` resolves segments like `` into `Trait`, but just the trait name should - // not be used as the replacement of the original - // segment. - return None; - } + if let hir::ModuleDef::Trait(_) = def + && matches!(path.segment()?.kind()?, ast::PathSegmentKind::Type { .. }) + { + // `speculative_resolve` resolves segments like `` into `Trait`, but just the trait name should + // not be used as the replacement of the original + // segment. + return None; } let cfg = ImportPathConfig { @@ -446,19 +444,17 @@ impl Ctx<'_> { let found_path = self.target_module.find_path(self.source_scope.db, def, cfg)?; let res = mod_path_to_ast(&found_path, self.target_edition).clone_for_update(); let mut res_editor = SyntaxEditor::new(res.syntax().clone_subtree()); - if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) { - if let Some(segment) = res.segment() { - if let Some(old) = segment.generic_arg_list() { - res_editor.replace( - old.syntax(), - args.clone_subtree().syntax().clone_for_update(), - ) - } else { - res_editor.insert( - syntax_editor::Position::last_child_of(segment.syntax()), - args.clone_subtree().syntax().clone_for_update(), - ); - } + if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) + && let Some(segment) = res.segment() + { + if let Some(old) = segment.generic_arg_list() { + res_editor + .replace(old.syntax(), args.clone_subtree().syntax().clone_for_update()) + } else { + res_editor.insert( + syntax_editor::Position::last_child_of(segment.syntax()), + args.clone_subtree().syntax().clone_for_update(), + ); } } let res = res_editor.finish().new_root().clone(); @@ -485,27 +481,27 @@ impl Ctx<'_> { .ok()?; let ast_ty = make::ty(ty_str).clone_for_update(); - if let Some(adt) = ty.as_adt() { - if let ast::Type::PathType(path_ty) = &ast_ty { - let cfg = ImportPathConfig { - prefer_no_std: false, - prefer_prelude: true, - prefer_absolute: false, - allow_unstable: true, - }; - let found_path = self.target_module.find_path( - self.source_scope.db, - ModuleDef::from(adt), - cfg, - )?; - - if let Some(qual) = - mod_path_to_ast(&found_path, self.target_edition).qualifier() - { - let res = make::path_concat(qual, path_ty.path()?).clone_for_update(); - editor.replace(path.syntax(), res.syntax()); - return Some(()); - } + if let Some(adt) = ty.as_adt() + && let ast::Type::PathType(path_ty) = &ast_ty + { + let cfg = ImportPathConfig { + prefer_no_std: false, + prefer_prelude: true, + prefer_absolute: false, + allow_unstable: true, + }; + let found_path = self.target_module.find_path( + self.source_scope.db, + ModuleDef::from(adt), + cfg, + )?; + + if let Some(qual) = + mod_path_to_ast(&found_path, self.target_edition).qualifier() + { + let res = make::path_concat(qual, path_ty.path()?).clone_for_update(); + editor.replace(path.syntax(), res.syntax()); + return Some(()); } } diff --git a/src/tools/rust-analyzer/crates/ide-db/src/rename.rs b/src/tools/rust-analyzer/crates/ide-db/src/rename.rs index 4e737e27f050..424b27a398b2 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/rename.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/rename.rs @@ -442,17 +442,17 @@ fn source_edit_from_name( name: &ast::Name, new_name: &dyn Display, ) -> bool { - if ast::RecordPatField::for_field_name(name).is_some() { - if let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) { - cov_mark::hit!(rename_record_pat_field_name_split); - // Foo { ref mut field } -> Foo { new_name: ref mut field } - // ^ insert `new_name: ` - - // FIXME: instead of splitting the shorthand, recursively trigger a rename of the - // other name https://github.com/rust-lang/rust-analyzer/issues/6547 - edit.insert(ident_pat.syntax().text_range().start(), format!("{new_name}: ")); - return true; - } + if ast::RecordPatField::for_field_name(name).is_some() + && let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) + { + cov_mark::hit!(rename_record_pat_field_name_split); + // Foo { ref mut field } -> Foo { new_name: ref mut field } + // ^ insert `new_name: ` + + // FIXME: instead of splitting the shorthand, recursively trigger a rename of the + // other name https://github.com/rust-lang/rust-analyzer/issues/6547 + edit.insert(ident_pat.syntax().text_range().start(), format!("{new_name}: ")); + return true; } false diff --git a/src/tools/rust-analyzer/crates/ide-db/src/search.rs b/src/tools/rust-analyzer/crates/ide-db/src/search.rs index 9cf0bcf91901..4dd64229d274 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/search.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/search.rs @@ -295,10 +295,10 @@ impl Definition { } // def is crate root - if let &Definition::Module(module) = self { - if module.is_crate_root() { - return SearchScope::reverse_dependencies(db, module.krate()); - } + if let &Definition::Module(module) = self + && module.is_crate_root() + { + return SearchScope::reverse_dependencies(db, module.krate()); } let module = match self.module(db) { @@ -683,51 +683,47 @@ impl<'a> FindUsages<'a> { } } else if let Some(alias) = usage.ancestors().find_map(ast::TypeAlias::cast) + && let Some(name) = alias.name() + && seen + .insert(InFileWrapper::new(file_id, name.syntax().text_range())) { - if let Some(name) = alias.name() { - if seen.insert(InFileWrapper::new( - file_id, - name.syntax().text_range(), - )) { - if let Some(def) = is_alias(&alias) { - cov_mark::hit!(container_type_alias); - insert_type_alias( - sema.db, - &mut to_process, - name.text().as_str(), - def.into(), - ); - } else { - cov_mark::hit!(same_name_different_def_type_alias); - } - } + if let Some(def) = is_alias(&alias) { + cov_mark::hit!(container_type_alias); + insert_type_alias( + sema.db, + &mut to_process, + name.text().as_str(), + def.into(), + ); + } else { + cov_mark::hit!(same_name_different_def_type_alias); } } // We need to account for `Self`. It can only refer to our type inside an impl. let impl_ = 'impl_: { for ancestor in usage.ancestors() { - if let Some(parent) = ancestor.parent() { - if let Some(parent) = ast::Impl::cast(parent) { - // Only if the GENERIC_PARAM_LIST is directly under impl, otherwise it may be in the self ty. - if matches!( - ancestor.kind(), - SyntaxKind::ASSOC_ITEM_LIST - | SyntaxKind::WHERE_CLAUSE - | SyntaxKind::GENERIC_PARAM_LIST - ) { - break; - } - if parent - .trait_() - .is_some_and(|trait_| *trait_.syntax() == ancestor) - { - break; - } - - // Otherwise, found an impl where its self ty may be our type. - break 'impl_ Some(parent); + if let Some(parent) = ancestor.parent() + && let Some(parent) = ast::Impl::cast(parent) + { + // Only if the GENERIC_PARAM_LIST is directly under impl, otherwise it may be in the self ty. + if matches!( + ancestor.kind(), + SyntaxKind::ASSOC_ITEM_LIST + | SyntaxKind::WHERE_CLAUSE + | SyntaxKind::GENERIC_PARAM_LIST + ) { + break; + } + if parent + .trait_() + .is_some_and(|trait_| *trait_.syntax() == ancestor) + { + break; } + + // Otherwise, found an impl where its self ty may be our type. + break 'impl_ Some(parent); } } None @@ -1356,11 +1352,10 @@ impl ReferenceCategory { if matches!(expr.op_kind()?, ast::BinaryOp::Assignment { .. }) { // If the variable or field ends on the LHS's end then it's a Write // (covers fields and locals). FIXME: This is not terribly accurate. - if let Some(lhs) = expr.lhs() { - if lhs.syntax().text_range().end() == r.syntax().text_range().end() { + if let Some(lhs) = expr.lhs() + && lhs.syntax().text_range().end() == r.syntax().text_range().end() { return Some(ReferenceCategory::WRITE) } - } } Some(ReferenceCategory::READ) }, diff --git a/src/tools/rust-analyzer/crates/ide-db/src/symbol_index.rs b/src/tools/rust-analyzer/crates/ide-db/src/symbol_index.rs index c15cade84a50..9c4e6f5cbf82 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/symbol_index.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/symbol_index.rs @@ -252,10 +252,10 @@ impl SymbolIndex { let mut last_batch_start = 0; for idx in 0..symbols.len() { - if let Some(next_symbol) = symbols.get(idx + 1) { - if cmp(&symbols[last_batch_start], next_symbol) == Ordering::Equal { - continue; - } + if let Some(next_symbol) = symbols.get(idx + 1) + && cmp(&symbols[last_batch_start], next_symbol) == Ordering::Equal + { + continue; } let start = last_batch_start; @@ -371,10 +371,10 @@ impl Query { if self.exclude_imports && symbol.is_import { continue; } - if self.mode.check(&self.query, self.case_sensitive, symbol_name) { - if let Some(b) = cb(symbol).break_value() { - return Some(b); - } + if self.mode.check(&self.query, self.case_sensitive, symbol_name) + && let Some(b) = cb(symbol).break_value() + { + return Some(b); } } } diff --git a/src/tools/rust-analyzer/crates/ide-db/src/syntax_helpers/format_string.rs b/src/tools/rust-analyzer/crates/ide-db/src/syntax_helpers/format_string.rs index 7e8c921d9ed3..1d4d8decf541 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/syntax_helpers/format_string.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/syntax_helpers/format_string.rs @@ -230,11 +230,11 @@ pub fn lex_format_specifiers( skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback); } continue; - } else if let '}' = first_char { - if let Some((_, '}')) = chars.peek() { - // Escaped format specifier, `}}` - read_escaped_format_specifier(&mut chars, &mut callback); - } + } else if let '}' = first_char + && let Some((_, '}')) = chars.peek() + { + // Escaped format specifier, `}}` + read_escaped_format_specifier(&mut chars, &mut callback); } } diff --git a/src/tools/rust-analyzer/crates/ide-db/src/syntax_helpers/node_ext.rs b/src/tools/rust-analyzer/crates/ide-db/src/syntax_helpers/node_ext.rs index bdff64dd0812..cefd8fd49676 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/syntax_helpers/node_ext.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/syntax_helpers/node_ext.rs @@ -79,14 +79,13 @@ pub fn preorder_expr_with_ctx_checker( continue; } }; - if let Some(let_stmt) = node.parent().and_then(ast::LetStmt::cast) { - if let_stmt.initializer().map(|it| it.syntax() != &node).unwrap_or(true) - && let_stmt.let_else().map(|it| it.syntax() != &node).unwrap_or(true) - { - // skipping potential const pat expressions in let statements - preorder.skip_subtree(); - continue; - } + if let Some(let_stmt) = node.parent().and_then(ast::LetStmt::cast) + && let_stmt.initializer().map(|it| it.syntax() != &node).unwrap_or(true) + && let_stmt.let_else().map(|it| it.syntax() != &node).unwrap_or(true) + { + // skipping potential const pat expressions in let statements + preorder.skip_subtree(); + continue; } match ast::Stmt::cast(node.clone()) { @@ -306,10 +305,10 @@ pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) { Some(ast::BlockModifier::AsyncGen(_)) => (), None => (), } - if let Some(stmt_list) = b.stmt_list() { - if let Some(e) = stmt_list.tail_expr() { - for_each_tail_expr(&e, cb); - } + if let Some(stmt_list) = b.stmt_list() + && let Some(e) = stmt_list.tail_expr() + { + for_each_tail_expr(&e, cb); } } ast::Expr::IfExpr(if_) => { diff --git a/src/tools/rust-analyzer/crates/ide-db/src/use_trivial_constructor.rs b/src/tools/rust-analyzer/crates/ide-db/src/use_trivial_constructor.rs index f63cd92694b3..a91d436afcfb 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/use_trivial_constructor.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/use_trivial_constructor.rs @@ -16,17 +16,17 @@ pub fn use_trivial_constructor( ) -> Option { match ty.as_adt() { Some(hir::Adt::Enum(x)) => { - if let &[variant] = &*x.variants(db) { - if variant.kind(db) == hir::StructKind::Unit { - let path = make::path_qualified( - path, - make::path_segment(make::name_ref( - &variant.name(db).display_no_db(edition).to_smolstr(), - )), - ); + if let &[variant] = &*x.variants(db) + && variant.kind(db) == hir::StructKind::Unit + { + let path = make::path_qualified( + path, + make::path_segment(make::name_ref( + &variant.name(db).display_no_db(edition).to_smolstr(), + )), + ); - return Some(make::expr_path(path)); - } + return Some(make::expr_path(path)); } } Some(hir::Adt::Struct(x)) if x.kind(db) == StructKind::Unit => { diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs index bf7dddacd8c5..742d614bc567 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs @@ -148,37 +148,27 @@ pub(crate) fn json_in_items( allow_unstable: true, }; - if !scope_has("Serialize") { - if let Some(PathResolution::Def(it)) = serialize_resolved { - if let Some(it) = current_module.find_use_path( - sema.db, - it, - config.insert_use.prefix_kind, - cfg, - ) { - insert_use( - &scope, - mod_path_to_ast(&it, edition), - &config.insert_use, - ); - } - } + if !scope_has("Serialize") + && let Some(PathResolution::Def(it)) = serialize_resolved + && let Some(it) = current_module.find_use_path( + sema.db, + it, + config.insert_use.prefix_kind, + cfg, + ) + { + insert_use(&scope, mod_path_to_ast(&it, edition), &config.insert_use); } - if !scope_has("Deserialize") { - if let Some(PathResolution::Def(it)) = deserialize_resolved { - if let Some(it) = current_module.find_use_path( - sema.db, - it, - config.insert_use.prefix_kind, - cfg, - ) { - insert_use( - &scope, - mod_path_to_ast(&it, edition), - &config.insert_use, - ); - } - } + if !scope_has("Deserialize") + && let Some(PathResolution::Def(it)) = deserialize_resolved + && let Some(it) = current_module.find_use_path( + sema.db, + it, + config.insert_use.prefix_kind, + cfg, + ) + { + insert_use(&scope, mod_path_to_ast(&it, edition), &config.insert_use); } let mut sc = scb.finish(); sc.insert_source_edit(vfs_file_id, edit.finish()); diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs index 7da799e0d490..893bfca6a129 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -227,12 +227,11 @@ fn get_default_constructor( // Look for a ::new() associated function let has_new_func = ty .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| { - if let AssocItem::Function(func) = assoc_item { - if func.name(ctx.sema.db) == sym::new - && func.assoc_fn_params(ctx.sema.db).is_empty() - { - return Some(()); - } + if let AssocItem::Function(func) = assoc_item + && func.name(ctx.sema.db) == sym::new + && func.assoc_fn_params(ctx.sema.db).is_empty() + { + return Some(()); } None diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs index 8831efa31172..6e30bf92dbaa 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/mutability_errors.rs @@ -12,14 +12,14 @@ pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_>, d: &hir::NeedMut) -> Option let root = ctx.sema.db.parse_or_expand(d.span.file_id); let node = d.span.value.to_node(&root); let mut span = d.span; - if let Some(parent) = node.parent() { - if ast::BinExpr::can_cast(parent.kind()) { - // In case of an assignment, the diagnostic is provided on the variable name. - // We want to expand it to include the whole assignment, but only when this - // is an ordinary assignment, not a destructuring assignment. So, the direct - // parent is an assignment expression. - span = d.span.with_value(SyntaxNodePtr::new(&parent)); - } + if let Some(parent) = node.parent() + && ast::BinExpr::can_cast(parent.kind()) + { + // In case of an assignment, the diagnostic is provided on the variable name. + // We want to expand it to include the whole assignment, but only when this + // is an ordinary assignment, not a destructuring assignment. So, the direct + // parent is an assignment expression. + span = d.span.with_value(SyntaxNodePtr::new(&parent)); }; let fixes = (|| { @@ -73,10 +73,10 @@ pub(crate) fn unused_mut(ctx: &DiagnosticsContext<'_>, d: &hir::UnusedMut) -> Op let ast = source.syntax(); let Some(mut_token) = token(ast, T![mut]) else { continue }; edit_builder.delete(mut_token.text_range()); - if let Some(token) = mut_token.next_token() { - if token.kind() == SyntaxKind::WHITESPACE { - edit_builder.delete(token.text_range()); - } + if let Some(token) = mut_token.next_token() + && token.kind() == SyntaxKind::WHITESPACE + { + edit_builder.delete(token.text_range()); } } let edit = edit_builder.finish(); diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unlinked_file.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unlinked_file.rs index d96c658d7b04..3a6e480f55ed 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unlinked_file.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/unlinked_file.rs @@ -231,13 +231,13 @@ fn make_fixes( // If there's an existing `mod m;` statement matching the new one, don't emit a fix (it's // probably `#[cfg]`d out). for item in items.clone() { - if let ast::Item::Module(m) = item { - if let Some(name) = m.name() { - if m.item_list().is_none() && name.to_string() == new_mod_name { - cov_mark::hit!(unlinked_file_skip_fix_when_mod_already_exists); - return None; - } - } + if let ast::Item::Module(m) = item + && let Some(name) = m.name() + && m.item_list().is_none() + && name.to_string() == new_mod_name + { + cov_mark::hit!(unlinked_file_skip_fix_when_mod_already_exists); + return None; } } diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/lib.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/lib.rs index 72bd66d1c8bb..a1db92641f5e 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/lib.rs @@ -568,10 +568,10 @@ fn handle_diag_from_macros( diag.fixes = None; // All Clippy lints report in macros, see https://github.com/rust-lang/rust-clippy/blob/903293b199364/declare_clippy_lint/src/lib.rs#L172. - if let DiagnosticCode::RustcLint(lint) = diag.code { - if !LINTS_TO_REPORT_IN_EXTERNAL_MACROS.contains(lint) { - return false; - } + if let DiagnosticCode::RustcLint(lint) = diag.code + && !LINTS_TO_REPORT_IN_EXTERNAL_MACROS.contains(lint) + { + return false; }; } true @@ -760,35 +760,35 @@ fn cfg_attr_lint_attrs( } while let Some(value) = iter.next() { - if let Some(token) = value.as_token() { - if token.kind() == SyntaxKind::IDENT { - let severity = match token.text() { - "allow" | "expect" => Some(Severity::Allow), - "warn" => Some(Severity::Warning), - "forbid" | "deny" => Some(Severity::Error), - "cfg_attr" => { - if let Some(NodeOrToken::Node(value)) = iter.next() { - cfg_attr_lint_attrs(sema, &value, lint_attrs); - } - None - } - _ => None, - }; - if let Some(severity) = severity { - let lints = iter.next(); - if let Some(NodeOrToken::Node(lints)) = lints { - lint_attrs.push((severity, lints)); + if let Some(token) = value.as_token() + && token.kind() == SyntaxKind::IDENT + { + let severity = match token.text() { + "allow" | "expect" => Some(Severity::Allow), + "warn" => Some(Severity::Warning), + "forbid" | "deny" => Some(Severity::Error), + "cfg_attr" => { + if let Some(NodeOrToken::Node(value)) = iter.next() { + cfg_attr_lint_attrs(sema, &value, lint_attrs); } + None + } + _ => None, + }; + if let Some(severity) = severity { + let lints = iter.next(); + if let Some(NodeOrToken::Node(lints)) = lints { + lint_attrs.push((severity, lints)); } } } } - if prev_len != lint_attrs.len() { - if let Some(false) | None = sema.check_cfg_attr(value) { - // Discard the attributes when the condition is false. - lint_attrs.truncate(prev_len); - } + if prev_len != lint_attrs.len() + && let Some(false) | None = sema.check_cfg_attr(value) + { + // Discard the attributes when the condition is false. + lint_attrs.truncate(prev_len); } } diff --git a/src/tools/rust-analyzer/crates/ide-ssr/src/lib.rs b/src/tools/rust-analyzer/crates/ide-ssr/src/lib.rs index e4b20f3f1aad..138af22089eb 100644 --- a/src/tools/rust-analyzer/crates/ide-ssr/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-ssr/src/lib.rs @@ -283,17 +283,16 @@ impl<'db> MatchFinder<'db> { node: node.clone(), }); } - } else if let Some(macro_call) = ast::MacroCall::cast(node.clone()) { - if let Some(expanded) = self.sema.expand_macro_call(¯o_call) { - if let Some(tt) = macro_call.token_tree() { - self.output_debug_for_nodes_at_range( - &expanded.value, - range, - &Some(self.sema.original_range(tt.syntax())), - out, - ); - } - } + } else if let Some(macro_call) = ast::MacroCall::cast(node.clone()) + && let Some(expanded) = self.sema.expand_macro_call(¯o_call) + && let Some(tt) = macro_call.token_tree() + { + self.output_debug_for_nodes_at_range( + &expanded.value, + range, + &Some(self.sema.original_range(tt.syntax())), + out, + ); } self.output_debug_for_nodes_at_range(&node, range, restrict_range, out); } diff --git a/src/tools/rust-analyzer/crates/ide-ssr/src/matching.rs b/src/tools/rust-analyzer/crates/ide-ssr/src/matching.rs index b350315ba548..f21132c297ee 100644 --- a/src/tools/rust-analyzer/crates/ide-ssr/src/matching.rs +++ b/src/tools/rust-analyzer/crates/ide-ssr/src/matching.rs @@ -156,12 +156,11 @@ impl<'db, 'sema> Matcher<'db, 'sema> { /// processing a macro expansion and we want to fail the match if we're working with a node that /// didn't originate from the token tree of the macro call. fn validate_range(&self, range: &FileRange) -> Result<(), MatchFailed> { - if let Some(restrict_range) = &self.restrict_range { - if restrict_range.file_id != range.file_id - || !restrict_range.range.contains_range(range.range) - { - fail_match!("Node originated from a macro"); - } + if let Some(restrict_range) = &self.restrict_range + && (restrict_range.file_id != range.file_id + || !restrict_range.range.contains_range(range.range)) + { + fail_match!("Node originated from a macro"); } Ok(()) } @@ -404,30 +403,27 @@ impl<'db, 'sema> Matcher<'db, 'sema> { // Build a map keyed by field name. let mut fields_by_name: FxHashMap = FxHashMap::default(); for child in code.children() { - if let Some(record) = ast::RecordExprField::cast(child.clone()) { - if let Some(name) = record.field_name() { - fields_by_name.insert(name.text().into(), child.clone()); - } + if let Some(record) = ast::RecordExprField::cast(child.clone()) + && let Some(name) = record.field_name() + { + fields_by_name.insert(name.text().into(), child.clone()); } } for p in pattern.children_with_tokens() { - if let SyntaxElement::Node(p) = p { - if let Some(name_element) = p.first_child_or_token() { - if self.get_placeholder(&name_element).is_some() { - // If the pattern is using placeholders for field names then order - // independence doesn't make sense. Fall back to regular ordered - // matching. - return self.attempt_match_node_children(phase, pattern, code); - } - if let Some(ident) = only_ident(name_element) { - let code_record = fields_by_name.remove(ident.text()).ok_or_else(|| { - match_error!( - "Placeholder has record field '{}', but code doesn't", - ident - ) - })?; - self.attempt_match_node(phase, &p, &code_record)?; - } + if let SyntaxElement::Node(p) = p + && let Some(name_element) = p.first_child_or_token() + { + if self.get_placeholder(&name_element).is_some() { + // If the pattern is using placeholders for field names then order + // independence doesn't make sense. Fall back to regular ordered + // matching. + return self.attempt_match_node_children(phase, pattern, code); + } + if let Some(ident) = only_ident(name_element) { + let code_record = fields_by_name.remove(ident.text()).ok_or_else(|| { + match_error!("Placeholder has record field '{}', but code doesn't", ident) + })?; + self.attempt_match_node(phase, &p, &code_record)?; } } } @@ -476,14 +472,13 @@ impl<'db, 'sema> Matcher<'db, 'sema> { } } SyntaxElement::Node(n) => { - if let Some(first_token) = n.first_token() { - if Some(first_token.text()) == next_pattern_token.as_deref() { - if let Some(SyntaxElement::Node(p)) = pattern.next() { - // We have a subtree that starts with the next token in our pattern. - self.attempt_match_token_tree(phase, &p, n)?; - break; - } - } + if let Some(first_token) = n.first_token() + && Some(first_token.text()) == next_pattern_token.as_deref() + && let Some(SyntaxElement::Node(p)) = pattern.next() + { + // We have a subtree that starts with the next token in our pattern. + self.attempt_match_token_tree(phase, &p, n)?; + break; } } }; @@ -562,23 +557,22 @@ impl<'db, 'sema> Matcher<'db, 'sema> { let deref_count = self.check_expr_type(pattern_type, expr)?; let pattern_receiver = pattern_args.next(); self.attempt_match_opt(phase, pattern_receiver.clone(), code.receiver())?; - if let Phase::Second(match_out) = phase { - if let Some(placeholder_value) = pattern_receiver + if let Phase::Second(match_out) = phase + && let Some(placeholder_value) = pattern_receiver .and_then(|n| self.get_placeholder_for_node(n.syntax())) .and_then(|placeholder| { match_out.placeholder_values.get_mut(&placeholder.ident) }) - { - placeholder_value.autoderef_count = deref_count; - placeholder_value.autoref_kind = self - .sema - .resolve_method_call_as_callable(code) - .and_then(|callable| { - let (self_param, _) = callable.receiver_param(self.sema.db)?; - Some(self.sema.source(self_param)?.value.kind()) - }) - .unwrap_or(ast::SelfParamKind::Owned); - } + { + placeholder_value.autoderef_count = deref_count; + placeholder_value.autoref_kind = self + .sema + .resolve_method_call_as_callable(code) + .and_then(|callable| { + let (self_param, _) = callable.receiver_param(self.sema.db)?; + Some(self.sema.source(self_param)?.value.kind()) + }) + .unwrap_or(ast::SelfParamKind::Owned); } } } else { @@ -698,12 +692,11 @@ impl Phase<'_> { } fn record_ignored_comments(&mut self, token: &SyntaxToken) { - if token.kind() == SyntaxKind::COMMENT { - if let Phase::Second(match_out) = self { - if let Some(comment) = ast::Comment::cast(token.clone()) { - match_out.ignored_comments.push(comment); - } - } + if token.kind() == SyntaxKind::COMMENT + && let Phase::Second(match_out) = self + && let Some(comment) = ast::Comment::cast(token.clone()) + { + match_out.ignored_comments.push(comment); } } } diff --git a/src/tools/rust-analyzer/crates/ide-ssr/src/replacing.rs b/src/tools/rust-analyzer/crates/ide-ssr/src/replacing.rs index 752edd6535a6..16287a439c35 100644 --- a/src/tools/rust-analyzer/crates/ide-ssr/src/replacing.rs +++ b/src/tools/rust-analyzer/crates/ide-ssr/src/replacing.rs @@ -112,12 +112,12 @@ impl<'db> ReplacementRenderer<'_, 'db> { self.out.push_str(&mod_path.display(self.db, self.edition).to_string()); // Emit everything except for the segment's name-ref, since we already effectively // emitted that as part of `mod_path`. - if let Some(path) = ast::Path::cast(node.clone()) { - if let Some(segment) = path.segment() { - for node_or_token in segment.syntax().children_with_tokens() { - if node_or_token.kind() != SyntaxKind::NAME_REF { - self.render_node_or_token(&node_or_token); - } + if let Some(path) = ast::Path::cast(node.clone()) + && let Some(segment) = path.segment() + { + for node_or_token in segment.syntax().children_with_tokens() { + if node_or_token.kind() != SyntaxKind::NAME_REF { + self.render_node_or_token(&node_or_token); } } } @@ -242,15 +242,15 @@ fn token_is_method_call_receiver(token: &SyntaxToken) -> bool { } fn parse_as_kind(code: &str, kind: SyntaxKind) -> Option { - if ast::Expr::can_cast(kind) { - if let Ok(expr) = fragments::expr(code) { - return Some(expr); - } + if ast::Expr::can_cast(kind) + && let Ok(expr) = fragments::expr(code) + { + return Some(expr); } - if ast::Item::can_cast(kind) { - if let Ok(item) = fragments::item(code) { - return Some(item); - } + if ast::Item::can_cast(kind) + && let Ok(item) = fragments::item(code) + { + return Some(item); } None } diff --git a/src/tools/rust-analyzer/crates/ide-ssr/src/resolving.rs b/src/tools/rust-analyzer/crates/ide-ssr/src/resolving.rs index 8f28a1cd3a62..a4e2cfbaee27 100644 --- a/src/tools/rust-analyzer/crates/ide-ssr/src/resolving.rs +++ b/src/tools/rust-analyzer/crates/ide-ssr/src/resolving.rs @@ -83,21 +83,17 @@ impl<'db> Resolver<'_, 'db> { let ufcs_function_calls = resolved_paths .iter() .filter_map(|(path_node, resolved)| { - if let Some(grandparent) = path_node.parent().and_then(|parent| parent.parent()) { - if let Some(call_expr) = ast::CallExpr::cast(grandparent.clone()) { - if let hir::PathResolution::Def(hir::ModuleDef::Function(function)) = - resolved.resolution - { - if function.as_assoc_item(self.resolution_scope.scope.db).is_some() { - let qualifier_type = - self.resolution_scope.qualifier_type(path_node); - return Some(( - grandparent, - UfcsCallInfo { call_expr, function, qualifier_type }, - )); - } - } - } + if let Some(grandparent) = path_node.parent().and_then(|parent| parent.parent()) + && let Some(call_expr) = ast::CallExpr::cast(grandparent.clone()) + && let hir::PathResolution::Def(hir::ModuleDef::Function(function)) = + resolved.resolution + && function.as_assoc_item(self.resolution_scope.scope.db).is_some() + { + let qualifier_type = self.resolution_scope.qualifier_type(path_node); + return Some(( + grandparent, + UfcsCallInfo { call_expr, function, qualifier_type }, + )); } None }) @@ -153,12 +149,11 @@ impl<'db> Resolver<'_, 'db> { /// Returns whether `path` contains a placeholder, but ignores any placeholders within type /// arguments. fn path_contains_placeholder(&self, path: &ast::Path) -> bool { - if let Some(segment) = path.segment() { - if let Some(name_ref) = segment.name_ref() { - if self.placeholders_by_stand_in.contains_key(name_ref.text().as_str()) { - return true; - } - } + if let Some(segment) = path.segment() + && let Some(name_ref) = segment.name_ref() + && self.placeholders_by_stand_in.contains_key(name_ref.text().as_str()) + { + return true; } if let Some(qualifier) = path.qualifier() { return self.path_contains_placeholder(&qualifier); @@ -252,14 +247,12 @@ impl<'db> ResolutionScope<'db> { fn qualifier_type(&self, path: &SyntaxNode) -> Option> { use syntax::ast::AstNode; - if let Some(path) = ast::Path::cast(path.clone()) { - if let Some(qualifier) = path.qualifier() { - if let Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) = - self.resolve_path(&qualifier) - { - return Some(adt.ty(self.scope.db)); - } - } + if let Some(path) = ast::Path::cast(path.clone()) + && let Some(qualifier) = path.qualifier() + && let Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) = + self.resolve_path(&qualifier) + { + return Some(adt.ty(self.scope.db)); } None } @@ -299,11 +292,11 @@ fn pick_node_for_resolution(node: SyntaxNode) -> SyntaxNode { /// Returns whether `path` or any of its qualifiers contains type arguments. fn path_contains_type_arguments(path: Option) -> bool { if let Some(path) = path { - if let Some(segment) = path.segment() { - if segment.generic_arg_list().is_some() { - cov_mark::hit!(type_arguments_within_path); - return true; - } + if let Some(segment) = path.segment() + && segment.generic_arg_list().is_some() + { + cov_mark::hit!(type_arguments_within_path); + return true; } return path_contains_type_arguments(path.qualifier()); } diff --git a/src/tools/rust-analyzer/crates/ide-ssr/src/search.rs b/src/tools/rust-analyzer/crates/ide-ssr/src/search.rs index 99a98fb2a713..72f857ceda90 100644 --- a/src/tools/rust-analyzer/crates/ide-ssr/src/search.rs +++ b/src/tools/rust-analyzer/crates/ide-ssr/src/search.rs @@ -187,16 +187,15 @@ impl<'db> MatchFinder<'db> { self.try_add_match(rule, code, restrict_range, matches_out); // If we've got a macro call, we already tried matching it pre-expansion, which is the only // way to match the whole macro, now try expanding it and matching the expansion. - if let Some(macro_call) = ast::MacroCall::cast(code.clone()) { - if let Some(expanded) = self.sema.expand_macro_call(¯o_call) { - if let Some(tt) = macro_call.token_tree() { - // When matching within a macro expansion, we only want to allow matches of - // nodes that originated entirely from within the token tree of the macro call. - // i.e. we don't want to match something that came from the macro itself. - if let Some(range) = self.sema.original_range_opt(tt.syntax()) { - self.slow_scan_node(&expanded.value, rule, &Some(range), matches_out); - } - } + if let Some(macro_call) = ast::MacroCall::cast(code.clone()) + && let Some(expanded) = self.sema.expand_macro_call(¯o_call) + && let Some(tt) = macro_call.token_tree() + { + // When matching within a macro expansion, we only want to allow matches of + // nodes that originated entirely from within the token tree of the macro call. + // i.e. we don't want to match something that came from the macro itself. + if let Some(range) = self.sema.original_range_opt(tt.syntax()) { + self.slow_scan_node(&expanded.value, rule, &Some(range), matches_out); } } for child in code.children() { @@ -241,10 +240,10 @@ impl<'db> MatchFinder<'db> { /// Returns whether we support matching within `node` and all of its ancestors. fn is_search_permitted_ancestors(node: &SyntaxNode) -> bool { - if let Some(parent) = node.parent() { - if !is_search_permitted_ancestors(&parent) { - return false; - } + if let Some(parent) = node.parent() + && !is_search_permitted_ancestors(&parent) + { + return false; } is_search_permitted(node) } diff --git a/src/tools/rust-analyzer/crates/ide/src/annotations.rs b/src/tools/rust-analyzer/crates/ide/src/annotations.rs index 05196ac98c03..dec1889926da 100644 --- a/src/tools/rust-analyzer/crates/ide/src/annotations.rs +++ b/src/tools/rust-analyzer/crates/ide/src/annotations.rs @@ -159,10 +159,10 @@ pub(crate) fn annotations( node.value.syntax().text_range(), Some(name), ); - if res.call_site.0.file_id == source_file_id { - if let Some(name_range) = res.call_site.1 { - return Some((res.call_site.0.range, Some(name_range))); - } + if res.call_site.0.file_id == source_file_id + && let Some(name_range) = res.call_site.1 + { + return Some((res.call_site.0.range, Some(name_range))); } }; // otherwise try upmapping the entire node out of attributes diff --git a/src/tools/rust-analyzer/crates/ide/src/expand_macro.rs b/src/tools/rust-analyzer/crates/ide/src/expand_macro.rs index f31886b96976..ad84eacfb3e8 100644 --- a/src/tools/rust-analyzer/crates/ide/src/expand_macro.rs +++ b/src/tools/rust-analyzer/crates/ide/src/expand_macro.rs @@ -96,14 +96,14 @@ pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option< let (name, expanded, kind) = loop { let node = anc.next()?; - if let Some(item) = ast::Item::cast(node.clone()) { - if let Some(def) = sema.resolve_attr_macro_call(&item) { - break ( - def.name(db).display(db, file_id.edition(db)).to_string(), - expand_macro_recur(&sema, &item, &mut error, &mut span_map, TextSize::new(0))?, - SyntaxKind::MACRO_ITEMS, - ); - } + if let Some(item) = ast::Item::cast(node.clone()) + && let Some(def) = sema.resolve_attr_macro_call(&item) + { + break ( + def.name(db).display(db, file_id.edition(db)).to_string(), + expand_macro_recur(&sema, &item, &mut error, &mut span_map, TextSize::new(0))?, + SyntaxKind::MACRO_ITEMS, + ); } if let Some(mac) = ast::MacroCall::cast(node) { let mut name = mac.path()?.segment()?.name_ref()?.to_string(); diff --git a/src/tools/rust-analyzer/crates/ide/src/extend_selection.rs b/src/tools/rust-analyzer/crates/ide/src/extend_selection.rs index a374f9752fcf..2926384c4078 100644 --- a/src/tools/rust-analyzer/crates/ide/src/extend_selection.rs +++ b/src/tools/rust-analyzer/crates/ide/src/extend_selection.rs @@ -81,10 +81,10 @@ fn try_extend_selection( if token.text_range() != range { return Some(token.text_range()); } - if let Some(comment) = ast::Comment::cast(token.clone()) { - if let Some(range) = extend_comments(comment) { - return Some(range); - } + if let Some(comment) = ast::Comment::cast(token.clone()) + && let Some(range) = extend_comments(comment) + { + return Some(range); } token.parent()? } @@ -92,12 +92,11 @@ fn try_extend_selection( }; // if we are in single token_tree, we maybe live in macro or attr - if node.kind() == TOKEN_TREE { - if let Some(macro_call) = node.ancestors().find_map(ast::MacroCall::cast) { - if let Some(range) = extend_tokens_from_range(sema, macro_call, range) { - return Some(range); - } - } + if node.kind() == TOKEN_TREE + && let Some(macro_call) = node.ancestors().find_map(ast::MacroCall::cast) + && let Some(range) = extend_tokens_from_range(sema, macro_call, range) + { + return Some(range); } if node.text_range() != range { @@ -106,10 +105,10 @@ fn try_extend_selection( let node = shallowest_node(&node); - if node.parent().is_some_and(|n| list_kinds.contains(&n.kind())) { - if let Some(range) = extend_list_item(&node) { - return Some(range); - } + if node.parent().is_some_and(|n| list_kinds.contains(&n.kind())) + && let Some(range) = extend_list_item(&node) + { + return Some(range); } node.parent().map(|it| it.text_range()) @@ -221,19 +220,20 @@ fn extend_ws(root: &SyntaxNode, ws: SyntaxToken, offset: TextSize) -> TextRange let prefix = TextRange::new(ws.text_range().start(), offset) - ws.text_range().start(); let ws_suffix = &ws_text[suffix]; let ws_prefix = &ws_text[prefix]; - if ws_text.contains('\n') && !ws_suffix.contains('\n') { - if let Some(node) = ws.next_sibling_or_token() { - let start = match ws_prefix.rfind('\n') { - Some(idx) => ws.text_range().start() + TextSize::from((idx + 1) as u32), - None => node.text_range().start(), - }; - let end = if root.text().char_at(node.text_range().end()) == Some('\n') { - node.text_range().end() + TextSize::of('\n') - } else { - node.text_range().end() - }; - return TextRange::new(start, end); - } + if ws_text.contains('\n') + && !ws_suffix.contains('\n') + && let Some(node) = ws.next_sibling_or_token() + { + let start = match ws_prefix.rfind('\n') { + Some(idx) => ws.text_range().start() + TextSize::from((idx + 1) as u32), + None => node.text_range().start(), + }; + let end = if root.text().char_at(node.text_range().end()) == Some('\n') { + node.text_range().end() + TextSize::of('\n') + } else { + node.text_range().end() + }; + return TextRange::new(start, end); } ws.text_range() } diff --git a/src/tools/rust-analyzer/crates/ide/src/folding_ranges.rs b/src/tools/rust-analyzer/crates/ide/src/folding_ranges.rs index 1901bcc797e7..ac64413effeb 100755 --- a/src/tools/rust-analyzer/crates/ide/src/folding_ranges.rs +++ b/src/tools/rust-analyzer/crates/ide/src/folding_ranges.rs @@ -61,30 +61,29 @@ pub(crate) fn folding_ranges(file: &SourceFile) -> Vec { }; if is_multiline { // for the func with multiline param list - if matches!(element.kind(), FN) { - if let NodeOrToken::Node(node) = &element { - if let Some(fn_node) = ast::Fn::cast(node.clone()) { - if !fn_node - .param_list() - .map(|param_list| param_list.syntax().text().contains_char('\n')) - .unwrap_or(false) - { - continue; - } + if matches!(element.kind(), FN) + && let NodeOrToken::Node(node) = &element + && let Some(fn_node) = ast::Fn::cast(node.clone()) + { + if !fn_node + .param_list() + .map(|param_list| param_list.syntax().text().contains_char('\n')) + .unwrap_or(false) + { + continue; + } - if fn_node.body().is_some() { - // Get the actual start of the function (excluding doc comments) - let fn_start = fn_node - .fn_token() - .map(|token| token.text_range().start()) - .unwrap_or(node.text_range().start()); - res.push(Fold { - range: TextRange::new(fn_start, node.text_range().end()), - kind: FoldKind::Function, - }); - continue; - } - } + if fn_node.body().is_some() { + // Get the actual start of the function (excluding doc comments) + let fn_start = fn_node + .fn_token() + .map(|token| token.text_range().start()) + .unwrap_or(node.text_range().start()); + res.push(Fold { + range: TextRange::new(fn_start, node.text_range().end()), + kind: FoldKind::Function, + }); + continue; } } res.push(Fold { range: element.text_range(), kind }); @@ -120,14 +119,13 @@ pub(crate) fn folding_ranges(file: &SourceFile) -> Vec { match_ast! { match node { ast::Module(module) => { - if module.item_list().is_none() { - if let Some(range) = contiguous_range_for_item_group( + if module.item_list().is_none() + && let Some(range) = contiguous_range_for_item_group( module, &mut visited_nodes, ) { res.push(Fold { range, kind: FoldKind::Modules }) } - } }, ast::Use(use_) => { if let Some(range) = contiguous_range_for_item_group(use_, &mut visited_nodes) { @@ -212,11 +210,11 @@ where for element in first.syntax().siblings_with_tokens(Direction::Next) { let node = match element { NodeOrToken::Token(token) => { - if let Some(ws) = ast::Whitespace::cast(token) { - if !ws.spans_multiple_lines() { - // Ignore whitespace without blank lines - continue; - } + if let Some(ws) = ast::Whitespace::cast(token) + && !ws.spans_multiple_lines() + { + // Ignore whitespace without blank lines + continue; } // There is a blank line or another token, which means that the // group ends here @@ -270,21 +268,21 @@ fn contiguous_range_for_comment( for element in first.syntax().siblings_with_tokens(Direction::Next) { match element { NodeOrToken::Token(token) => { - if let Some(ws) = ast::Whitespace::cast(token.clone()) { - if !ws.spans_multiple_lines() { - // Ignore whitespace without blank lines - continue; - } + if let Some(ws) = ast::Whitespace::cast(token.clone()) + && !ws.spans_multiple_lines() + { + // Ignore whitespace without blank lines + continue; } - if let Some(c) = ast::Comment::cast(token) { - if c.kind() == group_kind { - let text = c.text().trim_start(); - // regions are not real comments - if !(text.starts_with(REGION_START) || text.starts_with(REGION_END)) { - visited.insert(c.clone()); - last = c; - continue; - } + if let Some(c) = ast::Comment::cast(token) + && c.kind() == group_kind + { + let text = c.text().trim_start(); + // regions are not real comments + if !(text.starts_with(REGION_START) || text.starts_with(REGION_END)) { + visited.insert(c.clone()); + last = c; + continue; } } // The comment group ends because either: diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index 29fc68bb50f1..84e41277390f 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -94,18 +94,17 @@ pub(crate) fn goto_definition( let parent = token.value.parent()?; let token_file_id = token.file_id; - if let Some(token) = ast::String::cast(token.value.clone()) { - if let Some(x) = + if let Some(token) = ast::String::cast(token.value.clone()) + && let Some(x) = try_lookup_include_path(sema, InFile::new(token_file_id, token), file_id) - { - return Some(vec![x]); - } + { + return Some(vec![x]); } - if ast::TokenTree::can_cast(parent.kind()) { - if let Some(x) = try_lookup_macro_def_in_macro_use(sema, token.value) { - return Some(vec![x]); - } + if ast::TokenTree::can_cast(parent.kind()) + && let Some(x) = try_lookup_macro_def_in_macro_use(sema, token.value) + { + return Some(vec![x]); } Some( @@ -245,12 +244,11 @@ fn try_lookup_macro_def_in_macro_use( let krate = extern_crate.resolved_crate(sema.db)?; for mod_def in krate.root_module().declarations(sema.db) { - if let ModuleDef::Macro(mac) = mod_def { - if mac.name(sema.db).as_str() == token.text() { - if let Some(nav) = mac.try_to_nav(sema.db) { - return Some(nav.call_site); - } - } + if let ModuleDef::Macro(mac) = mod_def + && mac.name(sema.db).as_str() == token.text() + && let Some(nav) = mac.try_to_nav(sema.db) + { + return Some(nav.call_site); } } diff --git a/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs b/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs index 356bd69aa44e..9960e79a5380 100644 --- a/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs +++ b/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs @@ -722,20 +722,19 @@ impl<'a> WalkExpandedExprCtx<'a> { self.depth += 1; } - if let ast::Expr::MacroExpr(expr) = expr { - if let Some(expanded) = + if let ast::Expr::MacroExpr(expr) = expr + && let Some(expanded) = expr.macro_call().and_then(|call| self.sema.expand_macro_call(&call)) - { - match_ast! { - match (expanded.value) { - ast::MacroStmts(it) => { - self.handle_expanded(it, cb); - }, - ast::Expr(it) => { - self.walk(&it, cb); - }, - _ => {} - } + { + match_ast! { + match (expanded.value) { + ast::MacroStmts(it) => { + self.handle_expanded(it, cb); + }, + ast::Expr(it) => { + self.walk(&it, cb); + }, + _ => {} } } } @@ -755,10 +754,10 @@ impl<'a> WalkExpandedExprCtx<'a> { } for stmt in expanded.statements() { - if let ast::Stmt::ExprStmt(stmt) = stmt { - if let Some(expr) = stmt.expr() { - self.walk(&expr, cb); - } + if let ast::Stmt::ExprStmt(stmt) = stmt + && let Some(expr) = stmt.expr() + { + self.walk(&expr, cb); } } } @@ -806,12 +805,12 @@ pub(crate) fn highlight_unsafe_points( push_to_highlights(unsafe_token_file_id, Some(unsafe_token.text_range())); // highlight unsafe operations - if let Some(block) = block_expr { - if let Some(body) = sema.body_for(InFile::new(unsafe_token_file_id, block.syntax())) { - let unsafe_ops = sema.get_unsafe_ops(body); - for unsafe_op in unsafe_ops { - push_to_highlights(unsafe_op.file_id, Some(unsafe_op.value.text_range())); - } + if let Some(block) = block_expr + && let Some(body) = sema.body_for(InFile::new(unsafe_token_file_id, block.syntax())) + { + let unsafe_ops = sema.get_unsafe_ops(body); + for unsafe_op in unsafe_ops { + push_to_highlights(unsafe_op.file_id, Some(unsafe_op.value.text_range())); } } diff --git a/src/tools/rust-analyzer/crates/ide/src/hover.rs b/src/tools/rust-analyzer/crates/ide/src/hover.rs index e4d6279759ed..44c98a43f694 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover.rs @@ -244,17 +244,15 @@ fn hover_offset( let node = token.parent()?; // special case macro calls, we wanna render the invoked arm index - if let Some(name) = ast::NameRef::cast(node.clone()) { - if let Some(path_seg) = + if let Some(name) = ast::NameRef::cast(node.clone()) + && let Some(path_seg) = name.syntax().parent().and_then(ast::PathSegment::cast) - { - if let Some(macro_call) = path_seg + && let Some(macro_call) = path_seg .parent_path() .syntax() .parent() .and_then(ast::MacroCall::cast) - { - if let Some(macro_) = sema.resolve_macro_call(¯o_call) { + && let Some(macro_) = sema.resolve_macro_call(¯o_call) { break 'a vec![( (Definition::Macro(macro_), None), sema.resolve_macro_call_arm(¯o_call), @@ -262,9 +260,6 @@ fn hover_offset( node, )]; } - } - } - } match IdentClass::classify_node(sema, &node)? { // It's better for us to fall back to the keyword hover here, diff --git a/src/tools/rust-analyzer/crates/ide/src/hover/render.rs b/src/tools/rust-analyzer/crates/ide/src/hover/render.rs index 670210d4998d..51b5900e8155 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover/render.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover/render.rs @@ -95,23 +95,25 @@ pub(super) fn try_expr( if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts { let famous_defs = FamousDefs(sema, sema.scope(try_expr.syntax())?.krate()); // special case for two options, there is no value in showing them - if let Some(option_enum) = famous_defs.core_option_Option() { - if inner == option_enum && body == option_enum { - cov_mark::hit!(hover_try_expr_opt_opt); - return None; - } + if let Some(option_enum) = famous_defs.core_option_Option() + && inner == option_enum + && body == option_enum + { + cov_mark::hit!(hover_try_expr_opt_opt); + return None; } // special case two results to show the error variants only - if let Some(result_enum) = famous_defs.core_result_Result() { - if inner == result_enum && body == result_enum { - let error_type_args = - inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1)); - if let Some((inner, body)) = error_type_args { - inner_ty = inner; - body_ty = body; - "Try Error".clone_into(&mut s); - } + if let Some(result_enum) = famous_defs.core_result_Result() + && inner == result_enum + && body == result_enum + { + let error_type_args = + inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1)); + if let Some((inner, body)) = error_type_args { + inner_ty = inner; + body_ty = body; + "Try Error".clone_into(&mut s); } } } @@ -1132,10 +1134,10 @@ fn markup( ) -> (Markup, Option) { let mut buf = String::new(); - if let Some(mod_path) = mod_path { - if !mod_path.is_empty() { - format_to!(buf, "```rust\n{}\n```\n\n", mod_path); - } + if let Some(mod_path) = mod_path + && !mod_path.is_empty() + { + format_to!(buf, "```rust\n{}\n```\n\n", mod_path); } format_to!(buf, "```rust\n{}\n```", rust); @@ -1217,55 +1219,55 @@ fn render_memory_layout( format_to!(label, ", "); } - if let Some(render) = config.offset { - if let Some(offset) = offset(&layout) { - format_to!(label, "offset = "); - match render { - MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{offset}"), - MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{offset:#X}"), - MemoryLayoutHoverRenderKind::Both if offset >= 10 => { - format_to!(label, "{offset} ({offset:#X})") - } - MemoryLayoutHoverRenderKind::Both => { - format_to!(label, "{offset}") - } + if let Some(render) = config.offset + && let Some(offset) = offset(&layout) + { + format_to!(label, "offset = "); + match render { + MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{offset}"), + MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{offset:#X}"), + MemoryLayoutHoverRenderKind::Both if offset >= 10 => { + format_to!(label, "{offset} ({offset:#X})") + } + MemoryLayoutHoverRenderKind::Both => { + format_to!(label, "{offset}") } - format_to!(label, ", "); } + format_to!(label, ", "); } - if let Some(render) = config.padding { - if let Some((padding_name, padding)) = padding(&layout) { - format_to!(label, "{padding_name} = "); - match render { - MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{padding}"), - MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{padding:#X}"), - MemoryLayoutHoverRenderKind::Both if padding >= 10 => { - format_to!(label, "{padding} ({padding:#X})") - } - MemoryLayoutHoverRenderKind::Both => { - format_to!(label, "{padding}") - } + if let Some(render) = config.padding + && let Some((padding_name, padding)) = padding(&layout) + { + format_to!(label, "{padding_name} = "); + match render { + MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{padding}"), + MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{padding:#X}"), + MemoryLayoutHoverRenderKind::Both if padding >= 10 => { + format_to!(label, "{padding} ({padding:#X})") + } + MemoryLayoutHoverRenderKind::Both => { + format_to!(label, "{padding}") } - format_to!(label, ", "); } + format_to!(label, ", "); } - if config.niches { - if let Some(niches) = layout.niches() { - if niches > 1024 { - if niches.is_power_of_two() { - format_to!(label, "niches = 2{}, ", pwr2_to_exponent(niches)); - } else if is_pwr2plus1(niches) { - format_to!(label, "niches = 2{} + 1, ", pwr2_to_exponent(niches - 1)); - } else if is_pwr2minus1(niches) { - format_to!(label, "niches = 2{} - 1, ", pwr2_to_exponent(niches + 1)); - } else { - format_to!(label, "niches = a lot, "); - } + if config.niches + && let Some(niches) = layout.niches() + { + if niches > 1024 { + if niches.is_power_of_two() { + format_to!(label, "niches = 2{}, ", pwr2_to_exponent(niches)); + } else if is_pwr2plus1(niches) { + format_to!(label, "niches = 2{} + 1, ", pwr2_to_exponent(niches - 1)); + } else if is_pwr2minus1(niches) { + format_to!(label, "niches = 2{} - 1, ", pwr2_to_exponent(niches + 1)); } else { - format_to!(label, "niches = {niches}, "); + format_to!(label, "niches = a lot, "); } + } else { + format_to!(label, "niches = {niches}, "); } } label.pop(); // ' ' diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs index 671fddb43630..7a8514c47af9 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs @@ -576,13 +576,13 @@ impl InlayHintLabel { } pub fn append_part(&mut self, part: InlayHintLabelPart) { - if part.linked_location.is_none() && part.tooltip.is_none() { - if let Some(InlayHintLabelPart { text, linked_location: None, tooltip: None }) = + if part.linked_location.is_none() + && part.tooltip.is_none() + && let Some(InlayHintLabelPart { text, linked_location: None, tooltip: None }) = self.parts.last_mut() - { - text.push_str(&part.text); - return; - } + { + text.push_str(&part.text); + return; } self.parts.push(part); } diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs index 49b43fc37f24..4d020bac3aad 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/adjustment.rs @@ -39,10 +39,10 @@ pub(super) fn hints( if let ast::Expr::ParenExpr(_) = expr { return None; } - if let ast::Expr::BlockExpr(b) = expr { - if !b.is_standalone() { - return None; - } + if let ast::Expr::BlockExpr(b) = expr + && !b.is_standalone() + { + return None; } let descended = sema.descend_node_into_attributes(expr.clone()).pop(); diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/bind_pat.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/bind_pat.rs index 729349365e6c..922e9598aa01 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/bind_pat.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/bind_pat.rs @@ -41,13 +41,11 @@ pub(super) fn hints( Some(it.colon_token()) }, ast::LetStmt(it) => { - if config.hide_closure_initialization_hints { - if let Some(ast::Expr::ClosureExpr(closure)) = it.initializer() { - if closure_has_block_body(&closure) { + if config.hide_closure_initialization_hints + && let Some(ast::Expr::ClosureExpr(closure)) = it.initializer() + && closure_has_block_body(&closure) { return None; } - } - } if it.ty().is_some() { return None; } diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs index ff157fa171b5..a8bb652fda22 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs @@ -51,12 +51,11 @@ pub(super) fn hints( if ty.is_unknown() { return None; } - if matches!(expr, ast::Expr::PathExpr(_)) { - if let Some(hir::Adt::Struct(st)) = ty.as_adt() { - if st.fields(sema.db).is_empty() { - return None; - } - } + if matches!(expr, ast::Expr::PathExpr(_)) + && let Some(hir::Adt::Struct(st)) = ty.as_adt() + && st.fields(sema.db).is_empty() + { + return None; } let label = label_of_ty(famous_defs, config, &ty, display_target)?; acc.push(InlayHint { diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closing_brace.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closing_brace.rs index 05253b679489..e80c9dc9d473 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closing_brace.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closing_brace.rs @@ -120,11 +120,11 @@ pub(super) fn hints( }; if let Some(mut next) = closing_token.next_token() { - if next.kind() == T![;] { - if let Some(tok) = next.next_token() { - closing_token = next; - next = tok; - } + if next.kind() == T![;] + && let Some(tok) = next.next_token() + { + closing_token = next; + next = tok; } if !(next.kind() == SyntaxKind::WHITESPACE && next.text().contains('\n')) { // Only display the hint if the `}` is the last token on the line diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closure_ret.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closure_ret.rs index 9e600b5455be..fef1cb83c119 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closure_ret.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/closure_ret.rs @@ -55,11 +55,9 @@ pub(super) fn hints( // Insert braces if necessary let insert_braces = |builder: &mut TextEditBuilder| { - if !has_block_body { - if let Some(range) = closure.body().map(|b| b.syntax().text_range()) { - builder.insert(range.start(), "{ ".to_owned()); - builder.insert(range.end(), " }".to_owned()); - } + if !has_block_body && let Some(range) = closure.body().map(|b| b.syntax().text_range()) { + builder.insert(range.start(), "{ ".to_owned()); + builder.insert(range.end(), " }".to_owned()); } }; diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/extern_block.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/extern_block.rs index 88152bf3e388..491018a4dda8 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/extern_block.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/extern_block.rs @@ -81,10 +81,10 @@ fn item_hint( text_edit: Some(config.lazy_text_edit(|| { let mut builder = TextEdit::builder(); builder.insert(token.text_range().start(), "unsafe ".to_owned()); - if extern_block.unsafe_token().is_none() { - if let Some(abi) = extern_block.abi() { - builder.insert(abi.syntax().text_range().start(), "unsafe ".to_owned()); - } + if extern_block.unsafe_token().is_none() + && let Some(abi) = extern_block.abi() + { + builder.insert(abi.syntax().text_range().start(), "unsafe ".to_owned()); } builder.finish() })), diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/generic_param.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/generic_param.rs index 6e1b3bdbdf03..1fddb6fbe01d 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/generic_param.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/generic_param.rs @@ -33,10 +33,10 @@ pub(crate) fn hints( let mut args = generic_arg_list.generic_args().peekable(); let start_with_lifetime = matches!(args.peek()?, ast::GenericArg::LifetimeArg(_)); let params = generic_def.params(sema.db).into_iter().filter(|p| { - if let hir::GenericParam::TypeParam(it) = p { - if it.is_implicit(sema.db) { - return false; - } + if let hir::GenericParam::TypeParam(it) = p + && it.is_implicit(sema.db) + { + return false; } if !start_with_lifetime { return !matches!(p, hir::GenericParam::LifetimeParam(_)); diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/implicit_static.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/implicit_static.rs index 7212efd954e8..bddce904dfde 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/implicit_static.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/implicit_static.rs @@ -22,30 +22,31 @@ pub(super) fn hints( return None; } - if let Either::Right(it) = &statik_or_const { - if ast::AssocItemList::can_cast( + if let Either::Right(it) = &statik_or_const + && ast::AssocItemList::can_cast( it.syntax().parent().map_or(SyntaxKind::EOF, |it| it.kind()), - ) { - return None; - } + ) + { + return None; } - if let Some(ast::Type::RefType(ty)) = statik_or_const.either(|it| it.ty(), |it| it.ty()) { - if ty.lifetime().is_none() { - let t = ty.amp_token()?; - acc.push(InlayHint { - range: t.text_range(), - kind: InlayKind::Lifetime, - label: "'static".into(), - text_edit: Some(config.lazy_text_edit(|| { - TextEdit::insert(t.text_range().start(), "'static ".into()) - })), - position: InlayHintPosition::After, - pad_left: false, - pad_right: true, - resolve_parent: None, - }); - } + if let Some(ast::Type::RefType(ty)) = statik_or_const.either(|it| it.ty(), |it| it.ty()) + && ty.lifetime().is_none() + { + let t = ty.amp_token()?; + acc.push(InlayHint { + range: t.text_range(), + kind: InlayKind::Lifetime, + label: "'static".into(), + text_edit: Some( + config + .lazy_text_edit(|| TextEdit::insert(t.text_range().start(), "'static ".into())), + ), + position: InlayHintPosition::After, + pad_left: false, + pad_right: true, + resolve_parent: None, + }); } Some(()) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/lifetime.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/lifetime.rs index 49fec0a793c3..a89c53e00b3b 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/lifetime.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/lifetime.rs @@ -324,35 +324,35 @@ fn hints_( // apply hints // apply output if required - if let (Some(output_lt), Some(r)) = (&output, ret_type) { - if let Some(ty) = r.ty() { - walk_ty(&ty, &mut |ty| match ty { - ast::Type::RefType(ty) if ty.lifetime().is_none() => { - if let Some(amp) = ty.amp_token() { - is_trivial = false; - acc.push(mk_lt_hint(amp, output_lt.to_string())); - } - false + if let (Some(output_lt), Some(r)) = (&output, ret_type) + && let Some(ty) = r.ty() + { + walk_ty(&ty, &mut |ty| match ty { + ast::Type::RefType(ty) if ty.lifetime().is_none() => { + if let Some(amp) = ty.amp_token() { + is_trivial = false; + acc.push(mk_lt_hint(amp, output_lt.to_string())); } - ast::Type::FnPtrType(_) => { + false + } + ast::Type::FnPtrType(_) => { + is_trivial = false; + true + } + ast::Type::PathType(t) => { + if t.path() + .and_then(|it| it.segment()) + .and_then(|it| it.parenthesized_arg_list()) + .is_some() + { is_trivial = false; true + } else { + false } - ast::Type::PathType(t) => { - if t.path() - .and_then(|it| it.segment()) - .and_then(|it| it.parenthesized_arg_list()) - .is_some() - { - is_trivial = false; - true - } else { - false - } - } - _ => false, - }) - } + } + _ => false, + }) } if config.lifetime_elision_hints == LifetimeElisionHints::SkipTrivial && is_trivial { diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/param_name.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/param_name.rs index 5174228466c0..ec0a4c46c7fe 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/param_name.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/param_name.rs @@ -135,10 +135,10 @@ fn should_hide_param_name_hint( } if unary_function { - if let Some(function_name) = function_name { - if is_param_name_suffix_of_fn_name(param_name, function_name) { - return true; - } + if let Some(function_name) = function_name + && is_param_name_suffix_of_fn_name(param_name, function_name) + { + return true; } if is_obvious_param(param_name) { return true; diff --git a/src/tools/rust-analyzer/crates/ide/src/join_lines.rs b/src/tools/rust-analyzer/crates/ide/src/join_lines.rs index 0188c105faa7..a946559c3545 100644 --- a/src/tools/rust-analyzer/crates/ide/src/join_lines.rs +++ b/src/tools/rust-analyzer/crates/ide/src/join_lines.rs @@ -144,15 +144,15 @@ fn remove_newline( } } - if config.join_else_if { - if let (Some(prev), Some(_next)) = (as_if_expr(&prev), as_if_expr(&next)) { - match prev.else_token() { - Some(_) => cov_mark::hit!(join_two_ifs_with_existing_else), - None => { - cov_mark::hit!(join_two_ifs); - edit.replace(token.text_range(), " else ".to_owned()); - return; - } + if config.join_else_if + && let (Some(prev), Some(_next)) = (as_if_expr(&prev), as_if_expr(&next)) + { + match prev.else_token() { + Some(_) => cov_mark::hit!(join_two_ifs_with_existing_else), + None => { + cov_mark::hit!(join_two_ifs); + edit.replace(token.text_range(), " else ".to_owned()); + return; } } } @@ -213,10 +213,10 @@ fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Op let mut buf = expr.syntax().text().to_string(); // Match block needs to have a comma after the block - if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) { - if match_arm.comma_token().is_none() { - buf.push(','); - } + if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) + && match_arm.comma_token().is_none() + { + buf.push(','); } edit.replace(block_range, buf); diff --git a/src/tools/rust-analyzer/crates/ide/src/parent_module.rs b/src/tools/rust-analyzer/crates/ide/src/parent_module.rs index 50219cee57db..96d829d1260b 100644 --- a/src/tools/rust-analyzer/crates/ide/src/parent_module.rs +++ b/src/tools/rust-analyzer/crates/ide/src/parent_module.rs @@ -29,14 +29,13 @@ pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec(source_file.syntax(), position.offset); // If cursor is literally on `mod foo`, go to the grandpa. - if let Some(m) = &module { - if !m + if let Some(m) = &module + && !m .item_list() .is_some_and(|it| it.syntax().text_range().contains_inclusive(position.offset)) - { - cov_mark::hit!(test_resolve_parent_module_on_module_decl); - module = m.syntax().ancestors().skip(1).find_map(ast::Module::cast); - } + { + cov_mark::hit!(test_resolve_parent_module_on_module_decl); + module = m.syntax().ancestors().skip(1).find_map(ast::Module::cast); } match module { diff --git a/src/tools/rust-analyzer/crates/ide/src/rename.rs b/src/tools/rust-analyzer/crates/ide/src/rename.rs index 6c1d142c3b05..634edaa5edaf 100644 --- a/src/tools/rust-analyzer/crates/ide/src/rename.rs +++ b/src/tools/rust-analyzer/crates/ide/src/rename.rs @@ -494,10 +494,10 @@ mod tests { ) { let ra_fixture_after = &trim_indent(ra_fixture_after); let (analysis, position) = fixture::position(ra_fixture_before); - if !ra_fixture_after.starts_with("error: ") { - if let Err(err) = analysis.prepare_rename(position).unwrap() { - panic!("Prepare rename to '{new_name}' was failed: {err}") - } + if !ra_fixture_after.starts_with("error: ") + && let Err(err) = analysis.prepare_rename(position).unwrap() + { + panic!("Prepare rename to '{new_name}' was failed: {err}") } let rename_result = analysis .rename(position, new_name) diff --git a/src/tools/rust-analyzer/crates/ide/src/runnables.rs b/src/tools/rust-analyzer/crates/ide/src/runnables.rs index 9d1a5bae96fb..83e5c5ab1dfe 100644 --- a/src/tools/rust-analyzer/crates/ide/src/runnables.rs +++ b/src/tools/rust-analyzer/crates/ide/src/runnables.rs @@ -514,20 +514,19 @@ fn module_def_doctest(db: &RootDatabase, def: Definition) -> Option { .flat_map(|it| it.name(db)) .for_each(|name| format_to!(path, "{}::", name.display(db, edition))); // This probably belongs to canonical_path? - if let Some(assoc_item) = def.as_assoc_item(db) { - if let Some(ty) = assoc_item.implementing_ty(db) { - if let Some(adt) = ty.as_adt() { - let name = adt.name(db); - let mut ty_args = ty.generic_parameters(db, display_target).peekable(); - format_to!(path, "{}", name.display(db, edition)); - if ty_args.peek().is_some() { - format_to!(path, "<{}>", ty_args.format_with(",", |ty, cb| cb(&ty))); - } - format_to!(path, "::{}", def_name.display(db, edition)); - path.retain(|c| c != ' '); - return Some(path); - } + if let Some(assoc_item) = def.as_assoc_item(db) + && let Some(ty) = assoc_item.implementing_ty(db) + && let Some(adt) = ty.as_adt() + { + let name = adt.name(db); + let mut ty_args = ty.generic_parameters(db, display_target).peekable(); + format_to!(path, "{}", name.display(db, edition)); + if ty_args.peek().is_some() { + format_to!(path, "<{}>", ty_args.format_with(",", |ty, cb| cb(&ty))); } + format_to!(path, "::{}", def_name.display(db, edition)); + path.retain(|c| c != ' '); + return Some(path); } format_to!(path, "{}", def_name.display(db, edition)); Some(path) @@ -697,14 +696,13 @@ impl UpdateTest { continue; }; for item in items { - if let hir::ItemInNs::Macros(makro) = item { - if Definition::Macro(makro) + if let hir::ItemInNs::Macros(makro) = item + && Definition::Macro(makro) .usages(sema) .in_scope(&search_scope) .at_least_one() - { - return true; - } + { + return true; } } } diff --git a/src/tools/rust-analyzer/crates/ide/src/signature_help.rs b/src/tools/rust-analyzer/crates/ide/src/signature_help.rs index e30a3ebefb98..382573b68011 100644 --- a/src/tools/rust-analyzer/crates/ide/src/signature_help.rs +++ b/src/tools/rust-analyzer/crates/ide/src/signature_help.rs @@ -146,12 +146,11 @@ pub(crate) fn signature_help( // Stop at multi-line expressions, since the signature of the outer call is not very // helpful inside them. - if let Some(expr) = ast::Expr::cast(node.clone()) { - if !matches!(expr, ast::Expr::RecordExpr(..)) - && expr.syntax().text().contains_char('\n') - { - break; - } + if let Some(expr) = ast::Expr::cast(node.clone()) + && !matches!(expr, ast::Expr::RecordExpr(..)) + && expr.syntax().text().contains_char('\n') + { + break; } } @@ -366,10 +365,10 @@ fn signature_help_for_generics( res.signature.push('<'); let mut buf = String::new(); for param in params { - if let hir::GenericParam::TypeParam(ty) = param { - if ty.is_implicit(db) { - continue; - } + if let hir::GenericParam::TypeParam(ty) = param + && ty.is_implicit(db) + { + continue; } buf.clear(); diff --git a/src/tools/rust-analyzer/crates/ide/src/static_index.rs b/src/tools/rust-analyzer/crates/ide/src/static_index.rs index efee39c13db9..694ac22e1993 100644 --- a/src/tools/rust-analyzer/crates/ide/src/static_index.rs +++ b/src/tools/rust-analyzer/crates/ide/src/static_index.rs @@ -133,10 +133,10 @@ fn get_definitions( ) -> Option> { for token in sema.descend_into_macros_exact(token) { let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops); - if let Some(defs) = def { - if !defs.is_empty() { - return Some(defs); - } + if let Some(defs) = def + && !defs.is_empty() + { + return Some(defs); } } None diff --git a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/highlight.rs b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/highlight.rs index 87db0cd7dc53..8bde8fd97006 100644 --- a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/highlight.rs +++ b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/highlight.rs @@ -306,12 +306,12 @@ fn highlight_name_ref( }; let mut h = match name_class { NameRefClass::Definition(def, _) => { - if let Definition::Local(local) = &def { - if let Some(bindings_shadow_count) = bindings_shadow_count { - let name = local.name(sema.db); - let shadow_count = bindings_shadow_count.entry(name.clone()).or_default(); - *binding_hash = Some(calc_binding_hash(&name, *shadow_count)) - } + if let Definition::Local(local) = &def + && let Some(bindings_shadow_count) = bindings_shadow_count + { + let name = local.name(sema.db); + let shadow_count = bindings_shadow_count.entry(name.clone()).or_default(); + *binding_hash = Some(calc_binding_hash(&name, *shadow_count)) }; let mut h = highlight_def(sema, krate, def, edition, true); @@ -437,21 +437,21 @@ fn highlight_name( edition: Edition, ) -> Highlight { let name_kind = NameClass::classify(sema, &name); - if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind { - if let Some(bindings_shadow_count) = bindings_shadow_count { - let name = local.name(sema.db); - let shadow_count = bindings_shadow_count.entry(name.clone()).or_default(); - *shadow_count += 1; - *binding_hash = Some(calc_binding_hash(&name, *shadow_count)) - } + if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind + && let Some(bindings_shadow_count) = bindings_shadow_count + { + let name = local.name(sema.db); + let shadow_count = bindings_shadow_count.entry(name.clone()).or_default(); + *shadow_count += 1; + *binding_hash = Some(calc_binding_hash(&name, *shadow_count)) }; match name_kind { Some(NameClass::Definition(def)) => { let mut h = highlight_def(sema, krate, def, edition, false) | HlMod::Definition; - if let Definition::Trait(trait_) = &def { - if trait_.is_unsafe(sema.db) { - h |= HlMod::Unsafe; - } + if let Definition::Trait(trait_) = &def + && trait_.is_unsafe(sema.db) + { + h |= HlMod::Unsafe; } h } @@ -743,10 +743,9 @@ fn highlight_method_call( hir::Access::Owned => { if let Some(receiver_ty) = method_call.receiver().and_then(|it| sema.type_of_expr(&it)) + && !receiver_ty.adjusted().is_copy(sema.db) { - if !receiver_ty.adjusted().is_copy(sema.db) { - h |= HlMod::Consuming - } + h |= HlMod::Consuming } } } diff --git a/src/tools/rust-analyzer/crates/load-cargo/src/lib.rs b/src/tools/rust-analyzer/crates/load-cargo/src/lib.rs index 98f415a522cb..ad838a6550ec 100644 --- a/src/tools/rust-analyzer/crates/load-cargo/src/lib.rs +++ b/src/tools/rust-analyzer/crates/load-cargo/src/lib.rs @@ -475,10 +475,10 @@ fn load_crate_graph_into_db( } let changes = vfs.take_changes(); for (_, file) in changes { - if let vfs::Change::Create(v, _) | vfs::Change::Modify(v, _) = file.change { - if let Ok(text) = String::from_utf8(v) { - analysis_change.change_file(file.file_id, Some(text)) - } + if let vfs::Change::Create(v, _) | vfs::Change::Modify(v, _) = file.change + && let Ok(text) = String::from_utf8(v) + { + analysis_change.change_file(file.file_id, Some(text)) } } let source_roots = source_root_config.partition(vfs); diff --git a/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs b/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs index 04ac85ad43dd..b185556b5c7b 100644 --- a/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs +++ b/src/tools/rust-analyzer/crates/mbe/src/benchmark.rs @@ -185,24 +185,22 @@ fn invocation_fixtures( for it in tokens.iter() { collect_from_op(it, builder, seed); } - if i + 1 != cnt { - if let Some(sep) = separator { - match &**sep { - Separator::Literal(it) => { - builder.push(tt::Leaf::Literal(it.clone())) + if i + 1 != cnt + && let Some(sep) = separator + { + match &**sep { + Separator::Literal(it) => builder.push(tt::Leaf::Literal(it.clone())), + Separator::Ident(it) => builder.push(tt::Leaf::Ident(it.clone())), + Separator::Puncts(puncts) => { + for it in puncts { + builder.push(tt::Leaf::Punct(*it)) } - Separator::Ident(it) => builder.push(tt::Leaf::Ident(it.clone())), - Separator::Puncts(puncts) => { - for it in puncts { - builder.push(tt::Leaf::Punct(*it)) - } - } - Separator::Lifetime(punct, ident) => { - builder.push(tt::Leaf::Punct(*punct)); - builder.push(tt::Leaf::Ident(ident.clone())); - } - }; - } + } + Separator::Lifetime(punct, ident) => { + builder.push(tt::Leaf::Punct(*punct)); + builder.push(tt::Leaf::Ident(ident.clone())); + } + }; } } } diff --git a/src/tools/rust-analyzer/crates/mbe/src/expander/matcher.rs b/src/tools/rust-analyzer/crates/mbe/src/expander/matcher.rs index a8d5965d480c..189efcd15c2f 100644 --- a/src/tools/rust-analyzer/crates/mbe/src/expander/matcher.rs +++ b/src/tools/rust-analyzer/crates/mbe/src/expander/matcher.rs @@ -475,12 +475,12 @@ fn match_loop_inner<'t>( }) } OpDelimited::Op(Op::Subtree { tokens, delimiter }) => { - if let Ok((subtree, _)) = src.clone().expect_subtree() { - if subtree.delimiter.kind == delimiter.kind { - item.stack.push(item.dot); - item.dot = tokens.iter_delimited_with(*delimiter); - cur_items.push(item); - } + if let Ok((subtree, _)) = src.clone().expect_subtree() + && subtree.delimiter.kind == delimiter.kind + { + item.stack.push(item.dot); + item.dot = tokens.iter_delimited_with(*delimiter); + cur_items.push(item); } } OpDelimited::Op(Op::Var { kind, name, .. }) => { diff --git a/src/tools/rust-analyzer/crates/parser/src/grammar/expressions.rs b/src/tools/rust-analyzer/crates/parser/src/grammar/expressions.rs index 2b4151e3b752..41fd72d8d5a2 100644 --- a/src/tools/rust-analyzer/crates/parser/src/grammar/expressions.rs +++ b/src/tools/rust-analyzer/crates/parser/src/grammar/expressions.rs @@ -77,38 +77,38 @@ pub(super) fn stmt(p: &mut Parser<'_>, semicolon: Semicolon) { return; } - if let Some((cm, blocklike)) = expr_stmt(p, Some(m)) { - if !(p.at(T!['}']) || (semicolon != Semicolon::Required && p.at(EOF))) { - // test no_semi_after_block - // fn foo() { - // if true {} - // loop {} - // match () {} - // while true {} - // for _ in () {} - // {} - // {} - // macro_rules! test { - // () => {} - // } - // test!{} - // } - let m = cm.precede(p); - match semicolon { - Semicolon::Required => { - if blocklike.is_block() { - p.eat(T![;]); - } else { - p.expect(T![;]); - } - } - Semicolon::Optional => { + if let Some((cm, blocklike)) = expr_stmt(p, Some(m)) + && !(p.at(T!['}']) || (semicolon != Semicolon::Required && p.at(EOF))) + { + // test no_semi_after_block + // fn foo() { + // if true {} + // loop {} + // match () {} + // while true {} + // for _ in () {} + // {} + // {} + // macro_rules! test { + // () => {} + // } + // test!{} + // } + let m = cm.precede(p); + match semicolon { + Semicolon::Required => { + if blocklike.is_block() { p.eat(T![;]); + } else { + p.expect(T![;]); } - Semicolon::Forbidden => (), } - m.complete(p, EXPR_STMT); + Semicolon::Optional => { + p.eat(T![;]); + } + Semicolon::Forbidden => (), } + m.complete(p, EXPR_STMT); } } @@ -134,14 +134,11 @@ pub(super) fn let_stmt(p: &mut Parser<'_>, with_semi: Semicolon) { if p.at(T![else]) { // test_err let_else_right_curly_brace // fn func() { let Some(_) = {Some(1)} else { panic!("h") };} - if let Some(expr) = expr_after_eq { - if let Some(token) = expr.last_token(p) { - if token == T!['}'] { - p.error( - "right curly brace `}` before `else` in a `let...else` statement not allowed" - ) - } - } + if let Some(expr) = expr_after_eq + && let Some(token) = expr.last_token(p) + && token == T!['}'] + { + p.error("right curly brace `}` before `else` in a `let...else` statement not allowed") } // test let_else diff --git a/src/tools/rust-analyzer/crates/parser/src/input.rs b/src/tools/rust-analyzer/crates/parser/src/input.rs index 4490956f9704..331bc58dd052 100644 --- a/src/tools/rust-analyzer/crates/parser/src/input.rs +++ b/src/tools/rust-analyzer/crates/parser/src/input.rs @@ -61,7 +61,7 @@ impl Input { #[inline] fn push_impl(&mut self, kind: SyntaxKind, contextual_kind: SyntaxKind) { let idx = self.len(); - if idx % (bits::BITS as usize) == 0 { + if idx.is_multiple_of(bits::BITS as usize) { self.joint.push(0); } self.kind.push(kind); diff --git a/src/tools/rust-analyzer/crates/parser/src/shortcuts.rs b/src/tools/rust-analyzer/crates/parser/src/shortcuts.rs index e2baec890c3a..d5e513933f7a 100644 --- a/src/tools/rust-analyzer/crates/parser/src/shortcuts.rs +++ b/src/tools/rust-analyzer/crates/parser/src/shortcuts.rs @@ -252,10 +252,10 @@ fn n_attached_trivias<'a>( WHITESPACE if text.contains("\n\n") => { // we check whether the next token is a doc-comment // and skip the whitespace in this case - if let Some((COMMENT, peek_text)) = trivias.peek().map(|(_, pair)| pair) { - if is_outer(peek_text) { - continue; - } + if let Some((COMMENT, peek_text)) = trivias.peek().map(|(_, pair)| pair) + && is_outer(peek_text) + { + continue; } break; } diff --git a/src/tools/rust-analyzer/crates/query-group-macro/src/lib.rs b/src/tools/rust-analyzer/crates/query-group-macro/src/lib.rs index ec4b6b2a4ac3..277cc0b269d7 100644 --- a/src/tools/rust-analyzer/crates/query-group-macro/src/lib.rs +++ b/src/tools/rust-analyzer/crates/query-group-macro/src/lib.rs @@ -278,15 +278,15 @@ pub(crate) fn query_group_impl( return Err(syn::Error::new(signature.span(), "Queries must have a return type")); }; - if let syn::Type::Path(ref ty_path) = *return_ty { - if matches!(query_kind, QueryKind::Input) { - let field = InputStructField { - name: method_name.to_token_stream(), - ty: ty_path.path.to_token_stream(), - }; - - input_struct_fields.push(field); - } + if let syn::Type::Path(ref ty_path) = *return_ty + && matches!(query_kind, QueryKind::Input) + { + let field = InputStructField { + name: method_name.to_token_stream(), + ty: ty_path.path.to_token_stream(), + }; + + input_struct_fields.push(field); } if let Some(block) = &mut method.default { diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/bin/main.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/bin/main.rs index 4dba97c8ec49..ab045e0bf9ff 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/bin/main.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/bin/main.rs @@ -122,12 +122,12 @@ fn setup_logging(log_file_flag: Option) -> anyhow::Result<()> { // directory which we set to the project workspace. // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/general-environment-variables // https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-syminitialize - if let Ok(path) = env::current_exe() { - if let Some(path) = path.parent() { - // SAFETY: This is safe because this is single-threaded. - unsafe { - env::set_var("_NT_SYMBOL_PATH", path); - } + if let Ok(path) = env::current_exe() + && let Some(path) = path.parent() + { + // SAFETY: This is safe because this is single-threaded. + unsafe { + env::set_var("_NT_SYMBOL_PATH", path); } } } diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs index 4f75d14834c6..97886844a9f9 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -136,34 +136,30 @@ impl flags::AnalysisStats { for source_root_id in source_roots { let source_root = db.source_root(source_root_id).source_root(db); for file_id in source_root.iter() { - if let Some(p) = source_root.path_for_file(&file_id) { - if let Some((_, Some("rs"))) = p.name_and_extension() { - // measure workspace/project code - if !source_root.is_library || self.with_deps { - let length = db.file_text(file_id).text(db).lines().count(); - let item_stats = db - .file_item_tree( - EditionedFileId::current_edition(db, file_id).into(), - ) - .item_tree_stats() - .into(); - - workspace_loc += length; - workspace_item_trees += 1; - workspace_item_stats += item_stats; - } else { - let length = db.file_text(file_id).text(db).lines().count(); - let item_stats = db - .file_item_tree( - EditionedFileId::current_edition(db, file_id).into(), - ) - .item_tree_stats() - .into(); - - dep_loc += length; - dep_item_trees += 1; - dep_item_stats += item_stats; - } + if let Some(p) = source_root.path_for_file(&file_id) + && let Some((_, Some("rs"))) = p.name_and_extension() + { + // measure workspace/project code + if !source_root.is_library || self.with_deps { + let length = db.file_text(file_id).text(db).lines().count(); + let item_stats = db + .file_item_tree(EditionedFileId::current_edition(db, file_id).into()) + .item_tree_stats() + .into(); + + workspace_loc += length; + workspace_item_trees += 1; + workspace_item_stats += item_stats; + } else { + let length = db.file_text(file_id).text(db).lines().count(); + let item_stats = db + .file_item_tree(EditionedFileId::current_edition(db, file_id).into()) + .item_tree_stats() + .into(); + + dep_loc += length; + dep_item_trees += 1; + dep_item_stats += item_stats; } } } @@ -560,29 +556,35 @@ impl flags::AnalysisStats { std::fs::write(path, txt).unwrap(); let res = ws.run_build_scripts(&cargo_config, &|_| ()).unwrap(); - if let Some(err) = res.error() { - if err.contains("error: could not compile") { - if let Some(mut err_idx) = err.find("error[E") { - err_idx += 7; - let err_code = &err[err_idx..err_idx + 4]; - match err_code { - "0282" | "0283" => continue, // Byproduct of testing method - "0277" | "0308" if generated.contains(&todo) => continue, // See https://github.com/rust-lang/rust/issues/69882 - // FIXME: In some rare cases `AssocItem::container_or_implemented_trait` returns `None` for trait methods. - // Generated code is valid in case traits are imported - "0599" if err.contains("the following trait is implemented but not in scope") => continue, - _ => (), + if let Some(err) = res.error() + && err.contains("error: could not compile") + { + if let Some(mut err_idx) = err.find("error[E") { + err_idx += 7; + let err_code = &err[err_idx..err_idx + 4]; + match err_code { + "0282" | "0283" => continue, // Byproduct of testing method + "0277" | "0308" if generated.contains(&todo) => continue, // See https://github.com/rust-lang/rust/issues/69882 + // FIXME: In some rare cases `AssocItem::container_or_implemented_trait` returns `None` for trait methods. + // Generated code is valid in case traits are imported + "0599" + if err.contains( + "the following trait is implemented but not in scope", + ) => + { + continue; } - bar.println(err); - bar.println(generated); - acc.error_codes - .entry(err_code.to_owned()) - .and_modify(|n| *n += 1) - .or_insert(1); - } else { - acc.syntax_errors += 1; - bar.println(format!("Syntax error: \n{err}")); + _ => (), } + bar.println(err); + bar.println(generated); + acc.error_codes + .entry(err_code.to_owned()) + .and_modify(|n| *n += 1) + .or_insert(1); + } else { + acc.syntax_errors += 1; + bar.println(format!("Syntax error: \n{err}")); } } } @@ -731,12 +733,11 @@ impl flags::AnalysisStats { let name = body_id.name(db).unwrap_or_else(Name::missing); let module = body_id.module(db); let display_target = module.krate().to_display_target(db); - if let Some(only_name) = self.only.as_deref() { - if name.display(db, Edition::LATEST).to_string() != only_name - && full_name(db, body_id, module) != only_name - { - continue; - } + if let Some(only_name) = self.only.as_deref() + && name.display(db, Edition::LATEST).to_string() != only_name + && full_name(db, body_id, module) != only_name + { + continue; } let msg = move || { if verbosity.is_verbose() { diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/progress_report.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/progress_report.rs index 1b9b870a7c74..028311388c56 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/progress_report.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/progress_report.rs @@ -83,11 +83,11 @@ impl<'a> ProgressReport<'a> { output.extend(text.chars().skip(common_prefix_length)); // If the new text is shorter than the old one: delete overlapping characters - if let Some(overlap_count) = self.text.len().checked_sub(text.len()) { - if overlap_count > 0 { - output += &" ".repeat(overlap_count); - output += &"\x08".repeat(overlap_count); - } + if let Some(overlap_count) = self.text.len().checked_sub(text.len()) + && overlap_count > 0 + { + output += &" ".repeat(overlap_count); + output += &"\x08".repeat(overlap_count); } let _ = io::stdout().write(output.as_bytes()); diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/rustc_tests.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/rustc_tests.rs index 30ac93fb6f83..36ae98b321b8 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/rustc_tests.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/rustc_tests.rs @@ -305,10 +305,10 @@ impl flags::RustcTests { for i in walk_dir { let i = i?; let p = i.into_path(); - if let Some(f) = &self.filter { - if !p.as_os_str().to_string_lossy().contains(f) { - continue; - } + if let Some(f) = &self.filter + && !p.as_os_str().to_string_lossy().contains(f) + { + continue; } if p.extension().is_none_or(|x| x != "rs") { continue; diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs index a8bcce196c4e..70d04485ca08 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs @@ -3904,17 +3904,16 @@ mod tests { for idx in url_offsets { let link = &schema[idx..]; // matching on whitespace to ignore normal links - if let Some(link_end) = link.find([' ', '[']) { - if link.chars().nth(link_end) == Some('[') { - if let Some(link_text_end) = link.find(']') { - let link_text = link[link_end..(link_text_end + 1)].to_string(); - - schema.replace_range((idx + link_end)..(idx + link_text_end + 1), ""); - schema.insert(idx, '('); - schema.insert(idx + link_end + 1, ')'); - schema.insert_str(idx, &link_text); - } - } + if let Some(link_end) = link.find([' ', '[']) + && link.chars().nth(link_end) == Some('[') + && let Some(link_text_end) = link.find(']') + { + let link_text = link[link_end..(link_text_end + 1)].to_string(); + + schema.replace_range((idx + link_end)..(idx + link_text_end + 1), ""); + schema.insert(idx, '('); + schema.insert(idx + link_end + 1, ')'); + schema.insert_str(idx, &link_text); } } diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/config/patch_old_style.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/config/patch_old_style.rs index 95857dd8f3b4..389bb7848c01 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/config/patch_old_style.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/config/patch_old_style.rs @@ -73,19 +73,19 @@ pub(super) fn patch_json_for_outdated_configs(json: &mut Value) { } // completion.snippets -> completion.snippets.custom; - if let Some(Value::Object(obj)) = copy.pointer("/completion/snippets").cloned() { - if obj.len() != 1 || obj.get("custom").is_none() { - merge( - json, - json! {{ - "completion": { - "snippets": { - "custom": obj - }, + if let Some(Value::Object(obj)) = copy.pointer("/completion/snippets").cloned() + && (obj.len() != 1 || obj.get("custom").is_none()) + { + merge( + json, + json! {{ + "completion": { + "snippets": { + "custom": obj }, - }}, - ); - } + }, + }}, + ); } // callInfo_full -> signatureInfo_detail, signatureInfo_documentation_enable diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics/to_proto.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics/to_proto.rs index 79d8f678de4d..3f64628de860 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics/to_proto.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics/to_proto.rs @@ -298,10 +298,10 @@ pub(crate) fn map_rust_diagnostic_to_lsp( let mut source = String::from("rustc"); let mut code = rd.code.as_ref().map(|c| c.code.clone()); - if let Some(code_val) = &code { - if config.check_ignore.contains(code_val) { - return Vec::new(); - } + if let Some(code_val) = &code + && config.check_ignore.contains(code_val) + { + return Vec::new(); } if let Some(code_val) = &code { @@ -373,10 +373,8 @@ pub(crate) fn map_rust_diagnostic_to_lsp( let primary_location = primary_location(config, workspace_root, primary_span, snap); let message = { let mut message = message.clone(); - if needs_primary_span_label { - if let Some(primary_span_label) = &primary_span.label { - format_to!(message, "\n{}", primary_span_label); - } + if needs_primary_span_label && let Some(primary_span_label) = &primary_span.label { + format_to!(message, "\n{}", primary_span_label); } message }; diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/flycheck.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/flycheck.rs index 512ce0b9de35..e4e0bcdc1cd0 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/flycheck.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/flycheck.rs @@ -492,12 +492,11 @@ impl FlycheckActor { FlycheckConfig::CargoCommand { command, options, ansi_color_output } => { let mut cmd = toolchain::command(Tool::Cargo.path(), &*self.root, &options.extra_env); - if let Some(sysroot_root) = &self.sysroot_root { - if !options.extra_env.contains_key("RUSTUP_TOOLCHAIN") - && std::env::var_os("RUSTUP_TOOLCHAIN").is_none() - { - cmd.env("RUSTUP_TOOLCHAIN", AsRef::::as_ref(sysroot_root)); - } + if let Some(sysroot_root) = &self.sysroot_root + && !options.extra_env.contains_key("RUSTUP_TOOLCHAIN") + && std::env::var_os("RUSTUP_TOOLCHAIN").is_none() + { + cmd.env("RUSTUP_TOOLCHAIN", AsRef::::as_ref(sysroot_root)); } cmd.arg(command); diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/global_state.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/global_state.rs index 62a28a1a685d..3171bdd36178 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/global_state.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/global_state.rs @@ -591,10 +591,10 @@ impl GlobalState { pub(crate) fn respond(&mut self, response: lsp_server::Response) { if let Some((method, start)) = self.req_queue.incoming.complete(&response.id) { - if let Some(err) = &response.error { - if err.message.starts_with("server panicked") { - self.poke_rust_analyzer_developer(format!("{}, check the log", err.message)); - } + if let Some(err) = &response.error + && err.message.starts_with("server panicked") + { + self.poke_rust_analyzer_developer(format!("{}, check the log", err.message)); } let duration = start.elapsed(); @@ -663,18 +663,18 @@ impl GlobalState { pub(crate) fn check_workspaces_msrv(&self) -> impl Iterator + '_ { self.workspaces.iter().filter_map(|ws| { - if let Some(toolchain) = &ws.toolchain { - if *toolchain < crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION { - return Some(format!( - "Workspace `{}` is using an outdated toolchain version `{}` but \ + if let Some(toolchain) = &ws.toolchain + && *toolchain < crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION + { + return Some(format!( + "Workspace `{}` is using an outdated toolchain version `{}` but \ rust-analyzer only supports `{}` and higher.\n\ Consider using the rust-analyzer rustup component for your toolchain or upgrade your toolchain to a supported version.\n\n", - ws.manifest_or_root(), - toolchain, - crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION, - )); - } + ws.manifest_or_root(), + toolchain, + crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION, + )); } None }) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs index aea116e647db..b25245dd884a 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/dispatch.rs @@ -433,10 +433,10 @@ impl NotificationDispatcher<'_> { } pub(crate) fn finish(&mut self) { - if let Some(not) = &self.not { - if !not.method.starts_with("$/") { - tracing::error!("unhandled notification: {:?}", not); - } + if let Some(not) = &self.not + && !not.method.starts_with("$/") + { + tracing::error!("unhandled notification: {:?}", not); } } } diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/notification.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/notification.rs index 200e972e4289..e193ff77743d 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/notification.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/notification.rs @@ -39,14 +39,12 @@ pub(crate) fn handle_work_done_progress_cancel( state: &mut GlobalState, params: WorkDoneProgressCancelParams, ) -> anyhow::Result<()> { - if let lsp_types::NumberOrString::String(s) = ¶ms.token { - if let Some(id) = s.strip_prefix("rust-analyzer/flycheck/") { - if let Ok(id) = id.parse::() { - if let Some(flycheck) = state.flycheck.get(id as usize) { - flycheck.cancel(); - } - } - } + if let lsp_types::NumberOrString::String(s) = ¶ms.token + && let Some(id) = s.strip_prefix("rust-analyzer/flycheck/") + && let Ok(id) = id.parse::() + && let Some(flycheck) = state.flycheck.get(id as usize) + { + flycheck.cancel(); } // Just ignore this. It is OK to continue sending progress @@ -76,12 +74,12 @@ pub(crate) fn handle_did_open_text_document( tracing::error!("duplicate DidOpenTextDocument: {}", path); } - if let Some(abs_path) = path.as_path() { - if state.config.excluded().any(|excluded| abs_path.starts_with(&excluded)) { - tracing::trace!("opened excluded file {abs_path}"); - state.vfs.write().0.insert_excluded_file(path); - return Ok(()); - } + if let Some(abs_path) = path.as_path() + && state.config.excluded().any(|excluded| abs_path.starts_with(&excluded)) + { + tracing::trace!("opened excluded file {abs_path}"); + state.vfs.write().0.insert_excluded_file(path); + return Ok(()); } let contents = params.text_document.text.into_bytes(); @@ -449,12 +447,11 @@ pub(crate) fn handle_run_flycheck( params: RunFlycheckParams, ) -> anyhow::Result<()> { let _p = tracing::info_span!("handle_run_flycheck").entered(); - if let Some(text_document) = params.text_document { - if let Ok(vfs_path) = from_proto::vfs_path(&text_document.uri) { - if run_flycheck(state, vfs_path) { - return Ok(()); - } - } + if let Some(text_document) = params.text_document + && let Ok(vfs_path) = from_proto::vfs_path(&text_document.uri) + && run_flycheck(state, vfs_path) + { + return Ok(()); } // No specific flycheck was triggered, so let's trigger all of them. if state.config.flycheck_workspace(None) { diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs index a76a65220d3b..25c0aac405e7 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs @@ -973,14 +973,13 @@ pub(crate) fn handle_runnables( res.push(runnable); } - if let lsp_ext::RunnableArgs::Cargo(r) = &mut runnable.args { - if let Some(TargetSpec::Cargo(CargoTargetSpec { + if let lsp_ext::RunnableArgs::Cargo(r) = &mut runnable.args + && let Some(TargetSpec::Cargo(CargoTargetSpec { sysroot_root: Some(sysroot_root), .. })) = &target_spec - { - r.environment.insert("RUSTC_TOOLCHAIN".to_owned(), sysroot_root.to_string()); - } + { + r.environment.insert("RUSTC_TOOLCHAIN".to_owned(), sysroot_root.to_string()); }; res.push(runnable); @@ -1034,25 +1033,25 @@ pub(crate) fn handle_runnables( } Some(TargetSpec::ProjectJson(_)) => {} None => { - if !snap.config.linked_or_discovered_projects().is_empty() { - if let Some(path) = snap.file_id_to_file_path(file_id).parent() { - let mut cargo_args = vec!["check".to_owned(), "--workspace".to_owned()]; - cargo_args.extend(config.cargo_extra_args.iter().cloned()); - res.push(lsp_ext::Runnable { - label: "cargo check --workspace".to_owned(), - location: None, - kind: lsp_ext::RunnableKind::Cargo, - args: lsp_ext::RunnableArgs::Cargo(lsp_ext::CargoRunnableArgs { - workspace_root: None, - cwd: path.as_path().unwrap().to_path_buf().into(), - override_cargo: config.override_cargo, - cargo_args, - executable_args: Vec::new(), - environment: Default::default(), - }), - }); - }; - } + if !snap.config.linked_or_discovered_projects().is_empty() + && let Some(path) = snap.file_id_to_file_path(file_id).parent() + { + let mut cargo_args = vec!["check".to_owned(), "--workspace".to_owned()]; + cargo_args.extend(config.cargo_extra_args.iter().cloned()); + res.push(lsp_ext::Runnable { + label: "cargo check --workspace".to_owned(), + location: None, + kind: lsp_ext::RunnableKind::Cargo, + args: lsp_ext::RunnableArgs::Cargo(lsp_ext::CargoRunnableArgs { + workspace_root: None, + cwd: path.as_path().unwrap().to_path_buf().into(), + override_cargo: config.override_cargo, + cargo_args, + executable_args: Vec::new(), + environment: Default::default(), + }), + }); + }; } } Ok(res) @@ -1557,12 +1556,12 @@ pub(crate) fn handle_code_action_resolve( code_action.edit = ca.edit; code_action.command = ca.command; - if let Some(edit) = code_action.edit.as_ref() { - if let Some(changes) = edit.document_changes.as_ref() { - for change in changes { - if let lsp_ext::SnippetDocumentChangeOperation::Op(res_op) = change { - resource_ops_supported(&snap.config, resolve_resource_op(res_op))? - } + if let Some(edit) = code_action.edit.as_ref() + && let Some(changes) = edit.document_changes.as_ref() + { + for change in changes { + if let lsp_ext::SnippetDocumentChangeOperation::Op(res_op) = change { + resource_ops_supported(&snap.config, resolve_resource_op(res_op))? } } } @@ -1958,12 +1957,11 @@ pub(crate) fn handle_semantic_tokens_full_delta( if let Some(cached_tokens @ lsp_types::SemanticTokens { result_id: Some(prev_id), .. }) = &cached_tokens + && *prev_id == params.previous_result_id { - if *prev_id == params.previous_result_id { - let delta = to_proto::semantic_token_delta(cached_tokens, &semantic_tokens); - snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens); - return Ok(Some(delta.into())); - } + let delta = to_proto::semantic_token_delta(cached_tokens, &semantic_tokens); + snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens); + return Ok(Some(delta.into())); } // Clone first to keep the lock short @@ -2122,24 +2120,25 @@ fn show_impl_command_link( snap: &GlobalStateSnapshot, position: &FilePosition, ) -> Option { - if snap.config.hover_actions().implementations && snap.config.client_commands().show_reference { - if let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) { - let uri = to_proto::url(snap, position.file_id); - let line_index = snap.file_line_index(position.file_id).ok()?; - let position = to_proto::position(&line_index, position.offset); - let locations: Vec<_> = nav_data - .info - .into_iter() - .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok()) - .collect(); - let title = to_proto::implementation_title(locations.len()); - let command = to_proto::command::show_references(title, &uri, position, locations); - - return Some(lsp_ext::CommandLinkGroup { - commands: vec![to_command_link(command, "Go to implementations".into())], - ..Default::default() - }); - } + if snap.config.hover_actions().implementations + && snap.config.client_commands().show_reference + && let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) + { + let uri = to_proto::url(snap, position.file_id); + let line_index = snap.file_line_index(position.file_id).ok()?; + let position = to_proto::position(&line_index, position.offset); + let locations: Vec<_> = nav_data + .info + .into_iter() + .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok()) + .collect(); + let title = to_proto::implementation_title(locations.len()); + let command = to_proto::command::show_references(title, &uri, position, locations); + + return Some(lsp_ext::CommandLinkGroup { + commands: vec![to_command_link(command, "Go to implementations".into())], + ..Default::default() + }); } None } @@ -2148,28 +2147,29 @@ fn show_ref_command_link( snap: &GlobalStateSnapshot, position: &FilePosition, ) -> Option { - if snap.config.hover_actions().references && snap.config.client_commands().show_reference { - if let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) { - let uri = to_proto::url(snap, position.file_id); - let line_index = snap.file_line_index(position.file_id).ok()?; - let position = to_proto::position(&line_index, position.offset); - let locations: Vec<_> = ref_search_res - .into_iter() - .flat_map(|res| res.references) - .flat_map(|(file_id, ranges)| { - ranges.into_iter().map(move |(range, _)| FileRange { file_id, range }) - }) - .unique() - .filter_map(|range| to_proto::location(snap, range).ok()) - .collect(); - let title = to_proto::reference_title(locations.len()); - let command = to_proto::command::show_references(title, &uri, position, locations); - - return Some(lsp_ext::CommandLinkGroup { - commands: vec![to_command_link(command, "Go to references".into())], - ..Default::default() - }); - } + if snap.config.hover_actions().references + && snap.config.client_commands().show_reference + && let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) + { + let uri = to_proto::url(snap, position.file_id); + let line_index = snap.file_line_index(position.file_id).ok()?; + let position = to_proto::position(&line_index, position.offset); + let locations: Vec<_> = ref_search_res + .into_iter() + .flat_map(|res| res.references) + .flat_map(|(file_id, ranges)| { + ranges.into_iter().map(move |(range, _)| FileRange { file_id, range }) + }) + .unique() + .filter_map(|range| to_proto::location(snap, range).ok()) + .collect(); + let title = to_proto::reference_title(locations.len()); + let command = to_proto::command::show_references(title, &uri, position, locations); + + return Some(lsp_ext::CommandLinkGroup { + commands: vec![to_command_link(command, "Go to references".into())], + ..Default::default() + }); } None } diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs index 00cf890510d4..61c758d5e86e 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs @@ -501,14 +501,12 @@ impl GlobalState { } } - if self.config.cargo_autoreload_config(None) - || self.config.discover_workspace_config().is_some() - { - if let Some((cause, FetchWorkspaceRequest { path, force_crate_graph_reload })) = + if (self.config.cargo_autoreload_config(None) + || self.config.discover_workspace_config().is_some()) + && let Some((cause, FetchWorkspaceRequest { path, force_crate_graph_reload })) = self.fetch_workspaces_queue.should_start_op() - { - self.fetch_workspaces(cause, path, force_crate_graph_reload); - } + { + self.fetch_workspaces(cause, path, force_crate_graph_reload); } if !self.fetch_workspaces_queue.op_in_progress() { @@ -765,33 +763,33 @@ impl GlobalState { self.report_progress("Fetching", state, msg, None, None); } Task::DiscoverLinkedProjects(arg) => { - if let Some(cfg) = self.config.discover_workspace_config() { - if !self.discover_workspace_queue.op_in_progress() { - // the clone is unfortunately necessary to avoid a borrowck error when - // `self.report_progress` is called later - let title = &cfg.progress_label.clone(); - let command = cfg.command.clone(); - let discover = DiscoverCommand::new(self.discover_sender.clone(), command); - - self.report_progress(title, Progress::Begin, None, None, None); - self.discover_workspace_queue - .request_op("Discovering workspace".to_owned(), ()); - let _ = self.discover_workspace_queue.should_start_op(); - - let arg = match arg { - DiscoverProjectParam::Buildfile(it) => DiscoverArgument::Buildfile(it), - DiscoverProjectParam::Path(it) => DiscoverArgument::Path(it), - }; + if let Some(cfg) = self.config.discover_workspace_config() + && !self.discover_workspace_queue.op_in_progress() + { + // the clone is unfortunately necessary to avoid a borrowck error when + // `self.report_progress` is called later + let title = &cfg.progress_label.clone(); + let command = cfg.command.clone(); + let discover = DiscoverCommand::new(self.discover_sender.clone(), command); + + self.report_progress(title, Progress::Begin, None, None, None); + self.discover_workspace_queue + .request_op("Discovering workspace".to_owned(), ()); + let _ = self.discover_workspace_queue.should_start_op(); + + let arg = match arg { + DiscoverProjectParam::Buildfile(it) => DiscoverArgument::Buildfile(it), + DiscoverProjectParam::Path(it) => DiscoverArgument::Path(it), + }; - let handle = discover.spawn( - arg, - &std::env::current_dir() - .expect("Failed to get cwd during project discovery"), - ); - self.discover_handle = Some(handle.unwrap_or_else(|e| { - panic!("Failed to spawn project discovery command: {e}") - })); - } + let handle = discover.spawn( + arg, + &std::env::current_dir() + .expect("Failed to get cwd during project discovery"), + ); + self.discover_handle = Some(handle.unwrap_or_else(|e| { + panic!("Failed to spawn project discovery command: {e}") + })); } } Task::FetchBuildData(progress) => { diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/reload.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/reload.rs index e798aa6a8a60..aa38aa72d44e 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/reload.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/reload.rs @@ -306,13 +306,13 @@ impl GlobalState { _ => None, }); - if let Some(build) = build { - if is_quiescent { - let path = AbsPathBuf::try_from(build.build_file) - .expect("Unable to convert to an AbsPath"); - let arg = DiscoverProjectParam::Buildfile(path); - sender.send(Task::DiscoverLinkedProjects(arg)).unwrap(); - } + if let Some(build) = build + && is_quiescent + { + let path = AbsPathBuf::try_from(build.build_file) + .expect("Unable to convert to an AbsPath"); + let arg = DiscoverProjectParam::Buildfile(path); + sender.send(Task::DiscoverLinkedProjects(arg)).unwrap(); } } diff --git a/src/tools/rust-analyzer/crates/span/src/map.rs b/src/tools/rust-analyzer/crates/span/src/map.rs index f58201793da2..bb09933536e7 100644 --- a/src/tools/rust-analyzer/crates/span/src/map.rs +++ b/src/tools/rust-analyzer/crates/span/src/map.rs @@ -41,13 +41,13 @@ where /// Pushes a new span onto the [`SpanMap`]. pub fn push(&mut self, offset: TextSize, span: SpanData) { - if cfg!(debug_assertions) { - if let Some(&(last_offset, _)) = self.spans.last() { - assert!( - last_offset < offset, - "last_offset({last_offset:?}) must be smaller than offset({offset:?})" - ); - } + if cfg!(debug_assertions) + && let Some(&(last_offset, _)) = self.spans.last() + { + assert!( + last_offset < offset, + "last_offset({last_offset:?}) must be smaller than offset({offset:?})" + ); } self.spans.push((offset, span)); } diff --git a/src/tools/rust-analyzer/crates/syntax-bridge/src/lib.rs b/src/tools/rust-analyzer/crates/syntax-bridge/src/lib.rs index d59229952f52..bdff671802c2 100644 --- a/src/tools/rust-analyzer/crates/syntax-bridge/src/lib.rs +++ b/src/tools/rust-analyzer/crates/syntax-bridge/src/lib.rs @@ -768,17 +768,17 @@ where } fn bump(&mut self) -> Option<(Self::Token, TextRange)> { - if let Some((punct, offset)) = self.punct_offset.clone() { - if usize::from(offset) + 1 < punct.text().len() { - let offset = offset + TextSize::of('.'); - let range = punct.text_range(); - self.punct_offset = Some((punct.clone(), offset)); - let range = TextRange::at(range.start() + offset, TextSize::of('.')); - return Some(( - SynToken::Punct { token: punct, offset: u32::from(offset) as usize }, - range, - )); - } + if let Some((punct, offset)) = self.punct_offset.clone() + && usize::from(offset) + 1 < punct.text().len() + { + let offset = offset + TextSize::of('.'); + let range = punct.text_range(); + self.punct_offset = Some((punct.clone(), offset)); + let range = TextRange::at(range.start() + offset, TextSize::of('.')); + return Some(( + SynToken::Punct { token: punct, offset: u32::from(offset) as usize }, + range, + )); } if let Some(leaf) = self.current_leaves.pop() { diff --git a/src/tools/rust-analyzer/crates/syntax-bridge/src/prettify_macro_expansion.rs b/src/tools/rust-analyzer/crates/syntax-bridge/src/prettify_macro_expansion.rs index 0a5c8df0d0ae..2f932e045832 100644 --- a/src/tools/rust-analyzer/crates/syntax-bridge/src/prettify_macro_expansion.rs +++ b/src/tools/rust-analyzer/crates/syntax-bridge/src/prettify_macro_expansion.rs @@ -61,10 +61,11 @@ pub fn prettify_macro_expansion( } _ => continue, }; - if token.kind() == SyntaxKind::IDENT && token.text() == "$crate" { - if let Some(replacement) = dollar_crate_replacement(&token) { - dollar_crate_replacements.push((token.clone(), replacement)); - } + if token.kind() == SyntaxKind::IDENT + && token.text() == "$crate" + && let Some(replacement) = dollar_crate_replacement(&token) + { + dollar_crate_replacements.push((token.clone(), replacement)); } let tok = &token; diff --git a/src/tools/rust-analyzer/crates/syntax-bridge/src/tests.rs b/src/tools/rust-analyzer/crates/syntax-bridge/src/tests.rs index 8871bf56a5df..c8dc3131b59c 100644 --- a/src/tools/rust-analyzer/crates/syntax-bridge/src/tests.rs +++ b/src/tools/rust-analyzer/crates/syntax-bridge/src/tests.rs @@ -34,14 +34,11 @@ fn check_punct_spacing(fixture: &str) { while !cursor.eof() { while let Some(token_tree) = cursor.token_tree() { if let tt::TokenTree::Leaf(Leaf::Punct(Punct { - spacing, - span: Span { range, .. }, - .. + spacing, span: Span { range, .. }, .. })) = token_tree + && let Some(expected) = annotations.remove(range) { - if let Some(expected) = annotations.remove(range) { - assert_eq!(expected, *spacing); - } + assert_eq!(expected, *spacing); } cursor.bump(); } diff --git a/src/tools/rust-analyzer/crates/syntax-bridge/src/to_parser_input.rs b/src/tools/rust-analyzer/crates/syntax-bridge/src/to_parser_input.rs index 021dc6595f9b..c0ff8e1db2c2 100644 --- a/src/tools/rust-analyzer/crates/syntax-bridge/src/to_parser_input.rs +++ b/src/tools/rust-analyzer/crates/syntax-bridge/src/to_parser_input.rs @@ -21,17 +21,17 @@ pub fn to_parser_input( let tt = current.token_tree(); // Check if it is lifetime - if let Some(tt::TokenTree::Leaf(tt::Leaf::Punct(punct))) = tt { - if punct.char == '\'' { - current.bump(); - match current.token_tree() { - Some(tt::TokenTree::Leaf(tt::Leaf::Ident(_ident))) => { - res.push(LIFETIME_IDENT); - current.bump(); - continue; - } - _ => panic!("Next token must be ident"), + if let Some(tt::TokenTree::Leaf(tt::Leaf::Punct(punct))) = tt + && punct.char == '\'' + { + current.bump(); + match current.token_tree() { + Some(tt::TokenTree::Leaf(tt::Leaf::Ident(_ident))) => { + res.push(LIFETIME_IDENT); + current.bump(); + continue; } + _ => panic!("Next token must be ident"), } } diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/edit.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/edit.rs index d97fdec524fb..9b30642fe4b0 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/edit.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/edit.rs @@ -89,11 +89,11 @@ impl IndentLevel { _ => None, }); for token in tokens { - if let Some(ws) = ast::Whitespace::cast(token) { - if ws.text().contains('\n') { - let new_ws = make::tokens::whitespace(&format!("{}{self}", ws.syntax())); - ted::replace(ws.syntax(), &new_ws); - } + if let Some(ws) = ast::Whitespace::cast(token) + && ws.text().contains('\n') + { + let new_ws = make::tokens::whitespace(&format!("{}{self}", ws.syntax())); + ted::replace(ws.syntax(), &new_ws); } } } @@ -122,13 +122,13 @@ impl IndentLevel { _ => None, }); for token in tokens { - if let Some(ws) = ast::Whitespace::cast(token) { - if ws.text().contains('\n') { - let new_ws = make::tokens::whitespace( - &ws.syntax().text().replace(&format!("\n{self}"), "\n"), - ); - ted::replace(ws.syntax(), &new_ws); - } + if let Some(ws) = ast::Whitespace::cast(token) + && ws.text().contains('\n') + { + let new_ws = make::tokens::whitespace( + &ws.syntax().text().replace(&format!("\n{self}"), "\n"), + ); + ted::replace(ws.syntax(), &new_ws); } } } diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs index 28b543ea7064..f01ac081c8bd 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs @@ -383,10 +383,10 @@ impl ast::GenericParamList { impl ast::WhereClause { pub fn add_predicate(&self, predicate: ast::WherePred) { - if let Some(pred) = self.predicates().last() { - if !pred.syntax().siblings_with_tokens(Direction::Next).any(|it| it.kind() == T![,]) { - ted::append_child_raw(self.syntax(), make::token(T![,])); - } + if let Some(pred) = self.predicates().last() + && !pred.syntax().siblings_with_tokens(Direction::Next).any(|it| it.kind() == T![,]) + { + ted::append_child_raw(self.syntax(), make::token(T![,])); } ted::append_child(self.syntax(), predicate.syntax()); } @@ -744,10 +744,10 @@ impl ast::LetStmt { } if let Some(existing_ty) = self.ty() { - if let Some(sibling) = existing_ty.syntax().prev_sibling_or_token() { - if sibling.kind() == SyntaxKind::WHITESPACE { - ted::remove(sibling); - } + if let Some(sibling) = existing_ty.syntax().prev_sibling_or_token() + && sibling.kind() == SyntaxKind::WHITESPACE + { + ted::remove(sibling); } ted::remove(existing_ty.syntax()); @@ -823,19 +823,18 @@ impl ast::RecordExprField { return; } // this is a shorthand - if let Some(ast::Expr::PathExpr(path_expr)) = self.expr() { - if let Some(path) = path_expr.path() { - if let Some(name_ref) = path.as_single_name_ref() { - path_expr.syntax().detach(); - let children = vec![ - name_ref.syntax().clone().into(), - ast::make::token(T![:]).into(), - ast::make::tokens::single_space().into(), - expr.syntax().clone().into(), - ]; - ted::insert_all_raw(Position::last_child_of(self.syntax()), children); - } - } + if let Some(ast::Expr::PathExpr(path_expr)) = self.expr() + && let Some(path) = path_expr.path() + && let Some(name_ref) = path.as_single_name_ref() + { + path_expr.syntax().detach(); + let children = vec![ + name_ref.syntax().clone().into(), + ast::make::token(T![:]).into(), + ast::make::tokens::single_space().into(), + expr.syntax().clone().into(), + ]; + ted::insert_all_raw(Position::last_child_of(self.syntax()), children); } } } diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/prec.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/prec.rs index 00750bff0ba2..1364adb187fc 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/prec.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/prec.rs @@ -276,19 +276,19 @@ impl Expr { } // Not every expression can be followed by `else` in the `let-else` - if let Some(ast::Stmt::LetStmt(e)) = stmt { - if e.let_else().is_some() { - match self { - BinExpr(e) - if e.op_kind() - .map(|op| matches!(op, BinaryOp::LogicOp(_))) - .unwrap_or(false) => - { - return true; - } - _ if self.clone().trailing_brace().is_some() => return true, - _ => {} + if let Some(ast::Stmt::LetStmt(e)) = stmt + && e.let_else().is_some() + { + match self { + BinExpr(e) + if e.op_kind() + .map(|op| matches!(op, BinaryOp::LogicOp(_))) + .unwrap_or(false) => + { + return true; } + _ if self.clone().trailing_brace().is_some() => return true, + _ => {} } } diff --git a/src/tools/rust-analyzer/crates/syntax/src/syntax_editor.rs b/src/tools/rust-analyzer/crates/syntax/src/syntax_editor.rs index 5107754b1825..124ac5c072c9 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/syntax_editor.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/syntax_editor.rs @@ -626,10 +626,10 @@ mod tests { if let Some(ret_ty) = parent_fn.ret_type() { editor.delete(ret_ty.syntax().clone()); - if let Some(SyntaxElement::Token(token)) = ret_ty.syntax().next_sibling_or_token() { - if token.kind().is_trivia() { - editor.delete(token); - } + if let Some(SyntaxElement::Token(token)) = ret_ty.syntax().next_sibling_or_token() + && token.kind().is_trivia() + { + editor.delete(token); } } diff --git a/src/tools/rust-analyzer/crates/syntax/src/ted.rs b/src/tools/rust-analyzer/crates/syntax/src/ted.rs index 6fcbdd006c24..5c286479c4e3 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ted.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ted.rs @@ -90,15 +90,15 @@ pub fn insert_raw(position: Position, elem: impl Element) { insert_all_raw(position, vec![elem.syntax_element()]); } pub fn insert_all(position: Position, mut elements: Vec) { - if let Some(first) = elements.first() { - if let Some(ws) = ws_before(&position, first) { - elements.insert(0, ws.into()); - } + if let Some(first) = elements.first() + && let Some(ws) = ws_before(&position, first) + { + elements.insert(0, ws.into()); } - if let Some(last) = elements.last() { - if let Some(ws) = ws_after(&position, last) { - elements.push(ws.into()); - } + if let Some(last) = elements.last() + && let Some(ws) = ws_after(&position, last) + { + elements.push(ws.into()); } insert_all_raw(position, elements); } @@ -165,20 +165,22 @@ fn ws_before(position: &Position, new: &SyntaxElement) -> Option { PositionRepr::After(it) => it, }; - if prev.kind() == T!['{'] && new.kind() == SyntaxKind::USE { - if let Some(item_list) = prev.parent().and_then(ast::ItemList::cast) { - let mut indent = IndentLevel::from_element(&item_list.syntax().clone().into()); - indent.0 += 1; - return Some(make::tokens::whitespace(&format!("\n{indent}"))); - } + if prev.kind() == T!['{'] + && new.kind() == SyntaxKind::USE + && let Some(item_list) = prev.parent().and_then(ast::ItemList::cast) + { + let mut indent = IndentLevel::from_element(&item_list.syntax().clone().into()); + indent.0 += 1; + return Some(make::tokens::whitespace(&format!("\n{indent}"))); } - if prev.kind() == T!['{'] && ast::Stmt::can_cast(new.kind()) { - if let Some(stmt_list) = prev.parent().and_then(ast::StmtList::cast) { - let mut indent = IndentLevel::from_element(&stmt_list.syntax().clone().into()); - indent.0 += 1; - return Some(make::tokens::whitespace(&format!("\n{indent}"))); - } + if prev.kind() == T!['{'] + && ast::Stmt::can_cast(new.kind()) + && let Some(stmt_list) = prev.parent().and_then(ast::StmtList::cast) + { + let mut indent = IndentLevel::from_element(&stmt_list.syntax().clone().into()); + indent.0 += 1; + return Some(make::tokens::whitespace(&format!("\n{indent}"))); } ws_between(prev, new) diff --git a/src/tools/rust-analyzer/crates/syntax/src/validation.rs b/src/tools/rust-analyzer/crates/syntax/src/validation.rs index 4180f9cd1855..485140be8f69 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/validation.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/validation.rs @@ -142,50 +142,50 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec) { match literal.kind() { ast::LiteralKind::String(s) => { - if !s.is_raw() { - if let Some(without_quotes) = unquote(text, 1, '"') { - unescape_str(without_quotes, |range, char| { - if let Err(err) = char { - push_err(1, range.start, err); - } - }); - } + if !s.is_raw() + && let Some(without_quotes) = unquote(text, 1, '"') + { + unescape_str(without_quotes, |range, char| { + if let Err(err) = char { + push_err(1, range.start, err); + } + }); } } ast::LiteralKind::ByteString(s) => { - if !s.is_raw() { - if let Some(without_quotes) = unquote(text, 2, '"') { - unescape_byte_str(without_quotes, |range, char| { - if let Err(err) = char { - push_err(1, range.start, err); - } - }); - } + if !s.is_raw() + && let Some(without_quotes) = unquote(text, 2, '"') + { + unescape_byte_str(without_quotes, |range, char| { + if let Err(err) = char { + push_err(1, range.start, err); + } + }); } } ast::LiteralKind::CString(s) => { - if !s.is_raw() { - if let Some(without_quotes) = unquote(text, 2, '"') { - unescape_c_str(without_quotes, |range, char| { - if let Err(err) = char { - push_err(1, range.start, err); - } - }); - } + if !s.is_raw() + && let Some(without_quotes) = unquote(text, 2, '"') + { + unescape_c_str(without_quotes, |range, char| { + if let Err(err) = char { + push_err(1, range.start, err); + } + }); } } ast::LiteralKind::Char(_) => { - if let Some(without_quotes) = unquote(text, 1, '\'') { - if let Err(err) = unescape_char(without_quotes) { - push_err(1, 0, err); - } + if let Some(without_quotes) = unquote(text, 1, '\'') + && let Err(err) = unescape_char(without_quotes) + { + push_err(1, 0, err); } } ast::LiteralKind::Byte(_) => { - if let Some(without_quotes) = unquote(text, 2, '\'') { - if let Err(err) = unescape_byte(without_quotes) { - push_err(2, 0, err); - } + if let Some(without_quotes) = unquote(text, 2, '\'') + && let Err(err) = unescape_byte(without_quotes) + { + push_err(2, 0, err); } } ast::LiteralKind::IntNumber(_) @@ -224,14 +224,14 @@ pub(crate) fn validate_block_structure(root: &SyntaxNode) { } fn validate_numeric_name(name_ref: Option, errors: &mut Vec) { - if let Some(int_token) = int_token(name_ref) { - if int_token.text().chars().any(|c| !c.is_ascii_digit()) { - errors.push(SyntaxError::new( - "Tuple (struct) field access is only allowed through \ + if let Some(int_token) = int_token(name_ref) + && int_token.text().chars().any(|c| !c.is_ascii_digit()) + { + errors.push(SyntaxError::new( + "Tuple (struct) field access is only allowed through \ decimal integers with no underscores or suffix", - int_token.text_range(), - )); - } + int_token.text_range(), + )); } fn int_token(name_ref: Option) -> Option { @@ -285,13 +285,13 @@ fn validate_path_keywords(segment: ast::PathSegment, errors: &mut Vec Option { diff --git a/src/tools/rust-analyzer/crates/test-fixture/src/lib.rs b/src/tools/rust-analyzer/crates/test-fixture/src/lib.rs index 8937e53175ab..4413d2f222c1 100644 --- a/src/tools/rust-analyzer/crates/test-fixture/src/lib.rs +++ b/src/tools/rust-analyzer/crates/test-fixture/src/lib.rs @@ -955,12 +955,12 @@ impl ProcMacroExpander for DisallowCfgProcMacroExpander { _: String, ) -> Result { for tt in subtree.token_trees().flat_tokens() { - if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = tt { - if ident.sym == sym::cfg || ident.sym == sym::cfg_attr { - return Err(ProcMacroExpansionError::Panic( - "cfg or cfg_attr found in DisallowCfgProcMacroExpander".to_owned(), - )); - } + if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = tt + && (ident.sym == sym::cfg || ident.sym == sym::cfg_attr) + { + return Err(ProcMacroExpansionError::Panic( + "cfg or cfg_attr found in DisallowCfgProcMacroExpander".to_owned(), + )); } } Ok(subtree.clone()) diff --git a/src/tools/rust-analyzer/crates/tt/src/lib.rs b/src/tools/rust-analyzer/crates/tt/src/lib.rs index 44123385c8cc..243a27b83b0d 100644 --- a/src/tools/rust-analyzer/crates/tt/src/lib.rs +++ b/src/tools/rust-analyzer/crates/tt/src/lib.rs @@ -357,10 +357,10 @@ impl<'a, S: Copy> TokenTreesView<'a, S> { } pub fn try_into_subtree(self) -> Option> { - if let Some(TokenTree::Subtree(subtree)) = self.0.first() { - if subtree.usize_len() == (self.0.len() - 1) { - return Some(SubtreeView::new(self.0)); - } + if let Some(TokenTree::Subtree(subtree)) = self.0.first() + && subtree.usize_len() == (self.0.len() - 1) + { + return Some(SubtreeView::new(self.0)); } None } @@ -1028,10 +1028,10 @@ pub fn pretty(mut tkns: &[TokenTree]) -> String { tkns = rest; last = [last, tokentree_to_text(tkn, &mut tkns)].join(if last_to_joint { "" } else { " " }); last_to_joint = false; - if let TokenTree::Leaf(Leaf::Punct(punct)) = tkn { - if punct.spacing == Spacing::Joint { - last_to_joint = true; - } + if let TokenTree::Leaf(Leaf::Punct(punct)) = tkn + && punct.spacing == Spacing::Joint + { + last_to_joint = true; } } last diff --git a/src/tools/rust-analyzer/crates/vfs-notify/src/lib.rs b/src/tools/rust-analyzer/crates/vfs-notify/src/lib.rs index a03337dbc51e..c6393cc6922a 100644 --- a/src/tools/rust-analyzer/crates/vfs-notify/src/lib.rs +++ b/src/tools/rust-analyzer/crates/vfs-notify/src/lib.rs @@ -194,52 +194,49 @@ impl NotifyActor { } }, Event::NotifyEvent(event) => { - if let Some(event) = log_notify_error(event) { - if let EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) = + if let Some(event) = log_notify_error(event) + && let EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) = event.kind - { - let files = event - .paths - .into_iter() - .filter_map(|path| { - Some( - AbsPathBuf::try_from( - Utf8PathBuf::from_path_buf(path).ok()?, - ) + { + let files = event + .paths + .into_iter() + .filter_map(|path| { + Some( + AbsPathBuf::try_from(Utf8PathBuf::from_path_buf(path).ok()?) .expect("path is absolute"), - ) - }) - .filter_map(|path| -> Option<(AbsPathBuf, Option>)> { - let meta = fs::metadata(&path).ok()?; - if meta.file_type().is_dir() - && self - .watched_dir_entries - .iter() - .any(|dir| dir.contains_dir(&path)) - { - self.watch(path.as_ref()); - return None; - } - - if !meta.file_type().is_file() { - return None; - } - - if !(self.watched_file_entries.contains(&path) - || self - .watched_dir_entries - .iter() - .any(|dir| dir.contains_file(&path))) - { - return None; - } - - let contents = read(&path); - Some((path, contents)) - }) - .collect(); - self.send(loader::Message::Changed { files }); - } + ) + }) + .filter_map(|path| -> Option<(AbsPathBuf, Option>)> { + let meta = fs::metadata(&path).ok()?; + if meta.file_type().is_dir() + && self + .watched_dir_entries + .iter() + .any(|dir| dir.contains_dir(&path)) + { + self.watch(path.as_ref()); + return None; + } + + if !meta.file_type().is_file() { + return None; + } + + if !(self.watched_file_entries.contains(&path) + || self + .watched_dir_entries + .iter() + .any(|dir| dir.contains_file(&path))) + { + return None; + } + + let contents = read(&path); + Some((path, contents)) + }) + .collect(); + self.send(loader::Message::Changed { files }); } } } diff --git a/src/tools/rust-analyzer/xtask/src/codegen.rs b/src/tools/rust-analyzer/xtask/src/codegen.rs index 19ca62e8a329..bc7eb88f3a84 100644 --- a/src/tools/rust-analyzer/xtask/src/codegen.rs +++ b/src/tools/rust-analyzer/xtask/src/codegen.rs @@ -173,11 +173,11 @@ fn add_preamble(cg: CodegenType, mut text: String) -> String { #[allow(clippy::print_stderr)] fn ensure_file_contents(cg: CodegenType, file: &Path, contents: &str, check: bool) -> bool { let contents = normalize_newlines(contents); - if let Ok(old_contents) = fs::read_to_string(file) { - if normalize_newlines(&old_contents) == contents { - // File is already up to date. - return false; - } + if let Ok(old_contents) = fs::read_to_string(file) + && normalize_newlines(&old_contents) == contents + { + // File is already up to date. + return false; } let display_path = file.strip_prefix(project_root()).unwrap_or(file); diff --git a/src/tools/rust-analyzer/xtask/src/publish/notes.rs b/src/tools/rust-analyzer/xtask/src/publish/notes.rs index 93592d4986f8..8d36fcb61b44 100644 --- a/src/tools/rust-analyzer/xtask/src/publish/notes.rs +++ b/src/tools/rust-analyzer/xtask/src/publish/notes.rs @@ -72,13 +72,13 @@ impl<'a, 'b, R: BufRead> Converter<'a, 'b, R> { } fn process_document_title(&mut self) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if let Some((level, title)) = get_title(&line) { - let title = process_inline_macros(title)?; - if level == 1 { - self.write_title(level, &title); - return Ok(()); - } + if let Some(Ok(line)) = self.iter.next() + && let Some((level, title)) = get_title(&line) + { + let title = process_inline_macros(title)?; + if level == 1 { + self.write_title(level, &title); + return Ok(()); } } bail!("document title not found") @@ -141,39 +141,39 @@ impl<'a, 'b, R: BufRead> Converter<'a, 'b, R> { } fn process_source_code_block(&mut self, level: usize) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if let Some(styles) = line.strip_prefix("[source").and_then(|s| s.strip_suffix(']')) { - let mut styles = styles.split(','); - if !styles.next().unwrap().is_empty() { - bail!("not a source code block"); - } - let language = styles.next(); - return self.process_listing_block(language, level); + if let Some(Ok(line)) = self.iter.next() + && let Some(styles) = line.strip_prefix("[source").and_then(|s| s.strip_suffix(']')) + { + let mut styles = styles.split(','); + if !styles.next().unwrap().is_empty() { + bail!("not a source code block"); } + let language = styles.next(); + return self.process_listing_block(language, level); } bail!("not a source code block") } fn process_listing_block(&mut self, style: Option<&str>, level: usize) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if line == LISTING_DELIMITER { - self.write_indent(level); - self.output.push_str("```"); - if let Some(style) = style { - self.output.push_str(style); - } - self.output.push('\n'); - while let Some(line) = self.iter.next() { - let line = line?; - if line == LISTING_DELIMITER { - self.write_line("```", level); - return Ok(()); - } else { - self.write_line(&line, level); - } + if let Some(Ok(line)) = self.iter.next() + && line == LISTING_DELIMITER + { + self.write_indent(level); + self.output.push_str("```"); + if let Some(style) = style { + self.output.push_str(style); + } + self.output.push('\n'); + while let Some(line) = self.iter.next() { + let line = line?; + if line == LISTING_DELIMITER { + self.write_line("```", level); + return Ok(()); + } else { + self.write_line(&line, level); } - bail!("listing block is not terminated") } + bail!("listing block is not terminated") } bail!("not a listing block") } @@ -200,49 +200,48 @@ impl<'a, 'b, R: BufRead> Converter<'a, 'b, R> { } fn process_image_block(&mut self, caption: Option<&str>, level: usize) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if let Some((url, attrs)) = parse_media_block(&line, IMAGE_BLOCK_PREFIX) { - let alt = if let Some(stripped) = - attrs.strip_prefix('"').and_then(|s| s.strip_suffix('"')) - { + if let Some(Ok(line)) = self.iter.next() + && let Some((url, attrs)) = parse_media_block(&line, IMAGE_BLOCK_PREFIX) + { + let alt = + if let Some(stripped) = attrs.strip_prefix('"').and_then(|s| s.strip_suffix('"')) { stripped } else { attrs }; - if let Some(caption) = caption { - self.write_caption_line(caption, level); - } - self.write_indent(level); - self.output.push_str("!["); - self.output.push_str(alt); - self.output.push_str("]("); - self.output.push_str(url); - self.output.push_str(")\n"); - return Ok(()); + if let Some(caption) = caption { + self.write_caption_line(caption, level); } + self.write_indent(level); + self.output.push_str("!["); + self.output.push_str(alt); + self.output.push_str("]("); + self.output.push_str(url); + self.output.push_str(")\n"); + return Ok(()); } bail!("not a image block") } fn process_video_block(&mut self, caption: Option<&str>, level: usize) -> anyhow::Result<()> { - if let Some(Ok(line)) = self.iter.next() { - if let Some((url, attrs)) = parse_media_block(&line, VIDEO_BLOCK_PREFIX) { - let html_attrs = match attrs { - "options=loop" => "controls loop", - r#"options="autoplay,loop""# => "autoplay controls loop", - _ => bail!("unsupported video syntax"), - }; - if let Some(caption) = caption { - self.write_caption_line(caption, level); - } - self.write_indent(level); - self.output.push_str(r#"\n"); - return Ok(()); + if let Some(Ok(line)) = self.iter.next() + && let Some((url, attrs)) = parse_media_block(&line, VIDEO_BLOCK_PREFIX) + { + let html_attrs = match attrs { + "options=loop" => "controls loop", + r#"options="autoplay,loop""# => "autoplay controls loop", + _ => bail!("unsupported video syntax"), + }; + if let Some(caption) = caption { + self.write_caption_line(caption, level); } + self.write_indent(level); + self.output.push_str(r#"\n"); + return Ok(()); } bail!("not a video block") } @@ -371,12 +370,11 @@ fn strip_prefix_symbol(line: &str, symbol: char) -> Option<(usize, &str)> { } fn parse_media_block<'a>(line: &'a str, prefix: &str) -> Option<(&'a str, &'a str)> { - if let Some(line) = line.strip_prefix(prefix) { - if let Some((url, rest)) = line.split_once('[') { - if let Some(attrs) = rest.strip_suffix(']') { - return Some((url, attrs)); - } - } + if let Some(line) = line.strip_prefix(prefix) + && let Some((url, rest)) = line.split_once('[') + && let Some(attrs) = rest.strip_suffix(']') + { + return Some((url, attrs)); } None } From 94cc5bb9620cdee942b8b79e7026f622fcc695a0 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 14:29:28 +1000 Subject: [PATCH 0240/1134] Streamline const folding/visiting. Type folders can only modify a few "types of interest": `Binder`, `Ty`, `Predicate`, `Clauses`, `Region`, `Const`. Likewise for type visitors, but they can also visit errors (via `ErrorGuaranteed`). Currently the impls of `try_super_fold_with`, `super_fold_with`, and `super_visit_with` do more than they need to -- they fold/visit values that cannot contain any types of interest. This commit removes those unnecessary fold/visit operations, which makes these impls more similar to the impls for `Ty`. It also removes the now-unnecessary derived impls for the no-longer-visited types. --- .../rustc_middle/src/ty/structural_impls.rs | 46 ++++++++----------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index a5fdce93e4b2..10e499d9c758 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -232,6 +232,7 @@ TrivialLiftImpls! { crate::mir::Promoted, crate::mir::interpret::AllocId, crate::mir::interpret::Scalar, + crate::ty::ParamConst, rustc_abi::ExternAbi, rustc_abi::Size, rustc_hir::Safety, @@ -271,10 +272,6 @@ TrivialTypeTraversalImpls! { crate::ty::AssocItem, crate::ty::AssocKind, crate::ty::BoundRegion, - crate::ty::BoundVar, - crate::ty::InferConst, - crate::ty::Placeholder, - crate::ty::Placeholder, crate::ty::UserTypeAnnotationIndex, crate::ty::ValTree<'tcx>, crate::ty::abstract_const::NotConstEvaluatable, @@ -302,9 +299,8 @@ TrivialTypeTraversalImpls! { // interners). TrivialTypeTraversalAndLiftImpls! { // tidy-alphabetical-start - crate::ty::ParamConst, crate::ty::ParamTy, - crate::ty::Placeholder, + crate::ty::PlaceholderType, crate::ty::instance::ReifyReason, rustc_hir::def_id::DefId, // tidy-alphabetical-end @@ -673,30 +669,30 @@ impl<'tcx> TypeSuperFoldable> for ty::Const<'tcx> { folder: &mut F, ) -> Result { let kind = match self.kind() { - ConstKind::Param(p) => ConstKind::Param(p.try_fold_with(folder)?), - ConstKind::Infer(i) => ConstKind::Infer(i.try_fold_with(folder)?), - ConstKind::Bound(d, b) => { - ConstKind::Bound(d.try_fold_with(folder)?, b.try_fold_with(folder)?) - } - ConstKind::Placeholder(p) => ConstKind::Placeholder(p.try_fold_with(folder)?), ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.try_fold_with(folder)?), ConstKind::Value(v) => ConstKind::Value(v.try_fold_with(folder)?), - ConstKind::Error(e) => ConstKind::Error(e.try_fold_with(folder)?), ConstKind::Expr(e) => ConstKind::Expr(e.try_fold_with(folder)?), + + ConstKind::Param(_) + | ConstKind::Infer(_) + | ConstKind::Bound(..) + | ConstKind::Placeholder(_) + | ConstKind::Error(_) => return Ok(self), }; if kind != self.kind() { Ok(folder.cx().mk_ct_from_kind(kind)) } else { Ok(self) } } fn super_fold_with>>(self, folder: &mut F) -> Self { let kind = match self.kind() { - ConstKind::Param(p) => ConstKind::Param(p.fold_with(folder)), - ConstKind::Infer(i) => ConstKind::Infer(i.fold_with(folder)), - ConstKind::Bound(d, b) => ConstKind::Bound(d.fold_with(folder), b.fold_with(folder)), - ConstKind::Placeholder(p) => ConstKind::Placeholder(p.fold_with(folder)), ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.fold_with(folder)), ConstKind::Value(v) => ConstKind::Value(v.fold_with(folder)), - ConstKind::Error(e) => ConstKind::Error(e.fold_with(folder)), ConstKind::Expr(e) => ConstKind::Expr(e.fold_with(folder)), + + ConstKind::Param(_) + | ConstKind::Infer(_) + | ConstKind::Bound(..) + | ConstKind::Placeholder(_) + | ConstKind::Error(_) => return self, }; if kind != self.kind() { folder.cx().mk_ct_from_kind(kind) } else { self } } @@ -705,17 +701,15 @@ impl<'tcx> TypeSuperFoldable> for ty::Const<'tcx> { impl<'tcx> TypeSuperVisitable> for ty::Const<'tcx> { fn super_visit_with>>(&self, visitor: &mut V) -> V::Result { match self.kind() { - ConstKind::Param(p) => p.visit_with(visitor), - ConstKind::Infer(i) => i.visit_with(visitor), - ConstKind::Bound(d, b) => { - try_visit!(d.visit_with(visitor)); - b.visit_with(visitor) - } - ConstKind::Placeholder(p) => p.visit_with(visitor), ConstKind::Unevaluated(uv) => uv.visit_with(visitor), ConstKind::Value(v) => v.visit_with(visitor), - ConstKind::Error(e) => e.visit_with(visitor), ConstKind::Expr(e) => e.visit_with(visitor), + ConstKind::Error(e) => e.visit_with(visitor), + + ConstKind::Param(_) + | ConstKind::Infer(_) + | ConstKind::Bound(..) + | ConstKind::Placeholder(_) => V::Result::output(), } } } From 507dec4dc321c868ad876c0b7302c66088b7cc7c Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 14:21:00 +1000 Subject: [PATCH 0241/1134] Make const bound handling more like types/regions. Currently there is `Ty` and `BoundTy`, and `Region` and `BoundRegion`, and `Const` and... `BoundVar`. An annoying inconsistency. This commit repurposes the existing `BoundConst`, which was barely used, so it's the partner to `Const`. Unlike `BoundTy`/`BoundRegion` it lacks a `kind` field but it's still nice to have because it makes the const code more similar to the ty/region code everywhere. The commit also removes `impl From for BoundTy`, which has a single use and doesn't seem worth it. These changes fix the "FIXME: We really should have a separate `BoundConst` for consts". --- .../src/type_check/relate_tys.rs | 4 ++-- .../src/check/compare_impl_item.rs | 2 +- .../src/collect/item_bounds.rs | 10 ++++---- .../src/hir_ty_lowering/bounds.rs | 2 +- .../src/hir_ty_lowering/mod.rs | 8 ++++--- .../src/infer/canonical/canonicalizer.rs | 6 +++-- .../src/infer/canonical/instantiate.rs | 4 ++-- .../src/infer/canonical/query_response.rs | 6 ++--- compiler/rustc_infer/src/infer/mod.rs | 4 ++-- .../src/infer/relate/higher_ranked.rs | 4 ++-- compiler/rustc_middle/src/ty/consts.rs | 14 +++++++---- compiler/rustc_middle/src/ty/context.rs | 2 +- compiler/rustc_middle/src/ty/fold.rs | 24 ++++++++++++------- compiler/rustc_middle/src/ty/mod.rs | 23 ++++++++++++------ compiler/rustc_middle/src/ty/sty.rs | 6 ----- .../rustc_middle/src/ty/typeck_results.rs | 6 ++--- .../src/traits/coherence.rs | 5 +++- .../rustc_trait_selection/src/traits/mod.rs | 5 +++- .../rustc_trait_selection/src/traits/util.rs | 4 ++-- compiler/rustc_type_ir/src/inherent.rs | 2 +- compiler/rustc_type_ir/src/lib.rs | 10 -------- 21 files changed, 82 insertions(+), 69 deletions(-) diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index e023300f1c28..bb72d1d52f37 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -187,7 +187,7 @@ impl<'a, 'b, 'tcx> NllTypeRelating<'a, 'b, 'tcx> { types: &mut |_bound_ty: ty::BoundTy| { unreachable!("we only replace regions in nll_relate, not types") }, - consts: &mut |_bound_var: ty::BoundVar| { + consts: &mut |_bound_const: ty::BoundConst| { unreachable!("we only replace regions in nll_relate, not consts") }, }; @@ -226,7 +226,7 @@ impl<'a, 'b, 'tcx> NllTypeRelating<'a, 'b, 'tcx> { types: &mut |_bound_ty: ty::BoundTy| { unreachable!("we only replace regions in nll_relate, not types") }, - consts: &mut |_bound_var: ty::BoundVar| { + consts: &mut |_bound_const: ty::BoundConst| { unreachable!("we only replace regions in nll_relate, not consts") }, }; diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index e24426f9fedc..13d690054ce6 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -2498,7 +2498,7 @@ fn param_env_with_gat_bounds<'tcx>( ty::Const::new_bound( tcx, ty::INNERMOST, - ty::BoundVar::from_usize(bound_vars.len() - 1), + ty::BoundConst { var: ty::BoundVar::from_usize(bound_vars.len() - 1) }, ) .into() } diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 548ba343aaee..ba54fa8cc0db 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -189,7 +189,7 @@ fn remap_gat_vars_and_recurse_into_nested_projections<'tcx>( } ty::GenericArgKind::Const(ct) => { if let ty::ConstKind::Bound(ty::INNERMOST, bv) = ct.kind() { - mapping.insert(bv, tcx.mk_param_from_def(param)) + mapping.insert(bv.var, tcx.mk_param_from_def(param)) } else { return None; } @@ -307,16 +307,16 @@ impl<'tcx> TypeFolder> for MapAndCompressBoundVars<'tcx> { return ct; } - if let ty::ConstKind::Bound(binder, old_var) = ct.kind() + if let ty::ConstKind::Bound(binder, old_bound) = ct.kind() && self.binder == binder { - let mapped = if let Some(mapped) = self.mapping.get(&old_var) { + let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) { mapped.expect_const() } else { let var = ty::BoundVar::from_usize(self.still_bound_vars.len()); self.still_bound_vars.push(ty::BoundVariableKind::Const); - let mapped = ty::Const::new_bound(self.tcx, ty::INNERMOST, var); - self.mapping.insert(old_var, mapped.into()); + let mapped = ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst { var }); + self.mapping.insert(old_bound.var, mapped.into()); mapped }; diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index 7760642d8fb0..386e1091ac4e 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -1077,7 +1077,7 @@ impl<'tcx> TypeVisitor> for GenericParamAndBoundVarCollector<'_, 't ty::ConstKind::Param(param) => { self.params.insert(param.index); } - ty::ConstKind::Bound(db, ty::BoundVar { .. }) if db >= self.depth => { + ty::ConstKind::Bound(db, _) if db >= self.depth => { let guar = self.cx.dcx().delayed_bug("unexpected escaping late-bound const var"); return ControlFlow::Break(guar); } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index d76879983586..d93f3c5f5085 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -2107,9 +2107,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let name = tcx.item_name(param_def_id); ty::Const::new_param(tcx, ty::ParamConst::new(index, name)) } - Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => { - ty::Const::new_bound(tcx, debruijn, ty::BoundVar::from_u32(index)) - } + Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound( + tcx, + debruijn, + ty::BoundConst { var: ty::BoundVar::from_u32(index) }, + ), Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar), arg => bug!("unexpected bound var resolution for {:?}: {arg:?}", path_hir_id), } diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index 060447ba7206..a4c6d078125d 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -752,7 +752,8 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> { ) -> Ty<'tcx> { debug_assert!(!self.infcx.is_some_and(|infcx| ty_var != infcx.shallow_resolve(ty_var))); let var = self.canonical_var(var_kind, ty_var.into()); - Ty::new_bound(self.tcx, self.binder_index, var.into()) + let bt = ty::BoundTy { var, kind: ty::BoundTyKind::Anon }; + Ty::new_bound(self.tcx, self.binder_index, bt) } /// Given a type variable `const_var` of the given kind, first check @@ -768,6 +769,7 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> { !self.infcx.is_some_and(|infcx| ct_var != infcx.shallow_resolve_const(ct_var)) ); let var = self.canonical_var(var_kind, ct_var.into()); - ty::Const::new_bound(self.tcx, self.binder_index, var) + let bc = ty::BoundConst { var }; + ty::Const::new_bound(self.tcx, self.binder_index, bc) } } diff --git a/compiler/rustc_infer/src/infer/canonical/instantiate.rs b/compiler/rustc_infer/src/infer/canonical/instantiate.rs index 2385c68ef6bb..cc052fbd85c1 100644 --- a/compiler/rustc_infer/src/infer/canonical/instantiate.rs +++ b/compiler/rustc_infer/src/infer/canonical/instantiate.rs @@ -133,7 +133,7 @@ impl<'tcx> TypeFolder> for CanonicalInstantiator<'tcx> { fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { match ct.kind() { ty::ConstKind::Bound(debruijn, bound_const) if debruijn == self.current_index => { - self.var_values[bound_const.as_usize()].expect_const() + self.var_values[bound_const.var.as_usize()].expect_const() } _ => ct.super_fold_with(self), } @@ -217,7 +217,7 @@ fn highest_var_in_clauses<'tcx>(c: ty::Clauses<'tcx>) -> usize { if let ty::ConstKind::Bound(debruijn, bound_const) = ct.kind() && debruijn == self.current_index { - self.max_var = self.max_var.max(bound_const.as_usize()); + self.max_var = self.max_var.max(bound_const.var.as_usize()); } else if ct.has_vars_bound_at_or_above(self.current_index) { ct.super_visit_with(self); } diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 6be53c948c84..73b1ca6c6913 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -433,12 +433,12 @@ impl<'tcx> InferCtxt<'tcx> { } GenericArgKind::Lifetime(result_value) => { // e.g., here `result_value` might be `'?1` in the example above... - if let ty::ReBound(debruijn, br) = result_value.kind() { + if let ty::ReBound(debruijn, b) = result_value.kind() { // ... in which case we would set `canonical_vars[0]` to `Some('static)`. // We only allow a `ty::INNERMOST` index in generic parameters. assert_eq!(debruijn, ty::INNERMOST); - opt_values[br.var] = Some(*original_value); + opt_values[b.var] = Some(*original_value); } } GenericArgKind::Const(result_value) => { @@ -447,7 +447,7 @@ impl<'tcx> InferCtxt<'tcx> { // We only allow a `ty::INNERMOST` index in generic parameters. assert_eq!(debruijn, ty::INNERMOST); - opt_values[b] = Some(*original_value); + opt_values[b.var] = Some(*original_value); } } } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 2d269e320b64..41297e8ffca1 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -1208,8 +1208,8 @@ impl<'tcx> InferCtxt<'tcx> { fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> { self.args[bt.var.index()].expect_ty() } - fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx> { - self.args[bv.index()].expect_const() + fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> { + self.args[bc.var.index()].expect_const() } } let delegate = ToFreshVars { args }; diff --git a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs index 2143f72a3b0a..16fe591b29bb 100644 --- a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs +++ b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs @@ -45,10 +45,10 @@ impl<'tcx> InferCtxt<'tcx> { ty::PlaceholderType { universe: next_universe, bound: bound_ty }, ) }, - consts: &mut |bound_var: ty::BoundVar| { + consts: &mut |bound_const: ty::BoundConst| { ty::Const::new_placeholder( self.tcx, - ty::PlaceholderConst { universe: next_universe, bound: bound_var }, + ty::PlaceholderConst { universe: next_universe, bound: bound_const }, ) }, }; diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index fd1aa4042bcf..614b6471f188 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -93,9 +93,9 @@ impl<'tcx> Const<'tcx> { pub fn new_bound( tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, - var: ty::BoundVar, + bound_const: ty::BoundConst, ) -> Const<'tcx> { - Const::new(tcx, ty::ConstKind::Bound(debruijn, var)) + Const::new(tcx, ty::ConstKind::Bound(debruijn, bound_const)) } #[inline] @@ -168,12 +168,16 @@ impl<'tcx> rustc_type_ir::inherent::Const> for Const<'tcx> { Const::new_var(tcx, vid) } - fn new_bound(interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self { - Const::new_bound(interner, debruijn, var) + fn new_bound( + interner: TyCtxt<'tcx>, + debruijn: ty::DebruijnIndex, + bound_const: ty::BoundConst, + ) -> Self { + Const::new_bound(interner, debruijn, bound_const) } fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self { - Const::new_bound(tcx, debruijn, var) + Const::new_bound(tcx, debruijn, ty::BoundConst { var }) } fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderConst) -> Self { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 6f21160d1f66..466b3f191c06 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -152,7 +152,7 @@ impl<'tcx> Interner for TyCtxt<'tcx> { type PlaceholderConst = ty::PlaceholderConst; type ParamConst = ty::ParamConst; - type BoundConst = ty::BoundVar; + type BoundConst = ty::BoundConst; type ValueConst = ty::Value<'tcx>; type ExprConst = ty::Expr<'tcx>; type ValTree = ty::ValTree<'tcx>; diff --git a/compiler/rustc_middle/src/ty/fold.rs b/compiler/rustc_middle/src/ty/fold.rs index b2057fa36d7f..7d56ec1635f8 100644 --- a/compiler/rustc_middle/src/ty/fold.rs +++ b/compiler/rustc_middle/src/ty/fold.rs @@ -3,7 +3,7 @@ use rustc_hir::def_id::DefId; use rustc_type_ir::data_structures::DelayedMap; use crate::ty::{ - self, Binder, BoundTy, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, + self, Binder, BoundConst, BoundTy, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, }; @@ -60,7 +60,7 @@ where pub trait BoundVarReplacerDelegate<'tcx> { fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx>; fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx>; - fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx>; + fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx>; } /// A simple delegate taking 3 mutable functions. The used functions must @@ -69,7 +69,7 @@ pub trait BoundVarReplacerDelegate<'tcx> { pub struct FnMutDelegate<'a, 'tcx> { pub regions: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a), pub types: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a), - pub consts: &'a mut (dyn FnMut(ty::BoundVar) -> ty::Const<'tcx> + 'a), + pub consts: &'a mut (dyn FnMut(ty::BoundConst) -> ty::Const<'tcx> + 'a), } impl<'a, 'tcx> BoundVarReplacerDelegate<'tcx> for FnMutDelegate<'a, 'tcx> { @@ -79,8 +79,8 @@ impl<'a, 'tcx> BoundVarReplacerDelegate<'tcx> for FnMutDelegate<'a, 'tcx> { fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> { (self.types)(bt) } - fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx> { - (self.consts)(bv) + fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> { + (self.consts)(bc) } } @@ -300,7 +300,13 @@ impl<'tcx> TyCtxt<'tcx> { ty::BoundTy { var: shift_bv(t.var), kind: t.kind }, ) }, - consts: &mut |c| ty::Const::new_bound(self, ty::INNERMOST, shift_bv(c)), + consts: &mut |c| { + ty::Const::new_bound( + self, + ty::INNERMOST, + ty::BoundConst { var: shift_bv(c.var) }, + ) + }, }, ) } @@ -343,12 +349,12 @@ impl<'tcx> TyCtxt<'tcx> { .expect_ty(); Ty::new_bound(self.tcx, ty::INNERMOST, BoundTy { var, kind }) } - fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx> { - let entry = self.map.entry(bv); + fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> { + let entry = self.map.entry(bc.var); let index = entry.index(); let var = ty::BoundVar::from_usize(index); let () = entry.or_insert_with(|| ty::BoundVariableKind::Const).expect_const(); - ty::Const::new_bound(self.tcx, ty::INNERMOST, var) + ty::Const::new_bound(self.tcx, ty::INNERMOST, BoundConst { var }) } } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index bb70c61cd141..fab020547ad3 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -968,34 +968,43 @@ impl<'tcx> rustc_type_ir::inherent::PlaceholderLike> for Placeholde #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)] #[derive(TyEncodable, TyDecodable)] -pub struct BoundConst<'tcx> { +pub struct BoundConst { pub var: BoundVar, - pub ty: Ty<'tcx>, } -pub type PlaceholderConst = Placeholder; +impl<'tcx> rustc_type_ir::inherent::BoundVarLike> for BoundConst { + fn var(self) -> BoundVar { + self.var + } + + fn assert_eq(self, _var: ty::BoundVariableKind) { + unreachable!() + } +} + +pub type PlaceholderConst = Placeholder; impl<'tcx> rustc_type_ir::inherent::PlaceholderLike> for PlaceholderConst { - type Bound = BoundVar; + type Bound = BoundConst; fn universe(self) -> UniverseIndex { self.universe } fn var(self) -> BoundVar { - self.bound + self.bound.var } fn with_updated_universe(self, ui: UniverseIndex) -> Self { Placeholder { universe: ui, ..self } } - fn new(ui: UniverseIndex, bound: BoundVar) -> Self { + fn new(ui: UniverseIndex, bound: BoundConst) -> Self { Placeholder { universe: ui, bound } } fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self { - Placeholder { universe: ui, bound: var } + Placeholder { universe: ui, bound: BoundConst { var } } } } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 4569596cfbe8..ea84ea3af428 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -403,12 +403,6 @@ pub enum BoundTyKind { Param(DefId), } -impl From for BoundTy { - fn from(var: BoundVar) -> Self { - BoundTy { var, kind: BoundTyKind::Anon } - } -} - /// Constructors for `Ty` impl<'tcx> Ty<'tcx> { /// Avoid using this in favour of more specific `new_*` methods, where possible. diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 88583407d25d..6b187c5325a9 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -789,10 +789,10 @@ impl<'tcx> IsIdentity for CanonicalUserType<'tcx> { }, GenericArgKind::Lifetime(r) => match r.kind() { - ty::ReBound(debruijn, br) => { + ty::ReBound(debruijn, b) => { // We only allow a `ty::INNERMOST` index in generic parameters. assert_eq!(debruijn, ty::INNERMOST); - cvar == br.var + cvar == b.var } _ => false, }, @@ -801,7 +801,7 @@ impl<'tcx> IsIdentity for CanonicalUserType<'tcx> { ty::ConstKind::Bound(debruijn, b) => { // We only allow a `ty::INNERMOST` index in generic parameters. assert_eq!(debruijn, ty::INNERMOST); - cvar == b + cvar == b.var } _ => false, }, diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 07e78da37b3b..d8aedf5c2bf3 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -535,7 +535,10 @@ fn plug_infer_with_placeholders<'tcx>( ct, ty::Const::new_placeholder( self.infcx.tcx, - ty::Placeholder { universe: self.universe, bound: self.next_var() }, + ty::Placeholder { + universe: self.universe, + bound: ty::BoundConst { var: self.next_var() }, + }, ), ) else { diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 9b5e59ce0fdb..08315dbd21fb 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -706,7 +706,10 @@ fn replace_param_and_infer_args_with_placeholder<'tcx>( self.idx += 1; ty::Const::new_placeholder( self.tcx, - ty::PlaceholderConst { universe: ty::UniverseIndex::ROOT, bound: idx }, + ty::PlaceholderConst { + universe: ty::UniverseIndex::ROOT, + bound: ty::BoundConst { var: idx }, + }, ) } else { c.super_fold_with(self) diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index c3d60ec45c46..83c0969762f4 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -222,7 +222,7 @@ pub struct PlaceholderReplacer<'a, 'tcx> { infcx: &'a InferCtxt<'tcx>, mapped_regions: FxIndexMap, mapped_types: FxIndexMap, - mapped_consts: FxIndexMap, + mapped_consts: FxIndexMap, universe_indices: &'a [Option], current_index: ty::DebruijnIndex, } @@ -232,7 +232,7 @@ impl<'a, 'tcx> PlaceholderReplacer<'a, 'tcx> { infcx: &'a InferCtxt<'tcx>, mapped_regions: FxIndexMap, mapped_types: FxIndexMap, - mapped_consts: FxIndexMap, + mapped_consts: FxIndexMap, universe_indices: &'a [Option], value: T, ) -> T { diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index 0e307e15d5b4..1a6c99ce7dec 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -251,7 +251,7 @@ pub trait Const>: fn new_var(interner: I, var: ty::ConstVid) -> Self; - fn new_bound(interner: I, debruijn: ty::DebruijnIndex, var: I::BoundConst) -> Self; + fn new_bound(interner: I, debruijn: ty::DebruijnIndex, bound_const: I::BoundConst) -> Self; fn new_anon_bound(interner: I, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self; diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index a483c18813b0..5c9cac5b21b1 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -387,16 +387,6 @@ rustc_index::newtype_index! { pub struct BoundVar {} } -impl inherent::BoundVarLike for BoundVar { - fn var(self) -> BoundVar { - self - } - - fn assert_eq(self, _var: I::BoundVarKind) { - unreachable!("FIXME: We really should have a separate `BoundConst` for consts") - } -} - /// Represents the various closure traits in the language. This /// will determine the type of the environment (`self`, in the /// desugaring) argument that the closure expects. From 64be8bb599d3efa12235e266177c828ad97373e6 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 19:04:03 +1000 Subject: [PATCH 0242/1134] Check consts in `ValidateBoundVars`. Alongside the existing type and region checking. --- compiler/rustc_middle/src/ty/mod.rs | 4 ++-- compiler/rustc_type_ir/src/binder.rs | 23 +++++++++++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index fab020547ad3..342f59874661 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -977,8 +977,8 @@ impl<'tcx> rustc_type_ir::inherent::BoundVarLike> for BoundConst { self.var } - fn assert_eq(self, _var: ty::BoundVariableKind) { - unreachable!() + fn assert_eq(self, var: ty::BoundVariableKind) { + var.expect_const() } } diff --git a/compiler/rustc_type_ir/src/binder.rs b/compiler/rustc_type_ir/src/binder.rs index a7b915c48455..fb0dfe95b738 100644 --- a/compiler/rustc_type_ir/src/binder.rs +++ b/compiler/rustc_type_ir/src/binder.rs @@ -274,8 +274,9 @@ impl Binder { pub struct ValidateBoundVars { bound_vars: I::BoundVarKinds, binder_index: ty::DebruijnIndex, - // We may encounter the same variable at different levels of binding, so - // this can't just be `Ty` + // We only cache types because any complex const will have to step through + // a type at some point anyways. We may encounter the same variable at + // different levels of binding, so this can't just be `Ty`. visited: SsoHashSet<(ty::DebruijnIndex, I::Ty)>, } @@ -319,6 +320,24 @@ impl TypeVisitor for ValidateBoundVars { t.super_visit_with(self) } + fn visit_const(&mut self, c: I::Const) -> Self::Result { + if c.outer_exclusive_binder() < self.binder_index { + return ControlFlow::Break(()); + } + match c.kind() { + ty::ConstKind::Bound(debruijn, bound_const) if debruijn == self.binder_index => { + let idx = bound_const.var().as_usize(); + if self.bound_vars.len() <= idx { + panic!("Not enough bound vars: {:?} not found in {:?}", c, self.bound_vars); + } + bound_const.assert_eq(self.bound_vars.get(idx).unwrap()); + } + _ => {} + }; + + c.super_visit_with(self) + } + fn visit_region(&mut self, r: I::Region) -> Self::Result { match r.kind() { ty::ReBound(index, br) if index == self.binder_index => { From 618a90d1b0682f687b63cc591ef78814538d5a8f Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 11:52:42 +1000 Subject: [PATCH 0243/1134] Deduplicate `IntTy`/`UintTy`/`FloatTy`. There are identical definitions in `rustc_type_ir` and `rustc_ast`. This commit removes them and places a single definition in `rustc_ast_ir`. This requires adding `rust_span` as a dependency of `rustc_ast_ir`, but means a bunch of silly conversion functions can be removed. The one annoying wrinkle is that the old version had differences in their `Debug` impls, e.g. one printed `u32` while the other printed `U32`. Some compiler error messages rely on the former (yuk), and some clippy output depends on the latter. So the commit also changes clippy to not rely on `Debug` and just implement what it needs itself. --- clippy_lints/src/float_literal.rs | 10 ++++----- clippy_lints/src/utils/author.rs | 35 ++++++++++++++++++++++++++++--- clippy_utils/src/consts.rs | 10 ++++----- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/clippy_lints/src/float_literal.rs b/clippy_lints/src/float_literal.rs index c51267567d01..ccaf38aee4d8 100644 --- a/clippy_lints/src/float_literal.rs +++ b/clippy_lints/src/float_literal.rs @@ -1,6 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::numeric_literal; -use rustc_ast::ast::{self, LitFloatType, LitKind}; +use rustc_ast::ast::{LitFloatType, LitKind}; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; @@ -75,10 +75,10 @@ impl<'tcx> LateLintPass<'tcx> for FloatLiteral { let digits = count_digits(sym_str); let max = max_digits(fty); let type_suffix = match lit_float_ty { - LitFloatType::Suffixed(ast::FloatTy::F16) => Some("f16"), - LitFloatType::Suffixed(ast::FloatTy::F32) => Some("f32"), - LitFloatType::Suffixed(ast::FloatTy::F64) => Some("f64"), - LitFloatType::Suffixed(ast::FloatTy::F128) => Some("f128"), + LitFloatType::Suffixed(FloatTy::F16) => Some("f16"), + LitFloatType::Suffixed(FloatTy::F32) => Some("f32"), + LitFloatType::Suffixed(FloatTy::F64) => Some("f64"), + LitFloatType::Suffixed(FloatTy::F128) => Some("f128"), LitFloatType::Unsuffixed => None, }; let (is_whole, is_inf, mut float_str) = match fty { diff --git a/clippy_lints/src/utils/author.rs b/clippy_lints/src/utils/author.rs index ac92ab5a245c..299317384122 100644 --- a/clippy_lints/src/utils/author.rs +++ b/clippy_lints/src/utils/author.rs @@ -9,6 +9,7 @@ use rustc_hir::{ FnRetTy, HirId, Lit, PatExprKind, PatKind, QPath, StmtKind, StructTailExpr, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_middle::ty::{FloatTy, IntTy, UintTy}; use rustc_session::declare_lint_pass; use rustc_span::symbol::{Ident, Symbol}; use std::cell::Cell; @@ -337,15 +338,43 @@ impl<'a, 'tcx> PrintVisitor<'a, 'tcx> { LitKind::Byte(b) => kind!("Byte({b})"), LitKind::Int(i, suffix) => { let int_ty = match suffix { - LitIntType::Signed(int_ty) => format!("LitIntType::Signed(IntTy::{int_ty:?})"), - LitIntType::Unsigned(uint_ty) => format!("LitIntType::Unsigned(UintTy::{uint_ty:?})"), + LitIntType::Signed(int_ty) => { + let t = match int_ty { + IntTy::Isize => "Isize", + IntTy::I8 => "I8", + IntTy::I16 => "I16", + IntTy::I32 => "I32", + IntTy::I64 => "I64", + IntTy::I128 => "I128", + }; + format!("LitIntType::Signed(IntTy::{t})") + } + LitIntType::Unsigned(uint_ty) => { + let t = match uint_ty { + UintTy::Usize => "Usize", + UintTy::U8 => "U8", + UintTy::U16 => "U16", + UintTy::U32 => "U32", + UintTy::U64 => "U64", + UintTy::U128 => "U128", + }; + format!("LitIntType::Unsigned(UintTy::{t})") + } LitIntType::Unsuffixed => String::from("LitIntType::Unsuffixed"), }; kind!("Int({i}, {int_ty})"); }, LitKind::Float(_, suffix) => { let float_ty = match suffix { - LitFloatType::Suffixed(suffix_ty) => format!("LitFloatType::Suffixed(FloatTy::{suffix_ty:?})"), + LitFloatType::Suffixed(suffix_ty) => { + let t = match suffix_ty { + FloatTy::F16 => "F16", + FloatTy::F32 => "F32", + FloatTy::F64 => "F64", + FloatTy::F128 => "F128", + }; + format!("LitFloatType::Suffixed(FloatTy::{t})") + } LitFloatType::Unsuffixed => String::from("LitFloatType::Unsuffixed"), }; kind!("Float(_, {float_ty})"); diff --git a/clippy_utils/src/consts.rs b/clippy_utils/src/consts.rs index 25afa12e95d6..ecd88daa6b39 100644 --- a/clippy_utils/src/consts.rs +++ b/clippy_utils/src/consts.rs @@ -10,7 +10,7 @@ use crate::{clip, is_direct_expn_of, sext, unsext}; use rustc_abi::Size; use rustc_apfloat::Float; use rustc_apfloat::ieee::{Half, Quad}; -use rustc_ast::ast::{self, LitFloatType, LitKind}; +use rustc_ast::ast::{LitFloatType, LitKind}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{ BinOpKind, Block, ConstBlock, Expr, ExprKind, HirId, Item, ItemKind, Node, PatExpr, PatExprKind, QPath, UnOp, @@ -309,10 +309,10 @@ pub fn lit_to_mir_constant<'tcx>(lit: &LitKind, ty: Option>) -> Constan LitKind::Int(n, _) => Constant::Int(n.get()), LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty { // FIXME(f16_f128): just use `parse()` directly when available for `f16`/`f128` - ast::FloatTy::F16 => Constant::parse_f16(is.as_str()), - ast::FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()), - ast::FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()), - ast::FloatTy::F128 => Constant::parse_f128(is.as_str()), + FloatTy::F16 => Constant::parse_f16(is.as_str()), + FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()), + FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()), + FloatTy::F128 => Constant::parse_f128(is.as_str()), }, LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind() { ty::Float(FloatTy::F16) => Constant::parse_f16(is.as_str()), From 05e3a7a4997157e31b05f61f0a094e75574b025c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 31 Jul 2025 11:00:40 +0200 Subject: [PATCH 0244/1134] remove rustc_attr_data_structures --- clippy_lints/src/approx_const.rs | 2 +- clippy_lints/src/arbitrary_source_item_ordering.rs | 2 +- clippy_lints/src/attrs/inline_always.rs | 3 ++- clippy_lints/src/attrs/repr_attributes.rs | 3 ++- clippy_lints/src/booleans.rs | 2 +- clippy_lints/src/default_union_representation.rs | 3 ++- clippy_lints/src/doc/suspicious_doc_comments.rs | 2 +- clippy_lints/src/doc/too_long_first_doc_paragraph.rs | 2 +- clippy_lints/src/eta_reduction.rs | 3 ++- clippy_lints/src/exhaustive_items.rs | 3 ++- clippy_lints/src/format_args.rs | 3 ++- clippy_lints/src/functions/must_use.rs | 3 ++- clippy_lints/src/incompatible_msrv.rs | 2 +- clippy_lints/src/inline_fn_without_body.rs | 3 ++- clippy_lints/src/lib.rs | 1 - clippy_lints/src/macro_use.rs | 3 ++- clippy_lints/src/manual_non_exhaustive.rs | 3 ++- clippy_lints/src/missing_inline.rs | 3 ++- clippy_lints/src/no_mangle_with_rust_abi.rs | 2 +- clippy_lints/src/pass_by_ref_or_value.rs | 3 ++- clippy_lints/src/return_self_not_must_use.rs | 3 ++- clippy_lints/src/std_instead_of_core.rs | 2 +- .../src/derive_deserialize_allowing_unknown.rs | 3 ++- clippy_lints_internal/src/lib.rs | 1 - clippy_utils/src/attrs.rs | 3 ++- clippy_utils/src/lib.rs | 4 ++-- clippy_utils/src/msrvs.rs | 2 +- clippy_utils/src/qualify_min_const_fn.rs | 4 ++-- clippy_utils/src/ty/mod.rs | 3 ++- 29 files changed, 45 insertions(+), 31 deletions(-) diff --git a/clippy_lints/src/approx_const.rs b/clippy_lints/src/approx_const.rs index 184fbbf77962..ab47e3097524 100644 --- a/clippy_lints/src/approx_const.rs +++ b/clippy_lints/src/approx_const.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::msrvs::{self, Msrv}; use rustc_ast::ast::{FloatTy, LitFloatType, LitKind}; -use rustc_attr_data_structures::RustcVersion; +use rustc_hir::RustcVersion; use rustc_hir::{HirId, Lit}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; diff --git a/clippy_lints/src/arbitrary_source_item_ordering.rs b/clippy_lints/src/arbitrary_source_item_ordering.rs index 7b4cf0336741..d6469d32931d 100644 --- a/clippy_lints/src/arbitrary_source_item_ordering.rs +++ b/clippy_lints/src/arbitrary_source_item_ordering.rs @@ -6,7 +6,7 @@ use clippy_config::types::{ }; use clippy_utils::diagnostics::span_lint_and_note; use clippy_utils::is_cfg_test; -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_hir::{ Attribute, FieldDef, HirId, ImplItemId, IsAuto, Item, ItemKind, Mod, OwnerId, QPath, TraitItemId, TyKind, Variant, VariantData, diff --git a/clippy_lints/src/attrs/inline_always.rs b/clippy_lints/src/attrs/inline_always.rs index b8f93ee5e2c1..409bb698665f 100644 --- a/clippy_lints/src/attrs/inline_always.rs +++ b/clippy_lints/src/attrs/inline_always.rs @@ -1,6 +1,7 @@ use super::INLINE_ALWAYS; use clippy_utils::diagnostics::span_lint; -use rustc_attr_data_structures::{AttributeKind, InlineAttr, find_attr}; +use rustc_hir::attrs::{AttributeKind, InlineAttr}; +use rustc_hir::find_attr; use rustc_hir::Attribute; use rustc_lint::LateContext; use rustc_span::Span; diff --git a/clippy_lints/src/attrs/repr_attributes.rs b/clippy_lints/src/attrs/repr_attributes.rs index 3e8808cec617..4ece3ed44fdf 100644 --- a/clippy_lints/src/attrs/repr_attributes.rs +++ b/clippy_lints/src/attrs/repr_attributes.rs @@ -1,4 +1,5 @@ -use rustc_attr_data_structures::{AttributeKind, ReprAttr, find_attr}; +use rustc_hir::attrs::{AttributeKind, ReprAttr}; +use rustc_hir::find_attr; use rustc_hir::Attribute; use rustc_lint::LateContext; use rustc_span::Span; diff --git a/clippy_lints/src/booleans.rs b/clippy_lints/src/booleans.rs index 61c2fc49bd70..ba1135d745ae 100644 --- a/clippy_lints/src/booleans.rs +++ b/clippy_lints/src/booleans.rs @@ -7,7 +7,7 @@ use clippy_utils::sugg::Sugg; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; use clippy_utils::{eq_expr_value, sym}; use rustc_ast::ast::LitKind; -use rustc_attr_data_structures::RustcVersion; +use rustc_hir::RustcVersion; use rustc_errors::Applicability; use rustc_hir::intravisit::{FnKind, Visitor, walk_expr}; use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, UnOp}; diff --git a/clippy_lints/src/default_union_representation.rs b/clippy_lints/src/default_union_representation.rs index 9bf2144e445d..f41255e54db6 100644 --- a/clippy_lints/src/default_union_representation.rs +++ b/clippy_lints/src/default_union_representation.rs @@ -1,5 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; -use rustc_attr_data_structures::{AttributeKind, ReprAttr, find_attr}; +use rustc_hir::attrs::{AttributeKind, ReprAttr}; +use rustc_hir::find_attr; use rustc_hir::{HirId, Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::layout::LayoutOf; diff --git a/clippy_lints/src/doc/suspicious_doc_comments.rs b/clippy_lints/src/doc/suspicious_doc_comments.rs index ebfc9972aefd..1e7d1f92fa31 100644 --- a/clippy_lints/src/doc/suspicious_doc_comments.rs +++ b/clippy_lints/src/doc/suspicious_doc_comments.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use rustc_ast::AttrStyle; use rustc_ast::token::CommentKind; -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_errors::Applicability; use rustc_hir::Attribute; use rustc_lint::LateContext; diff --git a/clippy_lints/src/doc/too_long_first_doc_paragraph.rs b/clippy_lints/src/doc/too_long_first_doc_paragraph.rs index 7f7224ecfc65..32ba696b3ec7 100644 --- a/clippy_lints/src/doc/too_long_first_doc_paragraph.rs +++ b/clippy_lints/src/doc/too_long_first_doc_paragraph.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_errors::Applicability; use rustc_hir::{Attribute, Item, ItemKind}; use rustc_lint::LateContext; diff --git a/clippy_lints/src/eta_reduction.rs b/clippy_lints/src/eta_reduction.rs index 9b627678bd35..ba539d05b6be 100644 --- a/clippy_lints/src/eta_reduction.rs +++ b/clippy_lints/src/eta_reduction.rs @@ -7,7 +7,8 @@ use clippy_utils::{ get_path_from_caller_to_method_type, is_adjusted, is_no_std_crate, path_to_local, path_to_local_id, }; use rustc_abi::ExternAbi; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_errors::Applicability; use rustc_hir::{BindingMode, Expr, ExprKind, FnRetTy, GenericArgs, Param, PatKind, QPath, Safety, TyKind}; use rustc_infer::infer::TyCtxtInferExt; diff --git a/clippy_lints/src/exhaustive_items.rs b/clippy_lints/src/exhaustive_items.rs index 8ad092790718..5f40e5764435 100644 --- a/clippy_lints/src/exhaustive_items.rs +++ b/clippy_lints/src/exhaustive_items.rs @@ -1,6 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::indent_of; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_errors::Applicability; use rustc_hir::{Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/clippy_lints/src/format_args.rs b/clippy_lints/src/format_args.rs index a251f15ba3da..af4202422e44 100644 --- a/clippy_lints/src/format_args.rs +++ b/clippy_lints/src/format_args.rs @@ -17,7 +17,8 @@ use rustc_ast::{ FormatArgPosition, FormatArgPositionKind, FormatArgsPiece, FormatArgumentKind, FormatCount, FormatOptions, FormatPlaceholder, FormatTrait, }; -use rustc_attr_data_structures::{AttributeKind, RustcVersion, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::{find_attr,RustcVersion}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_errors::SuggestionStyle::{CompletelyHidden, ShowCode}; diff --git a/clippy_lints/src/functions/must_use.rs b/clippy_lints/src/functions/must_use.rs index b8d0cec5aeb1..55ca0d9ecb71 100644 --- a/clippy_lints/src/functions/must_use.rs +++ b/clippy_lints/src/functions/must_use.rs @@ -14,7 +14,8 @@ use clippy_utils::source::snippet_indent; use clippy_utils::ty::is_must_use_ty; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{return_ty, trait_ref_of_method}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_span::Symbol; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; diff --git a/clippy_lints/src/incompatible_msrv.rs b/clippy_lints/src/incompatible_msrv.rs index 116d63c3bb15..85ebc830d3bc 100644 --- a/clippy_lints/src/incompatible_msrv.rs +++ b/clippy_lints/src/incompatible_msrv.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::Msrv; use clippy_utils::{is_in_const_context, is_in_test}; -use rustc_attr_data_structures::{RustcVersion, StabilityLevel, StableSince}; +use rustc_hir::{RustcVersion, StabilityLevel, StableSince}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::DefKind; use rustc_hir::{self as hir, AmbigArg, Expr, ExprKind, HirId, QPath}; diff --git a/clippy_lints/src/inline_fn_without_body.rs b/clippy_lints/src/inline_fn_without_body.rs index ffe6ad14f630..ee59a4cc8cb7 100644 --- a/clippy_lints/src/inline_fn_without_body.rs +++ b/clippy_lints/src/inline_fn_without_body.rs @@ -1,6 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::sugg::DiagExt; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_errors::Applicability; use rustc_hir::{TraitFn, TraitItem, TraitItemKind}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 96a6dee58852..914aa6b9b804 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -35,7 +35,6 @@ extern crate rustc_abi; extern crate rustc_arena; extern crate rustc_ast; extern crate rustc_ast_pretty; -extern crate rustc_attr_data_structures; extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_errors; diff --git a/clippy_lints/src/macro_use.rs b/clippy_lints/src/macro_use.rs index 3aa449f64118..bf89556fbb61 100644 --- a/clippy_lints/src/macro_use.rs +++ b/clippy_lints/src/macro_use.rs @@ -1,7 +1,8 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::source::snippet; use hir::def::{DefKind, Res}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{self as hir, AmbigArg}; diff --git a/clippy_lints/src/manual_non_exhaustive.rs b/clippy_lints/src/manual_non_exhaustive.rs index 2d52a93f34e3..6b0f74468492 100644 --- a/clippy_lints/src/manual_non_exhaustive.rs +++ b/clippy_lints/src/manual_non_exhaustive.rs @@ -4,7 +4,8 @@ use clippy_utils::is_doc_hidden; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::snippet_indent; use itertools::Itertools; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; diff --git a/clippy_lints/src/missing_inline.rs b/clippy_lints/src/missing_inline.rs index 5a5025973b5b..c637fb247ff2 100644 --- a/clippy_lints/src/missing_inline.rs +++ b/clippy_lints/src/missing_inline.rs @@ -1,5 +1,6 @@ use clippy_utils::diagnostics::span_lint; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, Attribute}; use rustc_lint::{LateContext, LateLintPass, LintContext}; diff --git a/clippy_lints/src/no_mangle_with_rust_abi.rs b/clippy_lints/src/no_mangle_with_rust_abi.rs index dee8efeb2910..791bbbe30a8e 100644 --- a/clippy_lints/src/no_mangle_with_rust_abi.rs +++ b/clippy_lints/src/no_mangle_with_rust_abi.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::{snippet, snippet_with_applicability}; use rustc_abi::ExternAbi; -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_errors::Applicability; use rustc_hir::{Attribute, Item, ItemKind}; use rustc_lint::{LateContext, LateLintPass}; diff --git a/clippy_lints/src/pass_by_ref_or_value.rs b/clippy_lints/src/pass_by_ref_or_value.rs index b8005dfd6f8e..303c5dfed891 100644 --- a/clippy_lints/src/pass_by_ref_or_value.rs +++ b/clippy_lints/src/pass_by_ref_or_value.rs @@ -5,7 +5,8 @@ use clippy_utils::ty::{for_each_top_level_late_bound_region, is_copy}; use clippy_utils::{is_self, is_self_ty}; use core::ops::ControlFlow; use rustc_abi::ExternAbi; -use rustc_attr_data_structures::{AttributeKind, InlineAttr, find_attr}; +use rustc_hir::attrs::{AttributeKind, InlineAttr}; +use rustc_hir::find_attr; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir as hir; diff --git a/clippy_lints/src/return_self_not_must_use.rs b/clippy_lints/src/return_self_not_must_use.rs index 3497216d1c56..2cdb8ef3a654 100644 --- a/clippy_lints/src/return_self_not_must_use.rs +++ b/clippy_lints/src/return_self_not_must_use.rs @@ -1,7 +1,8 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::is_must_use_ty; use clippy_utils::{nth_arg, return_ty}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, FnDecl, OwnerId, TraitItem, TraitItemKind}; diff --git a/clippy_lints/src/std_instead_of_core.rs b/clippy_lints/src/std_instead_of_core.rs index 216f168471e6..50c44a8e75c4 100644 --- a/clippy_lints/src/std_instead_of_core.rs +++ b/clippy_lints/src/std_instead_of_core.rs @@ -2,7 +2,7 @@ use clippy_config::Conf; use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg}; use clippy_utils::is_from_proc_macro; use clippy_utils::msrvs::Msrv; -use rustc_attr_data_structures::{StabilityLevel, StableSince}; +use rustc_hir::{StabilityLevel, StableSince}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; diff --git a/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs b/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs index 41fafc08c259..e0ae0c11cc2d 100644 --- a/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs +++ b/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs @@ -2,7 +2,8 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::paths; use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_ast::{AttrStyle, DelimArgs}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_hir::def::Res; use rustc_hir::def_id::LocalDefId; use rustc_hir::{ diff --git a/clippy_lints_internal/src/lib.rs b/clippy_lints_internal/src/lib.rs index 0c94d100c417..43cde86504f5 100644 --- a/clippy_lints_internal/src/lib.rs +++ b/clippy_lints_internal/src/lib.rs @@ -20,7 +20,6 @@ #![allow(clippy::missing_clippy_version_attribute)] extern crate rustc_ast; -extern crate rustc_attr_data_structures; extern crate rustc_attr_parsing; extern crate rustc_data_structures; extern crate rustc_errors; diff --git a/clippy_utils/src/attrs.rs b/clippy_utils/src/attrs.rs index 34472eaab93c..4ccd9c5300b1 100644 --- a/clippy_utils/src/attrs.rs +++ b/clippy_utils/src/attrs.rs @@ -2,7 +2,8 @@ use crate::source::SpanRangeExt; use crate::{sym, tokenize_with_text}; use rustc_ast::attr; use rustc_ast::attr::AttributeExt; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_errors::Applicability; use rustc_lexer::TokenKind; use rustc_lint::LateContext; diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 67e09e772a77..5b9b0ef30014 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -28,7 +28,6 @@ extern crate indexmap; extern crate rustc_abi; extern crate rustc_ast; -extern crate rustc_attr_data_structures; extern crate rustc_attr_parsing; extern crate rustc_const_eval; extern crate rustc_data_structures; @@ -91,7 +90,8 @@ use itertools::Itertools; use rustc_abi::Integer; use rustc_ast::ast::{self, LitKind, RangeLimits}; use rustc_ast::join_path_syms; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::packed::Pu128; use rustc_data_structures::unhash::UnindexMap; diff --git a/clippy_utils/src/msrvs.rs b/clippy_utils/src/msrvs.rs index 24ed4c3a8bec..480e0687756f 100644 --- a/clippy_utils/src/msrvs.rs +++ b/clippy_utils/src/msrvs.rs @@ -1,7 +1,7 @@ use crate::sym; use rustc_ast::Attribute; use rustc_ast::attr::AttributeExt; -use rustc_attr_data_structures::RustcVersion; +use rustc_hir::RustcVersion; use rustc_attr_parsing::parse_version; use rustc_lint::LateContext; use rustc_session::Session; diff --git a/clippy_utils/src/qualify_min_const_fn.rs b/clippy_utils/src/qualify_min_const_fn.rs index 11c17a77b154..79116eba971a 100644 --- a/clippy_utils/src/qualify_min_const_fn.rs +++ b/clippy_utils/src/qualify_min_const_fn.rs @@ -5,7 +5,7 @@ use crate::msrvs::{self, Msrv}; use hir::LangItem; -use rustc_attr_data_structures::{RustcVersion, StableSince}; +use rustc_hir::{RustcVersion, StableSince}; use rustc_const_eval::check_consts::ConstCx; use rustc_hir as hir; use rustc_hir::def_id::DefId; @@ -424,7 +424,7 @@ pub fn is_stable_const_fn(cx: &LateContext<'_>, def_id: DefId, msrv: Msrv) -> bo .and_then(|trait_def_id| cx.tcx.lookup_const_stability(trait_def_id)) }) .is_none_or(|const_stab| { - if let rustc_attr_data_structures::StabilityLevel::Stable { since, .. } = const_stab.level { + if let rustc_hir::StabilityLevel::Stable { since, .. } = const_stab.level { // Checking MSRV is manually necessary because `rustc` has no such concept. This entire // function could be removed if `rustc` provided a MSRV-aware version of `is_stable_const_fn`. // as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262. diff --git a/clippy_utils/src/ty/mod.rs b/clippy_utils/src/ty/mod.rs index d70232ef3aa5..02a8eda5893e 100644 --- a/clippy_utils/src/ty/mod.rs +++ b/clippy_utils/src/ty/mod.rs @@ -6,7 +6,8 @@ use core::ops::ControlFlow; use itertools::Itertools; use rustc_abi::VariantIdx; use rustc_ast::ast::Mutability; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::{AttributeKind}; +use rustc_hir::find_attr; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; From f638ebcfcea887eff5f3f05b1b2a455176a3d49c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 31 Jul 2025 11:00:40 +0200 Subject: [PATCH 0245/1134] remove rustc_attr_data_structures --- src/attributes.rs | 4 ++-- src/callee.rs | 2 +- src/lib.rs | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/attributes.rs b/src/attributes.rs index 7a1ae6ca9c8b..04b43bb8bb7c 100644 --- a/src/attributes.rs +++ b/src/attributes.rs @@ -2,8 +2,8 @@ use gccjit::FnAttribute; use gccjit::Function; #[cfg(feature = "master")] -use rustc_attr_data_structures::InlineAttr; -use rustc_attr_data_structures::InstructionSetAttr; +use rustc_hir::attrs::InlineAttr; +use rustc_hir::attrs::InstructionSetAttr; #[cfg(feature = "master")] use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; #[cfg(feature = "master")] diff --git a/src/callee.rs b/src/callee.rs index e7ca95af594c..8487a85bd035 100644 --- a/src/callee.rs +++ b/src/callee.rs @@ -106,7 +106,7 @@ pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>) // This is a monomorphization of a generic function. if !(cx.tcx.sess.opts.share_generics() || tcx.codegen_instance_attrs(instance.def).inline - == rustc_attr_data_structures::InlineAttr::Never) + == rustc_hir::attrs::InlineAttr::Never) { // When not sharing generics, all instances are in the same // crate and have hidden visibility. diff --git a/src/lib.rs b/src/lib.rs index a31206825007..613315f77a6b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,7 +35,6 @@ extern crate tracing; extern crate rustc_abi; extern crate rustc_apfloat; extern crate rustc_ast; -extern crate rustc_attr_data_structures; extern crate rustc_codegen_ssa; extern crate rustc_data_structures; extern crate rustc_errors; From 26c03e206a7c45f5767d5f2eb521d9961a4aeaf5 Mon Sep 17 00:00:00 2001 From: lcnr Date: Mon, 28 Jul 2025 09:34:44 +0000 Subject: [PATCH 0246/1134] dont assemble shadowed impl candidates --- .../src/solve/assembly/mod.rs | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index b2d401463485..b75da23cdaca 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -21,7 +21,7 @@ use crate::delegate::SolverDelegate; use crate::solve::inspect::ProbeKind; use crate::solve::{ BuiltinImplSource, CandidateSource, CanonicalResponse, Certainty, EvalCtxt, Goal, GoalSource, - MaybeCause, NoSolution, ParamEnvSource, QueryResult, + MaybeCause, NoSolution, ParamEnvSource, QueryResult, has_no_inference_or_external_constraints, }; enum AliasBoundKind { @@ -395,9 +395,30 @@ where match assemble_from { AssembleCandidatesFrom::All => { - self.assemble_impl_candidates(goal, &mut candidates); self.assemble_builtin_impl_candidates(goal, &mut candidates); - self.assemble_object_bound_candidates(goal, &mut candidates); + // For performance we only assemble impls if there are no candidates + // which would shadow them. This is necessary to avoid hangs in rayon, + // see trait-system-refactor-initiative#109 for more details. + // + // We always assemble builtin impls as trivial builtin impls have a higher + // priority than where-clauses. + // + // We only do this if any such candidate applies without any constraints + // as we may want to weaken inference guidance in the future and don't want + // to worry about causing major performance regressions when doing so. + // See trait-system-refactor-initiative#226 for some ideas here. + if TypingMode::Coherence == self.typing_mode() + || !candidates.iter().any(|c| { + matches!( + c.source, + CandidateSource::ParamEnv(ParamEnvSource::NonGlobal) + | CandidateSource::AliasBound + ) && has_no_inference_or_external_constraints(c.result) + }) + { + self.assemble_impl_candidates(goal, &mut candidates); + self.assemble_object_bound_candidates(goal, &mut candidates); + } } AssembleCandidatesFrom::EnvAndBounds => {} } From a78f92be9bd29b8d4d31ca97d2f5ba0bf818df08 Mon Sep 17 00:00:00 2001 From: lcnr Date: Thu, 31 Jul 2025 14:36:22 +0200 Subject: [PATCH 0247/1134] add tests --- .../traits/next-solver/cycles/rayon-hang-1.rs | 32 ++++++++++++ .../traits/next-solver/cycles/rayon-hang-2.rs | 49 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 tests/ui/traits/next-solver/cycles/rayon-hang-1.rs create mode 100644 tests/ui/traits/next-solver/cycles/rayon-hang-2.rs diff --git a/tests/ui/traits/next-solver/cycles/rayon-hang-1.rs b/tests/ui/traits/next-solver/cycles/rayon-hang-1.rs new file mode 100644 index 000000000000..61e1f1b200f6 --- /dev/null +++ b/tests/ui/traits/next-solver/cycles/rayon-hang-1.rs @@ -0,0 +1,32 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +// A regression test for trait-system-refactor-initiative#109. + +trait ParallelIterator: Sized { + type Item; +} +trait IntoParallelIterator { + type Iter: ParallelIterator; + type Item; +} +impl IntoParallelIterator for T { + type Iter = T; + type Item = T::Item; +} + +macro_rules! multizip_impls { + ($($T:ident),+) => { + fn foo<$( $T, )+>() where + $( + $T: IntoParallelIterator, + $T::Iter: ParallelIterator, + )+ + ($( $T, )+): IntoParallelIterator, + {} + } +} + +multizip_impls! { A, B, C, D, E, F, G, H, I, J, K, L } + +fn main() {} diff --git a/tests/ui/traits/next-solver/cycles/rayon-hang-2.rs b/tests/ui/traits/next-solver/cycles/rayon-hang-2.rs new file mode 100644 index 000000000000..bb5d8335dd62 --- /dev/null +++ b/tests/ui/traits/next-solver/cycles/rayon-hang-2.rs @@ -0,0 +1,49 @@ +//@ compile-flags: -Znext-solver +//@ check-pass + +// A regression test for trait-system-refactor-initiative#109. +// Unlike `rayon-hang-1.rs` the cycles in this test are not +// unproductive, which causes the `AliasRelate` goal when trying +// to apply where-clauses to only error in the second iteration. +// +// This makes the exponential blowup to be significantly harder +// to avoid. + +trait ParallelIterator: Sized { + type Item; +} + +trait IntoParallelIteratorIndir { + type Iter: ParallelIterator; + type Item; +} +impl IntoParallelIteratorIndir for I +where + Box: IntoParallelIterator, +{ + type Iter = as IntoParallelIterator>::Iter; + type Item = as IntoParallelIterator>::Item; +} +trait IntoParallelIterator { + type Iter: ParallelIterator; + type Item; +} +impl IntoParallelIterator for T { + type Iter = T; + type Item = T::Item; +} + +macro_rules! multizip_impls { + ($($T:ident),+) => { + fn foo<'a, $( $T, )+>() where + $( + $T: IntoParallelIteratorIndir, + $T::Iter: ParallelIterator, + )+ + {} + } +} + +multizip_impls! { A, B, C, D, E, F, G, H, I, J, K, L } + +fn main() {} From 9f7a8f8f9efb57af1f46faf45086201c50e1afde Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Wed, 30 Jul 2025 20:31:27 +0500 Subject: [PATCH 0248/1134] Changelog for Clippy 1.89 --- CHANGELOG.md | 100 ++++++++++++++++++- clippy_lints/src/casts/mod.rs | 2 +- clippy_lints/src/cloned_ref_to_slice_refs.rs | 2 +- clippy_lints/src/coerce_container_to_any.rs | 2 +- clippy_lints/src/doc/mod.rs | 2 +- clippy_lints/src/format_args.rs | 2 +- clippy_lints/src/infallible_try_from.rs | 2 +- 7 files changed, 105 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a92fbdc767bd..fa95823f259f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,105 @@ document. ## Unreleased / Beta / In Rust Nightly -[03a5b6b9...master](https://github.com/rust-lang/rust-clippy/compare/03a5b6b9...master) +[4ef75291...master](https://github.com/rust-lang/rust-clippy/compare/4ef75291...master) + +## Rust 1.89 + +Current stable, released 2025-08-07 + +[View all 137 merged pull requests](https://github.com/rust-lang/rust-clippy/pulls?q=merged%3A2025-05-01T16%3A52%3A57Z..2025-06-13T08%3A33%3A27Z+base%3Amaster) + +### New Lints + +* Added [`coerce_container_to_any`] to `nursery` [#14812](https://github.com/rust-lang/rust-clippy/pull/14812) +* Added [`ip_constant`] to `pedantic` [#14878](https://github.com/rust-lang/rust-clippy/pull/14878) +* Added [`infallible_try_from`] to `suspicious` [#14813](https://github.com/rust-lang/rust-clippy/pull/14813) +* Added [`doc_suspicious_footnotes`] to `suspicious` [#14708](https://github.com/rust-lang/rust-clippy/pull/14708) +* Added [`pointer_format`] to `restriction` [#14792](https://github.com/rust-lang/rust-clippy/pull/14792) +* Added [`useless_concat`] to `complexity` [#13829](https://github.com/rust-lang/rust-clippy/pull/13829) +* Added [`cloned_ref_to_slice_refs`] to `perf` [#14284](https://github.com/rust-lang/rust-clippy/pull/14284) +* Added [`confusing_method_to_numeric_cast`] to `suspicious` [#13979](https://github.com/rust-lang/rust-clippy/pull/13979) + +### Moves and Deprecations + +* Removed superseded lints: `transmute_float_to_int`, `transmute_int_to_char`, + `transmute_int_to_float`, `transmute_num_to_bytes` (now in rustc) + [#14703](https://github.com/rust-lang/rust-clippy/pull/14703) + +### Enhancements + +* [`module_name_repetitions`] added `allow_exact_repetitions` configuration option + [#14261](https://github.com/rust-lang/rust-clippy/pull/14261) +* [`missing_docs_in_private_items`] added `allow_unused` config for underscored fields + [#14453](https://github.com/rust-lang/rust-clippy/pull/14453) +* [`unnecessary_unwrap`] fixed being emitted twice in closure + [#14763](https://github.com/rust-lang/rust-clippy/pull/14763) +* [`needless_return`] lint span no longer wraps to previous line + [#14790](https://github.com/rust-lang/rust-clippy/pull/14790) +* [`trivial-copy-size-limit`] now defaults to `target_pointer_width` + [#13319](https://github.com/rust-lang/rust-clippy/pull/13319) +* [`integer_division`] fixed false negative for NonZero denominators + [#14664](https://github.com/rust-lang/rust-clippy/pull/14664) +* [`arbitrary_source_item_ordering`] no longer lints inside items with `#[repr]` attribute + [#14610](https://github.com/rust-lang/rust-clippy/pull/14610) +* [`excessive_precision`] no longer triggers on exponent with leading zeros + [#14824](https://github.com/rust-lang/rust-clippy/pull/14824) +* [`to_digit_is_some`] no longer lints in const contexts when MSRV is below 1.87 + [#14771](https://github.com/rust-lang/rust-clippy/pull/14771) + +### False Positive Fixes + +* [`std_instead_of_core`] fixed FP when part of the `use` cannot be replaced + [#15016](https://github.com/rust-lang/rust-clippy/pull/15016) +* [`unused_unit`] fixed FP for `Fn` bounds + [#14962](https://github.com/rust-lang/rust-clippy/pull/14962) +* [`unnecessary_debug_formatting`] fixed FP inside `Debug` impl + [#14955](https://github.com/rust-lang/rust-clippy/pull/14955) +* [`assign_op_pattern`] fixed FP on unstable const trait + [#14886](https://github.com/rust-lang/rust-clippy/pull/14886) +* [`useless_conversion`] fixed FP when using `.into_iter().any()` + [#14800](https://github.com/rust-lang/rust-clippy/pull/14800) +* [`collapsible_if`] fixed FP on block stmt before expr + [#14730](https://github.com/rust-lang/rust-clippy/pull/14730) +* [`manual_unwrap_or_default`] fixed FP on ref binding + [#14731](https://github.com/rust-lang/rust-clippy/pull/14731) +* [`unused_async`] fixed FP on default impl + [#14720](https://github.com/rust-lang/rust-clippy/pull/14720) +* [`manual_slice_fill`] fixed FP on `IndexMut` overload + [#14719](https://github.com/rust-lang/rust-clippy/pull/14719) +* [`unnecessary_to_owned`] fixed FP when map key is a reference + [#14834](https://github.com/rust-lang/rust-clippy/pull/14834) + +### ICE Fixes + +* [`mutable_key_type`] fixed ICE when infinitely associated generic types are used + [#14965](https://github.com/rust-lang/rust-clippy/pull/14965) +* [`zero_sized_map_values`] fixed ICE while computing type layout + [#14837](https://github.com/rust-lang/rust-clippy/pull/14837) +* [`useless_asref`] fixed ICE on trait method + [#14830](https://github.com/rust-lang/rust-clippy/pull/14830) +* [`manual_slice_size_calculation`] fixed ICE in suggestion and triggers in `const` context + [#14804](https://github.com/rust-lang/rust-clippy/pull/14804) +* [`missing_const_for_fn`]: fix ICE with some compilation options + [#14776](https://github.com/rust-lang/rust-clippy/pull/14776) + +### Documentation Improvements + +* [`manual_contains`] improved documentation wording + [#14917](https://github.com/rust-lang/rust-clippy/pull/14917) + +### Performance improvements + +* [`strlen_on_c_strings`] optimized by 99.75% (31M → 76k instructions) + [#15043](https://github.com/rust-lang/rust-clippy/pull/15043) +* Reduced documentation lints execution time by 85% (7.5% → 1% of total runtime) + [#14870](https://github.com/rust-lang/rust-clippy/pull/14870) +* [`unit_return_expecting_ord`] optimized to reduce binder instantiation from 95k to 10k calls + [#14905](https://github.com/rust-lang/rust-clippy/pull/14905) +* [`doc_markdown`] optimized by 50% + [#14693](https://github.com/rust-lang/rust-clippy/pull/14693) +* Refactor and speed up `cargo dev fmt` + [#14638](https://github.com/rust-lang/rust-clippy/pull/14638) ## Rust 1.88 diff --git a/clippy_lints/src/casts/mod.rs b/clippy_lints/src/casts/mod.rs index 37accff5eaa8..dcc439a272cf 100644 --- a/clippy_lints/src/casts/mod.rs +++ b/clippy_lints/src/casts/mod.rs @@ -807,7 +807,7 @@ declare_clippy_lint! { /// ```no_run /// let _ = u16::MAX as usize; /// ``` - #[clippy::version = "1.86.0"] + #[clippy::version = "1.89.0"] pub CONFUSING_METHOD_TO_NUMERIC_CAST, suspicious, "casting a primitive method pointer to any integer type" diff --git a/clippy_lints/src/cloned_ref_to_slice_refs.rs b/clippy_lints/src/cloned_ref_to_slice_refs.rs index e33a8e0fb742..72ab292ee3c6 100644 --- a/clippy_lints/src/cloned_ref_to_slice_refs.rs +++ b/clippy_lints/src/cloned_ref_to_slice_refs.rs @@ -37,7 +37,7 @@ declare_clippy_lint! { /// let data_ref = &data; /// take_slice(slice::from_ref(data_ref)); /// ``` - #[clippy::version = "1.87.0"] + #[clippy::version = "1.89.0"] pub CLONED_REF_TO_SLICE_REFS, perf, "cloning a reference for slice references" diff --git a/clippy_lints/src/coerce_container_to_any.rs b/clippy_lints/src/coerce_container_to_any.rs index 6217fc4c8977..2e3acb7748e2 100644 --- a/clippy_lints/src/coerce_container_to_any.rs +++ b/clippy_lints/src/coerce_container_to_any.rs @@ -41,7 +41,7 @@ declare_clippy_lint! { /// // Succeeds since we have a &dyn Any to the inner u32! /// assert_eq!(dyn_any_of_u32.downcast_ref::(), Some(&0u32)); /// ``` - #[clippy::version = "1.88.0"] + #[clippy::version = "1.89.0"] pub COERCE_CONTAINER_TO_ANY, nursery, "coercing to `&dyn Any` when dereferencing could produce a `dyn Any` without coercion is usually not intended" diff --git a/clippy_lints/src/doc/mod.rs b/clippy_lints/src/doc/mod.rs index ea0da0d24675..d27d68d38664 100644 --- a/clippy_lints/src/doc/mod.rs +++ b/clippy_lints/src/doc/mod.rs @@ -662,7 +662,7 @@ declare_clippy_lint! { /// /// [^1]: defined here /// fn my_fn() {} /// ``` - #[clippy::version = "1.88.0"] + #[clippy::version = "1.89.0"] pub DOC_SUSPICIOUS_FOOTNOTES, suspicious, "looks like a link or footnote ref, but with no definition" diff --git a/clippy_lints/src/format_args.rs b/clippy_lints/src/format_args.rs index a251f15ba3da..aa8efcc1df17 100644 --- a/clippy_lints/src/format_args.rs +++ b/clippy_lints/src/format_args.rs @@ -222,7 +222,7 @@ declare_clippy_lint! { /// ``` /// /// [pointer format]: https://doc.rust-lang.org/std/fmt/index.html#formatting-traits - #[clippy::version = "1.88.0"] + #[clippy::version = "1.89.0"] pub POINTER_FORMAT, restriction, "formatting a pointer" diff --git a/clippy_lints/src/infallible_try_from.rs b/clippy_lints/src/infallible_try_from.rs index fba11adcd627..aa6fc78dbbcf 100644 --- a/clippy_lints/src/infallible_try_from.rs +++ b/clippy_lints/src/infallible_try_from.rs @@ -35,7 +35,7 @@ declare_clippy_lint! { /// } /// } /// ``` - #[clippy::version = "1.88.0"] + #[clippy::version = "1.89.0"] pub INFALLIBLE_TRY_FROM, suspicious, "TryFrom with infallible Error type" From cde0374d9301090c9b6b93bb033c07b04b55ab73 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 31 Jul 2025 19:17:51 +0300 Subject: [PATCH 0249/1134] resolve: Clarify extern prelude insertion for `extern crate` items --- Cargo.lock | 1 + compiler/rustc_resolve/Cargo.toml | 1 + .../rustc_resolve/src/build_reduced_graph.rs | 42 +++++++++++-------- 3 files changed, 26 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c1076f05ef12..e0f3a9d1ff1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4552,6 +4552,7 @@ name = "rustc_resolve" version = "0.0.0" dependencies = [ "bitflags", + "indexmap", "itertools", "pulldown-cmark", "rustc_arena", diff --git a/compiler/rustc_resolve/Cargo.toml b/compiler/rustc_resolve/Cargo.toml index 1238ce0125a1..19854502cc30 100644 --- a/compiler/rustc_resolve/Cargo.toml +++ b/compiler/rustc_resolve/Cargo.toml @@ -6,6 +6,7 @@ edition = "2024" [dependencies] # tidy-alphabetical-start bitflags = "2.4.1" +indexmap = "2.4.0" itertools = "0.12" pulldown-cmark = { version = "0.11", features = ["html"], default-features = false } rustc_arena = { path = "../rustc_arena" } diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 7912345ec56a..a665dd978990 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -968,7 +968,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { } self.r.potentially_unused_imports.push(import); let imported_binding = self.r.import(binding, import); - if parent == self.r.graph_root { + if ident.name != kw::Underscore && parent == self.r.graph_root { let ident = ident.normalize_to_macros_2_0(); if let Some(entry) = self.r.extern_prelude.get(&ident) && expansion != LocalExpnId::ROOT @@ -984,23 +984,29 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { // more details: https://github.com/rust-lang/rust/pull/111761 return; } - let entry = self.r.extern_prelude.entry(ident).or_insert(ExternPreludeEntry { - binding: Cell::new(None), - introduced_by_item: true, - }); - if orig_name.is_some() { - entry.introduced_by_item = true; - } - // Binding from `extern crate` item in source code can replace - // a binding from `--extern` on command line here. - if !entry.is_import() { - entry.binding.set(Some(imported_binding)); - } else if ident.name != kw::Underscore { - self.r.dcx().span_delayed_bug( - item.span, - format!("it had been define the external module '{ident}' multiple times"), - ); - } + + use indexmap::map::Entry; + match self.r.extern_prelude.entry(ident) { + Entry::Occupied(mut occupied) => { + let entry = occupied.get_mut(); + if let Some(old_binding) = entry.binding.get() + && old_binding.is_import() + { + let msg = format!("extern crate `{ident}` already in extern prelude"); + self.r.tcx.dcx().span_delayed_bug(item.span, msg); + } else { + // Binding from `extern crate` item in source code can replace + // a binding from `--extern` on command line here. + entry.binding.set(Some(imported_binding)); + entry.introduced_by_item = orig_name.is_some(); + } + entry + } + Entry::Vacant(vacant) => vacant.insert(ExternPreludeEntry { + binding: Cell::new(Some(imported_binding)), + introduced_by_item: true, + }), + }; } self.r.define_binding_local(parent, ident, TypeNS, imported_binding); } From 2f7a2fa00fd06f9a1dcd51891b11a255cbf9d32b Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 31 Jul 2025 19:33:12 +0300 Subject: [PATCH 0250/1134] resolve: Do not add erroneous names to extern prelude --- compiler/rustc_resolve/src/lib.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index a70ae4fd57a0..17ca2ef7743d 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1487,13 +1487,23 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let mut invocation_parents = FxHashMap::default(); invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT); - let mut extern_prelude: FxIndexMap> = tcx + let mut extern_prelude: FxIndexMap<_, _> = tcx .sess .opts .externs .iter() - .filter(|(_, entry)| entry.add_prelude) - .map(|(name, _)| (Ident::from_str(name), Default::default())) + .filter_map(|(name, entry)| { + // Make sure `self`, `super`, `_` etc do not get into extern prelude. + // FIXME: reject `--extern self` and similar in option parsing instead. + if entry.add_prelude + && let name = Symbol::intern(name) + && name.can_be_raw() + { + Some((Ident::with_dummy_span(name), Default::default())) + } else { + None + } + }) .collect(); if !attr::contains_name(attrs, sym::no_core) { @@ -2168,11 +2178,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option> { - if ident.is_path_segment_keyword() { - // Make sure `self`, `super` etc produce an error when passed to here. - return None; - } - let norm_ident = ident.normalize_to_macros_2_0(); let binding = self.extern_prelude.get(&norm_ident).cloned().and_then(|entry| { Some(if let Some(binding) = entry.binding.get() { From 73096965fbac485a83033516cf61645889700a71 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 31 Jul 2025 19:51:51 +0300 Subject: [PATCH 0251/1134] resolve: Avoid double table lookup in `extern_prelude_get` Do not write dummy bindings to extern prelude. Use more precise `Used::Scope` while recording use and remove now redundant `introduced_by_item` check. --- compiler/rustc_resolve/src/lib.rs | 51 ++++++++++++++++++------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 17ca2ef7743d..bdac1b4675a0 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -2178,35 +2178,42 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option> { - let norm_ident = ident.normalize_to_macros_2_0(); - let binding = self.extern_prelude.get(&norm_ident).cloned().and_then(|entry| { - Some(if let Some(binding) = entry.binding.get() { + let mut record_use = None; + let entry = self.extern_prelude.get(&ident.normalize_to_macros_2_0()); + let binding = entry.and_then(|entry| match entry.binding.get() { + Some(binding) if binding.is_import() => { if finalize { - if !entry.is_import() { - self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span); - } else if entry.introduced_by_item { - self.record_use(ident, binding, Used::Other); - } + record_use = Some(binding); } - binding - } else { + Some(binding) + } + Some(binding) => { + if finalize { + self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span); + } + Some(binding) + } + None => { let crate_id = if finalize { - let Some(crate_id) = - self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span) - else { - return Some(self.dummy_binding); - }; - crate_id + self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span) } else { - self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)? + self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name) }; - let res = Res::Def(DefKind::Mod, crate_id.as_def_id()); - self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT) - }) + match crate_id { + Some(crate_id) => { + let res = Res::Def(DefKind::Mod, crate_id.as_def_id()); + let binding = + self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT); + entry.binding.set(Some(binding)); + Some(binding) + } + None => finalize.then_some(self.dummy_binding), + } + } }); - if let Some(entry) = self.extern_prelude.get(&norm_ident) { - entry.binding.set(binding); + if let Some(binding) = record_use { + self.record_use(ident, binding, Used::Scope); } binding From e58e6f857f1335ef2436cb7bf3a4a55ddfc79387 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 31 Jul 2025 20:33:33 +0300 Subject: [PATCH 0252/1134] resolve: Cleanup some uses of extern prelude in diagnostics --- compiler/rustc_resolve/src/diagnostics.rs | 4 ++-- compiler/rustc_resolve/src/late/diagnostics.rs | 17 ++++------------- 2 files changed, 6 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 3af69b28780d..c80f8106049a 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1098,7 +1098,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } } Scope::ExternPrelude => { - suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| { + suggestions.extend(this.extern_prelude.keys().filter_map(|ident| { let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()); filter_fn(res).then_some(TypoSuggestion::typo_from_ident(*ident, res)) })); @@ -1411,7 +1411,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { ); if lookup_ident.span.at_least_rust_2018() { - for ident in self.extern_prelude.clone().into_keys() { + for &ident in self.extern_prelude.keys() { if ident.span.from_expansion() { // Idents are adjusted to the root context before being // resolved in the extern prelude, so reporting this to the diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 98e48664e681..efafb2494c20 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -2477,19 +2477,10 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { } else { // Items from the prelude if !module.no_implicit_prelude { - let extern_prelude = self.r.extern_prelude.clone(); - names.extend(extern_prelude.iter().flat_map(|(ident, _)| { - self.r - .cstore_mut() - .maybe_process_path_extern(self.r.tcx, ident.name) - .and_then(|crate_id| { - let crate_mod = - Res::Def(DefKind::Mod, crate_id.as_def_id()); - - filter_fn(crate_mod).then(|| { - TypoSuggestion::typo_from_ident(*ident, crate_mod) - }) - }) + names.extend(self.r.extern_prelude.keys().flat_map(|ident| { + let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()); + filter_fn(res) + .then_some(TypoSuggestion::typo_from_ident(*ident, res)) })); if let Some(prelude) = self.r.prelude { From f554c79ef819cbc0f9983d0d5306cd7a9bfea6d8 Mon Sep 17 00:00:00 2001 From: Zachary S Date: Wed, 30 Jul 2025 15:35:19 -0500 Subject: [PATCH 0253/1134] Do not give function allocations alignment in consteval or miri. --- .../rustc_const_eval/src/interpret/memory.rs | 8 ++++-- src/tools/miri/tests/pass/fn_align.rs | 25 ------------------- 2 files changed, 6 insertions(+), 27 deletions(-) delete mode 100644 src/tools/miri/tests/pass/fn_align.rs diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 47bebf5371a9..bbde7c66acc0 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -937,8 +937,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // (both global from `alloc_map` and local from `extra_fn_ptr_map`) if let Some(fn_val) = self.get_fn_alloc(id) { let align = match fn_val { - FnVal::Instance(instance) => { - self.tcx.codegen_instance_attrs(instance.def).alignment.unwrap_or(Align::ONE) + FnVal::Instance(_instance) => { + // FIXME: Until we have a clear design for the effects of align(N) functions + // on the address of function pointers, we don't consider the align(N) + // attribute on functions in the interpreter. + //self.tcx.codegen_instance_attrs(instance.def).alignment.unwrap_or(Align::ONE) + Align::ONE } // Machine-specific extra functions currently do not support alignment restrictions. FnVal::Other(_) => Align::ONE, diff --git a/src/tools/miri/tests/pass/fn_align.rs b/src/tools/miri/tests/pass/fn_align.rs deleted file mode 100644 index 9752d033458d..000000000000 --- a/src/tools/miri/tests/pass/fn_align.rs +++ /dev/null @@ -1,25 +0,0 @@ -//@compile-flags: -Zmin-function-alignment=8 - -// FIXME(rust-lang/rust#82232, rust-lang/rust#143834): temporarily renamed to mitigate `#[align]` -// nameres ambiguity -#![feature(rustc_attrs)] -#![feature(fn_align)] - -// When a function uses `align(N)`, the function address should be a multiple of `N`. - -#[rustc_align(256)] -fn foo() {} - -#[rustc_align(16)] -fn bar() {} - -#[rustc_align(4)] -fn baz() {} - -fn main() { - assert!((foo as usize).is_multiple_of(256)); - assert!((bar as usize).is_multiple_of(16)); - - // The maximum of `align(N)` and `-Zmin-function-alignment=N` is used. - assert!((baz as usize).is_multiple_of(8)); -} From cab16432fb3d2a54920eba9e6c49c5263077e80e Mon Sep 17 00:00:00 2001 From: lolbinarycat Date: Thu, 31 Jul 2025 13:33:51 -0500 Subject: [PATCH 0254/1134] improve linking in the "Auxilirary builds" section of directive index --- src/doc/rustc-dev-guide/src/tests/directives.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index 5c3ae359ba0b..8ea76cd8da01 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -52,6 +52,8 @@ not be exhaustive. Directives can generally be found by browsing the ### Auxiliary builds +See [Building auxiliary crates](compiletest.html#building-auxiliary-crates) + | Directive | Explanation | Supported test suites | Possible values | |-----------------------|-------------------------------------------------------------------------------------------------------|-----------------------|-----------------------------------------------| | `aux-bin` | Build a aux binary, made available in `auxiliary/bin` relative to test directory | All except `run-make` | Path to auxiliary `.rs` file | @@ -61,8 +63,7 @@ not be exhaustive. Directives can generally be found by browsing the | `proc-macro` | Similar to `aux-build`, but for aux forces host and don't use `-Cprefer-dynamic`[^pm]. | All except `run-make` | Path to auxiliary proc-macro `.rs` file | | `build-aux-docs` | Build docs for auxiliaries as well. Note that this only works with `aux-build`, not `aux-crate`. | All except `run-make` | N/A | -[^pm]: please see the Auxiliary proc-macro section in the - [compiletest](./compiletest.md) chapter for specifics. +[^pm]: please see the [Auxiliary proc-macro section](compiletest.html#auxiliary-proc-macro) in the compiletest chapter for specifics. ### Controlling outcome expectations From 8a3a7e625a8b607c018cdcf776fa79e29eaa56c8 Mon Sep 17 00:00:00 2001 From: Urgau Date: Tue, 22 Jul 2025 20:54:22 +0200 Subject: [PATCH 0255/1134] Add lint against dangling pointers form local variables --- compiler/rustc_lint/messages.ftl | 6 + compiler/rustc_lint/src/dangling.rs | 150 ++++++++++- compiler/rustc_lint/src/lints.rs | 16 ++ .../ui/lint/dangling-pointers-from-locals.rs | 188 +++++++++++++ .../lint/dangling-pointers-from-locals.stderr | 247 ++++++++++++++++++ 5 files changed, 599 insertions(+), 8 deletions(-) create mode 100644 tests/ui/lint/dangling-pointers-from-locals.rs create mode 100644 tests/ui/lint/dangling-pointers-from-locals.stderr diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index 69fe7fe83ffd..4d0c0c94a813 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -207,6 +207,12 @@ lint_confusable_identifier_pair = found both `{$existing_sym}` and `{$sym}` as i lint_custom_inner_attribute_unstable = custom inner attributes are unstable +lint_dangling_pointers_from_locals = a dangling pointer will be produced because the local variable `{$local_var_name}` will be dropped + .ret_ty = return type of the {$fn_kind} is `{$ret_ty}` + .local_var = `{$local_var_name}` is part the {$fn_kind} and will be dropped at the end of the {$fn_kind} + .created_at = dangling pointer created here + .note = pointers do not have a lifetime; after returning, the `{$local_var_ty}` will be deallocated at the end of the {$fn_kind} because nothing is referencing it as far as the type system is concerned + lint_dangling_pointers_from_temporaries = a dangling pointer will be produced because the temporary `{$ty}` will be dropped .label_ptr = this pointer will immediately be invalid .label_temporary = this `{$ty}` is deallocated at the end of the statement, bind it to a variable to extend its lifetime diff --git a/compiler/rustc_lint/src/dangling.rs b/compiler/rustc_lint/src/dangling.rs index 9e19949c3b6e..af4457f4314b 100644 --- a/compiler/rustc_lint/src/dangling.rs +++ b/compiler/rustc_lint/src/dangling.rs @@ -1,13 +1,14 @@ use rustc_ast::visit::{visit_opt, walk_list}; use rustc_hir::attrs::AttributeKind; +use rustc_hir::def::Res; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{FnKind, Visitor, walk_expr}; -use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, LangItem, find_attr}; -use rustc_middle::ty::{Ty, TyCtxt}; +use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, LangItem, TyKind, find_attr}; +use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::{declare_lint, impl_lint_pass}; use rustc_span::{Span, sym}; -use crate::lints::DanglingPointersFromTemporaries; +use crate::lints::{DanglingPointersFromLocals, DanglingPointersFromTemporaries}; use crate::{LateContext, LateLintPass}; declare_lint! { @@ -42,6 +43,36 @@ declare_lint! { "detects getting a pointer from a temporary" } +declare_lint! { + /// The `dangling_pointers_from_locals` lint detects getting a pointer to data + /// of a local that will be dropped at the end of the function. + /// + /// ### Example + /// + /// ```rust + /// fn f() -> *const u8 { + /// let x = 0; + /// &x // returns a dangling ptr to `x` + /// } + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Returning a pointer from a local value will not prolong its lifetime, + /// which means that the value can be dropped and the allocation freed + /// while the pointer still exists, making the pointer dangling. + /// This is not an error (as far as the type system is concerned) + /// but probably is not what the user intended either. + /// + /// If you need stronger guarantees, consider using references instead, + /// as they are statically verified by the borrow-checker to never dangle. + pub DANGLING_POINTERS_FROM_LOCALS, + Warn, + "detects returning a pointer from a local variable" +} + /// FIXME: false negatives (i.e. the lint is not emitted when it should be) /// 1. Ways to get a temporary that are not recognized: /// - `owning_temporary.field` @@ -53,20 +84,123 @@ declare_lint! { #[derive(Clone, Copy, Default)] pub(crate) struct DanglingPointers; -impl_lint_pass!(DanglingPointers => [DANGLING_POINTERS_FROM_TEMPORARIES]); +impl_lint_pass!(DanglingPointers => [DANGLING_POINTERS_FROM_TEMPORARIES, DANGLING_POINTERS_FROM_LOCALS]); // This skips over const blocks, but they cannot use or return a dangling pointer anyways. impl<'tcx> LateLintPass<'tcx> for DanglingPointers { fn check_fn( &mut self, cx: &LateContext<'tcx>, - _: FnKind<'tcx>, - _: &'tcx FnDecl<'tcx>, + fn_kind: FnKind<'tcx>, + fn_decl: &'tcx FnDecl<'tcx>, body: &'tcx Body<'tcx>, _: Span, - _: LocalDefId, + def_id: LocalDefId, ) { - DanglingPointerSearcher { cx, inside_call_args: false }.visit_body(body) + DanglingPointerSearcher { cx, inside_call_args: false }.visit_body(body); + + if let FnRetTy::Return(ret_ty) = &fn_decl.output + && let TyKind::Ptr(_) = ret_ty.kind + { + // get the return type of the function or closure + let ty = match cx.tcx.type_of(def_id).instantiate_identity().kind() { + ty::FnDef(..) => cx.tcx.fn_sig(def_id).instantiate_identity(), + ty::Closure(_, args) => args.as_closure().sig(), + _ => return, + }; + let ty = ty.output(); + + // this type is only used for layout computation and pretty-printing, neither of them rely on regions + let ty = cx.tcx.instantiate_bound_regions_with_erased(ty); + + // verify that we have a pointer type + let inner_ty = match ty.kind() { + ty::RawPtr(inner_ty, _) => *inner_ty, + _ => return, + }; + + if cx + .tcx + .layout_of(cx.typing_env().as_query_input(inner_ty)) + .is_ok_and(|layout| !layout.is_1zst()) + { + let dcx = &DanglingPointerLocalContext { + body: def_id, + fn_ret: ty, + fn_ret_span: ret_ty.span, + fn_ret_inner: inner_ty, + fn_kind: match fn_kind { + FnKind::ItemFn(..) => "function", + FnKind::Method(..) => "method", + FnKind::Closure => "closure", + }, + }; + + // look for `return`s + DanglingPointerReturnSearcher { cx, dcx }.visit_body(body); + + // analyze implicit return expression + if let ExprKind::Block(block, None) = &body.value.kind + && let innermost_block = block.innermost_block() + && let Some(expr) = innermost_block.expr + { + lint_addr_of_local(cx, dcx, expr); + } + } + } + } +} + +struct DanglingPointerLocalContext<'tcx> { + body: LocalDefId, + fn_ret: Ty<'tcx>, + fn_ret_span: Span, + fn_ret_inner: Ty<'tcx>, + fn_kind: &'static str, +} + +struct DanglingPointerReturnSearcher<'lcx, 'tcx> { + cx: &'lcx LateContext<'tcx>, + dcx: &'lcx DanglingPointerLocalContext<'tcx>, +} + +impl<'tcx> Visitor<'tcx> for DanglingPointerReturnSearcher<'_, 'tcx> { + fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) -> Self::Result { + if let ExprKind::Ret(Some(expr)) = expr.kind { + lint_addr_of_local(self.cx, self.dcx, expr); + } + walk_expr(self, expr) + } +} + +/// Look for `&` pattern and emit lint for it +fn lint_addr_of_local<'a>( + cx: &LateContext<'a>, + dcx: &DanglingPointerLocalContext<'a>, + expr: &'a Expr<'a>, +) { + // peel casts as they do not interest us here, we want the inner expression. + let (inner, _) = super::utils::peel_casts(cx, expr); + + if let ExprKind::AddrOf(_, _, inner_of) = inner.kind + && let ExprKind::Path(ref qpath) = inner_of.peel_blocks().kind + && let Res::Local(from) = cx.qpath_res(qpath, inner_of.hir_id) + && cx.tcx.hir_enclosing_body_owner(from) == dcx.body + { + cx.tcx.emit_node_span_lint( + DANGLING_POINTERS_FROM_LOCALS, + expr.hir_id, + expr.span, + DanglingPointersFromLocals { + ret_ty: dcx.fn_ret, + ret_ty_span: dcx.fn_ret_span, + fn_kind: dcx.fn_kind, + local_var: cx.tcx.hir_span(from), + local_var_name: cx.tcx.hir_ident(from), + local_var_ty: dcx.fn_ret_inner, + created_at: (expr.hir_id != inner.hir_id).then_some(inner.span), + }, + ); } } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index fd8d0f832aa4..ef63c0dee8c2 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -1188,6 +1188,22 @@ pub(crate) struct DanglingPointersFromTemporaries<'tcx> { pub temporary_span: Span, } +#[derive(LintDiagnostic)] +#[diag(lint_dangling_pointers_from_locals)] +#[note] +pub(crate) struct DanglingPointersFromLocals<'tcx> { + pub ret_ty: Ty<'tcx>, + #[label(lint_ret_ty)] + pub ret_ty_span: Span, + pub fn_kind: &'static str, + #[label(lint_local_var)] + pub local_var: Span, + pub local_var_name: Ident, + pub local_var_ty: Ty<'tcx>, + #[label(lint_created_at)] + pub created_at: Option, +} + // multiple_supertrait_upcastable.rs #[derive(LintDiagnostic)] #[diag(lint_multiple_supertrait_upcastable)] diff --git a/tests/ui/lint/dangling-pointers-from-locals.rs b/tests/ui/lint/dangling-pointers-from-locals.rs new file mode 100644 index 000000000000..e321df2f4279 --- /dev/null +++ b/tests/ui/lint/dangling-pointers-from-locals.rs @@ -0,0 +1,188 @@ +//@ check-pass + +struct Zst((), ()); +struct Adt(u8); + +const X: u8 = 5; + +fn simple() -> *const u8 { + let x = 0; + &x + //~^ WARN a dangling pointer will be produced +} + +fn bindings() -> *const u8 { + let x = 0; + let x = &x; + x + //~^ WARN a dangling pointer will be produced +} + +fn bindings_with_return() -> *const u8 { + let x = 42; + let y = &x; + return y; + //~^ WARN a dangling pointer will be produced +} + +fn with_simple_cast() -> *const u8 { + let x = 0u8; + &x as *const u8 + //~^ WARN a dangling pointer will be produced +} + +fn bindings_and_casts() -> *const u8 { + let x = 0u8; + let x = &x as *const u8; + x as *const u8 + //~^ WARN a dangling pointer will be produced +} + +fn return_with_complex_cast() -> *mut u8 { + let mut x = 0u8; + return &mut x as *mut u8 as *const u8 as *mut u8; + //~^ WARN a dangling pointer will be produced +} + +fn with_block() -> *const u8 { + let x = 0; + &{ x } + //~^ WARN a dangling pointer will be produced +} + +fn with_many_blocks() -> *const u8 { + let x = 0; + { + { + &{ + //~^ WARN a dangling pointer will be produced + { x } + } + } + } +} + +fn simple_return() -> *const u8 { + let x = 0; + return &x; + //~^ WARN a dangling pointer will be produced +} + +fn return_mut() -> *mut u8 { + let mut x = 0; + return &mut x; + //~^ WARN a dangling pointer will be produced +} + +fn const_and_flow() -> *const u8 { + if false { + let x = 8; + return &x; + //~^ WARN a dangling pointer will be produced + } + &X // not dangling +} + +fn vector() -> *const Vec { + let x = vec![T::default()]; + &x + //~^ WARN a dangling pointer will be produced +} + +fn local_adt() -> *const Adt { + let x = Adt(5); + return &x; + //~^ WARN a dangling pointer will be produced +} + +fn closure() -> *const u8 { + let _x = || -> *const u8 { + let x = 8; + return &x; + //~^ WARN a dangling pointer will be produced + }; + &X // not dangling +} + +fn fn_ptr() -> *const fn() -> u8 { + fn ret_u8() -> u8 { + 0 + } + + let x = ret_u8 as fn() -> u8; + &x + //~^ WARN a dangling pointer will be produced +} + +fn as_arg(a: Adt) -> *const Adt { + &a + //~^ WARN a dangling pointer will be produced +} + +fn fn_ptr_as_arg(a: fn() -> u8) -> *const fn() -> u8 { + &a + //~^ WARN a dangling pointer will be produced +} + +fn ptr_as_arg(a: *const Adt) -> *const *const Adt { + &a + //~^ WARN a dangling pointer will be produced +} + +fn adt_as_arg(a: &Adt) -> *const &Adt { + &a + //~^ WARN a dangling pointer will be produced +} + +fn unit() -> *const () { + let x = (); + &x // not dangling +} + +fn zst() -> *const Zst { + let x = Zst((), ()); + &x // not dangling +} + +fn ref_implicit(a: &Adt) -> *const Adt { + a // not dangling +} + +fn ref_explicit(a: &Adt) -> *const Adt { + &*a // not dangling +} + +fn identity(a: *const Adt) -> *const Adt { + a // not dangling +} + +fn from_ref(a: &Adt) -> *const Adt { + std::ptr::from_ref(a) // not dangling +} + +fn inner_static() -> *const u8 { + static U: u8 = 5; + if false { + return &U as *const u8; // not dangling + } + &U // not dangling +} + +fn return_in_closure() { + let x = 0; + let c = || -> *const u8 { + &x // not dangling by it-self + }; +} + +fn option() -> *const Option { + let x = Some(T::default()); + &x // can't compute layout of `Option`, so cnat' be sure it won't be a ZST +} + +fn generic() -> *const T { + let x = T::default(); + &x // can't compute layout of `T`, so can't be sure it won't be a ZST +} + +fn main() {} diff --git a/tests/ui/lint/dangling-pointers-from-locals.stderr b/tests/ui/lint/dangling-pointers-from-locals.stderr new file mode 100644 index 000000000000..e1d28bf22a0c --- /dev/null +++ b/tests/ui/lint/dangling-pointers-from-locals.stderr @@ -0,0 +1,247 @@ +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:10:5 + | +LL | fn simple() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | let x = 0; + | - `x` is part the function and will be dropped at the end of the function +LL | &x + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + = note: `#[warn(dangling_pointers_from_locals)]` on by default + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:17:5 + | +LL | fn bindings() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | let x = 0; + | - `x` is part the function and will be dropped at the end of the function +LL | let x = &x; + | -- dangling pointer created here +LL | x + | ^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:24:12 + | +LL | fn bindings_with_return() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | let x = 42; + | - `x` is part the function and will be dropped at the end of the function +LL | let y = &x; + | -- dangling pointer created here +LL | return y; + | ^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:30:5 + | +LL | fn with_simple_cast() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | let x = 0u8; + | - `x` is part the function and will be dropped at the end of the function +LL | &x as *const u8 + | --^^^^^^^^^^^^^ + | | + | dangling pointer created here + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:37:5 + | +LL | fn bindings_and_casts() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | let x = 0u8; + | - `x` is part the function and will be dropped at the end of the function +LL | let x = &x as *const u8; + | -- dangling pointer created here +LL | x as *const u8 + | ^^^^^^^^^^^^^^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:43:12 + | +LL | fn return_with_complex_cast() -> *mut u8 { + | ------- return type of the function is `*mut u8` +LL | let mut x = 0u8; + | ----- `x` is part the function and will be dropped at the end of the function +LL | return &mut x as *mut u8 as *const u8 as *mut u8; + | ------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | dangling pointer created here + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:49:5 + | +LL | fn with_block() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | let x = 0; + | - `x` is part the function and will be dropped at the end of the function +LL | &{ x } + | ^^^^^^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:57:13 + | +LL | fn with_many_blocks() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | let x = 0; + | - `x` is part the function and will be dropped at the end of the function +... +LL | / &{ +LL | | +LL | | { x } +LL | | } + | |_____________^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:67:12 + | +LL | fn simple_return() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | let x = 0; + | - `x` is part the function and will be dropped at the end of the function +LL | return &x; + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:73:12 + | +LL | fn return_mut() -> *mut u8 { + | ------- return type of the function is `*mut u8` +LL | let mut x = 0; + | ----- `x` is part the function and will be dropped at the end of the function +LL | return &mut x; + | ^^^^^^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:80:16 + | +LL | fn const_and_flow() -> *const u8 { + | --------- return type of the function is `*const u8` +LL | if false { +LL | let x = 8; + | - `x` is part the function and will be dropped at the end of the function +LL | return &x; + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:88:5 + | +LL | fn vector() -> *const Vec { + | ------------- return type of the function is `*const Vec` +LL | let x = vec![T::default()]; + | - `x` is part the function and will be dropped at the end of the function +LL | &x + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `Vec` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:94:12 + | +LL | fn local_adt() -> *const Adt { + | ---------- return type of the function is `*const Adt` +LL | let x = Adt(5); + | - `x` is part the function and will be dropped at the end of the function +LL | return &x; + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `Adt` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:101:16 + | +LL | let _x = || -> *const u8 { + | --------- return type of the closure is `*const u8` +LL | let x = 8; + | - `x` is part the closure and will be dropped at the end of the closure +LL | return &x; + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the closure because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `x` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:113:5 + | +LL | fn fn_ptr() -> *const fn() -> u8 { + | ----------------- return type of the function is `*const fn() -> u8` +... +LL | let x = ret_u8 as fn() -> u8; + | - `x` is part the function and will be dropped at the end of the function +LL | &x + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `fn() -> u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `a` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:118:5 + | +LL | fn as_arg(a: Adt) -> *const Adt { + | - ---------- return type of the function is `*const Adt` + | | + | `a` is part the function and will be dropped at the end of the function +LL | &a + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `Adt` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `a` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:123:5 + | +LL | fn fn_ptr_as_arg(a: fn() -> u8) -> *const fn() -> u8 { + | - ----------------- return type of the function is `*const fn() -> u8` + | | + | `a` is part the function and will be dropped at the end of the function +LL | &a + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `fn() -> u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `a` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:128:5 + | +LL | fn ptr_as_arg(a: *const Adt) -> *const *const Adt { + | - ----------------- return type of the function is `*const *const Adt` + | | + | `a` is part the function and will be dropped at the end of the function +LL | &a + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `*const Adt` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: a dangling pointer will be produced because the local variable `a` will be dropped + --> $DIR/dangling-pointers-from-locals.rs:133:5 + | +LL | fn adt_as_arg(a: &Adt) -> *const &Adt { + | - ----------- return type of the function is `*const &Adt` + | | + | `a` is part the function and will be dropped at the end of the function +LL | &a + | ^^ + | + = note: pointers do not have a lifetime; after returning, the `&Adt` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned + +warning: 19 warnings emitted + From 21ec0d5a4c0ebf11175a95f5f01749f8dcf134e7 Mon Sep 17 00:00:00 2001 From: Urgau Date: Tue, 22 Jul 2025 23:11:52 +0200 Subject: [PATCH 0256/1134] Allow `dangling_pointers_from_locals` lint in tests --- src/tools/miri/tests/fail/validity/dangling_ref3.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/tools/miri/tests/fail/validity/dangling_ref3.rs b/src/tools/miri/tests/fail/validity/dangling_ref3.rs index 8e8a75bd7ec0..0fecd8f1c285 100644 --- a/src/tools/miri/tests/fail/validity/dangling_ref3.rs +++ b/src/tools/miri/tests/fail/validity/dangling_ref3.rs @@ -1,5 +1,8 @@ // Make sure we catch this even without Stacked Borrows //@compile-flags: -Zmiri-disable-stacked-borrows + +#![allow(dangling_pointers_from_locals)] + use std::mem; fn dangling() -> *const u8 { From 5aec4379e304ef280ee9a470e7ab121e4a81fd17 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Thu, 31 Jul 2025 23:59:06 +0200 Subject: [PATCH 0257/1134] detect infinite recursion with tail calls in ctfe --- compiler/rustc_mir_transform/src/ctfe_limit.rs | 2 +- .../infinite-recursion-in-ctfe.rs | 10 ++++++++++ .../infinite-recursion-in-ctfe.stderr | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/ui/explicit-tail-calls/infinite-recursion-in-ctfe.rs create mode 100644 tests/ui/explicit-tail-calls/infinite-recursion-in-ctfe.stderr diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index fb17cca30f4a..ac46336b8347 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -18,7 +18,7 @@ impl<'tcx> crate::MirPass<'tcx> for CtfeLimit { .basic_blocks .iter_enumerated() .filter_map(|(node, node_data)| { - if matches!(node_data.terminator().kind, TerminatorKind::Call { .. }) + if matches!(node_data.terminator().kind, TerminatorKind::Call { .. } | TerminatorKind::TailCall { .. }) // Back edges in a CFG indicate loops || has_back_edge(doms, node, node_data) { diff --git a/tests/ui/explicit-tail-calls/infinite-recursion-in-ctfe.rs b/tests/ui/explicit-tail-calls/infinite-recursion-in-ctfe.rs new file mode 100644 index 000000000000..0c55f13c16c2 --- /dev/null +++ b/tests/ui/explicit-tail-calls/infinite-recursion-in-ctfe.rs @@ -0,0 +1,10 @@ +#![feature(explicit_tail_calls)] +#![expect(incomplete_features)] + +const _: () = f(); + +const fn f() { + become f(); //~ error: constant evaluation is taking a long time +} + +fn main() {} diff --git a/tests/ui/explicit-tail-calls/infinite-recursion-in-ctfe.stderr b/tests/ui/explicit-tail-calls/infinite-recursion-in-ctfe.stderr new file mode 100644 index 000000000000..b5a96114a583 --- /dev/null +++ b/tests/ui/explicit-tail-calls/infinite-recursion-in-ctfe.stderr @@ -0,0 +1,17 @@ +error: constant evaluation is taking a long time + --> $DIR/infinite-recursion-in-ctfe.rs:7:5 + | +LL | become f(); + | ^^^^^^^^^^ + | + = note: this lint makes sure the compiler doesn't get stuck due to infinite loops in const eval. + If your compilation actually takes a long time, you can safely allow the lint. +help: the constant being evaluated + --> $DIR/infinite-recursion-in-ctfe.rs:4:1 + | +LL | const _: () = f(); + | ^^^^^^^^^^^ + = note: `#[deny(long_running_const_eval)]` on by default + +error: aborting due to 1 previous error + From 040f71e8123b5994177f787e64aecd9b06cdfa7e Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Fri, 25 Jul 2025 15:18:51 +0200 Subject: [PATCH 0258/1134] loop match: error on `#[const_continue]` outside `#[loop_match]` --- compiler/rustc_hir/src/hir.rs | 2 +- compiler/rustc_hir_typeck/src/loops.rs | 50 +++++++++++-------- compiler/rustc_mir_build/messages.ftl | 2 +- compiler/rustc_mir_build/src/errors.rs | 4 +- compiler/rustc_mir_build/src/thir/cx/expr.rs | 4 +- .../ui/loop-match/const-continue-to-block.rs | 21 ++++++++ .../loop-match/const-continue-to-block.stderr | 17 ++++++- tests/ui/loop-match/invalid.rs | 19 +++++++ tests/ui/loop-match/invalid.stderr | 22 ++++++-- 9 files changed, 107 insertions(+), 34 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 1b1b3ced44db..08361718108b 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3016,7 +3016,7 @@ impl fmt::Display for LoopIdError { } } -#[derive(Copy, Clone, Debug, HashStable_Generic)] +#[derive(Copy, Clone, Debug, PartialEq, HashStable_Generic)] pub struct Destination { /// This is `Some(_)` iff there is an explicit user-specified 'label pub label: Option

{ let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook); if let Some(compiler) = self.rustdoc_compiler { - let mut rustdoc = builder.rustdoc(compiler); + let mut rustdoc = builder.rustdoc_for_compiler(compiler); rustdoc.pop(); let old_path = env::var_os("PATH").unwrap_or_default(); let new_path = @@ -365,7 +365,7 @@ impl Step for Standalone { } let html = out.join(filename).with_extension("html"); - let rustdoc = builder.rustdoc(compiler); + let rustdoc = builder.rustdoc_for_compiler(compiler); if up_to_date(&path, &html) && up_to_date(&footer, &html) && up_to_date(&favicon, &html) @@ -463,7 +463,7 @@ impl Step for Releases { let html = out.join("releases.html"); let tmppath = out.join("releases.md"); let inpath = builder.src.join("RELEASES.md"); - let rustdoc = builder.rustdoc(compiler); + let rustdoc = builder.rustdoc_for_compiler(compiler); if !up_to_date(&inpath, &html) || !up_to_date(&footer, &html) || !up_to_date(&favicon, &html) diff --git a/src/bootstrap/src/core/build_steps/perf.rs b/src/bootstrap/src/core/build_steps/perf.rs index 4d61b38c876d..108b7f90c149 100644 --- a/src/bootstrap/src/core/build_steps/perf.rs +++ b/src/bootstrap/src/core/build_steps/perf.rs @@ -157,7 +157,7 @@ Consider setting `rust.debuginfo-level = 1` in `bootstrap.toml`."#); if let Some(opts) = args.cmd.shared_opts() && opts.profiles.contains(&Profile::Doc) { - builder.ensure(Rustdoc { compiler }); + builder.ensure(Rustdoc { target_compiler: compiler }); } let sysroot = builder.ensure(Sysroot::new(compiler)); diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index dde4a86251fe..1884dec89f93 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -263,7 +263,7 @@ impl Step for Cargotest { .arg(&out_dir) .args(builder.config.test_args()) .env("RUSTC", builder.rustc(compiler)) - .env("RUSTDOC", builder.rustdoc(compiler)); + .env("RUSTDOC", builder.rustdoc_for_compiler(compiler)); add_rustdoc_cargo_linker_args( &mut cmd, builder, @@ -878,7 +878,7 @@ impl Step for RustdocTheme { .env("RUSTC_SYSROOT", builder.sysroot(self.compiler)) .env("RUSTDOC_LIBDIR", builder.sysroot_target_libdir(self.compiler, self.compiler.host)) .env("CFG_RELEASE_CHANNEL", &builder.config.channel) - .env("RUSTDOC_REAL", builder.rustdoc(self.compiler)) + .env("RUSTDOC_REAL", builder.rustdoc_for_compiler(self.compiler)) .env("RUSTC_BOOTSTRAP", "1"); cmd.args(linker_args(builder, self.compiler.host, LldThreads::No, self.compiler.stage)); @@ -1037,7 +1037,11 @@ impl Step for RustdocGUI { let mut cmd = builder.tool_cmd(Tool::RustdocGUITest); let out_dir = builder.test_out(self.target).join("rustdoc-gui"); - build_stamp::clear_if_dirty(builder, &out_dir, &builder.rustdoc(self.compiler)); + build_stamp::clear_if_dirty( + builder, + &out_dir, + &builder.rustdoc_for_compiler(self.compiler), + ); if let Some(src) = builder.config.src.to_str() { cmd.arg("--rust-src").arg(src); @@ -1053,7 +1057,7 @@ impl Step for RustdocGUI { cmd.arg("--jobs").arg(builder.jobs().to_string()); - cmd.env("RUSTDOC", builder.rustdoc(self.compiler)) + cmd.env("RUSTDOC", builder.rustdoc_for_compiler(self.compiler)) .env("RUSTC", builder.rustc(self.compiler)); add_rustdoc_cargo_linker_args( @@ -1742,7 +1746,7 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the || mode == "rustdoc-json" || suite == "coverage-run-rustdoc" { - cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler)); + cmd.arg("--rustdoc-path").arg(builder.rustdoc_for_compiler(compiler)); } if mode == "rustdoc-json" { @@ -2258,7 +2262,7 @@ impl BookTest { // mdbook just executes a binary named "rustdoc", so we need to update // PATH so that it points to our rustdoc. - let mut rustdoc_path = builder.rustdoc(compiler); + let mut rustdoc_path = builder.rustdoc_for_compiler(compiler); rustdoc_path.pop(); let old_path = env::var_os("PATH").unwrap_or_default(); let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path))) diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index bc79d3432ca7..77d15b131653 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -723,7 +723,7 @@ impl Step for RemoteTestServer { pub struct Rustdoc { /// This should only ever be 0 or 2. /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here. - pub compiler: Compiler, + pub target_compiler: Compiler, } impl Step for Rustdoc { @@ -736,12 +736,13 @@ impl Step for Rustdoc { } fn make_run(run: RunConfig<'_>) { - run.builder - .ensure(Rustdoc { compiler: run.builder.compiler(run.builder.top_stage, run.target) }); + run.builder.ensure(Rustdoc { + target_compiler: run.builder.compiler(run.builder.top_stage, run.target), + }); } fn run(self, builder: &Builder<'_>) -> ToolBuildResult { - let target_compiler = self.compiler; + let target_compiler = self.target_compiler; let target = target_compiler.host; if target_compiler.stage == 0 { @@ -838,11 +839,11 @@ impl Step for Rustdoc { fn metadata(&self) -> Option { Some( - StepMetadata::build("rustdoc", self.compiler.host) + StepMetadata::build("rustdoc", self.target_compiler.host) // rustdoc is ToolRustc, so stage N rustdoc is built by stage N-1 rustc // FIXME: make this stage deduction automatic somehow // FIXME: log the compiler that actually built ToolRustc steps - .stage(self.compiler.stage.saturating_sub(1)), + .stage(self.target_compiler.stage.saturating_sub(1)), ) } } diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index 6b3236ef47ef..1d0c9da694f0 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -508,7 +508,7 @@ impl Builder<'_> { } _ => panic!("doc mode {mode:?} not expected"), }; - let rustdoc = self.rustdoc(compiler); + let rustdoc = self.rustdoc_for_compiler(compiler); build_stamp::clear_if_dirty(self, &my_out, &rustdoc); } @@ -822,7 +822,7 @@ impl Builder<'_> { } let rustdoc_path = match cmd_kind { - Kind::Doc | Kind::Test | Kind::MiriTest => self.rustdoc(compiler), + Kind::Doc | Kind::Test | Kind::MiriTest => self.rustdoc_for_compiler(compiler), _ => PathBuf::from("/path/to/nowhere/rustdoc/not/required"), }; diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 9c45ad8575e9..1a28c170048e 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -1535,8 +1535,11 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s .map(|entry| entry.path()) } - pub fn rustdoc(&self, compiler: Compiler) -> PathBuf { - self.ensure(tool::Rustdoc { compiler }).tool_path + /// Returns a path to `Rustdoc` that "belongs" to the `target_compiler`. + /// It can be either a stage0 rustdoc or a locally built rustdoc that *links* to + /// `target_compiler`. + pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf { + self.ensure(tool::Rustdoc { target_compiler }).tool_path } pub fn cargo_clippy_cmd(&self, run_compiler: Compiler) -> BootstrapCommand { @@ -1596,7 +1599,7 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s // equivalently to rustc. .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler)) .env("CFG_RELEASE_CHANNEL", &self.config.channel) - .env("RUSTDOC_REAL", self.rustdoc(compiler)) + .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler)) .env("RUSTC_BOOTSTRAP", "1"); cmd.arg("-Wrustdoc::invalid_codeblock_attributes"); diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 319de1c5cf3d..d6f61f87863f 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -284,7 +284,7 @@ mod defaults { // not the one it was built by. assert_eq!( first(cache.all::()), - &[tool::Rustdoc { compiler: Compiler::new(1, a) },] + &[tool::Rustdoc { target_compiler: Compiler::new(1, a) },] ); } } @@ -341,7 +341,7 @@ mod dist { // stage minus 1 if --stage is not 0. Very confusing! assert_eq!( first(builder.cache.all::()), - &[tool::Rustdoc { compiler: Compiler::new(2, a) },] + &[tool::Rustdoc { target_compiler: Compiler::new(2, a) },] ); } } From 6d562b2c747c61a15de50c056e809c5202dff5bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Jul 2025 12:03:55 +0200 Subject: [PATCH 0279/1134] Implement `RustcPrivateCompilers` to unify building of `rustc_private` tools --- src/bootstrap/src/core/build_steps/compile.rs | 1 + src/bootstrap/src/core/build_steps/dist.rs | 83 +++--- src/bootstrap/src/core/build_steps/install.rs | 8 +- src/bootstrap/src/core/build_steps/run.rs | 14 +- src/bootstrap/src/core/build_steps/test.rs | 94 ++++--- src/bootstrap/src/core/build_steps/tool.rs | 264 ++++++++++-------- src/bootstrap/src/core/builder/mod.rs | 23 +- src/bootstrap/src/core/builder/tests.rs | 62 ++-- src/bootstrap/src/lib.rs | 7 +- 9 files changed, 287 insertions(+), 269 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 59541bf12def..488217549d9b 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -1635,6 +1635,7 @@ impl Step for CodegenBackend { let target = self.target; let backend = self.backend; + // FIXME: migrate to RustcPrivateCompilers builder.ensure(Rustc::new(compiler, target)); if builder.config.keep_stage.contains(&compiler.stage) { diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index f1f112896a97..2d504cbd55af 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -20,7 +20,7 @@ use object::read::archive::ArchiveFile; use tracing::instrument; use crate::core::build_steps::doc::DocumentationFormat; -use crate::core::build_steps::tool::{self, Tool}; +use crate::core::build_steps::tool::{self, RustcPrivateCompilers, Tool}; use crate::core::build_steps::vendor::{VENDOR_DIR, Vendor}; use crate::core::build_steps::{compile, llvm}; use crate::core::builder::{Builder, Kind, RunConfig, ShouldRun, Step, StepMetadata}; @@ -431,13 +431,14 @@ impl Step for Rustc { let ra_proc_macro_srv_compiler = builder.compiler_for(compiler.stage, builder.config.host_target, compiler.host); - builder.ensure(compile::Rustc::new(ra_proc_macro_srv_compiler, compiler.host)); + let compilers = RustcPrivateCompilers::from_build_compiler( + builder, + ra_proc_macro_srv_compiler, + compiler.host, + ); if let Some(ra_proc_macro_srv) = builder.ensure_if_default( - tool::RustAnalyzerProcMacroSrv { - compiler: ra_proc_macro_srv_compiler, - target: compiler.host, - }, + tool::RustAnalyzerProcMacroSrv::from_compilers(compilers), builder.kind, ) { let dst = image.join("libexec"); @@ -1228,7 +1229,7 @@ impl Step for Cargo { #[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] pub struct RustAnalyzer { - pub compiler: Compiler, + pub build_compiler: Compiler, pub target: TargetSelection, } @@ -1244,7 +1245,7 @@ impl Step for RustAnalyzer { fn make_run(run: RunConfig<'_>) { run.builder.ensure(RustAnalyzer { - compiler: run.builder.compiler_for( + build_compiler: run.builder.compiler_for( run.builder.top_stage, run.builder.config.host_target, run.target, @@ -1254,12 +1255,11 @@ impl Step for RustAnalyzer { } fn run(self, builder: &Builder<'_>) -> Option { - let compiler = self.compiler; let target = self.target; + let compilers = + RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target); - builder.ensure(compile::Rustc::new(compiler, target)); - - let rust_analyzer = builder.ensure(tool::RustAnalyzer { compiler, target }); + let rust_analyzer = builder.ensure(tool::RustAnalyzer::from_compilers(compilers)); let mut tarball = Tarball::new(builder, "rust-analyzer", &target.triple); tarball.set_overlay(OverlayKind::RustAnalyzer); @@ -1270,9 +1270,9 @@ impl Step for RustAnalyzer { } } -#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] +#[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Clippy { - pub compiler: Compiler, + pub build_compiler: Compiler, pub target: TargetSelection, } @@ -1288,7 +1288,7 @@ impl Step for Clippy { fn make_run(run: RunConfig<'_>) { run.builder.ensure(Clippy { - compiler: run.builder.compiler_for( + build_compiler: run.builder.compiler_for( run.builder.top_stage, run.builder.config.host_target, run.target, @@ -1298,16 +1298,15 @@ impl Step for Clippy { } fn run(self, builder: &Builder<'_>) -> Option { - let compiler = self.compiler; let target = self.target; - - builder.ensure(compile::Rustc::new(compiler, target)); + let compilers = + RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, target); // Prepare the image directory // We expect clippy to build, because we've exited this step above if tool // state for clippy isn't testing. - let clippy = builder.ensure(tool::Clippy { compiler, target }); - let cargoclippy = builder.ensure(tool::CargoClippy { compiler, target }); + let clippy = builder.ensure(tool::Clippy::from_compilers(compilers)); + let cargoclippy = builder.ensure(tool::CargoClippy::from_compilers(compilers)); let mut tarball = Tarball::new(builder, "clippy", &target.triple); tarball.set_overlay(OverlayKind::Clippy); @@ -1319,9 +1318,9 @@ impl Step for Clippy { } } -#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] +#[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Miri { - pub compiler: Compiler, + pub build_compiler: Compiler, pub target: TargetSelection, } @@ -1337,7 +1336,7 @@ impl Step for Miri { fn make_run(run: RunConfig<'_>) { run.builder.ensure(Miri { - compiler: run.builder.compiler_for( + build_compiler: run.builder.compiler_for( run.builder.top_stage, run.builder.config.host_target, run.target, @@ -1354,15 +1353,12 @@ impl Step for Miri { return None; } - let compiler = self.compiler; - let target = self.target; - - builder.ensure(compile::Rustc::new(compiler, target)); - - let miri = builder.ensure(tool::Miri { compiler, target }); - let cargomiri = builder.ensure(tool::CargoMiri { compiler, target }); + let compilers = + RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target); + let miri = builder.ensure(tool::Miri::from_compilers(compilers)); + let cargomiri = builder.ensure(tool::CargoMiri::from_compilers(compilers)); - let mut tarball = Tarball::new(builder, "miri", &target.triple); + let mut tarball = Tarball::new(builder, "miri", &self.target.triple); tarball.set_overlay(OverlayKind::Miri); tarball.is_preview(true); tarball.add_file(&miri.tool_path, "bin", FileType::Executable); @@ -1466,9 +1462,9 @@ impl Step for CodegenBackend { } } -#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] +#[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Rustfmt { - pub compiler: Compiler, + pub build_compiler: Compiler, pub target: TargetSelection, } @@ -1484,7 +1480,7 @@ impl Step for Rustfmt { fn make_run(run: RunConfig<'_>) { run.builder.ensure(Rustfmt { - compiler: run.builder.compiler_for( + build_compiler: run.builder.compiler_for( run.builder.top_stage, run.builder.config.host_target, run.target, @@ -1494,14 +1490,13 @@ impl Step for Rustfmt { } fn run(self, builder: &Builder<'_>) -> Option { - let compiler = self.compiler; - let target = self.target; + let compilers = + RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target); - builder.ensure(compile::Rustc::new(compiler, target)); + let rustfmt = builder.ensure(tool::Rustfmt::from_compilers(compilers)); + let cargofmt = builder.ensure(tool::Cargofmt::from_compilers(compilers)); - let rustfmt = builder.ensure(tool::Rustfmt { compiler, target }); - let cargofmt = builder.ensure(tool::Cargofmt { compiler, target }); - let mut tarball = Tarball::new(builder, "rustfmt", &target.triple); + let mut tarball = Tarball::new(builder, "rustfmt", &self.target.triple); tarball.set_overlay(OverlayKind::Rustfmt); tarball.is_preview(true); tarball.add_file(&rustfmt.tool_path, "bin", FileType::Executable); @@ -1569,11 +1564,11 @@ impl Step for Extended { add_component!("rust-docs" => Docs { host: target }); add_component!("rust-json-docs" => JsonDocs { host: target }); add_component!("cargo" => Cargo { compiler, target }); - add_component!("rustfmt" => Rustfmt { compiler, target }); - add_component!("rust-analyzer" => RustAnalyzer { compiler, target }); + add_component!("rustfmt" => Rustfmt { build_compiler: compiler, target }); + add_component!("rust-analyzer" => RustAnalyzer { build_compiler: compiler, target }); add_component!("llvm-components" => LlvmTools { target }); - add_component!("clippy" => Clippy { compiler, target }); - add_component!("miri" => Miri { compiler, target }); + add_component!("clippy" => Clippy { build_compiler: compiler, target }); + add_component!("miri" => Miri { build_compiler: compiler, target }); add_component!("analysis" => Analysis { compiler, target }); add_component!("rustc-codegen-cranelift" => CodegenBackend { compiler: builder.compiler(stage, target), diff --git a/src/bootstrap/src/core/build_steps/install.rs b/src/bootstrap/src/core/build_steps/install.rs index 4513a138e192..2427b0191294 100644 --- a/src/bootstrap/src/core/build_steps/install.rs +++ b/src/bootstrap/src/core/build_steps/install.rs @@ -221,7 +221,7 @@ install!((self, builder, _config), }; RustAnalyzer, alias = "rust-analyzer", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = - builder.ensure(dist::RustAnalyzer { compiler: self.compiler, target: self.target }) + builder.ensure(dist::RustAnalyzer { build_compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-analyzer", self.compiler.stage, Some(self.target), &tarball); } else { @@ -232,12 +232,12 @@ install!((self, builder, _config), }; Clippy, alias = "clippy", Self::should_build(_config), only_hosts: true, { let tarball = builder - .ensure(dist::Clippy { compiler: self.compiler, target: self.target }) + .ensure(dist::Clippy { build_compiler: self.compiler, target: self.target }) .expect("missing clippy"); install_sh(builder, "clippy", self.compiler.stage, Some(self.target), &tarball); }; Miri, alias = "miri", Self::should_build(_config), only_hosts: true, { - if let Some(tarball) = builder.ensure(dist::Miri { compiler: self.compiler, target: self.target }) { + if let Some(tarball) = builder.ensure(dist::Miri { build_compiler: self.compiler, target: self.target }) { install_sh(builder, "miri", self.compiler.stage, Some(self.target), &tarball); } else { // Miri is only available on nightly @@ -257,7 +257,7 @@ install!((self, builder, _config), }; Rustfmt, alias = "rustfmt", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rustfmt { - compiler: self.compiler, + build_compiler: self.compiler, target: self.target }) { install_sh(builder, "rustfmt", self.compiler.stage, Some(self.target), &tarball); diff --git a/src/bootstrap/src/core/build_steps/run.rs b/src/bootstrap/src/core/build_steps/run.rs index b2293fdd9b52..984744b5678f 100644 --- a/src/bootstrap/src/core/build_steps/run.rs +++ b/src/bootstrap/src/core/build_steps/run.rs @@ -9,7 +9,7 @@ use clap_complete::{Generator, shells}; use crate::core::build_steps::dist::distdir; use crate::core::build_steps::test; -use crate::core::build_steps::tool::{self, SourceType, Tool}; +use crate::core::build_steps::tool::{self, RustcPrivateCompilers, SourceType, Tool}; use crate::core::build_steps::vendor::{Vendor, default_paths_to_vendor}; use crate::core::builder::{Builder, Kind, RunConfig, ShouldRun, Step}; use crate::core::config::TargetSelection; @@ -135,13 +135,13 @@ impl Step for Miri { } // This compiler runs on the host, we'll just use it for the target. - let target_compiler = builder.compiler(stage, target); - let miri_build = builder.ensure(tool::Miri { compiler: target_compiler, target }); - // Rustc tools are off by one stage, so use the build compiler to run miri. + let compilers = RustcPrivateCompilers::new(builder, stage, target); + let miri_build = builder.ensure(tool::Miri::from_compilers(compilers)); let host_compiler = miri_build.build_compiler; // Get a target sysroot for Miri. - let miri_sysroot = test::Miri::build_miri_sysroot(builder, target_compiler, target); + let miri_sysroot = + test::Miri::build_miri_sysroot(builder, compilers.link_compiler(), target); // # Run miri. // Running it via `cargo run` as that figures out the right dylib path. @@ -465,8 +465,8 @@ impl Step for Rustfmt { std::process::exit(1); } - let compiler = builder.compiler(stage, host); - let rustfmt_build = builder.ensure(tool::Rustfmt { compiler, target: host }); + let compilers = RustcPrivateCompilers::new(builder, stage, host); + let rustfmt_build = builder.ensure(tool::Rustfmt::from_compilers(compilers)); let mut rustfmt = tool::prepare_tool_cargo( builder, diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 1884dec89f93..f725e458c4a5 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -17,7 +17,9 @@ use crate::core::build_steps::gcc::{Gcc, add_cg_gcc_cargo_flags}; use crate::core::build_steps::llvm::get_llvm_version; use crate::core::build_steps::run::get_completion_paths; use crate::core::build_steps::synthetic_targets::MirOptPanicAbortSyntheticTarget; -use crate::core::build_steps::tool::{self, COMPILETEST_ALLOW_FEATURES, SourceType, Tool}; +use crate::core::build_steps::tool::{ + self, COMPILETEST_ALLOW_FEATURES, RustcPrivateCompilers, SourceType, Tool, +}; use crate::core::build_steps::toolstate::ToolState; use crate::core::build_steps::{compile, dist, llvm}; use crate::core::builder::{ @@ -364,8 +366,7 @@ impl Step for Cargo { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct RustAnalyzer { - stage: u32, - host: TargetSelection, + compilers: RustcPrivateCompilers, } impl Step for RustAnalyzer { @@ -378,19 +379,18 @@ impl Step for RustAnalyzer { } fn make_run(run: RunConfig<'_>) { - run.builder.ensure(Self { stage: run.builder.top_stage, host: run.target }); + run.builder.ensure(Self { + compilers: RustcPrivateCompilers::new( + run.builder, + run.builder.top_stage, + run.builder.host_target, + ), + }); } /// Runs `cargo test` for rust-analyzer fn run(self, builder: &Builder<'_>) { - let stage = self.stage; - let host = self.host; - let compiler = builder.compiler(stage, host); - let compiler = tool::get_tool_rustc_build_compiler(builder, compiler); - - // We don't need to build the whole Rust Analyzer for the proc-macro-srv test suite, - // but we do need the standard library to be present. - builder.ensure(compile::Rustc::new(compiler, host)); + let host = self.compilers.target(); let workspace_path = "src/tools/rust-analyzer"; // until the whole RA test suite runs on `i686`, we only run @@ -398,7 +398,7 @@ impl Step for RustAnalyzer { let crate_path = "src/tools/rust-analyzer/crates/proc-macro-srv"; let mut cargo = tool::prepare_tool_cargo( builder, - compiler, + self.compilers.build_compiler(), Mode::ToolRustc, host, Kind::Test, @@ -425,8 +425,7 @@ impl Step for RustAnalyzer { /// Runs `cargo test` for rustfmt. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Rustfmt { - stage: u32, - host: TargetSelection, + compilers: RustcPrivateCompilers, } impl Step for Rustfmt { @@ -438,36 +437,39 @@ impl Step for Rustfmt { } fn make_run(run: RunConfig<'_>) { - run.builder.ensure(Rustfmt { stage: run.builder.top_stage, host: run.target }); + run.builder.ensure(Rustfmt { + compilers: RustcPrivateCompilers::new( + run.builder, + run.builder.top_stage, + run.builder.host_target, + ), + }); } /// Runs `cargo test` for rustfmt. fn run(self, builder: &Builder<'_>) { - let stage = self.stage; - let host = self.host; - let compiler = builder.compiler(stage, host); - - let tool_result = builder.ensure(tool::Rustfmt { compiler, target: self.host }); - let compiler = tool_result.build_compiler; + let tool_result = builder.ensure(tool::Rustfmt::from_compilers(self.compilers)); + let build_compiler = tool_result.build_compiler; + let target = self.compilers.target(); let mut cargo = tool::prepare_tool_cargo( builder, - compiler, + build_compiler, Mode::ToolRustc, - host, + target, Kind::Test, "src/tools/rustfmt", SourceType::InTree, &[], ); - let dir = testdir(builder, compiler.host); + let dir = testdir(builder, target); t!(fs::create_dir_all(&dir)); cargo.env("RUSTFMT_TEST_DIR", dir); cargo.add_rustc_lib_path(builder); - run_cargo_test(cargo, &[], &[], "rustfmt", host, builder); + run_cargo_test(cargo, &[], &[], "rustfmt", target, builder); } } @@ -542,12 +544,14 @@ impl Step for Miri { } // This compiler runs on the host, we'll just use it for the target. - let target_compiler = builder.compiler(stage, host); + let compilers = RustcPrivateCompilers::new(builder, stage, host); // Build our tools. - let miri = builder.ensure(tool::Miri { compiler: target_compiler, target: host }); + let miri = builder.ensure(tool::Miri::from_compilers(compilers)); // the ui tests also assume cargo-miri has been built - builder.ensure(tool::CargoMiri { compiler: target_compiler, target: host }); + builder.ensure(tool::CargoMiri::from_compilers(compilers)); + + let target_compiler = compilers.link_compiler(); // We also need sysroots, for Miri and for the host (the latter for build scripts). // This is for the tests so everything is done with the target compiler. @@ -756,7 +760,7 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Clippy { - host: TargetSelection, + compilers: RustcPrivateCompilers, } impl Step for Clippy { @@ -769,23 +773,30 @@ impl Step for Clippy { } fn make_run(run: RunConfig<'_>) { - run.builder.ensure(Clippy { host: run.target }); + run.builder.ensure(Clippy { + compilers: RustcPrivateCompilers::new( + run.builder, + run.builder.top_stage, + run.builder.host_target, + ), + }); } /// Runs `cargo test` for clippy. fn run(self, builder: &Builder<'_>) { - let stage = builder.top_stage; - let host = self.host; + let host = self.compilers.target(); + // We need to carefully distinguish the compiler that builds clippy, and the compiler // that is linked into the clippy being tested. `target_compiler` is the latter, // and it must also be used by clippy's test runner to build tests and their dependencies. - let target_compiler = builder.compiler(stage, host); + let compilers = self.compilers; + let target_compiler = compilers.link_compiler(); - let tool_result = builder.ensure(tool::Clippy { compiler: target_compiler, target: host }); - let tool_compiler = tool_result.build_compiler; + let tool_result = builder.ensure(tool::Clippy::from_compilers(compilers)); + let build_compiler = tool_result.build_compiler; let mut cargo = tool::prepare_tool_cargo( builder, - tool_compiler, + build_compiler, Mode::ToolRustc, host, Kind::Test, @@ -794,9 +805,10 @@ impl Step for Clippy { &[], ); - cargo.env("RUSTC_TEST_SUITE", builder.rustc(tool_compiler)); - cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(tool_compiler)); - let host_libs = builder.stage_out(tool_compiler, Mode::ToolRustc).join(builder.cargo_dir()); + cargo.env("RUSTC_TEST_SUITE", builder.rustc(build_compiler)); + cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(build_compiler)); + let host_libs = + builder.stage_out(build_compiler, Mode::ToolRustc).join(builder.cargo_dir()); cargo.env("HOST_LIBS", host_libs); // Build the standard library that the tests can use. @@ -826,7 +838,7 @@ impl Step for Clippy { let cargo = prepare_cargo_test(cargo, &[], &[], host, builder); let _guard = - builder.msg_sysroot_tool(Kind::Test, tool_compiler.stage, "clippy", host, host); + builder.msg_sysroot_tool(Kind::Test, build_compiler.stage, "clippy", host, host); // Clippy reports errors if it blessed the outputs if cargo.allow_failure().run(builder) { diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 77d15b131653..b3e054a9d8ba 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -90,11 +90,8 @@ impl Builder<'_> { pub struct ToolBuildResult { /// Artifact path of the corresponding tool that was built. pub tool_path: PathBuf, - /// Compiler used to build the tool. For non-`ToolRustc` tools this is equal to `target_compiler`. - /// For `ToolRustc` this is one stage before of the `target_compiler`. + /// Compiler used to build the tool. pub build_compiler: Compiler, - /// Target compiler passed to `Step`. - pub target_compiler: Compiler, } impl Step for ToolBuild { @@ -108,26 +105,13 @@ impl Step for ToolBuild { /// /// This will build the specified tool with the specified `host` compiler in /// `stage` into the normal cargo output directory. - fn run(mut self, builder: &Builder<'_>) -> ToolBuildResult { + fn run(self, builder: &Builder<'_>) -> ToolBuildResult { let target = self.target; let mut tool = self.tool; let path = self.path; - let target_compiler = self.build_compiler; - self.build_compiler = if self.mode == Mode::ToolRustc { - get_tool_rustc_build_compiler(builder, self.build_compiler) - } else { - self.build_compiler - }; - match self.mode { - Mode::ToolRustc => { - // If compiler was forced, its artifacts should have been prepared earlier. - if !self.build_compiler.is_forced_compiler() { - builder.std(self.build_compiler, self.build_compiler.host); - builder.ensure(compile::Rustc::new(self.build_compiler, target)); - } - } + Mode::ToolRustc => {} Mode::ToolStd => { // If compiler was forced, its artifacts should have been prepared earlier. if !self.build_compiler.is_forced_compiler() { @@ -184,8 +168,7 @@ impl Step for ToolBuild { Kind::Build, self.mode, self.tool, - // A stage N tool is built with the stage N-1 compiler. - self.build_compiler.stage + 1, + self.build_compiler.stage, &self.build_compiler.host, &self.target, ); @@ -216,7 +199,7 @@ impl Step for ToolBuild { .join(format!("lib{tool}.rlib")), }; - ToolBuildResult { tool_path, build_compiler: self.build_compiler, target_compiler } + ToolBuildResult { tool_path, build_compiler: self.build_compiler } } } } @@ -346,27 +329,6 @@ pub fn prepare_tool_cargo( cargo } -/// Handle stage-off logic for `ToolRustc` tools when necessary. -pub(crate) fn get_tool_rustc_build_compiler( - builder: &Builder<'_>, - target_compiler: Compiler, -) -> Compiler { - if target_compiler.is_forced_compiler() { - return target_compiler; - } - - if builder.download_rustc() && target_compiler.stage == 1 { - // We shouldn't drop to stage0 compiler when using CI rustc. - return builder.compiler(1, builder.config.host_target); - } - - // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise - // we'd have stageN/bin/rustc and stageN/bin/$rustc_tool be effectively different stage - // compilers, which isn't what we want. Rustc tools should be linked in the same way as the - // compiler it's paired with, so it must be built with the previous stage compiler. - builder.compiler(target_compiler.stage.saturating_sub(1), builder.config.host_target) -} - /// Determines how to build a `ToolTarget`, i.e. which compiler should be used to compile it. /// The compiler stage is automatically bumped if we need to cross-compile a stage 1 tool. pub enum ToolTargetBuildMode { @@ -753,7 +715,6 @@ impl Step for Rustdoc { return ToolBuildResult { tool_path: builder.initial_rustdoc.clone(), build_compiler: target_compiler, - target_compiler, }; } @@ -785,11 +746,7 @@ impl Step for Rustdoc { let bin_rustdoc = bin_rustdoc(); builder.copy_link(&precompiled_rustdoc, &bin_rustdoc, FileType::Executable); - return ToolBuildResult { - tool_path: bin_rustdoc, - build_compiler: target_compiler, - target_compiler, - }; + return ToolBuildResult { tool_path: bin_rustdoc, build_compiler: target_compiler }; } } @@ -805,23 +762,23 @@ impl Step for Rustdoc { extra_features.push("jemalloc".to_string()); } - let ToolBuildResult { tool_path, build_compiler, target_compiler } = - builder.ensure(ToolBuild { - build_compiler: target_compiler, - target, - // Cargo adds a number of paths to the dylib search path on windows, which results in - // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool" - // rustdoc a different name. - tool: "rustdoc_tool_binary", - mode: Mode::ToolRustc, - path: "src/tools/rustdoc", - source_type: SourceType::InTree, - extra_features, - allow_features: "", - cargo_args: Vec::new(), - artifact_kind: ToolArtifactKind::Binary, - }); + let ToolBuildResult { tool_path, build_compiler } = builder.ensure(ToolBuild { + build_compiler: target_compiler, + target, + // Cargo adds a number of paths to the dylib search path on windows, which results in + // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool" + // rustdoc a different name. + tool: "rustdoc_tool_binary", + mode: Mode::ToolRustc, + path: "src/tools/rustdoc", + source_type: SourceType::InTree, + extra_features, + allow_features: "", + cargo_args: Vec::new(), + artifact_kind: ToolArtifactKind::Binary, + }); + // FIXME: handle the build/target compiler split here somehow // don't create a stage0-sysroot/bin directory. if target_compiler.stage > 0 { if builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None { @@ -831,9 +788,9 @@ impl Step for Rustdoc { } let bin_rustdoc = bin_rustdoc(); builder.copy_link(&tool_path, &bin_rustdoc, FileType::Executable); - ToolBuildResult { tool_path: bin_rustdoc, build_compiler, target_compiler } + ToolBuildResult { tool_path: bin_rustdoc, build_compiler } } else { - ToolBuildResult { tool_path, build_compiler, target_compiler } + ToolBuildResult { tool_path, build_compiler } } } @@ -1075,8 +1032,13 @@ impl Step for WasmComponentLd { #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct RustAnalyzer { - pub compiler: Compiler, - pub target: TargetSelection, + compilers: RustcPrivateCompilers, +} + +impl RustAnalyzer { + pub fn from_compilers(compilers: RustcPrivateCompilers) -> Self { + Self { compilers } + } } impl RustAnalyzer { @@ -1095,15 +1057,16 @@ impl Step for RustAnalyzer { fn make_run(run: RunConfig<'_>) { run.builder.ensure(RustAnalyzer { - compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.host_target), - target: run.target, + compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target), }); } fn run(self, builder: &Builder<'_>) -> ToolBuildResult { + let build_compiler = self.compilers.build_compiler; + let target = self.compilers.target(); builder.ensure(ToolBuild { - build_compiler: self.compiler, - target: self.target, + build_compiler, + target, tool: "rust-analyzer", mode: Mode::ToolRustc, path: "src/tools/rust-analyzer", @@ -1116,18 +1079,22 @@ impl Step for RustAnalyzer { } fn metadata(&self) -> Option { - // FIXME: fix staging logic Some( - StepMetadata::build("rust-analyzer", self.target) - .built_by(self.compiler.with_stage(self.compiler.stage - 1)), + StepMetadata::build("rust-analyzer", self.compilers.target()) + .built_by(self.compilers.build_compiler), ) } } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct RustAnalyzerProcMacroSrv { - pub compiler: Compiler, - pub target: TargetSelection, + compilers: RustcPrivateCompilers, +} + +impl RustAnalyzerProcMacroSrv { + pub fn from_compilers(compilers: RustcPrivateCompilers) -> Self { + Self { compilers } + } } impl Step for RustAnalyzerProcMacroSrv { @@ -1149,15 +1116,14 @@ impl Step for RustAnalyzerProcMacroSrv { fn make_run(run: RunConfig<'_>) { run.builder.ensure(RustAnalyzerProcMacroSrv { - compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.host_target), - target: run.target, + compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target), }); } fn run(self, builder: &Builder<'_>) -> Self::Output { let tool_result = builder.ensure(ToolBuild { - build_compiler: self.compiler, - target: self.target, + build_compiler: self.compilers.build_compiler, + target: self.compilers.target(), tool: "rust-analyzer-proc-macro-srv", mode: Mode::ToolRustc, path: "src/tools/rust-analyzer/crates/proc-macro-srv-cli", @@ -1170,7 +1136,7 @@ impl Step for RustAnalyzerProcMacroSrv { // Copy `rust-analyzer-proc-macro-srv` to `/libexec/` // so that r-a can use it. - let libexec_path = builder.sysroot(self.compiler).join("libexec"); + let libexec_path = builder.sysroot(self.compilers.link_compiler).join("libexec"); t!(fs::create_dir_all(&libexec_path)); builder.copy_link( &tool_result.tool_path, @@ -1182,10 +1148,9 @@ impl Step for RustAnalyzerProcMacroSrv { } fn metadata(&self) -> Option { - // FIXME: fix ToolRust staging logic Some( - StepMetadata::build("rust-analyzer-proc-macro-srv", self.target) - .built_by(self.compiler.with_stage(self.compiler.stage - 1)), + StepMetadata::build("rust-analyzer-proc-macro-srv", self.compilers.target()) + .built_by(self.compilers.build_compiler), ) } } @@ -1328,6 +1293,70 @@ impl Step for LibcxxVersionTool { } } +/// Represents which compilers are involved in the compilation of a tool +/// that depends on compiler internals (`rustc_private`). +/// Their compilation looks like this: +/// +/// - `build_compiler` (stage N-1) builds `link_compiler` (stage N) to produce .rlibs +/// - These .rlibs are copied into the sysroot of `build_compiler` +/// - `build_compiler` (stage N-1) builds `` (stage N) +/// - `` links to .rlibs from `link_compiler` +/// +/// Eventually, this could also be used for .rmetas and check builds, but so far we only deal with +/// normal builds here. +#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] +pub struct RustcPrivateCompilers { + /// Compiler that builds the tool and that builds `link_compiler`. + build_compiler: Compiler, + /// Compiler to which .rlib artifacts the tool links to. + /// The host target of this compiler corresponds to the target of the tool. + link_compiler: Compiler, +} + +impl RustcPrivateCompilers { + /// Create compilers for a `rustc_private` tool with the given `stage` and for the given + /// `target`. + pub fn new(builder: &Builder<'_>, stage: u32, target: TargetSelection) -> Self { + assert!(stage > 0); + + let build_compiler = if builder.download_rustc() && stage == 1 { + // We shouldn't drop to stage0 compiler when using CI rustc. + builder.compiler(1, builder.config.host_target) + } else { + builder.compiler(stage - 1, builder.config.host_target) + }; + + // This is the compiler we'll link to + // FIXME: make 100% sure that `link_compiler` was indeed built with `build_compiler`... + let link_compiler = builder.compiler(stage, target); + + Self { build_compiler, link_compiler } + } + + /// Create rustc tool compilers from the build compiler. + pub fn from_build_compiler( + builder: &Builder<'_>, + build_compiler: Compiler, + target: TargetSelection, + ) -> Self { + let link_compiler = builder.compiler(build_compiler.stage + 1, target); + Self { build_compiler, link_compiler } + } + + pub fn build_compiler(&self) -> Compiler { + self.build_compiler + } + + pub fn link_compiler(&self) -> Compiler { + self.link_compiler + } + + /// Target of the tool being compiled + pub fn target(&self) -> TargetSelection { + self.link_compiler.host + } +} + /// Creates a step that builds an extended `Mode::ToolRustc` tool /// and installs it into the sysroot of a corresponding compiler. macro_rules! tool_rustc_extended { @@ -1344,8 +1373,15 @@ macro_rules! tool_rustc_extended { ) => { #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct $name { - pub compiler: Compiler, - pub target: TargetSelection, + compilers: RustcPrivateCompilers, + } + + impl $name { + pub fn from_compilers(compilers: RustcPrivateCompilers) -> Self { + Self { + compilers, + } + } } impl Step for $name { @@ -1364,17 +1400,15 @@ macro_rules! tool_rustc_extended { fn make_run(run: RunConfig<'_>) { run.builder.ensure($name { - compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.host_target), - target: run.target, + compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target), }); } fn run(self, builder: &Builder<'_>) -> ToolBuildResult { - let Self { compiler, target } = self; + let Self { compilers } = self; build_extended_rustc_tool( builder, - compiler, - target, + compilers, $tool_name, $path, None $( .or(Some(&$add_bins_to_sysroot)) )?, @@ -1384,11 +1418,9 @@ macro_rules! tool_rustc_extended { } fn metadata(&self) -> Option { - // FIXME: refactor extended tool steps to make the build_compiler explicit, - // it is offset by one now for rustc tools Some( - StepMetadata::build($tool_name, self.target) - .built_by(self.compiler.with_stage(self.compiler.stage.saturating_sub(1))) + StepMetadata::build($tool_name, self.compilers.target()) + .built_by(self.compilers.build_compiler) ) } } @@ -1422,36 +1454,36 @@ fn should_run_extended_rustc_tool<'a>( #[expect(clippy::too_many_arguments)] // silence overeager clippy lint fn build_extended_rustc_tool( builder: &Builder<'_>, - compiler: Compiler, - target: TargetSelection, + compilers: RustcPrivateCompilers, tool_name: &'static str, path: &'static str, add_bins_to_sysroot: Option<&[&str]>, add_features: Option, TargetSelection, &mut Vec)>, cargo_args: Option<&[&'static str]>, ) -> ToolBuildResult { + let target = compilers.target(); let mut extra_features = Vec::new(); if let Some(func) = add_features { func(builder, target, &mut extra_features); } - let ToolBuildResult { tool_path, build_compiler, target_compiler } = - builder.ensure(ToolBuild { - build_compiler: compiler, - target, - tool: tool_name, - mode: Mode::ToolRustc, - path, - extra_features, - source_type: SourceType::InTree, - allow_features: "", - cargo_args: cargo_args.unwrap_or_default().iter().map(|s| String::from(*s)).collect(), - artifact_kind: ToolArtifactKind::Binary, - }); - + let build_compiler = compilers.build_compiler; + let ToolBuildResult { tool_path, .. } = builder.ensure(ToolBuild { + build_compiler, + target, + tool: tool_name, + mode: Mode::ToolRustc, + path, + extra_features, + source_type: SourceType::InTree, + allow_features: "", + cargo_args: cargo_args.unwrap_or_default().iter().map(|s| String::from(*s)).collect(), + artifact_kind: ToolArtifactKind::Binary, + }); + + let target_compiler = compilers.link_compiler; if let Some(add_bins_to_sysroot) = add_bins_to_sysroot && !add_bins_to_sysroot.is_empty() - && target_compiler.stage > 0 { let bindir = builder.sysroot(target_compiler).join("bin"); t!(fs::create_dir_all(&bindir)); @@ -1463,9 +1495,9 @@ fn build_extended_rustc_tool( // Return a path into the bin dir. let path = bindir.join(exe(tool_name, target_compiler.host)); - ToolBuildResult { tool_path: path, build_compiler, target_compiler } + ToolBuildResult { tool_path: path, build_compiler } } else { - ToolBuildResult { tool_path, build_compiler, target_compiler } + ToolBuildResult { tool_path, build_compiler } } } diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 1a28c170048e..b30c460d5f1b 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -16,6 +16,7 @@ use tracing::instrument; pub use self::cargo::{Cargo, cargo_profile_var}; pub use crate::Compiler; use crate::core::build_steps::compile::{Std, StdLink}; +use crate::core::build_steps::tool::RustcPrivateCompilers; use crate::core::build_steps::{ check, clean, clippy, compile, dist, doc, gcc, install, llvm, run, setup, test, tool, vendor, }; @@ -1555,10 +1556,13 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s return cmd; } - let _ = - self.ensure(tool::Clippy { compiler: run_compiler, target: self.build.host_target }); - let cargo_clippy = self - .ensure(tool::CargoClippy { compiler: run_compiler, target: self.build.host_target }); + // FIXME: double check that `run_compiler`'s stage is what we want to use + let compilers = + RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target); + assert_eq!(run_compiler, compilers.link_compiler()); + + let _ = self.ensure(tool::Clippy::from_compilers(compilers)); + let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers)); let mut dylib_path = helpers::dylib_path(); dylib_path.insert(0, self.sysroot(run_compiler).join("lib")); @@ -1570,11 +1574,14 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand { assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0"); + + let compilers = + RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target); + assert_eq!(run_compiler, compilers.link_compiler()); + // Prepare the tools - let miri = - self.ensure(tool::Miri { compiler: run_compiler, target: self.build.host_target }); - let cargo_miri = - self.ensure(tool::CargoMiri { compiler: run_compiler, target: self.build.host_target }); + let miri = self.ensure(tool::Miri::from_compilers(compilers)); + let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers)); // Invoke cargo-miri, make sure it can find miri and cargo. let mut cmd = command(cargo_miri.tool_path); cmd.env("MIRI", &miri.tool_path); diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index d6f61f87863f..77832c5dc312 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -569,36 +569,6 @@ fn test_is_builder_target() { } } -#[test] -fn test_get_tool_rustc_compiler() { - let mut config = configure("build", &[], &[]); - config.download_rustc_commit = None; - let build = Build::new(config); - let builder = Builder::new(&build); - - let target_triple_1 = TargetSelection::from_user(TEST_TRIPLE_1); - - let compiler = Compiler::new(2, target_triple_1); - let expected = Compiler::new(1, target_triple_1); - let actual = tool::get_tool_rustc_build_compiler(&builder, compiler); - assert_eq!(expected, actual); - - let compiler = Compiler::new(1, target_triple_1); - let expected = Compiler::new(0, target_triple_1); - let actual = tool::get_tool_rustc_build_compiler(&builder, compiler); - assert_eq!(expected, actual); - - let mut config = configure("build", &[], &[]); - config.download_rustc_commit = Some("".to_owned()); - let build = Build::new(config); - let builder = Builder::new(&build); - - let compiler = Compiler::new(1, target_triple_1); - let expected = Compiler::new(1, target_triple_1); - let actual = tool::get_tool_rustc_build_compiler(&builder, compiler); - assert_eq!(expected, actual); -} - /// When bootstrap detects a step dependency cycle (which is a bug), its panic /// message should show the actual steps on the stack, not just several copies /// of `Any { .. }`. @@ -1097,19 +1067,19 @@ mod snapshot { [dist] docs [doc] std 2 crates=[] [dist] mingw - [build] rustc 0 -> rust-analyzer-proc-macro-srv 1 + [build] rustc 1 -> rust-analyzer-proc-macro-srv 2 [build] rustc 0 -> GenerateCopyright 1 [dist] rustc [dist] rustc 1 -> std 1 [dist] src <> [build] rustc 0 -> cargo 1 - [build] rustc 0 -> rust-analyzer 1 - [build] rustc 0 -> rustfmt 1 - [build] rustc 0 -> cargo-fmt 1 - [build] rustc 0 -> clippy-driver 1 - [build] rustc 0 -> cargo-clippy 1 - [build] rustc 0 -> miri 1 - [build] rustc 0 -> cargo-miri 1 + [build] rustc 1 -> rust-analyzer 2 + [build] rustc 1 -> rustfmt 2 + [build] rustc 1 -> cargo-fmt 2 + [build] rustc 1 -> clippy-driver 2 + [build] rustc 1 -> cargo-clippy 2 + [build] rustc 1 -> miri 2 + [build] rustc 1 -> cargo-miri 2 "); } @@ -1290,19 +1260,19 @@ mod snapshot { [build] rustc 1 -> rustc 2 [build] rustc 1 -> WasmComponentLd 2 [build] rustdoc 1 - [build] rustc 0 -> rust-analyzer-proc-macro-srv 1 + [build] rustc 1 -> rust-analyzer-proc-macro-srv 2 [build] rustc 0 -> GenerateCopyright 1 [dist] rustc [dist] rustc 1 -> std 1 [dist] src <> [build] rustc 0 -> cargo 1 - [build] rustc 0 -> rust-analyzer 1 - [build] rustc 0 -> rustfmt 1 - [build] rustc 0 -> cargo-fmt 1 - [build] rustc 0 -> clippy-driver 1 - [build] rustc 0 -> cargo-clippy 1 - [build] rustc 0 -> miri 1 - [build] rustc 0 -> cargo-miri 1 + [build] rustc 1 -> rust-analyzer 2 + [build] rustc 1 -> rustfmt 2 + [build] rustc 1 -> cargo-fmt 2 + [build] rustc 1 -> clippy-driver 2 + [build] rustc 1 -> cargo-clippy 2 + [build] rustc 1 -> miri 2 + [build] rustc 1 -> cargo-miri 2 [build] rustc 1 -> LlvmBitcodeLinker 2 "); } diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 011b52df97bb..7c7638c4b769 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -1160,17 +1160,18 @@ impl Build { fn msg_sysroot_tool( &self, action: impl Into, - stage: u32, + build_stage: u32, what: impl Display, host: TargetSelection, target: TargetSelection, ) -> Option { let action = action.into().description(); let msg = |fmt| format!("{action} {what} {fmt}"); + let msg = if host == target { - msg(format_args!("(stage{stage} -> stage{}, {target})", stage + 1)) + msg(format_args!("(stage{build_stage} -> stage{}, {target})", build_stage + 1)) } else { - msg(format_args!("(stage{stage}:{host} -> stage{}:{target})", stage + 1)) + msg(format_args!("(stage{build_stage}:{host} -> stage{}:{target})", build_stage + 1)) }; self.group(&msg) } From b944144087df2bd56a035d7571c0e50b4f8d9d77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Jul 2025 13:09:55 +0200 Subject: [PATCH 0280/1134] Add step metadata and a few tests for `Doc` steps --- src/bootstrap/src/core/build_steps/doc.rs | 8 ++ src/bootstrap/src/core/builder/tests.rs | 95 +++++++++++++++++++++++ 2 files changed, 103 insertions(+) diff --git a/src/bootstrap/src/core/build_steps/doc.rs b/src/bootstrap/src/core/build_steps/doc.rs index 4d8505fb2b95..6d780b5474c4 100644 --- a/src/bootstrap/src/core/build_steps/doc.rs +++ b/src/bootstrap/src/core/build_steps/doc.rs @@ -901,6 +901,10 @@ impl Step for Rustc { builder.open_in_browser(index); } } + + fn metadata(&self) -> Option { + Some(StepMetadata::doc("rustc", self.target).stage(self.stage)) + } } macro_rules! tool_doc { @@ -1018,6 +1022,10 @@ macro_rules! tool_doc { })? } } + + fn metadata(&self) -> Option { + Some(StepMetadata::doc(stringify!($tool), self.target)) + } } } } diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 77832c5dc312..06ae73a6ad3d 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1674,6 +1674,101 @@ mod snapshot { [doc] std 1 crates=[alloc,core] "); } + + #[test] + fn doc_compiler_stage_0() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("doc") + .path("compiler") + .stage(0) + .render_steps(), @r" + [build] rustdoc 0 + [build] llvm + [doc] rustc 0 + "); + } + + #[test] + fn doc_compiler_stage_1() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("doc") + .path("compiler") + .stage(1) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> std 1 + [build] rustdoc 0 + [doc] rustc 1 + "); + } + + #[test] + fn doc_compiler_stage_2() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("doc") + .path("compiler") + .stage(2) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> std 1 + [build] rustc 1 -> rustc 2 + [build] rustc 2 -> std 2 + [build] rustdoc 1 + [doc] rustc 2 + "); + } + + #[test] + fn doc_compiletest_stage_0() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("doc") + .path("src/tools/compiletest") + .stage(0) + .render_steps(), @r" + [build] rustdoc 0 + [doc] Compiletest + "); + } + + #[test] + fn doc_compiletest_stage_1() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("doc") + .path("src/tools/compiletest") + .stage(1) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> std 1 + [build] rustdoc 0 + [doc] Compiletest + "); + } + + #[test] + fn doc_compiletest_stage_2() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("doc") + .path("src/tools/compiletest") + .stage(2) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> std 1 + [build] rustc 1 -> rustc 2 + [build] rustc 2 -> std 2 + [build] rustdoc 1 + [doc] Compiletest + "); + } } struct ExecutedSteps { From 2c7581fd256b50d33494595e36e8319a18318ce2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Jul 2025 13:28:05 +0200 Subject: [PATCH 0281/1134] Refactor `Rustdoc` --- src/bootstrap/src/core/build_steps/tool.rs | 121 +++++++++++---------- src/bootstrap/src/core/builder/mod.rs | 2 +- src/bootstrap/src/core/builder/tests.rs | 63 +++++------ 3 files changed, 90 insertions(+), 96 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index b3e054a9d8ba..9ee83075ea0f 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -681,15 +681,21 @@ impl Step for RemoteTestServer { } } -#[derive(Debug, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)] +/// Represents `Rustdoc` that either comes from the external stage0 sysroot or that is built +/// locally. +/// Rustdoc is special, because it both essentially corresponds to a `Compiler` (that can be +/// externally provided), but also to a `ToolRustc` tool. +#[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Rustdoc { - /// This should only ever be 0 or 2. - /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here. + /// If the stage of `target_compiler` is `0`, then rustdoc is externally provided. + /// Otherwise it is built locally. pub target_compiler: Compiler, } impl Step for Rustdoc { - type Output = ToolBuildResult; + /// Path to the built rustdoc binary. + type Output = PathBuf; + const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; @@ -703,21 +709,20 @@ impl Step for Rustdoc { }); } - fn run(self, builder: &Builder<'_>) -> ToolBuildResult { + fn run(self, builder: &Builder<'_>) -> Self::Output { let target_compiler = self.target_compiler; let target = target_compiler.host; + // If stage is 0, we use a prebuilt rustdoc from stage0 if target_compiler.stage == 0 { if !target_compiler.is_snapshot(builder) { panic!("rustdoc in stage 0 must be snapshot rustdoc"); } - return ToolBuildResult { - tool_path: builder.initial_rustdoc.clone(), - build_compiler: target_compiler, - }; + return builder.initial_rustdoc.clone(); } + // If stage is higher, we build rustdoc instead let bin_rustdoc = || { let sysroot = builder.sysroot(target_compiler); let bindir = sysroot.join("bin"); @@ -729,10 +734,7 @@ impl Step for Rustdoc { // If CI rustc is enabled and we haven't modified the rustdoc sources, // use the precompiled rustdoc from CI rustc's sysroot to speed up bootstrapping. - if builder.download_rustc() - && target_compiler.stage > 0 - && builder.rust_info().is_managed_git_subrepository() - { + if builder.download_rustc() && builder.rust_info().is_managed_git_subrepository() { let files_to_track = &["src/librustdoc", "src/tools/rustdoc", "src/rustdoc-json-types"]; // Check if unchanged @@ -745,8 +747,7 @@ impl Step for Rustdoc { let bin_rustdoc = bin_rustdoc(); builder.copy_link(&precompiled_rustdoc, &bin_rustdoc, FileType::Executable); - - return ToolBuildResult { tool_path: bin_rustdoc, build_compiler: target_compiler }; + return bin_rustdoc; } } @@ -762,45 +763,39 @@ impl Step for Rustdoc { extra_features.push("jemalloc".to_string()); } - let ToolBuildResult { tool_path, build_compiler } = builder.ensure(ToolBuild { - build_compiler: target_compiler, - target, - // Cargo adds a number of paths to the dylib search path on windows, which results in - // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool" - // rustdoc a different name. - tool: "rustdoc_tool_binary", - mode: Mode::ToolRustc, - path: "src/tools/rustdoc", - source_type: SourceType::InTree, - extra_features, - allow_features: "", - cargo_args: Vec::new(), - artifact_kind: ToolArtifactKind::Binary, - }); - - // FIXME: handle the build/target compiler split here somehow - // don't create a stage0-sysroot/bin directory. - if target_compiler.stage > 0 { - if builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None { - // Due to LTO a lot of debug info from C++ dependencies such as jemalloc can make it into - // our final binaries - compile::strip_debug(builder, target, &tool_path); - } - let bin_rustdoc = bin_rustdoc(); - builder.copy_link(&tool_path, &bin_rustdoc, FileType::Executable); - ToolBuildResult { tool_path: bin_rustdoc, build_compiler } - } else { - ToolBuildResult { tool_path, build_compiler } + let compilers = RustcPrivateCompilers::from_link_compiler(builder, target_compiler); + let tool_path = builder + .ensure(ToolBuild { + build_compiler: compilers.build_compiler, + target, + // Cargo adds a number of paths to the dylib search path on windows, which results in + // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool" + // rustdoc a different name. + tool: "rustdoc_tool_binary", + mode: Mode::ToolRustc, + path: "src/tools/rustdoc", + source_type: SourceType::InTree, + extra_features, + allow_features: "", + cargo_args: Vec::new(), + artifact_kind: ToolArtifactKind::Binary, + }) + .tool_path; + + if builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None { + // Due to LTO a lot of debug info from C++ dependencies such as jemalloc can make it into + // our final binaries + compile::strip_debug(builder, target, &tool_path); } + let bin_rustdoc = bin_rustdoc(); + builder.copy_link(&tool_path, &bin_rustdoc, FileType::Executable); + bin_rustdoc } fn metadata(&self) -> Option { Some( StepMetadata::build("rustdoc", self.target_compiler.host) - // rustdoc is ToolRustc, so stage N rustdoc is built by stage N-1 rustc - // FIXME: make this stage deduction automatic somehow - // FIXME: log the compiler that actually built ToolRustc steps - .stage(self.target_compiler.stage.saturating_sub(1)), + .stage(self.target_compiler.stage), ) } } @@ -1317,18 +1312,11 @@ impl RustcPrivateCompilers { /// Create compilers for a `rustc_private` tool with the given `stage` and for the given /// `target`. pub fn new(builder: &Builder<'_>, stage: u32, target: TargetSelection) -> Self { - assert!(stage > 0); - - let build_compiler = if builder.download_rustc() && stage == 1 { - // We shouldn't drop to stage0 compiler when using CI rustc. - builder.compiler(1, builder.config.host_target) - } else { - builder.compiler(stage - 1, builder.config.host_target) - }; + let build_compiler = Self::build_compiler_from_stage(builder, stage); // This is the compiler we'll link to // FIXME: make 100% sure that `link_compiler` was indeed built with `build_compiler`... - let link_compiler = builder.compiler(stage, target); + let link_compiler = builder.compiler(build_compiler.stage + 1, target); Self { build_compiler, link_compiler } } @@ -1343,6 +1331,25 @@ impl RustcPrivateCompilers { Self { build_compiler, link_compiler } } + /// Create rustc tool compilers from the link compiler. + pub fn from_link_compiler(builder: &Builder<'_>, link_compiler: Compiler) -> Self { + Self { + build_compiler: Self::build_compiler_from_stage(builder, link_compiler.stage), + link_compiler, + } + } + + fn build_compiler_from_stage(builder: &Builder<'_>, stage: u32) -> Compiler { + assert!(stage > 0); + + if builder.download_rustc() && stage == 1 { + // We shouldn't drop to stage0 compiler when using CI rustc. + builder.compiler(1, builder.config.host_target) + } else { + builder.compiler(stage - 1, builder.config.host_target) + } + } + pub fn build_compiler(&self) -> Compiler { self.build_compiler } diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index b30c460d5f1b..660c869b67e9 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -1540,7 +1540,7 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s /// It can be either a stage0 rustdoc or a locally built rustdoc that *links* to /// `target_compiler`. pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf { - self.ensure(tool::Rustdoc { target_compiler }).tool_path + self.ensure(tool::Rustdoc { target_compiler }) } pub fn cargo_clippy_cmd(&self, run_compiler: Compiler) -> BootstrapCommand { diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 06ae73a6ad3d..26158abf4bd4 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -279,13 +279,6 @@ mod defaults { first(cache.all::()), &[tool::ErrorIndex { compiler: Compiler::new(1, a) }] ); - // docs should be built with the stage0 compiler, not with the stage0 artifacts. - // recall that rustdoc is off-by-one: `stage` is the compiler rustdoc is _linked_ to, - // not the one it was built by. - assert_eq!( - first(cache.all::()), - &[tool::Rustdoc { target_compiler: Compiler::new(1, a) },] - ); } } @@ -337,12 +330,6 @@ mod dist { first(builder.cache.all::()), &[tool::ErrorIndex { compiler: Compiler::new(1, a) }] ); - // This is actually stage 1, but Rustdoc::run swaps out the compiler with - // stage minus 1 if --stage is not 0. Very confusing! - assert_eq!( - first(builder.cache.all::()), - &[tool::Rustdoc { target_compiler: Compiler::new(2, a) },] - ); } } @@ -627,7 +614,7 @@ mod snapshot { [build] llvm [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 - [build] rustdoc 0 + [build] rustdoc 1 "); } @@ -650,10 +637,10 @@ mod snapshot { [build] rustc 2 -> std 2 [build] rustc 1 -> std 1 [build] rustc 2 -> std 2 - [build] rustdoc 1 + [build] rustdoc 2 [build] llvm [build] rustc 1 -> rustc 2 - [build] rustdoc 1 + [build] rustdoc 2 "); } @@ -750,7 +737,7 @@ mod snapshot { [build] rustc 1 -> LldWrapper 2 [build] rustc 1 -> LlvmBitcodeLinker 2 [build] rustc 2 -> std 2 - [build] rustdoc 1 + [build] rustdoc 2 " ); } @@ -779,7 +766,7 @@ mod snapshot { [build] rustc 1 -> rustc 2 [build] rustc 1 -> LldWrapper 2 [build] rustc 1 -> LlvmBitcodeLinker 2 - [build] rustdoc 1 + [build] rustdoc 2 " ); } @@ -968,7 +955,7 @@ mod snapshot { .render_steps(), @r" [build] llvm [build] rustc 0 -> rustc 1 - [build] rustdoc 0 + [build] rustdoc 1 [doc] std 1 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] "); } @@ -1017,7 +1004,7 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [build] rustc 2 -> std 2 [build] rustc 0 -> LintDocs 1 @@ -1059,7 +1046,7 @@ mod snapshot { [build] rustc 1 -> LldWrapper 2 [build] rustc 1 -> WasmComponentLd 2 [build] rustc 1 -> LlvmBitcodeLinker 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [build] rustc 2 -> std 2 [build] rustc 0 -> LintDocs 1 @@ -1098,7 +1085,7 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [build] rustc 2 -> std 2 @@ -1135,7 +1122,7 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [build] rustc 2 -> std 2 [build] rustc 0 -> LintDocs 1 @@ -1149,7 +1136,7 @@ mod snapshot { [dist] rustc [build] llvm [build] rustc 1 -> rustc 2 - [build] rustdoc 1 + [build] rustdoc 2 [dist] rustc [dist] rustc 1 -> std 1 [dist] src <> @@ -1172,7 +1159,7 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [build] rustc 2 -> std 2 @@ -1190,7 +1177,7 @@ mod snapshot { [dist] rustc [build] llvm [build] rustc 1 -> rustc 2 - [build] rustdoc 1 + [build] rustdoc 2 [dist] rustc [dist] rustc 1 -> std 1 [dist] rustc 1 -> std 1 @@ -1214,7 +1201,7 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [build] rustc 2 -> std 2 [build] rustc 0 -> RustInstaller 1 @@ -1246,7 +1233,7 @@ mod snapshot { [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 [build] rustc 1 -> WasmComponentLd 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] std 2 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] [build] rustc 2 -> std 2 [build] rustc 1 -> std 1 @@ -1259,7 +1246,7 @@ mod snapshot { [build] llvm [build] rustc 1 -> rustc 2 [build] rustc 1 -> WasmComponentLd 2 - [build] rustdoc 1 + [build] rustdoc 2 [build] rustc 1 -> rust-analyzer-proc-macro-srv 2 [build] rustc 0 -> GenerateCopyright 1 [dist] rustc @@ -1595,7 +1582,7 @@ mod snapshot { .render_steps(), @r" [build] llvm [build] rustc 0 -> rustc 1 - [build] rustdoc 0 + [build] rustdoc 1 [doc] std 1 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] "); } @@ -1609,7 +1596,7 @@ mod snapshot { .render_steps(), @r" [build] llvm [build] rustc 0 -> rustc 1 - [build] rustdoc 0 + [build] rustdoc 1 [doc] std 1 crates=[core] "); } @@ -1624,7 +1611,7 @@ mod snapshot { .render_steps(), @r" [build] llvm [build] rustc 0 -> rustc 1 - [build] rustdoc 0 + [build] rustdoc 1 [doc] std 1 crates=[core] "); } @@ -1654,7 +1641,7 @@ mod snapshot { .render_steps(), @r" [build] llvm [build] rustc 0 -> rustc 1 - [build] rustdoc 0 + [build] rustdoc 1 [doc] std 1 crates=[alloc,core] "); } @@ -1670,7 +1657,7 @@ mod snapshot { .render_steps(), @r" [build] llvm [build] rustc 0 -> rustc 1 - [build] rustdoc 0 + [build] rustdoc 1 [doc] std 1 crates=[alloc,core] "); } @@ -1700,7 +1687,7 @@ mod snapshot { [build] llvm [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 - [build] rustdoc 0 + [build] rustdoc 1 [doc] rustc 1 "); } @@ -1718,7 +1705,7 @@ mod snapshot { [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 [build] rustc 2 -> std 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] rustc 2 "); } @@ -1747,7 +1734,7 @@ mod snapshot { [build] llvm [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 - [build] rustdoc 0 + [build] rustdoc 1 [doc] Compiletest "); } @@ -1765,7 +1752,7 @@ mod snapshot { [build] rustc 1 -> std 1 [build] rustc 1 -> rustc 2 [build] rustc 2 -> std 2 - [build] rustdoc 1 + [build] rustdoc 2 [doc] Compiletest "); } From 91d40d270d66baa374169be662c403993f5a6591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Jul 2025 13:28:13 +0200 Subject: [PATCH 0282/1134] Fix `ToolRustc` build with `download-rustc` --- src/bootstrap/src/core/build_steps/tool.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 9ee83075ea0f..469def86f8f1 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -111,7 +111,13 @@ impl Step for ToolBuild { let path = self.path; match self.mode { - Mode::ToolRustc => {} + Mode::ToolRustc => { + // FIXME: remove this, it's only needed for download-rustc... + if !self.build_compiler.is_forced_compiler() && builder.download_rustc() { + builder.std(self.build_compiler, self.build_compiler.host); + builder.ensure(compile::Rustc::new(self.build_compiler, target)); + } + } Mode::ToolStd => { // If compiler was forced, its artifacts should have been prepared earlier. if !self.build_compiler.is_forced_compiler() { From 7a2c4d312276bec98e4182099d0f8b8b09d55fa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Jul 2025 13:45:33 +0200 Subject: [PATCH 0283/1134] Add step metadata and a simple test for codegen backends --- src/bootstrap/src/core/build_steps/compile.rs | 7 +++++++ src/bootstrap/src/core/builder/tests.rs | 20 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 488217549d9b..2c54a31ecbe4 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -1705,6 +1705,13 @@ impl Step for CodegenBackend { let codegen_backend = codegen_backend.to_str().unwrap(); t!(stamp.add_stamp(codegen_backend).write()); } + + fn metadata(&self) -> Option { + Some( + StepMetadata::build(&format!("rustc_codegen_{}", self.backend), self.target) + .built_by(self.compiler), + ) + } } /// Creates the `codegen-backends` folder for a compiler that's about to be diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 26158abf4bd4..8d458c74cf5b 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -719,6 +719,26 @@ mod snapshot { "); } + #[test] + fn build_compiler_codegen_backend() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx + .config("build") + .args(&["--set", "rust.codegen-backends=['llvm', 'cranelift']"]) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 0 -> rustc_codegen_cranelift 1 + [build] rustc 1 -> std 1 + [build] rustc 1 -> std 1 + [build] rustc 1 -> rustc 2 + [build] rustc 1 -> rustc_codegen_cranelift 2 + [build] rustdoc 1 + " + ); + } + #[test] fn build_compiler_tools() { let ctx = TestCtx::new(); From 06855be09d67e48980f986cad13ce9059165f0b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Jul 2025 13:51:01 +0200 Subject: [PATCH 0284/1134] Port codegen backends to `RustcPrivateCompilers` --- src/bootstrap/src/core/build_steps/compile.rs | 61 +++++++++---------- src/bootstrap/src/core/build_steps/doc.rs | 2 +- src/bootstrap/src/core/build_steps/test.rs | 13 ++-- src/bootstrap/src/core/build_steps/tool.rs | 14 ++--- src/bootstrap/src/core/builder/tests.rs | 3 - src/bootstrap/src/lib.rs | 13 +--- 6 files changed, 45 insertions(+), 61 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 2c54a31ecbe4..c76a96028fa8 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -19,7 +19,7 @@ use serde_derive::Deserialize; use tracing::{instrument, span}; use crate::core::build_steps::gcc::{Gcc, add_cg_gcc_cargo_flags}; -use crate::core::build_steps::tool::{SourceType, copy_lld_artifacts}; +use crate::core::build_steps::tool::{RustcPrivateCompilers, SourceType, copy_lld_artifacts}; use crate::core::build_steps::{dist, llvm}; use crate::core::builder; use crate::core::builder::{ @@ -1131,7 +1131,7 @@ impl Step for Rustc { cargo.env("RUSTC_BOLT_LINK_FLAGS", "1"); } - let _guard = builder.msg_sysroot_tool( + let _guard = builder.msg_rustc_tool( Kind::Build, build_compiler.stage, format_args!("compiler artifacts{}", crate_description(&self.crates)), @@ -1544,9 +1544,8 @@ impl Step for RustcLink { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct CodegenBackend { - pub target: TargetSelection, - pub compiler: Compiler, - pub backend: CodegenBackendKind, + compilers: RustcPrivateCompilers, + backend: CodegenBackendKind, } fn needs_codegen_config(run: &RunConfig<'_>) -> bool { @@ -1610,8 +1609,11 @@ impl Step for CodegenBackend { } run.builder.ensure(CodegenBackend { - target: run.target, - compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()), + compilers: RustcPrivateCompilers::new( + run.builder, + run.builder.top_stage, + run.target, + ), backend: backend.clone(), }); } @@ -1624,21 +1626,17 @@ impl Step for CodegenBackend { name = "CodegenBackend::run", skip_all, fields( - compiler = ?self.compiler, - target = ?self.target, - backend = ?self.target, + compilers = ?self.compilers, + backend = ?self.backend, ), ), )] fn run(self, builder: &Builder<'_>) { - let compiler = self.compiler; - let target = self.target; let backend = self.backend; + let target = self.compilers.target(); + let build_compiler = self.compilers.build_compiler(); - // FIXME: migrate to RustcPrivateCompilers - builder.ensure(Rustc::new(compiler, target)); - - if builder.config.keep_stage.contains(&compiler.stage) { + if builder.config.keep_stage.contains(&build_compiler.stage) { trace!("`keep-stage` requested"); builder.info( "WARNING: Using a potentially old codegen backend. \ @@ -1649,17 +1647,11 @@ impl Step for CodegenBackend { return; } - let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target); - if compiler_to_use != compiler { - builder.ensure(CodegenBackend { compiler: compiler_to_use, target, backend }); - return; - } - - let out_dir = builder.cargo_out(compiler, Mode::Codegen, target); + let out_dir = builder.cargo_out(build_compiler, Mode::Codegen, target); let mut cargo = builder::Cargo::new( builder, - compiler, + build_compiler, Mode::Codegen, SourceType::InTree, target, @@ -1680,8 +1672,13 @@ impl Step for CodegenBackend { let tmp_stamp = BuildStamp::new(&out_dir).with_prefix("tmp"); - let _guard = - builder.msg_build(compiler, format_args!("codegen backend {}", backend.name()), target); + let _guard = builder.msg_rustc_tool( + Kind::Build, + build_compiler.stage, + format_args!("codegen backend {}", backend.name()), + build_compiler.host, + target, + ); let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false, false); if builder.config.dry_run() { return; @@ -1701,15 +1698,15 @@ impl Step for CodegenBackend { f.display() ); } - let stamp = build_stamp::codegen_backend_stamp(builder, compiler, target, &backend); + let stamp = build_stamp::codegen_backend_stamp(builder, build_compiler, target, &backend); let codegen_backend = codegen_backend.to_str().unwrap(); t!(stamp.add_stamp(codegen_backend).write()); } fn metadata(&self) -> Option { Some( - StepMetadata::build(&format!("rustc_codegen_{}", self.backend), self.target) - .built_by(self.compiler), + StepMetadata::build(&self.backend.crate_name(), self.compilers.target()) + .built_by(self.compilers.build_compiler()), ) } } @@ -2198,8 +2195,10 @@ impl Step for Assemble { continue; } builder.ensure(CodegenBackend { - compiler: build_compiler, - target: target_compiler.host, + compilers: RustcPrivateCompilers::from_build_and_link_compiler( + build_compiler, + target_compiler, + ), backend: backend.clone(), }); } diff --git a/src/bootstrap/src/core/build_steps/doc.rs b/src/bootstrap/src/core/build_steps/doc.rs index 6d780b5474c4..d4539a0eb34d 100644 --- a/src/bootstrap/src/core/build_steps/doc.rs +++ b/src/bootstrap/src/core/build_steps/doc.rs @@ -811,7 +811,7 @@ impl Step for Rustc { let compiler = builder.compiler(stage, builder.config.host_target); builder.std(compiler, builder.config.host_target); - let _guard = builder.msg_sysroot_tool( + let _guard = builder.msg_rustc_tool( Kind::Doc, stage, format!("compiler{}", crate_description(&self.crates)), diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index f725e458c4a5..6c6b2e585495 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -603,7 +603,7 @@ impl Step for Miri { cargo.env("MIRI_TEST_TARGET", target.rustc_target_arg()); { - let _guard = builder.msg_sysroot_tool(Kind::Test, stage, "miri", host, target); + let _guard = builder.msg_rustc_tool(Kind::Test, stage, "miri", host, target); let _time = helpers::timeit(builder); cargo.run(builder); } @@ -619,7 +619,7 @@ impl Step for Miri { cargo.args(["tests/pass", "tests/panic"]); { - let _guard = builder.msg_sysroot_tool( + let _guard = builder.msg_rustc_tool( Kind::Test, stage, "miri (mir-opt-level 4)", @@ -696,7 +696,7 @@ impl Step for CargoMiri { // Finally, run everything. let mut cargo = BootstrapCommand::from(cargo); { - let _guard = builder.msg_sysroot_tool(Kind::Test, stage, "cargo-miri", host, target); + let _guard = builder.msg_rustc_tool(Kind::Test, stage, "cargo-miri", host, target); let _time = helpers::timeit(builder); cargo.run(builder); } @@ -837,8 +837,7 @@ impl Step for Clippy { cargo.add_rustc_lib_path(builder); let cargo = prepare_cargo_test(cargo, &[], &[], host, builder); - let _guard = - builder.msg_sysroot_tool(Kind::Test, build_compiler.stage, "clippy", host, host); + let _guard = builder.msg_rustc_tool(Kind::Test, build_compiler.stage, "clippy", host, host); // Clippy reports errors if it blessed the outputs if cargo.allow_failure().run(builder) { @@ -1105,7 +1104,7 @@ impl Step for RustdocGUI { } let _time = helpers::timeit(builder); - let _guard = builder.msg_sysroot_tool( + let _guard = builder.msg_rustc_tool( Kind::Test, self.compiler.stage, "rustdoc-gui", @@ -2597,7 +2596,7 @@ fn run_cargo_test<'a>( let mut cargo = prepare_cargo_test(cargo, libtest_args, crates, target, builder); let _time = helpers::timeit(builder); let _group = description.into().and_then(|what| { - builder.msg_sysroot_tool(Kind::Test, compiler.stage, what, compiler.host, target) + builder.msg_rustc_tool(Kind::Test, compiler.stage, what, compiler.host, target) }); #[cfg(feature = "build-metrics")] diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 469def86f8f1..c1b8b03e6a1a 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -71,13 +71,9 @@ impl Builder<'_> { ) -> Option { match mode { // depends on compiler stage, different to host compiler - Mode::ToolRustc => self.msg_sysroot_tool( - kind, - build_stage, - format_args!("tool {tool}"), - *host, - *target, - ), + Mode::ToolRustc => { + self.msg_rustc_tool(kind, build_stage, format_args!("tool {tool}"), *host, *target) + } // doesn't depend on compiler, same as host compiler _ => self.msg(kind, build_stage, format_args!("tool {tool}"), *host, *target), } @@ -1327,6 +1323,10 @@ impl RustcPrivateCompilers { Self { build_compiler, link_compiler } } + pub fn from_build_and_link_compiler(build_compiler: Compiler, link_compiler: Compiler) -> Self { + Self { build_compiler, link_compiler } + } + /// Create rustc tool compilers from the build compiler. pub fn from_build_compiler( builder: &Builder<'_>, diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 8d458c74cf5b..ac7d8c7cb48b 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -731,9 +731,6 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 0 -> rustc_codegen_cranelift 1 [build] rustc 1 -> std 1 - [build] rustc 1 -> std 1 - [build] rustc 1 -> rustc 2 - [build] rustc 1 -> rustc_codegen_cranelift 2 [build] rustdoc 1 " ); diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 7c7638c4b769..69546e923d0d 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -1100,17 +1100,6 @@ impl Build { self.msg(Kind::Doc, compiler.stage, what, compiler.host, target.into()) } - #[must_use = "Groups should not be dropped until the Step finishes running"] - #[track_caller] - fn msg_build( - &self, - compiler: Compiler, - what: impl Display, - target: impl Into>, - ) -> Option { - self.msg(Kind::Build, compiler.stage, what, compiler.host, target) - } - /// Return a `Group` guard for a [`Step`] that is built for each `--stage`. /// /// [`Step`]: crate::core::builder::Step @@ -1157,7 +1146,7 @@ impl Build { #[must_use = "Groups should not be dropped until the Step finishes running"] #[track_caller] - fn msg_sysroot_tool( + fn msg_rustc_tool( &self, action: impl Into, build_stage: u32, From c3da07beb42b7cd32cfff30d357368c6299c36dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Jul 2025 14:01:59 +0200 Subject: [PATCH 0285/1134] Rename `link_compiler` to `target_compiler` --- src/bootstrap/src/core/build_steps/compile.rs | 2 +- src/bootstrap/src/core/build_steps/run.rs | 2 +- src/bootstrap/src/core/build_steps/test.rs | 4 +- src/bootstrap/src/core/build_steps/tool.rs | 45 ++++++++++--------- src/bootstrap/src/core/builder/mod.rs | 4 +- 5 files changed, 30 insertions(+), 27 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index c76a96028fa8..95707e37018e 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -2195,7 +2195,7 @@ impl Step for Assemble { continue; } builder.ensure(CodegenBackend { - compilers: RustcPrivateCompilers::from_build_and_link_compiler( + compilers: RustcPrivateCompilers::from_build_and_target_compiler( build_compiler, target_compiler, ), diff --git a/src/bootstrap/src/core/build_steps/run.rs b/src/bootstrap/src/core/build_steps/run.rs index 984744b5678f..962dd372849d 100644 --- a/src/bootstrap/src/core/build_steps/run.rs +++ b/src/bootstrap/src/core/build_steps/run.rs @@ -141,7 +141,7 @@ impl Step for Miri { // Get a target sysroot for Miri. let miri_sysroot = - test::Miri::build_miri_sysroot(builder, compilers.link_compiler(), target); + test::Miri::build_miri_sysroot(builder, compilers.target_compiler(), target); // # Run miri. // Running it via `cargo run` as that figures out the right dylib path. diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 6c6b2e585495..073a1d62d7f1 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -551,7 +551,7 @@ impl Step for Miri { // the ui tests also assume cargo-miri has been built builder.ensure(tool::CargoMiri::from_compilers(compilers)); - let target_compiler = compilers.link_compiler(); + let target_compiler = compilers.target_compiler(); // We also need sysroots, for Miri and for the host (the latter for build scripts). // This is for the tests so everything is done with the target compiler. @@ -790,7 +790,7 @@ impl Step for Clippy { // that is linked into the clippy being tested. `target_compiler` is the latter, // and it must also be used by clippy's test runner to build tests and their dependencies. let compilers = self.compilers; - let target_compiler = compilers.link_compiler(); + let target_compiler = compilers.target_compiler(); let tool_result = builder.ensure(tool::Clippy::from_compilers(compilers)); let build_compiler = tool_result.build_compiler; diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index c1b8b03e6a1a..a56090ab1a4a 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -765,7 +765,7 @@ impl Step for Rustdoc { extra_features.push("jemalloc".to_string()); } - let compilers = RustcPrivateCompilers::from_link_compiler(builder, target_compiler); + let compilers = RustcPrivateCompilers::from_target_compiler(builder, target_compiler); let tool_path = builder .ensure(ToolBuild { build_compiler: compilers.build_compiler, @@ -1133,7 +1133,7 @@ impl Step for RustAnalyzerProcMacroSrv { // Copy `rust-analyzer-proc-macro-srv` to `/libexec/` // so that r-a can use it. - let libexec_path = builder.sysroot(self.compilers.link_compiler).join("libexec"); + let libexec_path = builder.sysroot(self.compilers.target_compiler).join("libexec"); t!(fs::create_dir_all(&libexec_path)); builder.copy_link( &tool_result.tool_path, @@ -1294,20 +1294,20 @@ impl Step for LibcxxVersionTool { /// that depends on compiler internals (`rustc_private`). /// Their compilation looks like this: /// -/// - `build_compiler` (stage N-1) builds `link_compiler` (stage N) to produce .rlibs +/// - `build_compiler` (stage N-1) builds `target_compiler` (stage N) to produce .rlibs /// - These .rlibs are copied into the sysroot of `build_compiler` /// - `build_compiler` (stage N-1) builds `` (stage N) -/// - `` links to .rlibs from `link_compiler` +/// - `` links to .rlibs from `target_compiler` /// /// Eventually, this could also be used for .rmetas and check builds, but so far we only deal with /// normal builds here. #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub struct RustcPrivateCompilers { - /// Compiler that builds the tool and that builds `link_compiler`. + /// Compiler that builds the tool and that builds `target_compiler`. build_compiler: Compiler, /// Compiler to which .rlib artifacts the tool links to. /// The host target of this compiler corresponds to the target of the tool. - link_compiler: Compiler, + target_compiler: Compiler, } impl RustcPrivateCompilers { @@ -1317,14 +1317,17 @@ impl RustcPrivateCompilers { let build_compiler = Self::build_compiler_from_stage(builder, stage); // This is the compiler we'll link to - // FIXME: make 100% sure that `link_compiler` was indeed built with `build_compiler`... - let link_compiler = builder.compiler(build_compiler.stage + 1, target); + // FIXME: make 100% sure that `target_compiler` was indeed built with `build_compiler`... + let target_compiler = builder.compiler(build_compiler.stage + 1, target); - Self { build_compiler, link_compiler } + Self { build_compiler, target_compiler } } - pub fn from_build_and_link_compiler(build_compiler: Compiler, link_compiler: Compiler) -> Self { - Self { build_compiler, link_compiler } + pub fn from_build_and_target_compiler( + build_compiler: Compiler, + target_compiler: Compiler, + ) -> Self { + Self { build_compiler, target_compiler } } /// Create rustc tool compilers from the build compiler. @@ -1333,15 +1336,15 @@ impl RustcPrivateCompilers { build_compiler: Compiler, target: TargetSelection, ) -> Self { - let link_compiler = builder.compiler(build_compiler.stage + 1, target); - Self { build_compiler, link_compiler } + let target_compiler = builder.compiler(build_compiler.stage + 1, target); + Self { build_compiler, target_compiler } } - /// Create rustc tool compilers from the link compiler. - pub fn from_link_compiler(builder: &Builder<'_>, link_compiler: Compiler) -> Self { + /// Create rustc tool compilers from the target compiler. + pub fn from_target_compiler(builder: &Builder<'_>, target_compiler: Compiler) -> Self { Self { - build_compiler: Self::build_compiler_from_stage(builder, link_compiler.stage), - link_compiler, + build_compiler: Self::build_compiler_from_stage(builder, target_compiler.stage), + target_compiler, } } @@ -1360,13 +1363,13 @@ impl RustcPrivateCompilers { self.build_compiler } - pub fn link_compiler(&self) -> Compiler { - self.link_compiler + pub fn target_compiler(&self) -> Compiler { + self.target_compiler } /// Target of the tool being compiled pub fn target(&self) -> TargetSelection { - self.link_compiler.host + self.target_compiler.host } } @@ -1494,7 +1497,7 @@ fn build_extended_rustc_tool( artifact_kind: ToolArtifactKind::Binary, }); - let target_compiler = compilers.link_compiler; + let target_compiler = compilers.target_compiler; if let Some(add_bins_to_sysroot) = add_bins_to_sysroot && !add_bins_to_sysroot.is_empty() { diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 660c869b67e9..98deb6603026 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -1559,7 +1559,7 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s // FIXME: double check that `run_compiler`'s stage is what we want to use let compilers = RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target); - assert_eq!(run_compiler, compilers.link_compiler()); + assert_eq!(run_compiler, compilers.target_compiler()); let _ = self.ensure(tool::Clippy::from_compilers(compilers)); let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers)); @@ -1577,7 +1577,7 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s let compilers = RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target); - assert_eq!(run_compiler, compilers.link_compiler()); + assert_eq!(run_compiler, compilers.target_compiler()); // Prepare the tools let miri = self.ensure(tool::Miri::from_compilers(compilers)); From 0ff8ff38ee75af184419fa396d6fc4db53eb22ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 22 Jul 2025 18:22:36 +0200 Subject: [PATCH 0286/1134] Appease Clippy --- src/bootstrap/src/core/build_steps/tool.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index a56090ab1a4a..6204476456ce 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -1467,7 +1467,6 @@ fn should_run_extended_rustc_tool<'a>( ) } -#[expect(clippy::too_many_arguments)] // silence overeager clippy lint fn build_extended_rustc_tool( builder: &Builder<'_>, compilers: RustcPrivateCompilers, From 316b5d390203c0592dab9810cf80b5cb6f7ce536 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 21 Jul 2025 17:38:20 +0200 Subject: [PATCH 0287/1134] Add basic Cargo snapshot test --- src/bootstrap/src/core/build_steps/tool.rs | 2 ++ src/bootstrap/src/core/builder/tests.rs | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 6204476456ce..00be04e26dc3 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -802,6 +802,8 @@ impl Step for Rustdoc { } } +/// Builds the cargo tool. +/// Note that it can be built using a stable compiler. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Cargo { pub compiler: Compiler, diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index ac7d8c7cb48b..3b3f321750f2 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1000,6 +1000,19 @@ mod snapshot { "); } + #[test] + fn build_cargo() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("build") + .paths(&["cargo"]) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> cargo 2 + "); + } + #[test] fn dist_default_stage() { let ctx = TestCtx::new(); From 21d7a540135a1f7a9c3a35fa139df8faefde637c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 21 Jul 2025 17:41:02 +0200 Subject: [PATCH 0288/1134] Make `Cargo` a `ToolTarget` tool --- src/bootstrap/src/core/build_steps/tool.rs | 10 +++------- src/bootstrap/src/core/builder/tests.rs | 6 +----- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 00be04e26dc3..a2c7c8c65b06 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -822,7 +822,7 @@ impl Step for Cargo { fn make_run(run: RunConfig<'_>) { run.builder.ensure(Cargo { - compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.host_target), + compiler: get_tool_target_compiler(run.builder, ToolTargetBuildMode::Build(run.target)), target: run.target, }); } @@ -834,7 +834,7 @@ impl Step for Cargo { build_compiler: self.compiler, target: self.target, tool: "cargo", - mode: Mode::ToolRustc, + mode: Mode::ToolTarget, path: "src/tools/cargo", source_type: SourceType::Submodule, extra_features: Vec::new(), @@ -845,11 +845,7 @@ impl Step for Cargo { } fn metadata(&self) -> Option { - // FIXME: fix staging logic - Some( - StepMetadata::build("cargo", self.target) - .built_by(self.compiler.with_stage(self.compiler.stage - 1)), - ) + Some(StepMetadata::build("cargo", self.target).built_by(self.compiler)) } } diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 3b3f321750f2..6bd5b16eabb3 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1006,11 +1006,7 @@ mod snapshot { insta::assert_snapshot!( ctx.config("build") .paths(&["cargo"]) - .render_steps(), @r" - [build] llvm - [build] rustc 0 -> rustc 1 - [build] rustc 1 -> cargo 2 - "); + .render_steps(), @"[build] rustc 0 -> cargo 1 "); } #[test] From 021f2ff54d2569b6074a019510d105050849b99f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 21 Jul 2025 17:59:33 +0200 Subject: [PATCH 0289/1134] Update `CargoTest` --- src/bootstrap/src/core/build_steps/test.rs | 31 +++++++++++++++------- src/bootstrap/src/core/builder/tests.rs | 17 ++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 073a1d62d7f1..e542ab7c1276 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -228,7 +228,7 @@ impl Step for HtmlCheck { /// order to test cargo. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Cargotest { - stage: u32, + build_compiler: Compiler, host: TargetSelection, } @@ -241,7 +241,12 @@ impl Step for Cargotest { } fn make_run(run: RunConfig<'_>) { - run.builder.ensure(Cargotest { stage: run.builder.top_stage, host: run.target }); + // FIXME: support testing stage 0 cargo? + assert!(run.builder.top_stage > 0); + run.builder.ensure(Cargotest { + build_compiler: run.builder.compiler(run.builder.top_stage - 1, run.target), + host: run.target, + }); } /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler. @@ -249,9 +254,13 @@ impl Step for Cargotest { /// This tool in `src/tools` will check out a few Rust projects and run `cargo /// test` to ensure that we don't regress the test suites there. fn run(self, builder: &Builder<'_>) { - let compiler = builder.compiler(self.stage, self.host); - builder.ensure(compile::Rustc::new(compiler, compiler.host)); - let cargo = builder.ensure(tool::Cargo { compiler, target: compiler.host }); + // Here we need to ensure that we run cargo with an in-tree compiler, because we test + // both their behavior together. + // We can build cargo with the earlier stage compiler though. + let cargo = + builder.ensure(tool::Cargo { compiler: self.build_compiler, target: self.host }); + let tested_compiler = builder.compiler(self.build_compiler.stage + 1, self.host); + builder.std(tested_compiler, self.host); // Note that this is a short, cryptic, and not scoped directory name. This // is currently to minimize the length of path on Windows where we otherwise @@ -264,17 +273,21 @@ impl Step for Cargotest { cmd.arg(&cargo.tool_path) .arg(&out_dir) .args(builder.config.test_args()) - .env("RUSTC", builder.rustc(compiler)) - .env("RUSTDOC", builder.rustdoc_for_compiler(compiler)); + .env("RUSTC", builder.rustc(tested_compiler)) + .env("RUSTDOC", builder.rustdoc_for_compiler(tested_compiler)); add_rustdoc_cargo_linker_args( &mut cmd, builder, - compiler.host, + tested_compiler.host, LldThreads::No, - compiler.stage, + tested_compiler.stage, ); cmd.delay_failure().run(builder); } + + fn metadata(&self) -> Option { + Some(StepMetadata::test("cargotest", self.host).stage(self.build_compiler.stage + 1)) + } } /// Runs `cargo test` for cargo itself. diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 6bd5b16eabb3..1c82f804fd2b 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1599,6 +1599,23 @@ mod snapshot { steps.assert_contains_fuzzy(StepMetadata::build("rustc", host)); } + #[test] + fn test_cargotest() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("test") + .path("cargotest") + .render_steps(), @r" + [build] rustc 0 -> cargo 1 + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> std 1 + [build] rustc 0 -> CargoTest 1 + [build] rustdoc 1 + [test] cargotest 1 + "); + } + #[test] fn doc_library() { let ctx = TestCtx::new(); From 3e6aa8169115ed1f9a3474ab45284561a30d780a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 21 Jul 2025 18:06:49 +0200 Subject: [PATCH 0290/1134] Add snapshot tests for `test cargo` and update Cargo snapshot tests --- src/bootstrap/src/core/builder/tests.rs | 37 +++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 1c82f804fd2b..057f37847975 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1085,7 +1085,7 @@ mod snapshot { [dist] rustc [dist] rustc 1 -> std 1 [dist] src <> - [build] rustc 0 -> cargo 1 + [build] rustc 1 -> cargo 2 [build] rustc 1 -> rust-analyzer 2 [build] rustc 1 -> rustfmt 2 [build] rustc 1 -> cargo-fmt 2 @@ -1278,7 +1278,7 @@ mod snapshot { [dist] rustc [dist] rustc 1 -> std 1 [dist] src <> - [build] rustc 0 -> cargo 1 + [build] rustc 1 -> cargo 2 [build] rustc 1 -> rust-analyzer 2 [build] rustc 1 -> rustfmt 2 [build] rustc 1 -> cargo-fmt 2 @@ -1599,6 +1599,39 @@ mod snapshot { steps.assert_contains_fuzzy(StepMetadata::build("rustc", host)); } + #[test] + fn test_cargo_stage_1() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("test") + .path("cargo") + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> std 1 + [build] rustc 1 -> rustc 2 + [build] rustc 2 -> cargo 3 + [build] rustdoc 2 + "); + } + + #[test] + fn test_cargo_stage_2() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("test") + .path("cargo") + .stage(2) + .render_steps(), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> std 1 + [build] rustc 1 -> rustc 2 + [build] rustc 2 -> cargo 3 + [build] rustdoc 2 + "); + } + #[test] fn test_cargotest() { let ctx = TestCtx::new(); From 528e7dc9aec150250097e5918879023051f06249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 28 Jul 2025 15:01:14 +0200 Subject: [PATCH 0291/1134] Make build compiler explicit in `dist::Cargo` --- src/bootstrap/src/core/build_steps/dist.rs | 12 +++++------ src/bootstrap/src/core/build_steps/install.rs | 2 +- src/bootstrap/src/core/build_steps/test.rs | 6 +++--- src/bootstrap/src/core/build_steps/tool.rs | 21 ++++++++++++++----- 4 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 2d504cbd55af..0465a071159b 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -1173,7 +1173,7 @@ impl Step for PlainSourceTarball { #[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] pub struct Cargo { - pub compiler: Compiler, + pub build_compiler: Compiler, pub target: TargetSelection, } @@ -1189,7 +1189,7 @@ impl Step for Cargo { fn make_run(run: RunConfig<'_>) { run.builder.ensure(Cargo { - compiler: run.builder.compiler_for( + build_compiler: run.builder.compiler_for( run.builder.top_stage, run.builder.config.host_target, run.target, @@ -1199,12 +1199,10 @@ impl Step for Cargo { } fn run(self, builder: &Builder<'_>) -> Option { - let compiler = self.compiler; + let build_compiler = self.build_compiler; let target = self.target; - builder.ensure(compile::Rustc::new(compiler, target)); - - let cargo = builder.ensure(tool::Cargo { compiler, target }); + let cargo = builder.ensure(tool::Cargo::from_build_compiler(build_compiler, target)); let src = builder.src.join("src/tools/cargo"); let etc = src.join("src/etc"); @@ -1563,7 +1561,7 @@ impl Step for Extended { add_component!("rust-docs" => Docs { host: target }); add_component!("rust-json-docs" => JsonDocs { host: target }); - add_component!("cargo" => Cargo { compiler, target }); + add_component!("cargo" => Cargo { build_compiler: compiler, target }); add_component!("rustfmt" => Rustfmt { build_compiler: compiler, target }); add_component!("rust-analyzer" => RustAnalyzer { build_compiler: compiler, target }); add_component!("llvm-components" => LlvmTools { target }); diff --git a/src/bootstrap/src/core/build_steps/install.rs b/src/bootstrap/src/core/build_steps/install.rs index 2427b0191294..f628330e9ed4 100644 --- a/src/bootstrap/src/core/build_steps/install.rs +++ b/src/bootstrap/src/core/build_steps/install.rs @@ -215,7 +215,7 @@ install!((self, builder, _config), }; Cargo, alias = "cargo", Self::should_build(_config), only_hosts: true, { let tarball = builder - .ensure(dist::Cargo { compiler: self.compiler, target: self.target }) + .ensure(dist::Cargo { build_compiler: self.compiler, target: self.target }) .expect("missing cargo"); install_sh(builder, "cargo", self.compiler.stage, Some(self.target), &tarball); }; diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index e542ab7c1276..c5e18f610476 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -258,7 +258,7 @@ impl Step for Cargotest { // both their behavior together. // We can build cargo with the earlier stage compiler though. let cargo = - builder.ensure(tool::Cargo { compiler: self.build_compiler, target: self.host }); + builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host)); let tested_compiler = builder.compiler(self.build_compiler.stage + 1, self.host); builder.std(tested_compiler, self.host); @@ -332,7 +332,7 @@ impl Step for Cargo { let compiler = builder.compiler(stage, self.host); - let cargo = builder.ensure(tool::Cargo { compiler, target: self.host }); + let cargo = builder.ensure(tool::Cargo::from_build_compiler(compiler, self.host)); let compiler = cargo.build_compiler; let cargo = tool::prepare_tool_cargo( @@ -1751,7 +1751,7 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the // If we're using `--stage 0`, we should provide the bootstrap cargo. builder.initial_cargo.clone() } else { - builder.ensure(tool::Cargo { compiler, target: compiler.host }).tool_path + builder.ensure(tool::Cargo::from_build_compiler(compiler, compiler.host)).tool_path }; cmd.arg("--cargo-path").arg(cargo_path); diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index a2c7c8c65b06..0dc9002d4e41 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -806,8 +806,16 @@ impl Step for Rustdoc { /// Note that it can be built using a stable compiler. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Cargo { - pub compiler: Compiler, - pub target: TargetSelection, + build_compiler: Compiler, + target: TargetSelection, +} + +impl Cargo { + /// Returns `Cargo` that will be **compiled** by the passed compiler, for the given + /// `target`. + pub fn from_build_compiler(build_compiler: Compiler, target: TargetSelection) -> Self { + Self { build_compiler, target } + } } impl Step for Cargo { @@ -822,7 +830,10 @@ impl Step for Cargo { fn make_run(run: RunConfig<'_>) { run.builder.ensure(Cargo { - compiler: get_tool_target_compiler(run.builder, ToolTargetBuildMode::Build(run.target)), + build_compiler: get_tool_target_compiler( + run.builder, + ToolTargetBuildMode::Build(run.target), + ), target: run.target, }); } @@ -831,7 +842,7 @@ impl Step for Cargo { builder.build.require_submodule("src/tools/cargo", None); builder.ensure(ToolBuild { - build_compiler: self.compiler, + build_compiler: self.build_compiler, target: self.target, tool: "cargo", mode: Mode::ToolTarget, @@ -845,7 +856,7 @@ impl Step for Cargo { } fn metadata(&self) -> Option { - Some(StepMetadata::build("cargo", self.target).built_by(self.compiler)) + Some(StepMetadata::build("cargo", self.target).built_by(self.build_compiler)) } } From 1d1efed4d46531fc185887b7f3849501eb28ed24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 13:31:40 +0200 Subject: [PATCH 0292/1134] Fix `x test cargo` --- src/bootstrap/src/core/build_steps/test.rs | 47 ++++++++++------------ src/bootstrap/src/core/build_steps/tool.rs | 7 +++- src/bootstrap/src/core/builder/tests.rs | 13 ++---- 3 files changed, 31 insertions(+), 36 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index c5e18f610476..5a3859792c73 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -18,7 +18,8 @@ use crate::core::build_steps::llvm::get_llvm_version; use crate::core::build_steps::run::get_completion_paths; use crate::core::build_steps::synthetic_targets::MirOptPanicAbortSyntheticTarget; use crate::core::build_steps::tool::{ - self, COMPILETEST_ALLOW_FEATURES, RustcPrivateCompilers, SourceType, Tool, + self, COMPILETEST_ALLOW_FEATURES, RustcPrivateCompilers, SourceType, Tool, ToolTargetBuildMode, + get_tool_target_compiler, }; use crate::core::build_steps::toolstate::ToolState; use crate::core::build_steps::{compile, dist, llvm}; @@ -293,7 +294,7 @@ impl Step for Cargotest { /// Runs `cargo test` for cargo itself. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Cargo { - stage: u32, + build_compiler: Compiler, host: TargetSelection, } @@ -310,35 +311,29 @@ impl Step for Cargo { } fn make_run(run: RunConfig<'_>) { - // If stage is explicitly set or not lower than 2, keep it. Otherwise, make sure it's at least 2 - // as tests for this step don't work with a lower stage. - let stage = if run.builder.config.is_explicit_stage() || run.builder.top_stage >= 2 { - run.builder.top_stage - } else { - 2 - }; - - run.builder.ensure(Cargo { stage, host: run.target }); + run.builder.ensure(Cargo { + build_compiler: get_tool_target_compiler( + run.builder, + ToolTargetBuildMode::Build(run.target), + ), + host: run.target, + }); } /// Runs `cargo test` for `cargo` packaged with Rust. fn run(self, builder: &Builder<'_>) { - let stage = self.stage; - - if stage < 2 { - eprintln!("WARNING: cargo tests on stage {stage} may not behave well."); - eprintln!("HELP: consider using stage 2"); - } - - let compiler = builder.compiler(stage, self.host); - - let cargo = builder.ensure(tool::Cargo::from_build_compiler(compiler, self.host)); - let compiler = cargo.build_compiler; + // FIXME: we now use the same compiler to build cargo and then we also test that compiler + // using cargo. + // We could build cargo using a different compiler, but that complicates some things, + // because when we run cargo tests, the crates that are being compiled are accessing the + // sysroot of the build compiler, rather than the compiler being tested. + // Since these two compilers are currently the same, it works. + builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host)); let cargo = tool::prepare_tool_cargo( builder, - compiler, - Mode::ToolRustc, + self.build_compiler, + Mode::ToolTarget, self.host, Kind::Test, Self::CRATE_PATH, @@ -355,7 +350,7 @@ impl Step for Cargo { // Forcibly disable tests using nightly features since any changes to // those features won't be able to land. cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1"); - cargo.env("PATH", path_for_cargo(builder, compiler)); + cargo.env("PATH", path_for_cargo(builder, self.build_compiler)); // Cargo's test suite uses `CARGO_RUSTC_CURRENT_DIR` to determine the path that `file!` is // relative to. Cargo no longer sets this env var, so we have to do that. This has to be the // same value as `-Zroot-dir`. @@ -367,7 +362,7 @@ impl Step for Cargo { crates: vec!["cargo".into()], target: self.host.triple.to_string(), host: self.host.triple.to_string(), - stage, + stage: self.build_compiler.stage + 1, }, builder, ); diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 0dc9002d4e41..e3f49fa126ed 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -841,6 +841,7 @@ impl Step for Cargo { fn run(self, builder: &Builder<'_>) -> ToolBuildResult { builder.build.require_submodule("src/tools/cargo", None); + builder.std(self.build_compiler, self.target); builder.ensure(ToolBuild { build_compiler: self.build_compiler, target: self.target, @@ -849,7 +850,11 @@ impl Step for Cargo { path: "src/tools/cargo", source_type: SourceType::Submodule, extra_features: Vec::new(), - allow_features: "", + // Cargo is compilable with a stable compiler, but since we run in bootstrap, + // with RUSTC_BOOTSTRAP being set, some "clever" build scripts enable specialization + // based on this, which breaks stuff. We thus have to explicitly allow these features + // here. + allow_features: "min_specialization,specialization", cargo_args: Vec::new(), artifact_kind: ToolArtifactKind::Binary, }) diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 057f37847975..67ad60e308dd 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1606,12 +1606,8 @@ mod snapshot { ctx.config("test") .path("cargo") .render_steps(), @r" - [build] llvm - [build] rustc 0 -> rustc 1 - [build] rustc 1 -> std 1 - [build] rustc 1 -> rustc 2 - [build] rustc 2 -> cargo 3 - [build] rustdoc 2 + [build] rustc 0 -> cargo 1 + [build] rustdoc 0 "); } @@ -1626,9 +1622,8 @@ mod snapshot { [build] llvm [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 - [build] rustc 1 -> rustc 2 - [build] rustc 2 -> cargo 3 - [build] rustdoc 2 + [build] rustc 1 -> cargo 2 + [build] rustdoc 1 "); } From 47da0147716e01e6f70cd6a275b6e7251b27929f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 31 Jul 2025 08:38:54 +0200 Subject: [PATCH 0293/1134] Make `x test cargo` stage N test rustc stage N --- src/bootstrap/src/core/build_steps/test.rs | 53 ++++++++++++++++------ src/bootstrap/src/core/builder/tests.rs | 7 +++ 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 5a3859792c73..e8b9ac440f50 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -4,10 +4,12 @@ //! However, this contains ~all test parts we expect people to be able to build and run locally. use std::collections::HashSet; +use std::env::join_paths; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::{env, fs, iter}; +use build_helper::exit; #[cfg(feature = "tracing")] use tracing::instrument; @@ -242,8 +244,12 @@ impl Step for Cargotest { } fn make_run(run: RunConfig<'_>) { - // FIXME: support testing stage 0 cargo? - assert!(run.builder.top_stage > 0); + if run.builder.top_stage == 0 { + eprintln!( + "ERROR: running cargotest with stage 0 is currently unsupported. Use at least stage 1." + ); + exit!(1); + } run.builder.ensure(Cargotest { build_compiler: run.builder.compiler(run.builder.top_stage - 1, run.target), host: run.target, @@ -322,14 +328,18 @@ impl Step for Cargo { /// Runs `cargo test` for `cargo` packaged with Rust. fn run(self, builder: &Builder<'_>) { - // FIXME: we now use the same compiler to build cargo and then we also test that compiler - // using cargo. - // We could build cargo using a different compiler, but that complicates some things, - // because when we run cargo tests, the crates that are being compiled are accessing the - // sysroot of the build compiler, rather than the compiler being tested. - // Since these two compilers are currently the same, it works. + // When we do a "stage 1 cargo test", it means that we test the stage 1 rustc + // using stage 1 cargo. So we actually build cargo using the stage 0 compiler, and then + // run its tests against the stage 1 compiler (called `tested_compiler` below). builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host)); + let tested_compiler = builder.compiler(self.build_compiler.stage + 1, self.host); + builder.std(tested_compiler, self.host); + // We also need to build rustdoc for cargo tests + // It will be located in the bindir of `tested_compiler`, so we don't need to explicitly + // pass its path to Cargo. + builder.rustdoc_for_compiler(tested_compiler); + let cargo = tool::prepare_tool_cargo( builder, self.build_compiler, @@ -350,7 +360,27 @@ impl Step for Cargo { // Forcibly disable tests using nightly features since any changes to // those features won't be able to land. cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1"); - cargo.env("PATH", path_for_cargo(builder, self.build_compiler)); + + // Configure PATH to find the right rustc. NB. we have to use PATH + // and not RUSTC because the Cargo test suite has tests that will + // fail if rustc is not spelled `rustc`. + cargo.env("PATH", bin_path_for_cargo(builder, tested_compiler)); + + // The `cargo` command configured above has dylib dir path set to the `build_compiler`'s + // libdir. That causes issues in cargo test, because the programs that cargo compiles are + // incorrectly picking that libdir, even though they should be picking the + // `tested_compiler`'s libdir. We thus have to override the precedence here. + let existing_dylib_path = cargo + .get_envs() + .find(|(k, _)| *k == OsStr::new(dylib_path_var())) + .and_then(|(_, v)| v) + .unwrap_or(OsStr::new("")); + cargo.env( + dylib_path_var(), + join_paths([builder.rustc_libdir(tested_compiler).as_ref(), existing_dylib_path]) + .unwrap_or_default(), + ); + // Cargo's test suite uses `CARGO_RUSTC_CURRENT_DIR` to determine the path that `file!` is // relative to. Cargo no longer sets this env var, so we have to do that. This has to be the // same value as `-Zroot-dir`. @@ -859,10 +889,7 @@ impl Step for Clippy { } } -fn path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString { - // Configure PATH to find the right rustc. NB. we have to use PATH - // and not RUSTC because the Cargo test suite has tests that will - // fail if rustc is not spelled `rustc`. +fn bin_path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString { let path = builder.sysroot(compiler).join("bin"); let old_path = env::var_os("PATH").unwrap_or_default(); env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("") diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 67ad60e308dd..139ddc9ed249 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1607,6 +1607,10 @@ mod snapshot { .path("cargo") .render_steps(), @r" [build] rustc 0 -> cargo 1 + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 1 -> std 1 + [build] rustdoc 1 [build] rustdoc 0 "); } @@ -1623,6 +1627,9 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 [build] rustc 1 -> cargo 2 + [build] rustc 1 -> rustc 2 + [build] rustc 2 -> std 2 + [build] rustdoc 2 [build] rustdoc 1 "); } From c46f42d239a67ec1e45fe70e8f791fb47423bbf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 1 Aug 2025 13:24:34 +0200 Subject: [PATCH 0294/1134] Clarify comments on Cargo (self-)test steps --- src/bootstrap/src/core/build_steps/test.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index e8b9ac440f50..218a6f563e4f 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -250,6 +250,9 @@ impl Step for Cargotest { ); exit!(1); } + // We want to build cargo stage N (where N == top_stage), and rustc stage N, + // and test both of these together. + // So we need to get a build compiler stage N-1 to build the stage N components. run.builder.ensure(Cargotest { build_compiler: run.builder.compiler(run.builder.top_stage - 1, run.target), host: run.target, @@ -261,9 +264,15 @@ impl Step for Cargotest { /// This tool in `src/tools` will check out a few Rust projects and run `cargo /// test` to ensure that we don't regress the test suites there. fn run(self, builder: &Builder<'_>) { - // Here we need to ensure that we run cargo with an in-tree compiler, because we test - // both their behavior together. - // We can build cargo with the earlier stage compiler though. + // cargotest's staging has several pieces: + // consider ./x test cargotest --stage=2. + // + // The test goal is to exercise a (stage 2 cargo, stage 2 rustc) pair through a stage 2 + // cargotest tool. + // To produce the stage 2 cargo and cargotest, we need to do so with the stage 1 rustc and std. + // Importantly, the stage 2 rustc being tested (`tested_compiler`) via stage 2 cargotest is + // the rustc built by an earlier stage 1 rustc (the build_compiler). These are two different + // compilers! let cargo = builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host)); let tested_compiler = builder.compiler(self.build_compiler.stage + 1, self.host); @@ -298,6 +307,7 @@ impl Step for Cargotest { } /// Runs `cargo test` for cargo itself. +/// We label these tests as "cargo self-tests". #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Cargo { build_compiler: Compiler, @@ -328,7 +338,7 @@ impl Step for Cargo { /// Runs `cargo test` for `cargo` packaged with Rust. fn run(self, builder: &Builder<'_>) { - // When we do a "stage 1 cargo test", it means that we test the stage 1 rustc + // When we do a "stage 1 cargo self-test", it means that we test the stage 1 rustc // using stage 1 cargo. So we actually build cargo using the stage 0 compiler, and then // run its tests against the stage 1 compiler (called `tested_compiler` below). builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host)); From ba57bbadc9744686c3e6c17422ad7d392119a028 Mon Sep 17 00:00:00 2001 From: lcnr Date: Fri, 1 Aug 2025 15:49:36 +0200 Subject: [PATCH 0295/1134] rarw --- src/doc/rustc-dev-guide/src/solve/candidate-preference.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/src/solve/candidate-preference.md b/src/doc/rustc-dev-guide/src/solve/candidate-preference.md index af066415a719..896052947353 100644 --- a/src/doc/rustc-dev-guide/src/solve/candidate-preference.md +++ b/src/doc/rustc-dev-guide/src/solve/candidate-preference.md @@ -94,7 +94,7 @@ fn overflow() { } ``` -This preference causes a lot of issues. See https://github.com/rust-lang/rust/issues/24066. Most of the +This preference causes a lot of issues. See [#24066]. Most of the issues are caused by prefering where-bounds over impls even if the where-bound guides type inference: ```rust trait Trait { @@ -423,4 +423,5 @@ where [`fn merge_trait_candidates`]: https://github.com/rust-lang/rust/blob/e3ee7f7aea5b45af3b42b5e4713da43876a65ac9/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs#L1342-L1424 [`fn assemble_and_merge_candidates`]: https://github.com/rust-lang/rust/blob/e3ee7f7aea5b45af3b42b5e4713da43876a65ac9/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs#L920-L1003 [trait-system-refactor-initiative#76]: https://github.com/rust-lang/trait-system-refactor-initiative/issues/76 +[#24066]: https://github.com/rust-lang/rust/issues/24066 [#133044]: https://github.com/rust-lang/rust/issues/133044 \ No newline at end of file From d5ffb061e1448d4ef28033718527f8f6c0dc2794 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 31 Jul 2025 21:09:49 +0300 Subject: [PATCH 0296/1134] compiletest: Improve diagnostics for line annotation mismatches 2 --- src/tools/compiletest/src/runtest.rs | 37 ++++++++++++++-------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index f66d4f98f1f2..ba7fcadbc2e5 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -765,12 +765,6 @@ impl<'test> TestCx<'test> { } if !unexpected.is_empty() || !not_found.is_empty() { - self.error(&format!( - "{} unexpected diagnostics reported, {} expected diagnostics not reported", - unexpected.len(), - not_found.len() - )); - // Emit locations in a format that is short (relative paths) but "clickable" in editors. // Also normalize path separators to `/`. let file_name = self @@ -794,19 +788,20 @@ impl<'test> TestCx<'test> { |suggestions: &mut Vec<_>, e: &Error, kind, line, msg, color, rank| { let mut ret = String::new(); if kind { - ret += &format!("{} {}", "with kind".color(color), e.kind); + ret += &format!("{} {}", "with different kind:".color(color), e.kind); } if line { if !ret.is_empty() { ret.push(' '); } - ret += &format!("{} {}", "on line".color(color), line_str(e)); + ret += &format!("{} {}", "on different line:".color(color), line_str(e)); } if msg { if !ret.is_empty() { ret.push(' '); } - ret += &format!("{} {}", "with message".color(color), e.msg.cyan()); + ret += + &format!("{} {}", "with different message:".color(color), e.msg.cyan()); } suggestions.push((ret, rank)); }; @@ -829,17 +824,20 @@ impl<'test> TestCx<'test> { // - only known line - meh, but suggested // - others are not worth suggesting if !unexpected.is_empty() { - let header = "--- reported in JSON output but not expected in test file ---"; - println!("{}", header.green()); + self.error(&format!( + "{} diagnostics reported in JSON output but not expected in test file", + unexpected.len(), + )); for error in &unexpected { print_error(error); let mut suggestions = Vec::new(); for candidate in ¬_found { + let kind_mismatch = candidate.kind != error.kind; let mut push_red_suggestion = |line, msg, rank| { push_suggestion( &mut suggestions, candidate, - candidate.kind != error.kind, + kind_mismatch, line, msg, Color::Red, @@ -851,26 +849,28 @@ impl<'test> TestCx<'test> { } else if candidate.line_num.is_some() && candidate.line_num == error.line_num { - push_red_suggestion(false, true, 1); + push_red_suggestion(false, true, if kind_mismatch { 2 } else { 1 }); } } show_suggestions(suggestions, "expected", Color::Red); } - println!("{}", "---".green()); } if !not_found.is_empty() { - let header = "--- expected in test file but not reported in JSON output ---"; - println!("{}", header.red()); + self.error(&format!( + "{} diagnostics expected in test file but not reported in JSON output", + not_found.len() + )); for error in ¬_found { print_error(error); let mut suggestions = Vec::new(); for candidate in unexpected.iter().chain(&unimportant) { + let kind_mismatch = candidate.kind != error.kind; let mut push_green_suggestion = |line, msg, rank| { push_suggestion( &mut suggestions, candidate, - candidate.kind != error.kind, + kind_mismatch, line, msg, Color::Green, @@ -882,13 +882,12 @@ impl<'test> TestCx<'test> { } else if candidate.line_num.is_some() && candidate.line_num == error.line_num { - push_green_suggestion(false, true, 1); + push_green_suggestion(false, true, if kind_mismatch { 2 } else { 1 }); } } show_suggestions(suggestions, "reported", Color::Green); } - println!("{}", "---".red()); } panic!( "errors differ from expected\nstatus: {}\ncommand: {}\n", From 8a2a9db29eca4468eb1ccf58183b01fe61d00120 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Fri, 1 Aug 2025 10:40:19 -0400 Subject: [PATCH 0297/1134] Fix LTO errors by not adding AlwaysInline to __rust_alloc_error_handler_should_panic_v2 --- src/allocator.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/allocator.rs b/src/allocator.rs index 66258390d909..2a95a7368aac 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -104,7 +104,8 @@ fn create_const_value_function( tcx.sess.default_visibility(), ))); - func.add_attribute(FnAttribute::AlwaysInline); + // FIXME(antoyo): cg_llvm sets AlwaysInline, but AlwaysInline is different in GCC and using + // it here will causes linking errors when using LTO. func.add_attribute(FnAttribute::Inline); } From f95edbee8ba8aa25571496b0e1270f88a193c09d Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 11:34:04 +0530 Subject: [PATCH 0298/1134] move gcc config parsing to parse_inner --- src/bootstrap/src/core/config/config.rs | 10 +++++++++- src/bootstrap/src/core/config/toml/gcc.rs | 20 ++------------------ 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 6055876c4757..54a73f934706 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -979,7 +979,15 @@ impl Config { config.apply_llvm_config(toml.llvm); - config.apply_gcc_config(toml.gcc); + if let Some(gcc) = toml.gcc { + config.gcc_ci_mode = match gcc.download_ci_gcc { + Some(value) => match value { + true => GccCiMode::DownloadFromCi, + false => GccCiMode::BuildLocally, + }, + None => GccCiMode::default(), + }; + } match ccache { Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()), diff --git a/src/bootstrap/src/core/config/toml/gcc.rs b/src/bootstrap/src/core/config/toml/gcc.rs index bb817c2aaef8..de061309c804 100644 --- a/src/bootstrap/src/core/config/toml/gcc.rs +++ b/src/bootstrap/src/core/config/toml/gcc.rs @@ -6,9 +6,9 @@ use serde::{Deserialize, Deserializer}; +use crate::core::config::Merge; use crate::core::config::toml::ReplaceOpt; -use crate::core::config::{GccCiMode, Merge}; -use crate::{Config, HashSet, PathBuf, define_config, exit}; +use crate::{HashSet, PathBuf, define_config, exit}; define_config! { /// TOML representation of how the GCC build is configured. @@ -16,19 +16,3 @@ define_config! { download_ci_gcc: Option = "download-ci-gcc", } } - -impl Config { - /// Applies GCC-related configuration from the `TomlGcc` struct to the - /// global `Config` structure. - pub fn apply_gcc_config(&mut self, toml_gcc: Option) { - if let Some(gcc) = toml_gcc { - self.gcc_ci_mode = match gcc.download_ci_gcc { - Some(value) => match value { - true => GccCiMode::DownloadFromCi, - false => GccCiMode::BuildLocally, - }, - None => GccCiMode::default(), - }; - } - } -} From 3f9bf57cf2350867e9bbb66e515801d5cc735492 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 11:36:32 +0530 Subject: [PATCH 0299/1134] move dist to parse_inner --- src/bootstrap/src/core/config/config.rs | 24 +++++++++++++++- src/bootstrap/src/core/config/toml/dist.rs | 32 ++-------------------- 2 files changed, 25 insertions(+), 31 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 54a73f934706..62c528538c48 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -37,6 +37,7 @@ use crate::core::config::target_selection::TargetSelectionList; use crate::core::config::toml::TomlConfig; use crate::core::config::toml::build::{Build, Tool}; use crate::core::config::toml::change_id::ChangeId; +use crate::core::config::toml::dist::Dist; use crate::core::config::toml::rust::{ LldMode, RustOptimize, check_incompatible_options_for_ci_rustc, }; @@ -1013,7 +1014,28 @@ impl Config { Some(ci_llvm_bin.join(exe("FileCheck", config.host_target))); } - config.apply_dist_config(toml.dist); + if let Some(dist) = toml.dist { + let Dist { + sign_folder, + upload_addr, + src_tarball, + compression_formats, + compression_profile, + include_mingw_linker, + vendor, + } = dist; + config.dist_sign_folder = sign_folder.map(PathBuf::from); + config.dist_upload_addr = upload_addr; + config.dist_compression_formats = compression_formats; + set(&mut config.dist_compression_profile, compression_profile); + set(&mut config.rust_dist_src, src_tarball); + set(&mut config.dist_include_mingw_linker, include_mingw_linker); + config.dist_vendor = vendor.unwrap_or_else(|| { + // If we're building from git or tarball sources, enable it by default. + config.rust_info.is_managed_git_subrepository() + || config.rust_info.is_from_tarball() + }); + } config.initial_rustfmt = if let Some(r) = rustfmt { Some(r) diff --git a/src/bootstrap/src/core/config/toml/dist.rs b/src/bootstrap/src/core/config/toml/dist.rs index b1429ef18617..4ab18762bb05 100644 --- a/src/bootstrap/src/core/config/toml/dist.rs +++ b/src/bootstrap/src/core/config/toml/dist.rs @@ -7,9 +7,9 @@ use serde::{Deserialize, Deserializer}; +use crate::core::config::Merge; use crate::core::config::toml::ReplaceOpt; -use crate::core::config::{Merge, set}; -use crate::{Config, HashSet, PathBuf, define_config, exit}; +use crate::{HashSet, PathBuf, define_config, exit}; define_config! { struct Dist { @@ -22,31 +22,3 @@ define_config! { vendor: Option = "vendor", } } - -impl Config { - /// Applies distribution-related configuration from the `Dist` struct - /// to the global `Config` structure. - pub fn apply_dist_config(&mut self, toml_dist: Option) { - if let Some(dist) = toml_dist { - let Dist { - sign_folder, - upload_addr, - src_tarball, - compression_formats, - compression_profile, - include_mingw_linker, - vendor, - } = dist; - self.dist_sign_folder = sign_folder.map(PathBuf::from); - self.dist_upload_addr = upload_addr; - self.dist_compression_formats = compression_formats; - set(&mut self.dist_compression_profile, compression_profile); - set(&mut self.rust_dist_src, src_tarball); - set(&mut self.dist_include_mingw_linker, include_mingw_linker); - self.dist_vendor = vendor.unwrap_or_else(|| { - // If we're building from git or tarball sources, enable it by default. - self.rust_info.is_managed_git_subrepository() || self.rust_info.is_from_tarball() - }); - } - } -} From 924912c5322274419383cbb6e7209bfe82b3e7bd Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 11:46:00 +0530 Subject: [PATCH 0300/1134] move target parsing to parse_inner --- src/bootstrap/src/core/config/config.rs | 65 +++++++++++++++++- src/bootstrap/src/core/config/toml/target.rs | 70 +------------------- 2 files changed, 64 insertions(+), 71 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 62c528538c48..8a6d90fa0b5a 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -39,7 +39,7 @@ use crate::core::config::toml::build::{Build, Tool}; use crate::core::config::toml::change_id::ChangeId; use crate::core::config::toml::dist::Dist; use crate::core::config::toml::rust::{ - LldMode, RustOptimize, check_incompatible_options_for_ci_rustc, + LldMode, RustOptimize, check_incompatible_options_for_ci_rustc, validate_codegen_backends, }; use crate::core::config::toml::target::Target; use crate::core::config::{ @@ -956,7 +956,68 @@ impl Config { config.rust_profile_use = flags_rust_profile_use; config.rust_profile_generate = flags_rust_profile_generate; - config.apply_target_config(toml.target); + if let Some(t) = toml.target { + for (triple, cfg) in t { + let mut target = Target::from_triple(&triple); + + if let Some(ref s) = cfg.llvm_config { + if config.download_rustc_commit.is_some() + && triple == *config.host_target.triple + { + panic!( + "setting llvm_config for the host is incompatible with download-rustc" + ); + } + target.llvm_config = Some(config.src.join(s)); + } + if let Some(patches) = cfg.llvm_has_rust_patches { + assert!( + config.submodules == Some(false) || cfg.llvm_config.is_some(), + "use of `llvm-has-rust-patches` is restricted to cases where either submodules are disabled or llvm-config been provided" + ); + target.llvm_has_rust_patches = Some(patches); + } + if let Some(ref s) = cfg.llvm_filecheck { + target.llvm_filecheck = Some(config.src.join(s)); + } + target.llvm_libunwind = cfg.llvm_libunwind.as_ref().map(|v| { + v.parse().unwrap_or_else(|_| { + panic!("failed to parse target.{triple}.llvm-libunwind") + }) + }); + if let Some(s) = cfg.no_std { + target.no_std = s; + } + target.cc = cfg.cc.map(PathBuf::from); + target.cxx = cfg.cxx.map(PathBuf::from); + target.ar = cfg.ar.map(PathBuf::from); + target.ranlib = cfg.ranlib.map(PathBuf::from); + target.linker = cfg.linker.map(PathBuf::from); + target.crt_static = cfg.crt_static; + target.musl_root = cfg.musl_root.map(PathBuf::from); + target.musl_libdir = cfg.musl_libdir.map(PathBuf::from); + target.wasi_root = cfg.wasi_root.map(PathBuf::from); + target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from); + target.runner = cfg.runner; + target.sanitizers = cfg.sanitizers; + target.profiler = cfg.profiler; + target.rpath = cfg.rpath; + target.optimized_compiler_builtins = cfg.optimized_compiler_builtins; + target.jemalloc = cfg.jemalloc; + if let Some(backends) = cfg.codegen_backends { + target.codegen_backends = + Some(validate_codegen_backends(backends, &format!("target.{triple}"))) + } + + target.split_debuginfo = cfg.split_debuginfo.as_ref().map(|v| { + v.parse().unwrap_or_else(|_| { + panic!("invalid value for target.{triple}.split-debuginfo") + }) + }); + + config.target_config.insert(TargetSelection::from_user(&triple), target); + } + } config.apply_rust_config(toml.rust, flags_warnings); config.reproducible_artifacts = flags_reproducible_artifact; diff --git a/src/bootstrap/src/core/config/toml/target.rs b/src/bootstrap/src/core/config/toml/target.rs index 9dedadff3a19..0c9d2bd0ab5f 100644 --- a/src/bootstrap/src/core/config/toml/target.rs +++ b/src/bootstrap/src/core/config/toml/target.rs @@ -12,13 +12,10 @@ //! applies it to the global [`Config`], ensuring proper path resolution, validation, //! and integration with other build settings. -use std::collections::HashMap; - use serde::{Deserialize, Deserializer}; -use crate::core::config::toml::rust::parse_codegen_backends; use crate::core::config::{LlvmLibunwind, Merge, ReplaceOpt, SplitDebuginfo, StringOrBool}; -use crate::{CodegenBackendKind, Config, HashSet, PathBuf, TargetSelection, define_config, exit}; +use crate::{HashSet, PathBuf, define_config, exit}; define_config! { /// TOML representation of how each build target is configured. @@ -93,68 +90,3 @@ impl Target { target } } - -impl Config { - pub fn apply_target_config(&mut self, toml_target: Option>) { - if let Some(t) = toml_target { - for (triple, cfg) in t { - let mut target = Target::from_triple(&triple); - - if let Some(ref s) = cfg.llvm_config { - if self.download_rustc_commit.is_some() && triple == *self.host_target.triple { - panic!( - "setting llvm_config for the host is incompatible with download-rustc" - ); - } - target.llvm_config = Some(self.src.join(s)); - } - if let Some(patches) = cfg.llvm_has_rust_patches { - assert!( - self.submodules == Some(false) || cfg.llvm_config.is_some(), - "use of `llvm-has-rust-patches` is restricted to cases where either submodules are disabled or llvm-config been provided" - ); - target.llvm_has_rust_patches = Some(patches); - } - if let Some(ref s) = cfg.llvm_filecheck { - target.llvm_filecheck = Some(self.src.join(s)); - } - target.llvm_libunwind = cfg.llvm_libunwind.as_ref().map(|v| { - v.parse().unwrap_or_else(|_| { - panic!("failed to parse target.{triple}.llvm-libunwind") - }) - }); - if let Some(s) = cfg.no_std { - target.no_std = s; - } - target.cc = cfg.cc.map(PathBuf::from); - target.cxx = cfg.cxx.map(PathBuf::from); - target.ar = cfg.ar.map(PathBuf::from); - target.ranlib = cfg.ranlib.map(PathBuf::from); - target.linker = cfg.linker.map(PathBuf::from); - target.crt_static = cfg.crt_static; - target.musl_root = cfg.musl_root.map(PathBuf::from); - target.musl_libdir = cfg.musl_libdir.map(PathBuf::from); - target.wasi_root = cfg.wasi_root.map(PathBuf::from); - target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from); - target.runner = cfg.runner; - target.sanitizers = cfg.sanitizers; - target.profiler = cfg.profiler; - target.rpath = cfg.rpath; - target.optimized_compiler_builtins = cfg.optimized_compiler_builtins; - target.jemalloc = cfg.jemalloc; - if let Some(backends) = cfg.codegen_backends { - target.codegen_backends = - Some(parse_codegen_backends(backends, &format!("target.{triple}"))) - } - - target.split_debuginfo = cfg.split_debuginfo.as_ref().map(|v| { - v.parse().unwrap_or_else(|_| { - panic!("invalid value for target.{triple}.split-debuginfo") - }) - }); - - self.target_config.insert(TargetSelection::from_user(&triple), target); - } - } - } -} From 89219ffc0e870398b38b398001190ab7d6082119 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 12:01:44 +0530 Subject: [PATCH 0301/1134] move install to parse_inner --- src/bootstrap/src/core/config/config.rs | 12 ++++++++++- src/bootstrap/src/core/config/toml/install.rs | 21 ++----------------- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 8a6d90fa0b5a..a7cdc84977a2 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -38,6 +38,7 @@ use crate::core::config::toml::TomlConfig; use crate::core::config::toml::build::{Build, Tool}; use crate::core::config::toml::change_id::ChangeId; use crate::core::config::toml::dist::Dist; +use crate::core::config::toml::install::Install; use crate::core::config::toml::rust::{ LldMode, RustOptimize, check_incompatible_options_for_ci_rustc, validate_codegen_backends, }; @@ -906,7 +907,16 @@ impl Config { // Verbose flag is a good default for `rust.verbose-tests`. config.verbose_tests = config.is_verbose(); - config.apply_install_config(toml.install); + if let Some(install) = toml.install { + let Install { prefix, sysconfdir, docdir, bindir, libdir, mandir, datadir } = install; + config.prefix = prefix.map(PathBuf::from); + config.sysconfdir = sysconfdir.map(PathBuf::from); + config.datadir = datadir.map(PathBuf::from); + config.docdir = docdir.map(PathBuf::from); + set(&mut config.bindir, bindir.map(PathBuf::from)); + config.libdir = libdir.map(PathBuf::from); + config.mandir = mandir.map(PathBuf::from); + } let file_content = t!(fs::read_to_string(config.src.join("src/ci/channel"))); let ci_channel = file_content.trim_end(); diff --git a/src/bootstrap/src/core/config/toml/install.rs b/src/bootstrap/src/core/config/toml/install.rs index 6b9ab87a0b66..da31c0cc878c 100644 --- a/src/bootstrap/src/core/config/toml/install.rs +++ b/src/bootstrap/src/core/config/toml/install.rs @@ -8,9 +8,9 @@ use serde::{Deserialize, Deserializer}; +use crate::core::config::Merge; use crate::core::config::toml::ReplaceOpt; -use crate::core::config::{Merge, set}; -use crate::{Config, HashSet, PathBuf, define_config, exit}; +use crate::{HashSet, PathBuf, define_config, exit}; define_config! { /// TOML representation of various global install decisions. @@ -24,20 +24,3 @@ define_config! { datadir: Option = "datadir", } } - -impl Config { - /// Applies installation-related configuration from the `Install` struct - /// to the global `Config` structure. - pub fn apply_install_config(&mut self, toml_install: Option) { - if let Some(install) = toml_install { - let Install { prefix, sysconfdir, docdir, bindir, libdir, mandir, datadir } = install; - self.prefix = prefix.map(PathBuf::from); - self.sysconfdir = sysconfdir.map(PathBuf::from); - self.datadir = datadir.map(PathBuf::from); - self.docdir = docdir.map(PathBuf::from); - set(&mut self.bindir, bindir.map(PathBuf::from)); - self.libdir = libdir.map(PathBuf::from); - self.mandir = mandir.map(PathBuf::from); - } - } -} From 3248ff1f06927116f23262eeef0bbd04e7dfc737 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 12:24:30 +0530 Subject: [PATCH 0302/1134] move llvm parsing to parse_inner --- src/bootstrap/src/core/config/config.rs | 122 +++++++++++++++++++- src/bootstrap/src/core/config/toml/llvm.rs | 128 +-------------------- 2 files changed, 123 insertions(+), 127 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index a7cdc84977a2..bb1185f859ab 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -39,6 +39,7 @@ use crate::core::config::toml::build::{Build, Tool}; use crate::core::config::toml::change_id::ChangeId; use crate::core::config::toml::dist::Dist; use crate::core::config::toml::install::Install; +use crate::core::config::toml::llvm::Llvm; use crate::core::config::toml::rust::{ LldMode, RustOptimize, check_incompatible_options_for_ci_rustc, validate_codegen_backends, }; @@ -1049,7 +1050,126 @@ impl Config { config.channel = channel; } - config.apply_llvm_config(toml.llvm); + let mut llvm_tests = None; + let mut llvm_enzyme = None; + let mut llvm_offload = None; + let mut llvm_plugins = None; + + if let Some(llvm) = toml.llvm { + let Llvm { + optimize: optimize_toml, + thin_lto, + release_debuginfo, + assertions: _, + tests, + enzyme, + plugins, + static_libstdcpp, + libzstd, + ninja, + targets, + experimental_targets, + link_jobs, + link_shared, + version_suffix, + clang_cl, + cflags, + cxxflags, + ldflags, + use_libcxx, + use_linker, + allow_old_toolchain, + offload, + polly, + clang, + enable_warnings, + download_ci_llvm, + build_config, + } = llvm; + + set(&mut config.ninja_in_file, ninja); + llvm_tests = tests; + llvm_enzyme = enzyme; + llvm_offload = offload; + llvm_plugins = plugins; + set(&mut config.llvm_optimize, optimize_toml); + set(&mut config.llvm_thin_lto, thin_lto); + set(&mut config.llvm_release_debuginfo, release_debuginfo); + set(&mut config.llvm_static_stdcpp, static_libstdcpp); + set(&mut config.llvm_libzstd, libzstd); + if let Some(v) = link_shared { + config.llvm_link_shared.set(Some(v)); + } + config.llvm_targets.clone_from(&targets); + config.llvm_experimental_targets.clone_from(&experimental_targets); + config.llvm_link_jobs = link_jobs; + config.llvm_version_suffix.clone_from(&version_suffix); + config.llvm_clang_cl.clone_from(&clang_cl); + + config.llvm_cflags.clone_from(&cflags); + config.llvm_cxxflags.clone_from(&cxxflags); + config.llvm_ldflags.clone_from(&ldflags); + set(&mut config.llvm_use_libcxx, use_libcxx); + config.llvm_use_linker.clone_from(&use_linker); + config.llvm_allow_old_toolchain = allow_old_toolchain.unwrap_or(false); + config.llvm_offload = offload.unwrap_or(false); + config.llvm_polly = polly.unwrap_or(false); + config.llvm_clang = clang.unwrap_or(false); + config.llvm_enable_warnings = enable_warnings.unwrap_or(false); + config.llvm_build_config = build_config.clone().unwrap_or(Default::default()); + + config.llvm_from_ci = + config.parse_download_ci_llvm(download_ci_llvm, config.llvm_assertions); + + if config.llvm_from_ci { + let warn = |option: &str| { + println!( + "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build." + ); + println!( + "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false." + ); + }; + + if static_libstdcpp.is_some() { + warn("static-libstdcpp"); + } + + if link_shared.is_some() { + warn("link-shared"); + } + + // FIXME(#129153): instead of all the ad-hoc `download-ci-llvm` checks that follow, + // use the `builder-config` present in tarballs since #128822 to compare the local + // config to the ones used to build the LLVM artifacts on CI, and only notify users + // if they've chosen a different value. + + if libzstd.is_some() { + println!( + "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \ + like almost all `llvm.*` options, will be ignored and set by the LLVM CI \ + artifacts builder config." + ); + println!( + "HELP: To use `llvm.libzstd` for LLVM/LLD builds, set `download-ci-llvm` option to false." + ); + } + } + + if !config.llvm_from_ci && config.llvm_thin_lto && link_shared.is_none() { + // If we're building with ThinLTO on, by default we want to link + // to LLVM shared, to avoid re-doing ThinLTO (which happens in + // the link step) with each stage. + config.llvm_link_shared.set(Some(true)); + } + } else { + config.llvm_from_ci = config.parse_download_ci_llvm(None, false); + } + + config.llvm_tests = llvm_tests.unwrap_or(false); + config.llvm_enzyme = llvm_enzyme.unwrap_or(false); + config.llvm_offload = llvm_offload.unwrap_or(false); + config.llvm_plugins = llvm_plugins.unwrap_or(false); if let Some(gcc) = toml.gcc { config.gcc_ci_mode = match gcc.download_ci_gcc { diff --git a/src/bootstrap/src/core/config/toml/llvm.rs b/src/bootstrap/src/core/config/toml/llvm.rs index 1f0cecd145c7..0ab290b9bd1e 100644 --- a/src/bootstrap/src/core/config/toml/llvm.rs +++ b/src/bootstrap/src/core/config/toml/llvm.rs @@ -3,9 +3,9 @@ use serde::{Deserialize, Deserializer}; +use crate::core::config::StringOrBool; use crate::core::config::toml::{Merge, ReplaceOpt, TomlConfig}; -use crate::core::config::{StringOrBool, set}; -use crate::{Config, HashMap, HashSet, PathBuf, define_config, exit}; +use crate::{HashMap, HashSet, PathBuf, define_config, exit}; define_config! { /// TOML representation of how the LLVM build is configured. @@ -144,127 +144,3 @@ pub fn check_incompatible_options_for_ci_llvm( Ok(()) } - -impl Config { - pub fn apply_llvm_config(&mut self, toml_llvm: Option) { - let mut llvm_tests = None; - let mut llvm_enzyme = None; - let mut llvm_offload = None; - let mut llvm_plugins = None; - - if let Some(llvm) = toml_llvm { - let Llvm { - optimize: optimize_toml, - thin_lto, - release_debuginfo, - assertions: _, - tests, - enzyme, - plugins, - static_libstdcpp, - libzstd, - ninja, - targets, - experimental_targets, - link_jobs, - link_shared, - version_suffix, - clang_cl, - cflags, - cxxflags, - ldflags, - use_libcxx, - use_linker, - allow_old_toolchain, - offload, - polly, - clang, - enable_warnings, - download_ci_llvm, - build_config, - } = llvm; - - set(&mut self.ninja_in_file, ninja); - llvm_tests = tests; - llvm_enzyme = enzyme; - llvm_offload = offload; - llvm_plugins = plugins; - set(&mut self.llvm_optimize, optimize_toml); - set(&mut self.llvm_thin_lto, thin_lto); - set(&mut self.llvm_release_debuginfo, release_debuginfo); - set(&mut self.llvm_static_stdcpp, static_libstdcpp); - set(&mut self.llvm_libzstd, libzstd); - if let Some(v) = link_shared { - self.llvm_link_shared.set(Some(v)); - } - self.llvm_targets.clone_from(&targets); - self.llvm_experimental_targets.clone_from(&experimental_targets); - self.llvm_link_jobs = link_jobs; - self.llvm_version_suffix.clone_from(&version_suffix); - self.llvm_clang_cl.clone_from(&clang_cl); - - self.llvm_cflags.clone_from(&cflags); - self.llvm_cxxflags.clone_from(&cxxflags); - self.llvm_ldflags.clone_from(&ldflags); - set(&mut self.llvm_use_libcxx, use_libcxx); - self.llvm_use_linker.clone_from(&use_linker); - self.llvm_allow_old_toolchain = allow_old_toolchain.unwrap_or(false); - self.llvm_offload = offload.unwrap_or(false); - self.llvm_polly = polly.unwrap_or(false); - self.llvm_clang = clang.unwrap_or(false); - self.llvm_enable_warnings = enable_warnings.unwrap_or(false); - self.llvm_build_config = build_config.clone().unwrap_or(Default::default()); - - self.llvm_from_ci = self.parse_download_ci_llvm(download_ci_llvm, self.llvm_assertions); - - if self.llvm_from_ci { - let warn = |option: &str| { - println!( - "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build." - ); - println!( - "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false." - ); - }; - - if static_libstdcpp.is_some() { - warn("static-libstdcpp"); - } - - if link_shared.is_some() { - warn("link-shared"); - } - - // FIXME(#129153): instead of all the ad-hoc `download-ci-llvm` checks that follow, - // use the `builder-config` present in tarballs since #128822 to compare the local - // config to the ones used to build the LLVM artifacts on CI, and only notify users - // if they've chosen a different value. - - if libzstd.is_some() { - println!( - "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \ - like almost all `llvm.*` options, will be ignored and set by the LLVM CI \ - artifacts builder config." - ); - println!( - "HELP: To use `llvm.libzstd` for LLVM/LLD builds, set `download-ci-llvm` option to false." - ); - } - } - - if !self.llvm_from_ci && self.llvm_thin_lto && link_shared.is_none() { - // If we're building with ThinLTO on, by default we want to link - // to LLVM shared, to avoid re-doing ThinLTO (which happens in - // the link step) with each stage. - self.llvm_link_shared.set(Some(true)); - } - } else { - self.llvm_from_ci = self.parse_download_ci_llvm(None, false); - } - - self.llvm_tests = llvm_tests.unwrap_or(false); - self.llvm_enzyme = llvm_enzyme.unwrap_or(false); - self.llvm_offload = llvm_offload.unwrap_or(false); - self.llvm_plugins = llvm_plugins.unwrap_or(false); - } -} From ddd2a547b2115684c77e1735cca2122d20075e98 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 12:31:06 +0530 Subject: [PATCH 0303/1134] move rust config to parse_inner --- src/bootstrap/src/core/config/config.rs | 250 +++++++++++++++++++- src/bootstrap/src/core/config/toml/rust.rs | 262 +-------------------- 2 files changed, 251 insertions(+), 261 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index bb1185f859ab..b66a9db1336c 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -32,7 +32,7 @@ use tracing::{instrument, span}; use crate::core::build_steps::llvm; use crate::core::build_steps::llvm::LLVM_INVALIDATION_PATHS; pub use crate::core::config::flags::Subcommand; -use crate::core::config::flags::{Color, Flags}; +use crate::core::config::flags::{Color, Flags, Warnings}; use crate::core::config::target_selection::TargetSelectionList; use crate::core::config::toml::TomlConfig; use crate::core::config::toml::build::{Build, Tool}; @@ -41,7 +41,8 @@ use crate::core::config::toml::dist::Dist; use crate::core::config::toml::install::Install; use crate::core::config::toml::llvm::Llvm; use crate::core::config::toml::rust::{ - LldMode, RustOptimize, check_incompatible_options_for_ci_rustc, validate_codegen_backends, + LldMode, Rust, RustOptimize, check_incompatible_options_for_ci_rustc, + default_lld_opt_in_targets, validate_codegen_backends, }; use crate::core::config::toml::target::Target; use crate::core::config::{ @@ -1029,7 +1030,250 @@ impl Config { config.target_config.insert(TargetSelection::from_user(&triple), target); } } - config.apply_rust_config(toml.rust, flags_warnings); + let mut debug = None; + let mut rustc_debug_assertions = None; + let mut std_debug_assertions = None; + let mut tools_debug_assertions = None; + let mut overflow_checks = None; + let mut overflow_checks_std = None; + let mut debug_logging = None; + let mut debuginfo_level = None; + let mut debuginfo_level_rustc = None; + let mut debuginfo_level_std = None; + let mut debuginfo_level_tools = None; + let mut debuginfo_level_tests = None; + let mut optimize = None; + let mut lld_enabled = None; + let mut std_features = None; + + if let Some(rust) = toml.rust { + let Rust { + optimize: optimize_toml, + debug: debug_toml, + codegen_units, + codegen_units_std, + rustc_debug_assertions: rustc_debug_assertions_toml, + std_debug_assertions: std_debug_assertions_toml, + tools_debug_assertions: tools_debug_assertions_toml, + overflow_checks: overflow_checks_toml, + overflow_checks_std: overflow_checks_std_toml, + debug_logging: debug_logging_toml, + debuginfo_level: debuginfo_level_toml, + debuginfo_level_rustc: debuginfo_level_rustc_toml, + debuginfo_level_std: debuginfo_level_std_toml, + debuginfo_level_tools: debuginfo_level_tools_toml, + debuginfo_level_tests: debuginfo_level_tests_toml, + backtrace, + incremental, + randomize_layout, + default_linker, + channel: _, // already handled above + musl_root, + rpath, + verbose_tests, + optimize_tests, + codegen_tests, + omit_git_hash: _, // already handled above + dist_src, + save_toolstates, + codegen_backends, + lld: lld_enabled_toml, + llvm_tools, + llvm_bitcode_linker, + deny_warnings, + backtrace_on_ice, + verify_llvm_ir, + thin_lto_import_instr_limit, + remap_debuginfo, + jemalloc, + test_compare_mode, + llvm_libunwind, + control_flow_guard, + ehcont_guard, + new_symbol_mangling, + profile_generate, + profile_use, + download_rustc, + lto, + validate_mir_opts, + frame_pointers, + stack_protector, + strip, + lld_mode, + std_features: std_features_toml, + } = rust; + + // FIXME(#133381): alt rustc builds currently do *not* have rustc debug assertions + // enabled. We should not download a CI alt rustc if we need rustc to have debug + // assertions (e.g. for crashes test suite). This can be changed once something like + // [Enable debug assertions on alt + // builds](https://github.com/rust-lang/rust/pull/131077) lands. + // + // Note that `rust.debug = true` currently implies `rust.debug-assertions = true`! + // + // This relies also on the fact that the global default for `download-rustc` will be + // `false` if it's not explicitly set. + let debug_assertions_requested = matches!(rustc_debug_assertions_toml, Some(true)) + || (matches!(debug_toml, Some(true)) + && !matches!(rustc_debug_assertions_toml, Some(false))); + + if debug_assertions_requested + && let Some(ref opt) = download_rustc + && opt.is_string_or_true() + { + eprintln!( + "WARN: currently no CI rustc builds have rustc debug assertions \ + enabled. Please either set `rust.debug-assertions` to `false` if you \ + want to use download CI rustc or set `rust.download-rustc` to `false`." + ); + } + + config.download_rustc_commit = config.download_ci_rustc_commit( + download_rustc, + debug_assertions_requested, + config.llvm_assertions, + ); + + debug = debug_toml; + rustc_debug_assertions = rustc_debug_assertions_toml; + std_debug_assertions = std_debug_assertions_toml; + tools_debug_assertions = tools_debug_assertions_toml; + overflow_checks = overflow_checks_toml; + overflow_checks_std = overflow_checks_std_toml; + debug_logging = debug_logging_toml; + debuginfo_level = debuginfo_level_toml; + debuginfo_level_rustc = debuginfo_level_rustc_toml; + debuginfo_level_std = debuginfo_level_std_toml; + debuginfo_level_tools = debuginfo_level_tools_toml; + debuginfo_level_tests = debuginfo_level_tests_toml; + lld_enabled = lld_enabled_toml; + std_features = std_features_toml; + + if optimize_toml.as_ref().is_some_and(|v| matches!(v, RustOptimize::Bool(false))) { + eprintln!( + "WARNING: setting `optimize` to `false` is known to cause errors and \ + should be considered unsupported. Refer to `bootstrap.example.toml` \ + for more details." + ); + } + + optimize = optimize_toml; + config.rust_new_symbol_mangling = new_symbol_mangling; + set(&mut config.rust_optimize_tests, optimize_tests); + set(&mut config.codegen_tests, codegen_tests); + set(&mut config.rust_rpath, rpath); + set(&mut config.rust_strip, strip); + set(&mut config.rust_frame_pointers, frame_pointers); + config.rust_stack_protector = stack_protector; + set(&mut config.jemalloc, jemalloc); + set(&mut config.test_compare_mode, test_compare_mode); + set(&mut config.backtrace, backtrace); + set(&mut config.rust_dist_src, dist_src); + set(&mut config.verbose_tests, verbose_tests); + // in the case "false" is set explicitly, do not overwrite the command line args + if let Some(true) = incremental { + config.incremental = true; + } + set(&mut config.lld_mode, lld_mode); + set(&mut config.llvm_bitcode_linker_enabled, llvm_bitcode_linker); + + config.rust_randomize_layout = randomize_layout.unwrap_or_default(); + config.llvm_tools_enabled = llvm_tools.unwrap_or(true); + + config.llvm_enzyme = config.channel == "dev" || config.channel == "nightly"; + config.rustc_default_linker = default_linker; + config.musl_root = musl_root.map(PathBuf::from); + config.save_toolstates = save_toolstates.map(PathBuf::from); + set( + &mut config.deny_warnings, + match flags_warnings { + Warnings::Deny => Some(true), + Warnings::Warn => Some(false), + Warnings::Default => deny_warnings, + }, + ); + set(&mut config.backtrace_on_ice, backtrace_on_ice); + set(&mut config.rust_verify_llvm_ir, verify_llvm_ir); + config.rust_thin_lto_import_instr_limit = thin_lto_import_instr_limit; + set(&mut config.rust_remap_debuginfo, remap_debuginfo); + set(&mut config.control_flow_guard, control_flow_guard); + set(&mut config.ehcont_guard, ehcont_guard); + config.llvm_libunwind_default = + llvm_libunwind.map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")); + set( + &mut config.rust_codegen_backends, + codegen_backends.map(|backends| validate_codegen_backends(backends, "rust")), + ); + + config.rust_codegen_units = codegen_units.map(threads_from_config); + config.rust_codegen_units_std = codegen_units_std.map(threads_from_config); + + if config.rust_profile_use.is_none() { + config.rust_profile_use = profile_use; + } + + if config.rust_profile_generate.is_none() { + config.rust_profile_generate = profile_generate; + } + + config.rust_lto = + lto.as_deref().map(|value| RustcLto::from_str(value).unwrap()).unwrap_or_default(); + config.rust_validate_mir_opts = validate_mir_opts; + } + + config.rust_optimize = optimize.unwrap_or(RustOptimize::Bool(true)); + + // We make `x86_64-unknown-linux-gnu` use the self-contained linker by default, so we will + // build our internal lld and use it as the default linker, by setting the `rust.lld` config + // to true by default: + // - on the `x86_64-unknown-linux-gnu` target + // - when building our in-tree llvm (i.e. the target has not set an `llvm-config`), so that + // we're also able to build the corresponding lld + // - or when using an external llvm that's downloaded from CI, which also contains our prebuilt + // lld + // - otherwise, we'd be using an external llvm, and lld would not necessarily available and + // thus, disabled + // - similarly, lld will not be built nor used by default when explicitly asked not to, e.g. + // when the config sets `rust.lld = false` + if default_lld_opt_in_targets().contains(&config.host_target.triple.to_string()) + && config.hosts == [config.host_target] + { + let no_llvm_config = config + .target_config + .get(&config.host_target) + .is_none_or(|target_config| target_config.llvm_config.is_none()); + let enable_lld = config.llvm_from_ci || no_llvm_config; + // Prefer the config setting in case an explicit opt-out is needed. + config.lld_enabled = lld_enabled.unwrap_or(enable_lld); + } else { + set(&mut config.lld_enabled, lld_enabled); + } + + let default_std_features = BTreeSet::from([String::from("panic-unwind")]); + config.rust_std_features = std_features.unwrap_or(default_std_features); + + let default = debug == Some(true); + config.rustc_debug_assertions = rustc_debug_assertions.unwrap_or(default); + config.std_debug_assertions = std_debug_assertions.unwrap_or(config.rustc_debug_assertions); + config.tools_debug_assertions = + tools_debug_assertions.unwrap_or(config.rustc_debug_assertions); + config.rust_overflow_checks = overflow_checks.unwrap_or(default); + config.rust_overflow_checks_std = + overflow_checks_std.unwrap_or(config.rust_overflow_checks); + + config.rust_debug_logging = debug_logging.unwrap_or(config.rustc_debug_assertions); + + let with_defaults = |debuginfo_level_specific: Option<_>| { + debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) { + DebuginfoLevel::Limited + } else { + DebuginfoLevel::None + }) + }; + config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc); + config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std); + config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools); + config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(DebuginfoLevel::None); config.reproducible_artifacts = flags_reproducible_artifact; config.description = description; diff --git a/src/bootstrap/src/core/config/toml/rust.rs b/src/bootstrap/src/core/config/toml/rust.rs index 03da993a17dd..4bd1eac683ce 100644 --- a/src/bootstrap/src/core/config/toml/rust.rs +++ b/src/bootstrap/src/core/config/toml/rust.rs @@ -1,19 +1,12 @@ //! This module defines the `Rust` struct, which represents the `[rust]` table //! in the `bootstrap.toml` configuration file. -use std::str::FromStr; - use serde::{Deserialize, Deserializer}; use crate::core::build_steps::compile::CODEGEN_BACKEND_PREFIX; use crate::core::config::toml::TomlConfig; -use crate::core::config::{ - DebuginfoLevel, Merge, ReplaceOpt, RustcLto, StringOrBool, set, threads_from_config, -}; -use crate::flags::Warnings; -use crate::{ - BTreeSet, CodegenBackendKind, Config, HashSet, PathBuf, TargetSelection, define_config, exit, -}; +use crate::core::config::{DebuginfoLevel, Merge, ReplaceOpt, StringOrBool}; +use crate::{BTreeSet, HashSet, PathBuf, TargetSelection, define_config, exit}; define_config! { /// TOML representation of how the Rust build is configured. @@ -424,7 +417,7 @@ pub(crate) fn parse_codegen_backends( } #[cfg(not(test))] -fn default_lld_opt_in_targets() -> Vec { +pub fn default_lld_opt_in_targets() -> Vec { vec!["x86_64-unknown-linux-gnu".to_string()] } @@ -434,7 +427,7 @@ thread_local! { } #[cfg(test)] -fn default_lld_opt_in_targets() -> Vec { +pub fn default_lld_opt_in_targets() -> Vec { TEST_LLD_OPT_IN_TARGETS.with(|cell| cell.borrow().clone()).unwrap_or_default() } @@ -447,250 +440,3 @@ pub fn with_lld_opt_in_targets(targets: Vec, f: impl FnOnce() -> R) - result }) } - -impl Config { - pub fn apply_rust_config(&mut self, toml_rust: Option, warnings: Warnings) { - let mut debug = None; - let mut rustc_debug_assertions = None; - let mut std_debug_assertions = None; - let mut tools_debug_assertions = None; - let mut overflow_checks = None; - let mut overflow_checks_std = None; - let mut debug_logging = None; - let mut debuginfo_level = None; - let mut debuginfo_level_rustc = None; - let mut debuginfo_level_std = None; - let mut debuginfo_level_tools = None; - let mut debuginfo_level_tests = None; - let mut optimize = None; - let mut lld_enabled = None; - let mut std_features = None; - - if let Some(rust) = toml_rust { - let Rust { - optimize: optimize_toml, - debug: debug_toml, - codegen_units, - codegen_units_std, - rustc_debug_assertions: rustc_debug_assertions_toml, - std_debug_assertions: std_debug_assertions_toml, - tools_debug_assertions: tools_debug_assertions_toml, - overflow_checks: overflow_checks_toml, - overflow_checks_std: overflow_checks_std_toml, - debug_logging: debug_logging_toml, - debuginfo_level: debuginfo_level_toml, - debuginfo_level_rustc: debuginfo_level_rustc_toml, - debuginfo_level_std: debuginfo_level_std_toml, - debuginfo_level_tools: debuginfo_level_tools_toml, - debuginfo_level_tests: debuginfo_level_tests_toml, - backtrace, - incremental, - randomize_layout, - default_linker, - channel: _, // already handled above - musl_root, - rpath, - verbose_tests, - optimize_tests, - codegen_tests, - omit_git_hash: _, // already handled above - dist_src, - save_toolstates, - codegen_backends, - lld: lld_enabled_toml, - llvm_tools, - llvm_bitcode_linker, - deny_warnings, - backtrace_on_ice, - verify_llvm_ir, - thin_lto_import_instr_limit, - remap_debuginfo, - jemalloc, - test_compare_mode, - llvm_libunwind, - control_flow_guard, - ehcont_guard, - new_symbol_mangling, - profile_generate, - profile_use, - download_rustc, - lto, - validate_mir_opts, - frame_pointers, - stack_protector, - strip, - lld_mode, - std_features: std_features_toml, - } = rust; - - // FIXME(#133381): alt rustc builds currently do *not* have rustc debug assertions - // enabled. We should not download a CI alt rustc if we need rustc to have debug - // assertions (e.g. for crashes test suite). This can be changed once something like - // [Enable debug assertions on alt - // builds](https://github.com/rust-lang/rust/pull/131077) lands. - // - // Note that `rust.debug = true` currently implies `rust.debug-assertions = true`! - // - // This relies also on the fact that the global default for `download-rustc` will be - // `false` if it's not explicitly set. - let debug_assertions_requested = matches!(rustc_debug_assertions_toml, Some(true)) - || (matches!(debug_toml, Some(true)) - && !matches!(rustc_debug_assertions_toml, Some(false))); - - if debug_assertions_requested - && let Some(ref opt) = download_rustc - && opt.is_string_or_true() - { - eprintln!( - "WARN: currently no CI rustc builds have rustc debug assertions \ - enabled. Please either set `rust.debug-assertions` to `false` if you \ - want to use download CI rustc or set `rust.download-rustc` to `false`." - ); - } - - self.download_rustc_commit = self.download_ci_rustc_commit( - download_rustc, - debug_assertions_requested, - self.llvm_assertions, - ); - - debug = debug_toml; - rustc_debug_assertions = rustc_debug_assertions_toml; - std_debug_assertions = std_debug_assertions_toml; - tools_debug_assertions = tools_debug_assertions_toml; - overflow_checks = overflow_checks_toml; - overflow_checks_std = overflow_checks_std_toml; - debug_logging = debug_logging_toml; - debuginfo_level = debuginfo_level_toml; - debuginfo_level_rustc = debuginfo_level_rustc_toml; - debuginfo_level_std = debuginfo_level_std_toml; - debuginfo_level_tools = debuginfo_level_tools_toml; - debuginfo_level_tests = debuginfo_level_tests_toml; - lld_enabled = lld_enabled_toml; - std_features = std_features_toml; - - if optimize_toml.as_ref().is_some_and(|v| matches!(v, RustOptimize::Bool(false))) { - eprintln!( - "WARNING: setting `optimize` to `false` is known to cause errors and \ - should be considered unsupported. Refer to `bootstrap.example.toml` \ - for more details." - ); - } - - optimize = optimize_toml; - self.rust_new_symbol_mangling = new_symbol_mangling; - set(&mut self.rust_optimize_tests, optimize_tests); - set(&mut self.codegen_tests, codegen_tests); - set(&mut self.rust_rpath, rpath); - set(&mut self.rust_strip, strip); - set(&mut self.rust_frame_pointers, frame_pointers); - self.rust_stack_protector = stack_protector; - set(&mut self.jemalloc, jemalloc); - set(&mut self.test_compare_mode, test_compare_mode); - set(&mut self.backtrace, backtrace); - set(&mut self.rust_dist_src, dist_src); - set(&mut self.verbose_tests, verbose_tests); - // in the case "false" is set explicitly, do not overwrite the command line args - if let Some(true) = incremental { - self.incremental = true; - } - set(&mut self.lld_mode, lld_mode); - set(&mut self.llvm_bitcode_linker_enabled, llvm_bitcode_linker); - - self.rust_randomize_layout = randomize_layout.unwrap_or_default(); - self.llvm_tools_enabled = llvm_tools.unwrap_or(true); - - self.llvm_enzyme = self.channel == "dev" || self.channel == "nightly"; - self.rustc_default_linker = default_linker; - self.musl_root = musl_root.map(PathBuf::from); - self.save_toolstates = save_toolstates.map(PathBuf::from); - set( - &mut self.deny_warnings, - match warnings { - Warnings::Deny => Some(true), - Warnings::Warn => Some(false), - Warnings::Default => deny_warnings, - }, - ); - set(&mut self.backtrace_on_ice, backtrace_on_ice); - set(&mut self.rust_verify_llvm_ir, verify_llvm_ir); - self.rust_thin_lto_import_instr_limit = thin_lto_import_instr_limit; - set(&mut self.rust_remap_debuginfo, remap_debuginfo); - set(&mut self.control_flow_guard, control_flow_guard); - set(&mut self.ehcont_guard, ehcont_guard); - self.llvm_libunwind_default = - llvm_libunwind.map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")); - set( - &mut self.rust_codegen_backends, - codegen_backends.map(|backends| parse_codegen_backends(backends, "rust")), - ); - - self.rust_codegen_units = codegen_units.map(threads_from_config); - self.rust_codegen_units_std = codegen_units_std.map(threads_from_config); - - if self.rust_profile_use.is_none() { - self.rust_profile_use = profile_use; - } - - if self.rust_profile_generate.is_none() { - self.rust_profile_generate = profile_generate; - } - - self.rust_lto = - lto.as_deref().map(|value| RustcLto::from_str(value).unwrap()).unwrap_or_default(); - self.rust_validate_mir_opts = validate_mir_opts; - } - - self.rust_optimize = optimize.unwrap_or(RustOptimize::Bool(true)); - - // We make `x86_64-unknown-linux-gnu` use the self-contained linker by default, so we will - // build our internal lld and use it as the default linker, by setting the `rust.lld` config - // to true by default: - // - on the `x86_64-unknown-linux-gnu` target - // - when building our in-tree llvm (i.e. the target has not set an `llvm-config`), so that - // we're also able to build the corresponding lld - // - or when using an external llvm that's downloaded from CI, which also contains our prebuilt - // lld - // - otherwise, we'd be using an external llvm, and lld would not necessarily available and - // thus, disabled - // - similarly, lld will not be built nor used by default when explicitly asked not to, e.g. - // when the config sets `rust.lld = false` - if default_lld_opt_in_targets().contains(&self.host_target.triple.to_string()) - && self.hosts == [self.host_target] - { - let no_llvm_config = self - .target_config - .get(&self.host_target) - .is_none_or(|target_config| target_config.llvm_config.is_none()); - let enable_lld = self.llvm_from_ci || no_llvm_config; - // Prefer the config setting in case an explicit opt-out is needed. - self.lld_enabled = lld_enabled.unwrap_or(enable_lld); - } else { - set(&mut self.lld_enabled, lld_enabled); - } - - let default_std_features = BTreeSet::from([String::from("panic-unwind")]); - self.rust_std_features = std_features.unwrap_or(default_std_features); - - let default = debug == Some(true); - self.rustc_debug_assertions = rustc_debug_assertions.unwrap_or(default); - self.std_debug_assertions = std_debug_assertions.unwrap_or(self.rustc_debug_assertions); - self.tools_debug_assertions = tools_debug_assertions.unwrap_or(self.rustc_debug_assertions); - self.rust_overflow_checks = overflow_checks.unwrap_or(default); - self.rust_overflow_checks_std = overflow_checks_std.unwrap_or(self.rust_overflow_checks); - - self.rust_debug_logging = debug_logging.unwrap_or(self.rustc_debug_assertions); - - let with_defaults = |debuginfo_level_specific: Option<_>| { - debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) { - DebuginfoLevel::Limited - } else { - DebuginfoLevel::None - }) - }; - self.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc); - self.rust_debuginfo_level_std = with_defaults(debuginfo_level_std); - self.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools); - self.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(DebuginfoLevel::None); - } -} From ae05591ade894daf8ac1974f001111b5520fcecf Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 15:30:03 +0530 Subject: [PATCH 0304/1134] Force initializing ExecutionContext with verbosity and fail_fast mode --- src/bootstrap/src/core/config/config.rs | 4 +--- src/bootstrap/src/utils/exec.rs | 10 +++++----- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index b66a9db1336c..1dd62d9b7563 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -454,9 +454,7 @@ impl Config { } = flags; let mut config = Config::default_opts(); - let mut exec_ctx = ExecutionContext::new(); - exec_ctx.set_verbose(flags_verbose); - exec_ctx.set_fail_fast(flags_cmd.fail_fast()); + let exec_ctx = ExecutionContext::new(flags_verbose, flags_cmd.fail_fast()); config.exec_ctx = exec_ctx; diff --git a/src/bootstrap/src/utils/exec.rs b/src/bootstrap/src/utils/exec.rs index 209ff3939731..26582214c930 100644 --- a/src/bootstrap/src/utils/exec.rs +++ b/src/bootstrap/src/utils/exec.rs @@ -550,7 +550,7 @@ impl Default for CommandOutput { #[derive(Clone, Default)] pub struct ExecutionContext { dry_run: DryRun, - verbose: u8, + verbosity: u8, pub fail_fast: bool, delayed_failures: Arc>>, command_cache: Arc, @@ -603,8 +603,8 @@ impl CommandCache { } impl ExecutionContext { - pub fn new() -> Self { - ExecutionContext::default() + pub fn new(verbosity: u8, fail_fast: bool) -> Self { + Self { verbosity, fail_fast, ..Default::default() } } pub fn dry_run(&self) -> bool { @@ -629,7 +629,7 @@ impl ExecutionContext { } pub fn is_verbose(&self) -> bool { - self.verbose > 0 + self.verbosity > 0 } pub fn fail_fast(&self) -> bool { @@ -641,7 +641,7 @@ impl ExecutionContext { } pub fn set_verbose(&mut self, value: u8) { - self.verbose = value; + self.verbosity = value; } pub fn set_fail_fast(&mut self, value: bool) { From 82756fd5f3b8abfef1838aac86f97ba96ca9612f Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 15:37:21 +0530 Subject: [PATCH 0305/1134] Extract TOML config loading and src directory computation into separate functions --- src/bootstrap/src/core/config/config.rs | 206 ++++++++++++++---------- 1 file changed, 117 insertions(+), 89 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 1dd62d9b7563..61787162a7e7 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -453,11 +453,21 @@ impl Config { skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc, } = flags; + // First initialize the bare minimum that we need for further operation - source directory + // and execution context. let mut config = Config::default_opts(); let exec_ctx = ExecutionContext::new(flags_verbose, flags_cmd.fail_fast()); config.exec_ctx = exec_ctx; + if let Some(src) = compute_src_directory(flags_src, &config.exec_ctx) { + config.src = src; + } + + // Now load the TOML config, as soon as possible + let (mut toml, toml_path) = load_toml_config(&config.src, flags_config, &get_toml); + config.config = toml_path.clone(); + // Set flags. config.paths = std::mem::take(&mut flags_paths); @@ -501,53 +511,6 @@ impl Config { // Infer the rest of the configuration. - if let Some(src) = flags_src { - config.src = src - } else { - // Infer the source directory. This is non-trivial because we want to support a downloaded bootstrap binary, - // running on a completely different machine from where it was compiled. - let mut cmd = helpers::git(None); - // NOTE: we cannot support running from outside the repository because the only other path we have available - // is set at compile time, which can be wrong if bootstrap was downloaded rather than compiled locally. - // We still support running outside the repository if we find we aren't in a git directory. - - // NOTE: We get a relative path from git to work around an issue on MSYS/mingw. If we used an absolute path, - // and end up using MSYS's git rather than git-for-windows, we would get a unix-y MSYS path. But as bootstrap - // has already been (kinda-cross-)compiled to Windows land, we require a normal Windows path. - cmd.arg("rev-parse").arg("--show-cdup"); - // Discard stderr because we expect this to fail when building from a tarball. - let output = cmd.allow_failure().run_capture_stdout(&config); - if output.is_success() { - let git_root_relative = output.stdout(); - // We need to canonicalize this path to make sure it uses backslashes instead of forward slashes, - // and to resolve any relative components. - let git_root = env::current_dir() - .unwrap() - .join(PathBuf::from(git_root_relative.trim())) - .canonicalize() - .unwrap(); - let s = git_root.to_str().unwrap(); - - // Bootstrap is quite bad at handling /? in front of paths - let git_root = match s.strip_prefix("\\\\?\\") { - Some(p) => PathBuf::from(p), - None => git_root, - }; - // If this doesn't have at least `stage0`, we guessed wrong. This can happen when, - // for example, the build directory is inside of another unrelated git directory. - // In that case keep the original `CARGO_MANIFEST_DIR` handling. - // - // NOTE: this implies that downloadable bootstrap isn't supported when the build directory is outside - // the source directory. We could fix that by setting a variable from all three of python, ./x, and x.ps1. - if git_root.join("src").join("stage0").exists() { - config.src = git_root; - } - } else { - // We're building from a tarball, not git sources. - // We don't support pre-downloaded bootstrap in this case. - } - } - if cfg!(test) { // Use the build directory of the original x.py invocation, so that we can set `initial_rustc` properly. config.out = Path::new( @@ -560,47 +523,6 @@ impl Config { config.stage0_metadata = build_helper::stage0_parser::parse_stage0_file(); - // Locate the configuration file using the following priority (first match wins): - // 1. `--config ` (explicit flag) - // 2. `RUST_BOOTSTRAP_CONFIG` environment variable - // 3. `./bootstrap.toml` (local file) - // 4. `/bootstrap.toml` - // 5. `./config.toml` (fallback for backward compatibility) - // 6. `/config.toml` - let toml_path = flags_config - .clone() - .or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from)); - let using_default_path = toml_path.is_none(); - let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("bootstrap.toml")); - - if using_default_path && !toml_path.exists() { - toml_path = config.src.join(PathBuf::from("bootstrap.toml")); - if !toml_path.exists() { - toml_path = PathBuf::from("config.toml"); - if !toml_path.exists() { - toml_path = config.src.join(PathBuf::from("config.toml")); - } - } - } - - // Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path, - // but not if `bootstrap.toml` hasn't been created. - let mut toml = if !using_default_path || toml_path.exists() { - config.config = Some(if cfg!(not(test)) { - toml_path = toml_path.canonicalize().unwrap(); - toml_path.clone() - } else { - toml_path.clone() - }); - get_toml(&toml_path).unwrap_or_else(|e| { - eprintln!("ERROR: Failed to parse '{}': {e}", toml_path.display()); - exit!(2); - }) - } else { - config.config = None; - TomlConfig::default() - }; - if cfg!(test) { // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the // same ones used to call the tests (if custom ones are not defined in the toml). If we @@ -622,7 +544,12 @@ impl Config { // This must be handled before applying the `profile` since `include`s should always take // precedence over `profile`s. for include_path in toml.include.clone().unwrap_or_default().iter().rev() { - let include_path = toml_path.parent().unwrap().join(include_path); + let include_path = toml_path + .as_ref() + .expect("include found in default TOML config") + .parent() + .unwrap() + .join(include_path); let included_toml = get_toml(&include_path).unwrap_or_else(|e| { eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display()); @@ -2309,3 +2236,104 @@ impl AsRef for Config { &self.exec_ctx } } + +fn compute_src_directory(src_dir: Option, exec_ctx: &ExecutionContext) -> Option { + if let Some(src) = src_dir { + return Some(src); + } else { + // Infer the source directory. This is non-trivial because we want to support a downloaded bootstrap binary, + // running on a completely different machine from where it was compiled. + let mut cmd = helpers::git(None); + // NOTE: we cannot support running from outside the repository because the only other path we have available + // is set at compile time, which can be wrong if bootstrap was downloaded rather than compiled locally. + // We still support running outside the repository if we find we aren't in a git directory. + + // NOTE: We get a relative path from git to work around an issue on MSYS/mingw. If we used an absolute path, + // and end up using MSYS's git rather than git-for-windows, we would get a unix-y MSYS path. But as bootstrap + // has already been (kinda-cross-)compiled to Windows land, we require a normal Windows path. + cmd.arg("rev-parse").arg("--show-cdup"); + // Discard stderr because we expect this to fail when building from a tarball. + let output = cmd.allow_failure().run_capture_stdout(exec_ctx); + if output.is_success() { + let git_root_relative = output.stdout(); + // We need to canonicalize this path to make sure it uses backslashes instead of forward slashes, + // and to resolve any relative components. + let git_root = env::current_dir() + .unwrap() + .join(PathBuf::from(git_root_relative.trim())) + .canonicalize() + .unwrap(); + let s = git_root.to_str().unwrap(); + + // Bootstrap is quite bad at handling /? in front of paths + let git_root = match s.strip_prefix("\\\\?\\") { + Some(p) => PathBuf::from(p), + None => git_root, + }; + // If this doesn't have at least `stage0`, we guessed wrong. This can happen when, + // for example, the build directory is inside of another unrelated git directory. + // In that case keep the original `CARGO_MANIFEST_DIR` handling. + // + // NOTE: this implies that downloadable bootstrap isn't supported when the build directory is outside + // the source directory. We could fix that by setting a variable from all three of python, ./x, and x.ps1. + if git_root.join("src").join("stage0").exists() { + return Some(git_root); + } + } else { + // We're building from a tarball, not git sources. + // We don't support pre-downloaded bootstrap in this case. + } + }; + None +} + +/// Loads bootstrap TOML config and returns the config together with a path from where +/// it was loaded. +/// `src` is the source root directory, and `config_path` is an optionally provided path to the +/// config. +fn load_toml_config( + src: &Path, + config_path: Option, + get_toml: &impl Fn(&Path) -> Result, +) -> (TomlConfig, Option) { + // Locate the configuration file using the following priority (first match wins): + // 1. `--config ` (explicit flag) + // 2. `RUST_BOOTSTRAP_CONFIG` environment variable + // 3. `./bootstrap.toml` (local file) + // 4. `/bootstrap.toml` + // 5. `./config.toml` (fallback for backward compatibility) + // 6. `/config.toml` + let toml_path = config_path.or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from)); + let using_default_path = toml_path.is_none(); + let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("bootstrap.toml")); + + if using_default_path && !toml_path.exists() { + toml_path = src.join(PathBuf::from("bootstrap.toml")); + if !toml_path.exists() { + toml_path = PathBuf::from("config.toml"); + if !toml_path.exists() { + toml_path = src.join(PathBuf::from("config.toml")); + } + } + } + + // Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path, + // but not if `bootstrap.toml` hasn't been created. + if !using_default_path || toml_path.exists() { + let path = Some(if cfg!(not(test)) { + toml_path = toml_path.canonicalize().unwrap(); + toml_path.clone() + } else { + toml_path.clone() + }); + ( + get_toml(&toml_path).unwrap_or_else(|e| { + eprintln!("ERROR: Failed to parse '{}': {e}", toml_path.display()); + exit!(2); + }), + path, + ) + } else { + (TomlConfig::default(), None) + } +} From f89ea086c43b745d0b655967bd469b2891834967 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 16:21:20 +0530 Subject: [PATCH 0306/1134] Split TOML postprocessing into a separate function --- src/bootstrap/src/core/config/config.rs | 213 +++++++++++++----------- 1 file changed, 114 insertions(+), 99 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 61787162a7e7..99b99f4660a2 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -468,6 +468,15 @@ impl Config { let (mut toml, toml_path) = load_toml_config(&config.src, flags_config, &get_toml); config.config = toml_path.clone(); + postprocess_toml( + &mut toml, + &config.src, + toml_path, + config.exec_ctx(), + &flags_set, + &get_toml, + ); + // Set flags. config.paths = std::mem::take(&mut flags_paths); @@ -534,105 +543,6 @@ impl Config { build.cargo = build.cargo.take().or(std::env::var_os("CARGO").map(|p| p.into())); } - if config.git_info(false, &config.src).is_from_tarball() && toml.profile.is_none() { - toml.profile = Some("dist".into()); - } - - // Reverse the list to ensure the last added config extension remains the most dominant. - // For example, given ["a.toml", "b.toml"], "b.toml" should take precedence over "a.toml". - // - // This must be handled before applying the `profile` since `include`s should always take - // precedence over `profile`s. - for include_path in toml.include.clone().unwrap_or_default().iter().rev() { - let include_path = toml_path - .as_ref() - .expect("include found in default TOML config") - .parent() - .unwrap() - .join(include_path); - - let included_toml = get_toml(&include_path).unwrap_or_else(|e| { - eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display()); - exit!(2); - }); - toml.merge( - Some(include_path), - &mut Default::default(), - included_toml, - ReplaceOpt::IgnoreDuplicate, - ); - } - - if let Some(include) = &toml.profile { - // Allows creating alias for profile names, allowing - // profiles to be renamed while maintaining back compatibility - // Keep in sync with `profile_aliases` in bootstrap.py - let profile_aliases = HashMap::from([("user", "dist")]); - let include = match profile_aliases.get(include.as_str()) { - Some(alias) => alias, - None => include.as_str(), - }; - let mut include_path = config.src.clone(); - include_path.push("src"); - include_path.push("bootstrap"); - include_path.push("defaults"); - include_path.push(format!("bootstrap.{include}.toml")); - let included_toml = get_toml(&include_path).unwrap_or_else(|e| { - eprintln!( - "ERROR: Failed to parse default config profile at '{}': {e}", - include_path.display() - ); - exit!(2); - }); - toml.merge( - Some(include_path), - &mut Default::default(), - included_toml, - ReplaceOpt::IgnoreDuplicate, - ); - } - - let mut override_toml = TomlConfig::default(); - for option in flags_set.iter() { - fn get_table(option: &str) -> Result { - toml::from_str(option).and_then(|table: toml::Value| TomlConfig::deserialize(table)) - } - - let mut err = match get_table(option) { - Ok(v) => { - override_toml.merge( - None, - &mut Default::default(), - v, - ReplaceOpt::ErrorOnDuplicate, - ); - continue; - } - Err(e) => e, - }; - // We want to be able to set string values without quotes, - // like in `configure.py`. Try adding quotes around the right hand side - if let Some((key, value)) = option.split_once('=') - && !value.contains('"') - { - match get_table(&format!(r#"{key}="{value}""#)) { - Ok(v) => { - override_toml.merge( - None, - &mut Default::default(), - v, - ReplaceOpt::ErrorOnDuplicate, - ); - continue; - } - Err(e) => err = e, - } - } - eprintln!("failed to parse override `{option}`: `{err}"); - exit!(2) - } - toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override); - config.change_id = toml.change_id.inner; let Build { @@ -2337,3 +2247,108 @@ fn load_toml_config( (TomlConfig::default(), None) } } + +fn postprocess_toml( + toml: &mut TomlConfig, + src_dir: &Path, + toml_path: Option, + exec_ctx: &ExecutionContext, + override_set: &[String], + get_toml: &impl Fn(&Path) -> Result, +) { + let git_info = GitInfo::new(false, src_dir, exec_ctx); + + if git_info.is_from_tarball() && toml.profile.is_none() { + toml.profile = Some("dist".into()); + } + + // Reverse the list to ensure the last added config extension remains the most dominant. + // For example, given ["a.toml", "b.toml"], "b.toml" should take precedence over "a.toml". + // + // This must be handled before applying the `profile` since `include`s should always take + // precedence over `profile`s. + for include_path in toml.include.clone().unwrap_or_default().iter().rev() { + let include_path = toml_path + .as_ref() + .expect("include found in default TOML config") + .parent() + .unwrap() + .join(include_path); + + let included_toml = get_toml(&include_path).unwrap_or_else(|e| { + eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display()); + exit!(2); + }); + toml.merge( + Some(include_path), + &mut Default::default(), + included_toml, + ReplaceOpt::IgnoreDuplicate, + ); + } + + if let Some(include) = &toml.profile { + // Allows creating alias for profile names, allowing + // profiles to be renamed while maintaining back compatibility + // Keep in sync with `profile_aliases` in bootstrap.py + let profile_aliases = HashMap::from([("user", "dist")]); + let include = match profile_aliases.get(include.as_str()) { + Some(alias) => alias, + None => include.as_str(), + }; + let mut include_path = PathBuf::from(src_dir); + include_path.push("src"); + include_path.push("bootstrap"); + include_path.push("defaults"); + include_path.push(format!("bootstrap.{include}.toml")); + let included_toml = get_toml(&include_path).unwrap_or_else(|e| { + eprintln!( + "ERROR: Failed to parse default config profile at '{}': {e}", + include_path.display() + ); + exit!(2); + }); + toml.merge( + Some(include_path.into()), + &mut Default::default(), + included_toml, + ReplaceOpt::IgnoreDuplicate, + ); + } + + let mut override_toml = TomlConfig::default(); + for option in override_set.iter() { + fn get_table(option: &str) -> Result { + toml::from_str(option).and_then(|table: toml::Value| TomlConfig::deserialize(table)) + } + + let mut err = match get_table(option) { + Ok(v) => { + override_toml.merge(None, &mut Default::default(), v, ReplaceOpt::ErrorOnDuplicate); + continue; + } + Err(e) => e, + }; + // We want to be able to set string values without quotes, + // like in `configure.py`. Try adding quotes around the right hand side + if let Some((key, value)) = option.split_once('=') + && !value.contains('"') + { + match get_table(&format!(r#"{key}="{value}""#)) { + Ok(v) => { + override_toml.merge( + None, + &mut Default::default(), + v, + ReplaceOpt::ErrorOnDuplicate, + ); + continue; + } + Err(e) => err = e, + } + } + eprintln!("failed to parse override `{option}`: `{err}"); + exit!(2) + } + toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override); +} From cfc40de9c504c9e05bd9905e3f99011199026ac8 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 16:48:14 +0530 Subject: [PATCH 0307/1134] Override some build TOML values by flags --- src/bootstrap/src/core/config/config.rs | 276 +++++++++++++----------- 1 file changed, 149 insertions(+), 127 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 99b99f4660a2..49359afbed62 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -477,61 +477,6 @@ impl Config { &get_toml, ); - // Set flags. - config.paths = std::mem::take(&mut flags_paths); - - #[cfg(feature = "tracing")] - span!( - target: "CONFIG_HANDLING", - tracing::Level::TRACE, - "collecting paths and path exclusions", - "flags.paths" = ?flags_paths, - "flags.skip" = ?flags_skip, - "flags.exclude" = ?flags_exclude - ); - - #[cfg(feature = "tracing")] - span!( - target: "CONFIG_HANDLING", - tracing::Level::TRACE, - "normalizing and combining `flag.skip`/`flag.exclude` paths", - "config.skip" = ?config.skip, - ); - - config.include_default_paths = flags_include_default_paths; - config.rustc_error_format = flags_rustc_error_format; - config.json_output = flags_json_output; - config.compile_time_deps = flags_compile_time_deps; - config.on_fail = flags_on_fail; - config.cmd = flags_cmd; - config.incremental = flags_incremental; - config.set_dry_run(if flags_dry_run { DryRun::UserSelected } else { DryRun::Disabled }); - config.dump_bootstrap_shims = flags_dump_bootstrap_shims; - config.keep_stage = flags_keep_stage; - config.keep_stage_std = flags_keep_stage_std; - config.color = flags_color; - config.free_args = std::mem::take(&mut flags_free_args); - config.llvm_profile_use = flags_llvm_profile_use; - config.llvm_profile_generate = flags_llvm_profile_generate; - config.enable_bolt_settings = flags_enable_bolt_settings; - config.bypass_bootstrap_lock = flags_bypass_bootstrap_lock; - config.is_running_on_ci = flags_ci.unwrap_or(CiEnv::is_ci()); - config.skip_std_check_if_no_download_rustc = flags_skip_std_check_if_no_download_rustc; - - // Infer the rest of the configuration. - - if cfg!(test) { - // Use the build directory of the original x.py invocation, so that we can set `initial_rustc` properly. - config.out = Path::new( - &env::var_os("CARGO_TARGET_DIR").expect("cargo test directly is not supported"), - ) - .parent() - .unwrap() - .to_path_buf(); - } - - config.stage0_metadata = build_helper::stage0_parser::parse_stage0_file(); - if cfg!(test) { // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the // same ones used to call the tests (if custom ones are not defined in the toml). If we @@ -543,11 +488,11 @@ impl Config { build.cargo = build.cargo.take().or(std::env::var_os("CARGO").map(|p| p.into())); } - config.change_id = toml.change_id.inner; - + // Now override TOML values with flags, to make sure that we won't later override flags with + // TOML values by accident instead, because flags have higher priority. let Build { description, - build, + mut build, host, target, build_dir, @@ -594,7 +539,7 @@ impl Config { metrics: _, android_ndk, optimized_compiler_builtins, - jobs, + mut jobs, compiletest_diff_tool, compiletest_allow_stage0, compiletest_use_stage0_libtest, @@ -602,6 +547,90 @@ impl Config { ccache, exclude, } = toml.build.unwrap_or_default(); + jobs = flags_jobs.or(jobs); + build = flags_build.or(build); + let build_dir = flags_build_dir.or(build_dir.map(PathBuf::from)); + let host = if let Some(TargetSelectionList(hosts)) = flags_host { + Some(hosts) + } else if let Some(file_host) = host { + Some(file_host.iter().map(|h| TargetSelection::from_user(h)).collect()) + } else { + None + }; + let target = if let Some(TargetSelectionList(targets)) = flags_target { + Some(targets) + } else if let Some(file_target) = target { + Some(file_target.iter().map(|h| TargetSelection::from_user(h)).collect()) + } else { + None + }; + + if let Some(rustc) = &rustc { + if !flags_skip_stage0_validation { + check_stage0_version(&rustc, "rustc", &config.src, config.exec_ctx()); + } + } + if let Some(cargo) = &cargo { + if !flags_skip_stage0_validation { + check_stage0_version(&cargo, "cargo", &config.src, config.exec_ctx()); + } + } + + #[cfg(feature = "tracing")] + span!( + target: "CONFIG_HANDLING", + tracing::Level::TRACE, + "collecting paths and path exclusions", + "flags.paths" = ?flags_paths, + "flags.skip" = ?flags_skip, + "flags.exclude" = ?flags_exclude + ); + + #[cfg(feature = "tracing")] + span!( + target: "CONFIG_HANDLING", + tracing::Level::TRACE, + "normalizing and combining `flag.skip`/`flag.exclude` paths", + "config.skip" = ?config.skip, + ); + + // Set flags. + config.paths = std::mem::take(&mut flags_paths); + config.include_default_paths = flags_include_default_paths; + config.rustc_error_format = flags_rustc_error_format; + config.json_output = flags_json_output; + config.compile_time_deps = flags_compile_time_deps; + config.on_fail = flags_on_fail; + config.cmd = flags_cmd; + config.incremental = flags_incremental; + config.set_dry_run(if flags_dry_run { DryRun::UserSelected } else { DryRun::Disabled }); + config.dump_bootstrap_shims = flags_dump_bootstrap_shims; + config.keep_stage = flags_keep_stage; + config.keep_stage_std = flags_keep_stage_std; + config.color = flags_color; + config.free_args = std::mem::take(&mut flags_free_args); + config.llvm_profile_use = flags_llvm_profile_use; + config.llvm_profile_generate = flags_llvm_profile_generate; + config.enable_bolt_settings = flags_enable_bolt_settings; + config.bypass_bootstrap_lock = flags_bypass_bootstrap_lock; + config.is_running_on_ci = flags_ci.unwrap_or(CiEnv::is_ci()); + config.skip_std_check_if_no_download_rustc = flags_skip_std_check_if_no_download_rustc; + + // Infer the rest of the configuration. + + if cfg!(test) { + // Use the build directory of the original x.py invocation, so that we can set `initial_rustc` properly. + config.out = Path::new( + &env::var_os("CARGO_TARGET_DIR").expect("cargo test directly is not supported"), + ) + .parent() + .unwrap() + .to_path_buf(); + } + + config.stage0_metadata = build_helper::stage0_parser::parse_stage0_file(); + + config.change_id = toml.change_id.inner; let mut paths: Vec = flags_skip.into_iter().chain(flags_exclude).collect(); @@ -623,15 +652,12 @@ impl Config { }) .collect(); - config.jobs = Some(threads_from_config(flags_jobs.unwrap_or(jobs.unwrap_or(0)))); - - if let Some(flags_build) = flags_build { - config.host_target = TargetSelection::from_user(&flags_build); - } else if let Some(file_build) = build { - config.host_target = TargetSelection::from_user(&file_build); - }; + config.jobs = Some(threads_from_config(jobs.unwrap_or(0))); + if let Some(build) = build { + config.host_target = TargetSelection::from_user(&build); + } - set(&mut config.out, flags_build_dir.or_else(|| build_dir.map(PathBuf::from))); + set(&mut config.out, build_dir); // NOTE: Bootstrap spawns various commands with different working directories. // To avoid writing to random places on the file system, `config.out` needs to be an absolute path. if !config.out.is_absolute() { @@ -651,9 +677,6 @@ impl Config { toml.llvm.as_ref().is_some_and(|llvm| llvm.assertions.unwrap_or(false)); config.initial_rustc = if let Some(rustc) = rustc { - if !flags_skip_stage0_validation { - config.check_stage0_version(&rustc, "rustc"); - } rustc } else { let dwn_ctx = DownloadContext::from(&config); @@ -678,9 +701,6 @@ impl Config { config.initial_cargo_clippy = cargo_clippy; config.initial_cargo = if let Some(cargo) = cargo { - if !flags_skip_stage0_validation { - config.check_stage0_version(&cargo, "cargo"); - } cargo } else { let dwn_ctx = DownloadContext::from(&config); @@ -695,17 +715,9 @@ impl Config { config.out = dir; } - config.hosts = if let Some(TargetSelectionList(arg_host)) = flags_host { - arg_host - } else if let Some(file_host) = host { - file_host.iter().map(|h| TargetSelection::from_user(h)).collect() - } else { - vec![config.host_target] - }; - config.targets = if let Some(TargetSelectionList(arg_target)) = flags_target { - arg_target - } else if let Some(file_target) = target { - file_target.iter().map(|h| TargetSelection::from_user(h)).collect() + config.hosts = if let Some(hosts) = host { hosts } else { vec![config.host_target] }; + config.targets = if let Some(targets) = target { + targets } else { // If target is *not* configured, then default to the host // toolchains. @@ -1812,49 +1824,6 @@ impl Config { } } - #[cfg(test)] - pub fn check_stage0_version(&self, _program_path: &Path, _component_name: &'static str) {} - - /// check rustc/cargo version is same or lower with 1 apart from the building one - #[cfg(not(test))] - pub fn check_stage0_version(&self, program_path: &Path, component_name: &'static str) { - use build_helper::util::fail; - - if self.dry_run() { - return; - } - - let stage0_output = - command(program_path).arg("--version").run_capture_stdout(self).stdout(); - let mut stage0_output = stage0_output.lines().next().unwrap().split(' '); - - let stage0_name = stage0_output.next().unwrap(); - if stage0_name != component_name { - fail(&format!( - "Expected to find {component_name} at {} but it claims to be {stage0_name}", - program_path.display() - )); - } - - let stage0_version = - semver::Version::parse(stage0_output.next().unwrap().split('-').next().unwrap().trim()) - .unwrap(); - let source_version = semver::Version::parse( - fs::read_to_string(self.src.join("src/version")).unwrap().trim(), - ) - .unwrap(); - if !(source_version == stage0_version - || (source_version.major == stage0_version.major - && (source_version.minor == stage0_version.minor - || source_version.minor == stage0_version.minor + 1))) - { - let prev_version = format!("{}.{}.x", source_version.major, source_version.minor - 1); - fail(&format!( - "Unexpected {component_name} version: {stage0_version}, we should use {prev_version}/{source_version} to build source with {source_version}" - )); - } - } - /// Returns the commit to download, or `None` if we shouldn't download CI artifacts. pub fn download_ci_rustc_commit( &self, @@ -2352,3 +2321,56 @@ fn postprocess_toml( } toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override); } + +#[cfg(test)] +pub fn check_stage0_version( + _program_path: &Path, + _component_name: &'static str, + _src_dir: &Path, + _exec_ctx: &ExecutionContext, +) { +} + +/// check rustc/cargo version is same or lower with 1 apart from the building one +#[cfg(not(test))] +pub fn check_stage0_version( + program_path: &Path, + component_name: &'static str, + src_dir: &Path, + exec_ctx: &ExecutionContext, +) { + use build_helper::util::fail; + + if exec_ctx.dry_run() { + return; + } + + let stage0_output = + command(program_path).arg("--version").run_capture_stdout(exec_ctx).stdout(); + let mut stage0_output = stage0_output.lines().next().unwrap().split(' '); + + let stage0_name = stage0_output.next().unwrap(); + if stage0_name != component_name { + fail(&format!( + "Expected to find {component_name} at {} but it claims to be {stage0_name}", + program_path.display() + )); + } + + let stage0_version = + semver::Version::parse(stage0_output.next().unwrap().split('-').next().unwrap().trim()) + .unwrap(); + let source_version = + semver::Version::parse(fs::read_to_string(src_dir.join("src/version")).unwrap().trim()) + .unwrap(); + if !(source_version == stage0_version + || (source_version.major == stage0_version.major + && (source_version.minor == stage0_version.minor + || source_version.minor == stage0_version.minor + 1))) + { + let prev_version = format!("{}.{}.x", source_version.major, source_version.minor - 1); + fail(&format!( + "Unexpected {component_name} version: {stage0_version}, we should use {prev_version}/{source_version} to build source with {source_version}" + )); + } +} From 8652d96ff7b58ec491de45d0767b211f631dfbee Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 16:56:38 +0530 Subject: [PATCH 0308/1134] Fix logging of config skip values --- src/bootstrap/src/core/config/config.rs | 55 ++++++++++++------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 49359afbed62..c3cc920d331d 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -446,13 +446,23 @@ impl Config { enable_bolt_settings: flags_enable_bolt_settings, skip_stage0_validation: flags_skip_stage0_validation, reproducible_artifact: flags_reproducible_artifact, - paths: mut flags_paths, + paths: flags_paths, set: flags_set, - free_args: mut flags_free_args, + free_args: flags_free_args, ci: flags_ci, skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc, } = flags; + #[cfg(feature = "tracing")] + span!( + target: "CONFIG_HANDLING", + tracing::Level::TRACE, + "collecting paths and path exclusions", + "flags.paths" = ?flags_paths, + "flags.skip" = ?flags_skip, + "flags.exclude" = ?flags_exclude + ); + // First initialize the bare minimum that we need for further operation - source directory // and execution context. let mut config = Config::default_opts(); @@ -576,26 +586,13 @@ impl Config { } } - #[cfg(feature = "tracing")] - span!( - target: "CONFIG_HANDLING", - tracing::Level::TRACE, - "collecting paths and path exclusions", - "flags.paths" = ?flags_paths, - "flags.skip" = ?flags_skip, - "flags.exclude" = ?flags_exclude - ); - - #[cfg(feature = "tracing")] - span!( - target: "CONFIG_HANDLING", - tracing::Level::TRACE, - "normalizing and combining `flag.skip`/`flag.exclude` paths", - "config.skip" = ?config.skip, - ); + let mut paths: Vec = flags_skip.into_iter().chain(flags_exclude).collect(); + if let Some(exclude) = exclude { + paths.extend(exclude); + } - // Set flags. - config.paths = std::mem::take(&mut flags_paths); + // Set config values based on flags. + config.paths = flags_paths; config.include_default_paths = flags_include_default_paths; config.rustc_error_format = flags_rustc_error_format; config.json_output = flags_json_output; @@ -608,7 +605,7 @@ impl Config { config.keep_stage = flags_keep_stage; config.keep_stage_std = flags_keep_stage_std; config.color = flags_color; - config.free_args = std::mem::take(&mut flags_free_args); + config.free_args = flags_free_args; config.llvm_profile_use = flags_llvm_profile_use; config.llvm_profile_generate = flags_llvm_profile_generate; config.enable_bolt_settings = flags_enable_bolt_settings; @@ -632,12 +629,6 @@ impl Config { config.change_id = toml.change_id.inner; - let mut paths: Vec = flags_skip.into_iter().chain(flags_exclude).collect(); - - if let Some(exclude) = exclude { - paths.extend(exclude); - } - config.skip = paths .into_iter() .map(|p| { @@ -652,6 +643,14 @@ impl Config { }) .collect(); + #[cfg(feature = "tracing")] + span!( + target: "CONFIG_HANDLING", + tracing::Level::TRACE, + "normalizing and combining `flag.skip`/`flag.exclude` paths", + "config.skip" = ?config.skip, + ); + config.jobs = Some(threads_from_config(jobs.unwrap_or(0))); if let Some(build) = build { config.host_target = TargetSelection::from_user(&build); From 58a38cd7deba18d4b449214cab5cad36d3b4cceb Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Wed, 30 Jul 2025 17:08:52 +0530 Subject: [PATCH 0309/1134] Fix verbosity setting --- src/bootstrap/src/core/config/config.rs | 12 +++++++----- src/bootstrap/src/lib.rs | 2 +- src/bootstrap/src/utils/exec.rs | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index c3cc920d331d..d9cc215683ea 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -93,7 +93,6 @@ pub struct Config { pub ccache: Option, /// Call Build::ninja() instead of this. pub ninja_in_file: bool, - pub verbose: usize, pub submodules: Option, pub compiler_docs: bool, pub library_docs_private_items: bool, @@ -528,7 +527,7 @@ impl Config { extended, tools, tool, - verbose, + verbose: build_verbose, sanitizers, profiler, cargo_native_static, @@ -586,6 +585,12 @@ impl Config { } } + // Prefer CLI verbosity flags if set (`flags_verbose` > 0), otherwise take the value from + // TOML. + config + .exec_ctx + .set_verbosity(cmp::max(build_verbose.unwrap_or_default() as u8, flags_verbose)); + let mut paths: Vec = flags_skip.into_iter().chain(flags_exclude).collect(); if let Some(exclude) = exclude { paths.extend(exclude); @@ -741,7 +746,6 @@ impl Config { set(&mut config.extended, extended); config.tools = tools; set(&mut config.tool, tool); - set(&mut config.verbose, verbose); set(&mut config.sanitizers, sanitizers); set(&mut config.profiler, profiler); set(&mut config.cargo_native_static, cargo_native_static); @@ -750,8 +754,6 @@ impl Config { set(&mut config.print_step_timings, print_step_timings); set(&mut config.print_step_rusage, print_step_rusage); - config.verbose = cmp::max(config.verbose, flags_verbose as usize); - // Verbose flag is a good default for `rust.verbose-tests`. config.verbose_tests = config.is_verbose(); diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 011b52df97bb..254b8658b668 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -515,7 +515,7 @@ impl Build { local_rebuild: config.local_rebuild, fail_fast: config.cmd.fail_fast(), doc_tests: config.cmd.doc_tests(), - verbosity: config.verbose, + verbosity: config.exec_ctx.verbosity as usize, host_target: config.host_target, hosts: config.hosts.clone(), diff --git a/src/bootstrap/src/utils/exec.rs b/src/bootstrap/src/utils/exec.rs index 26582214c930..7527dff9cd84 100644 --- a/src/bootstrap/src/utils/exec.rs +++ b/src/bootstrap/src/utils/exec.rs @@ -550,7 +550,7 @@ impl Default for CommandOutput { #[derive(Clone, Default)] pub struct ExecutionContext { dry_run: DryRun, - verbosity: u8, + pub verbosity: u8, pub fail_fast: bool, delayed_failures: Arc>>, command_cache: Arc, @@ -640,7 +640,7 @@ impl ExecutionContext { self.dry_run = value; } - pub fn set_verbose(&mut self, value: u8) { + pub fn set_verbosity(&mut self, value: u8) { self.verbosity = value; } From 222dfcc02fdadc854335fd2a1cc8961203933a94 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 14:04:41 +0530 Subject: [PATCH 0310/1134] add install default implementation --- src/bootstrap/src/core/config/config.rs | 35 +++++++++++++------ src/bootstrap/src/core/config/toml/install.rs | 1 + 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index d9cc215683ea..c97e675f577c 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -757,16 +757,31 @@ impl Config { // Verbose flag is a good default for `rust.verbose-tests`. config.verbose_tests = config.is_verbose(); - if let Some(install) = toml.install { - let Install { prefix, sysconfdir, docdir, bindir, libdir, mandir, datadir } = install; - config.prefix = prefix.map(PathBuf::from); - config.sysconfdir = sysconfdir.map(PathBuf::from); - config.datadir = datadir.map(PathBuf::from); - config.docdir = docdir.map(PathBuf::from); - set(&mut config.bindir, bindir.map(PathBuf::from)); - config.libdir = libdir.map(PathBuf::from); - config.mandir = mandir.map(PathBuf::from); - } + let Install { + prefix: install_prefix, + sysconfdir: install_sysconfdir, + docdir: install_docdir, + bindir: install_bindir, + libdir: install_libdir, + mandir: install_mandir, + datadir: install_datadir, + } = toml.install.unwrap_or_default(); + + let install_prefix = install_prefix.map(PathBuf::from); + let install_sysconfdir = install_sysconfdir.map(PathBuf::from); + let install_docdir = install_docdir.map(PathBuf::from); + let install_bindir = install_bindir.map(PathBuf::from); + let install_libdir = install_libdir.map(PathBuf::from); + let install_mandir = install_mandir.map(PathBuf::from); + let install_datadir = install_datadir.map(PathBuf::from); + + config.prefix = install_prefix; + config.sysconfdir = install_sysconfdir; + config.datadir = install_datadir; + config.docdir = install_docdir; + set(&mut config.bindir, install_bindir); + config.libdir = install_libdir; + config.mandir = install_mandir; let file_content = t!(fs::read_to_string(config.src.join("src/ci/channel"))); let ci_channel = file_content.trim_end(); diff --git a/src/bootstrap/src/core/config/toml/install.rs b/src/bootstrap/src/core/config/toml/install.rs index da31c0cc878c..60fa958bd82f 100644 --- a/src/bootstrap/src/core/config/toml/install.rs +++ b/src/bootstrap/src/core/config/toml/install.rs @@ -14,6 +14,7 @@ use crate::{HashSet, PathBuf, define_config, exit}; define_config! { /// TOML representation of various global install decisions. + #[derive(Default)] struct Install { prefix: Option = "prefix", sysconfdir: Option = "sysconfdir", From bbe7c087622b0490306bbf7d5eb342dad57f5243 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 14:28:17 +0530 Subject: [PATCH 0311/1134] add gcc and dist default implementation --- src/bootstrap/src/core/config/config.rs | 62 +++++++++++----------- src/bootstrap/src/core/config/toml/dist.rs | 1 + src/bootstrap/src/core/config/toml/gcc.rs | 1 + 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index c97e675f577c..47c228d3cc3f 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -38,6 +38,7 @@ use crate::core::config::toml::TomlConfig; use crate::core::config::toml::build::{Build, Tool}; use crate::core::config::toml::change_id::ChangeId; use crate::core::config::toml::dist::Dist; +use crate::core::config::toml::gcc::Gcc; use crate::core::config::toml::install::Install; use crate::core::config::toml::llvm::Llvm; use crate::core::config::toml::rust::{ @@ -774,7 +775,6 @@ impl Config { let install_libdir = install_libdir.map(PathBuf::from); let install_mandir = install_mandir.map(PathBuf::from); let install_datadir = install_datadir.map(PathBuf::from); - config.prefix = install_prefix; config.sysconfdir = install_sysconfdir; config.datadir = install_datadir; @@ -1278,15 +1278,15 @@ impl Config { config.llvm_offload = llvm_offload.unwrap_or(false); config.llvm_plugins = llvm_plugins.unwrap_or(false); - if let Some(gcc) = toml.gcc { - config.gcc_ci_mode = match gcc.download_ci_gcc { - Some(value) => match value { - true => GccCiMode::DownloadFromCi, - false => GccCiMode::BuildLocally, - }, - None => GccCiMode::default(), - }; - } + let Gcc { download_ci_gcc: gcc_download_ci_gcc } = toml.gcc.unwrap_or_default(); + + config.gcc_ci_mode = match gcc_download_ci_gcc { + Some(value) => match value { + true => GccCiMode::DownloadFromCi, + false => GccCiMode::BuildLocally, + }, + None => GccCiMode::default(), + }; match ccache { Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()), @@ -1312,28 +1312,26 @@ impl Config { Some(ci_llvm_bin.join(exe("FileCheck", config.host_target))); } - if let Some(dist) = toml.dist { - let Dist { - sign_folder, - upload_addr, - src_tarball, - compression_formats, - compression_profile, - include_mingw_linker, - vendor, - } = dist; - config.dist_sign_folder = sign_folder.map(PathBuf::from); - config.dist_upload_addr = upload_addr; - config.dist_compression_formats = compression_formats; - set(&mut config.dist_compression_profile, compression_profile); - set(&mut config.rust_dist_src, src_tarball); - set(&mut config.dist_include_mingw_linker, include_mingw_linker); - config.dist_vendor = vendor.unwrap_or_else(|| { - // If we're building from git or tarball sources, enable it by default. - config.rust_info.is_managed_git_subrepository() - || config.rust_info.is_from_tarball() - }); - } + let Dist { + sign_folder: dist_sign_folder, + upload_addr: dist_upload_addr, + src_tarball: dist_src_tarball, + compression_formats: dist_compression_formats, + compression_profile: dist_compression_profile, + include_mingw_linker: dist_include_mingw_linker, + vendor: dist_vendor, + } = toml.dist.unwrap_or_default(); + + config.dist_sign_folder = dist_sign_folder.map(PathBuf::from); + config.dist_upload_addr = dist_upload_addr; + config.dist_compression_formats = dist_compression_formats; + set(&mut config.dist_compression_profile, dist_compression_profile); + set(&mut config.rust_dist_src, dist_src_tarball); + set(&mut config.dist_include_mingw_linker, dist_include_mingw_linker); + config.dist_vendor = dist_vendor.unwrap_or_else(|| { + // If we're building from git or tarball sources, enable it by default. + config.rust_info.is_managed_git_subrepository() || config.rust_info.is_from_tarball() + }); config.initial_rustfmt = if let Some(r) = rustfmt { Some(r) diff --git a/src/bootstrap/src/core/config/toml/dist.rs b/src/bootstrap/src/core/config/toml/dist.rs index 4ab18762bb05..934d64d88991 100644 --- a/src/bootstrap/src/core/config/toml/dist.rs +++ b/src/bootstrap/src/core/config/toml/dist.rs @@ -12,6 +12,7 @@ use crate::core::config::toml::ReplaceOpt; use crate::{HashSet, PathBuf, define_config, exit}; define_config! { + #[derive(Default)] struct Dist { sign_folder: Option = "sign-folder", upload_addr: Option = "upload-addr", diff --git a/src/bootstrap/src/core/config/toml/gcc.rs b/src/bootstrap/src/core/config/toml/gcc.rs index de061309c804..9ea697edf159 100644 --- a/src/bootstrap/src/core/config/toml/gcc.rs +++ b/src/bootstrap/src/core/config/toml/gcc.rs @@ -12,6 +12,7 @@ use crate::{HashSet, PathBuf, define_config, exit}; define_config! { /// TOML representation of how the GCC build is configured. + #[derive(Default)] struct Gcc { download_ci_gcc: Option = "download-ci-gcc", } From 38ddefa15db96befe1ba5b2a2e02501e886d4417 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 14:51:14 +0530 Subject: [PATCH 0312/1134] add llvm default implementation --- src/bootstrap/src/core/config/config.rs | 207 ++++++++++----------- src/bootstrap/src/core/config/toml/llvm.rs | 1 + 2 files changed, 97 insertions(+), 111 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 47c228d3cc3f..66f21ba89e50 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1157,126 +1157,111 @@ impl Config { config.channel = channel; } - let mut llvm_tests = None; - let mut llvm_enzyme = None; - let mut llvm_offload = None; - let mut llvm_plugins = None; - - if let Some(llvm) = toml.llvm { - let Llvm { - optimize: optimize_toml, - thin_lto, - release_debuginfo, - assertions: _, - tests, - enzyme, - plugins, - static_libstdcpp, - libzstd, - ninja, - targets, - experimental_targets, - link_jobs, - link_shared, - version_suffix, - clang_cl, - cflags, - cxxflags, - ldflags, - use_libcxx, - use_linker, - allow_old_toolchain, - offload, - polly, - clang, - enable_warnings, - download_ci_llvm, - build_config, - } = llvm; - - set(&mut config.ninja_in_file, ninja); - llvm_tests = tests; - llvm_enzyme = enzyme; - llvm_offload = offload; - llvm_plugins = plugins; - set(&mut config.llvm_optimize, optimize_toml); - set(&mut config.llvm_thin_lto, thin_lto); - set(&mut config.llvm_release_debuginfo, release_debuginfo); - set(&mut config.llvm_static_stdcpp, static_libstdcpp); - set(&mut config.llvm_libzstd, libzstd); - if let Some(v) = link_shared { - config.llvm_link_shared.set(Some(v)); - } - config.llvm_targets.clone_from(&targets); - config.llvm_experimental_targets.clone_from(&experimental_targets); - config.llvm_link_jobs = link_jobs; - config.llvm_version_suffix.clone_from(&version_suffix); - config.llvm_clang_cl.clone_from(&clang_cl); - - config.llvm_cflags.clone_from(&cflags); - config.llvm_cxxflags.clone_from(&cxxflags); - config.llvm_ldflags.clone_from(&ldflags); - set(&mut config.llvm_use_libcxx, use_libcxx); - config.llvm_use_linker.clone_from(&use_linker); - config.llvm_allow_old_toolchain = allow_old_toolchain.unwrap_or(false); - config.llvm_offload = offload.unwrap_or(false); - config.llvm_polly = polly.unwrap_or(false); - config.llvm_clang = clang.unwrap_or(false); - config.llvm_enable_warnings = enable_warnings.unwrap_or(false); - config.llvm_build_config = build_config.clone().unwrap_or(Default::default()); - - config.llvm_from_ci = - config.parse_download_ci_llvm(download_ci_llvm, config.llvm_assertions); - - if config.llvm_from_ci { - let warn = |option: &str| { - println!( - "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build." - ); - println!( - "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false." - ); - }; + let Llvm { + optimize: optimize_toml, + thin_lto, + release_debuginfo, + assertions: _, + tests: llvm_tests, + enzyme: llvm_enzyme, + plugins: llvm_plugin, + static_libstdcpp, + libzstd, + ninja, + targets, + experimental_targets, + link_jobs, + link_shared, + version_suffix, + clang_cl, + cflags, + cxxflags, + ldflags, + use_libcxx, + use_linker, + allow_old_toolchain, + offload: llvm_offload, + polly, + clang, + enable_warnings, + download_ci_llvm, + build_config, + } = toml.llvm.unwrap_or_default(); + + set(&mut config.ninja_in_file, ninja); + set(&mut config.llvm_optimize, optimize_toml); + set(&mut config.llvm_thin_lto, thin_lto); + set(&mut config.llvm_release_debuginfo, release_debuginfo); + set(&mut config.llvm_static_stdcpp, static_libstdcpp); + set(&mut config.llvm_libzstd, libzstd); + if let Some(v) = link_shared { + config.llvm_link_shared.set(Some(v)); + } + config.llvm_targets.clone_from(&targets); + config.llvm_experimental_targets.clone_from(&experimental_targets); + config.llvm_link_jobs = link_jobs; + config.llvm_version_suffix.clone_from(&version_suffix); + config.llvm_clang_cl.clone_from(&clang_cl); + config.llvm_tests = llvm_tests.unwrap_or_default(); + config.llvm_enzyme = llvm_enzyme.unwrap_or_default(); + config.llvm_plugins = llvm_plugin.unwrap_or_default(); + + config.llvm_cflags.clone_from(&cflags); + config.llvm_cxxflags.clone_from(&cxxflags); + config.llvm_ldflags.clone_from(&ldflags); + set(&mut config.llvm_use_libcxx, use_libcxx); + config.llvm_use_linker.clone_from(&use_linker); + config.llvm_allow_old_toolchain = allow_old_toolchain.unwrap_or(false); + config.llvm_offload = llvm_offload.unwrap_or(false); + config.llvm_polly = polly.unwrap_or(false); + config.llvm_clang = clang.unwrap_or(false); + config.llvm_enable_warnings = enable_warnings.unwrap_or(false); + config.llvm_build_config = build_config.clone().unwrap_or(Default::default()); - if static_libstdcpp.is_some() { - warn("static-libstdcpp"); - } + config.llvm_from_ci = + config.parse_download_ci_llvm(download_ci_llvm, config.llvm_assertions); - if link_shared.is_some() { - warn("link-shared"); - } + if config.llvm_from_ci { + let warn = |option: &str| { + println!( + "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build." + ); + println!( + "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false." + ); + }; - // FIXME(#129153): instead of all the ad-hoc `download-ci-llvm` checks that follow, - // use the `builder-config` present in tarballs since #128822 to compare the local - // config to the ones used to build the LLVM artifacts on CI, and only notify users - // if they've chosen a different value. + if static_libstdcpp.is_some() { + warn("static-libstdcpp"); + } - if libzstd.is_some() { - println!( - "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \ - like almost all `llvm.*` options, will be ignored and set by the LLVM CI \ - artifacts builder config." - ); - println!( - "HELP: To use `llvm.libzstd` for LLVM/LLD builds, set `download-ci-llvm` option to false." - ); - } + if link_shared.is_some() { + warn("link-shared"); } - if !config.llvm_from_ci && config.llvm_thin_lto && link_shared.is_none() { - // If we're building with ThinLTO on, by default we want to link - // to LLVM shared, to avoid re-doing ThinLTO (which happens in - // the link step) with each stage. - config.llvm_link_shared.set(Some(true)); + // FIXME(#129153): instead of all the ad-hoc `download-ci-llvm` checks that follow, + // use the `builder-config` present in tarballs since #128822 to compare the local + // config to the ones used to build the LLVM artifacts on CI, and only notify users + // if they've chosen a different value. + + if libzstd.is_some() { + println!( + "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \ + like almost all `llvm.*` options, will be ignored and set by the LLVM CI \ + artifacts builder config." + ); + println!( + "HELP: To use `llvm.libzstd` for LLVM/LLD builds, set `download-ci-llvm` option to false." + ); } - } else { - config.llvm_from_ci = config.parse_download_ci_llvm(None, false); } - config.llvm_tests = llvm_tests.unwrap_or(false); - config.llvm_enzyme = llvm_enzyme.unwrap_or(false); - config.llvm_offload = llvm_offload.unwrap_or(false); - config.llvm_plugins = llvm_plugins.unwrap_or(false); + if !config.llvm_from_ci && config.llvm_thin_lto && link_shared.is_none() { + // If we're building with ThinLTO on, by default we want to link + // to LLVM shared, to avoid re-doing ThinLTO (which happens in + // the link step) with each stage. + config.llvm_link_shared.set(Some(true)); + } let Gcc { download_ci_gcc: gcc_download_ci_gcc } = toml.gcc.unwrap_or_default(); diff --git a/src/bootstrap/src/core/config/toml/llvm.rs b/src/bootstrap/src/core/config/toml/llvm.rs index 0ab290b9bd1e..9751837a8879 100644 --- a/src/bootstrap/src/core/config/toml/llvm.rs +++ b/src/bootstrap/src/core/config/toml/llvm.rs @@ -9,6 +9,7 @@ use crate::{HashMap, HashSet, PathBuf, define_config, exit}; define_config! { /// TOML representation of how the LLVM build is configured. + #[derive(Default)] struct Llvm { optimize: Option = "optimize", thin_lto: Option = "thin-lto", From 8b80cb0ac72d2d577e4b934e6c19376a6104527d Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 15:22:14 +0530 Subject: [PATCH 0313/1134] add rust default implementation --- src/bootstrap/src/core/config/config.rs | 374 ++++++++++----------- src/bootstrap/src/core/config/toml/rust.rs | 1 + 2 files changed, 175 insertions(+), 200 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 66f21ba89e50..b4163d70e3b8 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -893,198 +893,167 @@ impl Config { config.target_config.insert(TargetSelection::from_user(&triple), target); } } - let mut debug = None; - let mut rustc_debug_assertions = None; - let mut std_debug_assertions = None; - let mut tools_debug_assertions = None; - let mut overflow_checks = None; - let mut overflow_checks_std = None; - let mut debug_logging = None; - let mut debuginfo_level = None; - let mut debuginfo_level_rustc = None; - let mut debuginfo_level_std = None; - let mut debuginfo_level_tools = None; - let mut debuginfo_level_tests = None; - let mut optimize = None; - let mut lld_enabled = None; - let mut std_features = None; - - if let Some(rust) = toml.rust { - let Rust { - optimize: optimize_toml, - debug: debug_toml, - codegen_units, - codegen_units_std, - rustc_debug_assertions: rustc_debug_assertions_toml, - std_debug_assertions: std_debug_assertions_toml, - tools_debug_assertions: tools_debug_assertions_toml, - overflow_checks: overflow_checks_toml, - overflow_checks_std: overflow_checks_std_toml, - debug_logging: debug_logging_toml, - debuginfo_level: debuginfo_level_toml, - debuginfo_level_rustc: debuginfo_level_rustc_toml, - debuginfo_level_std: debuginfo_level_std_toml, - debuginfo_level_tools: debuginfo_level_tools_toml, - debuginfo_level_tests: debuginfo_level_tests_toml, - backtrace, - incremental, - randomize_layout, - default_linker, - channel: _, // already handled above - musl_root, - rpath, - verbose_tests, - optimize_tests, - codegen_tests, - omit_git_hash: _, // already handled above - dist_src, - save_toolstates, - codegen_backends, - lld: lld_enabled_toml, - llvm_tools, - llvm_bitcode_linker, - deny_warnings, - backtrace_on_ice, - verify_llvm_ir, - thin_lto_import_instr_limit, - remap_debuginfo, - jemalloc, - test_compare_mode, - llvm_libunwind, - control_flow_guard, - ehcont_guard, - new_symbol_mangling, - profile_generate, - profile_use, - download_rustc, - lto, - validate_mir_opts, - frame_pointers, - stack_protector, - strip, - lld_mode, - std_features: std_features_toml, - } = rust; - - // FIXME(#133381): alt rustc builds currently do *not* have rustc debug assertions - // enabled. We should not download a CI alt rustc if we need rustc to have debug - // assertions (e.g. for crashes test suite). This can be changed once something like - // [Enable debug assertions on alt - // builds](https://github.com/rust-lang/rust/pull/131077) lands. - // - // Note that `rust.debug = true` currently implies `rust.debug-assertions = true`! - // - // This relies also on the fact that the global default for `download-rustc` will be - // `false` if it's not explicitly set. - let debug_assertions_requested = matches!(rustc_debug_assertions_toml, Some(true)) - || (matches!(debug_toml, Some(true)) - && !matches!(rustc_debug_assertions_toml, Some(false))); - - if debug_assertions_requested - && let Some(ref opt) = download_rustc - && opt.is_string_or_true() - { - eprintln!( - "WARN: currently no CI rustc builds have rustc debug assertions \ - enabled. Please either set `rust.debug-assertions` to `false` if you \ - want to use download CI rustc or set `rust.download-rustc` to `false`." - ); - } - config.download_rustc_commit = config.download_ci_rustc_commit( - download_rustc, - debug_assertions_requested, - config.llvm_assertions, + let Rust { + optimize: rust_optimize_toml, + debug: rust_debug_toml, + codegen_units: rust_codegen_units_toml, + codegen_units_std: rust_codegen_units_std_toml, + rustc_debug_assertions: rust_rustc_debug_assertions_toml, + std_debug_assertions: rust_std_debug_assertions_toml, + tools_debug_assertions: rust_tools_debug_assertions_toml, + overflow_checks: rust_overflow_checks_toml, + overflow_checks_std: rust_overflow_checks_std_toml, + debug_logging: rust_debug_logging_toml, + debuginfo_level: rust_debuginfo_level_toml, + debuginfo_level_rustc: rust_debuginfo_level_rustc_toml, + debuginfo_level_std: rust_debuginfo_level_std_toml, + debuginfo_level_tools: rust_debuginfo_level_tools_toml, + debuginfo_level_tests: rust_debuginfo_level_tests_toml, + backtrace: rust_backtrace_toml, + incremental: rust_incremental_toml, + randomize_layout: rust_randomize_layout_toml, + default_linker: rust_default_linker_toml, + channel: _, // already handled above + musl_root: rust_musl_root_toml, + rpath: rust_rpath_toml, + verbose_tests: rust_verbose_tests_toml, + optimize_tests: rust_optimize_tests_toml, + codegen_tests: rust_codegen_tests_toml, + omit_git_hash: _, // already handled above + dist_src: rust_dist_src_toml, + save_toolstates: rust_save_toolstates_toml, + codegen_backends: rust_codegen_backends_toml, + lld: rust_lld_enabled_toml, + llvm_tools: rust_llvm_tools_toml, + llvm_bitcode_linker: rust_llvm_bitcode_linker_toml, + deny_warnings: rust_deny_warnings_toml, + backtrace_on_ice: rust_backtrace_on_ice_toml, + verify_llvm_ir: rust_verify_llvm_ir_toml, + thin_lto_import_instr_limit: rust_thin_lto_import_instr_limit_toml, + remap_debuginfo: rust_remap_debuginfo_toml, + jemalloc: rust_jemalloc_toml, + test_compare_mode: rust_test_compare_mode_toml, + llvm_libunwind: rust_llvm_libunwind_toml, + control_flow_guard: rust_control_flow_guard_toml, + ehcont_guard: rust_ehcont_guard_toml, + new_symbol_mangling: rust_new_symbol_mangling_toml, + profile_generate: rust_profile_generate_toml, + profile_use: rust_profile_use_toml, + download_rustc: rust_download_rustc_toml, + lto: rust_lto_toml, + validate_mir_opts: rust_validate_mir_opts_toml, + frame_pointers: rust_frame_pointers_toml, + stack_protector: rust_stack_protector_toml, + strip: rust_strip_toml, + lld_mode: rust_lld_mode_toml, + std_features: rust_std_features_toml, + } = toml.rust.unwrap_or_default(); + + // FIXME(#133381): alt rustc builds currently do *not* have rustc debug assertions + // enabled. We should not download a CI alt rustc if we need rustc to have debug + // assertions (e.g. for crashes test suite). This can be changed once something like + // [Enable debug assertions on alt + // builds](https://github.com/rust-lang/rust/pull/131077) lands. + // + // Note that `rust.debug = true` currently implies `rust.debug-assertions = true`! + // + // This relies also on the fact that the global default for `download-rustc` will be + // `false` if it's not explicitly set. + let debug_assertions_requested = matches!(rust_rustc_debug_assertions_toml, Some(true)) + || (matches!(rust_debug_toml, Some(true)) + && !matches!(rust_rustc_debug_assertions_toml, Some(false))); + + if debug_assertions_requested + && let Some(ref opt) = rust_download_rustc_toml + && opt.is_string_or_true() + { + eprintln!( + "WARN: currently no CI rustc builds have rustc debug assertions \ + enabled. Please either set `rust.debug-assertions` to `false` if you \ + want to use download CI rustc or set `rust.download-rustc` to `false`." ); + } - debug = debug_toml; - rustc_debug_assertions = rustc_debug_assertions_toml; - std_debug_assertions = std_debug_assertions_toml; - tools_debug_assertions = tools_debug_assertions_toml; - overflow_checks = overflow_checks_toml; - overflow_checks_std = overflow_checks_std_toml; - debug_logging = debug_logging_toml; - debuginfo_level = debuginfo_level_toml; - debuginfo_level_rustc = debuginfo_level_rustc_toml; - debuginfo_level_std = debuginfo_level_std_toml; - debuginfo_level_tools = debuginfo_level_tools_toml; - debuginfo_level_tests = debuginfo_level_tests_toml; - lld_enabled = lld_enabled_toml; - std_features = std_features_toml; - - if optimize_toml.as_ref().is_some_and(|v| matches!(v, RustOptimize::Bool(false))) { - eprintln!( - "WARNING: setting `optimize` to `false` is known to cause errors and \ - should be considered unsupported. Refer to `bootstrap.example.toml` \ - for more details." - ); - } + config.download_rustc_commit = config.download_ci_rustc_commit( + rust_download_rustc_toml, + debug_assertions_requested, + config.llvm_assertions, + ); - optimize = optimize_toml; - config.rust_new_symbol_mangling = new_symbol_mangling; - set(&mut config.rust_optimize_tests, optimize_tests); - set(&mut config.codegen_tests, codegen_tests); - set(&mut config.rust_rpath, rpath); - set(&mut config.rust_strip, strip); - set(&mut config.rust_frame_pointers, frame_pointers); - config.rust_stack_protector = stack_protector; - set(&mut config.jemalloc, jemalloc); - set(&mut config.test_compare_mode, test_compare_mode); - set(&mut config.backtrace, backtrace); - set(&mut config.rust_dist_src, dist_src); - set(&mut config.verbose_tests, verbose_tests); - // in the case "false" is set explicitly, do not overwrite the command line args - if let Some(true) = incremental { - config.incremental = true; - } - set(&mut config.lld_mode, lld_mode); - set(&mut config.llvm_bitcode_linker_enabled, llvm_bitcode_linker); - - config.rust_randomize_layout = randomize_layout.unwrap_or_default(); - config.llvm_tools_enabled = llvm_tools.unwrap_or(true); - - config.llvm_enzyme = config.channel == "dev" || config.channel == "nightly"; - config.rustc_default_linker = default_linker; - config.musl_root = musl_root.map(PathBuf::from); - config.save_toolstates = save_toolstates.map(PathBuf::from); - set( - &mut config.deny_warnings, - match flags_warnings { - Warnings::Deny => Some(true), - Warnings::Warn => Some(false), - Warnings::Default => deny_warnings, - }, - ); - set(&mut config.backtrace_on_ice, backtrace_on_ice); - set(&mut config.rust_verify_llvm_ir, verify_llvm_ir); - config.rust_thin_lto_import_instr_limit = thin_lto_import_instr_limit; - set(&mut config.rust_remap_debuginfo, remap_debuginfo); - set(&mut config.control_flow_guard, control_flow_guard); - set(&mut config.ehcont_guard, ehcont_guard); - config.llvm_libunwind_default = - llvm_libunwind.map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")); - set( - &mut config.rust_codegen_backends, - codegen_backends.map(|backends| validate_codegen_backends(backends, "rust")), + if rust_optimize_toml.as_ref().is_some_and(|v| matches!(v, RustOptimize::Bool(false))) { + eprintln!( + "WARNING: setting `optimize` to `false` is known to cause errors and \ + should be considered unsupported. Refer to `bootstrap.example.toml` \ + for more details." ); + } - config.rust_codegen_units = codegen_units.map(threads_from_config); - config.rust_codegen_units_std = codegen_units_std.map(threads_from_config); + config.rust_new_symbol_mangling = rust_new_symbol_mangling_toml; + set(&mut config.rust_optimize_tests, rust_optimize_tests_toml); + set(&mut config.codegen_tests, rust_codegen_tests_toml); + set(&mut config.rust_rpath, rust_rpath_toml); + set(&mut config.rust_strip, rust_strip_toml); + set(&mut config.rust_frame_pointers, rust_frame_pointers_toml); + config.rust_stack_protector = rust_stack_protector_toml; + set(&mut config.jemalloc, rust_jemalloc_toml); + set(&mut config.test_compare_mode, rust_test_compare_mode_toml); + set(&mut config.backtrace, rust_backtrace_toml); + set(&mut config.rust_dist_src, rust_dist_src_toml); + set(&mut config.verbose_tests, rust_verbose_tests_toml); + // in the case "false" is set explicitly, do not overwrite the command line args + if let Some(true) = rust_incremental_toml { + config.incremental = true; + } + set(&mut config.lld_mode, rust_lld_mode_toml); + set(&mut config.llvm_bitcode_linker_enabled, rust_llvm_bitcode_linker_toml); + + config.rust_randomize_layout = rust_randomize_layout_toml.unwrap_or_default(); + config.llvm_tools_enabled = rust_llvm_tools_toml.unwrap_or(true); + + config.llvm_enzyme = config.channel == "dev" || config.channel == "nightly"; + config.rustc_default_linker = rust_default_linker_toml; + config.musl_root = rust_musl_root_toml.map(PathBuf::from); + config.save_toolstates = rust_save_toolstates_toml.map(PathBuf::from); + set( + &mut config.deny_warnings, + match flags_warnings { + Warnings::Deny => Some(true), + Warnings::Warn => Some(false), + Warnings::Default => rust_deny_warnings_toml, + }, + ); + set(&mut config.backtrace_on_ice, rust_backtrace_on_ice_toml); + set(&mut config.rust_verify_llvm_ir, rust_verify_llvm_ir_toml); + config.rust_thin_lto_import_instr_limit = rust_thin_lto_import_instr_limit_toml; + set(&mut config.rust_remap_debuginfo, rust_remap_debuginfo_toml); + set(&mut config.control_flow_guard, rust_control_flow_guard_toml); + set(&mut config.ehcont_guard, rust_ehcont_guard_toml); + config.llvm_libunwind_default = rust_llvm_libunwind_toml + .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")); + set( + &mut config.rust_codegen_backends, + rust_codegen_backends_toml.map(|backends| validate_codegen_backends(backends, "rust")), + ); - if config.rust_profile_use.is_none() { - config.rust_profile_use = profile_use; - } + config.rust_codegen_units = rust_codegen_units_toml.map(threads_from_config); + config.rust_codegen_units_std = rust_codegen_units_std_toml.map(threads_from_config); - if config.rust_profile_generate.is_none() { - config.rust_profile_generate = profile_generate; - } + if config.rust_profile_use.is_none() { + config.rust_profile_use = rust_profile_use_toml; + } - config.rust_lto = - lto.as_deref().map(|value| RustcLto::from_str(value).unwrap()).unwrap_or_default(); - config.rust_validate_mir_opts = validate_mir_opts; + if config.rust_profile_generate.is_none() { + config.rust_profile_generate = rust_profile_generate_toml; } - config.rust_optimize = optimize.unwrap_or(RustOptimize::Bool(true)); + config.rust_lto = rust_lto_toml + .as_deref() + .map(|value| RustcLto::from_str(value).unwrap()) + .unwrap_or_default(); + config.rust_validate_mir_opts = rust_validate_mir_opts_toml; + + config.rust_optimize = rust_optimize_toml.unwrap_or(RustOptimize::Bool(true)); // We make `x86_64-unknown-linux-gnu` use the self-contained linker by default, so we will // build our internal lld and use it as the default linker, by setting the `rust.lld` config @@ -1107,36 +1076,41 @@ impl Config { .is_none_or(|target_config| target_config.llvm_config.is_none()); let enable_lld = config.llvm_from_ci || no_llvm_config; // Prefer the config setting in case an explicit opt-out is needed. - config.lld_enabled = lld_enabled.unwrap_or(enable_lld); + config.lld_enabled = rust_lld_enabled_toml.unwrap_or(enable_lld); } else { - set(&mut config.lld_enabled, lld_enabled); + set(&mut config.lld_enabled, rust_lld_enabled_toml); } let default_std_features = BTreeSet::from([String::from("panic-unwind")]); - config.rust_std_features = std_features.unwrap_or(default_std_features); + config.rust_std_features = rust_std_features_toml.unwrap_or(default_std_features); - let default = debug == Some(true); - config.rustc_debug_assertions = rustc_debug_assertions.unwrap_or(default); - config.std_debug_assertions = std_debug_assertions.unwrap_or(config.rustc_debug_assertions); + let default = rust_debug_toml == Some(true); + config.rustc_debug_assertions = rust_rustc_debug_assertions_toml.unwrap_or(default); + config.std_debug_assertions = + rust_std_debug_assertions_toml.unwrap_or(config.rustc_debug_assertions); config.tools_debug_assertions = - tools_debug_assertions.unwrap_or(config.rustc_debug_assertions); - config.rust_overflow_checks = overflow_checks.unwrap_or(default); + rust_tools_debug_assertions_toml.unwrap_or(config.rustc_debug_assertions); + config.rust_overflow_checks = rust_overflow_checks_toml.unwrap_or(default); config.rust_overflow_checks_std = - overflow_checks_std.unwrap_or(config.rust_overflow_checks); + rust_overflow_checks_std_toml.unwrap_or(config.rust_overflow_checks); - config.rust_debug_logging = debug_logging.unwrap_or(config.rustc_debug_assertions); + config.rust_debug_logging = + rust_debug_logging_toml.unwrap_or(config.rustc_debug_assertions); let with_defaults = |debuginfo_level_specific: Option<_>| { - debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) { - DebuginfoLevel::Limited - } else { - DebuginfoLevel::None - }) + debuginfo_level_specific.or(rust_debuginfo_level_toml).unwrap_or( + if rust_debug_toml == Some(true) { + DebuginfoLevel::Limited + } else { + DebuginfoLevel::None + }, + ) }; - config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc); - config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std); - config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools); - config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(DebuginfoLevel::None); + config.rust_debuginfo_level_rustc = with_defaults(rust_debuginfo_level_rustc_toml); + config.rust_debuginfo_level_std = with_defaults(rust_debuginfo_level_std_toml); + config.rust_debuginfo_level_tools = with_defaults(rust_debuginfo_level_tools_toml); + config.rust_debuginfo_level_tests = + rust_debuginfo_level_tests_toml.unwrap_or(DebuginfoLevel::None); config.reproducible_artifacts = flags_reproducible_artifact; config.description = description; diff --git a/src/bootstrap/src/core/config/toml/rust.rs b/src/bootstrap/src/core/config/toml/rust.rs index 4bd1eac683ce..fd154200bc7a 100644 --- a/src/bootstrap/src/core/config/toml/rust.rs +++ b/src/bootstrap/src/core/config/toml/rust.rs @@ -10,6 +10,7 @@ use crate::{BTreeSet, HashSet, PathBuf, TargetSelection, define_config, exit}; define_config! { /// TOML representation of how the Rust build is configured. + #[derive(Default)] struct Rust { optimize: Option = "optimize", debug: Option = "debug", From d3d3b10e828773371cae6b85e2deab1f13df215c Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 15:34:29 +0530 Subject: [PATCH 0314/1134] make llvm toml fields follow a specific naming convention --- src/bootstrap/src/core/config/config.rs | 118 ++++++++++++------------ 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index b4163d70e3b8..3f373a667899 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1132,68 +1132,68 @@ impl Config { } let Llvm { - optimize: optimize_toml, - thin_lto, - release_debuginfo, + optimize: llvm_optimize_toml, + thin_lto: llvm_thin_lto_toml, + release_debuginfo: llvm_release_debuginfo_toml, assertions: _, - tests: llvm_tests, - enzyme: llvm_enzyme, - plugins: llvm_plugin, - static_libstdcpp, - libzstd, - ninja, - targets, - experimental_targets, - link_jobs, - link_shared, - version_suffix, - clang_cl, - cflags, - cxxflags, - ldflags, - use_libcxx, - use_linker, - allow_old_toolchain, - offload: llvm_offload, - polly, - clang, - enable_warnings, - download_ci_llvm, - build_config, + tests: llvm_tests_toml, + enzyme: llvm_enzyme_toml, + plugins: llvm_plugin_toml, + static_libstdcpp: llvm_static_libstdcpp_toml, + libzstd: llvm_libzstd_toml, + ninja: llvm_ninja_toml, + targets: llvm_targets_toml, + experimental_targets: llvm_experimental_targets_toml, + link_jobs: llvm_link_jobs_toml, + link_shared: llvm_link_shared_toml, + version_suffix: llvm_version_suffix_toml, + clang_cl: llvm_clang_cl_toml, + cflags: llvm_cflags_toml, + cxxflags: llvm_cxxflags_toml, + ldflags: llvm_ldflags_toml, + use_libcxx: llvm_use_libcxx_toml, + use_linker: llvm_use_linker_toml, + allow_old_toolchain: llvm_allow_old_toolchain_toml, + offload: llvm_offload_toml, + polly: llvm_polly_toml, + clang: llvm_clang_toml, + enable_warnings: llvm_enable_warnings_toml, + download_ci_llvm: llvm_download_ci_llvm_toml, + build_config: llvm_build_config_toml, } = toml.llvm.unwrap_or_default(); - set(&mut config.ninja_in_file, ninja); - set(&mut config.llvm_optimize, optimize_toml); - set(&mut config.llvm_thin_lto, thin_lto); - set(&mut config.llvm_release_debuginfo, release_debuginfo); - set(&mut config.llvm_static_stdcpp, static_libstdcpp); - set(&mut config.llvm_libzstd, libzstd); - if let Some(v) = link_shared { + set(&mut config.ninja_in_file, llvm_ninja_toml); + set(&mut config.llvm_optimize, llvm_optimize_toml); + set(&mut config.llvm_thin_lto, llvm_thin_lto_toml); + set(&mut config.llvm_release_debuginfo, llvm_release_debuginfo_toml); + set(&mut config.llvm_static_stdcpp, llvm_static_libstdcpp_toml); + set(&mut config.llvm_libzstd, llvm_libzstd_toml); + if let Some(v) = llvm_link_shared_toml { config.llvm_link_shared.set(Some(v)); } - config.llvm_targets.clone_from(&targets); - config.llvm_experimental_targets.clone_from(&experimental_targets); - config.llvm_link_jobs = link_jobs; - config.llvm_version_suffix.clone_from(&version_suffix); - config.llvm_clang_cl.clone_from(&clang_cl); - config.llvm_tests = llvm_tests.unwrap_or_default(); - config.llvm_enzyme = llvm_enzyme.unwrap_or_default(); - config.llvm_plugins = llvm_plugin.unwrap_or_default(); - - config.llvm_cflags.clone_from(&cflags); - config.llvm_cxxflags.clone_from(&cxxflags); - config.llvm_ldflags.clone_from(&ldflags); - set(&mut config.llvm_use_libcxx, use_libcxx); - config.llvm_use_linker.clone_from(&use_linker); - config.llvm_allow_old_toolchain = allow_old_toolchain.unwrap_or(false); - config.llvm_offload = llvm_offload.unwrap_or(false); - config.llvm_polly = polly.unwrap_or(false); - config.llvm_clang = clang.unwrap_or(false); - config.llvm_enable_warnings = enable_warnings.unwrap_or(false); - config.llvm_build_config = build_config.clone().unwrap_or(Default::default()); + config.llvm_targets.clone_from(&llvm_targets_toml); + config.llvm_experimental_targets.clone_from(&llvm_experimental_targets_toml); + config.llvm_link_jobs = llvm_link_jobs_toml; + config.llvm_version_suffix.clone_from(&llvm_version_suffix_toml); + config.llvm_clang_cl.clone_from(&llvm_clang_cl_toml); + config.llvm_tests = llvm_tests_toml.unwrap_or_default(); + config.llvm_enzyme = llvm_enzyme_toml.unwrap_or_default(); + config.llvm_plugins = llvm_plugin_toml.unwrap_or_default(); + + config.llvm_cflags.clone_from(&llvm_cflags_toml); + config.llvm_cxxflags.clone_from(&llvm_cxxflags_toml); + config.llvm_ldflags.clone_from(&llvm_ldflags_toml); + set(&mut config.llvm_use_libcxx, llvm_use_libcxx_toml); + config.llvm_use_linker.clone_from(&llvm_use_linker_toml); + config.llvm_allow_old_toolchain = llvm_allow_old_toolchain_toml.unwrap_or(false); + config.llvm_offload = llvm_offload_toml.unwrap_or(false); + config.llvm_polly = llvm_polly_toml.unwrap_or(false); + config.llvm_clang = llvm_clang_toml.unwrap_or(false); + config.llvm_enable_warnings = llvm_enable_warnings_toml.unwrap_or(false); + config.llvm_build_config = llvm_build_config_toml.clone().unwrap_or(Default::default()); config.llvm_from_ci = - config.parse_download_ci_llvm(download_ci_llvm, config.llvm_assertions); + config.parse_download_ci_llvm(llvm_download_ci_llvm_toml, config.llvm_assertions); if config.llvm_from_ci { let warn = |option: &str| { @@ -1205,11 +1205,11 @@ impl Config { ); }; - if static_libstdcpp.is_some() { + if llvm_static_libstdcpp_toml.is_some() { warn("static-libstdcpp"); } - if link_shared.is_some() { + if llvm_link_shared_toml.is_some() { warn("link-shared"); } @@ -1218,7 +1218,7 @@ impl Config { // config to the ones used to build the LLVM artifacts on CI, and only notify users // if they've chosen a different value. - if libzstd.is_some() { + if llvm_libzstd_toml.is_some() { println!( "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \ like almost all `llvm.*` options, will be ignored and set by the LLVM CI \ @@ -1230,7 +1230,7 @@ impl Config { } } - if !config.llvm_from_ci && config.llvm_thin_lto && link_shared.is_none() { + if !config.llvm_from_ci && config.llvm_thin_lto && llvm_link_shared_toml.is_none() { // If we're building with ThinLTO on, by default we want to link // to LLVM shared, to avoid re-doing ThinLTO (which happens in // the link step) with each stage. From c008a4b49c897ce511c37fbb9cb7c97cc3b22ec7 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 17:47:15 +0530 Subject: [PATCH 0315/1134] make gcc toml fields follow a specific naming convention --- src/bootstrap/src/core/config/config.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 3f373a667899..a42a8e7fe7fc 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1237,9 +1237,9 @@ impl Config { config.llvm_link_shared.set(Some(true)); } - let Gcc { download_ci_gcc: gcc_download_ci_gcc } = toml.gcc.unwrap_or_default(); + let Gcc { download_ci_gcc: gcc_download_ci_gcc_toml } = toml.gcc.unwrap_or_default(); - config.gcc_ci_mode = match gcc_download_ci_gcc { + config.gcc_ci_mode = match gcc_download_ci_gcc_toml { Some(value) => match value { true => GccCiMode::DownloadFromCi, false => GccCiMode::BuildLocally, From 4d2a2c22b566429aee5a19cc04f182a43bf35f72 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 17:49:30 +0530 Subject: [PATCH 0316/1134] make dist toml fields follow a specific naming convention --- src/bootstrap/src/core/config/config.rs | 28 ++++++++++++------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index a42a8e7fe7fc..7e8e66b36980 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1272,22 +1272,22 @@ impl Config { } let Dist { - sign_folder: dist_sign_folder, - upload_addr: dist_upload_addr, - src_tarball: dist_src_tarball, - compression_formats: dist_compression_formats, - compression_profile: dist_compression_profile, - include_mingw_linker: dist_include_mingw_linker, - vendor: dist_vendor, + sign_folder: dist_sign_folder_toml, + upload_addr: dist_upload_addr_toml, + src_tarball: dist_src_tarball_toml, + compression_formats: dist_compression_formats_toml, + compression_profile: dist_compression_profile_toml, + include_mingw_linker: dist_include_mingw_linker_toml, + vendor: dist_vendor_toml, } = toml.dist.unwrap_or_default(); - config.dist_sign_folder = dist_sign_folder.map(PathBuf::from); - config.dist_upload_addr = dist_upload_addr; - config.dist_compression_formats = dist_compression_formats; - set(&mut config.dist_compression_profile, dist_compression_profile); - set(&mut config.rust_dist_src, dist_src_tarball); - set(&mut config.dist_include_mingw_linker, dist_include_mingw_linker); - config.dist_vendor = dist_vendor.unwrap_or_else(|| { + config.dist_sign_folder = dist_sign_folder_toml.map(PathBuf::from); + config.dist_upload_addr = dist_upload_addr_toml; + config.dist_compression_formats = dist_compression_formats_toml; + set(&mut config.dist_compression_profile, dist_compression_profile_toml); + set(&mut config.rust_dist_src, dist_src_tarball_toml); + set(&mut config.dist_include_mingw_linker, dist_include_mingw_linker_toml); + config.dist_vendor = dist_vendor_toml.unwrap_or_else(|| { // If we're building from git or tarball sources, enable it by default. config.rust_info.is_managed_git_subrepository() || config.rust_info.is_from_tarball() }); From ad98550f708d1b18e7c2ea800d67e9662eee6995 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 17:51:38 +0530 Subject: [PATCH 0317/1134] make install toml fields follow a specific naming convention --- src/bootstrap/src/core/config/config.rs | 28 ++++++++++++------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 7e8e66b36980..8736f271cdac 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -759,22 +759,22 @@ impl Config { config.verbose_tests = config.is_verbose(); let Install { - prefix: install_prefix, - sysconfdir: install_sysconfdir, - docdir: install_docdir, - bindir: install_bindir, - libdir: install_libdir, - mandir: install_mandir, - datadir: install_datadir, + prefix: install_prefix_toml, + sysconfdir: install_sysconfdir_toml, + docdir: install_docdir_toml, + bindir: install_bindir_toml, + libdir: install_libdir_toml, + mandir: install_mandir_toml, + datadir: install_datadir_toml, } = toml.install.unwrap_or_default(); - let install_prefix = install_prefix.map(PathBuf::from); - let install_sysconfdir = install_sysconfdir.map(PathBuf::from); - let install_docdir = install_docdir.map(PathBuf::from); - let install_bindir = install_bindir.map(PathBuf::from); - let install_libdir = install_libdir.map(PathBuf::from); - let install_mandir = install_mandir.map(PathBuf::from); - let install_datadir = install_datadir.map(PathBuf::from); + let install_prefix = install_prefix_toml.map(PathBuf::from); + let install_sysconfdir = install_sysconfdir_toml.map(PathBuf::from); + let install_docdir = install_docdir_toml.map(PathBuf::from); + let install_bindir = install_bindir_toml.map(PathBuf::from); + let install_libdir = install_libdir_toml.map(PathBuf::from); + let install_mandir = install_mandir_toml.map(PathBuf::from); + let install_datadir = install_datadir_toml.map(PathBuf::from); config.prefix = install_prefix; config.sysconfdir = install_sysconfdir; config.datadir = install_datadir; From 2c96132c72a07d149511e01f3c3045911eeb8a53 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 18:12:33 +0530 Subject: [PATCH 0318/1134] make build toml fields follow a specific naming convention --- src/bootstrap/src/core/config/config.rs | 245 ++++++++++++------------ 1 file changed, 120 insertions(+), 125 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 8736f271cdac..f8df5687f5a7 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -501,86 +501,85 @@ impl Config { // Now override TOML values with flags, to make sure that we won't later override flags with // TOML values by accident instead, because flags have higher priority. let Build { - description, - mut build, - host, - target, - build_dir, - cargo, - rustc, - rustfmt, - cargo_clippy, - docs, - compiler_docs, - library_docs_private_items, - docs_minification, - submodules, - gdb, - lldb, - nodejs, - npm, - python, - reuse, - locked_deps, - vendor, - full_bootstrap, - bootstrap_cache_path, - extended, - tools, - tool, - verbose: build_verbose, - sanitizers, - profiler, - cargo_native_static, - low_priority, - configure_args, - local_rebuild, - print_step_timings, - print_step_rusage, - check_stage, - doc_stage, - build_stage, - test_stage, - install_stage, - dist_stage, - bench_stage, - patch_binaries_for_nix, + description: build_description_toml, + build: mut build_build_toml, + host: build_host_toml, + target: build_target_toml, + build_dir: build_build_dir_toml, + cargo: build_cargo_toml, + rustc: build_rustc_toml, + rustfmt: build_rustfmt_toml, + cargo_clippy: build_cargo_clippy_toml, + docs: build_docs_toml, + compiler_docs: build_compiler_docs_toml, + library_docs_private_items: build_library_docs_private_items_toml, + docs_minification: build_docs_minification_toml, + submodules: build_submodules_toml, + gdb: build_gdb_toml, + lldb: build_lldb_toml, + nodejs: build_nodejs_toml, + npm: build_npm_toml, + python: build_python_toml, + reuse: build_reuse_toml, + locked_deps: build_locked_deps_toml, + vendor: build_vendor_toml, + full_bootstrap: build_full_bootstrap_toml, + bootstrap_cache_path: build_bootstrap_cache_path_toml, + extended: build_extended_toml, + tools: build_tools_toml, + tool: build_tool_toml, + verbose: build_verbose_toml, + sanitizers: build_sanitizers_toml, + profiler: build_profiler_toml, + cargo_native_static: build_cargo_native_static_toml, + low_priority: build_low_priority_toml, + configure_args: build_configure_args_toml, + local_rebuild: build_local_rebuild_toml, + print_step_timings: build_print_step_timings_toml, + print_step_rusage: build_print_step_rusage_toml, + check_stage: build_check_stage_toml, + doc_stage: build_doc_stage_toml, + build_stage: build_build_stage_toml, + test_stage: build_test_stage_toml, + install_stage: build_install_stage_toml, + dist_stage: build_dist_stage_toml, + bench_stage: build_bench_stage_toml, + patch_binaries_for_nix: build_patch_binaries_for_nix_toml, // This field is only used by bootstrap.py metrics: _, - android_ndk, - optimized_compiler_builtins, - mut jobs, - compiletest_diff_tool, - compiletest_allow_stage0, - compiletest_use_stage0_libtest, - tidy_extra_checks, - ccache, - exclude, + android_ndk: build_android_ndk_toml, + optimized_compiler_builtins: build_optimized_compiler_builtins_toml, + jobs: mut build_jobs_toml, + compiletest_diff_tool: build_compiletest_diff_tool_toml, + compiletest_use_stage0_libtest: build_compiletest_use_stage0_libtest_toml, + tidy_extra_checks: build_tidy_extra_checks_toml, + ccache: build_ccache_toml, + exclude: build_exclude_toml, } = toml.build.unwrap_or_default(); - jobs = flags_jobs.or(jobs); - build = flags_build.or(build); - let build_dir = flags_build_dir.or(build_dir.map(PathBuf::from)); + build_jobs_toml = flags_jobs.or(build_jobs_toml); + build_build_toml = flags_build.or(build_build_toml); + let build_dir = flags_build_dir.or(build_build_dir_toml.map(PathBuf::from)); let host = if let Some(TargetSelectionList(hosts)) = flags_host { Some(hosts) - } else if let Some(file_host) = host { + } else if let Some(file_host) = build_host_toml { Some(file_host.iter().map(|h| TargetSelection::from_user(h)).collect()) } else { None }; let target = if let Some(TargetSelectionList(targets)) = flags_target { Some(targets) - } else if let Some(file_target) = target { + } else if let Some(file_target) = build_target_toml { Some(file_target.iter().map(|h| TargetSelection::from_user(h)).collect()) } else { None }; - if let Some(rustc) = &rustc { + if let Some(rustc) = &build_rustc_toml { if !flags_skip_stage0_validation { check_stage0_version(&rustc, "rustc", &config.src, config.exec_ctx()); } } - if let Some(cargo) = &cargo { + if let Some(cargo) = &build_cargo_toml { if !flags_skip_stage0_validation { check_stage0_version(&cargo, "cargo", &config.src, config.exec_ctx()); } @@ -590,10 +589,10 @@ impl Config { // TOML. config .exec_ctx - .set_verbosity(cmp::max(build_verbose.unwrap_or_default() as u8, flags_verbose)); + .set_verbosity(cmp::max(build_verbose_toml.unwrap_or_default() as u8, flags_verbose)); let mut paths: Vec = flags_skip.into_iter().chain(flags_exclude).collect(); - if let Some(exclude) = exclude { + if let Some(exclude) = build_exclude_toml { paths.extend(exclude); } @@ -657,8 +656,8 @@ impl Config { "config.skip" = ?config.skip, ); - config.jobs = Some(threads_from_config(jobs.unwrap_or(0))); - if let Some(build) = build { + config.jobs = Some(threads_from_config(build_jobs_toml.unwrap_or(0))); + if let Some(build) = build_build_toml { config.host_target = TargetSelection::from_user(&build); } @@ -670,18 +669,13 @@ impl Config { config.out = absolute(&config.out).expect("can't make empty path absolute"); } - if cargo_clippy.is_some() && rustc.is_none() { + if build_cargo_clippy_toml.is_some() && build_rustc_toml.is_none() { println!( "WARNING: Using `build.cargo-clippy` without `build.rustc` usually fails due to toolchain conflict." ); } - config.patch_binaries_for_nix = patch_binaries_for_nix; - config.bootstrap_cache_path = bootstrap_cache_path; - config.llvm_assertions = - toml.llvm.as_ref().is_some_and(|llvm| llvm.assertions.unwrap_or(false)); - - config.initial_rustc = if let Some(rustc) = rustc { + config.initial_rustc = if let Some(rustc) = build_rustc_toml { rustc } else { let dwn_ctx = DownloadContext::from(&config); @@ -703,9 +697,9 @@ impl Config { .trim() )); - config.initial_cargo_clippy = cargo_clippy; + config.initial_cargo_clippy = build_cargo_clippy_toml; - config.initial_cargo = if let Some(cargo) = cargo { + config.initial_cargo = if let Some(cargo) = build_cargo_toml { cargo } else { let dwn_ctx = DownloadContext::from(&config); @@ -729,31 +723,33 @@ impl Config { config.hosts.clone() }; - config.nodejs = nodejs.map(PathBuf::from); - config.npm = npm.map(PathBuf::from); - config.gdb = gdb.map(PathBuf::from); - config.lldb = lldb.map(PathBuf::from); - config.python = python.map(PathBuf::from); - config.reuse = reuse.map(PathBuf::from); - config.submodules = submodules; - config.android_ndk = android_ndk; - set(&mut config.low_priority, low_priority); - set(&mut config.compiler_docs, compiler_docs); - set(&mut config.library_docs_private_items, library_docs_private_items); - set(&mut config.docs_minification, docs_minification); - set(&mut config.docs, docs); - set(&mut config.locked_deps, locked_deps); - set(&mut config.full_bootstrap, full_bootstrap); - set(&mut config.extended, extended); - config.tools = tools; - set(&mut config.tool, tool); - set(&mut config.sanitizers, sanitizers); - set(&mut config.profiler, profiler); - set(&mut config.cargo_native_static, cargo_native_static); - set(&mut config.configure_args, configure_args); - set(&mut config.local_rebuild, local_rebuild); - set(&mut config.print_step_timings, print_step_timings); - set(&mut config.print_step_rusage, print_step_rusage); + config.nodejs = build_nodejs_toml.map(PathBuf::from); + config.npm = build_npm_toml.map(PathBuf::from); + config.gdb = build_gdb_toml.map(PathBuf::from); + config.lldb = build_lldb_toml.map(PathBuf::from); + config.python = build_python_toml.map(PathBuf::from); + config.reuse = build_reuse_toml.map(PathBuf::from); + config.submodules = build_submodules_toml; + config.android_ndk = build_android_ndk_toml; + config.bootstrap_cache_path = build_bootstrap_cache_path_toml; + set(&mut config.low_priority, build_low_priority_toml); + set(&mut config.compiler_docs, build_compiler_docs_toml); + set(&mut config.library_docs_private_items, build_library_docs_private_items_toml); + set(&mut config.docs_minification, build_docs_minification_toml); + set(&mut config.docs, build_docs_toml); + set(&mut config.locked_deps, build_locked_deps_toml); + set(&mut config.full_bootstrap, build_full_bootstrap_toml); + set(&mut config.extended, build_extended_toml); + config.tools = build_tools_toml; + set(&mut config.tool, build_tool_toml); + set(&mut config.sanitizers, build_sanitizers_toml); + set(&mut config.profiler, build_profiler_toml); + set(&mut config.cargo_native_static, build_cargo_native_static_toml); + set(&mut config.configure_args, build_configure_args_toml); + set(&mut config.local_rebuild, build_local_rebuild_toml); + set(&mut config.print_step_timings, build_print_step_timings_toml); + set(&mut config.print_step_rusage, build_print_step_rusage_toml); + config.patch_binaries_for_nix = build_patch_binaries_for_nix_toml; // Verbose flag is a good default for `rust.verbose-tests`. config.verbose_tests = config.is_verbose(); @@ -818,7 +814,7 @@ impl Config { config.in_tree_llvm_info = config.git_info(false, &config.src.join("src/llvm-project")); config.in_tree_gcc_info = config.git_info(false, &config.src.join("src/gcc")); - config.vendor = vendor.unwrap_or( + config.vendor = build_vendor_toml.unwrap_or( config.rust_info.is_from_tarball() && config.src.join("vendor").exists() && config.src.join(".cargo/config.toml").exists(), @@ -1113,7 +1109,7 @@ impl Config { rust_debuginfo_level_tests_toml.unwrap_or(DebuginfoLevel::None); config.reproducible_artifacts = flags_reproducible_artifact; - config.description = description; + config.description = build_description_toml; // We need to override `rust.channel` if it's manually specified when using the CI rustc. // This is because if the compiler uses a different channel than the one specified in bootstrap.toml, @@ -1247,7 +1243,7 @@ impl Config { None => GccCiMode::default(), }; - match ccache { + match build_ccache_toml { Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()), Some(StringOrBool::Bool(true)) => { config.ccache = Some("ccache".to_string()); @@ -1292,7 +1288,7 @@ impl Config { config.rust_info.is_managed_git_subrepository() || config.rust_info.is_from_tarball() }); - config.initial_rustfmt = if let Some(r) = rustfmt { + config.initial_rustfmt = if let Some(r) = build_rustfmt_toml { Some(r) } else { let dwn_ctx = DownloadContext::from(&config); @@ -1313,41 +1309,40 @@ impl Config { } config.optimized_compiler_builtins = - optimized_compiler_builtins.unwrap_or(config.channel != "dev"); - - config.compiletest_diff_tool = compiletest_diff_tool; - - config.compiletest_allow_stage0 = compiletest_allow_stage0.unwrap_or(false); - config.compiletest_use_stage0_libtest = compiletest_use_stage0_libtest.unwrap_or(true); - - config.tidy_extra_checks = tidy_extra_checks; + build_optimized_compiler_builtins_toml.unwrap_or(config.channel != "dev"); + config.compiletest_diff_tool = build_compiletest_diff_tool_toml; + config.compiletest_use_stage0_libtest = + build_compiletest_use_stage0_libtest_toml.unwrap_or(true); + config.tidy_extra_checks = build_tidy_extra_checks_toml; let download_rustc = config.download_rustc_commit.is_some(); config.explicit_stage_from_cli = flags_stage.is_some(); - config.explicit_stage_from_config = test_stage.is_some() - || build_stage.is_some() - || doc_stage.is_some() - || dist_stage.is_some() - || install_stage.is_some() - || check_stage.is_some() - || bench_stage.is_some(); + config.explicit_stage_from_config = build_test_stage_toml.is_some() + || build_build_stage_toml.is_some() + || build_doc_stage_toml.is_some() + || build_dist_stage_toml.is_some() + || build_install_stage_toml.is_some() + || build_check_stage_toml.is_some() + || build_bench_stage_toml.is_some(); config.stage = match config.cmd { - Subcommand::Check { .. } => flags_stage.or(check_stage).unwrap_or(1), - Subcommand::Clippy { .. } | Subcommand::Fix => flags_stage.or(check_stage).unwrap_or(1), + Subcommand::Check { .. } => flags_stage.or(build_check_stage_toml).unwrap_or(1), + Subcommand::Clippy { .. } | Subcommand::Fix => { + flags_stage.or(build_check_stage_toml).unwrap_or(1) + } // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden. Subcommand::Doc { .. } => { - flags_stage.or(doc_stage).unwrap_or(if download_rustc { 2 } else { 1 }) + flags_stage.or(build_doc_stage_toml).unwrap_or(if download_rustc { 2 } else { 1 }) } Subcommand::Build => { - flags_stage.or(build_stage).unwrap_or(if download_rustc { 2 } else { 1 }) + flags_stage.or(build_build_stage_toml).unwrap_or(if download_rustc { 2 } else { 1 }) } Subcommand::Test { .. } | Subcommand::Miri { .. } => { - flags_stage.or(test_stage).unwrap_or(if download_rustc { 2 } else { 1 }) + flags_stage.or(build_test_stage_toml).unwrap_or(if download_rustc { 2 } else { 1 }) } - Subcommand::Bench { .. } => flags_stage.or(bench_stage).unwrap_or(2), - Subcommand::Dist => flags_stage.or(dist_stage).unwrap_or(2), - Subcommand::Install => flags_stage.or(install_stage).unwrap_or(2), + Subcommand::Bench { .. } => flags_stage.or(build_bench_stage_toml).unwrap_or(2), + Subcommand::Dist => flags_stage.or(build_dist_stage_toml).unwrap_or(2), + Subcommand::Install => flags_stage.or(build_install_stage_toml).unwrap_or(2), Subcommand::Perf { .. } => flags_stage.unwrap_or(1), // These are all bootstrap tools, which don't depend on the compiler. // The stage we pass shouldn't matter, but use 0 just in case. From a75326bde1018e38f74e979dd20309010c02fbae Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 18:21:02 +0530 Subject: [PATCH 0319/1134] move build config to the top of parse method --- src/bootstrap/src/core/config/config.rs | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index f8df5687f5a7..00f76c40fc6a 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -487,17 +487,6 @@ impl Config { &get_toml, ); - if cfg!(test) { - // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the - // same ones used to call the tests (if custom ones are not defined in the toml). If we - // don't do that, bootstrap will use its own detection logic to find a suitable rustc - // and Cargo, which doesn't work when the caller is specìfying a custom local rustc or - // Cargo in their bootstrap.toml. - let build = toml.build.get_or_insert_with(Default::default); - build.rustc = build.rustc.take().or(std::env::var_os("RUSTC").map(|p| p.into())); - build.cargo = build.cargo.take().or(std::env::var_os("CARGO").map(|p| p.into())); - } - // Now override TOML values with flags, to make sure that we won't later override flags with // TOML values by accident instead, because flags have higher priority. let Build { @@ -507,7 +496,7 @@ impl Config { target: build_target_toml, build_dir: build_build_dir_toml, cargo: build_cargo_toml, - rustc: build_rustc_toml, + rustc: mut build_rustc_toml, rustfmt: build_rustfmt_toml, cargo_clippy: build_cargo_clippy_toml, docs: build_docs_toml, @@ -556,8 +545,20 @@ impl Config { ccache: build_ccache_toml, exclude: build_exclude_toml, } = toml.build.unwrap_or_default(); + + if cfg!(test) { + // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the + // same ones used to call the tests (if custom ones are not defined in the toml). If we + // don't do that, bootstrap will use its own detection logic to find a suitable rustc + // and Cargo, which doesn't work when the caller is specìfying a custom local rustc or + // Cargo in their bootstrap.toml. + build_rustc_toml = build_rustc_toml.take().or(std::env::var_os("RUSTC").map(|p| p.into())); + build_build_toml = build_build_toml.take().or(std::env::var_os("CARGO").map(|p| p.into_string().unwrap())); + } + build_jobs_toml = flags_jobs.or(build_jobs_toml); build_build_toml = flags_build.or(build_build_toml); + let build_dir = flags_build_dir.or(build_build_dir_toml.map(PathBuf::from)); let host = if let Some(TargetSelectionList(hosts)) = flags_host { Some(hosts) From 39d9cf7d952b14e0ea40486428a20032061bb53c Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 18:22:30 +0530 Subject: [PATCH 0320/1134] move install config to the top of parse method --- src/bootstrap/src/core/config/config.rs | 27 ++++++++++++++----------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 00f76c40fc6a..3d42200d0d83 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -546,14 +546,27 @@ impl Config { exclude: build_exclude_toml, } = toml.build.unwrap_or_default(); + let Install { + prefix: install_prefix_toml, + sysconfdir: install_sysconfdir_toml, + docdir: install_docdir_toml, + bindir: install_bindir_toml, + libdir: install_libdir_toml, + mandir: install_mandir_toml, + datadir: install_datadir_toml, + } = toml.install.unwrap_or_default(); + if cfg!(test) { // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the // same ones used to call the tests (if custom ones are not defined in the toml). If we // don't do that, bootstrap will use its own detection logic to find a suitable rustc // and Cargo, which doesn't work when the caller is specìfying a custom local rustc or // Cargo in their bootstrap.toml. - build_rustc_toml = build_rustc_toml.take().or(std::env::var_os("RUSTC").map(|p| p.into())); - build_build_toml = build_build_toml.take().or(std::env::var_os("CARGO").map(|p| p.into_string().unwrap())); + build_rustc_toml = + build_rustc_toml.take().or(std::env::var_os("RUSTC").map(|p| p.into())); + build_build_toml = build_build_toml + .take() + .or(std::env::var_os("CARGO").map(|p| p.into_string().unwrap())); } build_jobs_toml = flags_jobs.or(build_jobs_toml); @@ -755,16 +768,6 @@ impl Config { // Verbose flag is a good default for `rust.verbose-tests`. config.verbose_tests = config.is_verbose(); - let Install { - prefix: install_prefix_toml, - sysconfdir: install_sysconfdir_toml, - docdir: install_docdir_toml, - bindir: install_bindir_toml, - libdir: install_libdir_toml, - mandir: install_mandir_toml, - datadir: install_datadir_toml, - } = toml.install.unwrap_or_default(); - let install_prefix = install_prefix_toml.map(PathBuf::from); let install_sysconfdir = install_sysconfdir_toml.map(PathBuf::from); let install_docdir = install_docdir_toml.map(PathBuf::from); From 120d93efdbbb0f83bc5327d7fa18c95643e709cc Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 18:31:01 +0530 Subject: [PATCH 0321/1134] move rust config to the top of parse method --- src/bootstrap/src/core/config/config.rs | 117 ++++++++++++------------ 1 file changed, 58 insertions(+), 59 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 3d42200d0d83..1550fe367465 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -556,6 +556,62 @@ impl Config { datadir: install_datadir_toml, } = toml.install.unwrap_or_default(); + let Rust { + optimize: rust_optimize_toml, + debug: rust_debug_toml, + codegen_units: rust_codegen_units_toml, + codegen_units_std: rust_codegen_units_std_toml, + rustc_debug_assertions: rust_rustc_debug_assertions_toml, + std_debug_assertions: rust_std_debug_assertions_toml, + tools_debug_assertions: rust_tools_debug_assertions_toml, + overflow_checks: rust_overflow_checks_toml, + overflow_checks_std: rust_overflow_checks_std_toml, + debug_logging: rust_debug_logging_toml, + debuginfo_level: rust_debuginfo_level_toml, + debuginfo_level_rustc: rust_debuginfo_level_rustc_toml, + debuginfo_level_std: rust_debuginfo_level_std_toml, + debuginfo_level_tools: rust_debuginfo_level_tools_toml, + debuginfo_level_tests: rust_debuginfo_level_tests_toml, + backtrace: rust_backtrace_toml, + incremental: rust_incremental_toml, + randomize_layout: rust_randomize_layout_toml, + default_linker: rust_default_linker_toml, + channel: rust_channel_toml, + musl_root: rust_musl_root_toml, + rpath: rust_rpath_toml, + verbose_tests: rust_verbose_tests_toml, + optimize_tests: rust_optimize_tests_toml, + codegen_tests: rust_codegen_tests_toml, + omit_git_hash: rust_omit_git_hash_toml, + dist_src: rust_dist_src_toml, + save_toolstates: rust_save_toolstates_toml, + codegen_backends: rust_codegen_backends_toml, + lld: rust_lld_enabled_toml, + llvm_tools: rust_llvm_tools_toml, + llvm_bitcode_linker: rust_llvm_bitcode_linker_toml, + deny_warnings: rust_deny_warnings_toml, + backtrace_on_ice: rust_backtrace_on_ice_toml, + verify_llvm_ir: rust_verify_llvm_ir_toml, + thin_lto_import_instr_limit: rust_thin_lto_import_instr_limit_toml, + remap_debuginfo: rust_remap_debuginfo_toml, + jemalloc: rust_jemalloc_toml, + test_compare_mode: rust_test_compare_mode_toml, + llvm_libunwind: rust_llvm_libunwind_toml, + control_flow_guard: rust_control_flow_guard_toml, + ehcont_guard: rust_ehcont_guard_toml, + new_symbol_mangling: rust_new_symbol_mangling_toml, + profile_generate: rust_profile_generate_toml, + profile_use: rust_profile_use_toml, + download_rustc: rust_download_rustc_toml, + lto: rust_lto_toml, + validate_mir_opts: rust_validate_mir_opts_toml, + frame_pointers: rust_frame_pointers_toml, + stack_protector: rust_stack_protector_toml, + strip: rust_strip_toml, + lld_mode: rust_lld_mode_toml, + std_features: rust_std_features_toml, + } = toml.rust.unwrap_or_default(); + if cfg!(test) { // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the // same ones used to call the tests (if custom ones are not defined in the toml). If we @@ -786,8 +842,7 @@ impl Config { let file_content = t!(fs::read_to_string(config.src.join("src/ci/channel"))); let ci_channel = file_content.trim_end(); - let toml_channel = toml.rust.as_ref().and_then(|r| r.channel.clone()); - let is_user_configured_rust_channel = match toml_channel { + let is_user_configured_rust_channel = match rust_channel_toml { Some(channel) if channel == "auto-detect" => { config.channel = ci_channel.into(); true @@ -800,7 +855,7 @@ impl Config { }; let default = config.channel == "dev"; - config.omit_git_hash = toml.rust.as_ref().and_then(|r| r.omit_git_hash).unwrap_or(default); + config.omit_git_hash = rust_omit_git_hash_toml.unwrap_or(default); config.rust_info = config.git_info(config.omit_git_hash, &config.src); config.cargo_info = @@ -894,62 +949,6 @@ impl Config { } } - let Rust { - optimize: rust_optimize_toml, - debug: rust_debug_toml, - codegen_units: rust_codegen_units_toml, - codegen_units_std: rust_codegen_units_std_toml, - rustc_debug_assertions: rust_rustc_debug_assertions_toml, - std_debug_assertions: rust_std_debug_assertions_toml, - tools_debug_assertions: rust_tools_debug_assertions_toml, - overflow_checks: rust_overflow_checks_toml, - overflow_checks_std: rust_overflow_checks_std_toml, - debug_logging: rust_debug_logging_toml, - debuginfo_level: rust_debuginfo_level_toml, - debuginfo_level_rustc: rust_debuginfo_level_rustc_toml, - debuginfo_level_std: rust_debuginfo_level_std_toml, - debuginfo_level_tools: rust_debuginfo_level_tools_toml, - debuginfo_level_tests: rust_debuginfo_level_tests_toml, - backtrace: rust_backtrace_toml, - incremental: rust_incremental_toml, - randomize_layout: rust_randomize_layout_toml, - default_linker: rust_default_linker_toml, - channel: _, // already handled above - musl_root: rust_musl_root_toml, - rpath: rust_rpath_toml, - verbose_tests: rust_verbose_tests_toml, - optimize_tests: rust_optimize_tests_toml, - codegen_tests: rust_codegen_tests_toml, - omit_git_hash: _, // already handled above - dist_src: rust_dist_src_toml, - save_toolstates: rust_save_toolstates_toml, - codegen_backends: rust_codegen_backends_toml, - lld: rust_lld_enabled_toml, - llvm_tools: rust_llvm_tools_toml, - llvm_bitcode_linker: rust_llvm_bitcode_linker_toml, - deny_warnings: rust_deny_warnings_toml, - backtrace_on_ice: rust_backtrace_on_ice_toml, - verify_llvm_ir: rust_verify_llvm_ir_toml, - thin_lto_import_instr_limit: rust_thin_lto_import_instr_limit_toml, - remap_debuginfo: rust_remap_debuginfo_toml, - jemalloc: rust_jemalloc_toml, - test_compare_mode: rust_test_compare_mode_toml, - llvm_libunwind: rust_llvm_libunwind_toml, - control_flow_guard: rust_control_flow_guard_toml, - ehcont_guard: rust_ehcont_guard_toml, - new_symbol_mangling: rust_new_symbol_mangling_toml, - profile_generate: rust_profile_generate_toml, - profile_use: rust_profile_use_toml, - download_rustc: rust_download_rustc_toml, - lto: rust_lto_toml, - validate_mir_opts: rust_validate_mir_opts_toml, - frame_pointers: rust_frame_pointers_toml, - stack_protector: rust_stack_protector_toml, - strip: rust_strip_toml, - lld_mode: rust_lld_mode_toml, - std_features: rust_std_features_toml, - } = toml.rust.unwrap_or_default(); - // FIXME(#133381): alt rustc builds currently do *not* have rustc debug assertions // enabled. We should not download a CI alt rustc if we need rustc to have debug // assertions (e.g. for crashes test suite). This can be changed once something like From 071606b2a385b734fddf27d67a60484dc7df1797 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Fri, 1 Aug 2025 11:01:59 -0400 Subject: [PATCH 0322/1134] Add failing LTO test --- tests/failing-lto-tests.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/failing-lto-tests.txt b/tests/failing-lto-tests.txt index b1ae1e91078b..bf0633f73200 100644 --- a/tests/failing-lto-tests.txt +++ b/tests/failing-lto-tests.txt @@ -30,3 +30,4 @@ tests/ui/macros/rfc-2011-nicer-assert-messages/feature-gate-generic_assert.rs tests/ui/macros/stringify.rs tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-in-test.rs tests/ui/binding/fn-arg-incomplete-pattern-drop-order.rs +tests/ui/lto/debuginfo-lto-alloc.rs From f74f1a006c983d621c5bf2c9989d695a14342c41 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 18:33:55 +0530 Subject: [PATCH 0323/1134] move llvm config to the top of parse method --- src/bootstrap/src/core/config/config.rs | 67 +++++++++++++------------ 1 file changed, 36 insertions(+), 31 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 1550fe367465..73e4e4310e07 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -612,6 +612,37 @@ impl Config { std_features: rust_std_features_toml, } = toml.rust.unwrap_or_default(); + let Llvm { + optimize: llvm_optimize_toml, + thin_lto: llvm_thin_lto_toml, + release_debuginfo: llvm_release_debuginfo_toml, + assertions: llvm_assertions_toml, + tests: llvm_tests_toml, + enzyme: llvm_enzyme_toml, + plugins: llvm_plugin_toml, + static_libstdcpp: llvm_static_libstdcpp_toml, + libzstd: llvm_libzstd_toml, + ninja: llvm_ninja_toml, + targets: llvm_targets_toml, + experimental_targets: llvm_experimental_targets_toml, + link_jobs: llvm_link_jobs_toml, + link_shared: llvm_link_shared_toml, + version_suffix: llvm_version_suffix_toml, + clang_cl: llvm_clang_cl_toml, + cflags: llvm_cflags_toml, + cxxflags: llvm_cxxflags_toml, + ldflags: llvm_ldflags_toml, + use_libcxx: llvm_use_libcxx_toml, + use_linker: llvm_use_linker_toml, + allow_old_toolchain: llvm_allow_old_toolchain_toml, + offload: llvm_offload_toml, + polly: llvm_polly_toml, + clang: llvm_clang_toml, + enable_warnings: llvm_enable_warnings_toml, + download_ci_llvm: llvm_download_ci_llvm_toml, + build_config: llvm_build_config_toml, + } = toml.llvm.unwrap_or_default(); + if cfg!(test) { // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the // same ones used to call the tests (if custom ones are not defined in the toml). If we @@ -839,6 +870,11 @@ impl Config { config.libdir = install_libdir; config.mandir = install_mandir; +<<<<<<< HEAD +======= + config.llvm_assertions = llvm_assertions_toml.unwrap_or(false); + +>>>>>>> f1dbcb5ad2c (move llvm config to the top of parse method) let file_content = t!(fs::read_to_string(config.src.join("src/ci/channel"))); let ci_channel = file_content.trim_end(); @@ -1130,37 +1166,6 @@ impl Config { config.channel = channel; } - let Llvm { - optimize: llvm_optimize_toml, - thin_lto: llvm_thin_lto_toml, - release_debuginfo: llvm_release_debuginfo_toml, - assertions: _, - tests: llvm_tests_toml, - enzyme: llvm_enzyme_toml, - plugins: llvm_plugin_toml, - static_libstdcpp: llvm_static_libstdcpp_toml, - libzstd: llvm_libzstd_toml, - ninja: llvm_ninja_toml, - targets: llvm_targets_toml, - experimental_targets: llvm_experimental_targets_toml, - link_jobs: llvm_link_jobs_toml, - link_shared: llvm_link_shared_toml, - version_suffix: llvm_version_suffix_toml, - clang_cl: llvm_clang_cl_toml, - cflags: llvm_cflags_toml, - cxxflags: llvm_cxxflags_toml, - ldflags: llvm_ldflags_toml, - use_libcxx: llvm_use_libcxx_toml, - use_linker: llvm_use_linker_toml, - allow_old_toolchain: llvm_allow_old_toolchain_toml, - offload: llvm_offload_toml, - polly: llvm_polly_toml, - clang: llvm_clang_toml, - enable_warnings: llvm_enable_warnings_toml, - download_ci_llvm: llvm_download_ci_llvm_toml, - build_config: llvm_build_config_toml, - } = toml.llvm.unwrap_or_default(); - set(&mut config.ninja_in_file, llvm_ninja_toml); set(&mut config.llvm_optimize, llvm_optimize_toml); set(&mut config.llvm_thin_lto, llvm_thin_lto_toml); From 7f20ad86ba273315252c44adbce3ad99b6651863 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 1 Aug 2025 18:37:11 +0530 Subject: [PATCH 0324/1134] move dist and gcc config to the top of parse method --- src/bootstrap/src/core/config/config.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 73e4e4310e07..59c20377066a 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -643,6 +643,18 @@ impl Config { build_config: llvm_build_config_toml, } = toml.llvm.unwrap_or_default(); + let Dist { + sign_folder: dist_sign_folder_toml, + upload_addr: dist_upload_addr_toml, + src_tarball: dist_src_tarball_toml, + compression_formats: dist_compression_formats_toml, + compression_profile: dist_compression_profile_toml, + include_mingw_linker: dist_include_mingw_linker_toml, + vendor: dist_vendor_toml, + } = toml.dist.unwrap_or_default(); + + let Gcc { download_ci_gcc: gcc_download_ci_gcc_toml } = toml.gcc.unwrap_or_default(); + if cfg!(test) { // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the // same ones used to call the tests (if custom ones are not defined in the toml). If we @@ -1241,8 +1253,6 @@ impl Config { config.llvm_link_shared.set(Some(true)); } - let Gcc { download_ci_gcc: gcc_download_ci_gcc_toml } = toml.gcc.unwrap_or_default(); - config.gcc_ci_mode = match gcc_download_ci_gcc_toml { Some(value) => match value { true => GccCiMode::DownloadFromCi, @@ -1275,16 +1285,6 @@ impl Config { Some(ci_llvm_bin.join(exe("FileCheck", config.host_target))); } - let Dist { - sign_folder: dist_sign_folder_toml, - upload_addr: dist_upload_addr_toml, - src_tarball: dist_src_tarball_toml, - compression_formats: dist_compression_formats_toml, - compression_profile: dist_compression_profile_toml, - include_mingw_linker: dist_include_mingw_linker_toml, - vendor: dist_vendor_toml, - } = toml.dist.unwrap_or_default(); - config.dist_sign_folder = dist_sign_folder_toml.map(PathBuf::from); config.dist_upload_addr = dist_upload_addr_toml; config.dist_compression_formats = dist_compression_formats_toml; From 32cf3d48b311857b90a58a67bd5852b1d56ed9fe Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Fri, 1 Aug 2025 17:08:02 +0200 Subject: [PATCH 0325/1134] Cleanup the definition of `group_type` Signed-off-by: Jonathan Brouwer --- compiler/rustc_attr_parsing/src/context.rs | 61 +++++++++++++--------- 1 file changed, 36 insertions(+), 25 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 54c0fbcd0626..767d19bd2340 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -62,15 +62,23 @@ use crate::attributes::{AttributeParser as _, Combine, Single, WithoutArgs}; use crate::parser::{ArgParser, MetaItemParser, PathParser}; use crate::session_diagnostics::{AttributeParseError, AttributeParseErrorReason, UnknownMetaItem}; -macro_rules! group_type { - ($stage: ty) => { - LazyLock<( - BTreeMap<&'static [Symbol], Vec<(AttributeTemplate, Box Fn(&mut AcceptContext<'_, 'sess, $stage>, &ArgParser<'a>) + Send + Sync>)>>, - Vec) -> Option>> - )> - }; +type GroupType = LazyLock>; + +struct GroupTypeInner { + accepters: BTreeMap<&'static [Symbol], Vec>>, + finalizers: Vec>, +} + +struct GroupTypeInnerAccept { + template: AttributeTemplate, + accept_fn: AcceptFn, } +type AcceptFn = + Box Fn(&mut AcceptContext<'_, 'sess, S>, &ArgParser<'a>) + Send + Sync>; +type FinalizeFn = + Box) -> Option>; + macro_rules! attribute_parsers { ( pub(crate) static $name: ident = [$($names: ty),* $(,)?]; @@ -93,11 +101,11 @@ macro_rules! attribute_parsers { } }; ( - @[$ty: ty] pub(crate) static $name: ident = [$($names: ty),* $(,)?]; + @[$stage: ty] pub(crate) static $name: ident = [$($names: ty),* $(,)?]; ) => { - pub(crate) static $name: group_type!($ty) = LazyLock::new(|| { - let mut accepts = BTreeMap::<_, Vec<(AttributeTemplate, Box Fn(&mut AcceptContext<'_, 'sess, $ty>, &ArgParser<'a>) + Send + Sync>)>>::new(); - let mut finalizes = Vec::) -> Option>>::new(); + pub(crate) static $name: GroupType<$stage> = LazyLock::new(|| { + let mut accepts = BTreeMap::<_, Vec>>::new(); + let mut finalizes = Vec::>::new(); $( { thread_local! { @@ -105,11 +113,14 @@ macro_rules! attribute_parsers { }; for (path, template, accept_fn) in <$names>::ATTRIBUTES { - accepts.entry(*path).or_default().push((*template, Box::new(|cx, args| { - STATE_OBJECT.with_borrow_mut(|s| { - accept_fn(s, cx, args) + accepts.entry(*path).or_default().push(GroupTypeInnerAccept { + template: *template, + accept_fn: Box::new(|cx, args| { + STATE_OBJECT.with_borrow_mut(|s| { + accept_fn(s, cx, args) + }) }) - }))); + }); } finalizes.push(Box::new(|cx| { @@ -119,7 +130,7 @@ macro_rules! attribute_parsers { } )* - (accepts, finalizes) + GroupTypeInner { accepters:accepts, finalizers:finalizes } }); }; } @@ -215,7 +226,7 @@ pub trait Stage: Sized + 'static + Sealed { type Id: Copy; const SHOULD_EMIT_LINTS: bool; - fn parsers() -> &'static group_type!(Self); + fn parsers() -> &'static GroupType; fn emit_err<'sess>( &self, @@ -230,7 +241,7 @@ impl Stage for Early { type Id = NodeId; const SHOULD_EMIT_LINTS: bool = false; - fn parsers() -> &'static group_type!(Self) { + fn parsers() -> &'static GroupType { &early::ATTRIBUTE_PARSERS } fn emit_err<'sess>( @@ -252,7 +263,7 @@ impl Stage for Late { type Id = HirId; const SHOULD_EMIT_LINTS: bool = true; - fn parsers() -> &'static group_type!(Self) { + fn parsers() -> &'static GroupType { &late::ATTRIBUTE_PARSERS } fn emit_err<'sess>( @@ -811,8 +822,8 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { let args = parser.args(); let parts = path.segments().map(|i| i.name).collect::>(); - if let Some(accepts) = S::parsers().0.get(parts.as_slice()) { - for (template, accept) in accepts { + if let Some(accepts) = S::parsers().accepters.get(parts.as_slice()) { + for accept in accepts { let mut cx: AcceptContext<'_, 'sess, S> = AcceptContext { shared: SharedContext { cx: self, @@ -821,11 +832,11 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { emit_lint: &mut emit_lint, }, attr_span: lower_span(attr.span), - template, + template: &accept.template, attr_path: path.get_attribute_path(), }; - accept(&mut cx, args) + (accept.accept_fn)(&mut cx, args) } } else { // If we're here, we must be compiling a tool attribute... Or someone @@ -856,7 +867,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { } let mut parsed_attributes = Vec::new(); - for f in &S::parsers().1 { + for f in &S::parsers().finalizers { if let Some(attr) = f(&mut FinalizeContext { shared: SharedContext { cx: self, @@ -877,7 +888,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> { /// Returns whether there is a parser for an attribute with this name pub fn is_parsed_attribute(path: &[Symbol]) -> bool { - Late::parsers().0.contains_key(path) + Late::parsers().accepters.contains_key(path) } fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs { From bc5c2229d01cd06bfd91476636409d619bd5a807 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Fri, 1 Aug 2025 11:29:05 -0400 Subject: [PATCH 0326/1134] Fix issues in count_leading_zeroes --- src/intrinsic/mod.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index 21b650bdecd7..57bdbad5e536 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -889,10 +889,17 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { // TODO(antoyo): use width? let arg_type = arg.get_type(); let result_type = self.u32_type; + let arg = if arg_type.is_signed(self.cx) { + let new_type = arg_type.to_unsigned(self.cx); + self.gcc_int_cast(arg, new_type) + } else { + arg + }; + let arg_type = arg.get_type(); let count_leading_zeroes = // TODO(antoyo): write a new function Type::is_compatible_with(&Type) and use it here // instead of using is_uint(). - if arg_type.is_uint(self.cx) { + if arg_type.is_uchar(self.cx) || arg_type.is_ushort(self.cx) || arg_type.is_uint(self.cx) { "__builtin_clz" } else if arg_type.is_ulong(self.cx) { From 053f68151b8e6fb079b6a9254699d5a46220e52f Mon Sep 17 00:00:00 2001 From: Ifeanyi Orizu Date: Thu, 31 Jul 2025 22:38:49 -0500 Subject: [PATCH 0327/1134] Update documentation for overrideCommand config options --- .../rust-analyzer/crates/rust-analyzer/src/config.rs | 11 +++++++++-- .../docs/book/src/configuration_generated.md | 11 +++++++++-- src/tools/rust-analyzer/editors/code/package.json | 6 +++--- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs index 70d04485ca08..1a00295b9ac1 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs @@ -726,7 +726,9 @@ config_data! { /// ```bash /// cargo check --quiet --workspace --message-format=json --all-targets --keep-going /// ``` - /// . + /// + /// Note: The option must be specified as an array of command line arguments, with + /// the first argument being the name of the command to run. cargo_buildScripts_overrideCommand: Option> = None, /// Rerun proc-macros building/build-scripts running when proc-macro /// or build-script sources change and are saved. @@ -840,7 +842,9 @@ config_data! { /// ```bash /// cargo check --workspace --message-format=json --all-targets /// ``` - /// . + /// + /// Note: The option must be specified as an array of command line arguments, with + /// the first argument being the name of the command to run. check_overrideCommand | checkOnSave_overrideCommand: Option> = None, /// Check for specific targets. Defaults to `#rust-analyzer.cargo.target#` if empty. /// @@ -890,6 +894,9 @@ config_data! { /// not that of `cargo fmt`. The file contents will be passed on the /// standard input and the formatted result will be read from the /// standard output. + /// + /// Note: The option must be specified as an array of command line arguments, with + /// the first argument being the name of the command to run. rustfmt_overrideCommand: Option> = None, /// Enables the use of rustfmt's unstable range formatting command for the /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only diff --git a/src/tools/rust-analyzer/docs/book/src/configuration_generated.md b/src/tools/rust-analyzer/docs/book/src/configuration_generated.md index 05299f1d017e..99a30d8f6213 100644 --- a/src/tools/rust-analyzer/docs/book/src/configuration_generated.md +++ b/src/tools/rust-analyzer/docs/book/src/configuration_generated.md @@ -104,7 +104,9 @@ targets and features, with the following base command line: ```bash cargo check --quiet --workspace --message-format=json --all-targets --keep-going ``` -. + +Note: The option must be specified as an array of command line arguments, with +the first argument being the name of the command to run. ## rust-analyzer.cargo.buildScripts.rebuildOnSave {#cargo.buildScripts.rebuildOnSave} @@ -331,7 +333,9 @@ An example command would be: ```bash cargo check --workspace --message-format=json --all-targets ``` -. + +Note: The option must be specified as an array of command line arguments, with +the first argument being the name of the command to run. ## rust-analyzer.check.targets {#check.targets} @@ -1343,6 +1347,9 @@ not that of `cargo fmt`. The file contents will be passed on the standard input and the formatted result will be read from the standard output. +Note: The option must be specified as an array of command line arguments, with +the first argument being the name of the command to run. + ## rust-analyzer.rustfmt.rangeFormatting.enable {#rustfmt.rangeFormatting.enable} diff --git a/src/tools/rust-analyzer/editors/code/package.json b/src/tools/rust-analyzer/editors/code/package.json index 8953a30dacb2..470db244f14b 100644 --- a/src/tools/rust-analyzer/editors/code/package.json +++ b/src/tools/rust-analyzer/editors/code/package.json @@ -887,7 +887,7 @@ "title": "Cargo", "properties": { "rust-analyzer.cargo.buildScripts.overrideCommand": { - "markdownDescription": "Override the command rust-analyzer uses to run build scripts and\nbuild procedural macros. The command is required to output json\nand should therefore include `--message-format=json` or a similar\noption.\n\nIf there are multiple linked projects/workspaces, this command is invoked for\neach of them, with the working directory being the workspace root\n(i.e., the folder containing the `Cargo.toml`). This can be overwritten\nby changing `#rust-analyzer.cargo.buildScripts.invocationStrategy#`.\n\nBy default, a cargo invocation will be constructed for the configured\ntargets and features, with the following base command line:\n\n```bash\ncargo check --quiet --workspace --message-format=json --all-targets --keep-going\n```\n.", + "markdownDescription": "Override the command rust-analyzer uses to run build scripts and\nbuild procedural macros. The command is required to output json\nand should therefore include `--message-format=json` or a similar\noption.\n\nIf there are multiple linked projects/workspaces, this command is invoked for\neach of them, with the working directory being the workspace root\n(i.e., the folder containing the `Cargo.toml`). This can be overwritten\nby changing `#rust-analyzer.cargo.buildScripts.invocationStrategy#`.\n\nBy default, a cargo invocation will be constructed for the configured\ntargets and features, with the following base command line:\n\n```bash\ncargo check --quiet --workspace --message-format=json --all-targets --keep-going\n```\n\nNote: The option must be specified as an array of command line arguments, with\nthe first argument being the name of the command to run.", "default": null, "type": [ "null", @@ -1207,7 +1207,7 @@ "title": "Check", "properties": { "rust-analyzer.check.overrideCommand": { - "markdownDescription": "Override the command rust-analyzer uses instead of `cargo check` for\ndiagnostics on save. The command is required to output json and\nshould therefore include `--message-format=json` or a similar option\n(if your client supports the `colorDiagnosticOutput` experimental\ncapability, you can use `--message-format=json-diagnostic-rendered-ansi`).\n\nIf you're changing this because you're using some tool wrapping\nCargo, you might also want to change\n`#rust-analyzer.cargo.buildScripts.overrideCommand#`.\n\nIf there are multiple linked projects/workspaces, this command is invoked for\neach of them, with the working directory being the workspace root\n(i.e., the folder containing the `Cargo.toml`). This can be overwritten\nby changing `#rust-analyzer.check.invocationStrategy#`.\n\nIf `$saved_file` is part of the command, rust-analyzer will pass\nthe absolute path of the saved file to the provided command. This is\nintended to be used with non-Cargo build systems.\nNote that `$saved_file` is experimental and may be removed in the future.\n\nAn example command would be:\n\n```bash\ncargo check --workspace --message-format=json --all-targets\n```\n.", + "markdownDescription": "Override the command rust-analyzer uses instead of `cargo check` for\ndiagnostics on save. The command is required to output json and\nshould therefore include `--message-format=json` or a similar option\n(if your client supports the `colorDiagnosticOutput` experimental\ncapability, you can use `--message-format=json-diagnostic-rendered-ansi`).\n\nIf you're changing this because you're using some tool wrapping\nCargo, you might also want to change\n`#rust-analyzer.cargo.buildScripts.overrideCommand#`.\n\nIf there are multiple linked projects/workspaces, this command is invoked for\neach of them, with the working directory being the workspace root\n(i.e., the folder containing the `Cargo.toml`). This can be overwritten\nby changing `#rust-analyzer.check.invocationStrategy#`.\n\nIf `$saved_file` is part of the command, rust-analyzer will pass\nthe absolute path of the saved file to the provided command. This is\nintended to be used with non-Cargo build systems.\nNote that `$saved_file` is experimental and may be removed in the future.\n\nAn example command would be:\n\n```bash\ncargo check --workspace --message-format=json --all-targets\n```\n\nNote: The option must be specified as an array of command line arguments, with\nthe first argument being the name of the command to run.", "default": null, "type": [ "null", @@ -2808,7 +2808,7 @@ "title": "Rustfmt", "properties": { "rust-analyzer.rustfmt.overrideCommand": { - "markdownDescription": "Advanced option, fully override the command rust-analyzer uses for\nformatting. This should be the equivalent of `rustfmt` here, and\nnot that of `cargo fmt`. The file contents will be passed on the\nstandard input and the formatted result will be read from the\nstandard output.", + "markdownDescription": "Advanced option, fully override the command rust-analyzer uses for\nformatting. This should be the equivalent of `rustfmt` here, and\nnot that of `cargo fmt`. The file contents will be passed on the\nstandard input and the formatted result will be read from the\nstandard output.\n\nNote: The option must be specified as an array of command line arguments, with\nthe first argument being the name of the command to run.", "default": null, "type": [ "null", From 7d167260ca00ab7778d3198d9b34fbb3fd95d1e4 Mon Sep 17 00:00:00 2001 From: Ifeanyi Orizu Date: Fri, 1 Aug 2025 00:33:01 -0500 Subject: [PATCH 0328/1134] Fix more docs --- .../docs/book/src/contributing/style.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/tools/rust-analyzer/docs/book/src/contributing/style.md b/src/tools/rust-analyzer/docs/book/src/contributing/style.md index 5654e37753a5..746f3eb13211 100644 --- a/src/tools/rust-analyzer/docs/book/src/contributing/style.md +++ b/src/tools/rust-analyzer/docs/book/src/contributing/style.md @@ -49,8 +49,8 @@ In this case, we'll probably ask you to split API changes into a separate PR. Changes of the third group should be pretty rare, so we don't specify any specific process for them. That said, adding an innocent-looking `pub use` is a very simple way to break encapsulation, keep an eye on it! -Note: if you enjoyed this abstract hand-waving about boundaries, you might appreciate -https://www.tedinski.com/2018/02/06/system-boundaries.html +Note: if you enjoyed this abstract hand-waving about boundaries, you might appreciate [this post](https://www.tedinski.com/2018/02/06/system-boundaries.html). + ## Crates.io Dependencies @@ -231,7 +231,7 @@ fn is_string_literal(s: &str) -> bool { } ``` -In the "Not as good" version, the precondition that `1` is a valid char boundary is checked in `is_string_literal` and used in `foo`. +In the "Bad" version, the precondition that `1` and `s.len() - 1` are valid string literal boundaries is checked in `is_string_literal` but used in `main`. In the "Good" version, the precondition check and usage are checked in the same block, and then encoded in the types. **Rationale:** non-local code properties degrade under change. @@ -271,6 +271,8 @@ fn f() { } ``` +See also [this post](https://matklad.github.io/2023/11/15/push-ifs-up-and-fors-down.html) + ## Assertions Assert liberally. @@ -608,7 +610,7 @@ Avoid making a lot of code type parametric, *especially* on the boundaries betwe ```rust // GOOD -fn frobnicate(f: impl FnMut()) { +fn frobnicate(mut f: impl FnMut()) { frobnicate_impl(&mut f) } fn frobnicate_impl(f: &mut dyn FnMut()) { @@ -616,7 +618,7 @@ fn frobnicate_impl(f: &mut dyn FnMut()) { } // BAD -fn frobnicate(f: impl FnMut()) { +fn frobnicate(mut f: impl FnMut()) { // lots of code } ``` @@ -975,7 +977,7 @@ Don't use the `ref` keyword. **Rationale:** consistency & simplicity. `ref` was required before [match ergonomics](https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md). Today, it is redundant. -Between `ref` and mach ergonomics, the latter is more ergonomic in most cases, and is simpler (does not require a keyword). +Between `ref` and match ergonomics, the latter is more ergonomic in most cases, and is simpler (does not require a keyword). ## Empty Match Arms From fe720181b52157f9a7195b3d9b0b28b20dc9583d Mon Sep 17 00:00:00 2001 From: zachs18 <8355914+zachs18@users.noreply.github.com> Date: Fri, 1 Aug 2025 11:06:13 -0500 Subject: [PATCH 0329/1134] Update compiler/rustc_const_eval/src/interpret/memory.rs Replace commented-out code with link to context for change. Co-authored-by: Ralf Jung --- compiler/rustc_const_eval/src/interpret/memory.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index bbde7c66acc0..23b40894f16d 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -941,7 +941,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // FIXME: Until we have a clear design for the effects of align(N) functions // on the address of function pointers, we don't consider the align(N) // attribute on functions in the interpreter. - //self.tcx.codegen_instance_attrs(instance.def).alignment.unwrap_or(Align::ONE) + // See for more context. Align::ONE } // Machine-specific extra functions currently do not support alignment restrictions. From 1a64684b0421d9e7090c0f805ef7637d0d6789ba Mon Sep 17 00:00:00 2001 From: lucarlig Date: Fri, 1 Aug 2025 15:04:58 +0100 Subject: [PATCH 0330/1134] LLVM error with unsupported expression in static initializer for const pointer in array on macOS --- ...ported-static-initializer-in-const-array.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 tests/ui/codegen/unsupported-static-initializer-in-const-array.rs diff --git a/tests/ui/codegen/unsupported-static-initializer-in-const-array.rs b/tests/ui/codegen/unsupported-static-initializer-in-const-array.rs new file mode 100644 index 000000000000..bc94130ee199 --- /dev/null +++ b/tests/ui/codegen/unsupported-static-initializer-in-const-array.rs @@ -0,0 +1,18 @@ +//! LLVM error with unsupported expression in static +//! initializer for const pointer in array on macOS. +//! +//! Regression test for . + +//@ build-pass +//@ compile-flags: -C opt-level=3 + +const fn make() -> (i32, i32, *const i32) { + const V: i32 = 123; + &V as *const i32; + (0, 0, &V) +} + +fn main() { + let arr = [make(); 32]; + println!("{}", arr[0].0); +} From 19c6815a212d86c389ef54c3ddb02697ffc45f93 Mon Sep 17 00:00:00 2001 From: lucarlig Date: Fri, 1 Aug 2025 18:27:59 +0100 Subject: [PATCH 0331/1134] Multiple bounds checking elision failures --- .../bounds-check-elision-slice-min.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 tests/codegen-llvm/bounds-check-elision-slice-min.rs diff --git a/tests/codegen-llvm/bounds-check-elision-slice-min.rs b/tests/codegen-llvm/bounds-check-elision-slice-min.rs new file mode 100644 index 000000000000..e160e5da50f9 --- /dev/null +++ b/tests/codegen-llvm/bounds-check-elision-slice-min.rs @@ -0,0 +1,19 @@ +//! Regression test for #: +//! Multiple bounds checking elision failures +//! (ensures bounds checks are properly elided, +//! with no calls to panic_bounds_check in the LLVM IR). + +//@ compile-flags: -C opt-level=3 + +#![crate_type = "lib"] + +// CHECK-LABEL: @foo +// CHECK-NOT: panic_bounds_check +#[no_mangle] +pub fn foo(buf: &[u8], alloced_size: usize) -> &[u8] { + if alloced_size.checked_add(1).map(|total| buf.len() < total).unwrap_or(true) { + return &[]; + } + let size = buf[0]; + &buf[1..1 + usize::min(alloced_size, usize::from(size))] +} From 21ab47e3cb0613ad268e7a93fcfb076a41047c3b Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 1 Aug 2025 21:59:40 +0200 Subject: [PATCH 0332/1134] Add my previous commit name to .mailmap --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 90533e81b39f..2b75f5a145f2 100644 --- a/.mailmap +++ b/.mailmap @@ -597,6 +597,7 @@ Sam Radhakrishnan Samuel Tardieu Santiago Pastorino Santiago Pastorino +Sasha Pourcelot Sasha Scott McMurray Scott McMurray Scott Olson Scott Olson From ae2f8d921654f01e008824385fb1e1d7b36ce705 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 31 Jul 2025 14:56:49 +0000 Subject: [PATCH 0333/1134] Remove the omit_gdb_pretty_printer_section attribute Disabling loading of pretty printers in the debugger itself is more reliable. Before this commit the .gdb_debug_scripts section couldn't be included in dylibs or rlibs as otherwise there is no way to disable the section anymore without recompiling the entire standard library. --- .../src/attributes/codegen_attrs.rs | 8 - compiler/rustc_attr_parsing/src/context.rs | 6 +- .../rustc_codegen_llvm/src/debuginfo/gdb.rs | 8 +- compiler/rustc_feature/src/builtin_attrs.rs | 5 - compiler/rustc_feature/src/removed.rs | 2 + compiler/rustc_feature/src/unstable.rs | 2 - .../rustc_hir/src/attrs/data_structures.rs | 3 - .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 - compiler/rustc_passes/src/check_attr.rs | 3 +- .../rustc-dev-guide/src/tests/directives.md | 1 + src/tools/compiletest/src/directives.rs | 10 ++ .../src/directives/directive_names.rs | 1 + .../compiletest/src/runtest/debuginfo.rs | 4 +- tests/debuginfo/associated-types.rs | 3 +- .../debuginfo/auxiliary/cross_crate_spans.rs | 2 - .../debuginfo/basic-types-globals-metadata.rs | 3 +- tests/debuginfo/basic-types-globals.rs | 3 +- tests/debuginfo/basic-types-metadata.rs | 3 +- tests/debuginfo/basic-types-mut-globals.rs | 3 +- tests/debuginfo/basic-types.rs | 3 +- tests/debuginfo/borrowed-basic.rs | 3 +- tests/debuginfo/borrowed-c-style-enum.rs | 3 +- tests/debuginfo/borrowed-enum.rs | 3 +- tests/debuginfo/borrowed-struct.rs | 3 +- tests/debuginfo/borrowed-tuple.rs | 3 +- tests/debuginfo/borrowed-unique-basic.rs | 3 +- tests/debuginfo/box.rs | 3 +- tests/debuginfo/boxed-struct.rs | 3 +- .../by-value-non-immediate-argument.rs | 4 +- .../by-value-self-argument-in-trait-impl.rs | 4 +- tests/debuginfo/c-style-enum-in-composite.rs | 3 +- tests/debuginfo/c-style-enum.rs | 3 +- .../debuginfo/closure-in-generic-function.rs | 4 +- tests/debuginfo/constant-debug-locs.rs | 3 +- tests/debuginfo/constant-in-match-pattern.rs | 3 +- tests/debuginfo/coroutine-locals.rs | 4 +- tests/debuginfo/coroutine-objects.rs | 4 +- tests/debuginfo/cross-crate-spans.rs | 8 +- tests/debuginfo/destructured-fn-argument.rs | 3 +- .../destructured-for-loop-variable.rs | 3 +- tests/debuginfo/destructured-local.rs | 3 +- tests/debuginfo/enum-thinlto.rs | 3 +- tests/debuginfo/evec-in-struct.rs | 3 +- tests/debuginfo/extern-c-fn.rs | 4 +- .../debuginfo/function-arg-initialization.rs | 3 +- tests/debuginfo/function-arguments.rs | 5 +- tests/debuginfo/function-names.rs | 3 +- .../function-prologue-stepping-regular.rs | 3 +- tests/debuginfo/gdb-char.rs | 3 +- .../generic-enum-with-different-disr-sizes.rs | 3 +- tests/debuginfo/generic-function.rs | 4 +- tests/debuginfo/generic-functions-nested.rs | 5 +- .../generic-method-on-generic-struct.rs | 4 +- ...eneric-static-method-on-struct-and-enum.rs | 4 +- tests/debuginfo/generic-struct-style-enum.rs | 4 +- tests/debuginfo/generic-struct.rs | 4 +- tests/debuginfo/generic-tuple-style-enum.rs | 3 +- tests/debuginfo/include_string.rs | 3 +- tests/debuginfo/issue-12886.rs | 5 +- tests/debuginfo/issue-22656.rs | 3 +- tests/debuginfo/issue-57822.rs | 4 +- tests/debuginfo/lexical-scope-in-for-loop.rs | 4 +- tests/debuginfo/lexical-scope-in-if.rs | 4 +- tests/debuginfo/lexical-scope-in-match.rs | 4 +- .../lexical-scope-in-stack-closure.rs | 4 +- .../lexical-scope-in-unconditional-loop.rs | 4 +- .../lexical-scope-in-unique-closure.rs | 4 +- tests/debuginfo/lexical-scope-in-while.rs | 4 +- tests/debuginfo/lexical-scope-with-macro.rs | 4 +- .../lexical-scopes-in-block-expression.rs | 3 +- tests/debuginfo/limited-debuginfo.rs | 3 +- tests/debuginfo/method-on-enum.rs | 4 +- tests/debuginfo/method-on-generic-struct.rs | 4 +- tests/debuginfo/method-on-struct.rs | 4 +- tests/debuginfo/method-on-trait.rs | 4 +- tests/debuginfo/method-on-tuple-struct.rs | 4 +- tests/debuginfo/multi-cgu.rs | 4 +- .../multiple-functions-equal-var-names.rs | 3 +- tests/debuginfo/multiple-functions.rs | 3 +- .../name-shadowing-and-scope-nesting.rs | 4 +- tests/debuginfo/option-like-enum.rs | 4 +- .../packed-struct-with-destructor.rs | 3 +- tests/debuginfo/packed-struct.rs | 3 +- tests/debuginfo/recursive-enum.rs | 3 +- tests/debuginfo/recursive-struct.rs | 3 +- tests/debuginfo/reference-debuginfo.rs | 3 +- tests/debuginfo/self-in-default-method.rs | 4 +- .../self-in-generic-default-method.rs | 4 +- tests/debuginfo/shadowed-argument.rs | 4 +- tests/debuginfo/shadowed-variable.rs | 4 +- tests/debuginfo/simd.rs | 3 +- tests/debuginfo/simple-lexical-scope.rs | 4 +- tests/debuginfo/simple-struct.rs | 3 +- tests/debuginfo/simple-tuple.rs | 3 +- .../static-method-on-struct-and-enum.rs | 4 +- tests/debuginfo/strings-and-strs.rs | 3 +- tests/debuginfo/struct-in-enum.rs | 3 +- tests/debuginfo/struct-in-struct.rs | 3 +- tests/debuginfo/struct-namespace.rs | 3 +- tests/debuginfo/struct-style-enum.rs | 3 +- tests/debuginfo/struct-with-destructor.rs | 3 +- tests/debuginfo/trait-pointers.rs | 3 +- tests/debuginfo/tuple-in-struct.rs | 3 +- tests/debuginfo/tuple-in-tuple.rs | 3 +- tests/debuginfo/tuple-struct.rs | 4 +- tests/debuginfo/tuple-style-enum.rs | 3 +- tests/debuginfo/type-names.rs | 3 +- tests/debuginfo/union-smoke.rs | 3 +- tests/debuginfo/unique-enum.rs | 3 +- tests/debuginfo/unreachable-locals.rs | 3 +- tests/debuginfo/unsized.rs | 4 +- .../var-captured-in-nested-closure.rs | 3 +- .../var-captured-in-sendable-closure.rs | 3 +- .../var-captured-in-stack-closure.rs | 3 +- tests/debuginfo/vec-slices.rs | 3 +- tests/debuginfo/vec.rs | 3 +- tests/ui/attributes/malformed-attrs.rs | 4 - tests/ui/attributes/malformed-attrs.stderr | 169 +++++++++--------- ...re-gate-omit-gdb-pretty-printer-section.rs | 2 - ...ate-omit-gdb-pretty-printer-section.stderr | 12 -- 120 files changed, 209 insertions(+), 387 deletions(-) delete mode 100644 tests/ui/feature-gates/feature-gate-omit-gdb-pretty-printer-section.rs delete mode 100644 tests/ui/feature-gates/feature-gate-omit-gdb-pretty-printer-section.stderr diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index 7c8ef90ed7f1..c5fb11dbf6a0 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -374,11 +374,3 @@ impl CombineAttributeParser for TargetFeatureParser { features } } - -pub(crate) struct OmitGdbPrettyPrinterSectionParser; - -impl NoArgsAttributeParser for OmitGdbPrettyPrinterSectionParser { - const PATH: &[Symbol] = &[sym::omit_gdb_pretty_printer_section]; - const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; - const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::OmitGdbPrettyPrinterSection; -} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 54c0fbcd0626..0fccaf94e27f 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -17,9 +17,8 @@ use crate::attributes::allow_unstable::{ AllowConstFnUnstableParser, AllowInternalUnstableParser, UnstableFeatureBoundParser, }; use crate::attributes::codegen_attrs::{ - ColdParser, CoverageParser, ExportNameParser, NakedParser, NoMangleParser, - OmitGdbPrettyPrinterSectionParser, OptimizeParser, TargetFeatureParser, TrackCallerParser, - UsedParser, + ColdParser, CoverageParser, ExportNameParser, NakedParser, NoMangleParser, OptimizeParser, + TargetFeatureParser, TrackCallerParser, UsedParser, }; use crate::attributes::confusables::ConfusablesParser; use crate::attributes::deprecation::DeprecationParser; @@ -187,7 +186,6 @@ attribute_parsers!( Single>, Single>, Single>, - Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index bcfa0381cc1b..6eb7042da617 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -2,9 +2,7 @@ use rustc_codegen_ssa::base::collect_debugger_visualizers_transitive; use rustc_codegen_ssa::traits::*; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LOCAL_CRATE; -use rustc_hir::find_attr; use rustc_middle::bug; use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerType; use rustc_session::config::{CrateType, DebugInfo}; @@ -86,9 +84,6 @@ pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>( } pub(crate) fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool { - let omit_gdb_pretty_printer_section = - find_attr!(cx.tcx.hir_krate_attrs(), AttributeKind::OmitGdbPrettyPrinterSection); - // To ensure the section `__rustc_debug_gdb_scripts_section__` will not create // ODR violations at link time, this section will not be emitted for rlibs since // each rlib could produce a different set of visualizers that would be embedded @@ -117,8 +112,7 @@ pub(crate) fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool { } }); - !omit_gdb_pretty_printer_section - && cx.sess().opts.debuginfo != DebugInfo::None + cx.sess().opts.debuginfo != DebugInfo::None && cx.sess().target.emit_debug_gdb_scripts && embed_visualizers } diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index ceb7fc5bf6f8..5c63d4808db2 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -1257,11 +1257,6 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/), DuplicatesOk, EncodeCrossCrate::No ), - gated!( - omit_gdb_pretty_printer_section, Normal, template!(Word), - WarnFollowing, EncodeCrossCrate::No, - "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite", - ), rustc_attr!( TEST, pattern_complexity_limit, CrateLevel, template!(NameValueStr: "N"), ErrorFollowing, EncodeCrossCrate::No, diff --git a/compiler/rustc_feature/src/removed.rs b/compiler/rustc_feature/src/removed.rs index 7e174c465d59..4eee79a2a71e 100644 --- a/compiler/rustc_feature/src/removed.rs +++ b/compiler/rustc_feature/src/removed.rs @@ -199,6 +199,8 @@ declare_features! ( /// Renamed to `dyn_compatible_for_dispatch`. (removed, object_safe_for_dispatch, "1.83.0", Some(43561), Some("renamed to `dyn_compatible_for_dispatch`"), 131511), + /// Allows using `#[omit_gdb_pretty_printer_section]`. + (removed, omit_gdb_pretty_printer_section, "CURRENT_RUSTC_VERSION", None, None, 144738), /// Allows using `#[on_unimplemented(..)]` on traits. /// (Moved to `rustc_attrs`.) (removed, on_unimplemented, "1.40.0", None, None, 65794), diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index e985e04ba330..1303b3317e05 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -225,8 +225,6 @@ declare_features! ( (unstable, multiple_supertrait_upcastable, "1.69.0", None), /// Allow negative trait bounds. This is an internal-only feature for testing the trait solver! (internal, negative_bounds, "1.71.0", None), - /// Allows using `#[omit_gdb_pretty_printer_section]`. - (internal, omit_gdb_pretty_printer_section, "1.5.0", None), /// Set the maximum pattern complexity allowed (not limited by default). (internal, pattern_complexity_limit, "1.78.0", None), /// Allows using pattern types. diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 80f5e6177f75..80618422b56d 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -391,9 +391,6 @@ pub enum AttributeKind { /// Represents `#[non_exhaustive]` NonExhaustive(Span), - /// Represents `#[omit_gdb_pretty_printer_section]` - OmitGdbPrettyPrinterSection, - /// Represents `#[optimize(size|speed)]` Optimize(OptimizeAttr, Span), diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index bbdecb2986e0..9644a597a311 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -55,7 +55,6 @@ impl AttributeKind { NoImplicitPrelude(..) => No, NoMangle(..) => Yes, // Needed for rustdoc NonExhaustive(..) => Yes, // Needed for rustdoc - OmitGdbPrettyPrinterSection => No, Optimize(..) => No, ParenSugar(..) => No, PassByValue(..) => Yes, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index ede74bdc0df6..2663d5fe99c7 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -289,8 +289,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::MacroTransparency(_) | AttributeKind::Pointee(..) | AttributeKind::Dummy - | AttributeKind::RustcBuiltinMacro { .. } - | AttributeKind::OmitGdbPrettyPrinterSection, + | AttributeKind::RustcBuiltinMacro { .. }, ) => { /* do nothing */ } Attribute::Parsed(AttributeKind::AsPtr(attr_span)) => { self.check_applied_to_fn_or_method(hir_id, *attr_span, span, target) diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index 89e4d3e9b58e..08975777210c 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -298,6 +298,7 @@ See [Pretty-printer](compiletest.md#pretty-printer-tests). - [`should-ice`](compiletest.md#incremental-tests) — incremental cfail should ICE - [`reference`] — an annotation linking to a rule in the reference +- `disable-gdb-pretty-printers` — disable gdb pretty printers for debuginfo tests [`reference`]: https://github.com/rust-lang/reference/blob/master/docs/authoring.md#test-rule-annotations diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index 54511f4fd085..13e694b7f03c 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -203,6 +203,8 @@ pub struct TestProps { pub add_core_stubs: bool, /// Whether line annotatins are required for the given error kind. pub dont_require_annotations: HashSet, + /// Whether pretty printers should be disabled in gdb. + pub disable_gdb_pretty_printers: bool, } mod directives { @@ -251,6 +253,7 @@ mod directives { pub const ADD_CORE_STUBS: &'static str = "add-core-stubs"; // This isn't a real directive, just one that is probably mistyped often pub const INCORRECT_COMPILER_FLAGS: &'static str = "compiler-flags"; + pub const DISABLE_GDB_PRETTY_PRINTERS: &'static str = "disable-gdb-pretty-printers"; } impl TestProps { @@ -306,6 +309,7 @@ impl TestProps { has_enzyme: false, add_core_stubs: false, dont_require_annotations: Default::default(), + disable_gdb_pretty_printers: false, } } @@ -654,6 +658,12 @@ impl TestProps { self.dont_require_annotations .insert(ErrorKind::expect_from_user_str(err_kind.trim())); } + + config.set_name_directive( + ln, + DISABLE_GDB_PRETTY_PRINTERS, + &mut self.disable_gdb_pretty_printers, + ); }, ); diff --git a/src/tools/compiletest/src/directives/directive_names.rs b/src/tools/compiletest/src/directives/directive_names.rs index 7fc76a42e0ca..f7955429d836 100644 --- a/src/tools/compiletest/src/directives/directive_names.rs +++ b/src/tools/compiletest/src/directives/directive_names.rs @@ -18,6 +18,7 @@ pub(crate) const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "check-stdout", "check-test-line-numbers-match", "compile-flags", + "disable-gdb-pretty-printers", "doc-flags", "dont-check-compiler-stderr", "dont-check-compiler-stdout", diff --git a/src/tools/compiletest/src/runtest/debuginfo.rs b/src/tools/compiletest/src/runtest/debuginfo.rs index 471e4a4c8193..6114afdc9df5 100644 --- a/src/tools/compiletest/src/runtest/debuginfo.rs +++ b/src/tools/compiletest/src/runtest/debuginfo.rs @@ -259,7 +259,9 @@ impl TestCx<'_> { Some(version) => { println!("NOTE: compiletest thinks it is using GDB version {}", version); - if version > extract_gdb_version("7.4").unwrap() { + if !self.props.disable_gdb_pretty_printers + && version > extract_gdb_version("7.4").unwrap() + { // Add the directory containing the pretty printers to // GDB's script auto loading safe path script_str.push_str(&format!( diff --git a/tests/debuginfo/associated-types.rs b/tests/debuginfo/associated-types.rs index b20bd5209368..7c2a793c8cd3 100644 --- a/tests/debuginfo/associated-types.rs +++ b/tests/debuginfo/associated-types.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== // gdb-command:run @@ -68,8 +69,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] trait TraitWithAssocType { type Type; diff --git a/tests/debuginfo/auxiliary/cross_crate_spans.rs b/tests/debuginfo/auxiliary/cross_crate_spans.rs index af853ee0b003..d0d32c2cbe32 100644 --- a/tests/debuginfo/auxiliary/cross_crate_spans.rs +++ b/tests/debuginfo/auxiliary/cross_crate_spans.rs @@ -1,8 +1,6 @@ #![crate_type = "rlib"] #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] //@ no-prefer-dynamic //@ compile-flags:-g diff --git a/tests/debuginfo/basic-types-globals-metadata.rs b/tests/debuginfo/basic-types-globals-metadata.rs index aec8ff183ad7..fc8f6dc173fc 100644 --- a/tests/debuginfo/basic-types-globals-metadata.rs +++ b/tests/debuginfo/basic-types-globals-metadata.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run // gdb-command:whatis basic_types_globals_metadata::B @@ -35,8 +36,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(f16)] // N.B. These are `mut` only so they don't constant fold away. diff --git a/tests/debuginfo/basic-types-globals.rs b/tests/debuginfo/basic-types-globals.rs index 15a0deb64c12..9d28820ce685 100644 --- a/tests/debuginfo/basic-types-globals.rs +++ b/tests/debuginfo/basic-types-globals.rs @@ -1,6 +1,7 @@ //@ revisions: lto no-lto //@ compile-flags:-g +//@ disable-gdb-pretty-printers //@ [lto] compile-flags:-C lto //@ [lto] no-prefer-dynamic @@ -39,8 +40,6 @@ // gdb-command:continue #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(f16)] // N.B. These are `mut` only so they don't constant fold away. diff --git a/tests/debuginfo/basic-types-metadata.rs b/tests/debuginfo/basic-types-metadata.rs index 6b7cfbdebca9..941db81a4dec 100644 --- a/tests/debuginfo/basic-types-metadata.rs +++ b/tests/debuginfo/basic-types-metadata.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run // gdb-command:whatis unit @@ -53,8 +54,6 @@ // gdb-command:continue #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(f16)] fn main() { diff --git a/tests/debuginfo/basic-types-mut-globals.rs b/tests/debuginfo/basic-types-mut-globals.rs index f6a2399d230a..e979d82b55c6 100644 --- a/tests/debuginfo/basic-types-mut-globals.rs +++ b/tests/debuginfo/basic-types-mut-globals.rs @@ -5,6 +5,7 @@ // its numerical value. //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run @@ -74,8 +75,6 @@ // gdb-check:$30 = 9.25 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(f16)] static mut B: bool = false; diff --git a/tests/debuginfo/basic-types.rs b/tests/debuginfo/basic-types.rs index fea5262bc41d..7862f45b3c4e 100644 --- a/tests/debuginfo/basic-types.rs +++ b/tests/debuginfo/basic-types.rs @@ -5,6 +5,7 @@ // its numerical value. //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -112,8 +113,6 @@ // cdb-check:s : [...] [Type: ref$] #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(f16)] fn main() { diff --git a/tests/debuginfo/borrowed-basic.rs b/tests/debuginfo/borrowed-basic.rs index 91de691e78e1..334eae38318e 100644 --- a/tests/debuginfo/borrowed-basic.rs +++ b/tests/debuginfo/borrowed-basic.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -96,8 +97,6 @@ // lldb-check:[...] 3.5 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(f16)] fn main() { diff --git a/tests/debuginfo/borrowed-c-style-enum.rs b/tests/debuginfo/borrowed-c-style-enum.rs index 6a91d4f96504..d382a389fe41 100644 --- a/tests/debuginfo/borrowed-c-style-enum.rs +++ b/tests/debuginfo/borrowed-c-style-enum.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -28,8 +29,6 @@ // lldb-check:[...] TheC #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] enum ABC { TheA, TheB, TheC } diff --git a/tests/debuginfo/borrowed-enum.rs b/tests/debuginfo/borrowed-enum.rs index c5a795fdede6..517b439ff15c 100644 --- a/tests/debuginfo/borrowed-enum.rs +++ b/tests/debuginfo/borrowed-enum.rs @@ -1,6 +1,7 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -28,8 +29,6 @@ // lldb-check:(borrowed_enum::Univariant) *univariant_ref = { value = { 0 = 4820353753753434 } } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when diff --git a/tests/debuginfo/borrowed-struct.rs b/tests/debuginfo/borrowed-struct.rs index 245af35f5055..5d64ba3cbefb 100644 --- a/tests/debuginfo/borrowed-struct.rs +++ b/tests/debuginfo/borrowed-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -52,8 +53,6 @@ // lldb-check:[...] 26.5 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct SomeStruct { x: isize, diff --git a/tests/debuginfo/borrowed-tuple.rs b/tests/debuginfo/borrowed-tuple.rs index 9e4ceec033ec..fd4e22feb069 100644 --- a/tests/debuginfo/borrowed-tuple.rs +++ b/tests/debuginfo/borrowed-tuple.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -29,8 +30,6 @@ #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] fn main() { let stack_val: (i16, f32) = (-14, -19f32); diff --git a/tests/debuginfo/borrowed-unique-basic.rs b/tests/debuginfo/borrowed-unique-basic.rs index 7a9b4d1df825..54d7f27bb0c8 100644 --- a/tests/debuginfo/borrowed-unique-basic.rs +++ b/tests/debuginfo/borrowed-unique-basic.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -100,8 +101,6 @@ // lldb-check:[...] 3.5 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(f16)] fn main() { diff --git a/tests/debuginfo/box.rs b/tests/debuginfo/box.rs index d22566c0b179..d4612f98a5f1 100644 --- a/tests/debuginfo/box.rs +++ b/tests/debuginfo/box.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -19,8 +20,6 @@ // lldb-check:[...] { 0 = 2 1 = 3.5 } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] fn main() { let a = Box::new(1); diff --git a/tests/debuginfo/boxed-struct.rs b/tests/debuginfo/boxed-struct.rs index 158609fb2ed7..ca072693cdcd 100644 --- a/tests/debuginfo/boxed-struct.rs +++ b/tests/debuginfo/boxed-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -22,8 +23,6 @@ // lldb-check:[...] { x = 77 y = 777 z = 7777 w = 77777 } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct StructWithSomePadding { x: i16, diff --git a/tests/debuginfo/by-value-non-immediate-argument.rs b/tests/debuginfo/by-value-non-immediate-argument.rs index deacea5f6ccd..b5b0df73a68a 100644 --- a/tests/debuginfo/by-value-non-immediate-argument.rs +++ b/tests/debuginfo/by-value-non-immediate-argument.rs @@ -1,6 +1,7 @@ //@ min-lldb-version: 1800 //@ min-gdb-version: 13.0 //@ compile-flags:-g +//@ disable-gdb-pretty-printers //@ ignore-windows-gnu: #128973 //@ ignore-aarch64-unknown-linux-gnu (gdb tries to read from 0x0; FIXME: #128973) //@ ignore-powerpc64: #128973 on both -gnu and -musl @@ -62,9 +63,6 @@ // lldb-check:[...] Case1 { x: 0, y: 8970181431921507452 } // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Clone)] struct Struct { a: isize, diff --git a/tests/debuginfo/by-value-self-argument-in-trait-impl.rs b/tests/debuginfo/by-value-self-argument-in-trait-impl.rs index 6981fdfc9e11..a49a375569b1 100644 --- a/tests/debuginfo/by-value-self-argument-in-trait-impl.rs +++ b/tests/debuginfo/by-value-self-argument-in-trait-impl.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -33,9 +34,6 @@ // lldb-check:[...] { 0 = 4444.5 1 = 5555 2 = 6666 3 = 7777.5 } // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - trait Trait { fn method(self) -> Self; } diff --git a/tests/debuginfo/c-style-enum-in-composite.rs b/tests/debuginfo/c-style-enum-in-composite.rs index 642879cf3b67..47b4b980f9cc 100644 --- a/tests/debuginfo/c-style-enum-in-composite.rs +++ b/tests/debuginfo/c-style-enum-in-composite.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -51,8 +52,6 @@ // lldb-check:[...] { 0 = { a = OneHundred b = Vienna } 1 = 9 } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::AnEnum::{OneHundred, OneThousand, OneMillion}; use self::AnotherEnum::{MountainView, Toronto, Vienna}; diff --git a/tests/debuginfo/c-style-enum.rs b/tests/debuginfo/c-style-enum.rs index 08378f7af181..d5455be0cb56 100644 --- a/tests/debuginfo/c-style-enum.rs +++ b/tests/debuginfo/c-style-enum.rs @@ -1,6 +1,7 @@ //@ ignore-aarch64 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -88,8 +89,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::AutoDiscriminant::{One, Two, Three}; use self::ManualDiscriminant::{OneHundred, OneThousand, OneMillion}; diff --git a/tests/debuginfo/closure-in-generic-function.rs b/tests/debuginfo/closure-in-generic-function.rs index 0c6a6fdfca1b..0bb72209cc82 100644 --- a/tests/debuginfo/closure-in-generic-function.rs +++ b/tests/debuginfo/closure-in-generic-function.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -33,9 +34,6 @@ // lldb-check:[...] 110 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn some_generic_fun(a: T1, b: T2) -> (T2, T1) { let closure = |x, y| { diff --git a/tests/debuginfo/constant-debug-locs.rs b/tests/debuginfo/constant-debug-locs.rs index 81115fc3c384..d13b8648b18a 100644 --- a/tests/debuginfo/constant-debug-locs.rs +++ b/tests/debuginfo/constant-debug-locs.rs @@ -1,8 +1,7 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers #![allow(dead_code, unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // This test makes sure that the compiler doesn't crash when trying to assign // debug locations to const-expressions. diff --git a/tests/debuginfo/constant-in-match-pattern.rs b/tests/debuginfo/constant-in-match-pattern.rs index 952db216debf..922e0a5d8da2 100644 --- a/tests/debuginfo/constant-in-match-pattern.rs +++ b/tests/debuginfo/constant-in-match-pattern.rs @@ -1,8 +1,7 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers #![allow(dead_code, unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // This test makes sure that the compiler doesn't crash when trying to assign // debug locations to 'constant' patterns in match expressions. diff --git a/tests/debuginfo/coroutine-locals.rs b/tests/debuginfo/coroutine-locals.rs index f3593adc9453..c2b8aef8a673 100644 --- a/tests/debuginfo/coroutine-locals.rs +++ b/tests/debuginfo/coroutine-locals.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -44,8 +45,7 @@ // lldb-command:v c // lldb-check:(int) c = 6 -#![feature(omit_gdb_pretty_printer_section, coroutines, coroutine_trait, stmt_expr_attributes)] -#![omit_gdb_pretty_printer_section] +#![feature(coroutines, coroutine_trait, stmt_expr_attributes)] use std::ops::Coroutine; use std::pin::Pin; diff --git a/tests/debuginfo/coroutine-objects.rs b/tests/debuginfo/coroutine-objects.rs index 242c76c2989e..7ead154cbdb1 100644 --- a/tests/debuginfo/coroutine-objects.rs +++ b/tests/debuginfo/coroutine-objects.rs @@ -5,6 +5,7 @@ // ensure that LLDB won't crash at least (like #57822). //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -53,8 +54,7 @@ // cdb-check: b : Returned [Type: enum2$] // cdb-check: [+0x[...]] _ref__a : 0x[...] : 6 [Type: int *] -#![feature(omit_gdb_pretty_printer_section, coroutines, coroutine_trait, stmt_expr_attributes)] -#![omit_gdb_pretty_printer_section] +#![feature(coroutines, coroutine_trait, stmt_expr_attributes)] use std::ops::Coroutine; use std::pin::Pin; diff --git a/tests/debuginfo/cross-crate-spans.rs b/tests/debuginfo/cross-crate-spans.rs index e337aaf5a6c9..38176e46909c 100644 --- a/tests/debuginfo/cross-crate-spans.rs +++ b/tests/debuginfo/cross-crate-spans.rs @@ -1,15 +1,13 @@ -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - //@ aux-build:cross_crate_spans.rs extern crate cross_crate_spans; //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== -// gdb-command:break cross_crate_spans.rs:14 +// gdb-command:break cross_crate_spans.rs:12 // gdb-command:run // gdb-command:print result @@ -32,7 +30,7 @@ extern crate cross_crate_spans; // === LLDB TESTS ================================================================================== -// lldb-command:b cross_crate_spans.rs:14 +// lldb-command:b cross_crate_spans.rs:12 // lldb-command:run // lldb-command:v result diff --git a/tests/debuginfo/destructured-fn-argument.rs b/tests/debuginfo/destructured-fn-argument.rs index 37a7bb2b7786..fe8f91588e06 100644 --- a/tests/debuginfo/destructured-fn-argument.rs +++ b/tests/debuginfo/destructured-fn-argument.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -299,8 +300,6 @@ #![allow(unused_variables)] #![feature(box_patterns)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::Univariant::Unit; diff --git a/tests/debuginfo/destructured-for-loop-variable.rs b/tests/debuginfo/destructured-for-loop-variable.rs index cc16be1268ae..01c524083dae 100644 --- a/tests/debuginfo/destructured-for-loop-variable.rs +++ b/tests/debuginfo/destructured-for-loop-variable.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -141,8 +142,6 @@ #![allow(unused_variables)] #![feature(box_patterns)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct Struct { x: i16, diff --git a/tests/debuginfo/destructured-local.rs b/tests/debuginfo/destructured-local.rs index fad96ca7d4b6..ff24c924aada 100644 --- a/tests/debuginfo/destructured-local.rs +++ b/tests/debuginfo/destructured-local.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -232,8 +233,6 @@ #![allow(unused_variables)] #![feature(box_patterns)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::Univariant::Unit; diff --git a/tests/debuginfo/enum-thinlto.rs b/tests/debuginfo/enum-thinlto.rs index af77145c312d..6eb33b2ef46a 100644 --- a/tests/debuginfo/enum-thinlto.rs +++ b/tests/debuginfo/enum-thinlto.rs @@ -1,5 +1,6 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g -Z thinlto +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -16,8 +17,6 @@ // lldb-check:(enum_thinlto::ABC) *abc = { value = { x = 0 y = 8970181431921507452 } $discr$ = 0 } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when diff --git a/tests/debuginfo/evec-in-struct.rs b/tests/debuginfo/evec-in-struct.rs index 303669cf06cd..f08c436bbe3a 100644 --- a/tests/debuginfo/evec-in-struct.rs +++ b/tests/debuginfo/evec-in-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -38,8 +39,6 @@ // lldb-check:[...] { x = { [0] = 22 [1] = 23 } y = { [0] = 24 [1] = 25 } } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct NoPadding1 { x: [u32; 3], diff --git a/tests/debuginfo/extern-c-fn.rs b/tests/debuginfo/extern-c-fn.rs index 4642073faabc..7130658f2d82 100644 --- a/tests/debuginfo/extern-c-fn.rs +++ b/tests/debuginfo/extern-c-fn.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== // gdb-command:run @@ -32,9 +33,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[no_mangle] pub unsafe extern "C" fn fn_with_c_abi(s: *const u8, len: i32) -> i32 { diff --git a/tests/debuginfo/function-arg-initialization.rs b/tests/debuginfo/function-arg-initialization.rs index ae54d56623c6..03fb1e2d062f 100644 --- a/tests/debuginfo/function-arg-initialization.rs +++ b/tests/debuginfo/function-arg-initialization.rs @@ -8,6 +8,7 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g -Zmir-enable-passes=-SingleUseConsts // SingleUseConsts shouldn't need to be disabled, see #128945 +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -214,8 +215,6 @@ #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] fn immediate_args(a: isize, b: bool, c: f64) { zzz(); // #break diff --git a/tests/debuginfo/function-arguments.rs b/tests/debuginfo/function-arguments.rs index 21c0c7d859cc..64d026a705bf 100644 --- a/tests/debuginfo/function-arguments.rs +++ b/tests/debuginfo/function-arguments.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -32,10 +33,6 @@ // lldb-check:[...] 3000 // lldb-command:continue - -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { fun(111102, true); diff --git a/tests/debuginfo/function-names.rs b/tests/debuginfo/function-names.rs index c51884451e56..b5aec5c595e7 100644 --- a/tests/debuginfo/function-names.rs +++ b/tests/debuginfo/function-names.rs @@ -2,6 +2,7 @@ //@ min-gdb-version: 10.1 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -78,8 +79,6 @@ // cdb-check:[...] a!function_names::const_generic_fn_bool (void) #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(adt_const_params, coroutines, coroutine_trait, stmt_expr_attributes)] #![allow(incomplete_features)] diff --git a/tests/debuginfo/function-prologue-stepping-regular.rs b/tests/debuginfo/function-prologue-stepping-regular.rs index 07b9356fb507..f61128ca2df1 100644 --- a/tests/debuginfo/function-prologue-stepping-regular.rs +++ b/tests/debuginfo/function-prologue-stepping-regular.rs @@ -4,6 +4,7 @@ //@ min-lldb-version: 1800 //@ ignore-gdb //@ compile-flags:-g +//@ disable-gdb-pretty-printers // lldb-command:breakpoint set --name immediate_args // lldb-command:breakpoint set --name non_immediate_args @@ -116,8 +117,6 @@ // lldb-command:continue #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] fn immediate_args(a: isize, b: bool, c: f64) { () diff --git a/tests/debuginfo/gdb-char.rs b/tests/debuginfo/gdb-char.rs index 7d8608d4f511..d296e675fa3e 100644 --- a/tests/debuginfo/gdb-char.rs +++ b/tests/debuginfo/gdb-char.rs @@ -3,6 +3,7 @@ //@ min-gdb-version: 11.2 //@ compile-flags: -g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -11,8 +12,6 @@ // gdb-check:$1 = 97 'a' #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] fn main() { let ch: char = 'a'; diff --git a/tests/debuginfo/generic-enum-with-different-disr-sizes.rs b/tests/debuginfo/generic-enum-with-different-disr-sizes.rs index e723543a37b2..5c5f05d9c4b1 100644 --- a/tests/debuginfo/generic-enum-with-different-disr-sizes.rs +++ b/tests/debuginfo/generic-enum-with-different-disr-sizes.rs @@ -1,6 +1,7 @@ //@ ignore-lldb: FIXME(#27089) //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== // gdb-command:run @@ -57,8 +58,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // This test case makes sure that we get correct type descriptions for the enum // discriminant of different instantiations of the same generic enum type where, diff --git a/tests/debuginfo/generic-function.rs b/tests/debuginfo/generic-function.rs index 4be8d5ad45aa..ab3cb6953ace 100644 --- a/tests/debuginfo/generic-function.rs +++ b/tests/debuginfo/generic-function.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -44,9 +45,6 @@ // lldb-check:[...] { a = 6 b = 7.5 } // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Clone)] struct Struct { a: isize, diff --git a/tests/debuginfo/generic-functions-nested.rs b/tests/debuginfo/generic-functions-nested.rs index 7e0c20f89038..8ac2b8b9d7a1 100644 --- a/tests/debuginfo/generic-functions-nested.rs +++ b/tests/debuginfo/generic-functions-nested.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -57,10 +58,6 @@ // lldb-check:[...] 2.5 // lldb-command:continue - -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn outer(a: TA) { inner(a.clone(), 1); inner(a.clone(), 2.5f64); diff --git a/tests/debuginfo/generic-method-on-generic-struct.rs b/tests/debuginfo/generic-method-on-generic-struct.rs index 9c587ca2839b..36a94f2999d7 100644 --- a/tests/debuginfo/generic-method-on-generic-struct.rs +++ b/tests/debuginfo/generic-method-on-generic-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -99,9 +100,6 @@ // lldb-check:[...] -10.5 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Copy, Clone)] struct Struct { x: T diff --git a/tests/debuginfo/generic-static-method-on-struct-and-enum.rs b/tests/debuginfo/generic-static-method-on-struct-and-enum.rs index 79fe2144cf4b..09b515d69e49 100644 --- a/tests/debuginfo/generic-static-method-on-struct-and-enum.rs +++ b/tests/debuginfo/generic-static-method-on-struct-and-enum.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run @@ -19,9 +20,6 @@ // gdb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - struct Struct { x: isize } diff --git a/tests/debuginfo/generic-struct-style-enum.rs b/tests/debuginfo/generic-struct-style-enum.rs index a5529ab8027d..4f580f8c515d 100644 --- a/tests/debuginfo/generic-struct-style-enum.rs +++ b/tests/debuginfo/generic-struct-style-enum.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:set print union on // gdb-command:run @@ -16,9 +17,6 @@ // gdb-check:$4 = generic_struct_style_enum::Univariant::TheOnlyCase{a: -1} -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - use self::Regular::{Case1, Case2, Case3}; use self::Univariant::TheOnlyCase; diff --git a/tests/debuginfo/generic-struct.rs b/tests/debuginfo/generic-struct.rs index f26d823d4f2e..0196ca435447 100644 --- a/tests/debuginfo/generic-struct.rs +++ b/tests/debuginfo/generic-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -49,9 +50,6 @@ // cdb-check:[...]value [Type: generic_struct::AGenericStruct] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - struct AGenericStruct { key: TKey, value: TValue diff --git a/tests/debuginfo/generic-tuple-style-enum.rs b/tests/debuginfo/generic-tuple-style-enum.rs index 4a5996645cb4..719b5c6161f0 100644 --- a/tests/debuginfo/generic-tuple-style-enum.rs +++ b/tests/debuginfo/generic-tuple-style-enum.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -30,8 +31,6 @@ // lldb-command:v univariant -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::Regular::{Case1, Case2, Case3}; use self::Univariant::TheOnlyCase; diff --git a/tests/debuginfo/include_string.rs b/tests/debuginfo/include_string.rs index 704b85e1ac2d..4ec23b68262a 100644 --- a/tests/debuginfo/include_string.rs +++ b/tests/debuginfo/include_string.rs @@ -2,6 +2,7 @@ // ^ test temporarily disabled as it fails under gdb 15 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run // gdb-command:print string1.length // gdb-check:$1 = 48 @@ -26,8 +27,6 @@ // lldb-command:continue #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // This test case makes sure that debug info does not ICE when include_str is // used multiple times (see issue #11322). diff --git a/tests/debuginfo/issue-12886.rs b/tests/debuginfo/issue-12886.rs index 48250e885374..5574294cd57c 100644 --- a/tests/debuginfo/issue-12886.rs +++ b/tests/debuginfo/issue-12886.rs @@ -2,14 +2,13 @@ //@ ignore-aarch64 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run // gdb-command:next -// gdb-check:[...]23[...]let s = Some(5).unwrap(); // #break +// gdb-check:[...]22[...]let s = Some(5).unwrap(); // #break // gdb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // IF YOU MODIFY THIS FILE, BE CAREFUL TO ADAPT THE LINE NUMBERS IN THE DEBUGGER COMMANDS diff --git a/tests/debuginfo/issue-22656.rs b/tests/debuginfo/issue-22656.rs index eb0b38cfa4d6..3407c0524ebb 100644 --- a/tests/debuginfo/issue-22656.rs +++ b/tests/debuginfo/issue-22656.rs @@ -5,6 +5,7 @@ //@ ignore-gdb //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === LLDB TESTS ================================================================================== // lldb-command:run @@ -16,8 +17,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct ZeroSizedStruct; diff --git a/tests/debuginfo/issue-57822.rs b/tests/debuginfo/issue-57822.rs index 7abac1c14d32..ba4e01196a4c 100644 --- a/tests/debuginfo/issue-57822.rs +++ b/tests/debuginfo/issue-57822.rs @@ -3,6 +3,7 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -24,8 +25,7 @@ // lldb-command:v b // lldb-check:(issue_57822::main::{coroutine_env#3}) b = { value = { a = { value = { y = 2 } $discr$ = '\x02' } } $discr$ = '\x02' } -#![feature(omit_gdb_pretty_printer_section, coroutines, coroutine_trait, stmt_expr_attributes)] -#![omit_gdb_pretty_printer_section] +#![feature(coroutines, coroutine_trait, stmt_expr_attributes)] use std::ops::Coroutine; use std::pin::Pin; diff --git a/tests/debuginfo/lexical-scope-in-for-loop.rs b/tests/debuginfo/lexical-scope-in-for-loop.rs index 08f244f89a02..f591f48ad59d 100644 --- a/tests/debuginfo/lexical-scope-in-for-loop.rs +++ b/tests/debuginfo/lexical-scope-in-for-loop.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -73,9 +74,6 @@ // lldb-check:[...] 1000000 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let range = [1, 2, 3]; diff --git a/tests/debuginfo/lexical-scope-in-if.rs b/tests/debuginfo/lexical-scope-in-if.rs index c0e1f2f3e05c..2b3a4ee5fc4a 100644 --- a/tests/debuginfo/lexical-scope-in-if.rs +++ b/tests/debuginfo/lexical-scope-in-if.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -121,9 +122,6 @@ // lldb-check:[...] -1 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let x = 999; diff --git a/tests/debuginfo/lexical-scope-in-match.rs b/tests/debuginfo/lexical-scope-in-match.rs index 9169c19c6a33..0e369c6ca164 100644 --- a/tests/debuginfo/lexical-scope-in-match.rs +++ b/tests/debuginfo/lexical-scope-in-match.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -113,9 +114,6 @@ // lldb-check:[...] 232 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - struct Struct { x: isize, y: isize diff --git a/tests/debuginfo/lexical-scope-in-stack-closure.rs b/tests/debuginfo/lexical-scope-in-stack-closure.rs index d01162c39d69..483d5dda86ce 100644 --- a/tests/debuginfo/lexical-scope-in-stack-closure.rs +++ b/tests/debuginfo/lexical-scope-in-stack-closure.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -57,9 +58,6 @@ // lldb-check:[...] false // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let x = false; diff --git a/tests/debuginfo/lexical-scope-in-unconditional-loop.rs b/tests/debuginfo/lexical-scope-in-unconditional-loop.rs index dfec570218f3..129d0b8c83de 100644 --- a/tests/debuginfo/lexical-scope-in-unconditional-loop.rs +++ b/tests/debuginfo/lexical-scope-in-unconditional-loop.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -119,9 +120,6 @@ // lldb-check:[...] 2 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let mut x = 0; diff --git a/tests/debuginfo/lexical-scope-in-unique-closure.rs b/tests/debuginfo/lexical-scope-in-unique-closure.rs index db84005121af..93bea18d7cd9 100644 --- a/tests/debuginfo/lexical-scope-in-unique-closure.rs +++ b/tests/debuginfo/lexical-scope-in-unique-closure.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -58,9 +59,6 @@ // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let x = false; diff --git a/tests/debuginfo/lexical-scope-in-while.rs b/tests/debuginfo/lexical-scope-in-while.rs index d6536d77545b..5fe76851bd7f 100644 --- a/tests/debuginfo/lexical-scope-in-while.rs +++ b/tests/debuginfo/lexical-scope-in-while.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -119,9 +120,6 @@ // lldb-check:[...] 2 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let mut x = 0; diff --git a/tests/debuginfo/lexical-scope-with-macro.rs b/tests/debuginfo/lexical-scope-with-macro.rs index 6e8fef201ead..efec9a3b1ce7 100644 --- a/tests/debuginfo/lexical-scope-with-macro.rs +++ b/tests/debuginfo/lexical-scope-with-macro.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -97,9 +98,6 @@ // lldb-check:[...] 400 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - macro_rules! trivial { ($e1:expr) => ($e1) } diff --git a/tests/debuginfo/lexical-scopes-in-block-expression.rs b/tests/debuginfo/lexical-scopes-in-block-expression.rs index cd27c88db58e..bec69ec87e84 100644 --- a/tests/debuginfo/lexical-scopes-in-block-expression.rs +++ b/tests/debuginfo/lexical-scopes-in-block-expression.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -336,8 +337,6 @@ #![allow(unused_variables)] #![allow(unused_assignments)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] static mut MUT_INT: isize = 0; diff --git a/tests/debuginfo/limited-debuginfo.rs b/tests/debuginfo/limited-debuginfo.rs index fb453d8078ce..c3b516460aa3 100644 --- a/tests/debuginfo/limited-debuginfo.rs +++ b/tests/debuginfo/limited-debuginfo.rs @@ -1,6 +1,7 @@ //@ ignore-lldb //@ compile-flags:-C debuginfo=1 +//@ disable-gdb-pretty-printers // Make sure functions have proper names // gdb-command:info functions @@ -18,8 +19,6 @@ #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct Struct { a: i64, diff --git a/tests/debuginfo/method-on-enum.rs b/tests/debuginfo/method-on-enum.rs index 754b4a2dc26c..f86cf8ccfdf7 100644 --- a/tests/debuginfo/method-on-enum.rs +++ b/tests/debuginfo/method-on-enum.rs @@ -2,6 +2,7 @@ //@ min-gdb-version: 13.0 //@ compile-flags:-g +//@ disable-gdb-pretty-printers //@ ignore-windows-gnu: #128973 @@ -104,9 +105,6 @@ // lldb-check:[...] -10 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Copy, Clone)] enum Enum { Variant1 { x: u16, y: u16 }, diff --git a/tests/debuginfo/method-on-generic-struct.rs b/tests/debuginfo/method-on-generic-struct.rs index 1e6c9d66178a..5da952fa4e10 100644 --- a/tests/debuginfo/method-on-generic-struct.rs +++ b/tests/debuginfo/method-on-generic-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -99,9 +100,6 @@ // lldb-check:[...] -10 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Copy, Clone)] struct Struct { x: T diff --git a/tests/debuginfo/method-on-struct.rs b/tests/debuginfo/method-on-struct.rs index 91f609365e9a..83badd8dbf01 100644 --- a/tests/debuginfo/method-on-struct.rs +++ b/tests/debuginfo/method-on-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -99,9 +100,6 @@ // lldb-check:[...] -10 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Copy, Clone)] struct Struct { x: isize diff --git a/tests/debuginfo/method-on-trait.rs b/tests/debuginfo/method-on-trait.rs index 7b95e1f81c70..c91b255bd6af 100644 --- a/tests/debuginfo/method-on-trait.rs +++ b/tests/debuginfo/method-on-trait.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -99,9 +100,6 @@ // lldb-check:[...] -10 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Copy, Clone)] struct Struct { x: isize diff --git a/tests/debuginfo/method-on-tuple-struct.rs b/tests/debuginfo/method-on-tuple-struct.rs index 04c00d883025..7e6e724d42eb 100644 --- a/tests/debuginfo/method-on-tuple-struct.rs +++ b/tests/debuginfo/method-on-tuple-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -99,9 +100,6 @@ // lldb-check:[...] -10 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Copy, Clone)] struct TupleStruct(isize, f64); diff --git a/tests/debuginfo/multi-cgu.rs b/tests/debuginfo/multi-cgu.rs index 3bb5269adead..ca4146da405e 100644 --- a/tests/debuginfo/multi-cgu.rs +++ b/tests/debuginfo/multi-cgu.rs @@ -2,6 +2,7 @@ // compiled with multiple codegen units. (see #39160) //@ compile-flags:-g -Ccodegen-units=2 +//@ disable-gdb-pretty-printers // === GDB TESTS =============================================================== @@ -29,9 +30,6 @@ // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - mod a { pub fn foo(xxx: u32) { super::_zzz(); // #break diff --git a/tests/debuginfo/multiple-functions-equal-var-names.rs b/tests/debuginfo/multiple-functions-equal-var-names.rs index 6ae9225d55c3..2bc40b87e6f5 100644 --- a/tests/debuginfo/multiple-functions-equal-var-names.rs +++ b/tests/debuginfo/multiple-functions-equal-var-names.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -32,8 +33,6 @@ // lldb-check:[...] 30303 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] fn function_one() { let abc = 10101; diff --git a/tests/debuginfo/multiple-functions.rs b/tests/debuginfo/multiple-functions.rs index 3f7a0ded91b0..5469408c78fb 100644 --- a/tests/debuginfo/multiple-functions.rs +++ b/tests/debuginfo/multiple-functions.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -32,8 +33,6 @@ // lldb-check:[...] 30303 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] fn function_one() { let a = 10101; diff --git a/tests/debuginfo/name-shadowing-and-scope-nesting.rs b/tests/debuginfo/name-shadowing-and-scope-nesting.rs index d3829b60713d..e8d85473d863 100644 --- a/tests/debuginfo/name-shadowing-and-scope-nesting.rs +++ b/tests/debuginfo/name-shadowing-and-scope-nesting.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -81,9 +82,6 @@ // lldb-check:[...] 20 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let x = false; let y = true; diff --git a/tests/debuginfo/option-like-enum.rs b/tests/debuginfo/option-like-enum.rs index 72a41986dcef..5a55b143fbbd 100644 --- a/tests/debuginfo/option-like-enum.rs +++ b/tests/debuginfo/option-like-enum.rs @@ -2,6 +2,7 @@ //@ min-gdb-version: 13.0 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -69,9 +70,6 @@ // lldb-check:[...] Nope -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - // If a struct has exactly two variants, one of them is empty, and the other one // contains a non-nullable pointer, then this value is used as the discriminator. // The test cases in this file make sure that something readable is generated for diff --git a/tests/debuginfo/packed-struct-with-destructor.rs b/tests/debuginfo/packed-struct-with-destructor.rs index f923d36953c7..0c5725ca25cd 100644 --- a/tests/debuginfo/packed-struct-with-destructor.rs +++ b/tests/debuginfo/packed-struct-with-destructor.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -60,8 +61,6 @@ #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #[repr(packed)] struct Packed { diff --git a/tests/debuginfo/packed-struct.rs b/tests/debuginfo/packed-struct.rs index 2b3652fe8611..3bc39adee831 100644 --- a/tests/debuginfo/packed-struct.rs +++ b/tests/debuginfo/packed-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -46,8 +47,6 @@ // lldb-check:[...] 40 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #[repr(packed)] struct Packed { diff --git a/tests/debuginfo/recursive-enum.rs b/tests/debuginfo/recursive-enum.rs index b861e6d617c8..5fb339f54f39 100644 --- a/tests/debuginfo/recursive-enum.rs +++ b/tests/debuginfo/recursive-enum.rs @@ -1,14 +1,13 @@ //@ ignore-lldb //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run // Test whether compiling a recursive enum definition crashes debug info generation. The test case // is taken from issue #11083 and #135093. #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] pub struct Window<'a> { callbacks: WindowCallbacks<'a> diff --git a/tests/debuginfo/recursive-struct.rs b/tests/debuginfo/recursive-struct.rs index a97eb295eb43..5be909928480 100644 --- a/tests/debuginfo/recursive-struct.rs +++ b/tests/debuginfo/recursive-struct.rs @@ -1,6 +1,7 @@ //@ ignore-lldb //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run @@ -58,8 +59,6 @@ // gdb-command:continue #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::Opt::{Empty, Val}; use std::boxed::Box as B; diff --git a/tests/debuginfo/reference-debuginfo.rs b/tests/debuginfo/reference-debuginfo.rs index 773c3ae4bc36..242da1dd6541 100644 --- a/tests/debuginfo/reference-debuginfo.rs +++ b/tests/debuginfo/reference-debuginfo.rs @@ -3,6 +3,7 @@ // and leaves codegen to create a ladder of allocations so as `*a == b`. // //@ compile-flags:-g -Zmir-enable-passes=+ReferencePropagation,-ConstDebugInfo +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -106,8 +107,6 @@ // lldb-check:[...] 3.5 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(f16)] fn main() { diff --git a/tests/debuginfo/self-in-default-method.rs b/tests/debuginfo/self-in-default-method.rs index 02fc01d96eb3..4297129e0cf8 100644 --- a/tests/debuginfo/self-in-default-method.rs +++ b/tests/debuginfo/self-in-default-method.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -99,9 +100,6 @@ // lldb-check:[...] -10 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Copy, Clone)] struct Struct { x: isize diff --git a/tests/debuginfo/self-in-generic-default-method.rs b/tests/debuginfo/self-in-generic-default-method.rs index 65018e549ee0..e7ffa05f4188 100644 --- a/tests/debuginfo/self-in-generic-default-method.rs +++ b/tests/debuginfo/self-in-generic-default-method.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -99,9 +100,6 @@ // lldb-check:[...] -10.5 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - #[derive(Copy, Clone)] struct Struct { x: isize diff --git a/tests/debuginfo/shadowed-argument.rs b/tests/debuginfo/shadowed-argument.rs index 3a575b4addfd..3a0f0ad17a81 100644 --- a/tests/debuginfo/shadowed-argument.rs +++ b/tests/debuginfo/shadowed-argument.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -46,9 +47,6 @@ // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn a_function(x: bool, y: bool) { zzz(); // #break sentinel(); diff --git a/tests/debuginfo/shadowed-variable.rs b/tests/debuginfo/shadowed-variable.rs index 752e4c233f12..6a658a7c4943 100644 --- a/tests/debuginfo/shadowed-variable.rs +++ b/tests/debuginfo/shadowed-variable.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -68,9 +69,6 @@ // lldb-check:[...] 20 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let x = false; let y = true; diff --git a/tests/debuginfo/simd.rs b/tests/debuginfo/simd.rs index 12675a71a570..43cd7130b252 100644 --- a/tests/debuginfo/simd.rs +++ b/tests/debuginfo/simd.rs @@ -7,6 +7,7 @@ //@ ignore-s390x //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run // gdb-command:print vi8x16 @@ -35,8 +36,6 @@ // gdb-command:continue #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(repr_simd)] #[repr(simd)] diff --git a/tests/debuginfo/simple-lexical-scope.rs b/tests/debuginfo/simple-lexical-scope.rs index 6008489bd65d..64afcf8d61dc 100644 --- a/tests/debuginfo/simple-lexical-scope.rs +++ b/tests/debuginfo/simple-lexical-scope.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -66,9 +67,6 @@ // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - fn main() { let x = false; diff --git a/tests/debuginfo/simple-struct.rs b/tests/debuginfo/simple-struct.rs index bb6b2b798102..da09a8a3ce02 100644 --- a/tests/debuginfo/simple-struct.rs +++ b/tests/debuginfo/simple-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags: -g -Zmir-enable-passes=-CheckAlignment +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -84,8 +85,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct NoPadding16 { x: u16, diff --git a/tests/debuginfo/simple-tuple.rs b/tests/debuginfo/simple-tuple.rs index 82467ef3bcf2..f086472d7256 100644 --- a/tests/debuginfo/simple-tuple.rs +++ b/tests/debuginfo/simple-tuple.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -121,8 +122,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] static mut NO_PADDING_8: (i8, u8) = (-50, 50); static mut NO_PADDING_16: (i16, i16, u16) = (-1, 2, 3); diff --git a/tests/debuginfo/static-method-on-struct-and-enum.rs b/tests/debuginfo/static-method-on-struct-and-enum.rs index b487512a52f1..2a3502712de1 100644 --- a/tests/debuginfo/static-method-on-struct-and-enum.rs +++ b/tests/debuginfo/static-method-on-struct-and-enum.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -41,9 +42,6 @@ // lldb-check:[...] 5 // lldb-command:continue -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - struct Struct { x: isize } diff --git a/tests/debuginfo/strings-and-strs.rs b/tests/debuginfo/strings-and-strs.rs index 7d550408bec3..392cf697e110 100644 --- a/tests/debuginfo/strings-and-strs.rs +++ b/tests/debuginfo/strings-and-strs.rs @@ -2,6 +2,7 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== // gdb-command:run @@ -40,8 +41,6 @@ #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] pub struct Foo<'a> { inner: &'a str, diff --git a/tests/debuginfo/struct-in-enum.rs b/tests/debuginfo/struct-in-enum.rs index bc2c59fe4aa9..c5a7fb95e1e5 100644 --- a/tests/debuginfo/struct-in-enum.rs +++ b/tests/debuginfo/struct-in-enum.rs @@ -1,6 +1,7 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -30,8 +31,6 @@ // lldb-check:[...] TheOnlyCase(Struct { x: 123, y: 456, z: 789 }) #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::Regular::{Case1, Case2}; use self::Univariant::TheOnlyCase; diff --git a/tests/debuginfo/struct-in-struct.rs b/tests/debuginfo/struct-in-struct.rs index 3cf48470391b..c818df31b4b1 100644 --- a/tests/debuginfo/struct-in-struct.rs +++ b/tests/debuginfo/struct-in-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -43,8 +44,6 @@ // lldb-check:[...] { x = { x = 25 } y = { x = { x = 26 y = 27 } y = { x = 28 y = 29 } z = { x = 30 y = 31 } } z = { x = { x = { x = 32 } } } } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct Simple { x: i32 diff --git a/tests/debuginfo/struct-namespace.rs b/tests/debuginfo/struct-namespace.rs index 957884191003..d56c84c4f13b 100644 --- a/tests/debuginfo/struct-namespace.rs +++ b/tests/debuginfo/struct-namespace.rs @@ -1,5 +1,6 @@ //@ ignore-gdb //@ compile-flags:-g +//@ disable-gdb-pretty-printers // Check that structs get placed in the correct namespace @@ -16,8 +17,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct Struct1 { a: u32, diff --git a/tests/debuginfo/struct-style-enum.rs b/tests/debuginfo/struct-style-enum.rs index cea9f3def8bc..1f28fe4fea15 100644 --- a/tests/debuginfo/struct-style-enum.rs +++ b/tests/debuginfo/struct-style-enum.rs @@ -1,5 +1,6 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -36,8 +37,6 @@ // lldb-check:(struct_style_enum::Univariant) univariant = { value = { a = -1 } } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::Regular::{Case1, Case2, Case3}; use self::Univariant::TheOnlyCase; diff --git a/tests/debuginfo/struct-with-destructor.rs b/tests/debuginfo/struct-with-destructor.rs index c159824980a2..4d2ce8ff79db 100644 --- a/tests/debuginfo/struct-with-destructor.rs +++ b/tests/debuginfo/struct-with-destructor.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -32,8 +33,6 @@ // lldb-check:[...] { a = { a = { x = 7890 y = 9870 } } } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct NoDestructor { x: i32, diff --git a/tests/debuginfo/trait-pointers.rs b/tests/debuginfo/trait-pointers.rs index 71da71b897ad..5cdefe94e507 100644 --- a/tests/debuginfo/trait-pointers.rs +++ b/tests/debuginfo/trait-pointers.rs @@ -1,10 +1,9 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run // lldb-command:run #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] trait Trait { fn method(&self) -> isize { 0 } diff --git a/tests/debuginfo/tuple-in-struct.rs b/tests/debuginfo/tuple-in-struct.rs index a74d6203f5f5..bef96fad50c6 100644 --- a/tests/debuginfo/tuple-in-struct.rs +++ b/tests/debuginfo/tuple-in-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // gdb-command:run @@ -28,8 +29,6 @@ // gdb-check:$10 = tuple_in_struct::MixedPadding {x: ((40, 41, 42), (43, 44)), y: (45, 46, 47, 48)} #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct NoPadding1 { x: (i32, i32), diff --git a/tests/debuginfo/tuple-in-tuple.rs b/tests/debuginfo/tuple-in-tuple.rs index d4388095ad72..7bf97764c5c7 100644 --- a/tests/debuginfo/tuple-in-tuple.rs +++ b/tests/debuginfo/tuple-in-tuple.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -111,8 +112,6 @@ // cdb-check:[...][1] : 22 [Type: [...]] #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] fn main() { let no_padding1: ((u32, u32), u32, u32) = ((0, 1), 2, 3); diff --git a/tests/debuginfo/tuple-struct.rs b/tests/debuginfo/tuple-struct.rs index 0110203a7c79..a1bdaf1f3bb3 100644 --- a/tests/debuginfo/tuple-struct.rs +++ b/tests/debuginfo/tuple-struct.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -50,9 +51,6 @@ // structs. -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - struct NoPadding16(u16, i16); struct NoPadding32(i32, f32, u32); struct NoPadding64(f64, i64, u64); diff --git a/tests/debuginfo/tuple-style-enum.rs b/tests/debuginfo/tuple-style-enum.rs index a759ad61c056..6113ccc10a1b 100644 --- a/tests/debuginfo/tuple-style-enum.rs +++ b/tests/debuginfo/tuple-style-enum.rs @@ -1,6 +1,7 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -37,8 +38,6 @@ // lldb-check:(tuple_style_enum::Univariant) univariant = { value = { 0 = -1 } } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] use self::Regular::{Case1, Case2, Case3}; use self::Univariant::TheOnlyCase; diff --git a/tests/debuginfo/type-names.rs b/tests/debuginfo/type-names.rs index ac61fef48fe1..ecf7c597c0c0 100644 --- a/tests/debuginfo/type-names.rs +++ b/tests/debuginfo/type-names.rs @@ -6,6 +6,7 @@ //@ min-gdb-version: 9.2 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS ================================================================================== @@ -271,8 +272,6 @@ // cdb-check:struct type_names::mod1::extern$0::ForeignType2 * foreign2 = [...] #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] #![feature(extern_types)] use std::marker::PhantomData; diff --git a/tests/debuginfo/union-smoke.rs b/tests/debuginfo/union-smoke.rs index 6043240069e3..bd253794bd85 100644 --- a/tests/debuginfo/union-smoke.rs +++ b/tests/debuginfo/union-smoke.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -18,8 +19,6 @@ // lldb-check:[...] { a = { 0 = '\x01' 1 = '\x01' } b = 257 } #![allow(unused)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] union U { a: (u8, u8), diff --git a/tests/debuginfo/unique-enum.rs b/tests/debuginfo/unique-enum.rs index 230429278aa5..e5a9c5501356 100644 --- a/tests/debuginfo/unique-enum.rs +++ b/tests/debuginfo/unique-enum.rs @@ -1,6 +1,7 @@ //@ min-lldb-version: 1800 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -30,8 +31,6 @@ // lldb-check:(unique_enum::Univariant) *univariant = { value = { 0 = 123234 } } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when diff --git a/tests/debuginfo/unreachable-locals.rs b/tests/debuginfo/unreachable-locals.rs index d4416387e0b9..4d3f01fe423b 100644 --- a/tests/debuginfo/unreachable-locals.rs +++ b/tests/debuginfo/unreachable-locals.rs @@ -1,8 +1,7 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] // No need to actually run the debugger, just make sure that the compiler can // handle locals in unreachable code. diff --git a/tests/debuginfo/unsized.rs b/tests/debuginfo/unsized.rs index edd9f5af557d..e34eaaaacb97 100644 --- a/tests/debuginfo/unsized.rs +++ b/tests/debuginfo/unsized.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers //@ ignore-gdb-version: 13.1 - 99.0 // ^ https://sourceware.org/bugzilla/show_bug.cgi?id=30330 @@ -41,9 +42,6 @@ // cdb-check:[+0x000] pointer : 0x[...] [Type: unsized::Foo > *] // cdb-check:[...] vtable : 0x[...] [Type: unsigned [...]int[...] (*)[4]] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] - struct Foo { value: T, } diff --git a/tests/debuginfo/var-captured-in-nested-closure.rs b/tests/debuginfo/var-captured-in-nested-closure.rs index 4e8700015ba6..1795a352802f 100644 --- a/tests/debuginfo/var-captured-in-nested-closure.rs +++ b/tests/debuginfo/var-captured-in-nested-closure.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -115,8 +116,6 @@ // cdb-check:closure_local : 8 [Type: [...]] #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct Struct { a: isize, diff --git a/tests/debuginfo/var-captured-in-sendable-closure.rs b/tests/debuginfo/var-captured-in-sendable-closure.rs index cbb09daeb5f7..2b0d4bb430a1 100644 --- a/tests/debuginfo/var-captured-in-sendable-closure.rs +++ b/tests/debuginfo/var-captured-in-sendable-closure.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -28,8 +29,6 @@ // lldb-check:[...] 5 #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct Struct { a: isize, diff --git a/tests/debuginfo/var-captured-in-stack-closure.rs b/tests/debuginfo/var-captured-in-stack-closure.rs index 0f84ea57b007..7fda71c2297b 100644 --- a/tests/debuginfo/var-captured-in-stack-closure.rs +++ b/tests/debuginfo/var-captured-in-stack-closure.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -100,8 +101,6 @@ // cdb-check:owned : 0x[...] : 6 [Type: [...] *] #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct Struct { a: isize, diff --git a/tests/debuginfo/vec-slices.rs b/tests/debuginfo/vec-slices.rs index 2b4d624976ab..2a4e413612fc 100644 --- a/tests/debuginfo/vec-slices.rs +++ b/tests/debuginfo/vec-slices.rs @@ -2,6 +2,7 @@ // ^ test temporarily disabled as it fails under gdb 15 //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -71,8 +72,6 @@ // lldb-check:[...] size=2 { [0] = { x = 10 y = 11 z = 12 } [1] = { x = 13 y = 14 z = 15 } } #![allow(dead_code, unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] struct AStruct { x: i16, diff --git a/tests/debuginfo/vec.rs b/tests/debuginfo/vec.rs index 1093e38d8780..fd75e7005af5 100644 --- a/tests/debuginfo/vec.rs +++ b/tests/debuginfo/vec.rs @@ -1,4 +1,5 @@ //@ compile-flags:-g +//@ disable-gdb-pretty-printers // === GDB TESTS =================================================================================== @@ -16,8 +17,6 @@ // lldb-check:[...] { [0] = 1 [1] = 2 [2] = 3 } #![allow(unused_variables)] -#![feature(omit_gdb_pretty_printer_section)] -#![omit_gdb_pretty_printer_section] static mut VECT: [i32; 3] = [1, 2, 3]; diff --git a/tests/ui/attributes/malformed-attrs.rs b/tests/ui/attributes/malformed-attrs.rs index 2a8b7b41e58f..0d5bf69d548c 100644 --- a/tests/ui/attributes/malformed-attrs.rs +++ b/tests/ui/attributes/malformed-attrs.rs @@ -20,13 +20,9 @@ #![feature(linkage)] #![feature(cfi_encoding, extern_types)] #![feature(patchable_function_entry)] -#![feature(omit_gdb_pretty_printer_section)] #![feature(fundamental)] -#![omit_gdb_pretty_printer_section = 1] -//~^ ERROR malformed `omit_gdb_pretty_printer_section` attribute input - #![windows_subsystem] //~^ ERROR malformed diff --git a/tests/ui/attributes/malformed-attrs.stderr b/tests/ui/attributes/malformed-attrs.stderr index 814a1e5f6919..1b51075b4e88 100644 --- a/tests/ui/attributes/malformed-attrs.stderr +++ b/tests/ui/attributes/malformed-attrs.stderr @@ -1,5 +1,5 @@ error[E0539]: malformed `cfg` attribute input - --> $DIR/malformed-attrs.rs:103:1 + --> $DIR/malformed-attrs.rs:99:1 | LL | #[cfg] | ^^^^^^ @@ -8,7 +8,7 @@ LL | #[cfg] | help: must be of the form: `#[cfg(predicate)]` error: malformed `cfg_attr` attribute input - --> $DIR/malformed-attrs.rs:105:1 + --> $DIR/malformed-attrs.rs:101:1 | LL | #[cfg_attr] | ^^^^^^^^^^^ @@ -20,49 +20,49 @@ LL | #[cfg_attr(condition, attribute, other_attribute, ...)] | ++++++++++++++++++++++++++++++++++++++++++++ error[E0463]: can't find crate for `wloop` - --> $DIR/malformed-attrs.rs:212:1 + --> $DIR/malformed-attrs.rs:208:1 | LL | extern crate wloop; | ^^^^^^^^^^^^^^^^^^^ can't find crate error: malformed `windows_subsystem` attribute input - --> $DIR/malformed-attrs.rs:30:1 + --> $DIR/malformed-attrs.rs:26:1 | LL | #![windows_subsystem] | ^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#![windows_subsystem = "windows|console"]` error: malformed `crate_name` attribute input - --> $DIR/malformed-attrs.rs:75:1 + --> $DIR/malformed-attrs.rs:71:1 | LL | #[crate_name] | ^^^^^^^^^^^^^ help: must be of the form: `#[crate_name = "name"]` error: malformed `no_sanitize` attribute input - --> $DIR/malformed-attrs.rs:93:1 + --> $DIR/malformed-attrs.rs:89:1 | LL | #[no_sanitize] | ^^^^^^^^^^^^^^ help: must be of the form: `#[no_sanitize(address, kcfi, memory, thread)]` error: malformed `instruction_set` attribute input - --> $DIR/malformed-attrs.rs:107:1 + --> $DIR/malformed-attrs.rs:103:1 | LL | #[instruction_set] | ^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[instruction_set(set)]` error: malformed `patchable_function_entry` attribute input - --> $DIR/malformed-attrs.rs:109:1 + --> $DIR/malformed-attrs.rs:105:1 | LL | #[patchable_function_entry] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[patchable_function_entry(prefix_nops = m, entry_nops = n)]` error: malformed `coroutine` attribute input - --> $DIR/malformed-attrs.rs:112:5 + --> $DIR/malformed-attrs.rs:108:5 | LL | #[coroutine = 63] || {} | ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[coroutine]` error: malformed `must_not_suspend` attribute input - --> $DIR/malformed-attrs.rs:133:1 + --> $DIR/malformed-attrs.rs:129:1 | LL | #[must_not_suspend()] | ^^^^^^^^^^^^^^^^^^^^^ @@ -77,67 +77,67 @@ LL + #[must_not_suspend] | error: malformed `cfi_encoding` attribute input - --> $DIR/malformed-attrs.rs:135:1 + --> $DIR/malformed-attrs.rs:131:1 | LL | #[cfi_encoding] | ^^^^^^^^^^^^^^^ help: must be of the form: `#[cfi_encoding = "encoding"]` error: malformed `linkage` attribute input - --> $DIR/malformed-attrs.rs:174:5 + --> $DIR/malformed-attrs.rs:170:5 | LL | #[linkage] | ^^^^^^^^^^ help: must be of the form: `#[linkage = "external|internal|..."]` error: malformed `allow` attribute input - --> $DIR/malformed-attrs.rs:179:1 + --> $DIR/malformed-attrs.rs:175:1 | LL | #[allow] | ^^^^^^^^ help: must be of the form: `#[allow(lint1, lint2, ..., /*opt*/ reason = "...")]` error: malformed `expect` attribute input - --> $DIR/malformed-attrs.rs:181:1 + --> $DIR/malformed-attrs.rs:177:1 | LL | #[expect] | ^^^^^^^^^ help: must be of the form: `#[expect(lint1, lint2, ..., /*opt*/ reason = "...")]` error: malformed `warn` attribute input - --> $DIR/malformed-attrs.rs:183:1 + --> $DIR/malformed-attrs.rs:179:1 | LL | #[warn] | ^^^^^^^ help: must be of the form: `#[warn(lint1, lint2, ..., /*opt*/ reason = "...")]` error: malformed `deny` attribute input - --> $DIR/malformed-attrs.rs:185:1 + --> $DIR/malformed-attrs.rs:181:1 | LL | #[deny] | ^^^^^^^ help: must be of the form: `#[deny(lint1, lint2, ..., /*opt*/ reason = "...")]` error: malformed `forbid` attribute input - --> $DIR/malformed-attrs.rs:187:1 + --> $DIR/malformed-attrs.rs:183:1 | LL | #[forbid] | ^^^^^^^^^ help: must be of the form: `#[forbid(lint1, lint2, ..., /*opt*/ reason = "...")]` error: malformed `debugger_visualizer` attribute input - --> $DIR/malformed-attrs.rs:189:1 + --> $DIR/malformed-attrs.rs:185:1 | LL | #[debugger_visualizer] | ^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[debugger_visualizer(natvis_file = "...", gdb_script_file = "...")]` error: malformed `thread_local` attribute input - --> $DIR/malformed-attrs.rs:204:1 + --> $DIR/malformed-attrs.rs:200:1 | LL | #[thread_local()] | ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[thread_local]` error: malformed `no_link` attribute input - --> $DIR/malformed-attrs.rs:208:1 + --> $DIR/malformed-attrs.rs:204:1 | LL | #[no_link()] | ^^^^^^^^^^^^ help: must be of the form: `#[no_link]` error: malformed `macro_export` attribute input - --> $DIR/malformed-attrs.rs:215:1 + --> $DIR/malformed-attrs.rs:211:1 | LL | #[macro_export = 18] | ^^^^^^^^^^^^^^^^^^^^ @@ -152,31 +152,31 @@ LL + #[macro_export] | error: malformed `allow_internal_unsafe` attribute input - --> $DIR/malformed-attrs.rs:217:1 + --> $DIR/malformed-attrs.rs:213:1 | LL | #[allow_internal_unsafe = 1] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[allow_internal_unsafe]` error: the `#[proc_macro]` attribute is only usable with crates of the `proc-macro` crate type - --> $DIR/malformed-attrs.rs:100:1 + --> $DIR/malformed-attrs.rs:96:1 | LL | #[proc_macro = 18] | ^^^^^^^^^^^^^^^^^^ error: the `#[proc_macro_attribute]` attribute is only usable with crates of the `proc-macro` crate type - --> $DIR/malformed-attrs.rs:117:1 + --> $DIR/malformed-attrs.rs:113:1 | LL | #[proc_macro_attribute = 19] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: the `#[proc_macro_derive]` attribute is only usable with crates of the `proc-macro` crate type - --> $DIR/malformed-attrs.rs:124:1 + --> $DIR/malformed-attrs.rs:120:1 | LL | #[proc_macro_derive] | ^^^^^^^^^^^^^^^^^^^^ error[E0658]: allow_internal_unsafe side-steps the unsafe_code lint - --> $DIR/malformed-attrs.rs:217:1 + --> $DIR/malformed-attrs.rs:213:1 | LL | #[allow_internal_unsafe = 1] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -185,7 +185,7 @@ LL | #[allow_internal_unsafe = 1] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error: valid forms for the attribute are `#[doc(hidden|inline|...)]` and `#[doc = "string"]` - --> $DIR/malformed-attrs.rs:44:1 + --> $DIR/malformed-attrs.rs:40:1 | LL | #[doc] | ^^^^^^ @@ -195,7 +195,7 @@ LL | #[doc] = note: `#[deny(ill_formed_attribute_input)]` on by default error: valid forms for the attribute are `#[doc(hidden|inline|...)]` and `#[doc = "string"]` - --> $DIR/malformed-attrs.rs:77:1 + --> $DIR/malformed-attrs.rs:73:1 | LL | #[doc] | ^^^^^^ @@ -204,7 +204,7 @@ LL | #[doc] = note: for more information, see issue #57571 error: attribute must be of the form `#[link(name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ wasm_import_module = "...", /*opt*/ import_name_type = "decorated|noprefix|undecorated")]` - --> $DIR/malformed-attrs.rs:84:1 + --> $DIR/malformed-attrs.rs:80:1 | LL | #[link] | ^^^^^^^ @@ -213,7 +213,7 @@ LL | #[link] = note: for more information, see issue #57571 error: invalid argument - --> $DIR/malformed-attrs.rs:189:1 + --> $DIR/malformed-attrs.rs:185:1 | LL | #[debugger_visualizer] | ^^^^^^^^^^^^^^^^^^^^^^ @@ -222,35 +222,26 @@ LL | #[debugger_visualizer] = note: OR = note: expected: `gdb_script_file = "..."` -error[E0565]: malformed `omit_gdb_pretty_printer_section` attribute input - --> $DIR/malformed-attrs.rs:27:1 - | -LL | #![omit_gdb_pretty_printer_section = 1] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---^ - | | | - | | didn't expect any arguments here - | help: must be of the form: `#[omit_gdb_pretty_printer_section]` - error[E0539]: malformed `export_name` attribute input - --> $DIR/malformed-attrs.rs:33:1 + --> $DIR/malformed-attrs.rs:29:1 | LL | #[unsafe(export_name)] | ^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[export_name = "name"]` error: `rustc_allow_const_fn_unstable` expects a list of feature names - --> $DIR/malformed-attrs.rs:35:1 + --> $DIR/malformed-attrs.rs:31:1 | LL | #[rustc_allow_const_fn_unstable] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `allow_internal_unstable` expects a list of feature names - --> $DIR/malformed-attrs.rs:38:1 + --> $DIR/malformed-attrs.rs:34:1 | LL | #[allow_internal_unstable] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0539]: malformed `rustc_confusables` attribute input - --> $DIR/malformed-attrs.rs:40:1 + --> $DIR/malformed-attrs.rs:36:1 | LL | #[rustc_confusables] | ^^^^^^^^^^^^^^^^^^^^ @@ -259,7 +250,7 @@ LL | #[rustc_confusables] | help: must be of the form: `#[rustc_confusables("name1", "name2", ...)]` error[E0539]: malformed `deprecated` attribute input - --> $DIR/malformed-attrs.rs:42:1 + --> $DIR/malformed-attrs.rs:38:1 | LL | #[deprecated = 5] | ^^^^^^^^^^^^^^^-^ @@ -279,13 +270,13 @@ LL + #[deprecated] | error[E0539]: malformed `rustc_macro_transparency` attribute input - --> $DIR/malformed-attrs.rs:47:1 + --> $DIR/malformed-attrs.rs:43:1 | LL | #[rustc_macro_transparency] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[rustc_macro_transparency = "transparent|semitransparent|opaque"]` error[E0539]: malformed `repr` attribute input - --> $DIR/malformed-attrs.rs:49:1 + --> $DIR/malformed-attrs.rs:45:1 | LL | #[repr] | ^^^^^^^ @@ -294,7 +285,7 @@ LL | #[repr] | help: must be of the form: `#[repr(C | Rust | align(...) | packed(...) | | transparent)]` error[E0565]: malformed `rustc_as_ptr` attribute input - --> $DIR/malformed-attrs.rs:52:1 + --> $DIR/malformed-attrs.rs:48:1 | LL | #[rustc_as_ptr = 5] | ^^^^^^^^^^^^^^^---^ @@ -303,7 +294,7 @@ LL | #[rustc_as_ptr = 5] | help: must be of the form: `#[rustc_as_ptr]` error[E0539]: malformed `rustc_align` attribute input - --> $DIR/malformed-attrs.rs:57:1 + --> $DIR/malformed-attrs.rs:53:1 | LL | #[rustc_align] | ^^^^^^^^^^^^^^ @@ -312,7 +303,7 @@ LL | #[rustc_align] | help: must be of the form: `#[rustc_align()]` error[E0539]: malformed `optimize` attribute input - --> $DIR/malformed-attrs.rs:59:1 + --> $DIR/malformed-attrs.rs:55:1 | LL | #[optimize] | ^^^^^^^^^^^ @@ -321,7 +312,7 @@ LL | #[optimize] | help: must be of the form: `#[optimize(size|speed|none)]` error[E0565]: malformed `cold` attribute input - --> $DIR/malformed-attrs.rs:61:1 + --> $DIR/malformed-attrs.rs:57:1 | LL | #[cold = 1] | ^^^^^^^---^ @@ -330,13 +321,13 @@ LL | #[cold = 1] | help: must be of the form: `#[cold]` error: valid forms for the attribute are `#[must_use = "reason"]` and `#[must_use]` - --> $DIR/malformed-attrs.rs:63:1 + --> $DIR/malformed-attrs.rs:59:1 | LL | #[must_use()] | ^^^^^^^^^^^^^ error[E0565]: malformed `no_mangle` attribute input - --> $DIR/malformed-attrs.rs:65:1 + --> $DIR/malformed-attrs.rs:61:1 | LL | #[no_mangle = 1] | ^^^^^^^^^^^^---^ @@ -345,7 +336,7 @@ LL | #[no_mangle = 1] | help: must be of the form: `#[no_mangle]` error[E0565]: malformed `naked` attribute input - --> $DIR/malformed-attrs.rs:67:1 + --> $DIR/malformed-attrs.rs:63:1 | LL | #[unsafe(naked())] | ^^^^^^^^^^^^^^--^^ @@ -354,7 +345,7 @@ LL | #[unsafe(naked())] | help: must be of the form: `#[naked]` error[E0565]: malformed `track_caller` attribute input - --> $DIR/malformed-attrs.rs:69:1 + --> $DIR/malformed-attrs.rs:65:1 | LL | #[track_caller()] | ^^^^^^^^^^^^^^--^ @@ -363,13 +354,13 @@ LL | #[track_caller()] | help: must be of the form: `#[track_caller]` error[E0539]: malformed `export_name` attribute input - --> $DIR/malformed-attrs.rs:71:1 + --> $DIR/malformed-attrs.rs:67:1 | LL | #[export_name()] | ^^^^^^^^^^^^^^^^ help: must be of the form: `#[export_name = "name"]` error[E0805]: malformed `used` attribute input - --> $DIR/malformed-attrs.rs:73:1 + --> $DIR/malformed-attrs.rs:69:1 | LL | #[used()] | ^^^^^^--^ @@ -385,7 +376,7 @@ LL + #[used] | error[E0539]: malformed `target_feature` attribute input - --> $DIR/malformed-attrs.rs:80:1 + --> $DIR/malformed-attrs.rs:76:1 | LL | #[target_feature] | ^^^^^^^^^^^^^^^^^ @@ -394,7 +385,7 @@ LL | #[target_feature] | help: must be of the form: `#[target_feature(enable = "feat1, feat2")]` error[E0565]: malformed `export_stable` attribute input - --> $DIR/malformed-attrs.rs:82:1 + --> $DIR/malformed-attrs.rs:78:1 | LL | #[export_stable = 1] | ^^^^^^^^^^^^^^^^---^ @@ -403,19 +394,19 @@ LL | #[export_stable = 1] | help: must be of the form: `#[export_stable]` error[E0539]: malformed `link_name` attribute input - --> $DIR/malformed-attrs.rs:87:1 + --> $DIR/malformed-attrs.rs:83:1 | LL | #[link_name] | ^^^^^^^^^^^^ help: must be of the form: `#[link_name = "name"]` error[E0539]: malformed `link_section` attribute input - --> $DIR/malformed-attrs.rs:89:1 + --> $DIR/malformed-attrs.rs:85:1 | LL | #[link_section] | ^^^^^^^^^^^^^^^ help: must be of the form: `#[link_section = "name"]` error[E0539]: malformed `coverage` attribute input - --> $DIR/malformed-attrs.rs:91:1 + --> $DIR/malformed-attrs.rs:87:1 | LL | #[coverage] | ^^^^^^^^^^^ this attribute is only valid with either `on` or `off` as an argument @@ -428,7 +419,7 @@ LL | #[coverage(on)] | ++++ error[E0565]: malformed `no_implicit_prelude` attribute input - --> $DIR/malformed-attrs.rs:98:1 + --> $DIR/malformed-attrs.rs:94:1 | LL | #[no_implicit_prelude = 23] | ^^^^^^^^^^^^^^^^^^^^^^----^ @@ -437,7 +428,7 @@ LL | #[no_implicit_prelude = 23] | help: must be of the form: `#[no_implicit_prelude]` error[E0565]: malformed `proc_macro` attribute input - --> $DIR/malformed-attrs.rs:100:1 + --> $DIR/malformed-attrs.rs:96:1 | LL | #[proc_macro = 18] | ^^^^^^^^^^^^^----^ @@ -446,7 +437,7 @@ LL | #[proc_macro = 18] | help: must be of the form: `#[proc_macro]` error[E0565]: malformed `proc_macro_attribute` attribute input - --> $DIR/malformed-attrs.rs:117:1 + --> $DIR/malformed-attrs.rs:113:1 | LL | #[proc_macro_attribute = 19] | ^^^^^^^^^^^^^^^^^^^^^^^----^ @@ -455,7 +446,7 @@ LL | #[proc_macro_attribute = 19] | help: must be of the form: `#[proc_macro_attribute]` error[E0539]: malformed `must_use` attribute input - --> $DIR/malformed-attrs.rs:120:1 + --> $DIR/malformed-attrs.rs:116:1 | LL | #[must_use = 1] | ^^^^^^^^^^^^^-^ @@ -472,7 +463,7 @@ LL + #[must_use] | error[E0539]: malformed `proc_macro_derive` attribute input - --> $DIR/malformed-attrs.rs:124:1 + --> $DIR/malformed-attrs.rs:120:1 | LL | #[proc_macro_derive] | ^^^^^^^^^^^^^^^^^^^^ @@ -481,7 +472,7 @@ LL | #[proc_macro_derive] | help: must be of the form: `#[proc_macro_derive(TraitName, /*opt*/ attributes(name1, name2, ...))]` error[E0539]: malformed `rustc_layout_scalar_valid_range_start` attribute input - --> $DIR/malformed-attrs.rs:129:1 + --> $DIR/malformed-attrs.rs:125:1 | LL | #[rustc_layout_scalar_valid_range_start] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -490,7 +481,7 @@ LL | #[rustc_layout_scalar_valid_range_start] | help: must be of the form: `#[rustc_layout_scalar_valid_range_start(start)]` error[E0539]: malformed `rustc_layout_scalar_valid_range_end` attribute input - --> $DIR/malformed-attrs.rs:131:1 + --> $DIR/malformed-attrs.rs:127:1 | LL | #[rustc_layout_scalar_valid_range_end] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -499,7 +490,7 @@ LL | #[rustc_layout_scalar_valid_range_end] | help: must be of the form: `#[rustc_layout_scalar_valid_range_end(end)]` error[E0565]: malformed `marker` attribute input - --> $DIR/malformed-attrs.rs:156:1 + --> $DIR/malformed-attrs.rs:152:1 | LL | #[marker = 3] | ^^^^^^^^^---^ @@ -508,7 +499,7 @@ LL | #[marker = 3] | help: must be of the form: `#[marker]` error[E0565]: malformed `fundamental` attribute input - --> $DIR/malformed-attrs.rs:158:1 + --> $DIR/malformed-attrs.rs:154:1 | LL | #[fundamental()] | ^^^^^^^^^^^^^--^ @@ -517,7 +508,7 @@ LL | #[fundamental()] | help: must be of the form: `#[fundamental]` error[E0565]: malformed `ffi_pure` attribute input - --> $DIR/malformed-attrs.rs:166:5 + --> $DIR/malformed-attrs.rs:162:5 | LL | #[unsafe(ffi_pure = 1)] | ^^^^^^^^^^^^^^^^^^---^^ @@ -526,7 +517,7 @@ LL | #[unsafe(ffi_pure = 1)] | help: must be of the form: `#[ffi_pure]` error[E0539]: malformed `link_ordinal` attribute input - --> $DIR/malformed-attrs.rs:168:5 + --> $DIR/malformed-attrs.rs:164:5 | LL | #[link_ordinal] | ^^^^^^^^^^^^^^^ @@ -535,7 +526,7 @@ LL | #[link_ordinal] | help: must be of the form: `#[link_ordinal(ordinal)]` error[E0565]: malformed `ffi_const` attribute input - --> $DIR/malformed-attrs.rs:172:5 + --> $DIR/malformed-attrs.rs:168:5 | LL | #[unsafe(ffi_const = 1)] | ^^^^^^^^^^^^^^^^^^^---^^ @@ -544,7 +535,7 @@ LL | #[unsafe(ffi_const = 1)] | help: must be of the form: `#[ffi_const]` error[E0565]: malformed `automatically_derived` attribute input - --> $DIR/malformed-attrs.rs:192:1 + --> $DIR/malformed-attrs.rs:188:1 | LL | #[automatically_derived = 18] | ^^^^^^^^^^^^^^^^^^^^^^^^----^ @@ -553,7 +544,7 @@ LL | #[automatically_derived = 18] | help: must be of the form: `#[automatically_derived]` error[E0565]: malformed `non_exhaustive` attribute input - --> $DIR/malformed-attrs.rs:198:1 + --> $DIR/malformed-attrs.rs:194:1 | LL | #[non_exhaustive = 1] | ^^^^^^^^^^^^^^^^^---^ @@ -562,13 +553,13 @@ LL | #[non_exhaustive = 1] | help: must be of the form: `#[non_exhaustive]` error: valid forms for the attribute are `#[macro_use(name1, name2, ...)]` and `#[macro_use]` - --> $DIR/malformed-attrs.rs:210:1 + --> $DIR/malformed-attrs.rs:206:1 | LL | #[macro_use = 1] | ^^^^^^^^^^^^^^^^ error[E0565]: malformed `type_const` attribute input - --> $DIR/malformed-attrs.rs:144:5 + --> $DIR/malformed-attrs.rs:140:5 | LL | #[type_const = 1] | ^^^^^^^^^^^^^---^ @@ -577,7 +568,7 @@ LL | #[type_const = 1] | help: must be of the form: `#[type_const]` error: attribute should be applied to `const fn` - --> $DIR/malformed-attrs.rs:35:1 + --> $DIR/malformed-attrs.rs:31:1 | LL | #[rustc_allow_const_fn_unstable] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -589,19 +580,19 @@ LL | | } | |_- not a `const fn` error: `#[repr(align(...))]` is not supported on function items - --> $DIR/malformed-attrs.rs:49:1 + --> $DIR/malformed-attrs.rs:45:1 | LL | #[repr] | ^^^^^^^ | help: use `#[rustc_align(...)]` instead - --> $DIR/malformed-attrs.rs:49:1 + --> $DIR/malformed-attrs.rs:45:1 | LL | #[repr] | ^^^^^^^ warning: `#[diagnostic::do_not_recommend]` does not expect any arguments - --> $DIR/malformed-attrs.rs:150:1 + --> $DIR/malformed-attrs.rs:146:1 | LL | #[diagnostic::do_not_recommend()] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -609,7 +600,7 @@ LL | #[diagnostic::do_not_recommend()] = note: `#[warn(malformed_diagnostic_attributes)]` on by default warning: missing options for `on_unimplemented` attribute - --> $DIR/malformed-attrs.rs:139:1 + --> $DIR/malformed-attrs.rs:135:1 | LL | #[diagnostic::on_unimplemented] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -617,7 +608,7 @@ LL | #[diagnostic::on_unimplemented] = help: at least one of the `message`, `note` and `label` options are expected warning: malformed `on_unimplemented` attribute - --> $DIR/malformed-attrs.rs:141:1 + --> $DIR/malformed-attrs.rs:137:1 | LL | #[diagnostic::on_unimplemented = 1] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ invalid option found here @@ -625,7 +616,7 @@ LL | #[diagnostic::on_unimplemented = 1] = help: only `message`, `note` and `label` are allowed as options error: valid forms for the attribute are `#[inline(always|never)]` and `#[inline]` - --> $DIR/malformed-attrs.rs:54:1 + --> $DIR/malformed-attrs.rs:50:1 | LL | #[inline = 5] | ^^^^^^^^^^^^^ @@ -634,7 +625,7 @@ LL | #[inline = 5] = note: for more information, see issue #57571 error: valid forms for the attribute are `#[ignore = "reason"]` and `#[ignore]` - --> $DIR/malformed-attrs.rs:95:1 + --> $DIR/malformed-attrs.rs:91:1 | LL | #[ignore()] | ^^^^^^^^^^^ @@ -643,7 +634,7 @@ LL | #[ignore()] = note: for more information, see issue #57571 error: valid forms for the attribute are `#[ignore = "reason"]` and `#[ignore]` - --> $DIR/malformed-attrs.rs:224:1 + --> $DIR/malformed-attrs.rs:220:1 | LL | #[ignore = 1] | ^^^^^^^^^^^^^ @@ -652,7 +643,7 @@ LL | #[ignore = 1] = note: for more information, see issue #57571 error[E0308]: mismatched types - --> $DIR/malformed-attrs.rs:112:23 + --> $DIR/malformed-attrs.rs:108:23 | LL | fn test() { | - help: a return type might be missing here: `-> _` @@ -660,9 +651,9 @@ LL | #[coroutine = 63] || {} | ^^^^^ expected `()`, found coroutine | = note: expected unit type `()` - found coroutine `{coroutine@$DIR/malformed-attrs.rs:112:23: 112:25}` + found coroutine `{coroutine@$DIR/malformed-attrs.rs:108:23: 108:25}` -error: aborting due to 75 previous errors; 3 warnings emitted +error: aborting due to 74 previous errors; 3 warnings emitted Some errors have detailed explanations: E0308, E0463, E0539, E0565, E0658, E0805. For more information about an error, try `rustc --explain E0308`. diff --git a/tests/ui/feature-gates/feature-gate-omit-gdb-pretty-printer-section.rs b/tests/ui/feature-gates/feature-gate-omit-gdb-pretty-printer-section.rs deleted file mode 100644 index 66bf7973832e..000000000000 --- a/tests/ui/feature-gates/feature-gate-omit-gdb-pretty-printer-section.rs +++ /dev/null @@ -1,2 +0,0 @@ -#[omit_gdb_pretty_printer_section] //~ ERROR the `#[omit_gdb_pretty_printer_section]` attribute is -fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-omit-gdb-pretty-printer-section.stderr b/tests/ui/feature-gates/feature-gate-omit-gdb-pretty-printer-section.stderr deleted file mode 100644 index 2e1d27fb7764..000000000000 --- a/tests/ui/feature-gates/feature-gate-omit-gdb-pretty-printer-section.stderr +++ /dev/null @@ -1,12 +0,0 @@ -error[E0658]: the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite - --> $DIR/feature-gate-omit-gdb-pretty-printer-section.rs:1:1 - | -LL | #[omit_gdb_pretty_printer_section] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = help: add `#![feature(omit_gdb_pretty_printer_section)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0658`. From 4c7c9de8acc7abc1788d6134716f3aeff8616300 Mon Sep 17 00:00:00 2001 From: Nico Lehmann Date: Fri, 1 Aug 2025 13:55:18 -0700 Subject: [PATCH 0334/1134] Fix safety comment for new_unchecked in niche_types --- library/core/src/num/niche_types.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/core/src/num/niche_types.rs b/library/core/src/num/niche_types.rs index b92561c9e356..d57b1d433e51 100644 --- a/library/core/src/num/niche_types.rs +++ b/library/core/src/num/niche_types.rs @@ -46,11 +46,11 @@ macro_rules! define_valid_range_type { /// primitive without checking whether its zero. /// /// # Safety - /// Immediate language UB if `val == 0`, as it violates the validity - /// invariant of this type. + /// Immediate language UB if `val` is not within the valid range for this + /// type, as it violates the validity invariant. #[inline] pub const unsafe fn new_unchecked(val: $int) -> Self { - // SAFETY: Caller promised that `val` is non-zero. + // SAFETY: Caller promised that `val` is within the valid range. unsafe { $name(val) } } From f516d4c9e341847d8f452adef68fe99cfdcfccc0 Mon Sep 17 00:00:00 2001 From: Mingwei Samuel Date: Fri, 25 Jul 2025 13:21:50 -0700 Subject: [PATCH 0335/1134] rustdoc font links only emit `crossorigin` when needed The `crossorigin` attribute may cause issues when the href is not actuall across origins. Specifically, the tag causes the browser to send a preflight OPTIONS request to the href even if it is same-origin. Some tempermental servers may reject all CORS preflect requests even if they're actually same-origin, which causes a CORS error and prevents the fonts from loading, even later on. This commit fixes that problem by not emitting `crossorigin` if the url looks like a domain-relative url. Co-authored-by: Guillaume Gomez --- src/librustdoc/html/layout.rs | 29 +++++++++++++++++++++++++ src/librustdoc/html/layout/tests.rs | 24 ++++++++++++++++++++ src/librustdoc/html/templates/page.html | 2 +- 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/librustdoc/html/layout/tests.rs diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index 1f92c521d46e..2782e8e0058c 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -8,6 +8,9 @@ use super::static_files::{STATIC_FILES, StaticFiles}; use crate::externalfiles::ExternalHtml; use crate::html::render::{StylePath, ensure_trailing_slash}; +#[cfg(test)] +mod tests; + pub(crate) struct Layout { pub(crate) logo: String, pub(crate) favicon: String, @@ -68,6 +71,13 @@ struct PageLayout<'a> { display_krate_version_extra: &'a str, } +impl PageLayout<'_> { + /// See [`may_remove_crossorigin`]. + fn static_root_path_may_remove_crossorigin(&self) -> bool { + may_remove_crossorigin(&self.static_root_path) + } +} + pub(crate) use crate::html::render::sidebar::filters; pub(crate) fn render( @@ -134,3 +144,22 @@ pub(crate) fn redirect(url: &str) -> String { "##, ) } + +/// Conservatively determines if `href` is relative to the current origin, +/// so that `crossorigin` may be safely removed from `` elements. +pub(crate) fn may_remove_crossorigin(href: &str) -> bool { + // Reject scheme-relative URLs (`//example.com/`). + if href.starts_with("//") { + return false; + } + // URL is interpreted as having a scheme iff: it starts with an ascii alpha, and only + // contains ascii alphanumeric or `+` `-` `.` up to the `:`. + // https://url.spec.whatwg.org/#url-parsing + let has_scheme = href.split_once(':').is_some_and(|(scheme, _rest)| { + let mut chars = scheme.chars(); + chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') + }); + // Reject anything with a scheme (`http:`, etc.). + !has_scheme +} diff --git a/src/librustdoc/html/layout/tests.rs b/src/librustdoc/html/layout/tests.rs new file mode 100644 index 000000000000..d4a19ee9abfd --- /dev/null +++ b/src/librustdoc/html/layout/tests.rs @@ -0,0 +1,24 @@ +#[test] +fn test_may_remove_crossorigin() { + use super::may_remove_crossorigin; + + assert!(may_remove_crossorigin("font.woff2")); + assert!(may_remove_crossorigin("/font.woff2")); + assert!(may_remove_crossorigin("./font.woff2")); + assert!(may_remove_crossorigin(":D/font.woff2")); + assert!(may_remove_crossorigin("../font.woff2")); + + assert!(!may_remove_crossorigin("//example.com/static.files")); + assert!(!may_remove_crossorigin("http://example.com/static.files")); + assert!(!may_remove_crossorigin("https://example.com/static.files")); + assert!(!may_remove_crossorigin("https://example.com:8080/static.files")); + + assert!(!may_remove_crossorigin("ftp://example.com/static.files")); + assert!(!may_remove_crossorigin("blob:http://example.com/static.files")); + assert!(!may_remove_crossorigin("javascript:alert('Hello, world!')")); + assert!(!may_remove_crossorigin("//./C:")); + assert!(!may_remove_crossorigin("file:////C:")); + assert!(!may_remove_crossorigin("file:///./C:")); + assert!(!may_remove_crossorigin("data:,Hello%2C%20World%21")); + assert!(!may_remove_crossorigin("hi...:hello")); +} diff --git a/src/librustdoc/html/templates/page.html b/src/librustdoc/html/templates/page.html index 7af99e7097c3..398436e3fe13 100644 --- a/src/librustdoc/html/templates/page.html +++ b/src/librustdoc/html/templates/page.html @@ -7,7 +7,7 @@ {# #} {{page.title}} {# #} {# #} {# #} From 066023e47c0c92e7edefd60831ce7d6f15f23750 Mon Sep 17 00:00:00 2001 From: stifskere Date: Sat, 2 Aug 2025 01:32:52 +0200 Subject: [PATCH 0336/1134] feat: implement `hash_map!` macro --- library/std/src/lib.rs | 2 ++ library/std/src/macros.rs | 74 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 77301d7228ea..fd06a3b540cd 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -294,6 +294,8 @@ #![feature(f128)] #![feature(ffi_const)] #![feature(formatting_options)] +#![feature(hash_map_internals)] +#![feature(hash_map_macro)] #![feature(if_let_guard)] #![feature(intra_doc_pointers)] #![feature(iter_advance_by)] diff --git a/library/std/src/macros.rs b/library/std/src/macros.rs index 25e2b7ea1370..254570ae9c83 100644 --- a/library/std/src/macros.rs +++ b/library/std/src/macros.rs @@ -379,3 +379,77 @@ macro_rules! dbg { ($($crate::dbg!($val)),+,) }; } + +#[doc(hidden)] +#[macro_export] +#[allow_internal_unstable(hash_map_internals)] +#[unstable(feature = "hash_map_internals", issue = "none")] +macro_rules! repetition_utils { + (@count $($tokens:tt),*) => {{ + [$($crate::repetition_utils!(@replace $tokens => ())),*].len() + }}; + + (@replace $x:tt => $y:tt) => { $y } +} + +/// Creates a [`HashMap`] containing the arguments. +/// +/// `hash_map!` allows specifying the entries that make +/// up the [`HashMap`] where the key and value are separated by a `=>`. +/// +/// The entries are separated by commas with a trailing comma being allowed. +/// +/// It is semantically equivalent to using repeated [`HashMap::insert`] +/// on a newly created hashmap. +/// +/// `hash_map!` will attempt to avoid repeated reallocations by +/// using [`HashMap::with_capacity`]. +/// +/// # Examples +/// +/// ```rust +/// #![feature(hash_map_macro)] +/// +/// let map = hash_map! { +/// "key" => "value", +/// "key1" => "value1" +/// }; +/// +/// assert_eq!(map.get("key"), Some(&"value")); +/// assert_eq!(map.get("key1"), Some(&"value1")); +/// assert!(map.get("brrrrrrooooommm").is_none()); +/// ``` +/// +/// And with a trailing comma +/// +///```rust +/// #![feature(hash_map_macro)] +/// +/// let map = hash_map! { +/// "key" => "value", // notice the , +/// }; +/// +/// assert_eq!(map.get("key"), Some(&"value")); +/// ``` +/// +/// The key and value are moved into the HashMap. +/// +/// [`HashMap`]: crate::collections::HashMap +/// [`HashMap::insert`]: crate::collections::HashMap::insert +/// [`HashMap::with_capacity`]: crate::collections::HashMap::with_capacity +#[macro_export] +#[allow_internal_unstable(hash_map_internals)] +#[unstable(feature = "hash_map_macro", issue = "144032")] +macro_rules! hash_map { + () => {{ + $crate::collections::HashMap::new() + }}; + + ( $( $key:expr => $value:expr ),* $(,)? ) => {{ + let mut map = $crate::collections::HashMap::with_capacity( + const { $crate::repetition_utils!(@count $($key),*) } + ); + $( map.insert($key, $value); )* + map + }} +} From 01d960f645b3f1e47a79ea925f9e04a5bfbbd769 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Sat, 2 Aug 2025 01:57:57 +0200 Subject: [PATCH 0337/1134] Optimize broken_links by 99.77% --- clippy_lints/src/doc/broken_link.rs | 76 ++++++++++++++--------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/clippy_lints/src/doc/broken_link.rs b/clippy_lints/src/doc/broken_link.rs index 4af10510023d..8878fa9180fe 100644 --- a/clippy_lints/src/doc/broken_link.rs +++ b/clippy_lints/src/doc/broken_link.rs @@ -19,52 +19,52 @@ pub fn check(cx: &LateContext<'_>, bl: &PullDownBrokenLink<'_>, doc: &str, fragm } fn warn_if_broken_link(cx: &LateContext<'_>, bl: &PullDownBrokenLink<'_>, doc: &str, fragments: &[DocFragment]) { - if let Some((span, _)) = source_span_for_markdown_range(cx.tcx, doc, &bl.span, fragments) { - let mut len = 0; + let mut len = 0; - // grab raw link data - let (_, raw_link) = doc.split_at(bl.span.start); + // grab raw link data + let (_, raw_link) = doc.split_at(bl.span.start); - // strip off link text part - let raw_link = match raw_link.split_once(']') { - None => return, - Some((prefix, suffix)) => { - len += prefix.len() + 1; - suffix - }, - }; + // strip off link text part + let raw_link = match raw_link.split_once(']') { + None => return, + Some((prefix, suffix)) => { + len += prefix.len() + 1; + suffix + }, + }; - let raw_link = match raw_link.split_once('(') { - None => return, - Some((prefix, suffix)) => { - if !prefix.is_empty() { - // there is text between ']' and '(' chars, so it is not a valid link - return; - } - len += prefix.len() + 1; - suffix - }, - }; - - if raw_link.starts_with("(http") { - // reduce chances of false positive reports - // by limiting this checking only to http/https links. - return; - } - - for c in raw_link.chars() { - if c == ')' { - // it is a valid link + let raw_link = match raw_link.split_once('(') { + None => return, + Some((prefix, suffix)) => { + if !prefix.is_empty() { + // there is text between ']' and '(' chars, so it is not a valid link return; } + len += prefix.len() + 1; + suffix + }, + }; - if c == '\n' { - report_broken_link(cx, span, len); - break; - } + if raw_link.starts_with("(http") { + // reduce chances of false positive reports + // by limiting this checking only to http/https links. + return; + } - len += 1; + for c in raw_link.chars() { + if c == ')' { + // it is a valid link + return; } + + if c == '\n' + && let Some((span, _)) = source_span_for_markdown_range(cx.tcx, doc, &bl.span, fragments) + { + report_broken_link(cx, span, len); + break; + } + + len += 1; } } From a067c6a3c6ac4db7652e1722acf2648ef65b0229 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Sun, 1 Jun 2025 12:51:17 +0200 Subject: [PATCH 0338/1134] refactor `unreachable/expr_cast.rs` test --- tests/ui/reachable/expr_cast.rs | 15 +++++++-------- tests/ui/reachable/expr_cast.stderr | 26 ++++++++++++++------------ 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/tests/ui/reachable/expr_cast.rs b/tests/ui/reachable/expr_cast.rs index e8e477ea4f68..58ebe2a7b9fc 100644 --- a/tests/ui/reachable/expr_cast.rs +++ b/tests/ui/reachable/expr_cast.rs @@ -1,13 +1,12 @@ -#![allow(unused_variables)] -#![allow(unused_assignments)] -#![allow(dead_code)] +//@ edition: 2024 #![deny(unreachable_code)] -#![feature(never_type, type_ascription)] fn a() { - // the cast is unreachable: - let x = {return} as !; //~ ERROR unreachable - //~| ERROR non-primitive cast + _ = {return} as u32; //~ error: unreachable } -fn main() { } +fn b() { + (return) as u32; //~ error: unreachable +} + +fn main() {} diff --git a/tests/ui/reachable/expr_cast.stderr b/tests/ui/reachable/expr_cast.stderr index 6643f1784a17..cf711d4436e0 100644 --- a/tests/ui/reachable/expr_cast.stderr +++ b/tests/ui/reachable/expr_cast.stderr @@ -1,24 +1,26 @@ error: unreachable expression - --> $DIR/expr_cast.rs:9:13 + --> $DIR/expr_cast.rs:5:9 | -LL | let x = {return} as !; - | ^------^^^^^^ - | || - | |any code following this expression is unreachable - | unreachable expression +LL | _ = {return} as u32; + | ^------^^^^^^^^ + | || + | |any code following this expression is unreachable + | unreachable expression | note: the lint level is defined here - --> $DIR/expr_cast.rs:4:9 + --> $DIR/expr_cast.rs:2:9 | LL | #![deny(unreachable_code)] | ^^^^^^^^^^^^^^^^ -error[E0605]: non-primitive cast: `()` as `!` - --> $DIR/expr_cast.rs:9:13 +error: unreachable expression + --> $DIR/expr_cast.rs:9:5 | -LL | let x = {return} as !; - | ^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object +LL | (return) as u32; + | --------^^^^^^^ + | | + | unreachable expression + | any code following this expression is unreachable error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0605`. From d2e133d96a2a7b0063cfd514a35304e4908dcb6f Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Sun, 1 Jun 2025 12:51:17 +0200 Subject: [PATCH 0339/1134] don't warn on explicit casts of never to any --- compiler/rustc_hir_typeck/src/expr.rs | 3 +++ tests/ui/reachable/expr_cast.rs | 13 ++++++++-- tests/ui/reachable/expr_cast.stderr | 26 ------------------- tests/ui/reachable/unreachable-try-pattern.rs | 2 +- .../reachable/unreachable-try-pattern.stderr | 11 ++++---- 5 files changed, 20 insertions(+), 35 deletions(-) delete mode 100644 tests/ui/reachable/expr_cast.stderr diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 454ec7ddcafb..74136b546282 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -290,6 +290,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | ExprKind::Let(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {} + // Do not warn on `as` casts from never to any, + // they are sometimes required to appeal typeck. + ExprKind::Cast(_, _) => {} // If `expr` is a result of desugaring the try block and is an ok-wrapped // diverging expression (e.g. it arose from desugaring of `try { return }`), // we skip issuing a warning because it is autogenerated code. diff --git a/tests/ui/reachable/expr_cast.rs b/tests/ui/reachable/expr_cast.rs index 58ebe2a7b9fc..aa412c99b2e9 100644 --- a/tests/ui/reachable/expr_cast.rs +++ b/tests/ui/reachable/expr_cast.rs @@ -1,12 +1,21 @@ +//@ check-pass //@ edition: 2024 +// +// Check that we don't warn on `as` casts of never to any as unreachable. +// While they *are* unreachable, sometimes they are required to appeal typeck. #![deny(unreachable_code)] fn a() { - _ = {return} as u32; //~ error: unreachable + _ = {return} as u32; } fn b() { - (return) as u32; //~ error: unreachable + (return) as u32; +} + +// example that needs an explicit never-to-any `as` cast +fn example() -> impl Iterator { + todo!() as std::iter::Empty<_> } fn main() {} diff --git a/tests/ui/reachable/expr_cast.stderr b/tests/ui/reachable/expr_cast.stderr deleted file mode 100644 index cf711d4436e0..000000000000 --- a/tests/ui/reachable/expr_cast.stderr +++ /dev/null @@ -1,26 +0,0 @@ -error: unreachable expression - --> $DIR/expr_cast.rs:5:9 - | -LL | _ = {return} as u32; - | ^------^^^^^^^^ - | || - | |any code following this expression is unreachable - | unreachable expression - | -note: the lint level is defined here - --> $DIR/expr_cast.rs:2:9 - | -LL | #![deny(unreachable_code)] - | ^^^^^^^^^^^^^^^^ - -error: unreachable expression - --> $DIR/expr_cast.rs:9:5 - | -LL | (return) as u32; - | --------^^^^^^^ - | | - | unreachable expression - | any code following this expression is unreachable - -error: aborting due to 2 previous errors - diff --git a/tests/ui/reachable/unreachable-try-pattern.rs b/tests/ui/reachable/unreachable-try-pattern.rs index 22cbfb95af08..1358722e229c 100644 --- a/tests/ui/reachable/unreachable-try-pattern.rs +++ b/tests/ui/reachable/unreachable-try-pattern.rs @@ -18,7 +18,7 @@ fn bar(x: Result) -> Result { fn foo(x: Result) -> Result { let y = (match x { Ok(n) => Ok(n as u32), Err(e) => Err(e) })?; //~^ WARN unreachable pattern - //~| WARN unreachable expression + //~| WARN unreachable call Ok(y) } diff --git a/tests/ui/reachable/unreachable-try-pattern.stderr b/tests/ui/reachable/unreachable-try-pattern.stderr index 40b116131057..468af427249c 100644 --- a/tests/ui/reachable/unreachable-try-pattern.stderr +++ b/tests/ui/reachable/unreachable-try-pattern.stderr @@ -1,11 +1,10 @@ -warning: unreachable expression - --> $DIR/unreachable-try-pattern.rs:19:36 +warning: unreachable call + --> $DIR/unreachable-try-pattern.rs:19:33 | LL | let y = (match x { Ok(n) => Ok(n as u32), Err(e) => Err(e) })?; - | -^^^^^^^ - | | - | unreachable expression - | any code following this expression is unreachable + | ^^ - any code following this expression is unreachable + | | + | unreachable call | note: the lint level is defined here --> $DIR/unreachable-try-pattern.rs:3:9 From 2f60cef412ab56b17c62f2ea44ce72094be8d947 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Sat, 2 Aug 2025 08:46:15 +0200 Subject: [PATCH 0340/1134] `Interner` arg to `EarlyBinder` does not affect auto traits Conceptually `EarlyBinder` does not contain an `Interner` so it shouldn't tell Rust it does via `PhantomData`. This is necessary for rust-analyzer as it stores `EarlyBinder`s in query results which require `Sync`, placing restrictions on our interner setup. --- compiler/rustc_type_ir/src/binder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_type_ir/src/binder.rs b/compiler/rustc_type_ir/src/binder.rs index a7b915c48455..202d81df5aec 100644 --- a/compiler/rustc_type_ir/src/binder.rs +++ b/compiler/rustc_type_ir/src/binder.rs @@ -357,7 +357,7 @@ impl TypeVisitor for ValidateBoundVars { pub struct EarlyBinder { value: T, #[derive_where(skip(Debug))] - _tcx: PhantomData, + _tcx: PhantomData I>, } /// For early binders, you should first call `instantiate` before using any visitors. From fe7730f648b99a6e275b40c487f25e0feff7f76b Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 26 Jul 2025 19:06:08 +0800 Subject: [PATCH 0341/1134] Stylize `*-lynxos178-*` target maintainer handle to make it easier to copy/paste --- src/doc/rustc/src/platform-support/lynxos178.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc/src/platform-support/lynxos178.md b/src/doc/rustc/src/platform-support/lynxos178.md index 6463f95a0b8e..121e11fb653c 100644 --- a/src/doc/rustc/src/platform-support/lynxos178.md +++ b/src/doc/rustc/src/platform-support/lynxos178.md @@ -15,7 +15,7 @@ Target triples available: ## Target maintainers -- Renat Fatykhov, https://github.com/rfatykhov-lynx +[@rfatykhov-lynx](https://github.com/rfatykhov-lynx) ## Requirements From 0f98da7c5ccb5e873ddc08aef7508213a98b6aaa Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sat, 2 Aug 2025 09:13:16 +0200 Subject: [PATCH 0342/1134] fix: let_with_type_underscore don't eat closing paren in let (i): _ = 0; add failing tests fix also remove whitespace before `:` --- clippy_lints/src/let_with_type_underscore.rs | 11 ++++- tests/ui/let_with_type_underscore.fixed | 12 +++++ tests/ui/let_with_type_underscore.rs | 12 +++++ tests/ui/let_with_type_underscore.stderr | 50 +++++++++++++++++++- 4 files changed, 82 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/let_with_type_underscore.rs b/clippy_lints/src/let_with_type_underscore.rs index 1917ca24a05b..5b0f95ffc377 100644 --- a/clippy_lints/src/let_with_type_underscore.rs +++ b/clippy_lints/src/let_with_type_underscore.rs @@ -1,5 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_from_proc_macro; +use clippy_utils::source::{IntoSpan, SpanRangeExt}; use rustc_errors::Applicability; use rustc_hir::{LetStmt, TyKind}; use rustc_lint::{LateContext, LateLintPass}; @@ -30,9 +31,15 @@ impl<'tcx> LateLintPass<'tcx> for UnderscoreTyped { if let Some(ty) = local.ty // Ensure that it has a type defined && let TyKind::Infer(()) = &ty.kind // that type is '_' && local.span.eq_ctxt(ty.span) - && !local.span.in_external_macro(cx.tcx.sess.source_map()) + && let sm = cx.tcx.sess.source_map() + && !local.span.in_external_macro(sm) && !is_from_proc_macro(cx, ty) { + let span_to_remove = sm + .span_extend_to_prev_char_before(ty.span, ':', true) + .with_leading_whitespace(cx) + .into_span(); + span_lint_and_then( cx, LET_WITH_TYPE_UNDERSCORE, @@ -40,7 +47,7 @@ impl<'tcx> LateLintPass<'tcx> for UnderscoreTyped { "variable declared with type underscore", |diag| { diag.span_suggestion_verbose( - ty.span.with_lo(local.pat.span.hi()), + span_to_remove, "remove the explicit type `_` declaration", "", Applicability::MachineApplicable, diff --git a/tests/ui/let_with_type_underscore.fixed b/tests/ui/let_with_type_underscore.fixed index 7a4af4e3d1e7..6339fe595c21 100644 --- a/tests/ui/let_with_type_underscore.fixed +++ b/tests/ui/let_with_type_underscore.fixed @@ -45,3 +45,15 @@ fn main() { x = (); }; } + +fn issue15377() { + let (a) = 0; + //~^ let_with_type_underscore + let ((a)) = 0; + //~^ let_with_type_underscore + let ((a,)) = (0,); + //~^ let_with_type_underscore + #[rustfmt::skip] + let ( (a ) ) = 0; + //~^ let_with_type_underscore +} diff --git a/tests/ui/let_with_type_underscore.rs b/tests/ui/let_with_type_underscore.rs index a7c2f598b56d..bd85346cf01a 100644 --- a/tests/ui/let_with_type_underscore.rs +++ b/tests/ui/let_with_type_underscore.rs @@ -45,3 +45,15 @@ fn main() { x = (); }; } + +fn issue15377() { + let (a): _ = 0; + //~^ let_with_type_underscore + let ((a)): _ = 0; + //~^ let_with_type_underscore + let ((a,)): _ = (0,); + //~^ let_with_type_underscore + #[rustfmt::skip] + let ( (a ) ): _ = 0; + //~^ let_with_type_underscore +} diff --git a/tests/ui/let_with_type_underscore.stderr b/tests/ui/let_with_type_underscore.stderr index 9179f9922071..c3f6c82397b8 100644 --- a/tests/ui/let_with_type_underscore.stderr +++ b/tests/ui/let_with_type_underscore.stderr @@ -60,5 +60,53 @@ LL - let x : _ = 1; LL + let x = 1; | -error: aborting due to 5 previous errors +error: variable declared with type underscore + --> tests/ui/let_with_type_underscore.rs:50:5 + | +LL | let (a): _ = 0; + | ^^^^^^^^^^^^^^^ + | +help: remove the explicit type `_` declaration + | +LL - let (a): _ = 0; +LL + let (a) = 0; + | + +error: variable declared with type underscore + --> tests/ui/let_with_type_underscore.rs:52:5 + | +LL | let ((a)): _ = 0; + | ^^^^^^^^^^^^^^^^^ + | +help: remove the explicit type `_` declaration + | +LL - let ((a)): _ = 0; +LL + let ((a)) = 0; + | + +error: variable declared with type underscore + --> tests/ui/let_with_type_underscore.rs:54:5 + | +LL | let ((a,)): _ = (0,); + | ^^^^^^^^^^^^^^^^^^^^^ + | +help: remove the explicit type `_` declaration + | +LL - let ((a,)): _ = (0,); +LL + let ((a,)) = (0,); + | + +error: variable declared with type underscore + --> tests/ui/let_with_type_underscore.rs:57:5 + | +LL | let ( (a ) ): _ = 0; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: remove the explicit type `_` declaration + | +LL - let ( (a ) ): _ = 0; +LL + let ( (a ) ) = 0; + | + +error: aborting due to 9 previous errors From 5b03d0711ad6a2af1199fd28488a5c3ed813b130 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 2 Aug 2025 15:55:56 +0800 Subject: [PATCH 0343/1134] Pull out unexpected extension check into own function --- src/tools/tidy/src/ui_tests.rs | 88 ++++++++++++++++++---------------- 1 file changed, 46 insertions(+), 42 deletions(-) diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 4d195b3952e2..91b89d411497 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -7,41 +7,6 @@ use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; -const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[ - "rs", // test source files - "stderr", // expected stderr file, corresponds to a rs file - "svg", // expected svg file, corresponds to a rs file, equivalent to stderr - "stdout", // expected stdout file, corresponds to a rs file - "fixed", // expected source file after applying fixes - "md", // test directory descriptions - "ftl", // translation tests -]; - -const EXTENSION_EXCEPTION_PATHS: &[&str] = &[ - "tests/ui/asm/named-asm-labels.s", // loading an external asm file to test named labels lint - "tests/ui/codegen/mismatched-data-layout.json", // testing mismatched data layout w/ custom targets - "tests/ui/check-cfg/my-awesome-platform.json", // testing custom targets with cfgs - "tests/ui/argfile/commandline-argfile-badutf8.args", // passing args via a file - "tests/ui/argfile/commandline-argfile.args", // passing args via a file - "tests/ui/crate-loading/auxiliary/libfoo.rlib", // testing loading a manually created rlib - "tests/ui/include-macros/data.bin", // testing including data with the include macros - "tests/ui/include-macros/file.txt", // testing including data with the include macros - "tests/ui/macros/macro-expanded-include/file.txt", // testing including data with the include macros - "tests/ui/macros/not-utf8.bin", // testing including data with the include macros - "tests/ui/macros/syntax-extension-source-utils-files/includeme.fragment", // more include - "tests/ui/proc-macro/auxiliary/included-file.txt", // more include - "tests/ui/unpretty/auxiliary/data.txt", // more include - "tests/ui/invalid/foo.natvis.xml", // sample debugger visualizer - "tests/ui/sanitizer/dataflow-abilist.txt", // dataflow sanitizer ABI list file - "tests/ui/shell-argfiles/shell-argfiles.args", // passing args via a file - "tests/ui/shell-argfiles/shell-argfiles-badquotes.args", // passing args via a file - "tests/ui/shell-argfiles/shell-argfiles-via-argfile-shell.args", // passing args via a file - "tests/ui/shell-argfiles/shell-argfiles-via-argfile.args", // passing args via a file - "tests/ui/std/windows-bat-args1.bat", // tests escaping arguments through batch files - "tests/ui/std/windows-bat-args2.bat", // tests escaping arguments through batch files - "tests/ui/std/windows-bat-args3.bat", // tests escaping arguments through batch files -]; - pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { let issues_txt_header = r#"============================================================ ⚠️⚠️⚠️NOTHING SHOULD EVER BE ADDED TO THIS LIST⚠️⚠️⚠️ @@ -82,13 +47,7 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { crate::walk::walk_no_read(&paths, |_, _| false, &mut |entry| { let file_path = entry.path(); if let Some(ext) = file_path.extension().and_then(OsStr::to_str) { - // files that are neither an expected extension or an exception should not exist - // they're probably typos or not meant to exist - if !(EXPECTED_TEST_FILE_EXTENSIONS.contains(&ext) - || EXTENSION_EXCEPTION_PATHS.iter().any(|path| file_path.ends_with(path))) - { - tidy_error!(bad, "file {} has unexpected extension {}", file_path.display(), ext); - } + check_unexpected_extension(bad, file_path, ext); // NB: We do not use file_stem() as some file names have multiple `.`s and we // must strip all of them. @@ -171,3 +130,48 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { } } } + +fn check_unexpected_extension(bad: &mut bool, file_path: &Path, ext: &str) { + const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[ + "rs", // test source files + "stderr", // expected stderr file, corresponds to a rs file + "svg", // expected svg file, corresponds to a rs file, equivalent to stderr + "stdout", // expected stdout file, corresponds to a rs file + "fixed", // expected source file after applying fixes + "md", // test directory descriptions + "ftl", // translation tests + ]; + + const EXTENSION_EXCEPTION_PATHS: &[&str] = &[ + "tests/ui/asm/named-asm-labels.s", // loading an external asm file to test named labels lint + "tests/ui/codegen/mismatched-data-layout.json", // testing mismatched data layout w/ custom targets + "tests/ui/check-cfg/my-awesome-platform.json", // testing custom targets with cfgs + "tests/ui/argfile/commandline-argfile-badutf8.args", // passing args via a file + "tests/ui/argfile/commandline-argfile.args", // passing args via a file + "tests/ui/crate-loading/auxiliary/libfoo.rlib", // testing loading a manually created rlib + "tests/ui/include-macros/data.bin", // testing including data with the include macros + "tests/ui/include-macros/file.txt", // testing including data with the include macros + "tests/ui/macros/macro-expanded-include/file.txt", // testing including data with the include macros + "tests/ui/macros/not-utf8.bin", // testing including data with the include macros + "tests/ui/macros/syntax-extension-source-utils-files/includeme.fragment", // more include + "tests/ui/proc-macro/auxiliary/included-file.txt", // more include + "tests/ui/unpretty/auxiliary/data.txt", // more include + "tests/ui/invalid/foo.natvis.xml", // sample debugger visualizer + "tests/ui/sanitizer/dataflow-abilist.txt", // dataflow sanitizer ABI list file + "tests/ui/shell-argfiles/shell-argfiles.args", // passing args via a file + "tests/ui/shell-argfiles/shell-argfiles-badquotes.args", // passing args via a file + "tests/ui/shell-argfiles/shell-argfiles-via-argfile-shell.args", // passing args via a file + "tests/ui/shell-argfiles/shell-argfiles-via-argfile.args", // passing args via a file + "tests/ui/std/windows-bat-args1.bat", // tests escaping arguments through batch files + "tests/ui/std/windows-bat-args2.bat", // tests escaping arguments through batch files + "tests/ui/std/windows-bat-args3.bat", // tests escaping arguments through batch files + ]; + + // files that are neither an expected extension or an exception should not exist + // they're probably typos or not meant to exist + if !(EXPECTED_TEST_FILE_EXTENSIONS.contains(&ext) + || EXTENSION_EXCEPTION_PATHS.iter().any(|path| file_path.ends_with(path))) + { + tidy_error!(bad, "file {} has unexpected extension {}", file_path.display(), ext); + } +} From c10dc999f004aa04d29652f6fa9dc9535cb10899 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 2 Aug 2025 15:58:53 +0800 Subject: [PATCH 0344/1134] Pull out stray/empty output snapshot checks into own functions --- src/tools/tidy/src/ui_tests.rs | 51 +++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 91b89d411497..ee26e81c97f6 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -54,28 +54,8 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { let testname = file_path.file_name().unwrap().to_str().unwrap().split_once('.').unwrap().0; if ext == "stderr" || ext == "stdout" || ext == "fixed" { - // Test output filenames have one of the formats: - // ``` - // $testname.stderr - // $testname.$mode.stderr - // $testname.$revision.stderr - // $testname.$revision.$mode.stderr - // ``` - // - // For now, just make sure that there is a corresponding - // `$testname.rs` file. - - if !file_path.with_file_name(testname).with_extension("rs").exists() - && !testname.contains("ignore-tidy") - { - tidy_error!(bad, "Stray file with UI testing output: {:?}", file_path); - } - - if let Ok(metadata) = fs::metadata(file_path) - && metadata.len() == 0 - { - tidy_error!(bad, "Empty file with UI testing output: {:?}", file_path); - } + check_stray_output_snapshot(bad, file_path, testname); + check_empty_output_snapshot(bad, file_path); } if ext == "rs" @@ -175,3 +155,30 @@ fn check_unexpected_extension(bad: &mut bool, file_path: &Path, ext: &str) { tidy_error!(bad, "file {} has unexpected extension {}", file_path.display(), ext); } } + +fn check_stray_output_snapshot(bad: &mut bool, file_path: &Path, testname: &str) { + // Test output filenames have one of the formats: + // ``` + // $testname.stderr + // $testname.$mode.stderr + // $testname.$revision.stderr + // $testname.$revision.$mode.stderr + // ``` + // + // For now, just make sure that there is a corresponding + // `$testname.rs` file. + + if !file_path.with_file_name(testname).with_extension("rs").exists() + && !testname.contains("ignore-tidy") + { + tidy_error!(bad, "Stray file with UI testing output: {:?}", file_path); + } +} + +fn check_empty_output_snapshot(bad: &mut bool, file_path: &Path) { + if let Ok(metadata) = fs::metadata(file_path) + && metadata.len() == 0 + { + tidy_error!(bad, "Empty file with UI testing output: {:?}", file_path); + } +} From a71428825a3322d2662efdc4299f9cfac3e3f5e5 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 2 Aug 2025 16:09:10 +0800 Subject: [PATCH 0345/1134] Pull out non-descriptive test name check to own function --- src/tools/tidy/src/ui_tests.rs | 60 ++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 21 deletions(-) diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index ee26e81c97f6..98a6b466ae91 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -58,27 +58,14 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { check_empty_output_snapshot(bad, file_path); } - if ext == "rs" - && let Some(test_name) = static_regex!(r"^issues?[-_]?(\d{3,})").captures(testname) - { - // these paths are always relative to the passed `path` and always UTF8 - let stripped_path = file_path - .strip_prefix(path) - .unwrap() - .to_str() - .unwrap() - .replace(std::path::MAIN_SEPARATOR_STR, "/"); - - if !remaining_issue_names.remove(stripped_path.as_str()) - && !stripped_path.starts_with("ui/issues/") - { - tidy_error!( - bad, - "file `tests/{stripped_path}` must begin with a descriptive name, consider `{{reason}}-issue-{issue_n}.rs`", - issue_n = &test_name[1], - ); - } - } + deny_new_nondescriptive_test_names( + bad, + path, + &mut remaining_issue_names, + file_path, + testname, + ext, + ); } }); @@ -182,3 +169,34 @@ fn check_empty_output_snapshot(bad: &mut bool, file_path: &Path) { tidy_error!(bad, "Empty file with UI testing output: {:?}", file_path); } } + +fn deny_new_nondescriptive_test_names( + bad: &mut bool, + path: &Path, + remaining_issue_names: &mut BTreeSet<&str>, + file_path: &Path, + testname: &str, + ext: &str, +) { + if ext == "rs" + && let Some(test_name) = static_regex!(r"^issues?[-_]?(\d{3,})").captures(testname) + { + // these paths are always relative to the passed `path` and always UTF8 + let stripped_path = file_path + .strip_prefix(path) + .unwrap() + .to_str() + .unwrap() + .replace(std::path::MAIN_SEPARATOR_STR, "/"); + + if !remaining_issue_names.remove(stripped_path.as_str()) + && !stripped_path.starts_with("ui/issues/") + { + tidy_error!( + bad, + "file `tests/{stripped_path}` must begin with a descriptive name, consider `{{reason}}-issue-{issue_n}.rs`", + issue_n = &test_name[1], + ); + } + } +} From a97d0aabc8bbaeff1aff88df67bc99e8c778ba06 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 2 Aug 2025 16:12:56 +0800 Subject: [PATCH 0346/1134] Make `issues_txt_header` a const --- src/tools/tidy/src/ui_tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 98a6b466ae91..6c83764cc194 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -7,12 +7,12 @@ use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; -pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { - let issues_txt_header = r#"============================================================ +const ISSUES_TXT_HEADER: &str = r#"============================================================ ⚠️⚠️⚠️NOTHING SHOULD EVER BE ADDED TO THIS LIST⚠️⚠️⚠️ ============================================================ "#; +pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { let path = &root_path.join("tests"); // the list of files in ui tests that are allowed to start with `issue-XXXX` @@ -20,7 +20,7 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { let mut prev_line = ""; let mut is_sorted = true; let allowed_issue_names: BTreeSet<_> = include_str!("issues.txt") - .strip_prefix(issues_txt_header) + .strip_prefix(ISSUES_TXT_HEADER) .unwrap() .lines() .inspect(|&line| { @@ -78,7 +78,7 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { // so we don't bork things on panic or a contributor using Ctrl+C let blessed_issues_path = tidy_src.join("issues_blessed.txt"); let mut blessed_issues_txt = fs::File::create(&blessed_issues_path).unwrap(); - blessed_issues_txt.write_all(issues_txt_header.as_bytes()).unwrap(); + blessed_issues_txt.write_all(ISSUES_TXT_HEADER.as_bytes()).unwrap(); // If we changed paths to use the OS separator, reassert Unix chauvinism for blessing. for filename in allowed_issue_names.difference(&remaining_issue_names) { writeln!(blessed_issues_txt, "{filename}").unwrap(); From fa31c7d49e7456b57bc32de118e72e0d7045ef6e Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 2 Aug 2025 16:16:41 +0800 Subject: [PATCH 0347/1134] Pull out recursive ui test check into its own function --- src/tools/tidy/src/ui_tests.rs | 65 +++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 6c83764cc194..b968ea5f2d89 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -40,34 +40,7 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { ); } - let mut remaining_issue_names: BTreeSet<&str> = allowed_issue_names.clone(); - - let (ui, ui_fulldeps) = (path.join("ui"), path.join("ui-fulldeps")); - let paths = [ui.as_path(), ui_fulldeps.as_path()]; - crate::walk::walk_no_read(&paths, |_, _| false, &mut |entry| { - let file_path = entry.path(); - if let Some(ext) = file_path.extension().and_then(OsStr::to_str) { - check_unexpected_extension(bad, file_path, ext); - - // NB: We do not use file_stem() as some file names have multiple `.`s and we - // must strip all of them. - let testname = - file_path.file_name().unwrap().to_str().unwrap().split_once('.').unwrap().0; - if ext == "stderr" || ext == "stdout" || ext == "fixed" { - check_stray_output_snapshot(bad, file_path, testname); - check_empty_output_snapshot(bad, file_path); - } - - deny_new_nondescriptive_test_names( - bad, - path, - &mut remaining_issue_names, - file_path, - testname, - ext, - ); - } - }); + let remaining_issue_names = recursively_check_ui_tests(bad, path, &allowed_issue_names); // if there are any file names remaining, they were moved on the fs. // our data must remain up to date, so it must be removed from issues.txt @@ -98,6 +71,42 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { } } +fn recursively_check_ui_tests<'issues>( + bad: &mut bool, + path: &Path, + allowed_issue_names: &'issues BTreeSet<&'issues str>, +) -> BTreeSet<&'issues str> { + let mut remaining_issue_names: BTreeSet<&str> = allowed_issue_names.clone(); + + let (ui, ui_fulldeps) = (path.join("ui"), path.join("ui-fulldeps")); + let paths = [ui.as_path(), ui_fulldeps.as_path()]; + crate::walk::walk_no_read(&paths, |_, _| false, &mut |entry| { + let file_path = entry.path(); + if let Some(ext) = file_path.extension().and_then(OsStr::to_str) { + check_unexpected_extension(bad, file_path, ext); + + // NB: We do not use file_stem() as some file names have multiple `.`s and we + // must strip all of them. + let testname = + file_path.file_name().unwrap().to_str().unwrap().split_once('.').unwrap().0; + if ext == "stderr" || ext == "stdout" || ext == "fixed" { + check_stray_output_snapshot(bad, file_path, testname); + check_empty_output_snapshot(bad, file_path); + } + + deny_new_nondescriptive_test_names( + bad, + path, + &mut remaining_issue_names, + file_path, + testname, + ext, + ); + } + }); + remaining_issue_names +} + fn check_unexpected_extension(bad: &mut bool, file_path: &Path, ext: &str) { const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[ "rs", // test source files From 0b1547e9c052b29d246a8e5cb3d6408407e88dab Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 2 Aug 2025 16:54:26 +0800 Subject: [PATCH 0348/1134] Reject adding new UI tests directly under `tests/ui/` As we want future UI tests to be added under a more meaningful subdirectory instead. --- src/tools/tidy/src/ui_tests.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index b968ea5f2d89..5bf966b658c6 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -40,6 +40,8 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { ); } + deny_new_top_level_ui_tests(bad, &path.join("ui")); + let remaining_issue_names = recursively_check_ui_tests(bad, path, &allowed_issue_names); // if there are any file names remaining, they were moved on the fs. @@ -71,6 +73,34 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { } } +fn deny_new_top_level_ui_tests(bad: &mut bool, tests_path: &Path) { + // See where we propose banning adding + // new ui tests *directly* under `tests/ui/`. For more context, see: + // + // - + // - + + let top_level_ui_tests = walkdir::WalkDir::new(tests_path) + .min_depth(1) + .max_depth(1) + .follow_links(false) + .same_file_system(true) + .into_iter() + .flatten() + .filter(|e| { + let file_name = e.file_name(); + file_name != ".gitattributes" && file_name != "README.md" + }) + .filter(|e| !e.file_type().is_dir()); + for entry in top_level_ui_tests { + tidy_error!( + bad, + "ui tests should be added under meaningful subdirectories: `{}`", + entry.path().display() + ) + } +} + fn recursively_check_ui_tests<'issues>( bad: &mut bool, path: &Path, From 870b58f4d060cc63c2969faa3f54da7802c4881e Mon Sep 17 00:00:00 2001 From: Noratrieb <48135649+Noratrieb@users.noreply.github.com> Date: Sat, 2 Aug 2025 11:27:38 +0200 Subject: [PATCH 0349/1134] Update E0562 to account for the new impl trait positions --- compiler/rustc_error_codes/src/error_codes/E0562.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_error_codes/src/error_codes/E0562.md b/compiler/rustc_error_codes/src/error_codes/E0562.md index 95f038df56d6..af7b219fb120 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0562.md +++ b/compiler/rustc_error_codes/src/error_codes/E0562.md @@ -1,5 +1,4 @@ -Abstract return types (written `impl Trait` for some trait `Trait`) are only -allowed as function and inherent impl return types. +`impl Trait` is only allowed as a function return and argument type. Erroneous code example: @@ -14,7 +13,7 @@ fn main() { } ``` -Make sure `impl Trait` only appears in return-type position. +Make sure `impl Trait` appears in a function signature. ``` fn count_to_n(n: usize) -> impl Iterator { @@ -28,6 +27,6 @@ fn main() { } ``` -See [RFC 1522] for more details. +See the [reference] for more details on `impl Trait`. -[RFC 1522]: https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md +[reference]: https://doc.rust-lang.org/stable/reference/types/impl-trait.html From 4ad8606d79a7cb9693f315fdd979fdb03d72318e Mon Sep 17 00:00:00 2001 From: "Pascal S. de Kloe" Date: Tue, 8 Jul 2025 17:56:25 +0200 Subject: [PATCH 0350/1134] fmt with table lookup for binary, octal and hex * correct buffer size * no trait abstraction * similar to decimal --- library/core/src/fmt/num.rs | 177 +++++++++++------------------------- 1 file changed, 55 insertions(+), 122 deletions(-) diff --git a/library/core/src/fmt/num.rs b/library/core/src/fmt/num.rs index a52749d43259..cdabaeb72654 100644 --- a/library/core/src/fmt/num.rs +++ b/library/core/src/fmt/num.rs @@ -10,9 +10,6 @@ use crate::{fmt, ptr, slice, str}; trait DisplayInt: PartialEq + PartialOrd + Div + Rem + Sub + Copy { - fn zero() -> Self; - fn from_u8(u: u8) -> Self; - fn to_u8(&self) -> u8; #[cfg(not(any(target_pointer_width = "64", target_arch = "wasm32")))] fn to_u32(&self) -> u32; fn to_u64(&self) -> u64; @@ -22,9 +19,6 @@ trait DisplayInt: macro_rules! impl_int { ($($t:ident)*) => ( $(impl DisplayInt for $t { - fn zero() -> Self { 0 } - fn from_u8(u: u8) -> Self { u as Self } - fn to_u8(&self) -> u8 { *self as u8 } #[cfg(not(any(target_pointer_width = "64", target_arch = "wasm32")))] fn to_u32(&self) -> u32 { *self as u32 } fn to_u64(&self) -> u64 { *self as u64 } @@ -38,137 +32,76 @@ impl_int! { u8 u16 u32 u64 u128 usize } -/// A type that represents a specific radix -/// -/// # Safety -/// -/// `digit` must return an ASCII character. -#[doc(hidden)] -unsafe trait GenericRadix: Sized { - /// The number of digits. - const BASE: u8; - - /// A radix-specific prefix string. - const PREFIX: &'static str; - - /// Converts an integer to corresponding radix digit. - fn digit(x: u8) -> u8; - - /// Format an unsigned integer using the radix using a formatter. - fn fmt_int(&self, mut x: T, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // The radix can be as low as 2, so we need a buffer of at least 128 - // characters for a base 2 number. - let zero = T::zero(); - let mut buf = [MaybeUninit::::uninit(); 128]; - let mut offset = buf.len(); - let base = T::from_u8(Self::BASE); - - // Accumulate each digit of the number from the least significant - // to the most significant figure. - loop { - let n = x % base; // Get the current place value. - x = x / base; // Deaccumulate the number. - offset -= 1; - buf[offset].write(Self::digit(n.to_u8())); // Store the digit in the buffer. - if x == zero { - // No more digits left to accumulate. - break; - }; - } +/// Formatting of integers with a non-decimal radix. +macro_rules! radix_integer { + (fmt::$Trait:ident for $Signed:ident and $Unsigned:ident, $prefix:literal, $dig_tab:literal) => { + #[stable(feature = "rust1", since = "1.0.0")] + impl fmt::$Trait for $Unsigned { + /// Format unsigned integers in the radix. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Check macro arguments at compile time. + const { + assert!($Unsigned::MIN == 0, "need unsigned"); + assert!($dig_tab.is_ascii(), "need single-byte entries"); + } - // SAFETY: Starting from `offset`, all elements of the slice have been set. - let digits = unsafe { slice_buffer_to_str(&buf, offset) }; - f.pad_integral(true, Self::PREFIX, digits) - } -} + // ASCII digits in ascending order are used as a lookup table. + const DIG_TAB: &[u8] = $dig_tab; + const BASE: $Unsigned = DIG_TAB.len() as $Unsigned; + const MAX_DIG_N: usize = $Unsigned::MAX.ilog(BASE) as usize + 1; + + // Buffer digits of self with right alignment. + let mut buf = [MaybeUninit::::uninit(); MAX_DIG_N]; + // Count the number of bytes in buf that are not initialized. + let mut offset = buf.len(); -/// A binary (base 2) radix -#[derive(Clone, PartialEq)] -struct Binary; - -/// An octal (base 8) radix -#[derive(Clone, PartialEq)] -struct Octal; - -/// A hexadecimal (base 16) radix, formatted with lower-case characters -#[derive(Clone, PartialEq)] -struct LowerHex; - -/// A hexadecimal (base 16) radix, formatted with upper-case characters -#[derive(Clone, PartialEq)] -struct UpperHex; - -macro_rules! radix { - ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => { - unsafe impl GenericRadix for $T { - const BASE: u8 = $base; - const PREFIX: &'static str = $prefix; - fn digit(x: u8) -> u8 { - match x { - $($x => $conv,)+ - x => panic!("number not in the range 0..={}: {}", Self::BASE - 1, x), + // Accumulate each digit of the number from the least + // significant to the most significant figure. + let mut remain = *self; + loop { + let digit = remain % BASE; + remain /= BASE; + + offset -= 1; + // SAFETY: `remain` will reach 0 and we will break before `offset` wraps + unsafe { core::hint::assert_unchecked(offset < buf.len()) } + buf[offset].write(DIG_TAB[digit as usize]); + if remain == 0 { + break; + } } + + // SAFETY: Starting from `offset`, all elements of the slice have been set. + let digits = unsafe { slice_buffer_to_str(&buf, offset) }; + f.pad_integral(true, $prefix, digits) } } - } -} - -radix! { Binary, 2, "0b", x @ 0 ..= 1 => b'0' + x } -radix! { Octal, 8, "0o", x @ 0 ..= 7 => b'0' + x } -radix! { LowerHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, x @ 10 ..= 15 => b'a' + (x - 10) } -radix! { UpperHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, x @ 10 ..= 15 => b'A' + (x - 10) } -macro_rules! int_base { - (fmt::$Trait:ident for $T:ident -> $Radix:ident) => { #[stable(feature = "rust1", since = "1.0.0")] - impl fmt::$Trait for $T { + impl fmt::$Trait for $Signed { + /// Format signed integers in the two’s-complement form. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - $Radix.fmt_int(*self, f) + fmt::$Trait::fmt(&self.cast_unsigned(), f) } } }; } -macro_rules! integer { - ($Int:ident, $Uint:ident) => { - int_base! { fmt::Binary for $Uint -> Binary } - int_base! { fmt::Octal for $Uint -> Octal } - int_base! { fmt::LowerHex for $Uint -> LowerHex } - int_base! { fmt::UpperHex for $Uint -> UpperHex } - - // Format signed integers as unsigned (two’s complement representation). - #[stable(feature = "rust1", since = "1.0.0")] - impl fmt::Binary for $Int { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Binary::fmt(&self.cast_unsigned(), f) - } - } - #[stable(feature = "rust1", since = "1.0.0")] - impl fmt::Octal for $Int { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Octal::fmt(&self.cast_unsigned(), f) - } - } - #[stable(feature = "rust1", since = "1.0.0")] - impl fmt::LowerHex for $Int { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::LowerHex::fmt(&self.cast_unsigned(), f) - } - } - #[stable(feature = "rust1", since = "1.0.0")] - impl fmt::UpperHex for $Int { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::UpperHex::fmt(&self.cast_unsigned(), f) - } - } +/// Formatting of integers with a non-decimal radix. +macro_rules! radix_integers { + ($Signed:ident, $Unsigned:ident) => { + radix_integer! { fmt::Binary for $Signed and $Unsigned, "0b", b"01" } + radix_integer! { fmt::Octal for $Signed and $Unsigned, "0o", b"01234567" } + radix_integer! { fmt::LowerHex for $Signed and $Unsigned, "0x", b"0123456789abcdef" } + radix_integer! { fmt::UpperHex for $Signed and $Unsigned, "0x", b"0123456789ABCDEF" } }; } -integer! { isize, usize } -integer! { i8, u8 } -integer! { i16, u16 } -integer! { i32, u32 } -integer! { i64, u64 } -integer! { i128, u128 } +radix_integers! { isize, usize } +radix_integers! { i8, u8 } +radix_integers! { i16, u16 } +radix_integers! { i32, u32 } +radix_integers! { i64, u64 } +radix_integers! { i128, u128 } macro_rules! impl_Debug { ($($T:ident)*) => { From 81c4086a03dcd5f114ed9d739622805cf77cb738 Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Sat, 2 Aug 2025 19:13:07 +0900 Subject: [PATCH 0351/1134] Migrate `convert_from_to_tryfrom` assist to use `SyntaxEditor` --- .../src/handlers/convert_from_to_tryfrom.rs | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs index a4742bc7bded..f1cc3d90b9c5 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs @@ -1,9 +1,7 @@ use ide_db::{famous_defs::FamousDefs, traits::resolve_target_trait}; -use itertools::Itertools; -use syntax::{ - ast::{self, AstNode, HasGenericArgs, HasName, make}, - ted, -}; +use syntax::ast::edit::IndentLevel; +use syntax::ast::{self, AstNode, HasGenericArgs, HasName, make}; +use syntax::syntax_editor::{Element, Position}; use crate::{AssistContext, AssistId, Assists}; @@ -49,6 +47,7 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_> }; let associated_items = impl_.assoc_item_list()?; + let associated_l_curly = associated_items.l_curly_token()?; let from_fn = associated_items.assoc_items().find_map(|item| { if let ast::AssocItem::Fn(f) = item && f.name()?.text() == "from" @@ -75,30 +74,25 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_> "Convert From to TryFrom", impl_.syntax().text_range(), |builder| { - let trait_ty = builder.make_mut(trait_ty); - let from_fn_return_type = builder.make_mut(from_fn_return_type); - let from_fn_name = builder.make_mut(from_fn_name); - let tail_expr = builder.make_mut(tail_expr); - let return_exprs = return_exprs.map(|r| builder.make_mut(r)).collect_vec(); - let associated_items = builder.make_mut(associated_items); - - ted::replace( + let mut editor = builder.make_editor(impl_.syntax()); + editor.replace( trait_ty.syntax(), make::ty(&format!("TryFrom<{from_type}>")).syntax().clone_for_update(), ); - ted::replace( + editor.replace( from_fn_return_type.syntax(), make::ty("Result").syntax().clone_for_update(), ); - ted::replace(from_fn_name.syntax(), make::name("try_from").syntax().clone_for_update()); - ted::replace( + editor + .replace(from_fn_name.syntax(), make::name("try_from").syntax().clone_for_update()); + editor.replace( tail_expr.syntax(), wrap_ok(tail_expr.clone()).syntax().clone_for_update(), ); for r in return_exprs { let t = r.expr().unwrap_or_else(make::ext::expr_unit); - ted::replace(t.syntax(), wrap_ok(t.clone()).syntax().clone_for_update()); + editor.replace(t.syntax(), wrap_ok(t.clone()).syntax().clone_for_update()); } let error_type = ast::AssocItem::TypeAlias(make::ty_alias( @@ -114,10 +108,20 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_> && let ast::AssocItem::TypeAlias(type_alias) = &error_type && let Some(ty) = type_alias.ty() { - builder.add_placeholder_snippet(cap, ty); + let placeholder = builder.make_placeholder_snippet(cap); + editor.add_annotation(ty.syntax(), placeholder); } - associated_items.add_item_at_start(error_type); + let indent = IndentLevel::from_token(&associated_l_curly) + 1; + editor.insert_all( + Position::after(associated_l_curly), + vec![ + make::tokens::whitespace(&format!("\n{indent}")).syntax_element(), + error_type.syntax().syntax_element(), + make::tokens::whitespace("\n").syntax_element(), + ], + ); + builder.add_file_edits(ctx.vfs_file_id(), editor); }, ) } From 74c6fdf171e04e368e6e2179158396a4ead6c634 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Sun, 27 Jul 2025 18:01:40 +0200 Subject: [PATCH 0352/1134] c-variadic: multiple ABIs in the same program for arm --- .../src/directives/directive_names.rs | 1 + .../same-program-multiple-abis-arm.rs | 77 +++++++++++++++++++ ...s => same-program-multiple-abis-x86_64.rs} | 0 3 files changed, 78 insertions(+) create mode 100644 tests/ui/c-variadic/same-program-multiple-abis-arm.rs rename tests/ui/c-variadic/{same-program-multiple-abis.rs => same-program-multiple-abis-x86_64.rs} (100%) diff --git a/src/tools/compiletest/src/directives/directive_names.rs b/src/tools/compiletest/src/directives/directive_names.rs index 7fc76a42e0ca..cc4e81c357ad 100644 --- a/src/tools/compiletest/src/directives/directive_names.rs +++ b/src/tools/compiletest/src/directives/directive_names.rs @@ -193,6 +193,7 @@ pub(crate) const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "only-bpf", "only-cdb", "only-dist", + "only-eabihf", "only-elf", "only-emscripten", "only-gnu", diff --git a/tests/ui/c-variadic/same-program-multiple-abis-arm.rs b/tests/ui/c-variadic/same-program-multiple-abis-arm.rs new file mode 100644 index 000000000000..1b0bdecabfbc --- /dev/null +++ b/tests/ui/c-variadic/same-program-multiple-abis-arm.rs @@ -0,0 +1,77 @@ +#![feature(extended_varargs_abi_support)] +//@ run-pass +//@ only-arm +//@ ignore-thumb (this test uses arm assembly) +//@ only-eabihf (the assembly below requires float hardware support) + +// Check that multiple c-variadic calling conventions can be used in the same program. +// +// Clang and gcc reject defining functions with a non-default calling convention and a variable +// argument list, so C programs that use multiple c-variadic calling conventions are unlikely +// to come up. Here we validate that our codegen backends do in fact generate correct code. + +extern "C" { + fn variadic_c(_: f64, _: ...) -> f64; +} + +extern "aapcs" { + fn variadic_aapcs(_: f64, _: ...) -> f64; +} + +fn main() { + unsafe { + assert_eq!(variadic_c(1.0, 2.0, 3.0), 1.0 + 2.0 + 3.0); + assert_eq!(variadic_aapcs(1.0, 2.0, 3.0), 1.0 + 2.0 + 3.0); + } +} + +// This assembly was generated using https://godbolt.org/z/xcW6a1Tj5, and corresponds to the +// following code compiled for the `armv7-unknown-linux-gnueabihf` target: +// +// ```rust +// #![feature(c_variadic)] +// +// #[unsafe(no_mangle)] +// unsafe extern "C" fn variadic(a: f64, mut args: ...) -> f64 { +// let b = args.arg::(); +// let c = args.arg::(); +// +// a + b + c +// } +// ``` +// +// This function uses floats (and passes one normal float argument) because the aapcs and C calling +// conventions differ in how floats are passed, e.g. https://godbolt.org/z/sz799f51x. However, for +// c-variadic functions, both ABIs actually behave the same, based on: +// +// https://github.com/ARM-software/abi-aa/blob/main/aapcs32/aapcs32.rst#65parameter-passing +// +// > A variadic function is always marshaled as for the base standard. +// +// https://github.com/ARM-software/abi-aa/blob/main/aapcs32/aapcs32.rst#7the-standard-variants +// +// > This section applies only to non-variadic functions. For a variadic function the base standard +// > is always used both for argument passing and result return. +core::arch::global_asm!( + r#" +{variadic_c}: +{variadic_aapcs}: + sub sp, sp, #12 + stmib sp, {{r2, r3}} + vmov d0, r0, r1 + add r0, sp, #4 + vldr d1, [sp, #4] + add r0, r0, #15 + bic r0, r0, #7 + vadd.f64 d0, d0, d1 + add r1, r0, #8 + str r1, [sp] + vldr d1, [r0] + vadd.f64 d0, d0, d1 + vmov r0, r1, d0 + add sp, sp, #12 + bx lr + "#, + variadic_c = sym variadic_c, + variadic_aapcs = sym variadic_aapcs, +); diff --git a/tests/ui/c-variadic/same-program-multiple-abis.rs b/tests/ui/c-variadic/same-program-multiple-abis-x86_64.rs similarity index 100% rename from tests/ui/c-variadic/same-program-multiple-abis.rs rename to tests/ui/c-variadic/same-program-multiple-abis-x86_64.rs From c861fbd30391596e8fb1979b5cbc4e2807a8aed4 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Sat, 2 Aug 2025 14:26:47 +0200 Subject: [PATCH 0353/1134] use gcc 15 as the linker on loongarch --- library/stdarch/Cargo.lock | 20 +++++++++---------- .../loongarch64-unknown-linux-gnu/Dockerfile | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/library/stdarch/Cargo.lock b/library/stdarch/Cargo.lock index 3d1fd6d6cc39..9df0791b8652 100644 --- a/library/stdarch/Cargo.lock +++ b/library/stdarch/Cargo.lock @@ -90,9 +90,9 @@ checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "cc" -version = "1.2.30" +version = "1.2.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deec109607ca693028562ed836a5f1c4b8bd77755c4e132fc5ce11b0b6211ae7" +checksum = "c3a42d84bb6b69d3a8b3eaacf0d88f179e1929695e1ad012b6cf64d9caaa5fd2" dependencies = [ "shlex", ] @@ -105,9 +105,9 @@ checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" [[package]] name = "clap" -version = "4.5.41" +version = "4.5.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9" +checksum = "ed87a9d530bb41a67537289bafcac159cb3ee28460e0a4571123d2a778a6a882" dependencies = [ "clap_builder", "clap_derive", @@ -115,9 +115,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.41" +version = "4.5.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d" +checksum = "64f4f3f3c77c94aff3c7e9aac9a2ca1974a5adf392a8bb751e827d6d127ab966" dependencies = [ "anstream", "anstyle", @@ -546,9 +546,9 @@ checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "rustc-demangle" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" +checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" [[package]] name = "ryu" @@ -593,9 +593,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.141" +version = "1.0.142" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" +checksum = "030fedb782600dcbd6f02d479bf0d817ac3bb40d644745b769d6a96bc3afc5a7" dependencies = [ "itoa", "memchr", diff --git a/library/stdarch/ci/docker/loongarch64-unknown-linux-gnu/Dockerfile b/library/stdarch/ci/docker/loongarch64-unknown-linux-gnu/Dockerfile index 5ab3431ba272..b5c6874ca52e 100644 --- a/library/stdarch/ci/docker/loongarch64-unknown-linux-gnu/Dockerfile +++ b/library/stdarch/ci/docker/loongarch64-unknown-linux-gnu/Dockerfile @@ -6,7 +6,7 @@ RUN apt-get update && \ gcc-loongarch64-linux-gnu libc6-dev-loong64-cross -ENV CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_GNU_LINKER=loongarch64-linux-gnu-gcc-14 \ +ENV CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_GNU_LINKER=loongarch64-linux-gnu-gcc \ CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_GNU_RUNNER="qemu-loongarch64-static -cpu max -L /usr/loongarch64-linux-gnu" \ OBJDUMP=loongarch64-linux-gnu-objdump \ STDARCH_TEST_SKIP_FEATURE=frecipe From 40f587aa0d0a792b3f4e558e739c591534778eb3 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 23:07:45 +1000 Subject: [PATCH 0354/1134] Flatten `hash_owner_nodes` with an early-return --- compiler/rustc_middle/src/hir/mod.rs | 42 ++++++++++++++-------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 6c07e49734ab..a928703542fd 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -175,32 +175,32 @@ impl<'tcx> TyCtxt<'tcx> { delayed_lints: &[DelayedLint], define_opaque: Option<&[(Span, LocalDefId)]>, ) -> (Option, Option, Option) { - if self.needs_crate_hash() { - self.with_stable_hashing_context(|mut hcx| { - let mut stable_hasher = StableHasher::new(); - node.hash_stable(&mut hcx, &mut stable_hasher); - // Bodies are stored out of line, so we need to pull them explicitly in the hash. - bodies.hash_stable(&mut hcx, &mut stable_hasher); - let h1 = stable_hasher.finish(); + if !self.needs_crate_hash() { + return (None, None, None); + } - let mut stable_hasher = StableHasher::new(); - attrs.hash_stable(&mut hcx, &mut stable_hasher); + self.with_stable_hashing_context(|mut hcx| { + let mut stable_hasher = StableHasher::new(); + node.hash_stable(&mut hcx, &mut stable_hasher); + // Bodies are stored out of line, so we need to pull them explicitly in the hash. + bodies.hash_stable(&mut hcx, &mut stable_hasher); + let h1 = stable_hasher.finish(); - // Hash the defined opaque types, which are not present in the attrs. - define_opaque.hash_stable(&mut hcx, &mut stable_hasher); + let mut stable_hasher = StableHasher::new(); + attrs.hash_stable(&mut hcx, &mut stable_hasher); - let h2 = stable_hasher.finish(); + // Hash the defined opaque types, which are not present in the attrs. + define_opaque.hash_stable(&mut hcx, &mut stable_hasher); - // hash lints emitted during ast lowering - let mut stable_hasher = StableHasher::new(); - delayed_lints.hash_stable(&mut hcx, &mut stable_hasher); - let h3 = stable_hasher.finish(); + let h2 = stable_hasher.finish(); - (Some(h1), Some(h2), Some(h3)) - }) - } else { - (None, None, None) - } + // hash lints emitted during ast lowering + let mut stable_hasher = StableHasher::new(); + delayed_lints.hash_stable(&mut hcx, &mut stable_hasher); + let h3 = stable_hasher.finish(); + + (Some(h1), Some(h2), Some(h3)) + }) } } From d3e597a1322575dd15ede6a032402488fdc6161d Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 23:06:48 +1000 Subject: [PATCH 0355/1134] Return a struct with named fields from `hash_owner_nodes` --- compiler/rustc_ast_lowering/src/lib.rs | 2 +- compiler/rustc_middle/src/hir/mod.rs | 22 +++++++++++++++++++--- compiler/rustc_middle/src/ty/context.rs | 2 +- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 189c82b614c2..d097e3cbaa82 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -675,7 +675,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let bodies = SortedMap::from_presorted_elements(bodies); // Don't hash unless necessary, because it's expensive. - let (opt_hash_including_bodies, attrs_hash, delayed_lints_hash) = + let rustc_middle::hir::Hashes { opt_hash_including_bodies, attrs_hash, delayed_lints_hash } = self.tcx.hash_owner_nodes(node, &bodies, &attrs, &delayed_lints, define_opaque); let num_nodes = self.item_local_id_counter.as_usize(); let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes); diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index a928703542fd..67bc89692ff7 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -174,9 +174,13 @@ impl<'tcx> TyCtxt<'tcx> { attrs: &SortedMap, delayed_lints: &[DelayedLint], define_opaque: Option<&[(Span, LocalDefId)]>, - ) -> (Option, Option, Option) { + ) -> Hashes { if !self.needs_crate_hash() { - return (None, None, None); + return Hashes { + opt_hash_including_bodies: None, + attrs_hash: None, + delayed_lints_hash: None, + }; } self.with_stable_hashing_context(|mut hcx| { @@ -199,11 +203,23 @@ impl<'tcx> TyCtxt<'tcx> { delayed_lints.hash_stable(&mut hcx, &mut stable_hasher); let h3 = stable_hasher.finish(); - (Some(h1), Some(h2), Some(h3)) + Hashes { + opt_hash_including_bodies: Some(h1), + attrs_hash: Some(h2), + delayed_lints_hash: Some(h3), + } }) } } +/// Hashes computed by [`TyCtxt::hash_owner_nodes`] if necessary. +#[derive(Clone, Copy, Debug)] +pub struct Hashes { + pub opt_hash_including_bodies: Option, + pub attrs_hash: Option, + pub delayed_lints_hash: Option, +} + pub fn provide(providers: &mut Providers) { providers.hir_crate_items = map::hir_crate_items; providers.crate_hash = map::crate_hash; diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index f4ee3d7971c3..d583c5d496ed 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1381,7 +1381,7 @@ impl<'tcx> TyCtxtFeed<'tcx, LocalDefId> { let bodies = Default::default(); let attrs = hir::AttributeMap::EMPTY; - let (opt_hash_including_bodies, _, _) = + let rustc_middle::hir::Hashes { opt_hash_including_bodies, .. } = self.tcx.hash_owner_nodes(node, &bodies, &attrs.map, &[], attrs.define_opaque); let node = node.into(); self.opt_hir_owner_nodes(Some(self.tcx.arena.alloc(hir::OwnerNodes { From 5ebb0dd7da0c1c0fe6c6505fc1387d8805fd8a6d Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sat, 2 Aug 2025 19:01:07 +0500 Subject: [PATCH 0356/1134] update doc --- src/doc/rustc-dev-guide/src/appendix/humorust.md | 2 +- src/doc/rustc-dev-guide/src/tests/directives.md | 2 +- src/doc/rustc-dev-guide/src/tests/ui.md | 8 +++----- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/appendix/humorust.md b/src/doc/rustc-dev-guide/src/appendix/humorust.md index 6df3b212aa77..8681512ed56a 100644 --- a/src/doc/rustc-dev-guide/src/appendix/humorust.md +++ b/src/doc/rustc-dev-guide/src/appendix/humorust.md @@ -3,7 +3,7 @@ What's a project without a sense of humor? And frankly some of these are enlightening? -- [Weird exprs test](https://github.com/rust-lang/rust/blob/master/tests/ui/weird-exprs.rs) +- [Weird exprs test](https://github.com/rust-lang/rust/blob/master/tests/ui/expr/weird-exprs.rs) - [Ferris Rap](https://fitzgen.com/2018/12/13/rust-raps.html) - [The Genesis of Generic Germination](https://github.com/rust-lang/rust/pull/53645#issue-210543221) - [The Bastion of the Turbofish test](https://github.com/rust-lang/rust/blob/79d8a0fcefa5134db2a94739b1d18daa01fc6e9f/src/test/ui/bastion-of-the-turbofish.rs) diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index 6fff021b0b12..bda95e4dfbcc 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -359,7 +359,7 @@ described below: - Example: `x86_64-unknown-linux-gnu` See -[`tests/ui/commandline-argfile.rs`](https://github.com/rust-lang/rust/blob/master/tests/ui/argfile/commandline-argfile.rs) +[`tests/ui/argfile/commandline-argfile.rs`](https://github.com/rust-lang/rust/blob/master/tests/ui/argfile/commandline-argfile.rs) for an example of a test that uses this substitution. [output normalization]: ui.md#normalization diff --git a/src/doc/rustc-dev-guide/src/tests/ui.md b/src/doc/rustc-dev-guide/src/tests/ui.md index 782f78d76148..eecd72695d95 100644 --- a/src/doc/rustc-dev-guide/src/tests/ui.md +++ b/src/doc/rustc-dev-guide/src/tests/ui.md @@ -25,9 +25,9 @@ If you need to work with `#![no_std]` cross-compiling tests, consult the ## General structure of a test -A test consists of a Rust source file located anywhere in the `tests/ui` -directory, but they should be placed in a suitable sub-directory. For example, -[`tests/ui/hello.rs`] is a basic hello-world test. +A test consists of a Rust source file located in the `tests/ui` directory. +**Tests must be placed in the appropriate subdirectory** based on their purpose +and testing category - placing tests directly in `tests/ui` is not permitted. Compiletest will use `rustc` to compile the test, and compare the output against the expected output which is stored in a `.stdout` or `.stderr` file located @@ -46,8 +46,6 @@ pass/fail expectations](#controlling-passfail-expectations). By default, a test is built as an executable binary. If you need a different crate type, you can use the `#![crate_type]` attribute to set it as needed. -[`tests/ui/hello.rs`]: https://github.com/rust-lang/rust/blob/master/tests/ui/hello.rs - ## Output comparison UI tests store the expected output from the compiler in `.stderr` and `.stdout` From e3a6469ac09ad7086049fc9ce3b0439432f29cea Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Fri, 1 Aug 2025 12:28:23 -0400 Subject: [PATCH 0357/1134] Implement SIMD funnel shifts --- src/intrinsic/simd.rs | 78 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/src/intrinsic/simd.rs b/src/intrinsic/simd.rs index 350915a277e3..6748e1a41257 100644 --- a/src/intrinsic/simd.rs +++ b/src/intrinsic/simd.rs @@ -206,6 +206,28 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( ); } + #[cfg(feature = "master")] + if name == sym::simd_funnel_shl { + return Ok(simd_funnel_shift( + bx, + args[0].immediate(), + args[1].immediate(), + args[2].immediate(), + true, + )); + } + + #[cfg(feature = "master")] + if name == sym::simd_funnel_shr { + return Ok(simd_funnel_shift( + bx, + args[0].immediate(), + args[1].immediate(), + args[2].immediate(), + false, + )); + } + if name == sym::simd_bswap { return Ok(simd_bswap(bx, args[0].immediate())); } @@ -1434,3 +1456,59 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( unimplemented!("simd {}", name); } + +#[cfg(feature = "master")] +fn simd_funnel_shift<'a, 'gcc, 'tcx>( + bx: &mut Builder<'a, 'gcc, 'tcx>, + a: RValue<'gcc>, + b: RValue<'gcc>, + shift: RValue<'gcc>, + shift_left: bool, +) -> RValue<'gcc> { + let a_type = a.get_type(); + let vector_type = a_type.unqualified().dyncast_vector().expect("vector type"); + let num_units = vector_type.get_num_units(); + let elem_type = vector_type.get_element_type(); + + let (new_int_type, int_shift_val, int_mask) = if elem_type.is_compatible_with(bx.u8_type) { + (bx.u16_type, 8, u8::MAX as u64) + } else if elem_type.is_compatible_with(bx.u16_type) { + (bx.u32_type, 16, u16::MAX as u64) + } else if elem_type.is_compatible_with(bx.u32_type) { + (bx.u64_type, 32, u32::MAX as u64) + } else if elem_type.is_compatible_with(bx.u64_type) { + (bx.u128_type, 64, u64::MAX) + } else if elem_type.is_compatible_with(bx.i8_type) { + (bx.i16_type, 8, u8::MAX as u64) + } else if elem_type.is_compatible_with(bx.i16_type) { + (bx.i32_type, 16, u16::MAX as u64) + } else if elem_type.is_compatible_with(bx.i32_type) { + (bx.i64_type, 32, u32::MAX as u64) + } else if elem_type.is_compatible_with(bx.i64_type) { + (bx.i128_type, 64, u64::MAX) + } else { + unimplemented!("funnel shift on {:?}", elem_type); + }; + + let int_mask = bx.context.new_rvalue_from_long(new_int_type, int_mask as i64); + let int_shift_val = bx.context.new_rvalue_from_int(new_int_type, int_shift_val); + let mut elements = vec![]; + for i in 0..num_units { + let index = bx.context.new_rvalue_from_int(bx.int_type, i as i32); + let a_val = bx.context.new_vector_access(None, a, index).to_rvalue(); + let a_val = bx.context.new_cast(None, a_val, new_int_type); + let b_val = bx.context.new_vector_access(None, b, index).to_rvalue(); + let b_val = bx.context.new_cast(None, b_val, new_int_type); + let shift_val = bx.context.new_vector_access(None, shift, index).to_rvalue(); + let shift_val = bx.context.new_cast(None, shift_val, new_int_type); + let mut val = a_val << int_shift_val | b_val; + if shift_left { + val = (val << shift_val) >> int_shift_val; + } else { + val = (val >> shift_val) & int_mask; + } + let val = bx.context.new_cast(None, val, elem_type); + elements.push(val); + } + bx.context.new_rvalue_from_vector(None, a_type, &elements) +} From f87e829d6e8782ac719acb38236d4eeae06f62dd Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sat, 2 Aug 2025 20:36:45 +0500 Subject: [PATCH 0358/1134] update flags for consistency --- compiler/rustc_codegen_ssa/src/back/link.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 162fbf3d6e24..b69fbf61185d 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -1011,11 +1011,12 @@ fn link_natively( (Strip::Debuginfo, _) => { strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"]) } - // Per the manpage, `-x` is the maximum safe strip level for dynamic libraries. (#93988) + + // Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988) ( Strip::Symbols, CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib, - ) => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]), + ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]), (Strip::Symbols, _) => { strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"]) } From 8ca798616acbbb87f80d74bd16c0e753a3cadc33 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sat, 2 Aug 2025 21:26:39 +0500 Subject: [PATCH 0359/1134] update links --- compiler/rustc_hir_typeck/src/method/confirm.rs | 2 +- compiler/rustc_hir_typeck/src/method/probe.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 8d9f7eaf1774..5a182dabebb8 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -116,7 +116,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // If there is a `Self: Sized` bound and `Self` is a trait object, it is possible that // something which derefs to `Self` actually implements the trait and the caller // wanted to make a static dispatch on it but forgot to import the trait. - // See test `tests/ui/issue-35976.rs`. + // See test `tests/ui/issues/issue-35976.rs`. // // In that case, we'll error anyway, but we'll also re-run the search with all traits // in scope, and if we find another method which can be used, we'll output an diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 1f3969bd93c3..3ca3b56b87e0 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -2051,7 +2051,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { /// probe. This will result in a pending obligation so when more type-info is available we can /// make the final decision. /// - /// Example (`tests/ui/method-two-trait-defer-resolution-1.rs`): + /// Example (`tests/ui/methods/method-two-trait-defer-resolution-1.rs`): /// /// ```ignore (illustrative) /// trait Foo { ... } From b8c16e47f4a2757992941a421423534be2dc8a87 Mon Sep 17 00:00:00 2001 From: Zihan Date: Sat, 2 Aug 2025 12:20:31 -0400 Subject: [PATCH 0360/1134] fix: `option_if_let_else` keep deref op if the inner expr is a raw pointer closes rust-clippy/issues/15379 Signed-off-by: Zihan --- clippy_lints/src/option_if_let_else.rs | 3 ++- tests/ui/option_if_let_else.fixed | 7 +++++++ tests/ui/option_if_let_else.rs | 7 +++++++ tests/ui/option_if_let_else.stderr | 8 +++++++- 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/option_if_let_else.rs b/clippy_lints/src/option_if_let_else.rs index 9487cec87efb..6c0bf2ad1545 100644 --- a/clippy_lints/src/option_if_let_else.rs +++ b/clippy_lints/src/option_if_let_else.rs @@ -127,7 +127,8 @@ fn try_get_option_occurrence<'tcx>( if_else: &'tcx Expr<'_>, ) -> Option { let cond_expr = match expr.kind { - ExprKind::Unary(UnOp::Deref, inner_expr) | ExprKind::AddrOf(_, _, inner_expr) => inner_expr, + ExprKind::AddrOf(_, _, inner_expr) => inner_expr, + ExprKind::Unary(UnOp::Deref, inner_expr) if !cx.typeck_results().expr_ty(inner_expr).is_raw_ptr() => inner_expr, _ => expr, }; let (inner_pat, is_result) = try_get_inner_pat_and_is_result(cx, pat)?; diff --git a/tests/ui/option_if_let_else.fixed b/tests/ui/option_if_let_else.fixed index fe3ac9e8f92c..c418a358dcb3 100644 --- a/tests/ui/option_if_let_else.fixed +++ b/tests/ui/option_if_let_else.fixed @@ -302,3 +302,10 @@ mod issue11059 { if let Some(o) = o { o } else { &S } } } + +fn issue15379() { + let opt = Some(0usize); + let opt_raw_ptr = &opt as *const Option; + let _ = unsafe { (*opt_raw_ptr).map_or(1, |o| o) }; + //~^ option_if_let_else +} diff --git a/tests/ui/option_if_let_else.rs b/tests/ui/option_if_let_else.rs index 5b7498bc8e23..4c3e4be3caeb 100644 --- a/tests/ui/option_if_let_else.rs +++ b/tests/ui/option_if_let_else.rs @@ -365,3 +365,10 @@ mod issue11059 { if let Some(o) = o { o } else { &S } } } + +fn issue15379() { + let opt = Some(0usize); + let opt_raw_ptr = &opt as *const Option; + let _ = unsafe { if let Some(o) = *opt_raw_ptr { o } else { 1 } }; + //~^ option_if_let_else +} diff --git a/tests/ui/option_if_let_else.stderr b/tests/ui/option_if_let_else.stderr index 9eb41f81a539..514ecca41142 100644 --- a/tests/ui/option_if_let_else.stderr +++ b/tests/ui/option_if_let_else.stderr @@ -334,5 +334,11 @@ error: use Option::map_or_else instead of an if let/else LL | let mut _hm = if let Some(hm) = &opt { hm.clone() } else { new_map!() }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `opt.as_ref().map_or_else(|| new_map!(), |hm| hm.clone())` -error: aborting due to 25 previous errors +error: use Option::map_or instead of an if let/else + --> tests/ui/option_if_let_else.rs:372:22 + | +LL | let _ = unsafe { if let Some(o) = *opt_raw_ptr { o } else { 1 } }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `(*opt_raw_ptr).map_or(1, |o| o)` + +error: aborting due to 26 previous errors From e314bfaad38f5958c82fac6af4f4f34dcb2dc94f Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Sat, 2 Aug 2025 19:13:07 +0900 Subject: [PATCH 0361/1134] Migrate `generate_delegate_methods` assist to use `SyntaxEditor` --- .../src/handlers/add_missing_impl_members.rs | 4 +- .../src/handlers/generate_delegate_methods.rs | 58 ++++++++++++------- .../ide-assists/src/handlers/generate_impl.rs | 1 - .../ide-assists/src/handlers/generate_new.rs | 4 +- .../replace_derive_with_manual_impl.rs | 6 +- .../crates/syntax/src/ast/make.rs | 4 +- 6 files changed, 41 insertions(+), 36 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_impl_members.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_impl_members.rs index 7f1e7ccb4487..11201afb8a7f 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_impl_members.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_impl_members.rs @@ -183,13 +183,11 @@ fn add_missing_impl_members_inner( .clone() .into_iter() .chain(other_items.iter().cloned()) - .map(either::Either::Right) .collect::>(); let mut editor = edit.make_editor(impl_def.syntax()); if let Some(assoc_item_list) = impl_def.assoc_item_list() { - let items = new_assoc_items.into_iter().filter_map(either::Either::right).collect(); - assoc_item_list.add_items(&mut editor, items); + assoc_item_list.add_items(&mut editor, new_assoc_items); } else { let assoc_item_list = make::assoc_item_list(Some(new_assoc_items)).clone_for_update(); editor.insert_all( diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_delegate_methods.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_delegate_methods.rs index 606389807604..2c81e2883a34 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_delegate_methods.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_delegate_methods.rs @@ -2,9 +2,11 @@ use hir::{HasCrate, HasVisibility}; use ide_db::{FxHashSet, path_transform::PathTransform}; use syntax::{ ast::{ - self, AstNode, HasGenericParams, HasName, HasVisibility as _, edit_in_place::Indent, make, + self, AstNode, HasGenericParams, HasName, HasVisibility as _, + edit::{AstNodeEdit, IndentLevel}, + make, }, - ted, + syntax_editor::Position, }; use crate::{ @@ -165,54 +167,66 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<' is_unsafe, is_gen, ) - .clone_for_update(); - - // Get the impl to update, or create one if we need to. - let impl_def = match impl_def { - Some(impl_def) => edit.make_mut(impl_def), + .indent(IndentLevel(1)); + let item = ast::AssocItem::Fn(f.clone()); + + let mut editor = edit.make_editor(strukt.syntax()); + let fn_: Option = match impl_def { + Some(impl_def) => match impl_def.assoc_item_list() { + Some(assoc_item_list) => { + let item = item.indent(IndentLevel::from_node(impl_def.syntax())); + assoc_item_list.add_items(&mut editor, vec![item.clone()]); + Some(item) + } + None => { + let assoc_item_list = make::assoc_item_list(Some(vec![item])); + editor.insert( + Position::last_child_of(impl_def.syntax()), + assoc_item_list.syntax(), + ); + assoc_item_list.assoc_items().next() + } + }, None => { let name = &strukt_name.to_string(); let ty_params = strukt.generic_param_list(); let ty_args = ty_params.as_ref().map(|it| it.to_generic_args()); let where_clause = strukt.where_clause(); + let assoc_item_list = make::assoc_item_list(Some(vec![item])); let impl_def = make::impl_( ty_params, ty_args, make::ty_path(make::ext::ident_path(name)), where_clause, - None, + Some(assoc_item_list), ) .clone_for_update(); // Fixup impl_def indentation let indent = strukt.indent_level(); - impl_def.reindent_to(indent); + let impl_def = impl_def.indent(indent); // Insert the impl block. let strukt = edit.make_mut(strukt.clone()); - ted::insert_all( - ted::Position::after(strukt.syntax()), + editor.insert_all( + Position::after(strukt.syntax()), vec![ make::tokens::whitespace(&format!("\n\n{indent}")).into(), impl_def.syntax().clone().into(), ], ); - - impl_def + impl_def.assoc_item_list().and_then(|list| list.assoc_items().next()) } }; - // Fixup function indentation. - // FIXME: Should really be handled by `AssocItemList::add_item` - f.reindent_to(impl_def.indent_level() + 1); - - let assoc_items = impl_def.get_or_create_assoc_item_list(); - assoc_items.add_item(f.clone().into()); - - if let Some(cap) = ctx.config.snippet_cap { - edit.add_tabstop_before(cap, f) + if let Some(cap) = ctx.config.snippet_cap + && let Some(fn_) = fn_ + { + let tabstop = edit.make_tabstop_before(cap); + editor.add_annotation(fn_.syntax(), tabstop); } + edit.add_file_edits(ctx.vfs_file_id(), editor); }, )?; } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_impl.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_impl.rs index fcb81d239ff3..b38ee6f7dce8 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_impl.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_impl.rs @@ -201,7 +201,6 @@ pub(crate) fn generate_impl_trait(acc: &mut Assists, ctx: &AssistContext<'_>) -> &impl_, &target_scope, ); - let assoc_items = assoc_items.into_iter().map(either::Either::Right).collect(); let assoc_item_list = make::assoc_item_list(Some(assoc_items)); make_impl_(Some(assoc_item_list)) }; diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_new.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_new.rs index 5bda1226cda3..351f134612f0 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_new.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_new.rs @@ -168,7 +168,7 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option ); fn_.syntax().clone() } else { - let items = vec![either::Either::Right(ast::AssocItem::Fn(fn_))]; + let items = vec![ast::AssocItem::Fn(fn_)]; let list = make::assoc_item_list(Some(items)); editor.insert(Position::after(impl_def.syntax()), list.syntax()); list.syntax().clone() @@ -176,7 +176,7 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option } else { // Generate a new impl to add the method to let indent_level = strukt.indent_level(); - let body = vec![either::Either::Right(ast::AssocItem::Fn(fn_))]; + let body = vec![ast::AssocItem::Fn(fn_)]; let list = make::assoc_item_list(Some(body)); let impl_def = generate_impl_with_item(&ast::Adt::Struct(strukt.clone()), Some(list)); diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs index 45bb6ce9129c..175f26131705 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs @@ -221,11 +221,7 @@ fn impl_def_from_trait( } else { Some(first.clone()) }; - let items = first_item - .into_iter() - .chain(other.iter().cloned()) - .map(either::Either::Right) - .collect(); + let items = first_item.into_iter().chain(other.iter().cloned()).collect(); make::assoc_item_list(Some(items)) } else { make::assoc_item_list(None) diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/make.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/make.rs index 2a7b51c3c248..daeb79cf081d 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/make.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/make.rs @@ -229,9 +229,7 @@ pub fn ty_fn_ptr>( } } -pub fn assoc_item_list( - body: Option>>, -) -> ast::AssocItemList { +pub fn assoc_item_list(body: Option>) -> ast::AssocItemList { let is_break_braces = body.is_some(); let body_newline = if is_break_braces { "\n".to_owned() } else { String::new() }; let body_indent = if is_break_braces { " ".to_owned() } else { String::new() }; From 1eb9b134f52ef9a3ffa28075bc1a1515bcfbaa8c Mon Sep 17 00:00:00 2001 From: Christopher Hotchkiss Date: Sat, 2 Aug 2025 10:46:29 -0700 Subject: [PATCH 0362/1134] Change visibility of Args new function Currently the Args new function is scope constrained to pub(super) but this stops me from being able to construct Args structs in unit tests. --- library/std/src/sys/args/common.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/args/common.rs b/library/std/src/sys/args/common.rs index e787105a05a7..33f3794ee633 100644 --- a/library/std/src/sys/args/common.rs +++ b/library/std/src/sys/args/common.rs @@ -12,7 +12,7 @@ impl !Sync for Args {} impl Args { #[inline] - pub(super) fn new(args: Vec) -> Self { + pub fn new(args: Vec) -> Self { Args { iter: args.into_iter() } } } From ac34f3db819f99fcc06a54396d6531862d6f2fb1 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Thu, 31 Jul 2025 23:33:38 +0300 Subject: [PATCH 0363/1134] When renaming a parameter to `self`, change callers to use method call syntax --- .../rust-analyzer/crates/base-db/src/lib.rs | 3 +- .../crates/hir-expand/src/builtin/fn_macro.rs | 2 +- .../crates/hir-expand/src/files.rs | 10 ++ .../crates/hir-ty/src/test_db.rs | 2 +- .../rust-analyzer/crates/ide-db/src/lib.rs | 2 +- .../rust-analyzer/crates/ide-db/src/search.rs | 17 +- .../crates/ide-diagnostics/src/tests.rs | 2 +- .../rust-analyzer/crates/ide-ssr/src/lib.rs | 4 +- src/tools/rust-analyzer/crates/ide/src/lib.rs | 2 +- .../rust-analyzer/crates/ide/src/rename.rs | 161 +++++++++++++++++- .../crates/rust-analyzer/src/global_state.rs | 6 +- 11 files changed, 186 insertions(+), 25 deletions(-) diff --git a/src/tools/rust-analyzer/crates/base-db/src/lib.rs b/src/tools/rust-analyzer/crates/base-db/src/lib.rs index ad17f1730bef..b8eadb608fea 100644 --- a/src/tools/rust-analyzer/crates/base-db/src/lib.rs +++ b/src/tools/rust-analyzer/crates/base-db/src/lib.rs @@ -206,6 +206,7 @@ impl EditionedFileId { #[salsa_macros::input(debug)] pub struct FileText { + #[returns(ref)] pub text: Arc, pub file_id: vfs::FileId, } @@ -357,7 +358,7 @@ fn parse(db: &dyn RootQueryDb, file_id: EditionedFileId) -> Parse Option<&[SyntaxError]> { diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs b/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs index 58ab7f470c40..ec3446137616 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs @@ -890,7 +890,7 @@ fn include_str_expand( }; let text = db.file_text(file_id.file_id(db)); - let text = &*text.text(db); + let text = &**text.text(db); ExpandResult::ok(quote!(call_site =>#text)) } diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/files.rs b/src/tools/rust-analyzer/crates/hir-expand/src/files.rs index 6730b337d356..a7f3e27a4553 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/files.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/files.rs @@ -99,6 +99,16 @@ impl FileRange { pub fn into_file_id(self, db: &dyn ExpandDatabase) -> FileRangeWrapper { FileRangeWrapper { file_id: self.file_id.file_id(db), range: self.range } } + + #[inline] + pub fn file_text(self, db: &dyn ExpandDatabase) -> &triomphe::Arc { + db.file_text(self.file_id.file_id(db)).text(db) + } + + #[inline] + pub fn text(self, db: &dyn ExpandDatabase) -> &str { + &self.file_text(db)[self.range] + } } /// `AstId` points to an AST node in any file. diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/test_db.rs b/src/tools/rust-analyzer/crates/hir-ty/src/test_db.rs index b5de0e52f5b6..775136dc0cbf 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/test_db.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/test_db.rs @@ -149,7 +149,7 @@ impl TestDB { .into_iter() .filter_map(|file_id| { let text = self.file_text(file_id.file_id(self)); - let annotations = extract_annotations(&text.text(self)); + let annotations = extract_annotations(text.text(self)); if annotations.is_empty() { return None; } diff --git a/src/tools/rust-analyzer/crates/ide-db/src/lib.rs b/src/tools/rust-analyzer/crates/ide-db/src/lib.rs index c94be7e164e2..49f7f63a04a4 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/lib.rs @@ -244,7 +244,7 @@ pub trait LineIndexDatabase: base_db::RootQueryDb { fn line_index(db: &dyn LineIndexDatabase, file_id: FileId) -> Arc { let text = db.file_text(file_id).text(db); - Arc::new(LineIndex::new(&text)) + Arc::new(LineIndex::new(text)) } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] diff --git a/src/tools/rust-analyzer/crates/ide-db/src/search.rs b/src/tools/rust-analyzer/crates/ide-db/src/search.rs index 4dd64229d274..abd4dc8300b3 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/search.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/search.rs @@ -487,9 +487,9 @@ impl<'a> FindUsages<'a> { scope.entries.iter().map(|(&file_id, &search_range)| { let text = db.file_text(file_id.file_id(db)).text(db); let search_range = - search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(&*text))); + search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(&**text))); - (text, file_id, search_range) + (text.clone(), file_id, search_range) }) } @@ -854,14 +854,7 @@ impl<'a> FindUsages<'a> { &finder, name, is_possibly_self.into_iter().map(|position| { - ( - self.sema - .db - .file_text(position.file_id.file_id(self.sema.db)) - .text(self.sema.db), - position.file_id, - position.range, - ) + (position.file_text(self.sema.db).clone(), position.file_id, position.range) }), |path, name_position| { let has_self = path @@ -1067,12 +1060,12 @@ impl<'a> FindUsages<'a> { let file_text = sema.db.file_text(file_id.file_id(self.sema.db)); let text = file_text.text(sema.db); let search_range = - search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(&*text))); + search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(&**text))); let tree = LazyCell::new(|| sema.parse(file_id).syntax().clone()); let finder = &Finder::new("self"); - for offset in Self::match_indices(&text, finder, search_range) { + for offset in Self::match_indices(text, finder, search_range) { for name_ref in Self::find_nodes(sema, "self", file_id, &tree, offset) .filter_map(ast::NameRef::cast) { diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/tests.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/tests.rs index 4e4bd47e1c2f..181993154e59 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/tests.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/tests.rs @@ -229,7 +229,7 @@ pub(crate) fn check_diagnostics_with_config( let line_index = db.line_index(file_id); let mut actual = annotations.remove(&file_id).unwrap_or_default(); - let mut expected = extract_annotations(&db.file_text(file_id).text(&db)); + let mut expected = extract_annotations(db.file_text(file_id).text(&db)); expected.sort_by_key(|(range, s)| (range.start(), s.clone())); actual.sort_by_key(|(range, s)| (range.start(), s.clone())); // FIXME: We should panic on duplicates instead, but includes currently cause us to report diff --git a/src/tools/rust-analyzer/crates/ide-ssr/src/lib.rs b/src/tools/rust-analyzer/crates/ide-ssr/src/lib.rs index 138af22089eb..43ad12c1f699 100644 --- a/src/tools/rust-analyzer/crates/ide-ssr/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide-ssr/src/lib.rs @@ -186,7 +186,7 @@ impl<'db> MatchFinder<'db> { replacing::matches_to_edit( self.sema.db, &matches, - &self.sema.db.file_text(file_id).text(self.sema.db), + self.sema.db.file_text(file_id).text(self.sema.db), &self.rules, ), ) @@ -228,7 +228,7 @@ impl<'db> MatchFinder<'db> { let file = self.sema.parse(file_id); let mut res = Vec::new(); let file_text = self.sema.db.file_text(file_id.file_id(self.sema.db)).text(self.sema.db); - let mut remaining_text = &*file_text; + let mut remaining_text = &**file_text; let mut base = 0; let len = snippet.len() as u32; while let Some(offset) = remaining_text.find(snippet) { diff --git a/src/tools/rust-analyzer/crates/ide/src/lib.rs b/src/tools/rust-analyzer/crates/ide/src/lib.rs index b3b8deb61fc0..98877482ed86 100644 --- a/src/tools/rust-analyzer/crates/ide/src/lib.rs +++ b/src/tools/rust-analyzer/crates/ide/src/lib.rs @@ -299,7 +299,7 @@ impl Analysis { /// Gets the text of the source file. pub fn file_text(&self, file_id: FileId) -> Cancellable> { - self.with_db(|db| SourceDatabase::file_text(db, file_id).text(db)) + self.with_db(|db| SourceDatabase::file_text(db, file_id).text(db).clone()) } /// Gets the syntax tree of the file. diff --git a/src/tools/rust-analyzer/crates/ide/src/rename.rs b/src/tools/rust-analyzer/crates/ide/src/rename.rs index 634edaa5edaf..aea4ae0fd970 100644 --- a/src/tools/rust-analyzer/crates/ide/src/rename.rs +++ b/src/tools/rust-analyzer/crates/ide/src/rename.rs @@ -13,8 +13,11 @@ use ide_db::{ }; use itertools::Itertools; use std::fmt::Write; -use stdx::{always, never}; -use syntax::{AstNode, SyntaxKind, SyntaxNode, TextRange, TextSize, ast}; +use stdx::{always, format_to, never}; +use syntax::{ + AstNode, SyntaxKind, SyntaxNode, TextRange, TextSize, + ast::{self, HasArgList, prec::ExprPrecedence}, +}; use ide_db::text_edit::TextEdit; @@ -331,6 +334,85 @@ fn find_definitions( } } +fn transform_assoc_fn_into_method_call( + sema: &Semantics<'_, RootDatabase>, + source_change: &mut SourceChange, + f: hir::Function, +) { + let calls = Definition::Function(f).usages(sema).all(); + for (file_id, calls) in calls { + for call in calls { + let Some(fn_name) = call.name.as_name_ref() else { continue }; + let Some(path) = fn_name.syntax().parent().and_then(ast::PathSegment::cast) else { + continue; + }; + let path = path.parent_path(); + // The `PathExpr` is the direct parent, above it is the `CallExpr`. + let Some(call) = + path.syntax().parent().and_then(|it| ast::CallExpr::cast(it.parent()?)) + else { + continue; + }; + + let Some(arg_list) = call.arg_list() else { continue }; + let mut args = arg_list.args(); + let Some(mut self_arg) = args.next() else { continue }; + let second_arg = args.next(); + + // Strip (de)references, as they will be taken automatically by auto(de)ref. + loop { + let self_ = match &self_arg { + ast::Expr::RefExpr(self_) => self_.expr(), + ast::Expr::ParenExpr(self_) => self_.expr(), + ast::Expr::PrefixExpr(self_) + if self_.op_kind() == Some(ast::UnaryOp::Deref) => + { + self_.expr() + } + _ => break, + }; + self_arg = match self_ { + Some(it) => it, + None => break, + }; + } + + let self_needs_parens = + self_arg.precedence().needs_parentheses_in(ExprPrecedence::Postfix); + + let replace_start = path.syntax().text_range().start(); + let replace_end = match second_arg { + Some(second_arg) => second_arg.syntax().text_range().start(), + None => arg_list + .r_paren_token() + .map(|it| it.text_range().start()) + .unwrap_or_else(|| arg_list.syntax().text_range().end()), + }; + let replace_range = TextRange::new(replace_start, replace_end); + + let Some(macro_mapped_self) = sema.original_range_opt(self_arg.syntax()) else { + continue; + }; + let mut replacement = String::new(); + if self_needs_parens { + replacement.push('('); + } + replacement.push_str(macro_mapped_self.text(sema.db)); + if self_needs_parens { + replacement.push(')'); + } + replacement.push('.'); + format_to!(replacement, "{fn_name}"); + replacement.push('('); + + source_change.insert_source_edit( + file_id.file_id(sema.db), + TextEdit::replace(replace_range, replacement), + ); + } + } +} + fn rename_to_self( sema: &Semantics<'_, RootDatabase>, local: hir::Local, @@ -408,6 +490,7 @@ fn rename_to_self( file_id.original_file(sema.db).file_id(sema.db), TextEdit::replace(param_source.syntax().text_range(), String::from(self_param)), ); + transform_assoc_fn_into_method_call(sema, &mut source_change, fn_def); Ok(source_change) } @@ -3412,4 +3495,78 @@ fn other_place() { Quux::Bar$0; } "#, ); } + + #[test] + fn rename_to_self_callers() { + check( + "self", + r#" +//- minicore: add +struct Foo; +impl core::ops::Add for Foo { + type Target = Foo; + fn add(self, _: Self) -> Foo { Foo } +} + +impl Foo { + fn foo(th$0is: &Self) {} +} + +fn bar(v: &Foo) { + Foo::foo(v); +} + +fn baz() { + Foo::foo(&Foo); + Foo::foo(Foo + Foo); +} + "#, + r#" +struct Foo; +impl core::ops::Add for Foo { + type Target = Foo; + fn add(self, _: Self) -> Foo { Foo } +} + +impl Foo { + fn foo(&self) {} +} + +fn bar(v: &Foo) { + v.foo(); +} + +fn baz() { + Foo.foo(); + (Foo + Foo).foo(); +} + "#, + ); + // Multiple arguments: + check( + "self", + r#" +struct Foo; + +impl Foo { + fn foo(th$0is: &Self, v: i32) {} +} + +fn bar(v: Foo) { + Foo::foo(&v, 123); +} + "#, + r#" +struct Foo; + +impl Foo { + fn foo(&self, v: i32) {} +} + +fn bar(v: Foo) { + v.foo(123); +} + "#, + ); + } } diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/global_state.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/global_state.rs index 3171bdd36178..2f1afba3634e 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/global_state.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/global_state.rs @@ -448,7 +448,7 @@ impl GlobalState { tracing::info!(%vfs_path, ?change_kind, "Processing rust-analyzer.toml changes"); if vfs_path.as_path() == user_config_abs_path { tracing::info!(%vfs_path, ?change_kind, "Use config rust-analyzer.toml changes"); - change.change_user_config(Some(db.file_text(file_id).text(db))); + change.change_user_config(Some(db.file_text(file_id).text(db).clone())); } // If change has been made to a ratoml file that @@ -462,14 +462,14 @@ impl GlobalState { change.change_workspace_ratoml( source_root_id, vfs_path.clone(), - Some(db.file_text(file_id).text(db)), + Some(db.file_text(file_id).text(db).clone()), ) } else { tracing::info!(%vfs_path, ?source_root_id, "crate rust-analyzer.toml changes"); change.change_ratoml( source_root_id, vfs_path.clone(), - Some(db.file_text(file_id).text(db)), + Some(db.file_text(file_id).text(db).clone()), ) }; From bc177055f748d87f358fc360ba19932ca79b7c68 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 Aug 2025 19:19:17 +0000 Subject: [PATCH 0364/1134] Do not record derived impl def-id for dead code. --- compiler/rustc_middle/src/query/mod.rs | 5 ++--- compiler/rustc_passes/src/dead.rs | 23 +++++++++-------------- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 2941808e806f..a45895765945 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1178,11 +1178,10 @@ rustc_queries! { /// Return the live symbols in the crate for dead code check. /// - /// The second return value maps from ADTs to ignored derived traits (e.g. Debug and Clone) and - /// their respective impl (i.e., part of the derive macro) + /// The second return value maps from ADTs to ignored derived traits (e.g. Debug and Clone). query live_symbols_and_ignored_derived_traits(_: ()) -> &'tcx ( LocalDefIdSet, - LocalDefIdMap> + LocalDefIdMap>, ) { arena_cache desc { "finding live symbols in crate" } diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index a90d1af87ca1..f8d1ef298820 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -84,7 +84,7 @@ struct MarkSymbolVisitor<'tcx> { // maps from ADTs to ignored derived traits (e.g. Debug and Clone) // and the span of their respective impl (i.e., part of the derive // macro) - ignored_derived_traits: LocalDefIdMap>, + ignored_derived_traits: LocalDefIdMap>, } impl<'tcx> MarkSymbolVisitor<'tcx> { @@ -380,10 +380,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind() && let Some(adt_def_id) = adt_def.did().as_local() { - self.ignored_derived_traits - .entry(adt_def_id) - .or_default() - .insert((trait_of, impl_of)); + self.ignored_derived_traits.entry(adt_def_id).or_default().insert(trait_of); } return true; } @@ -881,7 +878,7 @@ fn create_and_seed_worklist( fn live_symbols_and_ignored_derived_traits( tcx: TyCtxt<'_>, (): (), -) -> (LocalDefIdSet, LocalDefIdMap>) { +) -> (LocalDefIdSet, LocalDefIdMap>) { let (worklist, struct_constructors, mut unsolved_items) = create_and_seed_worklist(tcx); let mut symbol_visitor = MarkSymbolVisitor { worklist, @@ -925,7 +922,7 @@ struct DeadItem { struct DeadVisitor<'tcx> { tcx: TyCtxt<'tcx>, live_symbols: &'tcx LocalDefIdSet, - ignored_derived_traits: &'tcx LocalDefIdMap>, + ignored_derived_traits: &'tcx LocalDefIdMap>, } enum ShouldWarnAboutField { @@ -1047,20 +1044,18 @@ impl<'tcx> DeadVisitor<'tcx> { let encl_def_id = get_parent_if_enum_variant(tcx, encl_def_id); let ignored_derived_impls = - if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) { + self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| { let trait_list = ign_traits .iter() - .map(|(trait_id, _)| self.tcx.item_name(*trait_id)) + .map(|trait_id| self.tcx.item_name(*trait_id)) .collect::>(); let trait_list_len = trait_list.len(); - Some(IgnoredDerivedImpls { + IgnoredDerivedImpls { name: self.tcx.item_name(encl_def_id.to_def_id()), trait_list: trait_list.into(), trait_list_len, - }) - } else { - None - }; + } + }); let enum_variants_with_same_name = dead_codes .iter() From 807d3406c215a9b3078e69ffc1a956b77f685ae9 Mon Sep 17 00:00:00 2001 From: Oneirical Date: Sun, 13 Jul 2025 16:06:48 -0400 Subject: [PATCH 0365/1134] Rehome tests/ui/issues/ tests [2/?] --- ...t-trait-item-reference-selection-26095.rs} | 2 +- .../cold-attribute-application-54044.rs} | 1 + .../cold-attribute-application-54044.stderr} | 6 ++--- .../autoderef-vec-box-fn-36786.rs} | 1 + .../borrow-checker-lifetime-error-46471.rs} | 1 + ...orrow-checker-lifetime-error-46471.stderr} | 2 +- ...tring-borrowing-pattern-matching-11869.rs} | 1 + .../u8-to-char-cast-9918.rs} | 1 + ...miscompile-metadata-invalidation-36023.rs} | 1 + ...herence-error-for-undefined-type-18058.rs} | 1 + ...nce-error-for-undefined-type-18058.stderr} | 2 +- ...lution-error-with-const-generics-77919.rs} | 1 + ...on-error-with-const-generics-77919.stderr} | 6 ++--- .../destructor-run-for-expression-4734.rs} | 1 + .../unnecessary-path-disambiguator-36116.rs} | 1 + .../collection-type-copy-behavior-12909.rs} | 1 + tests/ui/issues/auxiliary/issue-25185-2.rs | 3 --- tests/ui/issues/issue-25185.rs | 12 --------- tests/ui/issues/issue-32655.rs | 19 -------------- tests/ui/issues/issue-32655.stderr | 25 ------------------- .../iterator-type-inference-sum-15673.rs} | 1 + .../auxiliary/aux-25185-1.rs} | 0 tests/ui/linking/auxiliary/aux-25185-2.rs | 3 +++ ...ib-to-dylib-native-deps-inclusion-25185.rs | 13 ++++++++++ .../invalid-assignment-in-macro-26093.rs} | 1 + .../invalid-assignment-in-macro-26093.stderr} | 4 +-- ...ern-matching-in-function-argument-7519.rs} | 1 + ...-associated-type-in-trait-object-22434.rs} | 1 + ...ociated-type-in-trait-object-22434.stderr} | 2 +- ...ncorrect-self-type-in-trait-impl-48276.rs} | 1 + ...rect-self-type-in-trait-impl-48276.stderr} | 6 ++--- ...enthesized-type-parameters-error-32995.rs} | 1 + ...esized-type-parameters-error-32995.stderr} | 6 ++--- ...pace-conflict-in-unboxed-closure-18685.rs} | 2 +- 34 files changed, 52 insertions(+), 78 deletions(-) rename tests/ui/{issues/issue-26095.rs => associated-consts/constant-trait-item-reference-selection-26095.rs} (85%) rename tests/ui/{issues/issue-54044.rs => attributes/cold-attribute-application-54044.rs} (91%) rename tests/ui/{issues/issue-54044.stderr => attributes/cold-attribute-application-54044.stderr} (82%) rename tests/ui/{issues/issue-36786-resolve-call.rs => autoref-autoderef/autoderef-vec-box-fn-36786.rs} (77%) rename tests/ui/{issues/issue-46471-1.rs => borrowck/borrow-checker-lifetime-error-46471.rs} (75%) rename tests/ui/{issues/issue-46471-1.stderr => borrowck/borrow-checker-lifetime-error-46471.stderr} (87%) rename tests/ui/{issues/issue-11869.rs => borrowck/string-borrowing-pattern-matching-11869.rs} (81%) rename tests/ui/{issues/issue-9918.rs => cast/u8-to-char-cast-9918.rs} (59%) rename tests/ui/{issues/issue-36023.rs => codegen/llvm-miscompile-metadata-invalidation-36023.rs} (91%) rename tests/ui/{issues/issue-18058.rs => coherence/impl-coherence-error-for-undefined-type-18058.rs} (63%) rename tests/ui/{issues/issue-18058.stderr => coherence/impl-coherence-error-for-undefined-type-18058.stderr} (78%) rename tests/ui/{issues/issue-77919.rs => const-generics/trait-resolution-error-with-const-generics-77919.rs} (88%) rename tests/ui/{issues/issue-77919.stderr => const-generics/trait-resolution-error-with-const-generics-77919.stderr} (84%) rename tests/ui/{issues/issue-4734.rs => drop/destructor-run-for-expression-4734.rs} (94%) rename tests/ui/{issues/issue-36116.rs => generics/unnecessary-path-disambiguator-36116.rs} (86%) rename tests/ui/{issues/issue-12909.rs => inference/collection-type-copy-behavior-12909.rs} (90%) delete mode 100644 tests/ui/issues/auxiliary/issue-25185-2.rs delete mode 100644 tests/ui/issues/issue-25185.rs delete mode 100644 tests/ui/issues/issue-32655.rs delete mode 100644 tests/ui/issues/issue-32655.stderr rename tests/ui/{issues/issue-15673.rs => iterators/iterator-type-inference-sum-15673.rs} (76%) rename tests/ui/{issues/auxiliary/issue-25185-1.rs => linking/auxiliary/aux-25185-1.rs} (100%) create mode 100644 tests/ui/linking/auxiliary/aux-25185-2.rs create mode 100644 tests/ui/linking/rlib-to-dylib-native-deps-inclusion-25185.rs rename tests/ui/{issues/issue-26093.rs => macros/invalid-assignment-in-macro-26093.rs} (83%) rename tests/ui/{issues/issue-26093.stderr => macros/invalid-assignment-in-macro-26093.stderr} (90%) rename tests/ui/{issues/issue-7519-match-unit-in-arg.rs => pattern/unit-pattern-matching-in-function-argument-7519.rs} (72%) rename tests/ui/{issues/issue-22434.rs => type-alias/missing-associated-type-in-trait-object-22434.rs} (75%) rename tests/ui/{issues/issue-22434.stderr => type-alias/missing-associated-type-in-trait-object-22434.stderr} (84%) rename tests/ui/{issues/issue-48276.rs => typeck/incorrect-self-type-in-trait-impl-48276.rs} (93%) rename tests/ui/{issues/issue-48276.stderr => typeck/incorrect-self-type-in-trait-impl-48276.stderr} (83%) rename tests/ui/{issues/issue-32995-2.rs => typeck/parenthesized-type-parameters-error-32995.rs} (89%) rename tests/ui/{issues/issue-32995-2.stderr => typeck/parenthesized-type-parameters-error-32995.stderr} (79%) rename tests/ui/{issues/issue-18685.rs => unboxed-closures/self-param-space-conflict-in-unboxed-closure-18685.rs} (85%) diff --git a/tests/ui/issues/issue-26095.rs b/tests/ui/associated-consts/constant-trait-item-reference-selection-26095.rs similarity index 85% rename from tests/ui/issues/issue-26095.rs rename to tests/ui/associated-consts/constant-trait-item-reference-selection-26095.rs index 34c617dc495a..f0fe2db432bc 100644 --- a/tests/ui/issues/issue-26095.rs +++ b/tests/ui/associated-consts/constant-trait-item-reference-selection-26095.rs @@ -1,8 +1,8 @@ +// https://github.com/rust-lang/rust/issues/26095 //@ check-pass #![allow(dead_code)] #![allow(non_upper_case_globals)] - trait HasNumber { const Number: usize; } diff --git a/tests/ui/issues/issue-54044.rs b/tests/ui/attributes/cold-attribute-application-54044.rs similarity index 91% rename from tests/ui/issues/issue-54044.rs rename to tests/ui/attributes/cold-attribute-application-54044.rs index 809ea7a87dbe..2e644b91c077 100644 --- a/tests/ui/issues/issue-54044.rs +++ b/tests/ui/attributes/cold-attribute-application-54044.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/54044 #![deny(unused_attributes)] //~ NOTE lint level is defined here #[cold] diff --git a/tests/ui/issues/issue-54044.stderr b/tests/ui/attributes/cold-attribute-application-54044.stderr similarity index 82% rename from tests/ui/issues/issue-54044.stderr rename to tests/ui/attributes/cold-attribute-application-54044.stderr index 8bd94a041d0c..efdf5e0de527 100644 --- a/tests/ui/issues/issue-54044.stderr +++ b/tests/ui/attributes/cold-attribute-application-54044.stderr @@ -1,5 +1,5 @@ error: attribute should be applied to a function definition - --> $DIR/issue-54044.rs:3:1 + --> $DIR/cold-attribute-application-54044.rs:4:1 | LL | #[cold] | ^^^^^^^ @@ -9,13 +9,13 @@ LL | struct Foo; | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! note: the lint level is defined here - --> $DIR/issue-54044.rs:1:9 + --> $DIR/cold-attribute-application-54044.rs:2:9 | LL | #![deny(unused_attributes)] | ^^^^^^^^^^^^^^^^^ error: attribute should be applied to a function definition - --> $DIR/issue-54044.rs:9:5 + --> $DIR/cold-attribute-application-54044.rs:10:5 | LL | #[cold] | ^^^^^^^ diff --git a/tests/ui/issues/issue-36786-resolve-call.rs b/tests/ui/autoref-autoderef/autoderef-vec-box-fn-36786.rs similarity index 77% rename from tests/ui/issues/issue-36786-resolve-call.rs rename to tests/ui/autoref-autoderef/autoderef-vec-box-fn-36786.rs index de7b0e18d521..e16929bf48ac 100644 --- a/tests/ui/issues/issue-36786-resolve-call.rs +++ b/tests/ui/autoref-autoderef/autoderef-vec-box-fn-36786.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/36786 //@ run-pass // Ensure that types that rely on obligations are autoderefed // correctly diff --git a/tests/ui/issues/issue-46471-1.rs b/tests/ui/borrowck/borrow-checker-lifetime-error-46471.rs similarity index 75% rename from tests/ui/issues/issue-46471-1.rs rename to tests/ui/borrowck/borrow-checker-lifetime-error-46471.rs index aa161d40f702..020b02aa34df 100644 --- a/tests/ui/issues/issue-46471-1.rs +++ b/tests/ui/borrowck/borrow-checker-lifetime-error-46471.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/46471 fn main() { let y = { let mut z = 0; diff --git a/tests/ui/issues/issue-46471-1.stderr b/tests/ui/borrowck/borrow-checker-lifetime-error-46471.stderr similarity index 87% rename from tests/ui/issues/issue-46471-1.stderr rename to tests/ui/borrowck/borrow-checker-lifetime-error-46471.stderr index d45172239820..c90da5516200 100644 --- a/tests/ui/issues/issue-46471-1.stderr +++ b/tests/ui/borrowck/borrow-checker-lifetime-error-46471.stderr @@ -1,5 +1,5 @@ error[E0597]: `z` does not live long enough - --> $DIR/issue-46471-1.rs:4:9 + --> $DIR/borrow-checker-lifetime-error-46471.rs:5:9 | LL | let mut z = 0; | ----- binding `z` declared here diff --git a/tests/ui/issues/issue-11869.rs b/tests/ui/borrowck/string-borrowing-pattern-matching-11869.rs similarity index 81% rename from tests/ui/issues/issue-11869.rs rename to tests/ui/borrowck/string-borrowing-pattern-matching-11869.rs index dd752227bbec..fe3d1bf6e8a3 100644 --- a/tests/ui/issues/issue-11869.rs +++ b/tests/ui/borrowck/string-borrowing-pattern-matching-11869.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/11869 //@ check-pass #![allow(dead_code)] diff --git a/tests/ui/issues/issue-9918.rs b/tests/ui/cast/u8-to-char-cast-9918.rs similarity index 59% rename from tests/ui/issues/issue-9918.rs rename to tests/ui/cast/u8-to-char-cast-9918.rs index 017e833aefb2..2b8be1f0fc9b 100644 --- a/tests/ui/issues/issue-9918.rs +++ b/tests/ui/cast/u8-to-char-cast-9918.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/9918 //@ run-pass pub fn main() { diff --git a/tests/ui/issues/issue-36023.rs b/tests/ui/codegen/llvm-miscompile-metadata-invalidation-36023.rs similarity index 91% rename from tests/ui/issues/issue-36023.rs rename to tests/ui/codegen/llvm-miscompile-metadata-invalidation-36023.rs index 32e8af65c7d1..efa31a51881a 100644 --- a/tests/ui/issues/issue-36023.rs +++ b/tests/ui/codegen/llvm-miscompile-metadata-invalidation-36023.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/36023 //@ run-pass #![allow(unused_variables)] use std::ops::Deref; diff --git a/tests/ui/issues/issue-18058.rs b/tests/ui/coherence/impl-coherence-error-for-undefined-type-18058.rs similarity index 63% rename from tests/ui/issues/issue-18058.rs rename to tests/ui/coherence/impl-coherence-error-for-undefined-type-18058.rs index cced66717e1b..52baf9871c3b 100644 --- a/tests/ui/issues/issue-18058.rs +++ b/tests/ui/coherence/impl-coherence-error-for-undefined-type-18058.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/18058 impl Undefined {} //~^ ERROR cannot find type `Undefined` in this scope diff --git a/tests/ui/issues/issue-18058.stderr b/tests/ui/coherence/impl-coherence-error-for-undefined-type-18058.stderr similarity index 78% rename from tests/ui/issues/issue-18058.stderr rename to tests/ui/coherence/impl-coherence-error-for-undefined-type-18058.stderr index c880bb002919..07dce0b04fd5 100644 --- a/tests/ui/issues/issue-18058.stderr +++ b/tests/ui/coherence/impl-coherence-error-for-undefined-type-18058.stderr @@ -1,5 +1,5 @@ error[E0412]: cannot find type `Undefined` in this scope - --> $DIR/issue-18058.rs:1:6 + --> $DIR/impl-coherence-error-for-undefined-type-18058.rs:2:6 | LL | impl Undefined {} | ^^^^^^^^^ not found in this scope diff --git a/tests/ui/issues/issue-77919.rs b/tests/ui/const-generics/trait-resolution-error-with-const-generics-77919.rs similarity index 88% rename from tests/ui/issues/issue-77919.rs rename to tests/ui/const-generics/trait-resolution-error-with-const-generics-77919.rs index bf603314977f..5ab443422df7 100644 --- a/tests/ui/issues/issue-77919.rs +++ b/tests/ui/const-generics/trait-resolution-error-with-const-generics-77919.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/77919 fn main() { [1; >::VAL]; } diff --git a/tests/ui/issues/issue-77919.stderr b/tests/ui/const-generics/trait-resolution-error-with-const-generics-77919.stderr similarity index 84% rename from tests/ui/issues/issue-77919.stderr rename to tests/ui/const-generics/trait-resolution-error-with-const-generics-77919.stderr index dbbe70ff0699..bac8abf46dce 100644 --- a/tests/ui/issues/issue-77919.stderr +++ b/tests/ui/const-generics/trait-resolution-error-with-const-generics-77919.stderr @@ -1,5 +1,5 @@ error[E0412]: cannot find type `PhantomData` in this scope - --> $DIR/issue-77919.rs:9:9 + --> $DIR/trait-resolution-error-with-const-generics-77919.rs:10:9 | LL | _n: PhantomData, | ^^^^^^^^^^^ not found in this scope @@ -10,7 +10,7 @@ LL + use std::marker::PhantomData; | error[E0412]: cannot find type `VAL` in this scope - --> $DIR/issue-77919.rs:11:63 + --> $DIR/trait-resolution-error-with-const-generics-77919.rs:12:63 | LL | impl TypeVal for Multiply where N: TypeVal {} | ^^^ not found in this scope @@ -21,7 +21,7 @@ LL | impl TypeVal for Multiply where N: TypeVal {} | +++++ error[E0046]: not all trait items implemented, missing: `VAL` - --> $DIR/issue-77919.rs:11:1 + --> $DIR/trait-resolution-error-with-const-generics-77919.rs:12:1 | LL | const VAL: T; | ------------ `VAL` from trait diff --git a/tests/ui/issues/issue-4734.rs b/tests/ui/drop/destructor-run-for-expression-4734.rs similarity index 94% rename from tests/ui/issues/issue-4734.rs rename to tests/ui/drop/destructor-run-for-expression-4734.rs index 58aa0179693e..57971ee5ef76 100644 --- a/tests/ui/issues/issue-4734.rs +++ b/tests/ui/drop/destructor-run-for-expression-4734.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/4734 //@ run-pass #![allow(dead_code)] // Ensures that destructors are run for expressions of the form "e;" where diff --git a/tests/ui/issues/issue-36116.rs b/tests/ui/generics/unnecessary-path-disambiguator-36116.rs similarity index 86% rename from tests/ui/issues/issue-36116.rs rename to tests/ui/generics/unnecessary-path-disambiguator-36116.rs index 2313e189aff7..c2dab605f592 100644 --- a/tests/ui/issues/issue-36116.rs +++ b/tests/ui/generics/unnecessary-path-disambiguator-36116.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/36116 // Unnecessary path disambiguator is ok //@ check-pass diff --git a/tests/ui/issues/issue-12909.rs b/tests/ui/inference/collection-type-copy-behavior-12909.rs similarity index 90% rename from tests/ui/issues/issue-12909.rs rename to tests/ui/inference/collection-type-copy-behavior-12909.rs index f2c33806aae8..83536e8875ca 100644 --- a/tests/ui/issues/issue-12909.rs +++ b/tests/ui/inference/collection-type-copy-behavior-12909.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/12909 //@ run-pass #![allow(unused_variables)] diff --git a/tests/ui/issues/auxiliary/issue-25185-2.rs b/tests/ui/issues/auxiliary/issue-25185-2.rs deleted file mode 100644 index 7ce3df255a33..000000000000 --- a/tests/ui/issues/auxiliary/issue-25185-2.rs +++ /dev/null @@ -1,3 +0,0 @@ -extern crate issue_25185_1; - -pub use issue_25185_1::rust_dbg_extern_identity_u32; diff --git a/tests/ui/issues/issue-25185.rs b/tests/ui/issues/issue-25185.rs deleted file mode 100644 index 7dc06ad96df6..000000000000 --- a/tests/ui/issues/issue-25185.rs +++ /dev/null @@ -1,12 +0,0 @@ -//@ run-pass -//@ aux-build:issue-25185-1.rs -//@ aux-build:issue-25185-2.rs - -extern crate issue_25185_2; - -fn main() { - let x = unsafe { - issue_25185_2::rust_dbg_extern_identity_u32(1) - }; - assert_eq!(x, 1); -} diff --git a/tests/ui/issues/issue-32655.rs b/tests/ui/issues/issue-32655.rs deleted file mode 100644 index f52e09231296..000000000000 --- a/tests/ui/issues/issue-32655.rs +++ /dev/null @@ -1,19 +0,0 @@ -macro_rules! foo ( - () => ( - #[derive_Clone] //~ ERROR cannot find attribute `derive_Clone` in this scope - struct T; - ); -); - -macro_rules! bar ( - ($e:item) => ($e) -); - -foo!(); - -bar!( - #[derive_Clone] //~ ERROR cannot find attribute `derive_Clone` in this scope - struct S; -); - -fn main() {} diff --git a/tests/ui/issues/issue-32655.stderr b/tests/ui/issues/issue-32655.stderr deleted file mode 100644 index b8362499b2d0..000000000000 --- a/tests/ui/issues/issue-32655.stderr +++ /dev/null @@ -1,25 +0,0 @@ -error: cannot find attribute `derive_Clone` in this scope - --> $DIR/issue-32655.rs:3:11 - | -LL | #[derive_Clone] - | ^^^^^^^^^^^^ help: an attribute macro with a similar name exists: `derive_const` -... -LL | foo!(); - | ------ in this macro invocation - --> $SRC_DIR/core/src/macros/mod.rs:LL:COL - | - = note: similarly named attribute macro `derive_const` defined here - | - = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: cannot find attribute `derive_Clone` in this scope - --> $DIR/issue-32655.rs:15:7 - | -LL | #[derive_Clone] - | ^^^^^^^^^^^^ help: an attribute macro with a similar name exists: `derive_const` - --> $SRC_DIR/core/src/macros/mod.rs:LL:COL - | - = note: similarly named attribute macro `derive_const` defined here - -error: aborting due to 2 previous errors - diff --git a/tests/ui/issues/issue-15673.rs b/tests/ui/iterators/iterator-type-inference-sum-15673.rs similarity index 76% rename from tests/ui/issues/issue-15673.rs rename to tests/ui/iterators/iterator-type-inference-sum-15673.rs index bb61c2462764..aee027927f2f 100644 --- a/tests/ui/issues/issue-15673.rs +++ b/tests/ui/iterators/iterator-type-inference-sum-15673.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/15673 //@ run-pass #![allow(stable_features)] diff --git a/tests/ui/issues/auxiliary/issue-25185-1.rs b/tests/ui/linking/auxiliary/aux-25185-1.rs similarity index 100% rename from tests/ui/issues/auxiliary/issue-25185-1.rs rename to tests/ui/linking/auxiliary/aux-25185-1.rs diff --git a/tests/ui/linking/auxiliary/aux-25185-2.rs b/tests/ui/linking/auxiliary/aux-25185-2.rs new file mode 100644 index 000000000000..96c73f623e4d --- /dev/null +++ b/tests/ui/linking/auxiliary/aux-25185-2.rs @@ -0,0 +1,3 @@ +extern crate aux_25185_1; + +pub use aux_25185_1::rust_dbg_extern_identity_u32; diff --git a/tests/ui/linking/rlib-to-dylib-native-deps-inclusion-25185.rs b/tests/ui/linking/rlib-to-dylib-native-deps-inclusion-25185.rs new file mode 100644 index 000000000000..bbcfcb75106f --- /dev/null +++ b/tests/ui/linking/rlib-to-dylib-native-deps-inclusion-25185.rs @@ -0,0 +1,13 @@ +// https://github.com/rust-lang/rust/issues/25185 +//@ run-pass +//@ aux-build:aux-25185-1.rs +//@ aux-build:aux-25185-2.rs + +extern crate aux_25185_2; + +fn main() { + let x = unsafe { + aux_25185_2::rust_dbg_extern_identity_u32(1) + }; + assert_eq!(x, 1); +} diff --git a/tests/ui/issues/issue-26093.rs b/tests/ui/macros/invalid-assignment-in-macro-26093.rs similarity index 83% rename from tests/ui/issues/issue-26093.rs rename to tests/ui/macros/invalid-assignment-in-macro-26093.rs index c838515caf99..686a13a3eec3 100644 --- a/tests/ui/issues/issue-26093.rs +++ b/tests/ui/macros/invalid-assignment-in-macro-26093.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/26093 macro_rules! not_a_place { ($thing:expr) => { $thing = 42; diff --git a/tests/ui/issues/issue-26093.stderr b/tests/ui/macros/invalid-assignment-in-macro-26093.stderr similarity index 90% rename from tests/ui/issues/issue-26093.stderr rename to tests/ui/macros/invalid-assignment-in-macro-26093.stderr index 1a08d0fef411..99f188c71836 100644 --- a/tests/ui/issues/issue-26093.stderr +++ b/tests/ui/macros/invalid-assignment-in-macro-26093.stderr @@ -1,5 +1,5 @@ error[E0070]: invalid left-hand side of assignment - --> $DIR/issue-26093.rs:3:16 + --> $DIR/invalid-assignment-in-macro-26093.rs:4:16 | LL | $thing = 42; | ^ @@ -13,7 +13,7 @@ LL | not_a_place!(99); = note: this error originates in the macro `not_a_place` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0067]: invalid left-hand side of assignment - --> $DIR/issue-26093.rs:5:16 + --> $DIR/invalid-assignment-in-macro-26093.rs:6:16 | LL | $thing += 42; | ^^ diff --git a/tests/ui/issues/issue-7519-match-unit-in-arg.rs b/tests/ui/pattern/unit-pattern-matching-in-function-argument-7519.rs similarity index 72% rename from tests/ui/issues/issue-7519-match-unit-in-arg.rs rename to tests/ui/pattern/unit-pattern-matching-in-function-argument-7519.rs index a7cea577b224..7bfa9ee66256 100644 --- a/tests/ui/issues/issue-7519-match-unit-in-arg.rs +++ b/tests/ui/pattern/unit-pattern-matching-in-function-argument-7519.rs @@ -2,6 +2,7 @@ /* #7519 ICE pattern matching unit in function argument +https://github.com/rust-lang/rust/issues/7519 */ fn foo(():()) { } diff --git a/tests/ui/issues/issue-22434.rs b/tests/ui/type-alias/missing-associated-type-in-trait-object-22434.rs similarity index 75% rename from tests/ui/issues/issue-22434.rs rename to tests/ui/type-alias/missing-associated-type-in-trait-object-22434.rs index d9f7b987c64f..35b30374c15c 100644 --- a/tests/ui/issues/issue-22434.rs +++ b/tests/ui/type-alias/missing-associated-type-in-trait-object-22434.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/22434 pub trait Foo { type A; } diff --git a/tests/ui/issues/issue-22434.stderr b/tests/ui/type-alias/missing-associated-type-in-trait-object-22434.stderr similarity index 84% rename from tests/ui/issues/issue-22434.stderr rename to tests/ui/type-alias/missing-associated-type-in-trait-object-22434.stderr index 172ae386c3e4..73afefa5a1fd 100644 --- a/tests/ui/issues/issue-22434.stderr +++ b/tests/ui/type-alias/missing-associated-type-in-trait-object-22434.stderr @@ -1,5 +1,5 @@ error[E0191]: the value of the associated type `A` in `Foo` must be specified - --> $DIR/issue-22434.rs:5:23 + --> $DIR/missing-associated-type-in-trait-object-22434.rs:6:23 | LL | type A; | ------ `A` defined here diff --git a/tests/ui/issues/issue-48276.rs b/tests/ui/typeck/incorrect-self-type-in-trait-impl-48276.rs similarity index 93% rename from tests/ui/issues/issue-48276.rs rename to tests/ui/typeck/incorrect-self-type-in-trait-impl-48276.rs index f55c056fa67d..1cff20787550 100644 --- a/tests/ui/issues/issue-48276.rs +++ b/tests/ui/typeck/incorrect-self-type-in-trait-impl-48276.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/48276 // Regression test for issue #48276 - ICE when self type does not match what is // required by a trait and regions are involved. diff --git a/tests/ui/issues/issue-48276.stderr b/tests/ui/typeck/incorrect-self-type-in-trait-impl-48276.stderr similarity index 83% rename from tests/ui/issues/issue-48276.stderr rename to tests/ui/typeck/incorrect-self-type-in-trait-impl-48276.stderr index 370905ee0dfb..124dc4592376 100644 --- a/tests/ui/issues/issue-48276.stderr +++ b/tests/ui/typeck/incorrect-self-type-in-trait-impl-48276.stderr @@ -1,5 +1,5 @@ error[E0185]: method `from` has a `&self` declaration in the impl, but not in the trait - --> $DIR/issue-48276.rs:11:5 + --> $DIR/incorrect-self-type-in-trait-impl-48276.rs:12:5 | LL | fn from(a: A) -> Self; | ---------------------- trait method declared without `&self` @@ -8,7 +8,7 @@ LL | fn from(self: &'a Self) -> &'b str { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&self` used in impl error[E0185]: method `from` has a `&self` declaration in the impl, but not in the trait - --> $DIR/issue-48276.rs:20:5 + --> $DIR/incorrect-self-type-in-trait-impl-48276.rs:21:5 | LL | fn from(&self) -> B { | ^^^^^^^^^^^^^^^^^^^ `&self` used in impl @@ -16,7 +16,7 @@ LL | fn from(&self) -> B { = note: `from` from trait: `fn(T) -> Self` error[E0185]: method `from` has a `&self` declaration in the impl, but not in the trait - --> $DIR/issue-48276.rs:27:5 + --> $DIR/incorrect-self-type-in-trait-impl-48276.rs:28:5 | LL | fn from(&self) -> &'static str { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&self` used in impl diff --git a/tests/ui/issues/issue-32995-2.rs b/tests/ui/typeck/parenthesized-type-parameters-error-32995.rs similarity index 89% rename from tests/ui/issues/issue-32995-2.rs rename to tests/ui/typeck/parenthesized-type-parameters-error-32995.rs index e713a64d3f5a..e0c2ab5f303a 100644 --- a/tests/ui/issues/issue-32995-2.rs +++ b/tests/ui/typeck/parenthesized-type-parameters-error-32995.rs @@ -1,3 +1,4 @@ +// https://github.com/rust-lang/rust/issues/32995 fn main() { { fn f() {} } //~^ ERROR parenthesized type parameters may only be used with a `Fn` trait diff --git a/tests/ui/issues/issue-32995-2.stderr b/tests/ui/typeck/parenthesized-type-parameters-error-32995.stderr similarity index 79% rename from tests/ui/issues/issue-32995-2.stderr rename to tests/ui/typeck/parenthesized-type-parameters-error-32995.stderr index 6c2d772a2333..590cdcdb43bc 100644 --- a/tests/ui/issues/issue-32995-2.stderr +++ b/tests/ui/typeck/parenthesized-type-parameters-error-32995.stderr @@ -1,17 +1,17 @@ error[E0214]: parenthesized type parameters may only be used with a `Fn` trait - --> $DIR/issue-32995-2.rs:2:22 + --> $DIR/parenthesized-type-parameters-error-32995.rs:3:22 | LL | { fn f() {} } | ^^^^^^^^ only `Fn` traits may use parentheses error[E0214]: parenthesized type parameters may only be used with a `Fn` trait - --> $DIR/issue-32995-2.rs:5:29 + --> $DIR/parenthesized-type-parameters-error-32995.rs:6:29 | LL | { fn f() -> impl ::std::marker()::Send { } } | ^^^^^^^^ only `Fn` traits may use parentheses error[E0214]: parenthesized type parameters may only be used with a `Fn` trait - --> $DIR/issue-32995-2.rs:12:13 + --> $DIR/parenthesized-type-parameters-error-32995.rs:13:13 | LL | impl ::std::marker()::Copy for X {} | ^^^^^^^^ only `Fn` traits may use parentheses diff --git a/tests/ui/issues/issue-18685.rs b/tests/ui/unboxed-closures/self-param-space-conflict-in-unboxed-closure-18685.rs similarity index 85% rename from tests/ui/issues/issue-18685.rs rename to tests/ui/unboxed-closures/self-param-space-conflict-in-unboxed-closure-18685.rs index 3dab341f615c..38cf26c27770 100644 --- a/tests/ui/issues/issue-18685.rs +++ b/tests/ui/unboxed-closures/self-param-space-conflict-in-unboxed-closure-18685.rs @@ -1,8 +1,8 @@ +// https://github.com/rust-lang/rust/issues/18685 //@ run-pass // Test that the self param space is not used in a conflicting // manner by unboxed closures within a default method on a trait - trait Tr { fn foo(&self); From 8f6b43dd656743730d32f5f7ee5a768434d25189 Mon Sep 17 00:00:00 2001 From: Zihan Date: Sat, 2 Aug 2025 12:54:04 -0400 Subject: [PATCH 0366/1134] fix: `option_if_let_else` don't suggest argless function for Result::map_or_else closes rust-clippy/issues/15002 Signed-off-by: Zihan --- clippy_lints/src/option_if_let_else.rs | 6 +++--- tests/ui/option_if_let_else.fixed | 5 +++++ tests/ui/option_if_let_else.rs | 9 +++++++++ tests/ui/option_if_let_else.stderr | 13 ++++++++++++- 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/option_if_let_else.rs b/clippy_lints/src/option_if_let_else.rs index 6c0bf2ad1545..3483f3081a58 100644 --- a/clippy_lints/src/option_if_let_else.rs +++ b/clippy_lints/src/option_if_let_else.rs @@ -224,8 +224,8 @@ fn try_get_option_occurrence<'tcx>( let mut app = Applicability::Unspecified; - let (none_body, is_argless_call) = match none_body.kind { - ExprKind::Call(call_expr, []) if !none_body.span.from_expansion() => (call_expr, true), + let (none_body, can_omit_arg) = match none_body.kind { + ExprKind::Call(call_expr, []) if !none_body.span.from_expansion() && !is_result => (call_expr, true), _ => (none_body, false), }; @@ -242,7 +242,7 @@ fn try_get_option_occurrence<'tcx>( ), none_expr: format!( "{}{}", - if method_sugg == "map_or" || is_argless_call { + if method_sugg == "map_or" || can_omit_arg { "" } else if is_result { "|_| " diff --git a/tests/ui/option_if_let_else.fixed b/tests/ui/option_if_let_else.fixed index c418a358dcb3..0f86de5646cd 100644 --- a/tests/ui/option_if_let_else.fixed +++ b/tests/ui/option_if_let_else.fixed @@ -309,3 +309,8 @@ fn issue15379() { let _ = unsafe { (*opt_raw_ptr).map_or(1, |o| o) }; //~^ option_if_let_else } + +fn issue15002() { + let res: Result = Ok("_".to_string()); + let _ = res.map_or_else(|_| String::new(), |s| s.clone()); +} diff --git a/tests/ui/option_if_let_else.rs b/tests/ui/option_if_let_else.rs index 4c3e4be3caeb..7aabd778f87e 100644 --- a/tests/ui/option_if_let_else.rs +++ b/tests/ui/option_if_let_else.rs @@ -372,3 +372,12 @@ fn issue15379() { let _ = unsafe { if let Some(o) = *opt_raw_ptr { o } else { 1 } }; //~^ option_if_let_else } + +fn issue15002() { + let res: Result = Ok("_".to_string()); + let _ = match res { + //~^ option_if_let_else + Ok(s) => s.clone(), + Err(_) => String::new(), + }; +} diff --git a/tests/ui/option_if_let_else.stderr b/tests/ui/option_if_let_else.stderr index 514ecca41142..2e2fe6f20492 100644 --- a/tests/ui/option_if_let_else.stderr +++ b/tests/ui/option_if_let_else.stderr @@ -340,5 +340,16 @@ error: use Option::map_or instead of an if let/else LL | let _ = unsafe { if let Some(o) = *opt_raw_ptr { o } else { 1 } }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `(*opt_raw_ptr).map_or(1, |o| o)` -error: aborting due to 26 previous errors +error: use Option::map_or_else instead of an if let/else + --> tests/ui/option_if_let_else.rs:378:13 + | +LL | let _ = match res { + | _____________^ +LL | | +LL | | Ok(s) => s.clone(), +LL | | Err(_) => String::new(), +LL | | }; + | |_____^ help: try: `res.map_or_else(|_| String::new(), |s| s.clone())` + +error: aborting due to 27 previous errors From aba0b65707f9980babb6dcc2855f32a3b21f05e7 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 Aug 2025 22:42:54 +0000 Subject: [PATCH 0367/1134] Use DefKind in should_explore. --- compiler/rustc_passes/src/dead.rs | 44 ++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index f8d1ef298820..bf5a31f7dde9 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -33,16 +33,40 @@ use crate::errors::{ // function, then we should explore its block to check for codes that // may need to be marked as live. fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { - matches!( - tcx.hir_node_by_def_id(def_id), - Node::Item(..) - | Node::ImplItem(..) - | Node::ForeignItem(..) - | Node::TraitItem(..) - | Node::Variant(..) - | Node::AnonConst(..) - | Node::OpaqueTy(..) - ) + match tcx.def_kind(def_id) { + DefKind::Mod + | DefKind::Struct + | DefKind::Union + | DefKind::Enum + | DefKind::Variant + | DefKind::Trait + | DefKind::TyAlias + | DefKind::ForeignTy + | DefKind::TraitAlias + | DefKind::AssocTy + | DefKind::Fn + | DefKind::Const + | DefKind::Static { .. } + | DefKind::AssocFn + | DefKind::AssocConst + | DefKind::Macro(_) + | DefKind::GlobalAsm + | DefKind::Impl { .. } + | DefKind::OpaqueTy + | DefKind::AnonConst + | DefKind::InlineConst + | DefKind::ExternCrate + | DefKind::Use + | DefKind::ForeignMod => true, + + DefKind::TyParam + | DefKind::ConstParam + | DefKind::Ctor(..) + | DefKind::Field + | DefKind::LifetimeParam + | DefKind::Closure + | DefKind::SyntheticCoroutineBody => false, + } } /// Returns the local def id of the ADT if the given ty refers to a local one. From 97435739ff5563ff87cc153b8eb09450997f68fd Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 3 Aug 2025 00:27:18 +0000 Subject: [PATCH 0368/1134] cargo update compiler & tools dependencies: Locking 14 packages to latest compatible versions Updating clap v4.5.41 -> v4.5.42 Updating clap_builder v4.5.41 -> v4.5.42 Updating jsonpath-rust v1.0.3 -> v1.0.4 Updating libredox v0.1.6 -> v0.1.9 Updating object v0.37.1 -> v0.37.2 Updating redox_syscall v0.5.16 -> v0.5.17 Updating redox_users v0.5.0 -> v0.5.2 Updating rustc-demangle v0.1.25 -> v0.1.26 Updating serde_json v1.0.141 -> v1.0.142 Updating wasm-encoder v0.235.0 -> v0.236.0 Updating wasmparser v0.235.0 -> v0.236.0 Updating wast v235.0.0 -> v236.0.0 Updating wat v1.235.0 -> v1.236.0 Updating windows-targets v0.53.2 -> v0.53.3 note: pass `--verbose` to see 36 unchanged dependencies behind latest library dependencies: Locking 3 packages to latest compatible versions Updating object v0.37.1 -> v0.37.2 Updating rustc-demangle v0.1.25 -> v0.1.26 Updating unwinding v0.2.7 -> v0.2.8 note: pass `--verbose` to see 2 unchanged dependencies behind latest rustbook dependencies: Locking 6 packages to latest compatible versions Updating cc v1.2.30 -> v1.2.31 Updating clap v4.5.41 -> v4.5.42 Updating clap_builder v4.5.41 -> v4.5.42 Updating redox_syscall v0.5.16 -> v0.5.17 Updating serde_json v1.0.141 -> v1.0.142 Updating windows-targets v0.53.2 -> v0.53.3 --- Cargo.lock | 77 ++++++++++++++++++----------------- library/Cargo.lock | 13 +++--- src/tools/rustbook/Cargo.lock | 27 ++++++------ 3 files changed, 59 insertions(+), 58 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d9cfda17ad92..a966493f1397 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -518,9 +518,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.41" +version = "4.5.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9" +checksum = "ed87a9d530bb41a67537289bafcac159cb3ee28460e0a4571123d2a778a6a882" dependencies = [ "clap_builder", "clap_derive", @@ -538,9 +538,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.41" +version = "4.5.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d" +checksum = "64f4f3f3c77c94aff3c7e9aac9a2ca1974a5adf392a8bb751e827d6d127ab966" dependencies = [ "anstream", "anstyle", @@ -1171,7 +1171,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users 0.5.0", + "redox_users 0.5.2", "windows-sys 0.60.2", ] @@ -2094,9 +2094,9 @@ dependencies = [ [[package]] name = "jsonpath-rust" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d057f8fd19e20c3f14d3663983397155739b6bc1148dc5cd4c4a1a5b3130eb0" +checksum = "633a7320c4bb672863a3782e89b9094ad70285e097ff6832cddd0ec615beadfa" dependencies = [ "pest", "pest_derive", @@ -2190,7 +2190,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" dependencies = [ "cfg-if", - "windows-targets 0.53.2", + "windows-targets 0.53.3", ] [[package]] @@ -2201,9 +2201,9 @@ checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "libredox" -version = "0.1.6" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4488594b9328dee448adb906d8b126d9b7deb7cf5c22161ee591610bb1be83c0" +checksum = "391290121bad3d37fbddad76d8f5d1c1c314cfc646d143d7e07a3086ddff0ce3" dependencies = [ "bitflags", "libc", @@ -2643,9 +2643,9 @@ dependencies = [ [[package]] name = "object" -version = "0.37.1" +version = "0.37.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03fd943161069e1768b4b3d050890ba48730e590f57e56d4aa04e7e090e61b4a" +checksum = "b3e3d0a7419f081f4a808147e845310313a39f322d7ae1f996b7f001d6cbed04" dependencies = [ "crc32fast", "flate2", @@ -2653,7 +2653,7 @@ dependencies = [ "indexmap", "memchr", "ruzstd 0.8.1", - "wasmparser 0.234.0", + "wasmparser 0.236.0", ] [[package]] @@ -3167,9 +3167,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.16" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7251471db004e509f4e75a62cca9435365b5ec7bcdff530d612ac7c87c44a792" +checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" dependencies = [ "bitflags", ] @@ -3187,9 +3187,9 @@ dependencies = [ [[package]] name = "redox_users" -version = "0.5.0" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.16", "libredox", @@ -3279,7 +3279,7 @@ dependencies = [ "build_helper", "gimli 0.32.0", "libc", - "object 0.37.1", + "object 0.37.2", "regex", "serde_json", "similar", @@ -3301,9 +3301,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" +checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" [[package]] name = "rustc-hash" @@ -3569,7 +3569,7 @@ dependencies = [ "itertools", "libc", "measureme", - "object 0.37.1", + "object 0.37.2", "rustc-demangle", "rustc_abi", "rustc_ast", @@ -3607,7 +3607,7 @@ dependencies = [ "cc", "itertools", "libc", - "object 0.37.1", + "object 0.37.2", "pathdiff", "regex", "rustc_abi", @@ -4642,7 +4642,7 @@ name = "rustc_target" version = "0.0.0" dependencies = [ "bitflags", - "object 0.37.1", + "object 0.37.2", "rustc_abi", "rustc_data_structures", "rustc_fs_util", @@ -5039,9 +5039,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.141" +version = "1.0.142" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" +checksum = "030fedb782600dcbd6f02d479bf0d817ac3bb40d644745b769d6a96bc3afc5a7" dependencies = [ "itoa", "memchr", @@ -6099,12 +6099,12 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.235.0" +version = "0.236.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3bc393c395cb621367ff02d854179882b9a351b4e0c93d1397e6090b53a5c2a" +checksum = "3108979166ab0d3c7262d2e16a2190ffe784b2a5beb963edef154b5e8e07680b" dependencies = [ "leb128fmt", - "wasmparser 0.235.0", + "wasmparser 0.236.0", ] [[package]] @@ -6144,9 +6144,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.235.0" +version = "0.236.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "161296c618fa2d63f6ed5fffd1112937e803cb9ec71b32b01a76321555660917" +checksum = "16d1eee846a705f6f3cb9d7b9f79b54583810f1fb57a1e3aea76d1742db2e3d2" dependencies = [ "bitflags", "indexmap", @@ -6155,22 +6155,22 @@ dependencies = [ [[package]] name = "wast" -version = "235.0.0" +version = "236.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1eda4293f626c99021bb3a6fbe4fbbe90c0e31a5ace89b5f620af8925de72e13" +checksum = "11d6b6faeab519ba6fbf9b26add41617ca6f5553f99ebc33d876e591d2f4f3c6" dependencies = [ "bumpalo", "leb128fmt", "memchr", "unicode-width 0.2.1", - "wasm-encoder 0.235.0", + "wasm-encoder 0.236.0", ] [[package]] name = "wat" -version = "1.235.0" +version = "1.236.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e777e0327115793cb96ab220b98f85327ec3d11f34ec9e8d723264522ef206aa" +checksum = "cc31704322400f461f7f31a5f9190d5488aaeafb63ae69ad2b5888d2704dcb08" dependencies = [ "wast", ] @@ -6426,7 +6426,7 @@ version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets 0.53.2", + "windows-targets 0.53.3", ] [[package]] @@ -6462,10 +6462,11 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.53.2" +version = "0.53.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" dependencies = [ + "windows-link", "windows_aarch64_gnullvm 0.53.0", "windows_aarch64_msvc 0.53.0", "windows_i686_gnu 0.53.0", diff --git a/library/Cargo.lock b/library/Cargo.lock index 988f4a8f7d51..09228825086e 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -169,9 +169,9 @@ dependencies = [ [[package]] name = "object" -version = "0.37.1" +version = "0.37.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03fd943161069e1768b4b3d050890ba48730e590f57e56d4aa04e7e090e61b4a" +checksum = "b3e3d0a7419f081f4a808147e845310313a39f322d7ae1f996b7f001d6cbed04" dependencies = [ "memchr", "rustc-std-workspace-alloc", @@ -259,9 +259,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" +checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" dependencies = [ "rustc-std-workspace-core", ] @@ -384,11 +384,10 @@ dependencies = [ [[package]] name = "unwinding" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d80f6c2bfede213d9a90b4a14f3eb99b84e33c52df6c1a15de0a100f5a88751" +checksum = "60612c845ef41699f39dc8c5391f252942c0a88b7d15da672eff0d14101bbd6d" dependencies = [ - "compiler_builtins", "gimli", "rustc-std-workspace-core", ] diff --git a/src/tools/rustbook/Cargo.lock b/src/tools/rustbook/Cargo.lock index 5f30c75732c7..d0eeab220623 100644 --- a/src/tools/rustbook/Cargo.lock +++ b/src/tools/rustbook/Cargo.lock @@ -156,9 +156,9 @@ checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "cc" -version = "1.2.30" +version = "1.2.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deec109607ca693028562ed836a5f1c4b8bd77755c4e132fc5ce11b0b6211ae7" +checksum = "c3a42d84bb6b69d3a8b3eaacf0d88f179e1929695e1ad012b6cf64d9caaa5fd2" dependencies = [ "shlex", ] @@ -185,9 +185,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.41" +version = "4.5.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9" +checksum = "ed87a9d530bb41a67537289bafcac159cb3ee28460e0a4571123d2a778a6a882" dependencies = [ "clap_builder", "clap_derive", @@ -195,9 +195,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.41" +version = "4.5.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d" +checksum = "64f4f3f3c77c94aff3c7e9aac9a2ca1974a5adf392a8bb751e827d6d127ab966" dependencies = [ "anstream", "anstyle", @@ -1343,9 +1343,9 @@ checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" [[package]] name = "redox_syscall" -version = "0.5.16" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7251471db004e509f4e75a62cca9435365b5ec7bcdff530d612ac7c87c44a792" +checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" dependencies = [ "bitflags 2.9.1", ] @@ -1459,9 +1459,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.141" +version = "1.0.142" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" +checksum = "030fedb782600dcbd6f02d479bf0d817ac3bb40d644745b769d6a96bc3afc5a7" dependencies = [ "itoa", "memchr", @@ -1969,7 +1969,7 @@ version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets 0.53.2", + "windows-targets 0.53.3", ] [[package]] @@ -1990,10 +1990,11 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.53.2" +version = "0.53.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" dependencies = [ + "windows-link", "windows_aarch64_gnullvm 0.53.0", "windows_aarch64_msvc 0.53.0", "windows_i686_gnu 0.53.0", From 99ee62305a4fbbf56f6be7b1ea3c315d4f0ac268 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 3 Aug 2025 01:44:20 +0000 Subject: [PATCH 0369/1134] Remove struct_constructors. --- compiler/rustc_passes/src/dead.rs | 46 ++++++++----------------------- 1 file changed, 12 insertions(+), 34 deletions(-) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index bf5a31f7dde9..cc39d3c346e2 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -57,11 +57,11 @@ fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { | DefKind::InlineConst | DefKind::ExternCrate | DefKind::Use + | DefKind::Ctor(..) | DefKind::ForeignMod => true, DefKind::TyParam | DefKind::ConstParam - | DefKind::Ctor(..) | DefKind::Field | DefKind::LifetimeParam | DefKind::Closure @@ -103,8 +103,6 @@ struct MarkSymbolVisitor<'tcx> { repr_has_repr_simd: bool, in_pat: bool, ignore_variant_stack: Vec, - // maps from tuple struct constructors to tuple struct items - struct_constructors: LocalDefIdMap, // maps from ADTs to ignored derived traits (e.g. Debug and Clone) // and the span of their respective impl (i.e., part of the derive // macro) @@ -123,7 +121,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { fn check_def_id(&mut self, def_id: DefId) { if let Some(def_id) = def_id.as_local() { - if should_explore(self.tcx, def_id) || self.struct_constructors.contains_key(&def_id) { + if should_explore(self.tcx, def_id) { self.worklist.push((def_id, ComesFromAllowExpect::No)); } self.live_symbols.insert(def_id); @@ -348,7 +346,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { continue; } - let (id, comes_from_allow_expect) = work; + let (mut id, comes_from_allow_expect) = work; // Avoid accessing the HIR for the synthesized associated type generated for RPITITs. if self.tcx.is_impl_trait_in_trait(id.to_def_id()) { @@ -356,9 +354,11 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { continue; } - // in the case of tuple struct constructors we want to check the item, not the generated - // tuple struct constructor function - let id = self.struct_constructors.get(&id).copied().unwrap_or(id); + // in the case of tuple struct constructors we want to check the item, + // not the generated tuple struct constructor function + if let DefKind::Ctor(..) = self.tcx.def_kind(id) { + id = self.tcx.local_parent(id); + } // When using `#[allow]` or `#[expect]` of `dead_code`, we do a QOL improvement // by declaring fn calls, statics, ... within said items as live, as well as @@ -751,7 +751,6 @@ fn has_allow_dead_code_or_lang_attr( fn check_item<'tcx>( tcx: TyCtxt<'tcx>, worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>, - struct_constructors: &mut LocalDefIdMap, unsolved_items: &mut Vec<(hir::ItemId, LocalDefId)>, id: hir::ItemId, ) { @@ -769,12 +768,6 @@ fn check_item<'tcx>( enum_def.variants.iter().map(|variant| (variant.def_id, comes_from_allow)), ); } - - for variant in enum_def.variants { - if let Some(ctor_def_id) = variant.data.ctor_def_id() { - struct_constructors.insert(ctor_def_id, variant.def_id); - } - } } } DefKind::Impl { of_trait } => { @@ -802,14 +795,6 @@ fn check_item<'tcx>( } } } - DefKind::Struct => { - let item = tcx.hir_item(id); - if let hir::ItemKind::Struct(_, _, ref variant_data) = item.kind - && let Some(ctor_def_id) = variant_data.ctor_def_id() - { - struct_constructors.insert(ctor_def_id, item.owner_id.def_id); - } - } DefKind::GlobalAsm => { // global_asm! is always live. worklist.push((id.owner_id.def_id, ComesFromAllowExpect::No)); @@ -859,15 +844,9 @@ fn check_foreign_item( fn create_and_seed_worklist( tcx: TyCtxt<'_>, -) -> ( - Vec<(LocalDefId, ComesFromAllowExpect)>, - LocalDefIdMap, - Vec<(hir::ItemId, LocalDefId)>, -) { +) -> (Vec<(LocalDefId, ComesFromAllowExpect)>, Vec<(hir::ItemId, LocalDefId)>) { let effective_visibilities = &tcx.effective_visibilities(()); - // see `MarkSymbolVisitor::struct_constructors` let mut unsolved_impl_item = Vec::new(); - let mut struct_constructors = Default::default(); let mut worklist = effective_visibilities .iter() .filter_map(|(&id, effective_vis)| { @@ -885,7 +864,7 @@ fn create_and_seed_worklist( let crate_items = tcx.hir_crate_items(()); for id in crate_items.free_items() { - check_item(tcx, &mut worklist, &mut struct_constructors, &mut unsolved_impl_item, id); + check_item(tcx, &mut worklist, &mut unsolved_impl_item, id); } for id in crate_items.trait_items() { @@ -896,14 +875,14 @@ fn create_and_seed_worklist( check_foreign_item(tcx, &mut worklist, id); } - (worklist, struct_constructors, unsolved_impl_item) + (worklist, unsolved_impl_item) } fn live_symbols_and_ignored_derived_traits( tcx: TyCtxt<'_>, (): (), ) -> (LocalDefIdSet, LocalDefIdMap>) { - let (worklist, struct_constructors, mut unsolved_items) = create_and_seed_worklist(tcx); + let (worklist, mut unsolved_items) = create_and_seed_worklist(tcx); let mut symbol_visitor = MarkSymbolVisitor { worklist, tcx, @@ -913,7 +892,6 @@ fn live_symbols_and_ignored_derived_traits( repr_has_repr_simd: false, in_pat: false, ignore_variant_stack: vec![], - struct_constructors, ignored_derived_traits: Default::default(), }; symbol_visitor.mark_live_symbols(); From 6c39b30f80ff8d970645288f7ada21036f2cab4b Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 Aug 2025 22:32:19 +0000 Subject: [PATCH 0370/1134] Simplify handling of unsolved items. --- compiler/rustc_passes/src/dead.rs | 90 +++++++++++++------------------ 1 file changed, 38 insertions(+), 52 deletions(-) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index cc39d3c346e2..e99bea57ff13 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -14,7 +14,7 @@ use rustc_errors::MultiSpan; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{self as hir, ImplItem, ImplItemKind, Node, PatKind, QPath, TyKind}; +use rustc_hir::{self as hir, ImplItem, ImplItemKind, Node, PatKind, QPath}; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::privacy::Level; use rustc_middle::query::Providers; @@ -69,23 +69,6 @@ fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { } } -/// Returns the local def id of the ADT if the given ty refers to a local one. -fn local_adt_def_of_ty<'tcx>(ty: &hir::Ty<'tcx>) -> Option { - match ty.kind { - TyKind::Path(QPath::Resolved(_, path)) => { - if let Res::Def(def_kind, def_id) = path.res - && let Some(local_def_id) = def_id.as_local() - && matches!(def_kind, DefKind::Struct | DefKind::Enum | DefKind::Union) - { - Some(local_def_id) - } else { - None - } - } - _ => None, - } -} - /// Determine if a work from the worklist is coming from a `#[allow]` /// or a `#[expect]` of `dead_code` #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] @@ -499,24 +482,24 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { /// `local_def_id` points to an impl or an impl item, /// both impl and impl item that may be passed to this function are of a trait, /// and added into the unsolved_items during `create_and_seed_worklist` - fn check_impl_or_impl_item_live( - &mut self, - impl_id: hir::ItemId, - local_def_id: LocalDefId, - ) -> bool { - let trait_def_id = match self.tcx.def_kind(local_def_id) { + fn check_impl_or_impl_item_live(&mut self, local_def_id: LocalDefId) -> bool { + let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) { // assoc impl items of traits are live if the corresponding trait items are live - DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn => self - .tcx - .associated_item(local_def_id) - .trait_item_def_id - .and_then(|def_id| def_id.as_local()), + DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn => ( + self.tcx.local_parent(local_def_id), + self.tcx + .associated_item(local_def_id) + .trait_item_def_id + .and_then(|def_id| def_id.as_local()), + ), // impl items are live if the corresponding traits are live - DefKind::Impl { of_trait: true } => self - .tcx - .impl_trait_ref(impl_id.owner_id.def_id) - .and_then(|trait_ref| trait_ref.skip_binder().def_id.as_local()), - _ => None, + DefKind::Impl { of_trait: true } => ( + local_def_id, + self.tcx + .impl_trait_ref(local_def_id) + .and_then(|trait_ref| trait_ref.skip_binder().def_id.as_local()), + ), + _ => bug!(), }; if let Some(trait_def_id) = trait_def_id @@ -526,9 +509,9 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { } // The impl or impl item is used if the corresponding trait or trait item is used and the ty is used. - if let Some(local_def_id) = - local_adt_def_of_ty(self.tcx.hir_item(impl_id).expect_impl().self_ty) - && !self.live_symbols.contains(&local_def_id) + if let ty::Adt(adt, _) = self.tcx.type_of(impl_block_id).instantiate_identity().kind() + && let Some(adt_def_id) = adt.did().as_local() + && !self.live_symbols.contains(&adt_def_id) { return false; } @@ -751,7 +734,7 @@ fn has_allow_dead_code_or_lang_attr( fn check_item<'tcx>( tcx: TyCtxt<'tcx>, worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>, - unsolved_items: &mut Vec<(hir::ItemId, LocalDefId)>, + unsolved_items: &mut Vec, id: hir::ItemId, ) { let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id); @@ -776,7 +759,7 @@ fn check_item<'tcx>( { worklist.push((id.owner_id.def_id, comes_from_allow)); } else if of_trait { - unsolved_items.push((id, id.owner_id.def_id)); + unsolved_items.push(id.owner_id.def_id); } for def_id in tcx.associated_item_def_ids(id.owner_id) { @@ -791,7 +774,7 @@ fn check_item<'tcx>( // so we later mark them as live if their corresponding traits // or trait items and self types are both live, // but inherent associated items can be visited and marked directly. - unsolved_items.push((id, local_def_id)); + unsolved_items.push(local_def_id); } } } @@ -844,7 +827,7 @@ fn check_foreign_item( fn create_and_seed_worklist( tcx: TyCtxt<'_>, -) -> (Vec<(LocalDefId, ComesFromAllowExpect)>, Vec<(hir::ItemId, LocalDefId)>) { +) -> (Vec<(LocalDefId, ComesFromAllowExpect)>, Vec) { let effective_visibilities = &tcx.effective_visibilities(()); let mut unsolved_impl_item = Vec::new(); let mut worklist = effective_visibilities @@ -895,21 +878,24 @@ fn live_symbols_and_ignored_derived_traits( ignored_derived_traits: Default::default(), }; symbol_visitor.mark_live_symbols(); - let mut items_to_check; - (items_to_check, unsolved_items) = - unsolved_items.into_iter().partition(|&(impl_id, local_def_id)| { - symbol_visitor.check_impl_or_impl_item_live(impl_id, local_def_id) - }); + + // We have marked the primary seeds as live. We now need to process unsolved items from traits + // and trait impls: add them to the work list if the trait or the implemented type is live. + let mut items_to_check: Vec<_> = unsolved_items + .extract_if(.., |&mut local_def_id| { + symbol_visitor.check_impl_or_impl_item_live(local_def_id) + }) + .collect(); while !items_to_check.is_empty() { - symbol_visitor.worklist = - items_to_check.into_iter().map(|(_, id)| (id, ComesFromAllowExpect::No)).collect(); + symbol_visitor + .worklist + .extend(items_to_check.drain(..).map(|id| (id, ComesFromAllowExpect::No))); symbol_visitor.mark_live_symbols(); - (items_to_check, unsolved_items) = - unsolved_items.into_iter().partition(|&(impl_id, local_def_id)| { - symbol_visitor.check_impl_or_impl_item_live(impl_id, local_def_id) - }); + items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| { + symbol_visitor.check_impl_or_impl_item_live(local_def_id) + })); } (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits) From f601717c5b52b5b0fbe468d911e663fe8740c7a9 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 2 Aug 2025 22:11:22 +0000 Subject: [PATCH 0371/1134] Use less HIR when seeding work list. --- compiler/rustc_passes/src/dead.rs | 140 +++++++++++------------------- 1 file changed, 50 insertions(+), 90 deletions(-) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index e99bea57ff13..43d2361aad89 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -718,113 +718,81 @@ fn has_allow_dead_code_or_lang_attr( } } -// These check_* functions seeds items that -// 1) We want to explicitly consider as live: -// * Item annotated with #[allow(dead_code)] -// - This is done so that if we want to suppress warnings for a -// group of dead functions, we only have to annotate the "root". -// For example, if both `f` and `g` are dead and `f` calls `g`, -// then annotating `f` with `#[allow(dead_code)]` will suppress -// warning for both `f` and `g`. -// * Item annotated with #[lang=".."] -// - This is because lang items are always callable from elsewhere. -// or -// 2) We are not sure to be live or not -// * Implementations of traits and trait methods -fn check_item<'tcx>( +/// Examine the given definition and record it in the worklist if it should be considered live. +/// +/// We want to explicitly consider as live: +/// * Item annotated with #[allow(dead_code)] +/// This is done so that if we want to suppress warnings for a +/// group of dead functions, we only have to annotate the "root". +/// For example, if both `f` and `g` are dead and `f` calls `g`, +/// then annotating `f` with `#[allow(dead_code)]` will suppress +/// warning for both `f` and `g`. +/// +/// * Item annotated with #[lang=".."] +/// Lang items are always callable from elsewhere. +/// +/// For trait methods and implementations of traits, we are not certain that the definitions are +/// live at this stage. We record them in `unsolved_items` for later examination. +fn maybe_record_as_seed<'tcx>( tcx: TyCtxt<'tcx>, + owner_id: hir::OwnerId, worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>, unsolved_items: &mut Vec, - id: hir::ItemId, ) { - let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id); + let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id); if let Some(comes_from_allow) = allow_dead_code { - worklist.push((id.owner_id.def_id, comes_from_allow)); + worklist.push((owner_id.def_id, comes_from_allow)); } - match tcx.def_kind(id.owner_id) { + match tcx.def_kind(owner_id) { DefKind::Enum => { - let item = tcx.hir_item(id); - if let hir::ItemKind::Enum(_, _, ref enum_def) = item.kind { - if let Some(comes_from_allow) = allow_dead_code { - worklist.extend( - enum_def.variants.iter().map(|variant| (variant.def_id, comes_from_allow)), - ); + let adt = tcx.adt_def(owner_id); + if let Some(comes_from_allow) = allow_dead_code { + worklist.extend( + adt.variants() + .iter() + .map(|variant| (variant.def_id.expect_local(), comes_from_allow)), + ); + } + } + DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => { + if allow_dead_code.is_none() { + let parent = tcx.local_parent(owner_id.def_id); + match tcx.def_kind(parent) { + DefKind::Impl { of_trait: false } | DefKind::Trait => {} + DefKind::Impl { of_trait: true } => { + // We only care about associated items of traits, + // because they cannot be visited directly, + // so we later mark them as live if their corresponding traits + // or trait items and self types are both live, + // but inherent associated items can be visited and marked directly. + unsolved_items.push(owner_id.def_id); + } + _ => bug!(), } } } DefKind::Impl { of_trait } => { - if let Some(comes_from_allow) = - has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id) - { - worklist.push((id.owner_id.def_id, comes_from_allow)); - } else if of_trait { - unsolved_items.push(id.owner_id.def_id); - } - - for def_id in tcx.associated_item_def_ids(id.owner_id) { - let local_def_id = def_id.expect_local(); - - if let Some(comes_from_allow) = has_allow_dead_code_or_lang_attr(tcx, local_def_id) - { - worklist.push((local_def_id, comes_from_allow)); - } else if of_trait { - // We only care about associated items of traits, - // because they cannot be visited directly, - // so we later mark them as live if their corresponding traits - // or trait items and self types are both live, - // but inherent associated items can be visited and marked directly. - unsolved_items.push(local_def_id); - } + if allow_dead_code.is_none() && of_trait { + unsolved_items.push(owner_id.def_id); } } DefKind::GlobalAsm => { // global_asm! is always live. - worklist.push((id.owner_id.def_id, ComesFromAllowExpect::No)); + worklist.push((owner_id.def_id, ComesFromAllowExpect::No)); } DefKind::Const => { - let item = tcx.hir_item(id); - if let hir::ItemKind::Const(ident, ..) = item.kind - && ident.name == kw::Underscore - { + if tcx.item_name(owner_id.def_id) == kw::Underscore { // `const _` is always live, as that syntax only exists for the side effects // of type checking and evaluating the constant expression, and marking them // as dead code would defeat that purpose. - worklist.push((id.owner_id.def_id, ComesFromAllowExpect::No)); + worklist.push((owner_id.def_id, ComesFromAllowExpect::No)); } } _ => {} } } -fn check_trait_item( - tcx: TyCtxt<'_>, - worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>, - id: hir::TraitItemId, -) { - use hir::TraitItemKind::{Const, Fn, Type}; - - let trait_item = tcx.hir_trait_item(id); - if matches!(trait_item.kind, Const(_, Some(_)) | Type(_, Some(_)) | Fn(..)) - && let Some(comes_from_allow) = - has_allow_dead_code_or_lang_attr(tcx, trait_item.owner_id.def_id) - { - worklist.push((trait_item.owner_id.def_id, comes_from_allow)); - } -} - -fn check_foreign_item( - tcx: TyCtxt<'_>, - worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>, - id: hir::ForeignItemId, -) { - if matches!(tcx.def_kind(id.owner_id), DefKind::Static { .. } | DefKind::Fn) - && let Some(comes_from_allow) = has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id) - { - worklist.push((id.owner_id.def_id, comes_from_allow)); - } -} - fn create_and_seed_worklist( tcx: TyCtxt<'_>, ) -> (Vec<(LocalDefId, ComesFromAllowExpect)>, Vec) { @@ -846,16 +814,8 @@ fn create_and_seed_worklist( .collect::>(); let crate_items = tcx.hir_crate_items(()); - for id in crate_items.free_items() { - check_item(tcx, &mut worklist, &mut unsolved_impl_item, id); - } - - for id in crate_items.trait_items() { - check_trait_item(tcx, &mut worklist, id); - } - - for id in crate_items.foreign_items() { - check_foreign_item(tcx, &mut worklist, id); + for id in crate_items.owners() { + maybe_record_as_seed(tcx, id, &mut worklist, &mut unsolved_impl_item); } (worklist, unsolved_impl_item) From 377728a4043e7337a29f9485c8c65c978662c6e2 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 3 Aug 2025 02:09:55 +0000 Subject: [PATCH 0372/1134] Keep scanned set across calls to mark_live_symbols. --- compiler/rustc_passes/src/dead.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 43d2361aad89..8eb834289370 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -81,6 +81,7 @@ struct MarkSymbolVisitor<'tcx> { worklist: Vec<(LocalDefId, ComesFromAllowExpect)>, tcx: TyCtxt<'tcx>, maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>, + scanned: UnordSet<(LocalDefId, ComesFromAllowExpect)>, live_symbols: LocalDefIdSet, repr_unconditionally_treats_fields_as_live: bool, repr_has_repr_simd: bool, @@ -323,9 +324,8 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { } fn mark_live_symbols(&mut self) { - let mut scanned = UnordSet::default(); while let Some(work) = self.worklist.pop() { - if !scanned.insert(work) { + if !self.scanned.insert(work) { continue; } @@ -830,6 +830,7 @@ fn live_symbols_and_ignored_derived_traits( worklist, tcx, maybe_typeck_results: None, + scanned: Default::default(), live_symbols: Default::default(), repr_unconditionally_treats_fields_as_live: false, repr_has_repr_simd: false, From effc509b40d90a5fe0fa7964cd739b1c887da19f Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 3 Aug 2025 02:36:01 +0000 Subject: [PATCH 0373/1134] Simplify lint emission. --- compiler/rustc_passes/src/dead.rs | 130 +++++++++++++----------------- 1 file changed, 56 insertions(+), 74 deletions(-) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 8eb834289370..88b3f742748e 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -5,7 +5,6 @@ use std::mem; -use hir::ItemKind; use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; use rustc_abi::FieldIdx; use rustc_data_structures::fx::FxIndexSet; @@ -14,7 +13,7 @@ use rustc_errors::MultiSpan; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{self as hir, ImplItem, ImplItemKind, Node, PatKind, QPath}; +use rustc_hir::{self as hir, Node, PatKind, QPath}; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::privacy::Level; use rustc_middle::query::Providers; @@ -930,25 +929,7 @@ impl<'tcx> DeadVisitor<'tcx> { parent_item: Option, report_on: ReportOn, ) { - fn get_parent_if_enum_variant<'tcx>( - tcx: TyCtxt<'tcx>, - may_variant: LocalDefId, - ) -> LocalDefId { - if let Node::Variant(_) = tcx.hir_node_by_def_id(may_variant) - && let Some(enum_did) = tcx.opt_parent(may_variant.to_def_id()) - && let Some(enum_local_id) = enum_did.as_local() - && let Node::Item(item) = tcx.hir_node_by_def_id(enum_local_id) - && let ItemKind::Enum(..) = item.kind - { - enum_local_id - } else { - may_variant - } - } - - let Some(&first_item) = dead_codes.first() else { - return; - }; + let Some(&first_item) = dead_codes.first() else { return }; let tcx = self.tcx; let first_lint_level = first_item.level; @@ -957,40 +938,40 @@ impl<'tcx> DeadVisitor<'tcx> { let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect(); let spans: Vec<_> = dead_codes .iter() - .map(|item| match tcx.def_ident_span(item.def_id) { - Some(s) => s.with_ctxt(tcx.def_span(item.def_id).ctxt()), - None => tcx.def_span(item.def_id), + .map(|item| { + let span = tcx.def_span(item.def_id); + let ident_span = tcx.def_ident_span(item.def_id); + // FIXME(cjgillot) this SyntaxContext manipulation does not make any sense. + ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span) }) .collect(); - let descr = tcx.def_descr(first_item.def_id.to_def_id()); + let mut descr = tcx.def_descr(first_item.def_id.to_def_id()); // `impl` blocks are "batched" and (unlike other batching) might // contain different kinds of associated items. - let descr = if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) - { - "associated item" - } else { - descr - }; + if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) { + descr = "associated item" + } + let num = dead_codes.len(); let multiple = num > 6; let name_list = names.into(); - let parent_info = if let Some(parent_item) = parent_item { + let parent_info = parent_item.map(|parent_item| { let parent_descr = tcx.def_descr(parent_item.to_def_id()); let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) { tcx.def_span(parent_item) } else { tcx.def_ident_span(parent_item).unwrap() }; - Some(ParentInfo { num, descr, parent_descr, span }) - } else { - None - }; + ParentInfo { num, descr, parent_descr, span } + }); - let encl_def_id = parent_item.unwrap_or(first_item.def_id); - // If parent of encl_def_id is an enum, use the parent ID instead. - let encl_def_id = get_parent_if_enum_variant(tcx, encl_def_id); + let mut encl_def_id = parent_item.unwrap_or(first_item.def_id); + // `ignored_derived_traits` is computed for the enum, not for the variants. + if let DefKind::Variant = tcx.def_kind(encl_def_id) { + encl_def_id = tcx.local_parent(encl_def_id); + } let ignored_derived_impls = self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| { @@ -1006,31 +987,6 @@ impl<'tcx> DeadVisitor<'tcx> { } }); - let enum_variants_with_same_name = dead_codes - .iter() - .filter_map(|dead_item| { - if let Node::ImplItem(ImplItem { - kind: ImplItemKind::Fn(..) | ImplItemKind::Const(..), - .. - }) = tcx.hir_node_by_def_id(dead_item.def_id) - && let Some(impl_did) = tcx.opt_parent(dead_item.def_id.to_def_id()) - && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did) - && let ty::Adt(maybe_enum, _) = tcx.type_of(impl_did).skip_binder().kind() - && maybe_enum.is_enum() - && let Some(variant) = - maybe_enum.variants().iter().find(|i| i.name == dead_item.name) - { - Some(crate::errors::EnumVariantSameName { - dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()), - dead_name: dead_item.name, - variant_span: tcx.def_span(variant.def_id), - }) - } else { - None - } - }) - .collect(); - let diag = match report_on { ReportOn::TupleField => { let tuple_fields = if let Some(parent_id) = parent_item @@ -1076,16 +1032,42 @@ impl<'tcx> DeadVisitor<'tcx> { ignored_derived_impls, } } - ReportOn::NamedField => MultipleDeadCodes::DeadCodes { - multiple, - num, - descr, - participle, - name_list, - parent_info, - ignored_derived_impls, - enum_variants_with_same_name, - }, + ReportOn::NamedField => { + let enum_variants_with_same_name = dead_codes + .iter() + .filter_map(|dead_item| { + if let DefKind::AssocFn | DefKind::AssocConst = + tcx.def_kind(dead_item.def_id) + && let impl_did = tcx.local_parent(dead_item.def_id) + && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did) + && let ty::Adt(maybe_enum, _) = + tcx.type_of(impl_did).instantiate_identity().kind() + && maybe_enum.is_enum() + && let Some(variant) = + maybe_enum.variants().iter().find(|i| i.name == dead_item.name) + { + Some(crate::errors::EnumVariantSameName { + dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()), + dead_name: dead_item.name, + variant_span: tcx.def_span(variant.def_id), + }) + } else { + None + } + }) + .collect(); + + MultipleDeadCodes::DeadCodes { + multiple, + num, + descr, + participle, + name_list, + parent_info, + ignored_derived_impls, + enum_variants_with_same_name, + } + } }; let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id); From 2ddf0ca9f5402ce6a710d35a5beb2067201ff23d Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 12:44:51 +1000 Subject: [PATCH 0374/1134] Change `ProcRes::print_info` to `format_info` This method now returns a string instead of printing directly to (possibly-captured) stdout. --- src/tools/compiletest/src/runtest.rs | 9 +++++---- src/tools/compiletest/src/runtest/rustdoc_json.rs | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index ba7fcadbc2e5..12a5e55e77b4 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2957,7 +2957,8 @@ pub struct ProcRes { } impl ProcRes { - pub fn print_info(&self) { + #[must_use] + pub fn format_info(&self) -> String { fn render(name: &str, contents: &str) -> String { let contents = json::extract_rendered(contents); let contents = contents.trim_end(); @@ -2973,20 +2974,20 @@ impl ProcRes { } } - println!( + format!( "status: {}\ncommand: {}\n{}\n{}\n", self.status, self.cmdline, render("stdout", &self.stdout), render("stderr", &self.stderr), - ); + ) } pub fn fatal(&self, err: Option<&str>, on_failure: impl FnOnce()) -> ! { if let Some(e) = err { println!("\nerror: {}", e); } - self.print_info(); + println!("{}", self.format_info()); on_failure(); // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from // compiletest, which is unnecessary noise. diff --git a/src/tools/compiletest/src/runtest/rustdoc_json.rs b/src/tools/compiletest/src/runtest/rustdoc_json.rs index 4f35efedfde4..7c23665c3902 100644 --- a/src/tools/compiletest/src/runtest/rustdoc_json.rs +++ b/src/tools/compiletest/src/runtest/rustdoc_json.rs @@ -31,7 +31,7 @@ impl TestCx<'_> { if !res.status.success() { self.fatal_proc_rec_with_ctx("jsondocck failed!", &res, |_| { println!("Rustdoc Output:"); - proc_res.print_info(); + println!("{}", proc_res.format_info()); }) } From d1d44d44f15f32ea4c53abc2dbb35bd8304e582e Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 12:57:30 +1000 Subject: [PATCH 0375/1134] Consolidate all `ProcRes` unwinds into one code path --- src/tools/compiletest/src/runtest.rs | 50 ++++++++++--------- src/tools/compiletest/src/runtest/rustdoc.rs | 4 +- .../compiletest/src/runtest/rustdoc_json.rs | 2 +- 3 files changed, 29 insertions(+), 27 deletions(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 12a5e55e77b4..b1f8e461aef8 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -354,13 +354,10 @@ impl<'test> TestCx<'test> { } } else { if proc_res.status.success() { - { - self.error(&format!("{} test did not emit an error", self.config.mode)); - if self.config.mode == crate::common::TestMode::Ui { - println!("note: by default, ui tests are expected not to compile"); - } - proc_res.fatal(None, || ()); - }; + let err = &format!("{} test did not emit an error", self.config.mode); + let extra_note = (self.config.mode == crate::common::TestMode::Ui) + .then_some("note: by default, ui tests are expected not to compile"); + self.fatal_proc_rec_general(err, extra_note, proc_res, || ()); } if !self.props.dont_check_failure_status { @@ -2010,18 +2007,34 @@ impl<'test> TestCx<'test> { } fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! { - self.error(err); - proc_res.fatal(None, || ()); + self.fatal_proc_rec_general(err, None, proc_res, || ()); } - fn fatal_proc_rec_with_ctx( + /// Underlying implementation of [`Self::fatal_proc_rec`], providing some + /// extra capabilities not needed by most callers. + fn fatal_proc_rec_general( &self, err: &str, + extra_note: Option<&str>, proc_res: &ProcRes, - on_failure: impl FnOnce(Self), + callback_before_unwind: impl FnOnce(), ) -> ! { self.error(err); - proc_res.fatal(None, || on_failure(*self)); + + // Some callers want to print additional notes after the main error message. + if let Some(note) = extra_note { + println!("{note}"); + } + + // Print the details and output of the subprocess that caused this test to fail. + println!("{}", proc_res.format_info()); + + // Some callers want print more context or show a custom diff before the unwind occurs. + callback_before_unwind(); + + // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from + // compiletest, which is unnecessary noise. + std::panic::resume_unwind(Box::new(())); } // codegen tests (using FileCheck) @@ -2080,7 +2093,7 @@ impl<'test> TestCx<'test> { if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" } } - fn compare_to_default_rustdoc(&mut self, out_dir: &Utf8Path) { + fn compare_to_default_rustdoc(&self, out_dir: &Utf8Path) { if !self.config.has_html_tidy { return; } @@ -2982,17 +2995,6 @@ impl ProcRes { render("stderr", &self.stderr), ) } - - pub fn fatal(&self, err: Option<&str>, on_failure: impl FnOnce()) -> ! { - if let Some(e) = err { - println!("\nerror: {}", e); - } - println!("{}", self.format_info()); - on_failure(); - // Use resume_unwind instead of panic!() to prevent a panic message + backtrace from - // compiletest, which is unnecessary noise. - std::panic::resume_unwind(Box::new(())); - } } #[derive(Debug)] diff --git a/src/tools/compiletest/src/runtest/rustdoc.rs b/src/tools/compiletest/src/runtest/rustdoc.rs index 236f021ce827..4a143aa5824e 100644 --- a/src/tools/compiletest/src/runtest/rustdoc.rs +++ b/src/tools/compiletest/src/runtest/rustdoc.rs @@ -28,8 +28,8 @@ impl TestCx<'_> { } let res = self.run_command_to_procres(&mut cmd); if !res.status.success() { - self.fatal_proc_rec_with_ctx("htmldocck failed!", &res, |mut this| { - this.compare_to_default_rustdoc(&out_dir) + self.fatal_proc_rec_general("htmldocck failed!", None, &res, || { + self.compare_to_default_rustdoc(&out_dir); }); } } diff --git a/src/tools/compiletest/src/runtest/rustdoc_json.rs b/src/tools/compiletest/src/runtest/rustdoc_json.rs index 7c23665c3902..083398f92745 100644 --- a/src/tools/compiletest/src/runtest/rustdoc_json.rs +++ b/src/tools/compiletest/src/runtest/rustdoc_json.rs @@ -29,7 +29,7 @@ impl TestCx<'_> { ); if !res.status.success() { - self.fatal_proc_rec_with_ctx("jsondocck failed!", &res, |_| { + self.fatal_proc_rec_general("jsondocck failed!", None, &res, || { println!("Rustdoc Output:"); println!("{}", proc_res.format_info()); }) From 1063b0f09010ffae99b6a3b55bec5539876ce57e Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 13:07:01 +1000 Subject: [PATCH 0376/1134] Change `TestCx::error` to `error_prefix`, which returns a string This reduces the amount of "hidden" printing in error-reporting code, which will be helpful when overhauling compiletest's error handling and output capture. --- src/tools/compiletest/src/runtest.rs | 36 +++++++++++++++++----------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index b1f8e461aef8..35670ba89e99 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -603,7 +603,10 @@ impl<'test> TestCx<'test> { ); } else { for pattern in missing_patterns { - self.error(&format!("error pattern '{}' not found!", pattern)); + println!( + "\n{prefix}: error pattern '{pattern}' not found!", + prefix = self.error_prefix() + ); } self.fatal_proc_rec("multiple error patterns not found", proc_res); } @@ -821,10 +824,11 @@ impl<'test> TestCx<'test> { // - only known line - meh, but suggested // - others are not worth suggesting if !unexpected.is_empty() { - self.error(&format!( - "{} diagnostics reported in JSON output but not expected in test file", - unexpected.len(), - )); + println!( + "\n{prefix}: {n} diagnostics reported in JSON output but not expected in test file", + prefix = self.error_prefix(), + n = unexpected.len(), + ); for error in &unexpected { print_error(error); let mut suggestions = Vec::new(); @@ -854,10 +858,11 @@ impl<'test> TestCx<'test> { } } if !not_found.is_empty() { - self.error(&format!( - "{} diagnostics expected in test file but not reported in JSON output", - not_found.len() - )); + println!( + "\n{prefix}: {n} diagnostics expected in test file but not reported in JSON output", + prefix = self.error_prefix(), + n = not_found.len(), + ); for error in ¬_found { print_error(error); let mut suggestions = Vec::new(); @@ -1992,16 +1997,19 @@ impl<'test> TestCx<'test> { output_base_name(self.config, self.testpaths, self.safe_revision()) } - fn error(&self, err: &str) { + /// Prefix to print before error messages. Normally just `error`, but also + /// includes the revision name for tests that use revisions. + #[must_use] + fn error_prefix(&self) -> String { match self.revision { - Some(rev) => println!("\nerror in revision `{}`: {}", rev, err), - None => println!("\nerror: {}", err), + Some(rev) => format!("error in revision `{rev}`"), + None => format!("error"), } } #[track_caller] fn fatal(&self, err: &str) -> ! { - self.error(err); + println!("\n{prefix}: {err}", prefix = self.error_prefix()); error!("fatal error, panic: {:?}", err); panic!("fatal error"); } @@ -2019,7 +2027,7 @@ impl<'test> TestCx<'test> { proc_res: &ProcRes, callback_before_unwind: impl FnOnce(), ) -> ! { - self.error(err); + println!("\n{prefix}: {err}", prefix = self.error_prefix()); // Some callers want to print additional notes after the main error message. if let Some(note) = extra_note { From f84c62112a3f86ac0e0916db07d70b391ce7db30 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Sun, 3 Aug 2025 07:18:26 +0200 Subject: [PATCH 0377/1134] there is still no official policy --- src/doc/rustc-dev-guide/src/crates-io.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/src/crates-io.md b/src/doc/rustc-dev-guide/src/crates-io.md index 4431585a2f02..677b1fc03134 100644 --- a/src/doc/rustc-dev-guide/src/crates-io.md +++ b/src/doc/rustc-dev-guide/src/crates-io.md @@ -11,7 +11,7 @@ you should avoid adding dependencies to the compiler for several reasons: - The dependency may have transitive dependencies that have one of the above problems. - + Note that there is no official policy for vetting new dependencies to the compiler. Decisions are made on a case-by-case basis, during code review. From b373cb100642ae0f154090ae57c74cc834ec0327 Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Sun, 3 Aug 2025 15:01:47 +0900 Subject: [PATCH 0378/1134] Migrate `generate_trait_from_impl` assist to use `SyntaxEditor` --- .../src/handlers/generate_trait_from_impl.rs | 69 ++++++++++--------- 1 file changed, 35 insertions(+), 34 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_trait_from_impl.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_trait_from_impl.rs index dc3dc73701f3..56500cf06802 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_trait_from_impl.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_trait_from_impl.rs @@ -2,12 +2,8 @@ use crate::assist_context::{AssistContext, Assists}; use ide_db::assists::AssistId; use syntax::{ AstNode, SyntaxKind, T, - ast::{ - self, HasGenericParams, HasName, HasVisibility, - edit_in_place::{HasVisibilityEdit, Indent}, - make, - }, - ted::{self, Position}, + ast::{self, HasGenericParams, HasName, HasVisibility, edit_in_place::Indent, make}, + syntax_editor::{Position, SyntaxEditor}, }; // NOTES : @@ -88,8 +84,8 @@ pub(crate) fn generate_trait_from_impl(acc: &mut Assists, ctx: &AssistContext<'_ return None; } - let assoc_items = impl_ast.assoc_item_list()?; - let first_element = assoc_items.assoc_items().next(); + let impl_assoc_items = impl_ast.assoc_item_list()?; + let first_element = impl_assoc_items.assoc_items().next(); first_element.as_ref()?; let impl_name = impl_ast.self_ty()?; @@ -99,20 +95,16 @@ pub(crate) fn generate_trait_from_impl(acc: &mut Assists, ctx: &AssistContext<'_ "Generate trait from impl", impl_ast.syntax().text_range(), |builder| { - let impl_ast = builder.make_mut(impl_ast); - let trait_items = assoc_items.clone_for_update(); - let impl_items = builder.make_mut(assoc_items); - let impl_name = builder.make_mut(impl_name); - - trait_items.assoc_items().for_each(|item| { - strip_body(&item); - remove_items_visibility(&item); - }); - - impl_items.assoc_items().for_each(|item| { - remove_items_visibility(&item); - }); - + let trait_items: ast::AssocItemList = { + let trait_items = impl_assoc_items.clone_subtree(); + let mut trait_items_editor = SyntaxEditor::new(trait_items.syntax().clone()); + + trait_items.assoc_items().for_each(|item| { + strip_body(&mut trait_items_editor, &item); + remove_items_visibility(&mut trait_items_editor, &item); + }); + ast::AssocItemList::cast(trait_items_editor.finish().new_root().clone()).unwrap() + }; let trait_ast = make::trait_( false, "NewTrait", @@ -130,6 +122,7 @@ pub(crate) fn generate_trait_from_impl(acc: &mut Assists, ctx: &AssistContext<'_ trait_name_ref.syntax().clone().into(), make::tokens::single_space().into(), make::token(T![for]).into(), + make::tokens::single_space().into(), ]; if let Some(params) = impl_ast.generic_param_list() { @@ -137,10 +130,15 @@ pub(crate) fn generate_trait_from_impl(acc: &mut Assists, ctx: &AssistContext<'_ elements.insert(1, gen_args.syntax().clone().into()); } - ted::insert_all(Position::before(impl_name.syntax()), elements); + let mut editor = builder.make_editor(impl_ast.syntax()); + impl_assoc_items.assoc_items().for_each(|item| { + remove_items_visibility(&mut editor, &item); + }); + + editor.insert_all(Position::before(impl_name.syntax()), elements); // Insert trait before TraitImpl - ted::insert_all_raw( + editor.insert_all( Position::before(impl_ast.syntax()), vec![ trait_ast.syntax().clone().into(), @@ -150,11 +148,12 @@ pub(crate) fn generate_trait_from_impl(acc: &mut Assists, ctx: &AssistContext<'_ // Link the trait name & trait ref names together as a placeholder snippet group if let Some(cap) = ctx.config.snippet_cap { - builder.add_placeholder_snippet_group( - cap, - vec![trait_name.syntax().clone(), trait_name_ref.syntax().clone()], - ); + let placeholder = builder.make_placeholder_snippet(cap); + editor.add_annotation(trait_name.syntax(), placeholder); + editor.add_annotation(trait_name_ref.syntax(), placeholder); } + + builder.add_file_edits(ctx.vfs_file_id(), editor); }, ); @@ -162,19 +161,21 @@ pub(crate) fn generate_trait_from_impl(acc: &mut Assists, ctx: &AssistContext<'_ } /// `E0449` Trait items always share the visibility of their trait -fn remove_items_visibility(item: &ast::AssocItem) { +fn remove_items_visibility(editor: &mut SyntaxEditor, item: &ast::AssocItem) { if let Some(has_vis) = ast::AnyHasVisibility::cast(item.syntax().clone()) { if let Some(vis) = has_vis.visibility() && let Some(token) = vis.syntax().next_sibling_or_token() && token.kind() == SyntaxKind::WHITESPACE { - ted::remove(token); + editor.delete(token); + } + if let Some(vis) = has_vis.visibility() { + editor.delete(vis.syntax()); } - has_vis.set_visibility(None); } } -fn strip_body(item: &ast::AssocItem) { +fn strip_body(editor: &mut SyntaxEditor, item: &ast::AssocItem) { if let ast::AssocItem::Fn(f) = item && let Some(body) = f.body() { @@ -183,10 +184,10 @@ fn strip_body(item: &ast::AssocItem) { if let Some(prev) = body.syntax().prev_sibling_or_token() && prev.kind() == SyntaxKind::WHITESPACE { - ted::remove(prev); + editor.delete(prev); } - ted::replace(body.syntax(), make::tokens::semicolon()); + editor.replace(body.syntax(), make::tokens::semicolon()); }; } From 3abbdffdbfe05a596e59dbd6d81a4f17e4d68044 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 3 Aug 2025 17:43:11 +1000 Subject: [PATCH 0379/1134] For "stage 1" ui-fulldeps, use the stage 1 compiler to query target info Testing ui-fulldeps in "stage 1" actually uses the stage 0 compiler, so that test programs can link against stage 1 rustc crates. Unfortunately, using the stage 0 compiler causes problems when compiletest tries to obtain target information from the compiler, but the output format has changed since the last bootstrap beta bump. We can work around this by also providing compiletest with a stage 1 compiler, and having it use that compiler to query for target information. --- src/bootstrap/src/core/build_steps/test.rs | 8 +++++ src/tools/compiletest/src/common.rs | 35 +++++++++++++++------- src/tools/compiletest/src/lib.rs | 7 +++++ 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index ffc5dfad459d..8bee00a9c137 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1663,7 +1663,11 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the // bootstrap compiler. // NOTE: Only stage 1 is special cased because we need the rustc_private artifacts to match the // running compiler in stage 2 when plugins run. + let query_compiler; let (stage, stage_id) = if suite == "ui-fulldeps" && compiler.stage == 1 { + // Even when using the stage 0 compiler, we also need to provide the stage 1 compiler + // so that compiletest can query it for target information. + query_compiler = Some(compiler); // At stage 0 (stage - 1) we are using the stage0 compiler. Using `self.target` can lead // finding an incorrect compiler path on cross-targets, as the stage 0 is always equal to // `build.build` in the configuration. @@ -1672,6 +1676,7 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the let test_stage = compiler.stage + 1; (test_stage, format!("stage{test_stage}-{build}")) } else { + query_compiler = None; let stage = compiler.stage; (stage, format!("stage{stage}-{target}")) }; @@ -1716,6 +1721,9 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler)); cmd.arg("--run-lib-path").arg(builder.sysroot_target_libdir(compiler, target)); cmd.arg("--rustc-path").arg(builder.rustc(compiler)); + if let Some(query_compiler) = query_compiler { + cmd.arg("--query-rustc-path").arg(builder.rustc(query_compiler)); + } // Minicore auxiliary lib for `no_core` tests that need `core` stubs in cross-compilation // scenarios. diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index aceae3e3a3b9..2d49b1a7097d 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -279,6 +279,15 @@ pub struct Config { /// [`Self::rustc_path`]. pub stage0_rustc_path: Option, + /// Path to the stage 1 or higher `rustc` used to obtain target information via + /// `--print=all-target-specs-json` and similar queries. + /// + /// Normally this is unset, because [`Self::rustc_path`] can be used instead. + /// But when running "stage 1" ui-fulldeps tests, `rustc_path` is a stage 0 + /// compiler, whereas target specs must be obtained from a stage 1+ compiler + /// (in case the JSON format has changed since the last bootstrap bump). + pub query_rustc_path: Option, + /// Path to the `rustdoc`-under-test. Like [`Self::rustc_path`], this `rustdoc` is *staged*. pub rustdoc_path: Option, @@ -712,6 +721,7 @@ impl Config { rustc_path: Utf8PathBuf::default(), cargo_path: Default::default(), stage0_rustc_path: Default::default(), + query_rustc_path: Default::default(), rustdoc_path: Default::default(), coverage_dump_path: Default::default(), python: Default::default(), @@ -917,7 +927,7 @@ pub struct TargetCfgs { impl TargetCfgs { fn new(config: &Config) -> TargetCfgs { - let mut targets: HashMap = serde_json::from_str(&rustc_output( + let mut targets: HashMap = serde_json::from_str(&query_rustc_output( config, &["--print=all-target-specs-json", "-Zunstable-options"], Default::default(), @@ -950,7 +960,7 @@ impl TargetCfgs { if config.target.ends_with(".json") || !envs.is_empty() { targets.insert( config.target.clone(), - serde_json::from_str(&rustc_output( + serde_json::from_str(&query_rustc_output( config, &[ "--print=target-spec-json", @@ -1009,10 +1019,13 @@ impl TargetCfgs { // which are respected for `--print=cfg` but not for `--print=all-target-specs-json`. The // code below extracts them from `--print=cfg`: make sure to only override fields that can // actually be changed with `-C` flags. - for config in - rustc_output(config, &["--print=cfg", "--target", &config.target], Default::default()) - .trim() - .lines() + for config in query_rustc_output( + config, + &["--print=cfg", "--target", &config.target], + Default::default(), + ) + .trim() + .lines() { let (name, value) = config .split_once("=\"") @@ -1113,7 +1126,7 @@ pub enum Endian { } fn builtin_cfg_names(config: &Config) -> HashSet { - rustc_output( + query_rustc_output( config, &["--print=check-cfg", "-Zunstable-options", "--check-cfg=cfg()"], Default::default(), @@ -1128,7 +1141,7 @@ pub const KNOWN_CRATE_TYPES: &[&str] = &["bin", "cdylib", "dylib", "lib", "proc-macro", "rlib", "staticlib"]; fn supported_crate_types(config: &Config) -> HashSet { - let crate_types: HashSet<_> = rustc_output( + let crate_types: HashSet<_> = query_rustc_output( config, &["--target", &config.target, "--print=supported-crate-types", "-Zunstable-options"], Default::default(), @@ -1149,8 +1162,10 @@ fn supported_crate_types(config: &Config) -> HashSet { crate_types } -fn rustc_output(config: &Config, args: &[&str], envs: HashMap) -> String { - let mut command = Command::new(&config.rustc_path); +fn query_rustc_output(config: &Config, args: &[&str], envs: HashMap) -> String { + let query_rustc_path = config.query_rustc_path.as_deref().unwrap_or(&config.rustc_path); + + let mut command = Command::new(query_rustc_path); add_dylib_path(&mut command, iter::once(&config.compile_lib_path)); command.args(&config.target_rustcflags).args(args); command.env("RUSTC_BOOTSTRAP", "1"); diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index c712185733c6..f5409e783418 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -63,6 +63,12 @@ pub fn parse_config(args: Vec) -> Config { "path to rustc to use for compiling run-make recipes", "PATH", ) + .optopt( + "", + "query-rustc-path", + "path to rustc to use for querying target information (defaults to `--rustc-path`)", + "PATH", + ) .optopt("", "rustdoc-path", "path to rustdoc to use for compiling", "PATH") .optopt("", "coverage-dump-path", "path to coverage-dump to use in tests", "PATH") .reqopt("", "python", "path to python to use for doc tests", "PATH") @@ -354,6 +360,7 @@ pub fn parse_config(args: Vec) -> Config { rustc_path: opt_path(matches, "rustc-path"), cargo_path: matches.opt_str("cargo-path").map(Utf8PathBuf::from), stage0_rustc_path: matches.opt_str("stage0-rustc-path").map(Utf8PathBuf::from), + query_rustc_path: matches.opt_str("query-rustc-path").map(Utf8PathBuf::from), rustdoc_path: matches.opt_str("rustdoc-path").map(Utf8PathBuf::from), coverage_dump_path: matches.opt_str("coverage-dump-path").map(Utf8PathBuf::from), python: matches.opt_str("python").unwrap(), From df524163be45ba32cd019529771c41605a11abe7 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 1 Aug 2025 08:10:16 +1000 Subject: [PATCH 0380/1134] Mark `Printer` methods as unreachable where appropriate. This helps me understand the structure of the code a lot. If any of these are actually reachable, we can put the old code back, add a new test case, and we will have improved our test coverage. --- compiler/rustc_const_eval/src/util/type_name.rs | 2 +- compiler/rustc_lint/src/context.rs | 16 ++++++++-------- compiler/rustc_symbol_mangling/src/legacy.rs | 2 +- .../src/error_reporting/infer/mod.rs | 11 +++++++---- 4 files changed, 17 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index e8f2728a7728..1a509048262e 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -18,7 +18,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { } fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `::should_print_region` returns false } fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index b694d3dd49b7..70feb49d0dd1 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -756,22 +756,22 @@ impl<'tcx> LateContext<'tcx> { } fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_dyn_existential( &mut self, _predicates: &'tcx ty::List>, ) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { @@ -784,10 +784,10 @@ impl<'tcx> LateContext<'tcx> { self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { - if trait_ref.is_none() { - if let ty::Adt(def, args) = self_ty.kind() { - return self.print_def_path(def.did(), args); - } + if trait_ref.is_none() + && let ty::Adt(def, args) = self_ty.kind() + { + return self.print_def_path(def.did(), args); } // This shouldn't ever be needed, but just in case: diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index 12d1de463136..b75e793dfd3a 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -236,7 +236,7 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> { } fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `::should_print_region` returns false } fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index b9acadc406e9..c158cce96573 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -235,28 +235,29 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { - Err(fmt::Error) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> { - Err(fmt::Error) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_dyn_existential( &mut self, _predicates: &'tcx ty::List>, ) -> Result<(), PrintError> { - Err(fmt::Error) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> { - Err(fmt::Error) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { self.segments = vec![self.tcx.crate_name(cnum)]; Ok(()) } + fn path_qualified( &mut self, _self_ty: Ty<'tcx>, @@ -274,6 +275,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ) -> Result<(), PrintError> { Err(fmt::Error) } + fn path_append( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, @@ -283,6 +285,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { self.segments.push(disambiguated_data.as_sym(true)); Ok(()) } + fn path_generic_args( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, From bd0a308ca28d599d0dd798e925d1cb57bc96e616 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 1 Aug 2025 08:33:57 +1000 Subject: [PATCH 0381/1134] Inline and remove two `FmtPrinter` methods. They each have a single call site. --- compiler/rustc_middle/src/ty/print/pretty.rs | 46 +++++--------------- 1 file changed, 12 insertions(+), 34 deletions(-) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 71eac294f155..38db784dd42e 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2456,7 +2456,12 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { where T: Print<'tcx, Self> + TypeFoldable>, { - self.pretty_print_in_binder(value) + let old_region_index = self.region_index; + let (new_value, _) = self.name_all_regions(value, WrapBinderMode::ForAll)?; + new_value.print(self)?; + self.region_index = old_region_index; + self.binder_depth -= 1; + Ok(()) } fn wrap_binder Result<(), PrintError>>( @@ -2468,7 +2473,12 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { where T: TypeFoldable>, { - self.pretty_wrap_binder(value, mode, f) + let old_region_index = self.region_index; + let (new_value, _) = self.name_all_regions(value, mode)?; + f(&new_value, self)?; + self.region_index = old_region_index; + self.binder_depth -= 1; + Ok(()) } fn typed_value( @@ -2855,38 +2865,6 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { Ok((new_value, map)) } - pub fn pretty_print_in_binder( - &mut self, - value: &ty::Binder<'tcx, T>, - ) -> Result<(), fmt::Error> - where - T: Print<'tcx, Self> + TypeFoldable>, - { - let old_region_index = self.region_index; - let (new_value, _) = self.name_all_regions(value, WrapBinderMode::ForAll)?; - new_value.print(self)?; - self.region_index = old_region_index; - self.binder_depth -= 1; - Ok(()) - } - - pub fn pretty_wrap_binder Result<(), fmt::Error>>( - &mut self, - value: &ty::Binder<'tcx, T>, - mode: WrapBinderMode, - f: C, - ) -> Result<(), fmt::Error> - where - T: TypeFoldable>, - { - let old_region_index = self.region_index; - let (new_value, _) = self.name_all_regions(value, mode)?; - f(&new_value, self)?; - self.region_index = old_region_index; - self.binder_depth -= 1; - Ok(()) - } - fn prepare_region_info(&mut self, value: &ty::Binder<'tcx, T>) where T: TypeFoldable>, From e7d6a0776b06673b5a6258bd7476f1f39ab86756 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 1 Aug 2025 09:18:35 +1000 Subject: [PATCH 0382/1134] Remove `type_name::AbsolutePathPrinter::comma_sep`. It's equivalent to the default `PrettyPrinter::comma_sep`. --- compiler/rustc_const_eval/src/util/type_name.rs | 15 +-------------- compiler/rustc_symbol_mangling/src/legacy.rs | 2 ++ 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index 1a509048262e..2e8b9ea010e9 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -4,7 +4,7 @@ use rustc_data_structures::intern::Interned; use rustc_hir::def_id::CrateNum; use rustc_hir::definitions::DisambiguatedDefPathData; use rustc_middle::bug; -use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer}; +use rustc_middle::ty::print::{PrettyPrinter, PrintError, Printer}; use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt}; struct AbsolutePathPrinter<'tcx> { @@ -138,19 +138,6 @@ impl<'tcx> PrettyPrinter<'tcx> for AbsolutePathPrinter<'tcx> { fn should_print_region(&self, _region: ty::Region<'_>) -> bool { false } - fn comma_sep(&mut self, mut elems: impl Iterator) -> Result<(), PrintError> - where - T: Print<'tcx, Self>, - { - if let Some(first) = elems.next() { - first.print(self)?; - for elem in elems { - self.path.push_str(", "); - elem.print(self)?; - } - } - Ok(()) - } fn generic_delimiters( &mut self, diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index b75e793dfd3a..a3bc650427b7 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -460,6 +460,8 @@ impl<'tcx> PrettyPrinter<'tcx> for SymbolPrinter<'tcx> { fn should_print_region(&self, _region: ty::Region<'_>) -> bool { false } + + // Identical to `PrettyPrinter::comma_sep` except there is no space after each comma. fn comma_sep(&mut self, mut elems: impl Iterator) -> Result<(), PrintError> where T: Print<'tcx, Self>, From 1698c8e322d0cd95aea94b85ef098e5ccfe3c856 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 1 Aug 2025 10:41:11 +1000 Subject: [PATCH 0383/1134] Rename `Printer` variables. Currently they are mostly named `cx`, which is a terrible name for a type that impls `Printer`/`PrettyPrinter`, and is easy to confuse with other types like `TyCtxt`. This commit changes them to `p`. A couple of existing `p` variables had to be renamed to make way. --- .../rustc_borrowck/src/diagnostics/mod.rs | 16 +- .../rustc_const_eval/src/interpret/operand.rs | 13 +- .../rustc_const_eval/src/util/type_name.rs | 6 +- compiler/rustc_lint/src/context.rs | 6 +- compiler/rustc_middle/src/mir/pretty.rs | 34 +-- compiler/rustc_middle/src/ty/error.rs | 24 +-- compiler/rustc_middle/src/ty/instance.rs | 6 +- compiler/rustc_middle/src/ty/print/mod.rs | 38 ++-- compiler/rustc_middle/src/ty/print/pretty.rs | 196 +++++++++--------- .../rustc_middle/src/ty/structural_impls.rs | 14 +- compiler/rustc_symbol_mangling/src/legacy.rs | 60 +++--- compiler/rustc_symbol_mangling/src/v0.rs | 74 +++---- .../src/error_reporting/infer/mod.rs | 4 +- .../error_reporting/infer/need_type_info.rs | 51 +++-- .../nice_region_error/placeholder_error.rs | 8 +- .../error_reporting/infer/note_and_explain.rs | 4 +- .../src/error_reporting/traits/overflow.rs | 6 +- 17 files changed, 279 insertions(+), 281 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 56fdaf1c724a..34bed375cb96 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -613,7 +613,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime /// name where required. pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String { - let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS); + let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS); // We need to add synthesized lifetimes where appropriate. We do // this by hooking into the pretty printer and telling it to label the @@ -624,19 +624,19 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { | ty::RePlaceholder(ty::PlaceholderRegion { bound: ty::BoundRegion { kind: br, .. }, .. - }) => printer.region_highlight_mode.highlighting_bound_region(br, counter), + }) => p.region_highlight_mode.highlighting_bound_region(br, counter), _ => {} } } - ty.print(&mut printer).unwrap(); - printer.into_buffer() + ty.print(&mut p).unwrap(); + p.into_buffer() } /// Returns the name of the provided `Ty` (that must be a reference)'s region with a /// synthesized lifetime name where required. pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String { - let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS); + let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS); let region = if let ty::Ref(region, ..) = ty.kind() { match region.kind() { @@ -644,7 +644,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { | ty::RePlaceholder(ty::PlaceholderRegion { bound: ty::BoundRegion { kind: br, .. }, .. - }) => printer.region_highlight_mode.highlighting_bound_region(br, counter), + }) => p.region_highlight_mode.highlighting_bound_region(br, counter), _ => {} } region @@ -652,8 +652,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { bug!("ty for annotation of borrow region is not a reference"); }; - region.print(&mut printer).unwrap(); - printer.into_buffer() + region.print(&mut p).unwrap(); + p.into_buffer() } /// Add a note to region errors and borrow explanations when higher-ranked regions in predicates diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 417134579086..145418090700 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -188,18 +188,18 @@ pub struct ImmTy<'tcx, Prov: Provenance = CtfeProvenance> { impl std::fmt::Display for ImmTy<'_, Prov> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// Helper function for printing a scalar to a FmtPrinter - fn p<'a, 'tcx, Prov: Provenance>( - cx: &mut FmtPrinter<'a, 'tcx>, + fn print_scalar<'a, 'tcx, Prov: Provenance>( + p: &mut FmtPrinter<'a, 'tcx>, s: Scalar, ty: Ty<'tcx>, ) -> Result<(), std::fmt::Error> { match s { - Scalar::Int(int) => cx.pretty_print_const_scalar_int(int, ty, true), + Scalar::Int(int) => p.pretty_print_const_scalar_int(int, ty, true), Scalar::Ptr(ptr, _sz) => { // Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to // print what is points to, which would fail since it has no access to the local // memory. - cx.pretty_print_const_pointer(ptr, ty) + p.pretty_print_const_pointer(ptr, ty) } } } @@ -207,8 +207,9 @@ impl std::fmt::Display for ImmTy<'_, Prov> { match self.imm { Immediate::Scalar(s) => { if let Some(ty) = tcx.lift(self.layout.ty) { - let s = - FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| p(cx, s, ty))?; + let s = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| { + print_scalar(p, s, ty) + })?; f.write_str(&s)?; return Ok(()); } diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index 2e8b9ea010e9..400ba23ae5f9 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -166,7 +166,7 @@ impl Write for AbsolutePathPrinter<'_> { } pub fn type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String { - let mut printer = AbsolutePathPrinter { tcx, path: String::new() }; - printer.print_type(ty).unwrap(); - printer.path + let mut p = AbsolutePathPrinter { tcx, path: String::new() }; + p.print_type(ty).unwrap(); + p.path } diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 70feb49d0dd1..7e35d4d142bd 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -854,9 +854,9 @@ impl<'tcx> LateContext<'tcx> { } } - let mut printer = AbsolutePathPrinter { tcx: self.tcx, path: vec![] }; - printer.print_def_path(def_id, &[]).unwrap(); - printer.path + let mut p = AbsolutePathPrinter { tcx: self.tcx, path: vec![] }; + p.print_def_path(def_id, &[]).unwrap(); + p.path } /// Returns the associated type `name` for `self_ty` as an implementation of `trait_id`. diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 809cdb329f79..f8a48005a736 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -1197,8 +1197,8 @@ impl<'tcx> Debug for Rvalue<'tcx> { ty::tls::with(|tcx| { let variant_def = &tcx.adt_def(adt_did).variant(variant); let args = tcx.lift(args).expect("could not lift for printing"); - let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| { - cx.print_def_path(variant_def.def_id, args) + let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| { + p.print_def_path(variant_def.def_id, args) })?; match variant_def.ctor_kind() { @@ -1473,9 +1473,9 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { }; let fmt_valtree = |cv: &ty::Value<'tcx>| { - let mut cx = FmtPrinter::new(self.tcx, Namespace::ValueNS); - cx.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap(); - cx.into_buffer() + let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS); + p.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap(); + p.into_buffer() }; let val = match const_ { @@ -1967,10 +1967,10 @@ fn pretty_print_const_value_tcx<'tcx>( .expect("destructed mir constant of adt without variant idx"); let variant_def = &def.variant(variant_idx); let args = tcx.lift(args).unwrap(); - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.print_alloc_ids = true; - cx.print_value_path(variant_def.def_id, args)?; - fmt.write_str(&cx.into_buffer())?; + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.print_alloc_ids = true; + p.print_value_path(variant_def.def_id, args)?; + fmt.write_str(&p.into_buffer())?; match variant_def.ctor_kind() { Some(CtorKind::Const) => {} @@ -2001,18 +2001,18 @@ fn pretty_print_const_value_tcx<'tcx>( } } (ConstValue::Scalar(scalar), _) => { - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.print_alloc_ids = true; + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.print_alloc_ids = true; let ty = tcx.lift(ty).unwrap(); - cx.pretty_print_const_scalar(scalar, ty)?; - fmt.write_str(&cx.into_buffer())?; + p.pretty_print_const_scalar(scalar, ty)?; + fmt.write_str(&p.into_buffer())?; return Ok(()); } (ConstValue::ZeroSized, ty::FnDef(d, s)) => { - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.print_alloc_ids = true; - cx.print_value_path(*d, s)?; - fmt.write_str(&cx.into_buffer())?; + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.print_alloc_ids = true; + p.print_value_path(*d, s)?; + fmt.write_str(&p.into_buffer())?; return Ok(()); } // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 13723874ad3a..c24dc983d216 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -213,13 +213,13 @@ impl<'tcx> Ty<'tcx> { } impl<'tcx> TyCtxt<'tcx> { - pub fn string_with_limit(self, p: T, length_limit: usize) -> String + pub fn string_with_limit(self, t: T, length_limit: usize) -> String where T: Copy + for<'a, 'b> Lift, Lifted: Print<'b, FmtPrinter<'a, 'b>>>, { let mut type_limit = 50; - let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| { - self.lift(p).expect("could not lift for printing").print(cx) + let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |p| { + self.lift(t).expect("could not lift for printing").print(p) }) .expect("could not write to `String`"); if regular.len() <= length_limit { @@ -229,16 +229,16 @@ impl<'tcx> TyCtxt<'tcx> { loop { // Look for the longest properly trimmed path that still fits in length_limit. short = with_forced_trimmed_paths!({ - let mut cx = FmtPrinter::new_with_limit( + let mut p = FmtPrinter::new_with_limit( self, hir::def::Namespace::TypeNS, rustc_session::Limit(type_limit), ); - self.lift(p) + self.lift(t) .expect("could not lift for printing") - .print(&mut cx) + .print(&mut p) .expect("could not print type"); - cx.into_buffer() + p.into_buffer() }); if short.len() <= length_limit || type_limit == 0 { break; @@ -252,12 +252,12 @@ impl<'tcx> TyCtxt<'tcx> { /// `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that keeps /// the existence of a "long type" anywhere in the diagnostic, so the note telling the user /// where we wrote the file to is only printed once. - pub fn short_string(self, p: T, path: &mut Option) -> String + pub fn short_string(self, t: T, path: &mut Option) -> String where T: Copy + Hash + for<'a, 'b> Lift, Lifted: Print<'b, FmtPrinter<'a, 'b>>>, { - let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| { - self.lift(p).expect("could not lift for printing").print(cx) + let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |p| { + self.lift(t).expect("could not lift for printing").print(p) }) .expect("could not write to `String`"); @@ -270,13 +270,13 @@ impl<'tcx> TyCtxt<'tcx> { if regular.len() <= width * 2 / 3 { return regular; } - let short = self.string_with_limit(p, length_limit); + let short = self.string_with_limit(t, length_limit); if regular == short { return regular; } // Ensure we create an unique file for the type passed in when we create a file. let mut s = DefaultHasher::new(); - p.hash(&mut s); + t.hash(&mut s); let hash = s.finish(); *path = Some(path.take().unwrap_or_else(|| { self.output_filenames(()).temp_path_for_diagnostic(&format!("long-type-{hash}.txt")) diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index eb35a9520326..16873b6ee21a 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -397,13 +397,13 @@ pub fn fmt_instance( ty::tls::with(|tcx| { let args = tcx.lift(instance.args).expect("could not lift for printing"); - let mut cx = if let Some(type_length) = type_length { + let mut p = if let Some(type_length) = type_length { FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length) } else { FmtPrinter::new(tcx, Namespace::ValueNS) }; - cx.print_def_path(instance.def_id(), args)?; - let s = cx.into_buffer(); + p.print_def_path(instance.def_id(), args)?; + let s = p.into_buffer(); f.write_str(&s) })?; diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index 9172c5d3ab75..1fee9d945f65 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -18,7 +18,7 @@ use super::Lift; pub type PrintError = std::fmt::Error; pub trait Print<'tcx, P> { - fn print(&self, cx: &mut P) -> Result<(), PrintError>; + fn print(&self, p: &mut P) -> Result<(), PrintError>; } /// Interface for outputting user-facing "type-system entities" @@ -148,7 +148,7 @@ pub trait Printer<'tcx>: Sized { && args.len() > parent_args.len() { return self.path_generic_args( - |cx| cx.print_def_path(def_id, parent_args), + |p| p.print_def_path(def_id, parent_args), &args[..parent_args.len() + 1][..1], ); } else { @@ -170,7 +170,7 @@ pub trait Printer<'tcx>: Sized { if !generics.is_own_empty() && args.len() >= generics.count() { let args = generics.own_args_no_defaults(self.tcx(), args); return self.path_generic_args( - |cx| cx.print_def_path(def_id, parent_args), + |p| p.print_def_path(def_id, parent_args), args, ); } @@ -186,16 +186,16 @@ pub trait Printer<'tcx>: Sized { } self.path_append( - |cx: &mut Self| { + |p: &mut Self| { if trait_qualify_parent { let trait_ref = ty::TraitRef::new( - cx.tcx(), + p.tcx(), parent_def_id, parent_args.iter().copied(), ); - cx.path_qualified(trait_ref.self_ty(), Some(trait_ref)) + p.path_qualified(trait_ref.self_ty(), Some(trait_ref)) } else { - cx.print_def_path(parent_def_id, parent_args) + p.print_def_path(parent_def_id, parent_args) } }, &key.disambiguated_data, @@ -237,7 +237,7 @@ pub trait Printer<'tcx>: Sized { // trait-type, then fallback to a format that identifies // the module more clearly. self.path_append_impl( - |cx| cx.print_def_path(parent_def_id, &[]), + |p| p.print_def_path(parent_def_id, &[]), &key.disambiguated_data, self_ty, impl_trait_ref, @@ -312,26 +312,26 @@ pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option { } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Region<'tcx> { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_region(*self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_region(*self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for Ty<'tcx> { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_type(*self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_type(*self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for &'tcx ty::List> { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_dyn_existential(self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_dyn_existential(self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Const<'tcx> { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_const(*self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_const(*self) } } @@ -351,9 +351,9 @@ where { fn print(t: &T, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ty::tls::with(|tcx| { - let mut cx = FmtPrinter::new(tcx, Namespace::TypeNS); - tcx.lift(*t).expect("could not lift for printing").print(&mut cx)?; - fmt.write_str(&cx.into_buffer())?; + let mut p = FmtPrinter::new(tcx, Namespace::TypeNS); + tcx.lift(*t).expect("could not lift for printing").print(&mut p)?; + fmt.write_str(&p.into_buffer())?; Ok(()) }) } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 38db784dd42e..2b5425e50275 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -31,26 +31,26 @@ use crate::ty::{ macro_rules! p { (@$lit:literal) => { - write!(scoped_cx!(), $lit)? + write!(scoped_printer!(), $lit)? }; (@write($($data:expr),+)) => { - write!(scoped_cx!(), $($data),+)? + write!(scoped_printer!(), $($data),+)? }; (@print($x:expr)) => { - $x.print(scoped_cx!())? + $x.print(scoped_printer!())? }; (@$method:ident($($arg:expr),*)) => { - scoped_cx!().$method($($arg),*)? + scoped_printer!().$method($($arg),*)? }; ($($elem:tt $(($($args:tt)*))?),+) => {{ $(p!(@ $elem $(($($args)*))?);)+ }}; } -macro_rules! define_scoped_cx { - ($cx:ident) => { - macro_rules! scoped_cx { +macro_rules! define_scoped_printer { + ($p:ident) => { + macro_rules! scoped_printer { () => { - $cx + $p }; } }; @@ -689,8 +689,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } } - self.generic_delimiters(|cx| { - define_scoped_cx!(cx); + self.generic_delimiters(|p| { + define_scoped_printer!(p); p!(print(self_ty)); if let Some(trait_ref) = trait_ref { @@ -708,8 +708,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ) -> Result<(), PrintError> { print_prefix(self)?; - self.generic_delimiters(|cx| { - define_scoped_cx!(cx); + self.generic_delimiters(|p| { + define_scoped_printer!(p); p!("impl "); if let Some(trait_ref) = trait_ref { @@ -722,7 +722,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } fn pretty_print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { - define_scoped_cx!(self); + define_scoped_printer!(self); match *ty.kind() { ty::Bool => p!("bool"), @@ -769,8 +769,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } ty::FnPtr(ref sig_tys, hdr) => p!(print(sig_tys.with(hdr))), ty::UnsafeBinder(ref bound_ty) => { - self.wrap_binder(bound_ty, WrapBinderMode::Unsafe, |ty, cx| { - cx.pretty_print_type(*ty) + self.wrap_binder(bound_ty, WrapBinderMode::Unsafe, |ty, p| { + p.pretty_print_type(*ty) })?; } ty::Infer(infer_ty) => { @@ -1137,8 +1137,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { self.wrap_binder( &bound_args_and_self_ty, WrapBinderMode::ForAll, - |(args, _), cx| { - define_scoped_cx!(cx); + |(args, _), p| { + define_scoped_printer!(p); p!(write("{}", tcx.item_name(trait_def_id))); p!("("); @@ -1181,8 +1181,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { for (trait_pred, assoc_items) in traits { write!(self, "{}", if first { "" } else { " + " })?; - self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, cx| { - define_scoped_cx!(cx); + self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, p| { + define_scoped_printer!(p); if trait_pred.polarity == ty::PredicatePolarity::Negative { p!("!"); @@ -1322,9 +1322,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ) -> Result<(), PrintError> { let def_key = self.tcx().def_key(alias_ty.def_id); self.path_generic_args( - |cx| { - cx.path_append( - |cx| cx.path_qualified(alias_ty.self_ty(), None), + |p| { + p.path_append( + |p| p.path_qualified(alias_ty.self_ty(), None), &def_key.disambiguated_data, ) }, @@ -1388,15 +1388,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let mut first = true; if let Some(bound_principal) = predicates.principal() { - self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, cx| { - define_scoped_cx!(cx); + self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, p| { + define_scoped_printer!(p); p!(print_def_path(principal.def_id, &[])); let mut resugared = false; // Special-case `Fn(...) -> ...` and re-sugar it. - let fn_trait_kind = cx.tcx().fn_trait_kind_from_def_id(principal.def_id); - if !cx.should_print_verbose() && fn_trait_kind.is_some() { + let fn_trait_kind = p.tcx().fn_trait_kind_from_def_id(principal.def_id); + if !p.should_print_verbose() && fn_trait_kind.is_some() { if let ty::Tuple(tys) = principal.args.type_at(0).kind() { let mut projections = predicates.projection_bounds(); if let (Some(proj), None) = (projections.next(), projections.next()) { @@ -1414,18 +1414,18 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // in order to place the projections inside the `<...>`. if !resugared { let principal_with_self = - principal.with_self_ty(cx.tcx(), cx.tcx().types.trait_object_dummy_self); + principal.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self); - let args = cx + let args = p .tcx() .generics_of(principal_with_self.def_id) - .own_args_no_defaults(cx.tcx(), principal_with_self.args); + .own_args_no_defaults(p.tcx(), principal_with_self.args); let bound_principal_with_self = bound_principal - .with_self_ty(cx.tcx(), cx.tcx().types.trait_object_dummy_self); + .with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self); - let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(cx.tcx()); - let super_projections: Vec<_> = elaborate::elaborate(cx.tcx(), [clause]) + let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(p.tcx()); + let super_projections: Vec<_> = elaborate::elaborate(p.tcx(), [clause]) .filter_only_self() .filter_map(|clause| clause.as_projection_clause()) .collect(); @@ -1436,15 +1436,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // Filter out projections that are implied by the super predicates. let proj_is_implied = super_projections.iter().any(|&super_proj| { let super_proj = super_proj.map_bound(|super_proj| { - ty::ExistentialProjection::erase_self_ty(cx.tcx(), super_proj) + ty::ExistentialProjection::erase_self_ty(p.tcx(), super_proj) }); // This function is sometimes called on types with erased and // anonymized regions, but the super projections can still // contain named regions. So we erase and anonymize everything // here to compare the types modulo regions below. - let proj = cx.tcx().erase_regions(proj); - let super_proj = cx.tcx().erase_regions(super_proj); + let proj = p.tcx().erase_regions(proj); + let super_proj = p.tcx().erase_regions(super_proj); proj == super_proj }); @@ -1458,15 +1458,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { .collect(); projections - .sort_by_cached_key(|proj| cx.tcx().item_name(proj.def_id).to_string()); + .sort_by_cached_key(|proj| p.tcx().item_name(proj.def_id).to_string()); if !args.is_empty() || !projections.is_empty() { - p!(generic_delimiters(|cx| { - cx.comma_sep(args.iter().copied())?; + p!(generic_delimiters(|p| { + p.comma_sep(args.iter().copied())?; if !args.is_empty() && !projections.is_empty() { - write!(cx, ", ")?; + write!(p, ", ")?; } - cx.comma_sep(projections.iter().copied()) + p.comma_sep(projections.iter().copied()) })); } } @@ -1476,11 +1476,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { first = false; } - define_scoped_cx!(self); + define_scoped_printer!(self); // Builtin bounds. // FIXME(eddyb) avoid printing twice (needed to ensure - // that the auto traits are sorted *and* printed via cx). + // that the auto traits are sorted *and* printed via p). let mut auto_traits: Vec<_> = predicates.auto_traits().collect(); // The auto traits come ordered by `DefPathHash`. While @@ -1510,7 +1510,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { c_variadic: bool, output: Ty<'tcx>, ) -> Result<(), PrintError> { - define_scoped_cx!(self); + define_scoped_printer!(self); p!("(", comma_sep(inputs.iter().copied())); if c_variadic { @@ -1532,7 +1532,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ct: ty::Const<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_cx!(self); + define_scoped_printer!(self); if self.should_print_verbose() { p!(write("{:?}", ct)); @@ -1595,7 +1595,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { expr: Expr<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_cx!(self); + define_scoped_printer!(self); match expr.kind { ty::ExprKind::Binop(op) => { let (_, _, c1, c2) = expr.binop_args(); @@ -1718,7 +1718,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ptr: Pointer, ty: Ty<'tcx>, ) -> Result<(), PrintError> { - define_scoped_cx!(self); + define_scoped_printer!(self); let (prov, offset) = ptr.prov_and_relative_offset(); match ty.kind() { @@ -1778,7 +1778,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty: Ty<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_cx!(self); + define_scoped_printer!(self); match ty.kind() { // Bool @@ -1876,7 +1876,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { cv: ty::Value<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_cx!(self); + define_scoped_printer!(self); if with_reduced_queries() || self.should_print_verbose() { p!(write("ValTree({:?}: ", cv.valtree), print(cv.ty), ")"); @@ -2012,8 +2012,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn); write!(self, "impl ")?; - self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, cx| { - define_scoped_cx!(cx); + self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, p| { + define_scoped_printer!(p); p!(write("{kind}(")); for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() { @@ -2036,7 +2036,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { &mut self, constness: ty::BoundConstness, ) -> Result<(), PrintError> { - define_scoped_cx!(self); + define_scoped_printer!(self); match constness { ty::BoundConstness::Const => { @@ -2061,10 +2061,10 @@ pub(crate) fn pretty_print_const<'tcx>( ) -> fmt::Result { ty::tls::with(|tcx| { let literal = tcx.lift(c).unwrap(); - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.print_alloc_ids = true; - cx.pretty_print_const(literal, print_types)?; - fmt.write_str(&cx.into_buffer())?; + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.print_alloc_ids = true; + p.pretty_print_const(literal, print_types)?; + fmt.write_str(&p.into_buffer())?; Ok(()) }) } @@ -2184,7 +2184,7 @@ impl<'t> TyCtxt<'t> { let ns = guess_def_namespace(self, def_id); debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns); - FmtPrinter::print_string(self, ns, |cx| cx.print_def_path(def_id, args)).unwrap() + FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap() } pub fn value_path_str_with_args( @@ -2196,7 +2196,7 @@ impl<'t> TyCtxt<'t> { let ns = guess_def_namespace(self, def_id); debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns); - FmtPrinter::print_string(self, ns, |cx| cx.print_value_path(def_id, args)).unwrap() + FmtPrinter::print_string(self, ns, |p| p.print_value_path(def_id, args)).unwrap() } } @@ -2363,10 +2363,10 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { trait_ref: Option>, ) -> Result<(), PrintError> { self.pretty_path_append_impl( - |cx| { - print_prefix(cx)?; - if !cx.empty_path { - write!(cx, "::")?; + |p| { + print_prefix(p)?; + if !p.empty_path { + write!(p, "::")?; } Ok(()) @@ -2420,7 +2420,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { if self.in_value { write!(self, "::")?; } - self.generic_delimiters(|cx| cx.comma_sep(args.iter().copied())) + self.generic_delimiters(|p| p.comma_sep(args.iter().copied())) } else { Ok(()) } @@ -2562,7 +2562,7 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { ty: Ty<'tcx>, ) -> Result<(), PrintError> { let print = |this: &mut Self| { - define_scoped_cx!(this); + define_scoped_printer!(this); if this.print_alloc_ids { p!(write("{:?}", p)); } else { @@ -2577,7 +2577,7 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`. impl<'tcx> FmtPrinter<'_, 'tcx> { pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> { - define_scoped_cx!(self); + define_scoped_printer!(self); // Watch out for region highlights. let highlight = self.region_highlight_mode; @@ -2755,17 +2755,17 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { debug!("self.used_region_names: {:?}", self.used_region_names); let mut empty = true; - let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| { + let mut start_or_continue = |p: &mut Self, start: &str, cont: &str| { let w = if empty { empty = false; start } else { cont }; - let _ = write!(cx, "{w}"); + let _ = write!(p, "{w}"); }; - let do_continue = |cx: &mut Self, cont: Symbol| { - let _ = write!(cx, "{cont}"); + let do_continue = |p: &mut Self, cont: Symbol| { + let _ = write!(p, "{cont}"); }; let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}"))); @@ -2918,8 +2918,8 @@ impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T> where T: Print<'tcx, P> + TypeFoldable>, { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_in_binder(self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_in_binder(self) } } @@ -2927,8 +2927,8 @@ impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<' where T: Print<'tcx, P>, { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - define_scoped_cx!(cx); + fn print(&self, p: &mut P) -> Result<(), PrintError> { + define_scoped_printer!(p); p!(print(self.0), ": ", print(self.1)); Ok(()) } @@ -3068,11 +3068,11 @@ macro_rules! forward_display_to_print { $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { - let mut cx = FmtPrinter::new(tcx, Namespace::TypeNS); + let mut p = FmtPrinter::new(tcx, Namespace::TypeNS); tcx.lift(*self) .expect("could not lift for printing") - .print(&mut cx)?; - f.write_str(&cx.into_buffer())?; + .print(&mut p)?; + f.write_str(&p.into_buffer())?; Ok(()) }) } @@ -3081,10 +3081,10 @@ macro_rules! forward_display_to_print { } macro_rules! define_print { - (($self:ident, $cx:ident): $($ty:ty $print:block)+) => { + (($self:ident, $p:ident): $($ty:ty $print:block)+) => { $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty { - fn print(&$self, $cx: &mut P) -> Result<(), PrintError> { - define_scoped_cx!($cx); + fn print(&$self, $p: &mut P) -> Result<(), PrintError> { + define_scoped_printer!($p); let _: () = $print; Ok(()) } @@ -3093,8 +3093,8 @@ macro_rules! define_print { } macro_rules! define_print_and_forward_display { - (($self:ident, $cx:ident): $($ty:ty $print:block)+) => { - define_print!(($self, $cx): $($ty $print)*); + (($self:ident, $p:ident): $($ty:ty $print:block)+) => { + define_print!(($self, $p): $($ty $print)*); forward_display_to_print!($($ty),+); }; } @@ -3107,7 +3107,7 @@ forward_display_to_print! { } define_print! { - (self, cx): + (self, p): ty::FnSig<'tcx> { p!(write("{}", self.safety.prefix_str())); @@ -3129,11 +3129,11 @@ define_print! { } ty::AliasTerm<'tcx> { - match self.kind(cx.tcx()) { + match self.kind(p.tcx()) { ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p!(pretty_print_inherent_projection(*self)), ty::AliasTermKind::ProjectionTy => { - if !(cx.should_print_verbose() || with_reduced_queries()) - && cx.tcx().is_impl_trait_in_trait(self.def_id) + if !(p.should_print_verbose() || with_reduced_queries()) + && p.tcx().is_impl_trait_in_trait(self.def_id) { p!(pretty_print_rpitit(self.def_id, self.args)) } else { @@ -3222,46 +3222,46 @@ define_print! { ty::ExistentialTraitRef<'tcx> { // Use a type that can't appear in defaults of type parameters. - let dummy_self = Ty::new_fresh(cx.tcx(), 0); - let trait_ref = self.with_self_ty(cx.tcx(), dummy_self); + let dummy_self = Ty::new_fresh(p.tcx(), 0); + let trait_ref = self.with_self_ty(p.tcx(), dummy_self); p!(print(trait_ref.print_only_trait_path())) } ty::ExistentialProjection<'tcx> { - let name = cx.tcx().associated_item(self.def_id).name(); + let name = p.tcx().associated_item(self.def_id).name(); // The args don't contain the self ty (as it has been erased) but the corresp. // generics do as the trait always has a self ty param. We need to offset. - let args = &self.args[cx.tcx().generics_of(self.def_id).parent_count - 1..]; - p!(path_generic_args(|cx| write!(cx, "{name}"), args), " = ", print(self.term)) + let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..]; + p!(path_generic_args(|p| write!(p, "{name}"), args), " = ", print(self.term)) } ty::ProjectionPredicate<'tcx> { p!(print(self.projection_term), " == "); - cx.reset_type_limit(); + p.reset_type_limit(); p!(print(self.term)) } ty::SubtypePredicate<'tcx> { p!(print(self.a), " <: "); - cx.reset_type_limit(); + p.reset_type_limit(); p!(print(self.b)) } ty::CoercePredicate<'tcx> { p!(print(self.a), " -> "); - cx.reset_type_limit(); + p.reset_type_limit(); p!(print(self.b)) } ty::NormalizesTo<'tcx> { p!(print(self.alias), " normalizes-to "); - cx.reset_type_limit(); + p.reset_type_limit(); p!(print(self.term)) } } define_print_and_forward_display! { - (self, cx): + (self, p): &'tcx ty::List> { p!("{{", comma_sep(self.iter()), "}}") @@ -3273,10 +3273,10 @@ define_print_and_forward_display! { TraitRefPrintSugared<'tcx> { if !with_reduced_queries() - && cx.tcx().trait_def(self.0.def_id).paren_sugar + && p.tcx().trait_def(self.0.def_id).paren_sugar && let ty::Tuple(args) = self.0.args.type_at(1).kind() { - p!(write("{}", cx.tcx().item_name(self.0.def_id)), "("); + p!(write("{}", p.tcx().item_name(self.0.def_id)), "("); for (i, arg) in args.iter().enumerate() { if i > 0 { p!(", "); @@ -3322,9 +3322,9 @@ define_print_and_forward_display! { ty::PlaceholderType { match self.bound.kind { ty::BoundTyKind::Anon => p!(write("{self:?}")), - ty::BoundTyKind::Param(def_id) => match cx.should_print_verbose() { + ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() { true => p!(write("{self:?}")), - false => p!(write("{}", cx.tcx().item_name(def_id))), + false => p!(write("{}", p.tcx().item_name(def_id))), }, } } diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 10e499d9c758..0e2aff6f9bda 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -25,8 +25,8 @@ impl fmt::Debug for ty::TraitDef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { with_no_trimmed_paths!({ - let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |cx| { - cx.print_def_path(self.def_id, &[]) + let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |p| { + p.print_def_path(self.def_id, &[]) })?; f.write_str(&s) }) @@ -38,8 +38,8 @@ impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { with_no_trimmed_paths!({ - let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |cx| { - cx.print_def_path(self.did(), &[]) + let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |p| { + p.print_def_path(self.did(), &[]) })?; f.write_str(&s) }) @@ -170,9 +170,9 @@ impl<'tcx> fmt::Debug for ty::Const<'tcx> { if let ConstKind::Value(cv) = self.kind() { return ty::tls::with(move |tcx| { let cv = tcx.lift(cv).unwrap(); - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.pretty_print_const_valtree(cv, /*print_ty*/ true)?; - f.write_str(&cx.into_buffer()) + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.pretty_print_const_valtree(cv, /*print_ty*/ true)?; + f.write_str(&p.into_buffer()) }); } // Fall back to something verbose. diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index a3bc650427b7..d1834abb32b0 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -58,59 +58,57 @@ pub(super) fn mangle<'tcx>( let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate); - let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false }; - printer - .print_def_path( - def_id, - if let ty::InstanceKind::DropGlue(_, _) - | ty::InstanceKind::AsyncDropGlueCtorShim(_, _) - | ty::InstanceKind::FutureDropPollShim(_, _, _) = instance.def - { - // Add the name of the dropped type to the symbol name - &*instance.args - } else if let ty::InstanceKind::AsyncDropGlue(_, ty) = instance.def { - let ty::Coroutine(_, cor_args) = ty.kind() else { - bug!(); - }; - let drop_ty = cor_args.first().unwrap().expect_ty(); - tcx.mk_args(&[GenericArg::from(drop_ty)]) - } else { - &[] - }, - ) - .unwrap(); + let mut p = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false }; + p.print_def_path( + def_id, + if let ty::InstanceKind::DropGlue(_, _) + | ty::InstanceKind::AsyncDropGlueCtorShim(_, _) + | ty::InstanceKind::FutureDropPollShim(_, _, _) = instance.def + { + // Add the name of the dropped type to the symbol name + &*instance.args + } else if let ty::InstanceKind::AsyncDropGlue(_, ty) = instance.def { + let ty::Coroutine(_, cor_args) = ty.kind() else { + bug!(); + }; + let drop_ty = cor_args.first().unwrap().expect_ty(); + tcx.mk_args(&[GenericArg::from(drop_ty)]) + } else { + &[] + }, + ) + .unwrap(); match instance.def { ty::InstanceKind::ThreadLocalShim(..) => { - printer.write_str("{{tls-shim}}").unwrap(); + p.write_str("{{tls-shim}}").unwrap(); } ty::InstanceKind::VTableShim(..) => { - printer.write_str("{{vtable-shim}}").unwrap(); + p.write_str("{{vtable-shim}}").unwrap(); } ty::InstanceKind::ReifyShim(_, reason) => { - printer.write_str("{{reify-shim").unwrap(); + p.write_str("{{reify-shim").unwrap(); match reason { - Some(ReifyReason::FnPtr) => printer.write_str("-fnptr").unwrap(), - Some(ReifyReason::Vtable) => printer.write_str("-vtable").unwrap(), + Some(ReifyReason::FnPtr) => p.write_str("-fnptr").unwrap(), + Some(ReifyReason::Vtable) => p.write_str("-vtable").unwrap(), None => (), } - printer.write_str("}}").unwrap(); + p.write_str("}}").unwrap(); } // FIXME(async_closures): This shouldn't be needed when we fix // `Instance::ty`/`Instance::def_id`. ty::InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref, .. } => { - printer - .write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" }) + p.write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" }) .unwrap(); } _ => {} } if let ty::InstanceKind::FutureDropPollShim(..) = instance.def { - let _ = printer.write_str("{{drop-shim}}"); + let _ = p.write_str("{{drop-shim}}"); } - printer.path.finish(hash) + p.path.finish(hash) } fn get_symbol_hash<'tcx>( diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index fe0f8e6113ef..ce1eb1a16486 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -33,7 +33,7 @@ pub(super) fn mangle<'tcx>( let args = tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), instance.args); let prefix = "_R"; - let mut cx: SymbolMangler<'_> = SymbolMangler { + let mut p: SymbolMangler<'_> = SymbolMangler { tcx, start_offset: prefix.len(), is_exportable, @@ -69,16 +69,16 @@ pub(super) fn mangle<'tcx>( bug!(); }; let drop_ty = cor_args.first().unwrap().expect_ty(); - cx.print_def_path(def_id, tcx.mk_args(&[GenericArg::from(drop_ty)])).unwrap() + p.print_def_path(def_id, tcx.mk_args(&[GenericArg::from(drop_ty)])).unwrap() } else if let Some(shim_kind) = shim_kind { - cx.path_append_ns(|cx| cx.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap() + p.path_append_ns(|p| p.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap() } else { - cx.print_def_path(def_id, args).unwrap() + p.print_def_path(def_id, args).unwrap() }; if let Some(instantiating_crate) = instantiating_crate { - cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap(); + p.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap(); } - std::mem::take(&mut cx.out) + std::mem::take(&mut p.out) } pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> String { @@ -88,7 +88,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin } let prefix = "_R"; - let mut cx: SymbolMangler<'_> = SymbolMangler { + let mut p: SymbolMangler<'_> = SymbolMangler { tcx, start_offset: prefix.len(), is_exportable: false, @@ -99,10 +99,10 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin out: String::from(prefix), }; - cx.path_append_ns( - |cx| { - cx.push("C"); - cx.push_disambiguator({ + p.path_append_ns( + |p| { + p.push("C"); + p.push_disambiguator({ let mut hasher = StableHasher::new(); // Incorporate the rustc version to ensure #[rustc_std_internal_symbol] functions // get a different symbol name depending on the rustc version. @@ -114,7 +114,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin let hash: Hash64 = hasher.finish(); hash.as_u64() }); - cx.push_ident("__rustc"); + p.push_ident("__rustc"); Ok(()) }, 'v', @@ -123,7 +123,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin ) .unwrap(); - std::mem::take(&mut cx.out) + std::mem::take(&mut p.out) } pub(super) fn mangle_typeid_for_trait_ref<'tcx>( @@ -131,7 +131,7 @@ pub(super) fn mangle_typeid_for_trait_ref<'tcx>( trait_ref: ty::ExistentialTraitRef<'tcx>, ) -> String { // FIXME(flip1995): See comment in `mangle_typeid_for_fnabi`. - let mut cx = SymbolMangler { + let mut p = SymbolMangler { tcx, start_offset: 0, is_exportable: false, @@ -141,8 +141,8 @@ pub(super) fn mangle_typeid_for_trait_ref<'tcx>( binders: vec![], out: String::new(), }; - cx.print_def_path(trait_ref.def_id, &[]).unwrap(); - std::mem::take(&mut cx.out) + p.print_def_path(trait_ref.def_id, &[]).unwrap(); + std::mem::take(&mut p.out) } struct BinderLevel { @@ -368,7 +368,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { self.path_generic_args( |this| { this.path_append_ns( - |cx| cx.print_def_path(parent_def_id, &[]), + |p| p.print_def_path(parent_def_id, &[]), 'I', key.disambiguated_data.disambiguator as u64, "", @@ -542,31 +542,31 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { ty::FnPtr(sig_tys, hdr) => { let sig = sig_tys.with(hdr); self.push("F"); - self.wrap_binder(&sig, |cx, sig| { + self.wrap_binder(&sig, |p, sig| { if sig.safety.is_unsafe() { - cx.push("U"); + p.push("U"); } match sig.abi { ExternAbi::Rust => {} - ExternAbi::C { unwind: false } => cx.push("KC"), + ExternAbi::C { unwind: false } => p.push("KC"), abi => { - cx.push("K"); + p.push("K"); let name = abi.as_str(); if name.contains('-') { - cx.push_ident(&name.replace('-', "_")); + p.push_ident(&name.replace('-', "_")); } else { - cx.push_ident(name); + p.push_ident(name); } } } for &ty in sig.inputs() { - ty.print(cx)?; + ty.print(p)?; } if sig.c_variadic { - cx.push("v"); + p.push("v"); } - cx.push("E"); - sig.output().print(cx) + p.push("E"); + sig.output().print(p) })?; } @@ -623,7 +623,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { // [ [{}]] [{}] // Since any predicates after the first one shouldn't change the binders, // just put them all in the binders of the first. - self.wrap_binder(&predicates[0], |cx, _| { + self.wrap_binder(&predicates[0], |p, _| { for predicate in predicates.iter() { // It would be nice to be able to validate bound vars here, but // projections can actually include bound vars from super traits @@ -632,21 +632,21 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { match predicate.as_ref().skip_binder() { ty::ExistentialPredicate::Trait(trait_ref) => { // Use a type that can't appear in defaults of type parameters. - let dummy_self = Ty::new_fresh(cx.tcx, 0); - let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self); - cx.print_def_path(trait_ref.def_id, trait_ref.args)?; + let dummy_self = Ty::new_fresh(p.tcx, 0); + let trait_ref = trait_ref.with_self_ty(p.tcx, dummy_self); + p.print_def_path(trait_ref.def_id, trait_ref.args)?; } ty::ExistentialPredicate::Projection(projection) => { - let name = cx.tcx.associated_item(projection.def_id).name(); - cx.push("p"); - cx.push_ident(name.as_str()); + let name = p.tcx.associated_item(projection.def_id).name(); + p.push("p"); + p.push_ident(name.as_str()); match projection.term.kind() { - ty::TermKind::Ty(ty) => ty.print(cx), - ty::TermKind::Const(c) => c.print(cx), + ty::TermKind::Ty(ty) => ty.print(p), + ty::TermKind::Const(c) => c.print(p), }?; } ty::ExistentialPredicate::AutoTrait(def_id) => { - cx.print_def_path(*def_id, &[])?; + p.print_def_path(*def_id, &[])?; } } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index c158cce96573..8daa5d5347a0 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -301,8 +301,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // let _ = [{struct Foo; Foo}, {struct Foo; Foo}]; if did1.krate != did2.krate { let abs_path = |def_id| { - let mut printer = AbsolutePathPrinter { tcx: self.tcx, segments: vec![] }; - printer.print_def_path(def_id, &[]).map(|_| printer.segments) + let mut p = AbsolutePathPrinter { tcx: self.tcx, segments: vec![] }; + p.print_def_path(def_id, &[]).map(|_| p.segments) }; // We compare strings because DefPath can be different diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index 022d549a9df8..966f117a1bf9 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -244,7 +244,7 @@ impl<'a, 'tcx> TypeFolder> for ClosureEraser<'a, 'tcx> { } fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinter<'a, 'tcx> { - let mut printer = FmtPrinter::new(infcx.tcx, ns); + let mut p = FmtPrinter::new(infcx.tcx, ns); let ty_getter = move |ty_vid| { if infcx.probe_ty_var(ty_vid).is_ok() { warn!("resolved ty var in error message"); @@ -270,11 +270,11 @@ fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinte None } }; - printer.ty_infer_name_resolver = Some(Box::new(ty_getter)); + p.ty_infer_name_resolver = Some(Box::new(ty_getter)); let const_getter = move |ct_vid| Some(infcx.tcx.item_name(infcx.const_var_origin(ct_vid)?.param_def_id?)); - printer.const_infer_name_resolver = Some(Box::new(const_getter)); - printer + p.const_infer_name_resolver = Some(Box::new(const_getter)); + p } fn ty_to_string<'tcx>( @@ -282,7 +282,7 @@ fn ty_to_string<'tcx>( ty: Ty<'tcx>, called_method_def_id: Option, ) -> String { - let mut printer = fmt_printer(infcx, Namespace::TypeNS); + let mut p = fmt_printer(infcx, Namespace::TypeNS); let ty = infcx.resolve_vars_if_possible(ty); // We use `fn` ptr syntax for closures, but this only works when the closure does not capture // anything. We also remove all type parameters that are fully known to the type system. @@ -292,8 +292,8 @@ fn ty_to_string<'tcx>( // We don't want the regular output for `fn`s because it includes its path in // invalid pseudo-syntax, we want the `fn`-pointer output instead. (ty::FnDef(..), _) => { - ty.fn_sig(infcx.tcx).print(&mut printer).unwrap(); - printer.into_buffer() + ty.fn_sig(infcx.tcx).print(&mut p).unwrap(); + p.into_buffer() } (_, Some(def_id)) if ty.is_ty_or_numeric_infer() @@ -303,8 +303,8 @@ fn ty_to_string<'tcx>( } _ if ty.is_ty_or_numeric_infer() => "/* Type */".to_string(), _ => { - ty.print(&mut printer).unwrap(); - printer.into_buffer() + ty.print(&mut p).unwrap(); + p.into_buffer() } } } @@ -561,21 +561,20 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { { "Vec<_>".to_string() } else { - let mut printer = fmt_printer(self, Namespace::TypeNS); - printer - .comma_sep(generic_args.iter().copied().map(|arg| { - if arg.is_suggestable(self.tcx, true) { - return arg; - } + let mut p = fmt_printer(self, Namespace::TypeNS); + p.comma_sep(generic_args.iter().copied().map(|arg| { + if arg.is_suggestable(self.tcx, true) { + return arg; + } - match arg.kind() { - GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"), - GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(), - GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(), - } - })) - .unwrap(); - printer.into_buffer() + match arg.kind() { + GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"), + GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(), + GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(), + } + })) + .unwrap(); + p.into_buffer() }; if !have_turbofish { @@ -589,9 +588,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { InferSourceKind::FullyQualifiedMethodCall { receiver, successor, args, def_id } => { let placeholder = Some(self.next_ty_var(DUMMY_SP)); if let Some(args) = args.make_suggestable(self.infcx.tcx, true, placeholder) { - let mut printer = fmt_printer(self, Namespace::ValueNS); - printer.print_def_path(def_id, args).unwrap(); - let def_path = printer.into_buffer(); + let mut p = fmt_printer(self, Namespace::ValueNS); + p.print_def_path(def_id, args).unwrap(); + let def_path = p.into_buffer(); // We only care about whether we have to add `&` or `&mut ` for now. // This is the case if the last adjustment is a borrow and the diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs index 64fc365c44a6..373b756dcdb7 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs @@ -47,11 +47,11 @@ where T: for<'a> Print<'tcx, FmtPrinter<'a, 'tcx>>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut printer = ty::print::FmtPrinter::new(self.tcx, self.ns); - printer.region_highlight_mode = self.highlight; + let mut p = ty::print::FmtPrinter::new(self.tcx, self.ns); + p.region_highlight_mode = self.highlight; - self.value.print(&mut printer)?; - f.write_str(&printer.into_buffer()) + self.value.print(&mut p)?; + f.write_str(&p.into_buffer()) } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index 8e0620f20487..129d0963a75a 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -946,8 +946,8 @@ fn foo(&self) -> Self::T { String::new() } } pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String { - FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |cx| { - cx.path_generic_args(|_| Ok(()), args) + FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |p| { + p.path_generic_args(|_| Ok(()), args) }) .expect("could not write to `String`.") } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs index d929ecf68bf3..4f1f5c330e5f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs @@ -66,10 +66,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if s.len() > 50 { // We don't need to save the type to a file, we will be talking about this type already // in a separate note when we explain the obligation, so it will be available that way. - let mut cx: FmtPrinter<'_, '_> = + let mut p: FmtPrinter<'_, '_> = FmtPrinter::new_with_limit(tcx, Namespace::TypeNS, rustc_session::Limit(6)); - value.print(&mut cx).unwrap(); - cx.into_buffer() + value.print(&mut p).unwrap(); + p.into_buffer() } else { s } From 03bc1be8dd9be8fb6a0672e89731d0826dff0a09 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 1 Aug 2025 13:10:35 +1000 Subject: [PATCH 0384/1134] Simplify `SymbolMangler::print_type`. `Bound`/`Placeholder`/`Infer`/`Error` shouldn't occur, so we can handle them in the second exhaustive `match`, and ignore them in the first non-exhaustive `match`. --- compiler/rustc_symbol_mangling/src/v0.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index ce1eb1a16486..a34d8b4436ed 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -425,7 +425,6 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { ty::Bool => "b", ty::Char => "c", ty::Str => "e", - ty::Tuple(_) if ty.is_unit() => "u", ty::Int(IntTy::I8) => "a", ty::Int(IntTy::I16) => "s", ty::Int(IntTy::I32) => "l", @@ -444,12 +443,12 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { ty::Float(FloatTy::F128) => "C4f128", ty::Never => "z", + ty::Tuple(_) if ty.is_unit() => "u", + // Should only be encountered within the identity-substituted // impl header of an item nested within an impl item. ty::Param(_) => "p", - ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => bug!(), - _ => "", }; if !basic_type.is_empty() { @@ -468,11 +467,9 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { unreachable!() } ty::Tuple(_) if ty.is_unit() => unreachable!(), + ty::Param(_) => unreachable!(), - // Placeholders, also handled as part of basic types. - ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => { - unreachable!() - } + ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => bug!(), ty::Ref(r, ty, mutbl) => { self.push(match mutbl { From 03dab500a2a885c3cf196d6d72695deda7da7698 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 1 Aug 2025 15:08:01 +1000 Subject: [PATCH 0385/1134] Remove `p!`. It's a cryptic macro that makes some things slightly more concise in `PrettyPrinter`. E.g. if you declare `define_scope_printer!(p)` in a scope you can then call `p! to get these transformations: ``` p!("foo"); --> write!(p, "foo")?; p!(print(ty)); --> ty.print(p)?; p!(method(args)); --> p.method(args)?; ``` You can also chain calls, e.g.: ``` p!("foo", print(ty)); --> write!(p, "foo")?; ty.print(p)?; ``` Ultimately this doesn't seem worth it. The macro definition is hard to read, the call sites are hard to read, `define_scope_printer!` is pretty gross, and the code size reductions are small. Tellingly, many normal `write!` and `print` calls are sprinkled throughout the code, probably because people have made modifications and didn't want to use or understand how to use `p!`. This commit removes it. --- compiler/rustc_middle/src/ty/print/pretty.rs | 732 ++++++++++--------- 1 file changed, 370 insertions(+), 362 deletions(-) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 2b5425e50275..538179245c42 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -29,33 +29,6 @@ use crate::ty::{ TypeFoldable, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; -macro_rules! p { - (@$lit:literal) => { - write!(scoped_printer!(), $lit)? - }; - (@write($($data:expr),+)) => { - write!(scoped_printer!(), $($data),+)? - }; - (@print($x:expr)) => { - $x.print(scoped_printer!())? - }; - (@$method:ident($($arg:expr),*)) => { - scoped_printer!().$method($($arg),*)? - }; - ($($elem:tt $(($($args:tt)*))?),+) => {{ - $(p!(@ $elem $(($($args)*))?);)+ - }}; -} -macro_rules! define_scoped_printer { - ($p:ident) => { - macro_rules! scoped_printer { - () => { - $p - }; - } - }; -} - thread_local! { static FORCE_IMPL_FILENAME_LINE: Cell = const { Cell::new(false) }; static SHOULD_PREFIX_WITH_CRATE: Cell = const { Cell::new(false) }; @@ -690,11 +663,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } self.generic_delimiters(|p| { - define_scoped_printer!(p); - - p!(print(self_ty)); + self_ty.print(p)?; if let Some(trait_ref) = trait_ref { - p!(" as ", print(trait_ref.print_only_trait_path())); + write!(p, " as ")?; + trait_ref.print_only_trait_path().print(p)?; } Ok(()) }) @@ -709,65 +681,69 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { print_prefix(self)?; self.generic_delimiters(|p| { - define_scoped_printer!(p); - - p!("impl "); + write!(p, "impl ")?; if let Some(trait_ref) = trait_ref { - p!(print(trait_ref.print_only_trait_path()), " for "); + trait_ref.print_only_trait_path().print(p)?; + write!(p, " for ")?; } - p!(print(self_ty)); + self_ty.print(p)?; Ok(()) }) } fn pretty_print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { - define_scoped_printer!(self); - match *ty.kind() { - ty::Bool => p!("bool"), - ty::Char => p!("char"), - ty::Int(t) => p!(write("{}", t.name_str())), - ty::Uint(t) => p!(write("{}", t.name_str())), - ty::Float(t) => p!(write("{}", t.name_str())), + ty::Bool => write!(self, "bool")?, + ty::Char => write!(self, "char")?, + ty::Int(t) => write!(self, "{}", t.name_str())?, + ty::Uint(t) => write!(self, "{}", t.name_str())?, + ty::Float(t) => write!(self, "{}", t.name_str())?, ty::Pat(ty, pat) => { - p!("(", print(ty), ") is ", write("{pat:?}")) + write!(self, "(")?; + ty.print(self)?; + write!(self, ") is {pat:?}")?; } ty::RawPtr(ty, mutbl) => { - p!(write("*{} ", mutbl.ptr_str())); - p!(print(ty)) + write!(self, "*{} ", mutbl.ptr_str())?; + ty.print(self)?; } ty::Ref(r, ty, mutbl) => { - p!("&"); + write!(self, "&")?; if self.should_print_region(r) { - p!(print(r), " "); + r.print(self)?; + write!(self, " ")?; } - p!(print(ty::TypeAndMut { ty, mutbl })) + ty::TypeAndMut { ty, mutbl }.print(self)?; } - ty::Never => p!("!"), + ty::Never => write!(self, "!")?, ty::Tuple(tys) => { - p!("(", comma_sep(tys.iter())); + write!(self, "(")?; + self.comma_sep(tys.iter())?; if tys.len() == 1 { - p!(","); + write!(self, ",")?; } - p!(")") + write!(self, ")")?; } ty::FnDef(def_id, args) => { if with_reduced_queries() { - p!(print_def_path(def_id, args)); + self.print_def_path(def_id, args)?; } else { let mut sig = self.tcx().fn_sig(def_id).instantiate(self.tcx(), args); if self.tcx().codegen_fn_attrs(def_id).safe_target_features { - p!("#[target_features] "); + write!(self, "#[target_features] ")?; sig = sig.map_bound(|mut sig| { sig.safety = hir::Safety::Safe; sig }); } - p!(print(sig), " {{", print_value_path(def_id, args), "}}"); + sig.print(self)?; + write!(self, " {{")?; + self.print_value_path(def_id, args)?; + write!(self, "}}")?; } } - ty::FnPtr(ref sig_tys, hdr) => p!(print(sig_tys.with(hdr))), + ty::FnPtr(ref sig_tys, hdr) => sig_tys.with(hdr).print(self)?, ty::UnsafeBinder(ref bound_ty) => { self.wrap_binder(bound_ty, WrapBinderMode::Unsafe, |ty, p| { p.pretty_print_type(*ty) @@ -775,54 +751,50 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } ty::Infer(infer_ty) => { if self.should_print_verbose() { - p!(write("{:?}", ty.kind())); + write!(self, "{:?}", ty.kind())?; return Ok(()); } if let ty::TyVar(ty_vid) = infer_ty { if let Some(name) = self.ty_infer_name(ty_vid) { - p!(write("{}", name)) + write!(self, "{name}")?; } else { - p!(write("{}", infer_ty)) + write!(self, "{infer_ty}")?; } } else { - p!(write("{}", infer_ty)) + write!(self, "{infer_ty}")?; } } - ty::Error(_) => p!("{{type error}}"), - ty::Param(ref param_ty) => p!(print(param_ty)), + ty::Error(_) => write!(self, "{{type error}}")?, + ty::Param(ref param_ty) => param_ty.print(self)?, ty::Bound(debruijn, bound_ty) => match bound_ty.kind { ty::BoundTyKind::Anon => { rustc_type_ir::debug_bound_var(self, debruijn, bound_ty.var)? } ty::BoundTyKind::Param(def_id) => match self.should_print_verbose() { - true => p!(write("{:?}", ty.kind())), - false => p!(write("{}", self.tcx().item_name(def_id))), + true => write!(self, "{:?}", ty.kind())?, + false => write!(self, "{}", self.tcx().item_name(def_id))?, }, }, - ty::Adt(def, args) => { - p!(print_def_path(def.did(), args)); - } + ty::Adt(def, args) => self.print_def_path(def.did(), args)?, ty::Dynamic(data, r, repr) => { let print_r = self.should_print_region(r); if print_r { - p!("("); + write!(self, "(")?; } match repr { - ty::Dyn => p!("dyn "), + ty::Dyn => write!(self, "dyn ")?, } - p!(print(data)); + data.print(self)?; if print_r { - p!(" + ", print(r), ")"); + write!(self, " + ")?; + r.print(self)?; + write!(self, ")")?; } } - ty::Foreign(def_id) => { - p!(print_def_path(def_id, &[])); - } - ty::Alias(ty::Projection | ty::Inherent | ty::Free, ref data) => { - p!(print(data)) - } - ty::Placeholder(placeholder) => p!(print(placeholder)), + ty::Foreign(def_id) => self.print_def_path(def_id, &[])?, + ty::Alias(ty::Projection | ty::Inherent | ty::Free, ref data) => data.print(self)?, + ty::Placeholder(placeholder) => placeholder.print(self)?, ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { // We use verbose printing in 'NO_QUERIES' mode, to // avoid needing to call `predicates_of`. This should @@ -834,7 +806,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // example.] if self.should_print_verbose() { // FIXME(eddyb) print this with `print_def_path`. - p!(write("Opaque({:?}, {})", def_id, args.print_as_list())); + write!(self, "Opaque({:?}, {})", def_id, args.print_as_list())?; return Ok(()); } @@ -849,17 +821,17 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if d == def_id { // If the type alias directly starts with the `impl` of the // opaque type we're printing, then skip the `::{opaque#1}`. - p!(print_def_path(parent, args)); + self.print_def_path(parent, args)?; return Ok(()); } } // Complex opaque type, e.g. `type Foo = (i32, impl Debug);` - p!(print_def_path(def_id, args)); + self.print_def_path(def_id, args)?; return Ok(()); } _ => { if with_reduced_queries() { - p!(print_def_path(def_id, &[])); + self.print_def_path(def_id, &[])?; return Ok(()); } else { return self.pretty_print_opaque_impl_type(def_id, args); @@ -867,9 +839,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } } } - ty::Str => p!("str"), + ty::Str => write!(self, "str")?, ty::Coroutine(did, args) => { - p!("{{"); + write!(self, "{{")?; let coroutine_kind = self.tcx().coroutine_kind(did).unwrap(); let should_print_movability = self.should_print_verbose() || matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_)); @@ -877,12 +849,12 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if should_print_movability { match coroutine_kind.movability() { hir::Movability::Movable => {} - hir::Movability::Static => p!("static "), + hir::Movability::Static => write!(self, "static ")?, } } if !self.should_print_verbose() { - p!(write("{}", coroutine_kind)); + write!(self, "{coroutine_kind}")?; if coroutine_kind.is_fn_like() { // If we are printing an `async fn` coroutine type, then give the path // of the fn, instead of its span, because that will in most cases be @@ -891,66 +863,71 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // This will look like: // {async fn body of some_fn()} let did_of_the_fn_item = self.tcx().parent(did); - p!(" of ", print_def_path(did_of_the_fn_item, args), "()"); + write!(self, " of ")?; + self.print_def_path(did_of_the_fn_item, args)?; + write!(self, "()")?; } else if let Some(local_did) = did.as_local() { let span = self.tcx().def_span(local_did); - p!(write( + write!( + self, "@{}", // This may end up in stderr diagnostics but it may also be emitted // into MIR. Hence we use the remapped path if available self.tcx().sess.source_map().span_to_embeddable_string(span) - )); + )?; } else { - p!("@", print_def_path(did, args)); + write!(self, "@")?; + self.print_def_path(did, args)?; } } else { - p!(print_def_path(did, args)); - p!( - " upvar_tys=", - print(args.as_coroutine().tupled_upvars_ty()), - " resume_ty=", - print(args.as_coroutine().resume_ty()), - " yield_ty=", - print(args.as_coroutine().yield_ty()), - " return_ty=", - print(args.as_coroutine().return_ty()) - ); + self.print_def_path(did, args)?; + write!(self, " upvar_tys=")?; + args.as_coroutine().tupled_upvars_ty().print(self)?; + write!(self, " resume_ty=")?; + args.as_coroutine().resume_ty().print(self)?; + write!(self, " yield_ty=")?; + args.as_coroutine().yield_ty().print(self)?; + write!(self, " return_ty=")?; + args.as_coroutine().return_ty().print(self)?; } - p!("}}") + write!(self, "}}")? } ty::CoroutineWitness(did, args) => { - p!(write("{{")); + write!(self, "{{")?; if !self.tcx().sess.verbose_internals() { - p!("coroutine witness"); + write!(self, "coroutine witness")?; if let Some(did) = did.as_local() { let span = self.tcx().def_span(did); - p!(write( + write!( + self, "@{}", // This may end up in stderr diagnostics but it may also be emitted // into MIR. Hence we use the remapped path if available self.tcx().sess.source_map().span_to_embeddable_string(span) - )); + )?; } else { - p!(write("@"), print_def_path(did, args)); + write!(self, "@")?; + self.print_def_path(did, args)?; } } else { - p!(print_def_path(did, args)); + self.print_def_path(did, args)?; } - p!("}}") + write!(self, "}}")? } ty::Closure(did, args) => { - p!(write("{{")); + write!(self, "{{")?; if !self.should_print_verbose() { - p!(write("closure")); + write!(self, "closure")?; if self.should_truncate() { write!(self, "@...}}")?; return Ok(()); } else { if let Some(did) = did.as_local() { if self.tcx().sess.opts.unstable_opts.span_free_formats { - p!("@", print_def_path(did.to_def_id(), args)); + write!(self, "@")?; + self.print_def_path(did.to_def_id(), args)?; } else { let span = self.tcx().def_span(did); let preference = if with_forced_trimmed_paths() { @@ -958,54 +935,56 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } else { FileNameDisplayPreference::Remapped }; - p!(write( + write!( + self, "@{}", - // This may end up in stderr diagnostics but it may also be emitted - // into MIR. Hence we use the remapped path if available + // This may end up in stderr diagnostics but it may also be + // emitted into MIR. Hence we use the remapped path if + // available self.tcx().sess.source_map().span_to_string(span, preference) - )); + )?; } } else { - p!(write("@"), print_def_path(did, args)); + write!(self, "@")?; + self.print_def_path(did, args)?; } } } else { - p!(print_def_path(did, args)); - p!( - " closure_kind_ty=", - print(args.as_closure().kind_ty()), - " closure_sig_as_fn_ptr_ty=", - print(args.as_closure().sig_as_fn_ptr_ty()), - " upvar_tys=", - print(args.as_closure().tupled_upvars_ty()) - ); + self.print_def_path(did, args)?; + write!(self, " closure_kind_ty=")?; + args.as_closure().kind_ty().print(self)?; + write!(self, " closure_sig_as_fn_ptr_ty=")?; + args.as_closure().sig_as_fn_ptr_ty().print(self)?; + write!(self, " upvar_tys=")?; + args.as_closure().tupled_upvars_ty().print(self)?; } - p!("}}"); + write!(self, "}}")?; } ty::CoroutineClosure(did, args) => { - p!(write("{{")); + write!(self, "{{")?; if !self.should_print_verbose() { match self.tcx().coroutine_kind(self.tcx().coroutine_for_closure(did)).unwrap() { hir::CoroutineKind::Desugared( hir::CoroutineDesugaring::Async, hir::CoroutineSource::Closure, - ) => p!("async closure"), + ) => write!(self, "async closure")?, hir::CoroutineKind::Desugared( hir::CoroutineDesugaring::AsyncGen, hir::CoroutineSource::Closure, - ) => p!("async gen closure"), + ) => write!(self, "async gen closure")?, hir::CoroutineKind::Desugared( hir::CoroutineDesugaring::Gen, hir::CoroutineSource::Closure, - ) => p!("gen closure"), + ) => write!(self, "gen closure")?, _ => unreachable!( "coroutine from coroutine-closure should have CoroutineSource::Closure" ), } if let Some(did) = did.as_local() { if self.tcx().sess.opts.unstable_opts.span_free_formats { - p!("@", print_def_path(did.to_def_id(), args)); + write!(self, "@")?; + self.print_def_path(did.to_def_id(), args)?; } else { let span = self.tcx().def_span(did); let preference = if with_forced_trimmed_paths() { @@ -1013,33 +992,43 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } else { FileNameDisplayPreference::Remapped }; - p!(write( + write!( + self, "@{}", // This may end up in stderr diagnostics but it may also be emitted // into MIR. Hence we use the remapped path if available self.tcx().sess.source_map().span_to_string(span, preference) - )); + )?; } } else { - p!(write("@"), print_def_path(did, args)); + write!(self, "@")?; + self.print_def_path(did, args)?; } } else { - p!(print_def_path(did, args)); - p!( - " closure_kind_ty=", - print(args.as_coroutine_closure().kind_ty()), - " signature_parts_ty=", - print(args.as_coroutine_closure().signature_parts_ty()), - " upvar_tys=", - print(args.as_coroutine_closure().tupled_upvars_ty()), - " coroutine_captures_by_ref_ty=", - print(args.as_coroutine_closure().coroutine_captures_by_ref_ty()) - ); + self.print_def_path(did, args)?; + write!(self, " closure_kind_ty=")?; + args.as_coroutine_closure().kind_ty().print(self)?; + write!(self, " signature_parts_ty=")?; + args.as_coroutine_closure().signature_parts_ty().print(self)?; + write!(self, " upvar_tys=")?; + args.as_coroutine_closure().tupled_upvars_ty().print(self)?; + write!(self, " coroutine_captures_by_ref_ty=")?; + args.as_coroutine_closure().coroutine_captures_by_ref_ty().print(self)?; } - p!("}}"); + write!(self, "}}")?; + } + ty::Array(ty, sz) => { + write!(self, "[")?; + ty.print(self)?; + write!(self, "; ")?; + sz.print(self)?; + write!(self, "]")?; + } + ty::Slice(ty) => { + write!(self, "[")?; + ty.print(self)?; + write!(self, "]")?; } - ty::Array(ty, sz) => p!("[", print(ty), "; ", print(sz), "]"), - ty::Slice(ty) => p!("[", print(ty), "]"), } Ok(()) @@ -1138,24 +1127,24 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { &bound_args_and_self_ty, WrapBinderMode::ForAll, |(args, _), p| { - define_scoped_printer!(p); - p!(write("{}", tcx.item_name(trait_def_id))); - p!("("); + write!(p, "{}", tcx.item_name(trait_def_id))?; + write!(p, "(")?; for (idx, ty) in args.iter().enumerate() { if idx > 0 { - p!(", "); + write!(p, ", ")?; } - p!(print(ty)); + ty.print(p)?; } - p!(")"); + write!(p, ")")?; if let Some(ty) = return_ty.skip_binder().as_type() { if !ty.is_unit() { - p!(" -> ", print(return_ty)); + write!(p, " -> ")?; + return_ty.print(p)?; } } - p!(write("{}", if paren_needed { ")" } else { "" })); + write!(p, "{}", if paren_needed { ")" } else { "" })?; first = false; Ok(()) @@ -1182,12 +1171,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(self, "{}", if first { "" } else { " + " })?; self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, p| { - define_scoped_printer!(p); - if trait_pred.polarity == ty::PredicatePolarity::Negative { - p!("!"); + write!(p, "!")?; } - p!(print(trait_pred.trait_ref.print_only_trait_name())); + trait_pred.trait_ref.print_only_trait_name().print(p)?; let generics = tcx.generics_of(trait_pred.def_id()); let own_args = generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args); @@ -1197,32 +1184,32 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { for ty in own_args { if first { - p!("<"); + write!(p, "<")?; first = false; } else { - p!(", "); + write!(p, ", ")?; } - p!(print(ty)); + ty.print(p)?; } for (assoc_item_def_id, term) in assoc_items { if first { - p!("<"); + write!(p, "<")?; first = false; } else { - p!(", "); + write!(p, ", ")?; } - p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name())); + write!(p, "{} = ", tcx.associated_item(assoc_item_def_id).name())?; match term.skip_binder().kind() { - TermKind::Ty(ty) => p!(print(ty)), - TermKind::Const(c) => p!(print(c)), + TermKind::Ty(ty) => ty.print(p)?, + TermKind::Const(c) => c.print(p)?, }; } if !first { - p!(">"); + write!(p, ">")?; } } @@ -1389,8 +1376,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if let Some(bound_principal) = predicates.principal() { self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, p| { - define_scoped_printer!(p); - p!(print_def_path(principal.def_id, &[])); + p.print_def_path(principal.def_id, &[])?; let mut resugared = false; @@ -1400,11 +1386,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if let ty::Tuple(tys) = principal.args.type_at(0).kind() { let mut projections = predicates.projection_bounds(); if let (Some(proj), None) = (projections.next(), projections.next()) { - p!(pretty_fn_sig( + p.pretty_fn_sig( tys, false, - proj.skip_binder().term.as_type().expect("Return type was a const") - )); + proj.skip_binder().term.as_type().expect("Return type was a const"), + )?; resugared = true; } } @@ -1461,13 +1447,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { .sort_by_cached_key(|proj| p.tcx().item_name(proj.def_id).to_string()); if !args.is_empty() || !projections.is_empty() { - p!(generic_delimiters(|p| { + p.generic_delimiters(|p| { p.comma_sep(args.iter().copied())?; if !args.is_empty() && !projections.is_empty() { write!(p, ", ")?; } p.comma_sep(projections.iter().copied()) - })); + })?; } } Ok(()) @@ -1476,8 +1462,6 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { first = false; } - define_scoped_printer!(self); - // Builtin bounds. // FIXME(eddyb) avoid printing twice (needed to ensure // that the auto traits are sorted *and* printed via p). @@ -1494,11 +1478,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { for def_id in auto_traits { if !first { - p!(" + "); + write!(self, " + ")?; } first = false; - p!(print_def_path(def_id, &[])); + self.print_def_path(def_id, &[])?; } Ok(()) @@ -1510,18 +1494,18 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { c_variadic: bool, output: Ty<'tcx>, ) -> Result<(), PrintError> { - define_scoped_printer!(self); - - p!("(", comma_sep(inputs.iter().copied())); + write!(self, "(")?; + self.comma_sep(inputs.iter().copied())?; if c_variadic { if !inputs.is_empty() { - p!(", "); + write!(self, ", ")?; } - p!("..."); + write!(self, "...")?; } - p!(")"); + write!(self, ")")?; if !output.is_unit() { - p!(" -> ", print(output)); + write!(self, " -> ")?; + output.print(self)?; } Ok(()) @@ -1532,10 +1516,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ct: ty::Const<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_printer!(self); - if self.should_print_verbose() { - p!(write("{:?}", ct)); + write!(self, "{ct:?}")?; return Ok(()); } @@ -1543,25 +1525,28 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => { match self.tcx().def_kind(def) { DefKind::Const | DefKind::AssocConst => { - p!(print_value_path(def, args)) + self.print_value_path(def, args)?; } DefKind::AnonConst => { if def.is_local() && let span = self.tcx().def_span(def) && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) { - p!(write("{}", snip)) + write!(self, "{snip}")?; } else { - // Do not call `print_value_path` as if a parent of this anon const is an impl it will - // attempt to print out the impl trait ref i.e. `::{constant#0}`. This would - // cause printing to enter an infinite recursion if the anon const is in the self type i.e. - // `impl Default for [T; 32 - 1 - 1 - 1] {` - // where we would try to print `<[T; /* print `constant#0` again */] as Default>::{constant#0}` - p!(write( + // Do not call `print_value_path` as if a parent of this anon const is + // an impl it will attempt to print out the impl trait ref i.e. `::{constant#0}`. This would cause printing to enter an + // infinite recursion if the anon const is in the self type i.e. + // `impl Default for [T; 32 - 1 - 1 - 1] {` where we would + // try to print + // `<[T; /* print constant#0 again */] as // Default>::{constant#0}`. + write!( + self, "{}::{}", self.tcx().crate_name(def.krate), self.tcx().def_path(def).to_string_no_crate_verbose() - )) + )?; } } defkind => bug!("`{:?}` has unexpected defkind {:?}", ct, defkind), @@ -1569,11 +1554,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } ty::ConstKind::Infer(infer_ct) => match infer_ct { ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => { - p!(write("{}", name)) + write!(self, "{name}")?; } _ => write!(self, "_")?, }, - ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)), + ty::ConstKind::Param(ParamConst { name, .. }) => write!(self, "{name}")?, ty::ConstKind::Value(cv) => { return self.pretty_print_const_valtree(cv, print_ty); } @@ -1581,11 +1566,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::ConstKind::Bound(debruijn, bound_var) => { rustc_type_ir::debug_bound_var(self, debruijn, bound_var)? } - ty::ConstKind::Placeholder(placeholder) => p!(write("{placeholder:?}")), + ty::ConstKind::Placeholder(placeholder) => write!(self, "{placeholder:?}")?, // FIXME(generic_const_exprs): // write out some legible representation of an abstract const? ty::ConstKind::Expr(expr) => self.pretty_print_const_expr(expr, print_ty)?, - ty::ConstKind::Error(_) => p!("{{const error}}"), + ty::ConstKind::Error(_) => write!(self, "{{const error}}")?, }; Ok(()) } @@ -1595,7 +1580,6 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { expr: Expr<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_printer!(self); match expr.kind { ty::ExprKind::Binop(op) => { let (_, _, c1, c2) = expr.binop_args(); @@ -1634,7 +1618,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { |this| this.pretty_print_const(c1, print_ty), lhs_parenthesized, )?; - p!(write(" {formatted_op} ")); + write!(self, " {formatted_op} ")?; self.maybe_parenthesized( |this| this.pretty_print_const(c2, print_ty), rhs_parenthesized, @@ -1657,7 +1641,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::ConstKind::Expr(_) => true, _ => false, }; - p!(write("{formatted_op}")); + write!(self, "{formatted_op}")?; self.maybe_parenthesized( |this| this.pretty_print_const(ct, print_ty), parenthesized, @@ -1668,7 +1652,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(self, "(")?; self.pretty_print_const(fn_def, print_ty)?; - p!(")(", comma_sep(fn_args), ")"); + write!(self, ")(")?; + self.comma_sep(fn_args)?; + write!(self, ")")?; } ty::ExprKind::Cast(kind) => { let (_, value, to_ty) = expr.cast_args(); @@ -1718,8 +1704,6 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ptr: Pointer, ty: Ty<'tcx>, ) -> Result<(), PrintError> { - define_scoped_printer!(self); - let (prov, offset) = ptr.prov_and_relative_offset(); match ty.kind() { // Byte strings (&[u8; N]) @@ -1734,19 +1718,19 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if let Ok(byte_str) = alloc.inner().get_bytes_strip_provenance(&self.tcx(), range) { - p!(pretty_print_byte_str(byte_str)) + self.pretty_print_byte_str(byte_str)?; } else { - p!("") + write!(self, "")?; } } // FIXME: for statics, vtables, and functions, we could in principle print more detail. Some(GlobalAlloc::Static(def_id)) => { - p!(write("", def_id)) + write!(self, "")?; } - Some(GlobalAlloc::Function { .. }) => p!(""), - Some(GlobalAlloc::VTable(..)) => p!(""), - Some(GlobalAlloc::TypeId { .. }) => p!(""), - None => p!(""), + Some(GlobalAlloc::Function { .. }) => write!(self, "")?, + Some(GlobalAlloc::VTable(..)) => write!(self, "")?, + Some(GlobalAlloc::TypeId { .. }) => write!(self, "")?, + None => write!(self, "")?, } return Ok(()); } @@ -1778,40 +1762,38 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty: Ty<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_printer!(self); - match ty.kind() { // Bool - ty::Bool if int == ScalarInt::FALSE => p!("false"), - ty::Bool if int == ScalarInt::TRUE => p!("true"), + ty::Bool if int == ScalarInt::FALSE => write!(self, "false")?, + ty::Bool if int == ScalarInt::TRUE => write!(self, "true")?, // Float ty::Float(fty) => match fty { ty::FloatTy::F16 => { let val = Half::try_from(int).unwrap(); - p!(write("{}{}f16", val, if val.is_finite() { "" } else { "_" })) + write!(self, "{}{}f16", val, if val.is_finite() { "" } else { "_" })?; } ty::FloatTy::F32 => { let val = Single::try_from(int).unwrap(); - p!(write("{}{}f32", val, if val.is_finite() { "" } else { "_" })) + write!(self, "{}{}f32", val, if val.is_finite() { "" } else { "_" })?; } ty::FloatTy::F64 => { let val = Double::try_from(int).unwrap(); - p!(write("{}{}f64", val, if val.is_finite() { "" } else { "_" })) + write!(self, "{}{}f64", val, if val.is_finite() { "" } else { "_" })?; } ty::FloatTy::F128 => { let val = Quad::try_from(int).unwrap(); - p!(write("{}{}f128", val, if val.is_finite() { "" } else { "_" })) + write!(self, "{}{}f128", val, if val.is_finite() { "" } else { "_" })?; } }, // Int ty::Uint(_) | ty::Int(_) => { let int = ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral()); - if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) } + if print_ty { write!(self, "{int:#?}")? } else { write!(self, "{int:?}")? } } // Char ty::Char if char::try_from(int).is_ok() => { - p!(write("{:?}", char::try_from(int).unwrap())) + write!(self, "{:?}", char::try_from(int).unwrap())?; } // Pointer types ty::Ref(..) | ty::RawPtr(_, _) | ty::FnPtr(..) => { @@ -1827,7 +1809,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => { self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?; - p!(write(" is {pat:?}")); + write!(self, " is {pat:?}")?; } // Nontrivial types with scalar bit representation _ => { @@ -1876,10 +1858,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { cv: ty::Value<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_printer!(self); - if with_reduced_queries() || self.should_print_verbose() { - p!(write("ValTree({:?}: ", cv.valtree), print(cv.ty), ")"); + write!(self, "ValTree({:?}: ", cv.valtree)?; + cv.ty.print(self)?; + write!(self, ")")?; return Ok(()); } @@ -1900,13 +1882,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| { bug!("expected to convert valtree to raw bytes for type {:?}", cv.ty) }); - p!(write("{:?}", String::from_utf8_lossy(bytes))); + write!(self, "{:?}", String::from_utf8_lossy(bytes))?; return Ok(()); } _ => { let cv = ty::Value { valtree: cv.valtree, ty: inner_ty }; - p!("&"); - p!(pretty_print_const_valtree(cv, print_ty)); + write!(self, "&")?; + self.pretty_print_const_valtree(cv, print_ty)?; return Ok(()); } }, @@ -1914,8 +1896,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| { bug!("expected to convert valtree to raw bytes for type {:?}", t) }); - p!("*"); - p!(pretty_print_byte_str(bytes)); + write!(self, "*")?; + self.pretty_print_byte_str(bytes)?; return Ok(()); } // Aggregates, printed as array/tuple/struct/variant construction syntax. @@ -1928,14 +1910,17 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let fields = contents.fields.iter().copied(); match *cv.ty.kind() { ty::Array(..) => { - p!("[", comma_sep(fields), "]"); + write!(self, "[")?; + self.comma_sep(fields)?; + write!(self, "]")?; } ty::Tuple(..) => { - p!("(", comma_sep(fields)); + write!(self, "(")?; + self.comma_sep(fields)?; if contents.fields.len() == 1 { - p!(","); + write!(self, ",")?; } - p!(")"); + write!(self, ")")?; } ty::Adt(def, _) if def.variants().is_empty() => { self.typed_value( @@ -1951,23 +1936,26 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let variant_idx = contents.variant.expect("destructed const of adt without variant idx"); let variant_def = &def.variant(variant_idx); - p!(print_value_path(variant_def.def_id, args)); + self.print_value_path(variant_def.def_id, args)?; match variant_def.ctor_kind() { Some(CtorKind::Const) => {} Some(CtorKind::Fn) => { - p!("(", comma_sep(fields), ")"); + write!(self, "(")?; + self.comma_sep(fields)?; + write!(self, ")")?; } None => { - p!(" {{ "); + write!(self, " {{ ")?; let mut first = true; for (field_def, field) in iter::zip(&variant_def.fields, fields) { if !first { - p!(", "); + write!(self, ", ")?; } - p!(write("{}: ", field_def.name), print(field)); + write!(self, "{}: ", field_def.name)?; + field.print(self)?; first = false; } - p!(" }}"); + write!(self, " }}")?; } } } @@ -1976,7 +1964,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { return Ok(()); } (ty::ValTreeKind::Leaf(leaf), ty::Ref(_, inner_ty, _)) => { - p!(write("&")); + write!(self, "&")?; return self.pretty_print_const_scalar_int(*leaf, inner_ty, print_ty); } (ty::ValTreeKind::Leaf(leaf), _) => { @@ -1984,7 +1972,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } (_, ty::FnDef(def_id, args)) => { // Never allowed today, but we still encounter them in invalid const args. - p!(print_value_path(def_id, args)); + self.print_value_path(def_id, args)?; return Ok(()); } // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading @@ -1994,12 +1982,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // fallback if cv.valtree.is_zst() { - p!(write("")); + write!(self, "")?; } else { - p!(write("{:?}", cv.valtree)); + write!(self, "{:?}", cv.valtree)?; } if print_ty { - p!(": ", print(cv.ty)); + write!(self, ": ")?; + cv.ty.print(self)?; } Ok(()) } @@ -2013,19 +2002,18 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(self, "impl ")?; self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, p| { - define_scoped_printer!(p); - - p!(write("{kind}(")); + write!(p, "{kind}(")?; for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() { if i > 0 { - p!(", "); + write!(p, ", ")?; } - p!(print(arg)); + arg.print(p)?; } - p!(")"); + write!(p, ")")?; if !sig.output().is_unit() { - p!(" -> ", print(sig.output())); + write!(p, " -> ")?; + sig.output().print(p)?; } Ok(()) @@ -2036,15 +2024,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { &mut self, constness: ty::BoundConstness, ) -> Result<(), PrintError> { - define_scoped_printer!(self); - match constness { - ty::BoundConstness::Const => { - p!("const "); - } - ty::BoundConstness::Maybe => { - p!("[const] "); - } + ty::BoundConstness::Const => write!(self, "const ")?, + ty::BoundConstness::Maybe => write!(self, "[const] ")?, } Ok(()) } @@ -2562,11 +2544,10 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { ty: Ty<'tcx>, ) -> Result<(), PrintError> { let print = |this: &mut Self| { - define_scoped_printer!(this); if this.print_alloc_ids { - p!(write("{:?}", p)); + write!(this, "{p:?}")?; } else { - p!("&_"); + write!(this, "&_")?; } Ok(()) }; @@ -2577,17 +2558,15 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`. impl<'tcx> FmtPrinter<'_, 'tcx> { pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> { - define_scoped_printer!(self); - // Watch out for region highlights. let highlight = self.region_highlight_mode; if let Some(n) = highlight.region_highlighted(region) { - p!(write("'{}", n)); + write!(self, "'{n}")?; return Ok(()); } if self.should_print_verbose() { - p!(write("{:?}", region)); + write!(self, "{region:?}")?; return Ok(()); } @@ -2599,12 +2578,12 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { // `explain_region()` or `note_and_explain_region()`. match region.kind() { ty::ReEarlyParam(data) => { - p!(write("{}", data.name)); + write!(self, "{}", data.name)?; return Ok(()); } ty::ReLateParam(ty::LateParamRegion { kind, .. }) => { if let Some(name) = kind.get_name(self.tcx) { - p!(write("{}", name)); + write!(self, "{name}")?; return Ok(()); } } @@ -2613,31 +2592,31 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { bound: ty::BoundRegion { kind: br, .. }, .. }) => { if let Some(name) = br.get_name(self.tcx) { - p!(write("{}", name)); + write!(self, "{name}")?; return Ok(()); } if let Some((region, counter)) = highlight.highlight_bound_region { if br == region { - p!(write("'{}", counter)); + write!(self, "'{counter}")?; return Ok(()); } } } ty::ReVar(region_vid) if identify_regions => { - p!(write("{:?}", region_vid)); + write!(self, "{region_vid:?}")?; return Ok(()); } ty::ReVar(_) => {} ty::ReErased => {} ty::ReError(_) => {} ty::ReStatic => { - p!("'static"); + write!(self, "'static")?; return Ok(()); } } - p!("'_"); + write!(self, "'_")?; Ok(()) } @@ -2928,8 +2907,9 @@ where T: Print<'tcx, P>, { fn print(&self, p: &mut P) -> Result<(), PrintError> { - define_scoped_printer!(p); - p!(print(self.0), ": ", print(self.1)); + self.0.print(p)?; + write!(p, ": ")?; + self.1.print(p)?; Ok(()) } } @@ -3084,7 +3064,6 @@ macro_rules! define_print { (($self:ident, $p:ident): $($ty:ty $print:block)+) => { $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty { fn print(&$self, $p: &mut P) -> Result<(), PrintError> { - define_scoped_printer!($p); let _: () = $print; Ok(()) } @@ -3110,34 +3089,35 @@ define_print! { (self, p): ty::FnSig<'tcx> { - p!(write("{}", self.safety.prefix_str())); + write!(p, "{}", self.safety.prefix_str())?; if self.abi != ExternAbi::Rust { - p!(write("extern {} ", self.abi)); + write!(p, "extern {} ", self.abi)?; } - p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output())); + write!(p, "fn")?; + p.pretty_fn_sig(self.inputs(), self.c_variadic, self.output())?; } ty::TraitRef<'tcx> { - p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path())) + write!(p, "<{} as {}>", self.self_ty(), self.print_only_trait_path())?; } ty::AliasTy<'tcx> { let alias_term: ty::AliasTerm<'tcx> = (*self).into(); - p!(print(alias_term)) + alias_term.print(p)?; } ty::AliasTerm<'tcx> { match self.kind(p.tcx()) { - ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p!(pretty_print_inherent_projection(*self)), + ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p.pretty_print_inherent_projection(*self)?, ty::AliasTermKind::ProjectionTy => { if !(p.should_print_verbose() || with_reduced_queries()) && p.tcx().is_impl_trait_in_trait(self.def_id) { - p!(pretty_print_rpitit(self.def_id, self.args)) + p.pretty_print_rpitit(self.def_id, self.args)?; } else { - p!(print_def_path(self.def_id, self.args)); + p.print_def_path(self.def_id, self.args)?; } } ty::AliasTermKind::FreeTy @@ -3145,17 +3125,18 @@ define_print! { | ty::AliasTermKind::OpaqueTy | ty::AliasTermKind::UnevaluatedConst | ty::AliasTermKind::ProjectionConst => { - p!(print_def_path(self.def_id, self.args)); + p.print_def_path(self.def_id, self.args)?; } } } ty::TraitPredicate<'tcx> { - p!(print(self.trait_ref.self_ty()), ": "); + self.trait_ref.self_ty().print(p)?; + write!(p, ": ")?; if let ty::PredicatePolarity::Negative = self.polarity { - p!("!"); + write!(p, "!")?; } - p!(print(self.trait_ref.print_trait_sugared())) + self.trait_ref.print_trait_sugared().print(p)?; } ty::HostEffectPredicate<'tcx> { @@ -3163,60 +3144,78 @@ define_print! { ty::BoundConstness::Const => { "const" } ty::BoundConstness::Maybe => { "[const]" } }; - p!(print(self.trait_ref.self_ty()), ": {constness} "); - p!(print(self.trait_ref.print_trait_sugared())) + self.trait_ref.self_ty().print(p)?; + write!(p, ": {constness} ")?; + self.trait_ref.print_trait_sugared().print(p)?; } ty::TypeAndMut<'tcx> { - p!(write("{}", self.mutbl.prefix_str()), print(self.ty)) + write!(p, "{}", self.mutbl.prefix_str())?; + self.ty.print(p)?; } ty::ClauseKind<'tcx> { match *self { - ty::ClauseKind::Trait(ref data) => { - p!(print(data)) - } - ty::ClauseKind::RegionOutlives(predicate) => p!(print(predicate)), - ty::ClauseKind::TypeOutlives(predicate) => p!(print(predicate)), - ty::ClauseKind::Projection(predicate) => p!(print(predicate)), - ty::ClauseKind::HostEffect(predicate) => p!(print(predicate)), + ty::ClauseKind::Trait(ref data) => data.print(p)?, + ty::ClauseKind::RegionOutlives(predicate) => predicate.print(p)?, + ty::ClauseKind::TypeOutlives(predicate) => predicate.print(p)?, + ty::ClauseKind::Projection(predicate) => predicate.print(p)?, + ty::ClauseKind::HostEffect(predicate) => predicate.print(p)?, ty::ClauseKind::ConstArgHasType(ct, ty) => { - p!("the constant `", print(ct), "` has type `", print(ty), "`") + write!(p, "the constant `")?; + ct.print(p)?; + write!(p, "` has type `")?; + ty.print(p)?; + write!(p, "`")?; }, - ty::ClauseKind::WellFormed(term) => p!(print(term), " well-formed"), + ty::ClauseKind::WellFormed(term) => { + term.print(p)?; + write!(p, " well-formed")?; + } ty::ClauseKind::ConstEvaluatable(ct) => { - p!("the constant `", print(ct), "` can be evaluated") + write!(p, "the constant `")?; + ct.print(p)?; + write!(p, "` can be evaluated")?; + } + ty::ClauseKind::UnstableFeature(symbol) => { + write!(p, "unstable feature: ")?; + write!(p, "`{symbol}`")?; } - ty::ClauseKind::UnstableFeature(symbol) => p!("unstable feature: ", write("`{}`", symbol)), } } ty::PredicateKind<'tcx> { match *self { - ty::PredicateKind::Clause(data) => { - p!(print(data)) - } - ty::PredicateKind::Subtype(predicate) => p!(print(predicate)), - ty::PredicateKind::Coerce(predicate) => p!(print(predicate)), + ty::PredicateKind::Clause(data) => data.print(p)?, + ty::PredicateKind::Subtype(predicate) => predicate.print(p)?, + ty::PredicateKind::Coerce(predicate) => predicate.print(p)?, ty::PredicateKind::DynCompatible(trait_def_id) => { - p!("the trait `", print_def_path(trait_def_id, &[]), "` is dyn-compatible") + write!(p, "the trait `")?; + p.print_def_path(trait_def_id, &[])?; + write!(p, "` is dyn-compatible")?; } ty::PredicateKind::ConstEquate(c1, c2) => { - p!("the constant `", print(c1), "` equals `", print(c2), "`") + write!(p, "the constant `")?; + c1.print(p)?; + write!(p, "` equals `")?; + c2.print(p)?; + write!(p, "`")?; + } + ty::PredicateKind::Ambiguous => write!(p, "ambiguous")?, + ty::PredicateKind::NormalizesTo(data) => data.print(p)?, + ty::PredicateKind::AliasRelate(t1, t2, dir) => { + t1.print(p)?; + write!(p, " {dir} ")?; + t2.print(p)?; } - ty::PredicateKind::Ambiguous => p!("ambiguous"), - ty::PredicateKind::NormalizesTo(data) => p!(print(data)), - ty::PredicateKind::AliasRelate(t1, t2, dir) => p!(print(t1), write(" {} ", dir), print(t2)), } } ty::ExistentialPredicate<'tcx> { match *self { - ty::ExistentialPredicate::Trait(x) => p!(print(x)), - ty::ExistentialPredicate::Projection(x) => p!(print(x)), - ty::ExistentialPredicate::AutoTrait(def_id) => { - p!(print_def_path(def_id, &[])); - } + ty::ExistentialPredicate::Trait(x) => x.print(p)?, + ty::ExistentialPredicate::Projection(x) => x.print(p)?, + ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, &[])?, } } @@ -3224,7 +3223,7 @@ define_print! { // Use a type that can't appear in defaults of type parameters. let dummy_self = Ty::new_fresh(p.tcx(), 0); let trait_ref = self.with_self_ty(p.tcx(), dummy_self); - p!(print(trait_ref.print_only_trait_path())) + trait_ref.print_only_trait_path().print(p)?; } ty::ExistentialProjection<'tcx> { @@ -3232,31 +3231,37 @@ define_print! { // The args don't contain the self ty (as it has been erased) but the corresp. // generics do as the trait always has a self ty param. We need to offset. let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..]; - p!(path_generic_args(|p| write!(p, "{name}"), args), " = ", print(self.term)) + p.path_generic_args(|p| write!(p, "{name}"), args)?; + write!(p, " = ")?; + self.term.print(p)?; } ty::ProjectionPredicate<'tcx> { - p!(print(self.projection_term), " == "); + self.projection_term.print(p)?; + write!(p, " == ")?; p.reset_type_limit(); - p!(print(self.term)) + self.term.print(p)?; } ty::SubtypePredicate<'tcx> { - p!(print(self.a), " <: "); + self.a.print(p)?; + write!(p, " <: ")?; p.reset_type_limit(); - p!(print(self.b)) + self.b.print(p)?; } ty::CoercePredicate<'tcx> { - p!(print(self.a), " -> "); + self.a.print(p)?; + write!(p, " -> ")?; p.reset_type_limit(); - p!(print(self.b)) + self.b.print(p)?; } ty::NormalizesTo<'tcx> { - p!(print(self.alias), " normalizes-to "); + self.alias.print(p)?; + write!(p, " normalizes-to ")?; p.reset_type_limit(); - p!(print(self.term)) + self.term.print(p)?; } } @@ -3264,11 +3269,13 @@ define_print_and_forward_display! { (self, p): &'tcx ty::List> { - p!("{{", comma_sep(self.iter()), "}}") + write!(p, "{{")?; + p.comma_sep(self.iter())?; + write!(p, "}}")?; } TraitRefPrintOnlyTraitPath<'tcx> { - p!(print_def_path(self.0.def_id, self.0.args)); + p.print_def_path(self.0.def_id, self.0.args)?; } TraitRefPrintSugared<'tcx> { @@ -3276,83 +3283,84 @@ define_print_and_forward_display! { && p.tcx().trait_def(self.0.def_id).paren_sugar && let ty::Tuple(args) = self.0.args.type_at(1).kind() { - p!(write("{}", p.tcx().item_name(self.0.def_id)), "("); + write!(p, "{}(", p.tcx().item_name(self.0.def_id))?; for (i, arg) in args.iter().enumerate() { if i > 0 { - p!(", "); + write!(p, ", ")?; } - p!(print(arg)); + arg.print(p)?; } - p!(")"); + write!(p, ")")?; } else { - p!(print_def_path(self.0.def_id, self.0.args)); + p.print_def_path(self.0.def_id, self.0.args)?; } } TraitRefPrintOnlyTraitName<'tcx> { - p!(print_def_path(self.0.def_id, &[])); + p.print_def_path(self.0.def_id, &[])?; } TraitPredPrintModifiersAndPath<'tcx> { if let ty::PredicatePolarity::Negative = self.0.polarity { - p!("!") + write!(p, "!")?; } - p!(print(self.0.trait_ref.print_trait_sugared())); + self.0.trait_ref.print_trait_sugared().print(p)?; } TraitPredPrintWithBoundConstness<'tcx> { - p!(print(self.0.trait_ref.self_ty()), ": "); + self.0.trait_ref.self_ty().print(p)?; + write!(p, ": ")?; if let Some(constness) = self.1 { - p!(pretty_print_bound_constness(constness)); + p.pretty_print_bound_constness(constness)?; } if let ty::PredicatePolarity::Negative = self.0.polarity { - p!("!"); + write!(p, "!")?; } - p!(print(self.0.trait_ref.print_trait_sugared())) + self.0.trait_ref.print_trait_sugared().print(p)?; } PrintClosureAsImpl<'tcx> { - p!(pretty_closure_as_impl(self.closure)) + p.pretty_closure_as_impl(self.closure)?; } ty::ParamTy { - p!(write("{}", self.name)) + write!(p, "{}", self.name)?; } ty::PlaceholderType { match self.bound.kind { - ty::BoundTyKind::Anon => p!(write("{self:?}")), + ty::BoundTyKind::Anon => write!(p, "{self:?}")?, ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() { - true => p!(write("{self:?}")), - false => p!(write("{}", p.tcx().item_name(def_id))), + true => write!(p, "{self:?}")?, + false => write!(p, "{}", p.tcx().item_name(def_id))?, }, } } ty::ParamConst { - p!(write("{}", self.name)) + write!(p, "{}", self.name)?; } ty::Term<'tcx> { match self.kind() { - ty::TermKind::Ty(ty) => p!(print(ty)), - ty::TermKind::Const(c) => p!(print(c)), + ty::TermKind::Ty(ty) => ty.print(p)?, + ty::TermKind::Const(c) => c.print(p)?, } } ty::Predicate<'tcx> { - p!(print(self.kind())) + self.kind().print(p)?; } ty::Clause<'tcx> { - p!(print(self.kind())) + self.kind().print(p)?; } GenericArg<'tcx> { match self.kind() { - GenericArgKind::Lifetime(lt) => p!(print(lt)), - GenericArgKind::Type(ty) => p!(print(ty)), - GenericArgKind::Const(ct) => p!(print(ct)), + GenericArgKind::Lifetime(lt) => lt.print(p)?, + GenericArgKind::Type(ty) => ty.print(p)?, + GenericArgKind::Const(ct) => ct.print(p)?, } } } From 2434d8cecfb228093277c1b4506ae47db1972de9 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 1 Aug 2025 19:01:32 +1000 Subject: [PATCH 0386/1134] Remove unused arg from `path_append_impl`. None of the impls use it. --- compiler/rustc_const_eval/src/util/type_name.rs | 1 - compiler/rustc_lint/src/context.rs | 1 - compiler/rustc_middle/src/ty/print/mod.rs | 8 +------- compiler/rustc_middle/src/ty/print/pretty.rs | 1 - compiler/rustc_symbol_mangling/src/legacy.rs | 1 - compiler/rustc_symbol_mangling/src/v0.rs | 1 - .../src/error_reporting/infer/mod.rs | 1 - 7 files changed, 1 insertion(+), 13 deletions(-) diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index 400ba23ae5f9..e6b9759819f1 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -89,7 +89,6 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 7e35d4d142bd..11181d10af5e 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -803,7 +803,6 @@ impl<'tcx> LateContext<'tcx> { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index 1fee9d945f65..8a125c7fe284 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -88,7 +88,6 @@ pub trait Printer<'tcx>: Sized { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError>; @@ -236,12 +235,7 @@ pub trait Printer<'tcx>: Sized { // If the impl is not co-located with either self-type or // trait-type, then fallback to a format that identifies // the module more clearly. - self.path_append_impl( - |p| p.print_def_path(parent_def_id, &[]), - &key.disambiguated_data, - self_ty, - impl_trait_ref, - ) + self.path_append_impl(|p| p.print_def_path(parent_def_id, &[]), self_ty, impl_trait_ref) } else { // Otherwise, try to give a good form that would be valid language // syntax. Preferably using associated item notation. diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 538179245c42..033f1e6cd064 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2340,7 +2340,6 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index d1834abb32b0..aa8292c05044 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -332,7 +332,6 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index a34d8b4436ed..c2458ae814b7 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -846,7 +846,6 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { fn path_append_impl( &mut self, _: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _: &DisambiguatedDefPathData, _: Ty<'tcx>, _: Option>, ) -> Result<(), PrintError> { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index 8daa5d5347a0..ed8229154a9b 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -269,7 +269,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn path_append_impl( &mut self, _print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, _self_ty: Ty<'tcx>, _trait_ref: Option>, ) -> Result<(), PrintError> { From 3b216c3f6ffe04f0bc66ef064fcb38fd60e52ad4 Mon Sep 17 00:00:00 2001 From: Madhav Madhusoodanan Date: Sat, 2 Aug 2025 17:31:41 +0530 Subject: [PATCH 0387/1134] feat: Added another variant of the Constraint enum --- .../crates/intrinsic-test/src/common/constraint.rs | 13 ++++++++++--- .../crates/intrinsic-test/src/common/gen_c.rs | 2 +- .../crates/intrinsic-test/src/common/gen_rust.rs | 4 ++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/library/stdarch/crates/intrinsic-test/src/common/constraint.rs b/library/stdarch/crates/intrinsic-test/src/common/constraint.rs index 269fb7f90cb7..5984e0fcc22f 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/constraint.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/constraint.rs @@ -1,17 +1,24 @@ use serde::Deserialize; use std::ops::Range; +/// Describes the values to test for a const generic parameter. #[derive(Debug, PartialEq, Clone, Deserialize)] pub enum Constraint { + /// Test a single value. Equal(i64), + /// Test a range of values, e.g. `0..16`. Range(Range), + /// Test discrete values, e.g. `vec![1, 2, 4, 8]`. + Set(Vec), } impl Constraint { - pub fn to_range(&self) -> Range { + /// Iterate over the values of this constraint. + pub fn iter<'a>(&'a self) -> impl Iterator + 'a { match self { - Constraint::Equal(eq) => *eq..*eq + 1, - Constraint::Range(range) => range.clone(), + Constraint::Equal(i) => std::slice::Iter::default().copied().chain(*i..*i + 1), + Constraint::Range(range) => std::slice::Iter::default().copied().chain(range.clone()), + Constraint::Set(items) => items.iter().copied().chain(std::ops::Range::default()), } } } diff --git a/library/stdarch/crates/intrinsic-test/src/common/gen_c.rs b/library/stdarch/crates/intrinsic-test/src/common/gen_c.rs index 905efb6d8909..84755ce52505 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/gen_c.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/gen_c.rs @@ -40,7 +40,7 @@ pub fn generate_c_constraint_blocks<'a, T: IntrinsicTypeDefinition + 'a>( }; let body_indentation = indentation.nested(); - for i in current.constraint.iter().flat_map(|c| c.to_range()) { + for i in current.constraint.iter().flat_map(|c| c.iter()) { let ty = current.ty.c_type(); writeln!(w, "{indentation}{{")?; diff --git a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs index acc18cfb92bc..2a02b8fdff1d 100644 --- a/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs +++ b/library/stdarch/crates/intrinsic-test/src/common/gen_rust.rs @@ -255,7 +255,7 @@ pub fn generate_rust_test_loop( /// Generate the specializations (unique sequences of const-generic arguments) for this intrinsic. fn generate_rust_specializations<'a>( - constraints: &mut impl Iterator>, + constraints: &mut impl Iterator>, ) -> Vec> { let mut specializations = vec![vec![]]; @@ -292,7 +292,7 @@ pub fn create_rust_test_module( let specializations = generate_rust_specializations( &mut arguments .iter() - .filter_map(|i| i.constraint.as_ref().map(|v| v.to_range())), + .filter_map(|i| i.constraint.as_ref().map(|v| v.iter())), ); generate_rust_test_loop(w, intrinsic, indentation, &specializations, PASSES)?; From 277cf46d3e4aecbaa393507c0c9612da5fc69c37 Mon Sep 17 00:00:00 2001 From: Hmikihiro <34ttrweoewiwe28@gmail.com> Date: Sun, 3 Aug 2025 19:38:29 +0900 Subject: [PATCH 0388/1134] Remove unused functions from edit_in_place --- .../crates/syntax/src/ast/edit_in_place.rs | 163 +----------------- 1 file changed, 2 insertions(+), 161 deletions(-) diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs index f01ac081c8bd..b50ce6442432 100644 --- a/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs +++ b/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs @@ -9,11 +9,11 @@ use crate::{ SyntaxKind::{ATTR, COMMENT, WHITESPACE}, SyntaxNode, SyntaxToken, algo::{self, neighbor}, - ast::{self, HasGenericArgs, HasGenericParams, edit::IndentLevel, make}, + ast::{self, HasGenericParams, edit::IndentLevel, make}, ted::{self, Position}, }; -use super::{GenericParam, HasArgList, HasName}; +use super::{GenericParam, HasName}; pub trait GenericParamsOwnerEdit: ast::HasGenericParams { fn get_or_create_generic_param_list(&self) -> ast::GenericParamList; @@ -419,34 +419,6 @@ impl Removable for ast::TypeBoundList { } } -impl ast::PathSegment { - pub fn get_or_create_generic_arg_list(&self) -> ast::GenericArgList { - if self.generic_arg_list().is_none() { - let arg_list = make::generic_arg_list(empty()).clone_for_update(); - ted::append_child(self.syntax(), arg_list.syntax()); - } - self.generic_arg_list().unwrap() - } -} - -impl ast::MethodCallExpr { - pub fn get_or_create_generic_arg_list(&self) -> ast::GenericArgList { - if self.generic_arg_list().is_none() { - let generic_arg_list = make::turbofish_generic_arg_list(empty()).clone_for_update(); - - if let Some(arg_list) = self.arg_list() { - ted::insert_raw( - ted::Position::before(arg_list.syntax()), - generic_arg_list.syntax(), - ); - } else { - ted::append_child(self.syntax(), generic_arg_list.syntax()); - } - } - self.generic_arg_list().unwrap() - } -} - impl Removable for ast::UseTree { fn remove(&self) { for dir in [Direction::Next, Direction::Prev] { @@ -677,106 +649,6 @@ impl ast::AssocItemList { ]; ted::insert_all(position, elements); } - - /// Adds a new associated item at the start of the associated item list. - /// - /// Attention! This function does align the first line of `item` with respect to `self`, - /// but it does _not_ change indentation of other lines (if any). - pub fn add_item_at_start(&self, item: ast::AssocItem) { - match self.assoc_items().next() { - Some(first_item) => { - let indent = IndentLevel::from_node(first_item.syntax()); - let before = Position::before(first_item.syntax()); - - ted::insert_all( - before, - vec![ - item.syntax().clone().into(), - make::tokens::whitespace(&format!("\n\n{indent}")).into(), - ], - ) - } - None => { - let (indent, position, whitespace) = match self.l_curly_token() { - Some(l_curly) => { - normalize_ws_between_braces(self.syntax()); - (IndentLevel::from_token(&l_curly) + 1, Position::after(&l_curly), "\n") - } - None => (IndentLevel::single(), Position::first_child_of(self.syntax()), ""), - }; - - let mut elements = vec![]; - - // Avoid pushing an empty whitespace token - if !indent.is_zero() || !whitespace.is_empty() { - elements.push(make::tokens::whitespace(&format!("{whitespace}{indent}")).into()) - } - elements.push(item.syntax().clone().into()); - - ted::insert_all(position, elements) - } - }; - } -} - -impl ast::Fn { - pub fn get_or_create_body(&self) -> ast::BlockExpr { - if self.body().is_none() { - let body = make::ext::empty_block_expr().clone_for_update(); - match self.semicolon_token() { - Some(semi) => { - ted::replace(semi, body.syntax()); - ted::insert(Position::before(body.syntax), make::tokens::single_space()); - } - None => ted::append_child(self.syntax(), body.syntax()), - } - } - self.body().unwrap() - } -} - -impl ast::LetStmt { - pub fn set_ty(&self, ty: Option) { - match ty { - None => { - if let Some(colon_token) = self.colon_token() { - ted::remove(colon_token); - } - - if let Some(existing_ty) = self.ty() { - if let Some(sibling) = existing_ty.syntax().prev_sibling_or_token() - && sibling.kind() == SyntaxKind::WHITESPACE - { - ted::remove(sibling); - } - - ted::remove(existing_ty.syntax()); - } - - // Remove any trailing ws - if let Some(last) = self.syntax().last_token().filter(|it| it.kind() == WHITESPACE) - { - last.detach(); - } - } - Some(new_ty) => { - if self.colon_token().is_none() { - ted::insert_raw( - Position::after( - self.pat().expect("let stmt should have a pattern").syntax(), - ), - make::token(T![:]), - ); - } - - if let Some(old_ty) = self.ty() { - ted::replace(old_ty.syntax(), new_ty.syntax()); - } else { - ted::insert(Position::after(self.colon_token().unwrap()), new_ty.syntax()); - } - } - } - } } impl ast::RecordExprFieldList { @@ -1091,35 +963,4 @@ mod tests { check("let a @ ()", "let a", None); check("let a @ ", "let a", None); } - - #[test] - fn test_let_stmt_set_ty() { - #[track_caller] - fn check(before: &str, expected: &str, ty: Option) { - let ty = ty.map(|it| it.clone_for_update()); - - let let_stmt = ast_mut_from_text::(&format!("fn f() {{ {before} }}")); - let_stmt.set_ty(ty); - - let after = ast_mut_from_text::(&format!("fn f() {{ {expected} }}")); - assert_eq!(let_stmt.to_string(), after.to_string(), "{let_stmt:#?}\n!=\n{after:#?}"); - } - - // adding - check("let a;", "let a: ();", Some(make::ty_tuple([]))); - // no semicolon due to it being eaten during error recovery - check("let a:", "let a: ()", Some(make::ty_tuple([]))); - - // replacing - check("let a: u8;", "let a: ();", Some(make::ty_tuple([]))); - check("let a: u8 = 3;", "let a: () = 3;", Some(make::ty_tuple([]))); - check("let a: = 3;", "let a: () = 3;", Some(make::ty_tuple([]))); - - // removing - check("let a: u8;", "let a;", None); - check("let a:;", "let a;", None); - - check("let a: u8 = 3;", "let a = 3;", None); - check("let a: = 3;", "let a = 3;", None); - } } From 754654d5a98a81a2f4f033a1cf4b2f9e7bb55f06 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sun, 3 Aug 2025 17:59:37 +0500 Subject: [PATCH 0389/1134] rename rust_panic_without_hook --- library/std/src/panic.rs | 2 +- library/std/src/panicking.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/panic.rs b/library/std/src/panic.rs index 234fb284a590..913ef72f6746 100644 --- a/library/std/src/panic.rs +++ b/library/std/src/panic.rs @@ -388,7 +388,7 @@ pub fn catch_unwind R + UnwindSafe, R>(f: F) -> Result { /// ``` #[stable(feature = "resume_unwind", since = "1.9.0")] pub fn resume_unwind(payload: Box) -> ! { - panicking::rust_panic_without_hook(payload) + panicking::resume_unwind(payload) } /// Makes all future panics abort directly without running the panic hook or unwinding. diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 7873049d20bf..bb399fc17734 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -861,7 +861,7 @@ fn rust_panic_with_hook( /// This is the entry point for `resume_unwind`. /// It just forwards the payload to the panic runtime. #[cfg_attr(feature = "panic_immediate_abort", inline)] -pub fn rust_panic_without_hook(payload: Box) -> ! { +pub fn resume_unwind(payload: Box) -> ! { panic_count::increase(false); struct RewrapBox(Box); From 02ebef4c6aef49cdc866c1367b2f12ef9082e1ea Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sun, 3 Aug 2025 17:13:54 +0200 Subject: [PATCH 0390/1134] don't allocate a `Vec` in an `Iterator::chain` --- clippy_lints/src/loops/never_loop.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_lints/src/loops/never_loop.rs b/clippy_lints/src/loops/never_loop.rs index 8a253ae5810f..2ccff7680976 100644 --- a/clippy_lints/src/loops/never_loop.rs +++ b/clippy_lints/src/loops/never_loop.rs @@ -202,7 +202,7 @@ fn all_spans_after_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> Vec { .iter() .skip_while(|inner| inner.hir_id != stmt.hir_id) .map(stmt_source_span) - .chain(if let Some(e) = block.expr { vec![e.span] } else { vec![] }) + .chain(block.expr.map(|e| e.span)) .collect(); } From 3b907eada71ea36710566e6fd22a268c42b55e94 Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sun, 3 Aug 2025 12:09:06 +0200 Subject: [PATCH 0391/1134] use parens for clearer formatting the first and second lines now each represent one approach to getting a `source` --- clippy_utils/src/source.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/clippy_utils/src/source.rs b/clippy_utils/src/source.rs index 7d21336be1cd..277b074ec587 100644 --- a/clippy_utils/src/source.rs +++ b/clippy_utils/src/source.rs @@ -342,10 +342,7 @@ impl SourceFileRange { /// Attempts to get the text from the source file. This can fail if the source text isn't /// loaded. pub fn as_str(&self) -> Option<&str> { - self.sf - .src - .as_ref() - .map(|src| src.as_str()) + (self.sf.src.as_ref().map(|src| src.as_str())) .or_else(|| self.sf.external_src.get().and_then(|src| src.get_source())) .and_then(|x| x.get(self.range.clone())) } From 2d8d45e20184628bbf35883164278c0892a7364d Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sun, 3 Aug 2025 12:12:52 +0200 Subject: [PATCH 0392/1134] use `?` for brevity --- clippy_utils/src/source.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy_utils/src/source.rs b/clippy_utils/src/source.rs index 277b074ec587..e675291b6f3a 100644 --- a/clippy_utils/src/source.rs +++ b/clippy_utils/src/source.rs @@ -343,7 +343,7 @@ impl SourceFileRange { /// loaded. pub fn as_str(&self) -> Option<&str> { (self.sf.src.as_ref().map(|src| src.as_str())) - .or_else(|| self.sf.external_src.get().and_then(|src| src.get_source())) + .or_else(|| self.sf.external_src.get()?.get_source()) .and_then(|x| x.get(self.range.clone())) } } From 035ff85042ed1b61e98346229c4aa059a3c87c69 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 3 Aug 2025 11:58:13 -0400 Subject: [PATCH 0393/1134] Fix intcast to use the is_signed parameter --- src/builder.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index 3cd464b61e14..dac3c3dcbb1b 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1278,11 +1278,19 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn intcast( &mut self, - value: RValue<'gcc>, + mut value: RValue<'gcc>, dest_typ: Type<'gcc>, - _is_signed: bool, + is_signed: bool, ) -> RValue<'gcc> { - // NOTE: is_signed is for value, not dest_typ. + let value_type = value.get_type(); + if is_signed && !value_type.is_signed(self.cx) { + let signed_type = value_type.to_signed(self.cx); + value = self.gcc_int_cast(value, signed_type); + } else if !is_signed && value_type.is_signed(self.cx) { + let unsigned_type = value_type.to_unsigned(self.cx); + value = self.gcc_int_cast(value, unsigned_type); + } + self.gcc_int_cast(value, dest_typ) } From 7d78968bd053eb7811126b2bad991579fb78cc3a Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Fri, 1 Aug 2025 00:23:36 +0900 Subject: [PATCH 0394/1134] fix: Error on illegal `[const]`s inside blocks within legal positions --- compiler/rustc_ast_passes/messages.ftl | 4 ++ .../rustc_ast_passes/src/ast_validation.rs | 47 ++++++++++++------- compiler/rustc_ast_passes/src/errors.rs | 20 ++++++++ .../conditionally-const-in-anon-const.rs | 28 +++++++++++ .../conditionally-const-in-anon-const.stderr | 32 +++++++++++++ .../conditionally-const-in-struct-args.rs | 21 --------- .../conditionally-const-invalid-places.stderr | 30 ++++++++++-- 7 files changed, 140 insertions(+), 42 deletions(-) create mode 100644 tests/ui/traits/const-traits/conditionally-const-in-anon-const.rs create mode 100644 tests/ui/traits/const-traits/conditionally-const-in-anon-const.stderr delete mode 100644 tests/ui/traits/const-traits/conditionally-const-in-struct-args.rs diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index af93d55c8982..42f3569f0f1e 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -241,6 +241,10 @@ ast_passes_tilde_const_disallowed = `[const]` is not allowed here .trait_assoc_ty = associated types in non-`const` traits cannot have `[const]` trait bounds .trait_impl_assoc_ty = associated types in non-const impls cannot have `[const]` trait bounds .inherent_assoc_ty = inherent associated types cannot have `[const]` trait bounds + .struct = structs cannot have `[const]` trait bounds + .enum = enums cannot have `[const]` trait bounds + .union = unions cannot have `[const]` trait bounds + .anon_const = anonymous constants cannot have `[const]` trait bounds .object = trait objects cannot have `[const]` trait bounds .item = this item cannot have `[const]` trait bounds diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 895a457ec1d5..ae482ceb9b72 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -1124,7 +1124,9 @@ impl<'a> Visitor<'a> for AstValidator<'a> { ); } } - visit::walk_item(self, item) + self.with_tilde_const(Some(TildeConstReason::Enum { span: item.span }), |this| { + visit::walk_item(this, item) + }); } ItemKind::Trait(box Trait { constness, @@ -1175,26 +1177,32 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } visit::walk_item(self, item) } - ItemKind::Struct(ident, generics, vdata) => match vdata { - VariantData::Struct { fields, .. } => { - self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident); - self.visit_generics(generics); - walk_list!(self, visit_field_def, fields); - } - _ => visit::walk_item(self, item), - }, + ItemKind::Struct(ident, generics, vdata) => { + self.with_tilde_const(Some(TildeConstReason::Struct { span: item.span }), |this| { + match vdata { + VariantData::Struct { fields, .. } => { + this.visit_attrs_vis_ident(&item.attrs, &item.vis, ident); + this.visit_generics(generics); + walk_list!(this, visit_field_def, fields); + } + _ => visit::walk_item(this, item), + } + }) + } ItemKind::Union(ident, generics, vdata) => { if vdata.fields().is_empty() { self.dcx().emit_err(errors::FieldlessUnion { span: item.span }); } - match vdata { - VariantData::Struct { fields, .. } => { - self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident); - self.visit_generics(generics); - walk_list!(self, visit_field_def, fields); + self.with_tilde_const(Some(TildeConstReason::Union { span: item.span }), |this| { + match vdata { + VariantData::Struct { fields, .. } => { + this.visit_attrs_vis_ident(&item.attrs, &item.vis, ident); + this.visit_generics(generics); + walk_list!(this, visit_field_def, fields); + } + _ => visit::walk_item(this, item), } - _ => visit::walk_item(self, item), - } + }); } ItemKind::Const(box ConstItem { defaultness, expr, .. }) => { self.check_defaultness(item.span, *defaultness); @@ -1623,6 +1631,13 @@ impl<'a> Visitor<'a> for AstValidator<'a> { _ => self.with_in_trait_impl(None, |this| visit::walk_assoc_item(this, item, ctxt)), } } + + fn visit_anon_const(&mut self, anon_const: &'a AnonConst) { + self.with_tilde_const( + Some(TildeConstReason::AnonConst { span: anon_const.value.span }), + |this| visit::walk_anon_const(this, anon_const), + ) + } } /// When encountering an equality constraint in a `where` clause, emit an error. If the code seems diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index fd4b2528541e..8b5873a3ef37 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -623,6 +623,26 @@ pub(crate) enum TildeConstReason { #[primary_span] span: Span, }, + #[note(ast_passes_struct)] + Struct { + #[primary_span] + span: Span, + }, + #[note(ast_passes_enum)] + Enum { + #[primary_span] + span: Span, + }, + #[note(ast_passes_union)] + Union { + #[primary_span] + span: Span, + }, + #[note(ast_passes_anon_const)] + AnonConst { + #[primary_span] + span: Span, + }, #[note(ast_passes_object)] TraitObject, #[note(ast_passes_item)] diff --git a/tests/ui/traits/const-traits/conditionally-const-in-anon-const.rs b/tests/ui/traits/const-traits/conditionally-const-in-anon-const.rs new file mode 100644 index 000000000000..5aebcceb7c75 --- /dev/null +++ b/tests/ui/traits/const-traits/conditionally-const-in-anon-const.rs @@ -0,0 +1,28 @@ +#![feature(const_trait_impl, impl_trait_in_bindings)] + +struct S; +#[const_trait] +trait Trait {} + +impl const Trait<0> for () {} + +const fn f< + T: Trait< + { + const fn g>() {} + + struct I>(U); + //~^ ERROR `[const]` is not allowed here + + let x: &impl [const] Trait<0> = &(); + //~^ ERROR `[const]` is not allowed here + + 0 + }, + >, +>(x: &T) { + // Should be allowed here + let y: &impl [const] Trait<0> = x; +} + +pub fn main() {} diff --git a/tests/ui/traits/const-traits/conditionally-const-in-anon-const.stderr b/tests/ui/traits/const-traits/conditionally-const-in-anon-const.stderr new file mode 100644 index 000000000000..c6be249b95a2 --- /dev/null +++ b/tests/ui/traits/const-traits/conditionally-const-in-anon-const.stderr @@ -0,0 +1,32 @@ +error: `[const]` is not allowed here + --> $DIR/conditionally-const-in-anon-const.rs:14:25 + | +LL | struct I>(U); + | ^^^^^^^ + | +note: structs cannot have `[const]` trait bounds + --> $DIR/conditionally-const-in-anon-const.rs:14:13 + | +LL | struct I>(U); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: `[const]` is not allowed here + --> $DIR/conditionally-const-in-anon-const.rs:17:26 + | +LL | let x: &impl [const] Trait<0> = &(); + | ^^^^^^^ + | +note: anonymous constants cannot have `[const]` trait bounds + --> $DIR/conditionally-const-in-anon-const.rs:11:9 + | +LL | / { +LL | | const fn g>() {} +LL | | +LL | | struct I>(U); +... | +LL | | 0 +LL | | }, + | |_________^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/traits/const-traits/conditionally-const-in-struct-args.rs b/tests/ui/traits/const-traits/conditionally-const-in-struct-args.rs deleted file mode 100644 index 0c644694585a..000000000000 --- a/tests/ui/traits/const-traits/conditionally-const-in-struct-args.rs +++ /dev/null @@ -1,21 +0,0 @@ -//@ compile-flags: -Znext-solver -//@ known-bug: #132067 -//@ check-pass - -#![feature(const_trait_impl)] - -struct S; -#[const_trait] -trait Trait {} - -const fn f< - T: Trait< - { - struct I>(U); - 0 - }, - >, ->() { -} - -pub fn main() {} diff --git a/tests/ui/traits/const-traits/conditionally-const-invalid-places.stderr b/tests/ui/traits/const-traits/conditionally-const-invalid-places.stderr index 010b15846436..5c3bb2369675 100644 --- a/tests/ui/traits/const-traits/conditionally-const-invalid-places.stderr +++ b/tests/ui/traits/const-traits/conditionally-const-invalid-places.stderr @@ -16,7 +16,11 @@ error: `[const]` is not allowed here LL | struct Struct { field: T } | ^^^^^^^ | - = note: this item cannot have `[const]` trait bounds +note: structs cannot have `[const]` trait bounds + --> $DIR/conditionally-const-invalid-places.rs:9:1 + | +LL | struct Struct { field: T } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `[const]` is not allowed here --> $DIR/conditionally-const-invalid-places.rs:10:23 @@ -24,7 +28,11 @@ error: `[const]` is not allowed here LL | struct TupleStruct(T); | ^^^^^^^ | - = note: this item cannot have `[const]` trait bounds +note: structs cannot have `[const]` trait bounds + --> $DIR/conditionally-const-invalid-places.rs:10:1 + | +LL | struct TupleStruct(T); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `[const]` is not allowed here --> $DIR/conditionally-const-invalid-places.rs:11:22 @@ -32,7 +40,11 @@ error: `[const]` is not allowed here LL | struct UnitStruct; | ^^^^^^^ | - = note: this item cannot have `[const]` trait bounds +note: structs cannot have `[const]` trait bounds + --> $DIR/conditionally-const-invalid-places.rs:11:1 + | +LL | struct UnitStruct; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `[const]` is not allowed here --> $DIR/conditionally-const-invalid-places.rs:14:14 @@ -40,7 +52,11 @@ error: `[const]` is not allowed here LL | enum Enum { Variant(T) } | ^^^^^^^ | - = note: this item cannot have `[const]` trait bounds +note: enums cannot have `[const]` trait bounds + --> $DIR/conditionally-const-invalid-places.rs:14:1 + | +LL | enum Enum { Variant(T) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `[const]` is not allowed here --> $DIR/conditionally-const-invalid-places.rs:16:16 @@ -48,7 +64,11 @@ error: `[const]` is not allowed here LL | union Union { field: T } | ^^^^^^^ | - = note: this item cannot have `[const]` trait bounds +note: unions cannot have `[const]` trait bounds + --> $DIR/conditionally-const-invalid-places.rs:16:1 + | +LL | union Union { field: T } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `[const]` is not allowed here --> $DIR/conditionally-const-invalid-places.rs:19:14 From 681651350f708260428b7b82621583f98c4d042f Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 3 Aug 2025 13:31:24 -0400 Subject: [PATCH 0395/1134] Only use bitcast in Builder::ret for non-native integers --- src/builder.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index dac3c3dcbb1b..751f0ba24301 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -539,9 +539,15 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn ret(&mut self, mut value: RValue<'gcc>) { let expected_return_type = self.current_func().get_return_type(); - if !expected_return_type.is_compatible_with(value.get_type()) { - // NOTE: due to opaque pointers now being used, we need to bitcast here. - value = self.context.new_bitcast(self.location, value, expected_return_type); + let value_type = value.get_type(); + if !expected_return_type.is_compatible_with(value_type) { + // NOTE: due to opaque pointers now being used, we need to (bit)cast here. + if self.is_native_int_type(value_type) && self.is_native_int_type(expected_return_type) + { + value = self.context.new_cast(self.location, value, expected_return_type); + } else { + value = self.context.new_bitcast(self.location, value, expected_return_type); + } } self.llbb().end_with_return(self.location, value); } From 74e85a218b418db7ff29f0743efb12c130dfd3ca Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sun, 3 Aug 2025 22:56:02 +0500 Subject: [PATCH 0396/1134] removed gate --- library/std/src/panic.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/library/std/src/panic.rs b/library/std/src/panic.rs index 234fb284a590..371516019823 100644 --- a/library/std/src/panic.rs +++ b/library/std/src/panic.rs @@ -108,8 +108,6 @@ impl<'a> PanicHookInfo<'a> { /// # Example /// /// ```should_panic - /// #![feature(panic_payload_as_str)] - /// /// std::panic::set_hook(Box::new(|panic_info| { /// if let Some(s) = panic_info.payload_as_str() { /// println!("panic occurred: {s:?}"); @@ -122,7 +120,7 @@ impl<'a> PanicHookInfo<'a> { /// ``` #[must_use] #[inline] - #[unstable(feature = "panic_payload_as_str", issue = "125175")] + #[stable(feature = "panic_payload_as_str", since = "CURRENT_RUSTC_VERSION")] pub fn payload_as_str(&self) -> Option<&str> { if let Some(s) = self.payload.downcast_ref::<&str>() { Some(s) From 3aeeae6d4406a97e3746263bfc6f3f70df6313a4 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sun, 3 Aug 2025 19:22:11 +0500 Subject: [PATCH 0397/1134] remove rust_ prefixes --- library/std/src/panicking.rs | 12 ++++++------ .../exported_symbol_bad_unwind2.both.stderr | 2 +- .../exported_symbol_bad_unwind2.definition.stderr | 2 +- src/tools/miri/tests/fail/panic/abort_unwind.stderr | 2 +- src/tools/miri/tests/fail/panic/double_panic.stderr | 2 +- src/tools/miri/tests/fail/panic/panic_abort1.stderr | 2 +- src/tools/miri/tests/fail/panic/panic_abort2.stderr | 2 +- src/tools/miri/tests/fail/panic/panic_abort3.stderr | 2 +- src/tools/miri/tests/fail/panic/panic_abort4.stderr | 2 +- .../miri/tests/fail/ptr_swap_nonoverlapping.stderr | 2 +- .../miri/tests/fail/terminate-terminator.stderr | 2 +- .../miri/tests/fail/unwind-action-terminate.stderr | 2 +- 12 files changed, 17 insertions(+), 17 deletions(-) diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 7873049d20bf..c2b0e43a3242 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -696,14 +696,14 @@ pub fn begin_panic_handler(info: &core::panic::PanicInfo<'_>) -> ! { let msg = info.message(); crate::sys::backtrace::__rust_end_short_backtrace(move || { if let Some(s) = msg.as_str() { - rust_panic_with_hook( + panic_with_hook( &mut StaticStrPayload(s), loc, info.can_unwind(), info.force_no_backtrace(), ); } else { - rust_panic_with_hook( + panic_with_hook( &mut FormatStringPayload { inner: &msg, string: None }, loc, info.can_unwind(), @@ -767,7 +767,7 @@ pub const fn begin_panic(msg: M) -> ! { let loc = Location::caller(); crate::sys::backtrace::__rust_end_short_backtrace(move || { - rust_panic_with_hook( + panic_with_hook( &mut Payload { inner: Some(msg) }, loc, /* can_unwind */ true, @@ -792,7 +792,7 @@ fn payload_as_str(payload: &dyn Any) -> &str { /// panics, panic hooks, and finally dispatching to the panic runtime to either /// abort or unwind. #[optimize(size)] -fn rust_panic_with_hook( +fn panic_with_hook( payload: &mut dyn PanicPayload, location: &Location<'_>, can_unwind: bool, @@ -885,8 +885,8 @@ pub fn rust_panic_without_hook(payload: Box) -> ! { rust_panic(&mut RewrapBox(payload)) } -/// An unmangled function (through `rustc_std_internal_symbol`) on which to slap -/// yer breakpoints. +/// A function with a fixed suffix (through `rustc_std_internal_symbol`) +/// on which to slap yer breakpoints. #[inline(never)] #[cfg_attr(not(test), rustc_std_internal_symbol)] #[cfg(not(feature = "panic_immediate_abort"))] diff --git a/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.both.stderr b/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.both.stderr index deec81f7e51b..14b3be02a793 100644 --- a/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.both.stderr +++ b/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.both.stderr @@ -16,7 +16,7 @@ LL | ABORT() | = note: BACKTRACE: = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.definition.stderr b/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.definition.stderr index deec81f7e51b..14b3be02a793 100644 --- a/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.definition.stderr +++ b/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.definition.stderr @@ -16,7 +16,7 @@ LL | ABORT() | = note: BACKTRACE: = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/panic/abort_unwind.stderr b/src/tools/miri/tests/fail/panic/abort_unwind.stderr index 81d560c27ec7..35052f37dfcc 100644 --- a/src/tools/miri/tests/fail/panic/abort_unwind.stderr +++ b/src/tools/miri/tests/fail/panic/abort_unwind.stderr @@ -16,7 +16,7 @@ LL | ABORT() | = note: BACKTRACE: = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/panic/double_panic.stderr b/src/tools/miri/tests/fail/panic/double_panic.stderr index bc6cce93d41e..3f1fbfef721c 100644 --- a/src/tools/miri/tests/fail/panic/double_panic.stderr +++ b/src/tools/miri/tests/fail/panic/double_panic.stderr @@ -19,7 +19,7 @@ LL | ABORT() | = note: BACKTRACE: = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/panic/panic_abort1.stderr b/src/tools/miri/tests/fail/panic/panic_abort1.stderr index 61bc9a7a4959..9aca2ed654f6 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort1.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort1.stderr @@ -15,7 +15,7 @@ LL | ABORT() = note: inside `std::rt::__rust_abort` at RUSTLIB/std/src/rt.rs:LL:CC = note: inside `panic_abort::__rust_start_panic` at RUSTLIB/panic_abort/src/lib.rs:LL:CC = note: inside `std::panicking::rust_panic` at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/panic/panic_abort2.stderr b/src/tools/miri/tests/fail/panic/panic_abort2.stderr index a7a42f8174e5..425817d5f86c 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort2.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort2.stderr @@ -15,7 +15,7 @@ LL | ABORT() = note: inside `std::rt::__rust_abort` at RUSTLIB/std/src/rt.rs:LL:CC = note: inside `panic_abort::__rust_start_panic` at RUSTLIB/panic_abort/src/lib.rs:LL:CC = note: inside `std::panicking::rust_panic` at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/panic/panic_abort3.stderr b/src/tools/miri/tests/fail/panic/panic_abort3.stderr index ba1f11065ead..a21e185219e6 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort3.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort3.stderr @@ -15,7 +15,7 @@ LL | ABORT() = note: inside `std::rt::__rust_abort` at RUSTLIB/std/src/rt.rs:LL:CC = note: inside `panic_abort::__rust_start_panic` at RUSTLIB/panic_abort/src/lib.rs:LL:CC = note: inside `std::panicking::rust_panic` at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/panic/panic_abort4.stderr b/src/tools/miri/tests/fail/panic/panic_abort4.stderr index 1464c1fcc7c9..a3cf5d72198b 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort4.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort4.stderr @@ -15,7 +15,7 @@ LL | ABORT() = note: inside `std::rt::__rust_abort` at RUSTLIB/std/src/rt.rs:LL:CC = note: inside `panic_abort::__rust_start_panic` at RUSTLIB/panic_abort/src/lib.rs:LL:CC = note: inside `std::panicking::rust_panic` at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr b/src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr index b893220426c9..8295a581060d 100644 --- a/src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr +++ b/src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr @@ -14,7 +14,7 @@ LL | ABORT() | = note: BACKTRACE: = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/terminate-terminator.stderr b/src/tools/miri/tests/fail/terminate-terminator.stderr index a0ee75e5dd27..f0f305d76bc8 100644 --- a/src/tools/miri/tests/fail/terminate-terminator.stderr +++ b/src/tools/miri/tests/fail/terminate-terminator.stderr @@ -18,7 +18,7 @@ LL | ABORT() | = note: BACKTRACE: = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC diff --git a/src/tools/miri/tests/fail/unwind-action-terminate.stderr b/src/tools/miri/tests/fail/unwind-action-terminate.stderr index 5fa485752a48..216ae84512af 100644 --- a/src/tools/miri/tests/fail/unwind-action-terminate.stderr +++ b/src/tools/miri/tests/fail/unwind-action-terminate.stderr @@ -16,7 +16,7 @@ LL | ABORT() | = note: BACKTRACE: = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC - = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::panicking::panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC From c539890ae68b5e0584ffdae2559e3e606da37657 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Sun, 3 Aug 2025 13:04:34 +0200 Subject: [PATCH 0398/1134] forbid tail calling intrinsics --- .../rustc_mir_build/src/check_tail_calls.rs | 20 ++++++++++++++++--- tests/ui/explicit-tail-calls/intrinsics.rs | 13 ++++++++++++ .../ui/explicit-tail-calls/intrinsics.stderr | 14 +++++++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 tests/ui/explicit-tail-calls/intrinsics.rs create mode 100644 tests/ui/explicit-tail-calls/intrinsics.stderr diff --git a/compiler/rustc_mir_build/src/check_tail_calls.rs b/compiler/rustc_mir_build/src/check_tail_calls.rs index 18db8c1debb1..6ed100899d8c 100644 --- a/compiler/rustc_mir_build/src/check_tail_calls.rs +++ b/compiler/rustc_mir_build/src/check_tail_calls.rs @@ -89,10 +89,10 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { self.report_op(ty, args, fn_span, expr); } - // Closures in thir look something akin to - // `for<'a> extern "rust-call" fn(&'a [closure@...], ()) -> <[closure@...] as FnOnce<()>>::Output {<[closure@...] as Fn<()>>::call}` - // So we have to check for them in this weird way... if let &ty::FnDef(did, args) = ty.kind() { + // Closures in thir look something akin to + // `for<'a> extern "rust-call" fn(&'a [closure@...], ()) -> <[closure@...] as FnOnce<()>>::Output {<[closure@...] as Fn<()>>::call}` + // So we have to check for them in this weird way... let parent = self.tcx.parent(did); if self.tcx.fn_trait_kind_from_def_id(parent).is_some() && args.first().and_then(|arg| arg.as_type()).is_some_and(Ty::is_closure) @@ -103,6 +103,10 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { // skip them, producing an error about calling a closure is enough. return; }; + + if self.tcx.intrinsic(did).is_some() { + self.report_calling_intrinsic(expr); + } } // Erase regions since tail calls don't care about lifetimes @@ -280,6 +284,16 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { self.found_errors = Err(err); } + fn report_calling_intrinsic(&mut self, expr: &Expr<'_>) { + let err = self + .tcx + .dcx() + .struct_span_err(expr.span, "tail calling intrinsics is not allowed") + .emit(); + + self.found_errors = Err(err); + } + fn report_abi_mismatch(&mut self, sp: Span, caller_abi: ExternAbi, callee_abi: ExternAbi) { let err = self .tcx diff --git a/tests/ui/explicit-tail-calls/intrinsics.rs b/tests/ui/explicit-tail-calls/intrinsics.rs new file mode 100644 index 000000000000..6fc521fa27d1 --- /dev/null +++ b/tests/ui/explicit-tail-calls/intrinsics.rs @@ -0,0 +1,13 @@ +#![feature(explicit_tail_calls, core_intrinsics)] +#![expect(incomplete_features, internal_features)] + +fn trans((): ()) { + unsafe { become std::mem::transmute(()) } //~ error: tail calling intrinsics is not allowed + +} + +fn cats(x: u64) -> u32 { + become std::intrinsics::ctlz(x) //~ error: tail calling intrinsics is not allowed +} + +fn main() {} diff --git a/tests/ui/explicit-tail-calls/intrinsics.stderr b/tests/ui/explicit-tail-calls/intrinsics.stderr new file mode 100644 index 000000000000..b012e3629dde --- /dev/null +++ b/tests/ui/explicit-tail-calls/intrinsics.stderr @@ -0,0 +1,14 @@ +error: tail calling intrinsics is not allowed + --> $DIR/intrinsics.rs:5:14 + | +LL | unsafe { become std::mem::transmute(()) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: tail calling intrinsics is not allowed + --> $DIR/intrinsics.rs:10:5 + | +LL | become std::intrinsics::ctlz(x) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + From eee28138b89902426815a0d9dd96800c686f5003 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 3 Aug 2025 12:47:11 -0700 Subject: [PATCH 0399/1134] Use `as_array` in PartialEq for arrays --- library/core/src/array/equality.rs | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/library/core/src/array/equality.rs b/library/core/src/array/equality.rs index bb668d2a6730..1ad2cca64a34 100644 --- a/library/core/src/array/equality.rs +++ b/library/core/src/array/equality.rs @@ -22,18 +22,16 @@ where { #[inline] fn eq(&self, other: &[U]) -> bool { - let b: Result<&[U; N], _> = other.try_into(); - match b { - Ok(b) => *self == *b, - Err(_) => false, + match other.as_array::() { + Some(b) => *self == *b, + None => false, } } #[inline] fn ne(&self, other: &[U]) -> bool { - let b: Result<&[U; N], _> = other.try_into(); - match b { - Ok(b) => *self != *b, - Err(_) => true, + match other.as_array::() { + Some(b) => *self != *b, + None => true, } } } @@ -45,18 +43,16 @@ where { #[inline] fn eq(&self, other: &[U; N]) -> bool { - let b: Result<&[T; N], _> = self.try_into(); - match b { - Ok(b) => *b == *other, - Err(_) => false, + match self.as_array::() { + Some(b) => *b == *other, + None => false, } } #[inline] fn ne(&self, other: &[U; N]) -> bool { - let b: Result<&[T; N], _> = self.try_into(); - match b { - Ok(b) => *b != *other, - Err(_) => true, + match self.as_array::() { + Some(b) => *b != *other, + None => true, } } } From f92934f43ac34d65a0c39e589d330f27a2f45574 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 3 Aug 2025 21:48:23 +0200 Subject: [PATCH 0400/1134] Remove `SHOULD_EMIT_LINTS` in favor of `should_emit` --- compiler/rustc_attr_parsing/src/context.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 767d19bd2340..91aae71cb82a 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -224,7 +224,6 @@ mod private { #[allow(private_interfaces)] pub trait Stage: Sized + 'static + Sealed { type Id: Copy; - const SHOULD_EMIT_LINTS: bool; fn parsers() -> &'static GroupType; @@ -233,13 +232,14 @@ pub trait Stage: Sized + 'static + Sealed { sess: &'sess Session, diag: impl for<'x> Diagnostic<'x>, ) -> ErrorGuaranteed; + + fn should_emit(&self) -> ShouldEmit; } // allow because it's a sealed trait #[allow(private_interfaces)] impl Stage for Early { type Id = NodeId; - const SHOULD_EMIT_LINTS: bool = false; fn parsers() -> &'static GroupType { &early::ATTRIBUTE_PARSERS @@ -255,13 +255,16 @@ impl Stage for Early { sess.dcx().create_err(diag).delay_as_bug() } } + + fn should_emit(&self) -> ShouldEmit { + self.emit_errors + } } // allow because it's a sealed trait #[allow(private_interfaces)] impl Stage for Late { type Id = HirId; - const SHOULD_EMIT_LINTS: bool = true; fn parsers() -> &'static GroupType { &late::ATTRIBUTE_PARSERS @@ -273,6 +276,10 @@ impl Stage for Late { ) -> ErrorGuaranteed { tcx.dcx().emit_err(diag) } + + fn should_emit(&self) -> ShouldEmit { + ShouldEmit::ErrorsAndLints + } } /// used when parsing attributes for miscellaneous things *before* ast lowering @@ -311,7 +318,7 @@ impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> { /// must be delayed until after HIR is built. This method will take care of the details of /// that. pub(crate) fn emit_lint(&mut self, lint: AttributeLintKind, span: Span) { - if !S::SHOULD_EMIT_LINTS { + if !self.stage.should_emit().should_emit() { return; } let id = self.target_id; From 566c9aeb66977f947f7b5a03d7e734c96625ca7f Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 3 Aug 2025 16:21:58 -0400 Subject: [PATCH 0401/1134] Fix simd_funnel_shift --- src/intrinsic/simd.rs | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/intrinsic/simd.rs b/src/intrinsic/simd.rs index 6748e1a41257..fdc15d580eff 100644 --- a/src/intrinsic/simd.rs +++ b/src/intrinsic/simd.rs @@ -1465,27 +1465,26 @@ fn simd_funnel_shift<'a, 'gcc, 'tcx>( shift: RValue<'gcc>, shift_left: bool, ) -> RValue<'gcc> { + use crate::common::SignType; + let a_type = a.get_type(); let vector_type = a_type.unqualified().dyncast_vector().expect("vector type"); let num_units = vector_type.get_num_units(); let elem_type = vector_type.get_element_type(); - let (new_int_type, int_shift_val, int_mask) = if elem_type.is_compatible_with(bx.u8_type) { + let (new_int_type, int_shift_val, int_mask) = if elem_type.is_compatible_with(bx.u8_type) + || elem_type.is_compatible_with(bx.i8_type) + { (bx.u16_type, 8, u8::MAX as u64) - } else if elem_type.is_compatible_with(bx.u16_type) { + } else if elem_type.is_compatible_with(bx.u16_type) || elem_type.is_compatible_with(bx.i16_type) + { (bx.u32_type, 16, u16::MAX as u64) - } else if elem_type.is_compatible_with(bx.u32_type) { + } else if elem_type.is_compatible_with(bx.u32_type) || elem_type.is_compatible_with(bx.i32_type) + { (bx.u64_type, 32, u32::MAX as u64) - } else if elem_type.is_compatible_with(bx.u64_type) { + } else if elem_type.is_compatible_with(bx.u64_type) || elem_type.is_compatible_with(bx.i64_type) + { (bx.u128_type, 64, u64::MAX) - } else if elem_type.is_compatible_with(bx.i8_type) { - (bx.i16_type, 8, u8::MAX as u64) - } else if elem_type.is_compatible_with(bx.i16_type) { - (bx.i32_type, 16, u16::MAX as u64) - } else if elem_type.is_compatible_with(bx.i32_type) { - (bx.i64_type, 32, u32::MAX as u64) - } else if elem_type.is_compatible_with(bx.i64_type) { - (bx.i128_type, 64, u64::MAX) } else { unimplemented!("funnel shift on {:?}", elem_type); }; @@ -1493,21 +1492,25 @@ fn simd_funnel_shift<'a, 'gcc, 'tcx>( let int_mask = bx.context.new_rvalue_from_long(new_int_type, int_mask as i64); let int_shift_val = bx.context.new_rvalue_from_int(new_int_type, int_shift_val); let mut elements = vec![]; + let unsigned_type = elem_type.to_unsigned(bx); for i in 0..num_units { let index = bx.context.new_rvalue_from_int(bx.int_type, i as i32); let a_val = bx.context.new_vector_access(None, a, index).to_rvalue(); - let a_val = bx.context.new_cast(None, a_val, new_int_type); + let a_val = bx.context.new_bitcast(None, a_val, unsigned_type); + // TODO: we probably need to use gcc_int_cast instead. + let a_val = bx.gcc_int_cast(a_val, new_int_type); let b_val = bx.context.new_vector_access(None, b, index).to_rvalue(); - let b_val = bx.context.new_cast(None, b_val, new_int_type); + let b_val = bx.context.new_bitcast(None, b_val, unsigned_type); + let b_val = bx.gcc_int_cast(b_val, new_int_type); let shift_val = bx.context.new_vector_access(None, shift, index).to_rvalue(); - let shift_val = bx.context.new_cast(None, shift_val, new_int_type); + let shift_val = bx.gcc_int_cast(shift_val, new_int_type); let mut val = a_val << int_shift_val | b_val; if shift_left { val = (val << shift_val) >> int_shift_val; } else { val = (val >> shift_val) & int_mask; } - let val = bx.context.new_cast(None, val, elem_type); + let val = bx.gcc_int_cast(val, elem_type); elements.push(val); } bx.context.new_rvalue_from_vector(None, a_type, &elements) From 68ef9c4ceed5f376f36e4b3e23094a115dd0d4c0 Mon Sep 17 00:00:00 2001 From: alexey semenyuk Date: Sat, 2 Aug 2025 21:47:53 +0500 Subject: [PATCH 0402/1134] Task priority --- CONTRIBUTING.md | 44 ++++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 72ab08792d37..42ed624ec212 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -199,26 +199,34 @@ currently. Between writing new lints, fixing issues, reviewing pull requests and responding to issues there may not always be enough time to stay on top of it all. -Our highest priority is fixing [ICEs][I-ICE] and [bugs][C-bug], for example -an ICE in a popular crate that many other crates depend on. We don't -want Clippy to crash on your code and we want it to be as reliable as the -suggestions from Rust compiler errors. - -We have prioritization labels and a sync-blocker label, which are described below. -- [P-low][p-low]: Requires attention (fix/response/evaluation) by a team member but isn't urgent. -- [P-medium][p-medium]: Should be addressed by a team member until the next sync. -- [P-high][p-high]: Should be immediately addressed and will require an out-of-cycle sync or a backport. -- [L-sync-blocker][l-sync-blocker]: An issue that "blocks" a sync. -Or rather: before the sync this should be addressed, -e.g. by removing a lint again, so it doesn't hit beta/stable. +To find things to fix, go to the [tracking issue][tracking_issue], find an issue that you like, +and claim it with `@rustbot claim`. + +As a general metric and always taking into account your skill and knowledge level, you can use this guide: + +- 🟥 [ICEs][search_ice], these are compiler errors that causes Clippy to panic and crash. Usually involves high-level +debugging, sometimes interacting directly with the upstream compiler. Difficult to fix but a great challenge that +improves a lot developer workflows! + +- 🟧 [Suggestion causes bug][sugg_causes_bug], Clippy suggested code that changed logic in some silent way. +Unacceptable, as this may have disastrous consequences. Easier to fix than ICEs + +- 🟨 [Suggestion causes error][sugg_causes_error], Clippy suggested code snippet that caused a compiler error +when applied. We need to make sure that Clippy doesn't suggest using a variable twice at the same time or similar +easy-to-happen occurrences. + +- 🟩 [False positives][false_positive], a lint should not have fired, the easiest of them all, as this is "just" +identifying the root of a false positive and making an exception for those cases. + +Note that false negatives do not have priority unless the case is very clear, as they are a feature-request in a +trench coat. [triage]: https://forge.rust-lang.org/release/triage-procedure.html -[I-ICE]: https://github.com/rust-lang/rust-clippy/labels/I-ICE -[C-bug]: https://github.com/rust-lang/rust-clippy/labels/C-bug -[p-low]: https://github.com/rust-lang/rust-clippy/labels/P-low -[p-medium]: https://github.com/rust-lang/rust-clippy/labels/P-medium -[p-high]: https://github.com/rust-lang/rust-clippy/labels/P-high -[l-sync-blocker]: https://github.com/rust-lang/rust-clippy/labels/L-sync-blocker +[search_ice]: https://github.com/rust-lang/rust-clippy/issues?q=sort%3Aupdated-desc+state%3Aopen+label%3A%22I-ICE%22 +[sugg_causes_bug]: https://github.com/rust-lang/rust-clippy/issues?q=sort%3Aupdated-desc%20state%3Aopen%20label%3AI-suggestion-causes-bug +[sugg_causes_error]: https://github.com/rust-lang/rust-clippy/issues?q=sort%3Aupdated-desc%20state%3Aopen%20label%3AI-suggestion-causes-error%20 +[false_positive]: https://github.com/rust-lang/rust-clippy/issues?q=sort%3Aupdated-desc%20state%3Aopen%20label%3AI-false-positive +[tracking_issue]: https://github.com/rust-lang/rust-clippy/issues/15086 ## Contributions From cf3865f7a540706cb4ae1537b8f37d136e47da4e Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Sun, 3 Aug 2025 22:28:04 +0200 Subject: [PATCH 0403/1134] fix broken doc section link in `poison.rs` --- library/std/src/sync/poison.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sync/poison.rs b/library/std/src/sync/poison.rs index d5adc9e29b50..31889dcc10fa 100644 --- a/library/std/src/sync/poison.rs +++ b/library/std/src/sync/poison.rs @@ -11,7 +11,7 @@ //! //! The specifics of how this "poisoned" state affects other threads and whether //! the panics are recognized reliably or on a best-effort basis depend on the -//! primitive. See [#Overview] below. +//! primitive. See [Overview](#overview) below. //! //! For the alternative implementations that do not employ poisoning, //! see [`std::sync::nonpoison`]. From 37922fc24cd785fff543be0c31b5c8529d7339f0 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Sun, 3 Aug 2025 22:28:49 +0200 Subject: [PATCH 0404/1134] add poisoning documentation to `LazyCell` --- library/core/src/cell/lazy.rs | 61 +++++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/library/core/src/cell/lazy.rs b/library/core/src/cell/lazy.rs index 1758e84ad7cd..a1bd4c857170 100644 --- a/library/core/src/cell/lazy.rs +++ b/library/core/src/cell/lazy.rs @@ -15,6 +15,22 @@ enum State { /// /// [`std::sync::LazyLock`]: ../../std/sync/struct.LazyLock.html /// +/// # Poisoning +/// +/// If the initialization closure passed to [`LazyCell::new`] panics, the cell will be poisoned. +/// Once the cell is poisoned, any threads that attempt to access this cell (via a dereference +/// or via an explicit call to [`force()`]) will panic. +/// +/// This concept is similar to that of poisoning in the [`std::sync::poison`] module. A key +/// difference, however, is that poisoning in `LazyCell` is _unrecoverable_. All future accesses of +/// the cell from other threads will panic, whereas a type in [`std::sync::poison`] like +/// [`std::sync::poison::Mutex`] allows recovery via [`PoisonError::into_inner()`]. +/// +/// [`force()`]: LazyCell::force +/// [`std::sync::poison`]: ../../std/sync/poison/index.html +/// [`std::sync::poison::Mutex`]: ../../std/sync/poison/struct.Mutex.html +/// [`PoisonError::into_inner()`]: ../../std/sync/poison/struct.PoisonError.html#method.into_inner +/// /// # Examples /// /// ``` @@ -64,6 +80,10 @@ impl T> LazyCell { /// /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise. /// + /// # Panics + /// + /// Panics if the cell is poisoned. + /// /// # Examples /// /// ``` @@ -93,6 +113,15 @@ impl T> LazyCell { /// /// This is equivalent to the `Deref` impl, but is explicit. /// + /// # Panics + /// + /// If the initialization closure panics (the one that is passed to the [`new()`] method), the + /// panic is propagated to the caller, and the cell becomes poisoned. This will cause all future + /// accesses of the cell (via [`force()`] or a dereference) to panic. + /// + /// [`new()`]: LazyCell::new + /// [`force()`]: LazyCell::force + /// /// # Examples /// /// ``` @@ -123,6 +152,15 @@ impl T> LazyCell { /// Forces the evaluation of this lazy value and returns a mutable reference to /// the result. /// + /// # Panics + /// + /// If the initialization closure panics (the one that is passed to the [`new()`] method), the + /// panic is propagated to the caller, and the cell becomes poisoned. This will cause all future + /// accesses of the cell (via [`force()`] or a dereference) to panic. + /// + /// [`new()`]: LazyCell::new + /// [`force()`]: LazyCell::force + /// /// # Examples /// /// ``` @@ -219,7 +257,8 @@ impl T> LazyCell { } impl LazyCell { - /// Returns a mutable reference to the value if initialized, or `None` if not. + /// Returns a mutable reference to the value if initialized. Otherwise (if uninitialized or + /// poisoned), returns `None`. /// /// # Examples /// @@ -245,7 +284,8 @@ impl LazyCell { } } - /// Returns a reference to the value if initialized, or `None` if not. + /// Returns a reference to the value if initialized. Otherwise (if uninitialized or poisoned), + /// returns `None`. /// /// # Examples /// @@ -278,6 +318,15 @@ impl LazyCell { #[stable(feature = "lazy_cell", since = "1.80.0")] impl T> Deref for LazyCell { type Target = T; + + /// # Panics + /// + /// If the initialization closure panics (the one that is passed to the [`new()`] method), the + /// panic is propagated to the caller, and the cell becomes poisoned. This will cause all future + /// accesses of the cell (via [`force()`] or a dereference) to panic. + /// + /// [`new()`]: LazyCell::new + /// [`force()`]: LazyCell::force #[inline] fn deref(&self) -> &T { LazyCell::force(self) @@ -286,6 +335,14 @@ impl T> Deref for LazyCell { #[stable(feature = "lazy_deref_mut", since = "1.89.0")] impl T> DerefMut for LazyCell { + /// # Panics + /// + /// If the initialization closure panics (the one that is passed to the [`new()`] method), the + /// panic is propagated to the caller, and the cell becomes poisoned. This will cause all future + /// accesses of the cell (via [`force()`] or a dereference) to panic. + /// + /// [`new()`]: LazyCell::new + /// [`force()`]: LazyCell::force #[inline] fn deref_mut(&mut self) -> &mut T { LazyCell::force_mut(self) From 96adb7df9628ae2f495dbafde387dda0152e5fb8 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Sun, 3 Aug 2025 22:29:19 +0200 Subject: [PATCH 0405/1134] add poisoning documentation to `LazyLock` --- library/std/src/sync/lazy_lock.rs | 60 +++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/library/std/src/sync/lazy_lock.rs b/library/std/src/sync/lazy_lock.rs index eba849d16dac..a40e29a772a9 100644 --- a/library/std/src/sync/lazy_lock.rs +++ b/library/std/src/sync/lazy_lock.rs @@ -25,6 +25,22 @@ union Data { /// /// [`LazyCell`]: crate::cell::LazyCell /// +/// # Poisoning +/// +/// If the initialization closure passed to [`LazyLock::new`] panics, the lock will be poisoned. +/// Once the lock is poisoned, any threads that attempt to access this lock (via a dereference +/// or via an explicit call to [`force()`]) will panic. +/// +/// This concept is similar to that of poisoning in the [`std::sync::poison`] module. A key +/// difference, however, is that poisoning in `LazyLock` is _unrecoverable_. All future accesses of +/// the lock from other threads will panic, whereas a type in [`std::sync::poison`] like +/// [`std::sync::poison::Mutex`] allows recovery via [`PoisonError::into_inner()`]. +/// +/// [`force()`]: LazyLock::force +/// [`std::sync::poison`]: crate::sync::poison +/// [`std::sync::poison::Mutex`]: crate::sync::poison::Mutex +/// [`PoisonError::into_inner()`]: crate::sync::poison::PoisonError::into_inner +/// /// # Examples /// /// Initialize static variables with `LazyLock`. @@ -102,6 +118,10 @@ impl T> LazyLock { /// /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise. /// + /// # Panics + /// + /// Panics if the lock is poisoned. + /// /// # Examples /// /// ``` @@ -136,6 +156,15 @@ impl T> LazyLock { /// Forces the evaluation of this lazy value and returns a mutable reference to /// the result. /// + /// # Panics + /// + /// If the initialization closure panics (the one that is passed to the [`new()`] method), the + /// panic is propagated to the caller, and the lock becomes poisoned. This will cause all future + /// accesses of the lock (via [`force()`] or a dereference) to panic. + /// + /// [`new()`]: LazyLock::new + /// [`force()`]: LazyLock::force + /// /// # Examples /// /// ``` @@ -193,6 +222,15 @@ impl T> LazyLock { /// This method will block the calling thread if another initialization /// routine is currently running. /// + /// # Panics + /// + /// If the initialization closure panics (the one that is passed to the [`new()`] method), the + /// panic is propagated to the caller, and the lock becomes poisoned. This will cause all future + /// accesses of the lock (via [`force()`] or a dereference) to panic. + /// + /// [`new()`]: LazyLock::new + /// [`force()`]: LazyLock::force + /// /// # Examples /// /// ``` @@ -227,7 +265,8 @@ impl T> LazyLock { } impl LazyLock { - /// Returns a mutable reference to the value if initialized, or `None` if not. + /// Returns a mutable reference to the value if initialized. Otherwise (if uninitialized or + /// poisoned), returns `None`. /// /// # Examples /// @@ -256,7 +295,8 @@ impl LazyLock { } } - /// Returns a reference to the value if initialized, or `None` if not. + /// Returns a reference to the value if initialized. Otherwise (if uninitialized or poisoned), + /// returns `None`. /// /// # Examples /// @@ -307,6 +347,14 @@ impl T> Deref for LazyLock { /// This method will block the calling thread if another initialization /// routine is currently running. /// + /// # Panics + /// + /// If the initialization closure panics (the one that is passed to the [`new()`] method), the + /// panic is propagated to the caller, and the lock becomes poisoned. This will cause all future + /// accesses of the lock (via [`force()`] or a dereference) to panic. + /// + /// [`new()`]: LazyLock::new + /// [`force()`]: LazyLock::force #[inline] fn deref(&self) -> &T { LazyLock::force(self) @@ -315,6 +363,14 @@ impl T> Deref for LazyLock { #[stable(feature = "lazy_deref_mut", since = "1.89.0")] impl T> DerefMut for LazyLock { + /// # Panics + /// + /// If the initialization closure panics (the one that is passed to the [`new()`] method), the + /// panic is propagated to the caller, and the lock becomes poisoned. This will cause all future + /// accesses of the lock (via [`force()`] or a dereference) to panic. + /// + /// [`new()`]: LazyLock::new + /// [`force()`]: LazyLock::force #[inline] fn deref_mut(&mut self) -> &mut T { LazyLock::force_mut(self) From 4c4b8b23c6935e719ca01b614922024abb694656 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Mon, 4 Aug 2025 01:06:04 +0500 Subject: [PATCH 0406/1134] remove gate --- library/std/src/path.rs | 3 +-- library/std/tests/path.rs | 8 +------- src/tools/clippy/tests/missing-test-files.rs | 2 +- 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 055e7f814800..5dd52a23e97c 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -2678,7 +2678,6 @@ impl Path { /// # Examples /// /// ``` - /// # #![feature(path_file_prefix)] /// use std::path::Path; /// /// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap()); @@ -2691,7 +2690,7 @@ impl Path { /// /// [`Path::file_stem`]: Path::file_stem /// - #[unstable(feature = "path_file_prefix", issue = "86319")] + #[stable(feature = "path_file_prefix", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn file_prefix(&self) -> Option<&OsStr> { self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before)) diff --git a/library/std/tests/path.rs b/library/std/tests/path.rs index 901d2770f203..e1576a0d4231 100644 --- a/library/std/tests/path.rs +++ b/library/std/tests/path.rs @@ -1,10 +1,4 @@ -#![feature( - clone_to_uninit, - path_add_extension, - path_file_prefix, - maybe_uninit_slice, - normalize_lexically -)] +#![feature(clone_to_uninit, path_add_extension, maybe_uninit_slice, normalize_lexically)] use std::clone::CloneToUninit; use std::ffi::OsStr; diff --git a/src/tools/clippy/tests/missing-test-files.rs b/src/tools/clippy/tests/missing-test-files.rs index 565dcd73f582..63f960c92fa3 100644 --- a/src/tools/clippy/tests/missing-test-files.rs +++ b/src/tools/clippy/tests/missing-test-files.rs @@ -1,6 +1,6 @@ #![warn(rust_2018_idioms, unused_lifetimes)] #![allow(clippy::assertions_on_constants)] -#![feature(path_file_prefix)] +#![cfg_attr(bootstrap, feature(path_file_prefix))] use std::cmp::Ordering; use std::ffi::OsStr; From 36f2045a930a3367963881db4f423d7de33b46a5 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 12 Jul 2025 13:47:45 +0000 Subject: [PATCH 0407/1134] Implement `stability_implications` without a visitor. --- compiler/rustc_hir/src/def.rs | 41 +++++++++ compiler/rustc_passes/src/stability.rs | 111 +++++++------------------ 2 files changed, 72 insertions(+), 80 deletions(-) diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index 3fee9af01b36..8774fb4d5858 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -305,6 +305,11 @@ impl DefKind { matches!(self, DefKind::Mod | DefKind::Enum | DefKind::Trait) } + #[inline] + pub fn is_adt(self) -> bool { + matches!(self, DefKind::Struct | DefKind::Union | DefKind::Enum) + } + #[inline] pub fn is_fn_like(self) -> bool { matches!( @@ -313,6 +318,42 @@ impl DefKind { ) } + pub fn has_generics(self) -> bool { + match self { + DefKind::AnonConst + | DefKind::AssocConst + | DefKind::AssocFn + | DefKind::AssocTy + | DefKind::Closure + | DefKind::Const + | DefKind::Ctor(..) + | DefKind::Enum + | DefKind::Field + | DefKind::Fn + | DefKind::ForeignTy + | DefKind::Impl { .. } + | DefKind::InlineConst + | DefKind::OpaqueTy + | DefKind::Static { .. } + | DefKind::Struct + | DefKind::SyntheticCoroutineBody + | DefKind::Trait + | DefKind::TraitAlias + | DefKind::TyAlias + | DefKind::Union + | DefKind::Variant => true, + DefKind::ConstParam + | DefKind::ExternCrate + | DefKind::ForeignMod + | DefKind::GlobalAsm + | DefKind::LifetimeParam + | DefKind::Macro(_) + | DefKind::Mod + | DefKind::TyParam + | DefKind::Use => false, + } + } + /// Whether `query get_codegen_attrs` should be used with this definition. pub fn has_codegen_attrs(self) -> bool { match self { diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 9ed7293873f5..abc1821e76d1 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -267,93 +267,51 @@ fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { - tcx: TyCtxt<'tcx>, - implications: UnordMap, -} - -impl<'tcx> Annotator<'tcx> { - /// Determine the stability for a node based on its attributes and inherited stability. The - /// stability is recorded in the index and used as the parent. If the node is a function, - /// `fn_sig` is its signature. - #[instrument(level = "trace", skip(self))] - fn annotate(&mut self, def_id: LocalDefId) { - if !self.tcx.features().staged_api() { - return; - } +fn stability_implications(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> UnordMap { + let mut implications = UnordMap::default(); - if let Some(stability) = self.tcx.lookup_stability(def_id) + let mut register_implication = |def_id| { + if let Some(stability) = tcx.lookup_stability(def_id) && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level { - self.implications.insert(implied_by, stability.feature); + implications.insert(implied_by, stability.feature); } - if let Some(stability) = self.tcx.lookup_const_stability(def_id) + if let Some(stability) = tcx.lookup_const_stability(def_id) && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level { - self.implications.insert(implied_by, stability.feature); + implications.insert(implied_by, stability.feature); } - } -} - -impl<'tcx> Visitor<'tcx> for Annotator<'tcx> { - /// Because stability levels are scoped lexically, we want to walk - /// nested items in the context of the outer item, so enable - /// deep-walking. - type NestedFilter = nested_filter::All; - - fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt { - self.tcx - } + }; - fn visit_item(&mut self, i: &'tcx Item<'tcx>) { - match i.kind { - hir::ItemKind::Struct(_, _, ref sd) => { - if let Some(ctor_def_id) = sd.ctor_def_id() { - self.annotate(ctor_def_id); + if tcx.features().staged_api() { + register_implication(CRATE_DEF_ID); + for def_id in tcx.hir_crate_items(()).definitions() { + register_implication(def_id); + let def_kind = tcx.def_kind(def_id); + if def_kind.is_adt() { + let adt = tcx.adt_def(def_id); + for variant in adt.variants() { + if variant.def_id != def_id.to_def_id() { + register_implication(variant.def_id.expect_local()); + } + for field in &variant.fields { + register_implication(field.did.expect_local()); + } + if let Some(ctor_def_id) = variant.ctor_def_id() { + register_implication(ctor_def_id.expect_local()) + } + } + } + if def_kind.has_generics() { + for param in tcx.generics_of(def_id).own_params.iter() { + register_implication(param.def_id.expect_local()) } } - _ => {} - } - - self.annotate(i.owner_id.def_id); - intravisit::walk_item(self, i) - } - - fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { - self.annotate(ti.owner_id.def_id); - intravisit::walk_trait_item(self, ti); - } - - fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { - self.annotate(ii.owner_id.def_id); - intravisit::walk_impl_item(self, ii); - } - - fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) { - self.annotate(var.def_id); - if let Some(ctor_def_id) = var.data.ctor_def_id() { - self.annotate(ctor_def_id); } - - intravisit::walk_variant(self, var) } - fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) { - self.annotate(s.def_id); - intravisit::walk_field_def(self, s); - } - - fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { - self.annotate(i.owner_id.def_id); - intravisit::walk_foreign_item(self, i); - } - - fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) { - self.annotate(p.def_id); - intravisit::walk_generic_param(self, p); - } + implications } struct MissingStabilityAnnotations<'tcx> { @@ -565,13 +523,6 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { } } -fn stability_implications(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> UnordMap { - let mut annotator = Annotator { tcx, implications: Default::default() }; - annotator.annotate(CRATE_DEF_ID); - tcx.hir_walk_toplevel_module(&mut annotator); - annotator.implications -} - /// Cross-references the feature names of unstable APIs with enabled /// features and possibly prints errors. fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { From cc62d552980238335fb7ef4c28196b63a4ec8894 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 4 Aug 2025 08:16:32 +1000 Subject: [PATCH 0408/1134] Avoid some code duplication. `print_binder` can call `wrap_binder`. --- compiler/rustc_middle/src/ty/print/pretty.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 033f1e6cd064..b381d62be47e 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2437,12 +2437,7 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { where T: Print<'tcx, Self> + TypeFoldable>, { - let old_region_index = self.region_index; - let (new_value, _) = self.name_all_regions(value, WrapBinderMode::ForAll)?; - new_value.print(self)?; - self.region_index = old_region_index; - self.binder_depth -= 1; - Ok(()) + self.wrap_binder(value, WrapBinderMode::ForAll, |new_value, this| new_value.print(this)) } fn wrap_binder Result<(), PrintError>>( From 1fc5e81436d6e08dacf2e6672ada8936d93e94b9 Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sat, 2 Aug 2025 09:27:07 +0200 Subject: [PATCH 0409/1134] clean-up `semicolon_inside_block` match on `StmtKind` directly use a let-chain break up match for a nicer let-chain shorten `get_line` move `expr` check down in the inside case as well for consistency use `shrink_to_hi` Apply suggestion Co-authored-by: Samuel Tardieu --- clippy_lints/src/semicolon_block.rs | 36 ++++++++++------------------- 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/clippy_lints/src/semicolon_block.rs b/clippy_lints/src/semicolon_block.rs index f6c128d4c529..db91c57b1816 100644 --- a/clippy_lints/src/semicolon_block.rs +++ b/clippy_lints/src/semicolon_block.rs @@ -102,7 +102,7 @@ impl SemicolonBlock { } fn semicolon_outside_block(&self, cx: &LateContext<'_>, block: &Block<'_>, tail_stmt_expr: &Expr<'_>) { - let insert_span = block.span.with_lo(block.span.hi()); + let insert_span = block.span.shrink_to_hi(); // For macro call semicolon statements (`mac!();`), the statement's span does not actually // include the semicolon itself, so use `mac_call_stmt_semi_span`, which finds the semicolon @@ -144,28 +144,20 @@ impl LateLintPass<'_> for SemicolonBlock { kind: ExprKind::Block(block, _), .. }) if !block.span.from_expansion() && stmt.span.contains(block.span) => { - let Block { - expr: None, - stmts: [.., stmt], - .. - } = block - else { - return; - }; - let &Stmt { - kind: StmtKind::Semi(expr), - .. - } = stmt - else { - return; - }; - self.semicolon_outside_block(cx, block, expr); + if block.expr.is_none() + && let [.., stmt] = block.stmts + && let StmtKind::Semi(expr) = stmt.kind + { + self.semicolon_outside_block(cx, block, expr); + } }, StmtKind::Semi(Expr { - kind: ExprKind::Block(block @ Block { expr: Some(tail), .. }, _), + kind: ExprKind::Block(block, _), .. }) if !block.span.from_expansion() => { - self.semicolon_inside_block(cx, block, tail, stmt.span); + if let Some(tail) = block.expr { + self.semicolon_inside_block(cx, block, tail, stmt.span); + } }, _ => (), } @@ -173,9 +165,5 @@ impl LateLintPass<'_> for SemicolonBlock { } fn get_line(cx: &LateContext<'_>, span: Span) -> Option { - if let Ok(line) = cx.sess().source_map().lookup_line(span.lo()) { - return Some(line.line); - } - - None + cx.sess().source_map().lookup_line(span.lo()).ok().map(|line| line.line) } From 6b363ae114e105baf8f91c3b34882b08b52a48b6 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 3 Aug 2025 18:58:23 -0400 Subject: [PATCH 0410/1134] Update to nightly-2025-08-03 --- rust-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain b/rust-toolchain index b220c804c2f2..058e734be5cf 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2025-07-21" +channel = "nightly-2025-08-03" components = ["rust-src", "rustc-dev", "llvm-tools-preview"] From 24f17515523a1abd255fee605483aed5d38843ff Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 3 Aug 2025 19:30:57 -0400 Subject: [PATCH 0411/1134] Add new failing test --- tests/failing-ui-tests.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/failing-ui-tests.txt b/tests/failing-ui-tests.txt index 4dc9507f28f1..41fb4729c07d 100644 --- a/tests/failing-ui-tests.txt +++ b/tests/failing-ui-tests.txt @@ -84,3 +84,5 @@ tests/ui/simd/intrinsic/generic-arithmetic-pass.rs tests/ui/linking/no-gc-encapsulation-symbols.rs tests/ui/panics/unwind-force-no-unwind-tables.rs tests/ui/attributes/fn-align-dyn.rs +tests/ui/linkage-attr/raw-dylib/elf/glibc-x86_64.rs +tests/ui/explicit-tail-calls/recursion-etc.rs From dac1f3451831c841fad635aca9c801c81652b2e9 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 3 Aug 2025 19:57:04 -0400 Subject: [PATCH 0412/1134] Fix stdarch patch --- ...1-Add-stdarch-Cargo.toml-for-testing.patch | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/patches/0001-Add-stdarch-Cargo.toml-for-testing.patch b/patches/0001-Add-stdarch-Cargo.toml-for-testing.patch index 9cc377850b9b..3a8c37a8b8d9 100644 --- a/patches/0001-Add-stdarch-Cargo.toml-for-testing.patch +++ b/patches/0001-Add-stdarch-Cargo.toml-for-testing.patch @@ -1,29 +1,28 @@ -From b8f3eed3053c9333b5dfbeaeb2a6a65a4b3156df Mon Sep 17 00:00:00 2001 -From: Antoni Boucher -Date: Tue, 29 Aug 2023 13:06:34 -0400 +From 190e26c9274b3c93a9ee3516b395590e6bd9213b Mon Sep 17 00:00:00 2001 +From: None +Date: Sun, 3 Aug 2025 19:54:56 -0400 Subject: [PATCH] Patch 0001-Add-stdarch-Cargo.toml-for-testing.patch --- - library/stdarch/Cargo.toml | 23 +++++++++++++++++++++++ - 1 file changed, 23 insertions(+) + library/stdarch/Cargo.toml | 20 ++++++++++++++++++++ + 1 file changed, 20 insertions(+) create mode 100644 library/stdarch/Cargo.toml diff --git a/library/stdarch/Cargo.toml b/library/stdarch/Cargo.toml new file mode 100644 -index 0000000..4c63700 +index 0000000..bd6725c --- /dev/null +++ b/library/stdarch/Cargo.toml -@@ -0,0 +1,21 @@ +@@ -0,0 +1,20 @@ +[workspace] +resolver = "1" +members = [ -+ "crates/core_arch", -+ "crates/std_detect", -+ "crates/stdarch-gen-arm", ++ "crates/*", + #"examples/" +] +exclude = [ -+ "crates/wasm-assert-instr-tests" ++ "crates/wasm-assert-instr-tests", ++ "rust_programs", +] + +[profile.release] @@ -36,5 +35,5 @@ index 0000000..4c63700 +opt-level = 3 +incremental = true -- -2.42.0 +2.50.1 From 17241a7a91d66629483c3ad479bca9b45bd59169 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nurzhan=20Sak=C3=A9n?= Date: Mon, 4 Aug 2025 04:13:10 +0400 Subject: [PATCH 0413/1134] Remove strict_overflow_ops lint --- .../crates/ide-db/src/generated/lints.rs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs index f9eb44d03abb..14bc380586aa 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs @@ -10699,20 +10699,6 @@ The tracking issue for this feature is: [#77998] [#77998]: https://github.com/rust-lang/rust/issues/77998 ------------------------- -"##, - default_severity: Severity::Allow, - warn_since: None, - deny_since: None, - }, - Lint { - label: "strict_overflow_ops", - description: r##"# `strict_overflow_ops` - -The tracking issue for this feature is: [#118260] - -[#118260]: https://github.com/rust-lang/rust/issues/118260 - ------------------------ "##, default_severity: Severity::Allow, From c441640f0eab5abcdf5004aacdc5e4830c3f1552 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Fri, 25 Jul 2025 11:16:14 -0700 Subject: [PATCH 0414/1134] Add a mir-opt test for *debug* MIR from `derive(PartialOrd, Ord)` Because the follow-up commits will affect it, and the goal is to show how. --- .../mir-opt/pre-codegen/derived_ord_debug.rs | 18 +++++++ ...rtial_cmp.PreCodegen.after.panic-abort.mir | 52 +++++++++++++++++++ ...tial_cmp.PreCodegen.after.panic-unwind.mir | 52 +++++++++++++++++++ ...pl#1}-cmp.PreCodegen.after.panic-abort.mir | 42 +++++++++++++++ ...l#1}-cmp.PreCodegen.after.panic-unwind.mir | 42 +++++++++++++++ 5 files changed, 206 insertions(+) create mode 100644 tests/mir-opt/pre-codegen/derived_ord_debug.rs create mode 100644 tests/mir-opt/pre-codegen/derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.panic-abort.mir create mode 100644 tests/mir-opt/pre-codegen/derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.panic-unwind.mir create mode 100644 tests/mir-opt/pre-codegen/derived_ord_debug.{impl#1}-cmp.PreCodegen.after.panic-abort.mir create mode 100644 tests/mir-opt/pre-codegen/derived_ord_debug.{impl#1}-cmp.PreCodegen.after.panic-unwind.mir diff --git a/tests/mir-opt/pre-codegen/derived_ord_debug.rs b/tests/mir-opt/pre-codegen/derived_ord_debug.rs new file mode 100644 index 000000000000..1d6a884cee44 --- /dev/null +++ b/tests/mir-opt/pre-codegen/derived_ord_debug.rs @@ -0,0 +1,18 @@ +//@ compile-flags: -Copt-level=0 -Zmir-opt-level=1 -Cdebuginfo=limited +// EMIT_MIR_FOR_EACH_PANIC_STRATEGY + +#![crate_type = "lib"] + +#[derive(PartialOrd, Ord, PartialEq, Eq)] +pub struct MultiField(char, i16); + +// EMIT_MIR derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.mir +// EMIT_MIR derived_ord_debug.{impl#1}-cmp.PreCodegen.after.mir + +// CHECK-LABEL: partial_cmp(_1: &MultiField, _2: &MultiField) -> Option +// CHECK: = ::partial_cmp( +// CHECK: = ::partial_cmp( + +// CHECK-LABEL: cmp(_1: &MultiField, _2: &MultiField) -> std::cmp::Ordering +// CHECK: = ::cmp( +// CHECK: = ::cmp( diff --git a/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.panic-abort.mir new file mode 100644 index 000000000000..9fc8da3a1120 --- /dev/null +++ b/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.panic-abort.mir @@ -0,0 +1,52 @@ +// MIR for `::partial_cmp` after PreCodegen + +fn ::partial_cmp(_1: &MultiField, _2: &MultiField) -> Option { + debug self => _1; + debug other => _2; + let mut _0: std::option::Option; + let _3: &char; + let _4: &char; + let mut _5: std::option::Option; + let mut _6: isize; + let mut _7: i8; + let _8: &i16; + let _9: &i16; + scope 1 { + debug cmp => _5; + } + + bb0: { + _3 = &((*_1).0: char); + _4 = &((*_2).0: char); + _5 = ::partial_cmp(copy _3, copy _4) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _6 = discriminant(_5); + switchInt(move _6) -> [1: bb2, 0: bb4, otherwise: bb6]; + } + + bb2: { + _7 = discriminant(((_5 as Some).0: std::cmp::Ordering)); + switchInt(move _7) -> [0: bb3, otherwise: bb4]; + } + + bb3: { + _8 = &((*_1).1: i16); + _9 = &((*_2).1: i16); + _0 = ::partial_cmp(copy _8, copy _9) -> [return: bb5, unwind unreachable]; + } + + bb4: { + _0 = copy _5; + goto -> bb5; + } + + bb5: { + return; + } + + bb6: { + unreachable; + } +} diff --git a/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.panic-unwind.mir new file mode 100644 index 000000000000..29cc54150764 --- /dev/null +++ b/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#0}-partial_cmp.PreCodegen.after.panic-unwind.mir @@ -0,0 +1,52 @@ +// MIR for `::partial_cmp` after PreCodegen + +fn ::partial_cmp(_1: &MultiField, _2: &MultiField) -> Option { + debug self => _1; + debug other => _2; + let mut _0: std::option::Option; + let _3: &char; + let _4: &char; + let mut _5: std::option::Option; + let mut _6: isize; + let mut _7: i8; + let _8: &i16; + let _9: &i16; + scope 1 { + debug cmp => _5; + } + + bb0: { + _3 = &((*_1).0: char); + _4 = &((*_2).0: char); + _5 = ::partial_cmp(copy _3, copy _4) -> [return: bb1, unwind continue]; + } + + bb1: { + _6 = discriminant(_5); + switchInt(move _6) -> [1: bb2, 0: bb4, otherwise: bb6]; + } + + bb2: { + _7 = discriminant(((_5 as Some).0: std::cmp::Ordering)); + switchInt(move _7) -> [0: bb3, otherwise: bb4]; + } + + bb3: { + _8 = &((*_1).1: i16); + _9 = &((*_2).1: i16); + _0 = ::partial_cmp(copy _8, copy _9) -> [return: bb5, unwind continue]; + } + + bb4: { + _0 = copy _5; + goto -> bb5; + } + + bb5: { + return; + } + + bb6: { + unreachable; + } +} diff --git a/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#1}-cmp.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#1}-cmp.PreCodegen.after.panic-abort.mir new file mode 100644 index 000000000000..66d96021aa9b --- /dev/null +++ b/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#1}-cmp.PreCodegen.after.panic-abort.mir @@ -0,0 +1,42 @@ +// MIR for `::cmp` after PreCodegen + +fn ::cmp(_1: &MultiField, _2: &MultiField) -> std::cmp::Ordering { + debug self => _1; + debug other => _2; + let mut _0: std::cmp::Ordering; + let _3: &char; + let _4: &char; + let mut _5: std::cmp::Ordering; + let mut _6: i8; + let _7: &i16; + let _8: &i16; + scope 1 { + debug cmp => _5; + } + + bb0: { + _3 = &((*_1).0: char); + _4 = &((*_2).0: char); + _5 = ::cmp(copy _3, copy _4) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _6 = discriminant(_5); + switchInt(move _6) -> [0: bb2, otherwise: bb3]; + } + + bb2: { + _7 = &((*_1).1: i16); + _8 = &((*_2).1: i16); + _0 = ::cmp(copy _7, copy _8) -> [return: bb4, unwind unreachable]; + } + + bb3: { + _0 = copy _5; + goto -> bb4; + } + + bb4: { + return; + } +} diff --git a/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#1}-cmp.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#1}-cmp.PreCodegen.after.panic-unwind.mir new file mode 100644 index 000000000000..2dcba6195f71 --- /dev/null +++ b/tests/mir-opt/pre-codegen/derived_ord_debug.{impl#1}-cmp.PreCodegen.after.panic-unwind.mir @@ -0,0 +1,42 @@ +// MIR for `::cmp` after PreCodegen + +fn ::cmp(_1: &MultiField, _2: &MultiField) -> std::cmp::Ordering { + debug self => _1; + debug other => _2; + let mut _0: std::cmp::Ordering; + let _3: &char; + let _4: &char; + let mut _5: std::cmp::Ordering; + let mut _6: i8; + let _7: &i16; + let _8: &i16; + scope 1 { + debug cmp => _5; + } + + bb0: { + _3 = &((*_1).0: char); + _4 = &((*_2).0: char); + _5 = ::cmp(copy _3, copy _4) -> [return: bb1, unwind continue]; + } + + bb1: { + _6 = discriminant(_5); + switchInt(move _6) -> [0: bb2, otherwise: bb3]; + } + + bb2: { + _7 = &((*_1).1: i16); + _8 = &((*_2).1: i16); + _0 = ::cmp(copy _7, copy _8) -> [return: bb4, unwind continue]; + } + + bb3: { + _0 = copy _5; + goto -> bb4; + } + + bb4: { + return; + } +} From e1a38ec2abe116454991aebc32a85b990fc35f7e Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Fri, 25 Jul 2025 21:11:26 -0700 Subject: [PATCH 0415/1134] Add a debug-mode MIR pre-codegen test for `?`-on-`Option` --- ...on_direct.PreCodegen.after.panic-abort.mir | 37 +++++++++++++++ ...n_direct.PreCodegen.after.panic-unwind.mir | 37 +++++++++++++++ ...on_traits.PreCodegen.after.panic-abort.mir | 47 +++++++++++++++++++ ...n_traits.PreCodegen.after.panic-unwind.mir | 47 +++++++++++++++++++ .../pre-codegen/option_bubble_debug.rs | 29 ++++++++++++ 5 files changed, 197 insertions(+) create mode 100644 tests/mir-opt/pre-codegen/option_bubble_debug.option_direct.PreCodegen.after.panic-abort.mir create mode 100644 tests/mir-opt/pre-codegen/option_bubble_debug.option_direct.PreCodegen.after.panic-unwind.mir create mode 100644 tests/mir-opt/pre-codegen/option_bubble_debug.option_traits.PreCodegen.after.panic-abort.mir create mode 100644 tests/mir-opt/pre-codegen/option_bubble_debug.option_traits.PreCodegen.after.panic-unwind.mir create mode 100644 tests/mir-opt/pre-codegen/option_bubble_debug.rs diff --git a/tests/mir-opt/pre-codegen/option_bubble_debug.option_direct.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/option_bubble_debug.option_direct.PreCodegen.after.panic-abort.mir new file mode 100644 index 000000000000..b29662dfa613 --- /dev/null +++ b/tests/mir-opt/pre-codegen/option_bubble_debug.option_direct.PreCodegen.after.panic-abort.mir @@ -0,0 +1,37 @@ +// MIR for `option_direct` after PreCodegen + +fn option_direct(_1: Option) -> Option { + debug x => _1; + let mut _0: std::option::Option; + let mut _2: isize; + let _3: u32; + let mut _4: u32; + scope 1 { + debug x => _3; + } + + bb0: { + _2 = discriminant(_1); + switchInt(move _2) -> [0: bb1, 1: bb2, otherwise: bb4]; + } + + bb1: { + _0 = Option::::None; + goto -> bb3; + } + + bb2: { + _3 = copy ((_1 as Some).0: u32); + _4 = Not(copy _3); + _0 = Option::::Some(move _4); + goto -> bb3; + } + + bb3: { + return; + } + + bb4: { + unreachable; + } +} diff --git a/tests/mir-opt/pre-codegen/option_bubble_debug.option_direct.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/option_bubble_debug.option_direct.PreCodegen.after.panic-unwind.mir new file mode 100644 index 000000000000..b29662dfa613 --- /dev/null +++ b/tests/mir-opt/pre-codegen/option_bubble_debug.option_direct.PreCodegen.after.panic-unwind.mir @@ -0,0 +1,37 @@ +// MIR for `option_direct` after PreCodegen + +fn option_direct(_1: Option) -> Option { + debug x => _1; + let mut _0: std::option::Option; + let mut _2: isize; + let _3: u32; + let mut _4: u32; + scope 1 { + debug x => _3; + } + + bb0: { + _2 = discriminant(_1); + switchInt(move _2) -> [0: bb1, 1: bb2, otherwise: bb4]; + } + + bb1: { + _0 = Option::::None; + goto -> bb3; + } + + bb2: { + _3 = copy ((_1 as Some).0: u32); + _4 = Not(copy _3); + _0 = Option::::Some(move _4); + goto -> bb3; + } + + bb3: { + return; + } + + bb4: { + unreachable; + } +} diff --git a/tests/mir-opt/pre-codegen/option_bubble_debug.option_traits.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/option_bubble_debug.option_traits.PreCodegen.after.panic-abort.mir new file mode 100644 index 000000000000..5b401064dd0e --- /dev/null +++ b/tests/mir-opt/pre-codegen/option_bubble_debug.option_traits.PreCodegen.after.panic-abort.mir @@ -0,0 +1,47 @@ +// MIR for `option_traits` after PreCodegen + +fn option_traits(_1: Option) -> Option { + debug x => _1; + let mut _0: std::option::Option; + let mut _2: std::ops::ControlFlow, u32>; + let mut _3: isize; + let _4: u32; + let mut _5: u32; + scope 1 { + debug residual => const Option::::None; + scope 2 { + } + } + scope 3 { + debug val => _4; + scope 4 { + } + } + + bb0: { + _2 = as Try>::branch(copy _1) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _3 = discriminant(_2); + switchInt(move _3) -> [0: bb2, 1: bb3, otherwise: bb5]; + } + + bb2: { + _4 = copy ((_2 as Continue).0: u32); + _5 = Not(copy _4); + _0 = as Try>::from_output(move _5) -> [return: bb4, unwind unreachable]; + } + + bb3: { + _0 = as FromResidual>>::from_residual(const Option::::None) -> [return: bb4, unwind unreachable]; + } + + bb4: { + return; + } + + bb5: { + unreachable; + } +} diff --git a/tests/mir-opt/pre-codegen/option_bubble_debug.option_traits.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/option_bubble_debug.option_traits.PreCodegen.after.panic-unwind.mir new file mode 100644 index 000000000000..bda9e9d8e604 --- /dev/null +++ b/tests/mir-opt/pre-codegen/option_bubble_debug.option_traits.PreCodegen.after.panic-unwind.mir @@ -0,0 +1,47 @@ +// MIR for `option_traits` after PreCodegen + +fn option_traits(_1: Option) -> Option { + debug x => _1; + let mut _0: std::option::Option; + let mut _2: std::ops::ControlFlow, u32>; + let mut _3: isize; + let _4: u32; + let mut _5: u32; + scope 1 { + debug residual => const Option::::None; + scope 2 { + } + } + scope 3 { + debug val => _4; + scope 4 { + } + } + + bb0: { + _2 = as Try>::branch(copy _1) -> [return: bb1, unwind continue]; + } + + bb1: { + _3 = discriminant(_2); + switchInt(move _3) -> [0: bb2, 1: bb3, otherwise: bb5]; + } + + bb2: { + _4 = copy ((_2 as Continue).0: u32); + _5 = Not(copy _4); + _0 = as Try>::from_output(move _5) -> [return: bb4, unwind continue]; + } + + bb3: { + _0 = as FromResidual>>::from_residual(const Option::::None) -> [return: bb4, unwind continue]; + } + + bb4: { + return; + } + + bb5: { + unreachable; + } +} diff --git a/tests/mir-opt/pre-codegen/option_bubble_debug.rs b/tests/mir-opt/pre-codegen/option_bubble_debug.rs new file mode 100644 index 000000000000..b9bf78a1d6ec --- /dev/null +++ b/tests/mir-opt/pre-codegen/option_bubble_debug.rs @@ -0,0 +1,29 @@ +//@ compile-flags: -Copt-level=0 -Zmir-opt-level=1 -Cdebuginfo=limited +//@ edition: 2024 +// EMIT_MIR_FOR_EACH_PANIC_STRATEGY + +#![crate_type = "lib"] +#![feature(try_blocks)] + +// EMIT_MIR option_bubble_debug.option_direct.PreCodegen.after.mir +pub fn option_direct(x: Option) -> Option { + // CHECK-LABEL: fn option_direct(_1: Option) -> Option + // CHECK: = discriminant(_1); + // CHECK: [[TEMP:_.+]] = Not({{.+}}); + // CHECK: _0 = Option::::Some(move [[TEMP]]); + + match x { + Some(x) => Some(!x), + None => None, + } +} + +// EMIT_MIR option_bubble_debug.option_traits.PreCodegen.after.mir +pub fn option_traits(x: Option) -> Option { + // CHECK-LABEL: fn option_traits(_1: Option) -> Option + // CHECK: = as Try>::branch(copy _1) + // CHECK: [[TEMP:_.+]] = Not({{.+}}); + // CHECK: _0 = as Try>::from_output(move [[TEMP]]) + + try { !(x?) } +} From 33706fc17f858caf42d36a9f67ef794269b6a83f Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 22:17:14 +1000 Subject: [PATCH 0416/1134] coverage: Include an `Instance` in `CovfunRecord` for debug messages --- .../rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs index b704cf2b1cd4..44b6eb0e6890 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs @@ -27,6 +27,9 @@ use crate::llvm; /// the final record that will be embedded in the `__llvm_covfun` section. #[derive(Debug)] pub(crate) struct CovfunRecord<'tcx> { + /// Not used directly, but helpful in debug messages. + _instance: Instance<'tcx>, + mangled_function_name: &'tcx str, source_hash: u64, is_used: bool, @@ -55,6 +58,7 @@ pub(crate) fn prepare_covfun_record<'tcx>( let expressions = prepare_expressions(ids_info); let mut covfun = CovfunRecord { + _instance: instance, mangled_function_name: tcx.symbol_name(instance).name, source_hash: if is_used { fn_cov_info.function_source_hash } else { 0 }, is_used, @@ -106,7 +110,7 @@ fn fill_region_tables<'tcx>( // first mapping's span to determine the file. let source_map = tcx.sess.source_map(); let Some(first_span) = (try { fn_cov_info.mappings.first()?.span }) else { - debug_assert!(false, "function has no mappings: {:?}", covfun.mangled_function_name); + debug_assert!(false, "function has no mappings: {covfun:?}"); return; }; let source_file = source_map.lookup_source_file(first_span.lo()); @@ -184,6 +188,7 @@ pub(crate) fn generate_covfun_record<'tcx>( covfun: &CovfunRecord<'tcx>, ) { let &CovfunRecord { + _instance, mangled_function_name, source_hash, is_used, From 16843ce427965a39a5f226ce3057ba3c2f5ed23c Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 9 May 2025 21:27:27 +1000 Subject: [PATCH 0417/1134] coverage: Hoist `counter_for_bcb` out of its loop Having this helper function in the loop was confusing, because it doesn't rely on anything that changes between loop iterations. --- .../src/coverageinfo/mapgen/covfun.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs index 44b6eb0e6890..69dfe1e98db1 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs @@ -106,6 +106,16 @@ fn fill_region_tables<'tcx>( ids_info: &'tcx CoverageIdsInfo, covfun: &mut CovfunRecord<'tcx>, ) { + // If this function is unused, replace all counters with zero. + let counter_for_bcb = |bcb: BasicCoverageBlock| -> ffi::Counter { + let term = if covfun.is_used { + ids_info.term_for_bcb[bcb].expect("every BCB in a mapping was given a term") + } else { + CovTerm::Zero + }; + ffi::Counter::from_term(term) + }; + // Currently a function's mappings must all be in the same file, so use the // first mapping's span to determine the file. let source_map = tcx.sess.source_map(); @@ -137,16 +147,6 @@ fn fill_region_tables<'tcx>( // For each counter/region pair in this function+file, convert it to a // form suitable for FFI. for &Mapping { ref kind, span } in &fn_cov_info.mappings { - // If this function is unused, replace all counters with zero. - let counter_for_bcb = |bcb: BasicCoverageBlock| -> ffi::Counter { - let term = if covfun.is_used { - ids_info.term_for_bcb[bcb].expect("every BCB in a mapping was given a term") - } else { - CovTerm::Zero - }; - ffi::Counter::from_term(term) - }; - let Some(coords) = make_coords(span) else { continue }; let cov_span = coords.make_coverage_span(local_file_id); From 51e62a09a376e30838db0d8ade4e3e89508357e0 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 18:20:56 +1000 Subject: [PATCH 0418/1134] coverage: Remove `-Zcoverage-options=no-mir-spans` This flag turned out to be less useful than anticipated, and interferes with work towards expansion support. --- compiler/rustc_interface/src/tests.rs | 4 +- .../src/coverage/mappings.rs | 6 +- compiler/rustc_session/src/config.rs | 8 -- compiler/rustc_session/src/options.rs | 4 +- compiler/rustc_session/src/session.rs | 5 -- tests/coverage/branch/no-mir-spans.cov-map | 63 --------------- tests/coverage/branch/no-mir-spans.coverage | 77 ------------------- tests/coverage/branch/no-mir-spans.rs | 62 --------------- .../coverage-options.bad.stderr | 2 +- 9 files changed, 5 insertions(+), 226 deletions(-) delete mode 100644 tests/coverage/branch/no-mir-spans.cov-map delete mode 100644 tests/coverage/branch/no-mir-spans.coverage delete mode 100644 tests/coverage/branch/no-mir-spans.rs diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 8771bb440504..86faab62d03a 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -778,8 +778,8 @@ fn test_unstable_options_tracking_hash() { coverage_options, CoverageOptions { level: CoverageLevel::Mcdc, - no_mir_spans: true, - discard_all_spans_in_codegen: true + // (don't collapse test-only options onto the same line) + discard_all_spans_in_codegen: true, } ); tracked!(crate_attr, vec!["abc".to_string()]); diff --git a/compiler/rustc_mir_transform/src/coverage/mappings.rs b/compiler/rustc_mir_transform/src/coverage/mappings.rs index b4b4d0416fb9..c79b76d90f29 100644 --- a/compiler/rustc_mir_transform/src/coverage/mappings.rs +++ b/compiler/rustc_mir_transform/src/coverage/mappings.rs @@ -82,15 +82,11 @@ pub(super) fn extract_all_mapping_info_from_mir<'tcx>( let mut mcdc_degraded_branches = vec![]; let mut mcdc_mappings = vec![]; - if hir_info.is_async_fn || tcx.sess.coverage_no_mir_spans() { + if hir_info.is_async_fn { // An async function desugars into a function that returns a future, // with the user code wrapped in a closure. Any spans in the desugared // outer function will be unhelpful, so just keep the signature span // and ignore all of the spans in the MIR body. - // - // When debugging flag `-Zcoverage-options=no-mir-spans` is set, we need - // to give the same treatment to _all_ functions, because `llvm-cov` - // seems to ignore functions that don't have any ordinary code spans. if let Some(span) = hir_info.fn_sig_span { code_mappings.push(CodeMapping { span, bcb: START_BCB }); } diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 8f624e0fb2fc..e82f4527c6cd 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -182,14 +182,6 @@ pub enum InstrumentCoverage { pub struct CoverageOptions { pub level: CoverageLevel, - /// `-Zcoverage-options=no-mir-spans`: Don't extract block coverage spans - /// from MIR statements/terminators, making it easier to inspect/debug - /// branch and MC/DC coverage mappings. - /// - /// For internal debugging only. If other code changes would make it hard - /// to keep supporting this flag, remove it. - pub no_mir_spans: bool, - /// `-Zcoverage-options=discard-all-spans-in-codegen`: During codegen, /// discard all coverage spans as though they were invalid. Needed by /// regression tests for #133606, because we don't have an easy way to diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 44b35e8921ec..880b08d44441 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -755,8 +755,7 @@ mod desc { pub(crate) const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavorCli::one_of(); pub(crate) const parse_dump_mono_stats: &str = "`markdown` (default) or `json`"; pub(crate) const parse_instrument_coverage: &str = parse_bool; - pub(crate) const parse_coverage_options: &str = - "`block` | `branch` | `condition` | `mcdc` | `no-mir-spans`"; + pub(crate) const parse_coverage_options: &str = "`block` | `branch` | `condition` | `mcdc`"; pub(crate) const parse_instrument_xray: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc), or a comma separated list of settings: `always` or `never` (mutually exclusive), `ignore-loops`, `instruction-threshold=N`, `skip-entry`, `skip-exit`"; pub(crate) const parse_unpretty: &str = "`string` or `string=string`"; pub(crate) const parse_treat_err_as_bug: &str = "either no value or a non-negative number"; @@ -1460,7 +1459,6 @@ pub mod parse { "branch" => slot.level = CoverageLevel::Branch, "condition" => slot.level = CoverageLevel::Condition, "mcdc" => slot.level = CoverageLevel::Mcdc, - "no-mir-spans" => slot.no_mir_spans = true, "discard-all-spans-in-codegen" => slot.discard_all_spans_in_codegen = true, _ => return false, } diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index e7097ec83275..c311a726aa7d 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -359,11 +359,6 @@ impl Session { && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Mcdc } - /// True if `-Zcoverage-options=no-mir-spans` was passed. - pub fn coverage_no_mir_spans(&self) -> bool { - self.opts.unstable_opts.coverage_options.no_mir_spans - } - /// True if `-Zcoverage-options=discard-all-spans-in-codegen` was passed. pub fn coverage_discard_all_spans_in_codegen(&self) -> bool { self.opts.unstable_opts.coverage_options.discard_all_spans_in_codegen diff --git a/tests/coverage/branch/no-mir-spans.cov-map b/tests/coverage/branch/no-mir-spans.cov-map deleted file mode 100644 index 4f893cba1f81..000000000000 --- a/tests/coverage/branch/no-mir-spans.cov-map +++ /dev/null @@ -1,63 +0,0 @@ -Function name: no_mir_spans::while_cond -Raw bytes (18): 0x[01, 01, 01, 05, 01, 02, 01, 10, 01, 00, 10, 20, 02, 01, 04, 0b, 00, 10] -Number of files: 1 -- file 0 => $DIR/no-mir-spans.rs -Number of expressions: 1 -- expression 0 operands: lhs = Counter(1), rhs = Counter(0) -Number of file 0 mappings: 2 -- Code(Counter(0)) at (prev + 16, 1) to (start + 0, 16) -- Branch { true: Expression(0, Sub), false: Counter(0) } at (prev + 4, 11) to (start + 0, 16) - true = (c1 - c0) - false = c0 -Highest counter ID seen: c0 - -Function name: no_mir_spans::while_cond_not -Raw bytes (18): 0x[01, 01, 01, 05, 01, 02, 01, 19, 01, 00, 14, 20, 02, 01, 04, 0b, 00, 14] -Number of files: 1 -- file 0 => $DIR/no-mir-spans.rs -Number of expressions: 1 -- expression 0 operands: lhs = Counter(1), rhs = Counter(0) -Number of file 0 mappings: 2 -- Code(Counter(0)) at (prev + 25, 1) to (start + 0, 20) -- Branch { true: Expression(0, Sub), false: Counter(0) } at (prev + 4, 11) to (start + 0, 20) - true = (c1 - c0) - false = c0 -Highest counter ID seen: c0 - -Function name: no_mir_spans::while_op_and -Raw bytes (31): 0x[01, 01, 04, 09, 05, 09, 01, 0f, 09, 01, 05, 03, 01, 22, 01, 00, 12, 20, 05, 02, 05, 0b, 00, 10, 20, 06, 0a, 00, 14, 00, 19] -Number of files: 1 -- file 0 => $DIR/no-mir-spans.rs -Number of expressions: 4 -- expression 0 operands: lhs = Counter(2), rhs = Counter(1) -- expression 1 operands: lhs = Counter(2), rhs = Counter(0) -- expression 2 operands: lhs = Expression(3, Add), rhs = Counter(2) -- expression 3 operands: lhs = Counter(0), rhs = Counter(1) -Number of file 0 mappings: 3 -- Code(Counter(0)) at (prev + 34, 1) to (start + 0, 18) -- Branch { true: Counter(1), false: Expression(0, Sub) } at (prev + 5, 11) to (start + 0, 16) - true = c1 - false = (c2 - c1) -- Branch { true: Expression(1, Sub), false: Expression(2, Sub) } at (prev + 0, 20) to (start + 0, 25) - true = (c2 - c0) - false = ((c0 + c1) - c2) -Highest counter ID seen: c1 - -Function name: no_mir_spans::while_op_or -Raw bytes (29): 0x[01, 01, 03, 09, 05, 09, 0b, 01, 05, 03, 01, 2d, 01, 00, 11, 20, 05, 02, 05, 0b, 00, 10, 20, 06, 01, 00, 14, 00, 19] -Number of files: 1 -- file 0 => $DIR/no-mir-spans.rs -Number of expressions: 3 -- expression 0 operands: lhs = Counter(2), rhs = Counter(1) -- expression 1 operands: lhs = Counter(2), rhs = Expression(2, Add) -- expression 2 operands: lhs = Counter(0), rhs = Counter(1) -Number of file 0 mappings: 3 -- Code(Counter(0)) at (prev + 45, 1) to (start + 0, 17) -- Branch { true: Counter(1), false: Expression(0, Sub) } at (prev + 5, 11) to (start + 0, 16) - true = c1 - false = (c2 - c1) -- Branch { true: Expression(1, Sub), false: Counter(0) } at (prev + 0, 20) to (start + 0, 25) - true = (c2 - (c0 + c1)) - false = c0 -Highest counter ID seen: c1 - diff --git a/tests/coverage/branch/no-mir-spans.coverage b/tests/coverage/branch/no-mir-spans.coverage deleted file mode 100644 index 2cae98ed3ff4..000000000000 --- a/tests/coverage/branch/no-mir-spans.coverage +++ /dev/null @@ -1,77 +0,0 @@ - LL| |#![feature(coverage_attribute)] - LL| |//@ edition: 2021 - LL| |//@ compile-flags: -Zcoverage-options=branch,no-mir-spans - LL| |//@ llvm-cov-flags: --show-branches=count - LL| | - LL| |// Tests the behaviour of the `-Zcoverage-options=no-mir-spans` debugging flag. - LL| |// The actual code below is just some non-trivial code copied from another test - LL| |// (`while.rs`), and has no particular significance. - LL| | - LL| |macro_rules! no_merge { - LL| | () => { - LL| | for _ in 0..1 {} - LL| | }; - LL| |} - LL| | - LL| 1|fn while_cond() { - LL| | no_merge!(); - LL| | - LL| | let mut a = 8; - LL| | while a > 0 { - ------------------ - | Branch (LL:11): [True: 8, False: 1] - ------------------ - LL| | a -= 1; - LL| | } - LL| |} - LL| | - LL| 1|fn while_cond_not() { - LL| | no_merge!(); - LL| | - LL| | let mut a = 8; - LL| | while !(a == 0) { - ------------------ - | Branch (LL:11): [True: 8, False: 1] - ------------------ - LL| | a -= 1; - LL| | } - LL| |} - LL| | - LL| 1|fn while_op_and() { - LL| | no_merge!(); - LL| | - LL| | let mut a = 8; - LL| | let mut b = 4; - LL| | while a > 0 && b > 0 { - ------------------ - | Branch (LL:11): [True: 5, False: 0] - | Branch (LL:20): [True: 4, False: 1] - ------------------ - LL| | a -= 1; - LL| | b -= 1; - LL| | } - LL| |} - LL| | - LL| 1|fn while_op_or() { - LL| | no_merge!(); - LL| | - LL| | let mut a = 4; - LL| | let mut b = 8; - LL| | while a > 0 || b > 0 { - ------------------ - | Branch (LL:11): [True: 4, False: 5] - | Branch (LL:20): [True: 4, False: 1] - ------------------ - LL| | a -= 1; - LL| | b -= 1; - LL| | } - LL| |} - LL| | - LL| |#[coverage(off)] - LL| |fn main() { - LL| | while_cond(); - LL| | while_cond_not(); - LL| | while_op_and(); - LL| | while_op_or(); - LL| |} - diff --git a/tests/coverage/branch/no-mir-spans.rs b/tests/coverage/branch/no-mir-spans.rs deleted file mode 100644 index acb268f2d455..000000000000 --- a/tests/coverage/branch/no-mir-spans.rs +++ /dev/null @@ -1,62 +0,0 @@ -#![feature(coverage_attribute)] -//@ edition: 2021 -//@ compile-flags: -Zcoverage-options=branch,no-mir-spans -//@ llvm-cov-flags: --show-branches=count - -// Tests the behaviour of the `-Zcoverage-options=no-mir-spans` debugging flag. -// The actual code below is just some non-trivial code copied from another test -// (`while.rs`), and has no particular significance. - -macro_rules! no_merge { - () => { - for _ in 0..1 {} - }; -} - -fn while_cond() { - no_merge!(); - - let mut a = 8; - while a > 0 { - a -= 1; - } -} - -fn while_cond_not() { - no_merge!(); - - let mut a = 8; - while !(a == 0) { - a -= 1; - } -} - -fn while_op_and() { - no_merge!(); - - let mut a = 8; - let mut b = 4; - while a > 0 && b > 0 { - a -= 1; - b -= 1; - } -} - -fn while_op_or() { - no_merge!(); - - let mut a = 4; - let mut b = 8; - while a > 0 || b > 0 { - a -= 1; - b -= 1; - } -} - -#[coverage(off)] -fn main() { - while_cond(); - while_cond_not(); - while_op_and(); - while_op_or(); -} diff --git a/tests/ui/instrument-coverage/coverage-options.bad.stderr b/tests/ui/instrument-coverage/coverage-options.bad.stderr index 1a6b30dc8324..4a272cf97fb0 100644 --- a/tests/ui/instrument-coverage/coverage-options.bad.stderr +++ b/tests/ui/instrument-coverage/coverage-options.bad.stderr @@ -1,2 +1,2 @@ -error: incorrect value `bad` for unstable option `coverage-options` - `block` | `branch` | `condition` | `mcdc` | `no-mir-spans` was expected +error: incorrect value `bad` for unstable option `coverage-options` - `block` | `branch` | `condition` | `mcdc` was expected From fb39d3ed880d7f9f2f1ef67e0ddd0d0b8af9e5ae Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 18:28:03 +1000 Subject: [PATCH 0419/1134] coverage: Push async special case down into `extract_refined_covspans` --- .../rustc_mir_transform/src/coverage/mappings.rs | 16 +++------------- .../rustc_mir_transform/src/coverage/spans.rs | 14 +++++++++++++- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_mir_transform/src/coverage/mappings.rs b/compiler/rustc_mir_transform/src/coverage/mappings.rs index c79b76d90f29..b0e24cf2bdb8 100644 --- a/compiler/rustc_mir_transform/src/coverage/mappings.rs +++ b/compiler/rustc_mir_transform/src/coverage/mappings.rs @@ -10,7 +10,7 @@ use rustc_middle::ty::TyCtxt; use rustc_span::Span; use crate::coverage::ExtractedHirInfo; -use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph, START_BCB}; +use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph}; use crate::coverage::spans::extract_refined_covspans; use crate::coverage::unexpand::unexpand_into_body_span; use crate::errors::MCDCExceedsTestVectorLimit; @@ -82,18 +82,8 @@ pub(super) fn extract_all_mapping_info_from_mir<'tcx>( let mut mcdc_degraded_branches = vec![]; let mut mcdc_mappings = vec![]; - if hir_info.is_async_fn { - // An async function desugars into a function that returns a future, - // with the user code wrapped in a closure. Any spans in the desugared - // outer function will be unhelpful, so just keep the signature span - // and ignore all of the spans in the MIR body. - if let Some(span) = hir_info.fn_sig_span { - code_mappings.push(CodeMapping { span, bcb: START_BCB }); - } - } else { - // Extract coverage spans from MIR statements/terminators as normal. - extract_refined_covspans(tcx, mir_body, hir_info, graph, &mut code_mappings); - } + // Extract ordinary code mappings from MIR statement/terminator spans. + extract_refined_covspans(tcx, mir_body, hir_info, graph, &mut code_mappings); branch_pairs.extend(extract_branch_pairs(mir_body, hir_info, graph)); diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index ddeae093df5b..0ee42abb1956 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -1,5 +1,6 @@ use rustc_data_structures::fx::FxHashSet; use rustc_middle::mir; +use rustc_middle::mir::coverage::START_BCB; use rustc_middle::ty::TyCtxt; use rustc_span::source_map::SourceMap; use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span}; @@ -16,8 +17,19 @@ pub(super) fn extract_refined_covspans<'tcx>( mir_body: &mir::Body<'tcx>, hir_info: &ExtractedHirInfo, graph: &CoverageGraph, - code_mappings: &mut impl Extend, + code_mappings: &mut Vec, ) { + if hir_info.is_async_fn { + // An async function desugars into a function that returns a future, + // with the user code wrapped in a closure. Any spans in the desugared + // outer function will be unhelpful, so just keep the signature span + // and ignore all of the spans in the MIR body. + if let Some(span) = hir_info.fn_sig_span { + code_mappings.push(mappings::CodeMapping { span, bcb: START_BCB }); + } + return; + } + let &ExtractedHirInfo { body_span, .. } = hir_info; let raw_spans = from_mir::extract_raw_spans_from_mir(mir_body, graph); From f496e83fe9a12cbaec6a61da83ba32159a87afde Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 2 Aug 2025 18:41:04 +1000 Subject: [PATCH 0420/1134] coverage: Simplify access to debug/testing `-Zcoverage-options` flags --- .../src/coverageinfo/mapgen/covfun.rs | 2 +- compiler/rustc_session/src/config.rs | 1 + compiler/rustc_session/src/session.rs | 12 +++++++----- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs index 69dfe1e98db1..fd1e7f7f160a 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs @@ -131,7 +131,7 @@ fn fill_region_tables<'tcx>( // codegen needs to handle that gracefully to avoid #133606. // It's hard for tests to trigger this organically, so instead we set // `-Zcoverage-options=discard-all-spans-in-codegen` to force it to occur. - let discard_all = tcx.sess.coverage_discard_all_spans_in_codegen(); + let discard_all = tcx.sess.coverage_options().discard_all_spans_in_codegen; let make_coords = |span: Span| { if discard_all { None } else { spans::make_coords(source_map, &source_file, span) } }; diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index e82f4527c6cd..cfeadf3c7595 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -182,6 +182,7 @@ pub enum InstrumentCoverage { pub struct CoverageOptions { pub level: CoverageLevel, + /// **(internal test-only flag)** /// `-Zcoverage-options=discard-all-spans-in-codegen`: During codegen, /// discard all coverage spans as though they were invalid. Needed by /// regression tests for #133606, because we don't have an easy way to diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index c311a726aa7d..b94636fea94e 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -39,8 +39,8 @@ use rustc_target::spec::{ use crate::code_stats::CodeStats; pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo}; use crate::config::{ - self, CoverageLevel, CrateType, DebugInfo, ErrorOutputType, FunctionReturn, Input, - InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents, + self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn, + Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents, SwitchWithOptPath, }; use crate::filesearch::FileSearch; @@ -359,9 +359,11 @@ impl Session { && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Mcdc } - /// True if `-Zcoverage-options=discard-all-spans-in-codegen` was passed. - pub fn coverage_discard_all_spans_in_codegen(&self) -> bool { - self.opts.unstable_opts.coverage_options.discard_all_spans_in_codegen + /// Provides direct access to the `CoverageOptions` struct, so that + /// individual flags for debugging/testing coverage instrumetation don't + /// need separate accessors. + pub fn coverage_options(&self) -> &CoverageOptions { + &self.opts.unstable_opts.coverage_options } pub fn is_sanitizer_cfi_enabled(&self) -> bool { From b37c214ec2bbb7609eb4b963bb2b0da160fef57f Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 3 Aug 2025 14:35:17 +1000 Subject: [PATCH 0421/1134] coverage: Represent `CovmapVersion` as an enum Using an enum here was historically not worth the extra hassle, but now we can lean on `#[derive(TryFromU32)]` to hide most of the boilerplate. --- .../src/coverageinfo/mapgen.rs | 47 +++++++++++++------ 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index 8c9dfcfd18c2..d1cb95507d91 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -1,3 +1,4 @@ +use std::assert_matches::assert_matches; use std::sync::Arc; use itertools::Itertools; @@ -5,6 +6,7 @@ use rustc_abi::Align; use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, ConstCodegenMethods}; use rustc_data_structures::fx::FxIndexMap; use rustc_index::IndexVec; +use rustc_macros::TryFromU32; use rustc_middle::ty::TyCtxt; use rustc_session::RemapFileNameExt; use rustc_session::config::RemapPathScopeComponents; @@ -20,6 +22,23 @@ mod covfun; mod spans; mod unused; +/// Version number that will be included the `__llvm_covmap` section header. +/// Corresponds to LLVM's `llvm::coverage::CovMapVersion` (in `CoverageMapping.h`), +/// or at least the subset that we know and care about. +/// +/// Note that version `n` is encoded as `(n-1)`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, TryFromU32)] +enum CovmapVersion { + /// Used by LLVM 18 onwards. + Version7 = 6, +} + +impl CovmapVersion { + fn to_u32(self) -> u32 { + self as u32 + } +} + /// Generates and exports the coverage map, which is embedded in special /// linker sections in the final binary. /// @@ -29,19 +48,13 @@ pub(crate) fn finalize(cx: &mut CodegenCx<'_, '_>) { let tcx = cx.tcx; // Ensure that LLVM is using a version of the coverage mapping format that - // agrees with our Rust-side code. Expected versions (encoded as n-1) are: - // - `CovMapVersion::Version7` (6) used by LLVM 18-19 - let covmap_version = { - let llvm_covmap_version = llvm_cov::mapping_version(); - let expected_versions = 6..=6; - assert!( - expected_versions.contains(&llvm_covmap_version), - "Coverage mapping version exposed by `llvm-wrapper` is out of sync; \ - expected {expected_versions:?} but was {llvm_covmap_version}" - ); - // This is the version number that we will embed in the covmap section: - llvm_covmap_version - }; + // agrees with our Rust-side code. Expected versions are: + // - `Version7` (6) used by LLVM 18 onwards. + let covmap_version = + CovmapVersion::try_from(llvm_cov::mapping_version()).unwrap_or_else(|raw_version: u32| { + panic!("unknown coverage mapping version reported by `llvm-wrapper`: {raw_version}") + }); + assert_matches!(covmap_version, CovmapVersion::Version7); debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name()); @@ -201,7 +214,11 @@ impl VirtualFileMapping { /// Generates the contents of the covmap record for this CGU, which mostly /// consists of a header and a list of filenames. The record is then stored /// as a global variable in the `__llvm_covmap` section. -fn generate_covmap_record<'ll>(cx: &mut CodegenCx<'ll, '_>, version: u32, filenames_buffer: &[u8]) { +fn generate_covmap_record<'ll>( + cx: &mut CodegenCx<'ll, '_>, + version: CovmapVersion, + filenames_buffer: &[u8], +) { // A covmap record consists of four target-endian u32 values, followed by // the encoded filenames table. Two of the header fields are unused in // modern versions of the LLVM coverage mapping format, and are always 0. @@ -212,7 +229,7 @@ fn generate_covmap_record<'ll>(cx: &mut CodegenCx<'ll, '_>, version: u32, filena cx.const_u32(0), // (unused) cx.const_u32(filenames_buffer.len() as u32), cx.const_u32(0), // (unused) - cx.const_u32(version), + cx.const_u32(version.to_u32()), ], /* packed */ false, ); From b8d1af5e5633ff1ac1c9c9a3921af2d8e8620410 Mon Sep 17 00:00:00 2001 From: The rustc-josh-sync Cronjob Bot Date: Mon, 4 Aug 2025 04:24:59 +0000 Subject: [PATCH 0422/1134] Prepare for merging from rust-lang/rust This updates the rust-version file to 383b9c447b61641e1f1a3850253944a897a60827. --- src/doc/rustc-dev-guide/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/rust-version b/src/doc/rustc-dev-guide/rust-version index 1ced6098acf4..e9f1626f1fdd 100644 --- a/src/doc/rustc-dev-guide/rust-version +++ b/src/doc/rustc-dev-guide/rust-version @@ -1 +1 @@ -32e7a4b92b109c24e9822c862a7c74436b50e564 +383b9c447b61641e1f1a3850253944a897a60827 From 607ecca1fbe884a7d032ef1ec1d98853ce284a3d Mon Sep 17 00:00:00 2001 From: The Miri Cronjob Bot Date: Mon, 4 Aug 2025 05:09:06 +0000 Subject: [PATCH 0423/1134] Prepare for merging from rust-lang/rust This updates the rust-version file to 07b7dc90ee4df5815dbb91ef8e98cb93571230f5. --- src/tools/miri/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index bf69accaf063..8cf5873eab42 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -adcb3d3b4cd3b7c4cde642f3ed537037f293738e +07b7dc90ee4df5815dbb91ef8e98cb93571230f5 From 9b107bed9f2d2098dbbaade0ddbc363c651cd38b Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 27 Jul 2025 21:37:17 -0700 Subject: [PATCH 0424/1134] Add a mir-opt test for an unneeded drop_in_place --- .../mir-opt/remove_unneeded_drop_in_place.rs | 13 ++++++++++++ ...ce.slice_in_place.RemoveUnneededDrops.diff | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 tests/mir-opt/remove_unneeded_drop_in_place.rs create mode 100644 tests/mir-opt/remove_unneeded_drop_in_place.slice_in_place.RemoveUnneededDrops.diff diff --git a/tests/mir-opt/remove_unneeded_drop_in_place.rs b/tests/mir-opt/remove_unneeded_drop_in_place.rs new file mode 100644 index 000000000000..7fb7b1e78de0 --- /dev/null +++ b/tests/mir-opt/remove_unneeded_drop_in_place.rs @@ -0,0 +1,13 @@ +//@ test-mir-pass: RemoveUnneededDrops +//@ needs-unwind + +// EMIT_MIR remove_unneeded_drop_in_place.slice_in_place.RemoveUnneededDrops.diff +unsafe fn slice_in_place(ptr: *mut [char]) { + std::ptr::drop_in_place(ptr) +} + +fn main() { + // CHECK-LABEL: fn main( + let mut a = ['o', 'k']; + unsafe { slice_in_place(&raw mut a) }; +} diff --git a/tests/mir-opt/remove_unneeded_drop_in_place.slice_in_place.RemoveUnneededDrops.diff b/tests/mir-opt/remove_unneeded_drop_in_place.slice_in_place.RemoveUnneededDrops.diff new file mode 100644 index 000000000000..4068e7940bc6 --- /dev/null +++ b/tests/mir-opt/remove_unneeded_drop_in_place.slice_in_place.RemoveUnneededDrops.diff @@ -0,0 +1,20 @@ +- // MIR for `slice_in_place` before RemoveUnneededDrops ++ // MIR for `slice_in_place` after RemoveUnneededDrops + + fn slice_in_place(_1: *mut [char]) -> () { + debug ptr => _1; + let mut _0: (); + let mut _2: *mut [char]; + + bb0: { + StorageLive(_2); + _2 = copy _1; + _0 = drop_in_place::<[char]>(move _2) -> [return: bb1, unwind continue]; + } + + bb1: { + StorageDead(_2); + return; + } + } + From 450040f2d39ae0f5ec7889d48d1a7aa4d2c08c5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 1 Aug 2025 14:58:06 +0200 Subject: [PATCH 0425/1134] Implement debugging output of the bootstrap Step graph into a DOT file --- src/bootstrap/src/bin/main.rs | 3 + src/bootstrap/src/core/builder/mod.rs | 25 ++- src/bootstrap/src/lib.rs | 12 +- src/bootstrap/src/utils/mod.rs | 3 + src/bootstrap/src/utils/step_graph.rs | 176 ++++++++++++++++++ .../bootstrapping/debugging-bootstrap.md | 6 + 6 files changed, 223 insertions(+), 2 deletions(-) create mode 100644 src/bootstrap/src/utils/step_graph.rs diff --git a/src/bootstrap/src/bin/main.rs b/src/bootstrap/src/bin/main.rs index 181d71f63c2f..cf24fedaebb1 100644 --- a/src/bootstrap/src/bin/main.rs +++ b/src/bootstrap/src/bin/main.rs @@ -159,6 +159,9 @@ fn main() { if is_bootstrap_profiling_enabled() { build.report_summary(start_time); } + + #[cfg(feature = "tracing")] + build.report_step_graph(); } fn check_version(config: &Config) -> Option { diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 96289a63785e..20f3fee1c6cb 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -77,7 +77,7 @@ impl Deref for Builder<'_> { /// type's [`Debug`] implementation. /// /// (Trying to debug-print `dyn Any` results in the unhelpful `"Any { .. }"`.) -trait AnyDebug: Any + Debug {} +pub trait AnyDebug: Any + Debug {} impl AnyDebug for T {} impl dyn AnyDebug { /// Equivalent to `::downcast_ref`. @@ -197,6 +197,14 @@ impl StepMetadata { // For everything else, a stage N things gets built by a stage N-1 compiler. .map(|compiler| if self.name == "std" { compiler.stage } else { compiler.stage + 1 })) } + + pub fn get_name(&self) -> &str { + &self.name + } + + pub fn get_target(&self) -> TargetSelection { + self.target + } } pub struct RunConfig<'a> { @@ -1657,9 +1665,24 @@ You have to build a stage1 compiler for `{}` first, and then use it to build a s if let Some(out) = self.cache.get(&step) { self.verbose_than(1, || println!("{}c {:?}", " ".repeat(stack.len()), step)); + #[cfg(feature = "tracing")] + { + if let Some(parent) = stack.last() { + let mut graph = self.build.step_graph.borrow_mut(); + graph.register_cached_step(&step, parent, self.config.dry_run()); + } + } return out; } self.verbose_than(1, || println!("{}> {:?}", " ".repeat(stack.len()), step)); + + #[cfg(feature = "tracing")] + { + let parent = stack.last(); + let mut graph = self.build.step_graph.borrow_mut(); + graph.register_step_execution(&step, parent, self.config.dry_run()); + } + stack.push(Box::new(step.clone())); } diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 011b52df97bb..e49513a21160 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -188,7 +188,6 @@ pub enum GitRepo { /// although most functions are implemented as free functions rather than /// methods specifically on this structure itself (to make it easier to /// organize). -#[derive(Clone)] pub struct Build { /// User-specified configuration from `bootstrap.toml`. config: Config, @@ -244,6 +243,9 @@ pub struct Build { #[cfg(feature = "build-metrics")] metrics: crate::utils::metrics::BuildMetrics, + + #[cfg(feature = "tracing")] + step_graph: std::cell::RefCell, } #[derive(Debug, Clone)] @@ -547,6 +549,9 @@ impl Build { #[cfg(feature = "build-metrics")] metrics: crate::utils::metrics::BuildMetrics::init(), + + #[cfg(feature = "tracing")] + step_graph: std::cell::RefCell::new(crate::utils::step_graph::StepGraph::default()), }; // If local-rust is the same major.minor as the current version, then force a @@ -2024,6 +2029,11 @@ to download LLVM rather than building it. pub fn report_summary(&self, start_time: Instant) { self.config.exec_ctx.profiler().report_summary(start_time); } + + #[cfg(feature = "tracing")] + pub fn report_step_graph(self) { + self.step_graph.into_inner().store_to_dot_files(); + } } impl AsRef for Build { diff --git a/src/bootstrap/src/utils/mod.rs b/src/bootstrap/src/utils/mod.rs index 169fcec303e9..97d8d274e8fb 100644 --- a/src/bootstrap/src/utils/mod.rs +++ b/src/bootstrap/src/utils/mod.rs @@ -19,5 +19,8 @@ pub(crate) mod tracing; #[cfg(feature = "build-metrics")] pub(crate) mod metrics; +#[cfg(feature = "tracing")] +pub(crate) mod step_graph; + #[cfg(test)] pub(crate) mod tests; diff --git a/src/bootstrap/src/utils/step_graph.rs b/src/bootstrap/src/utils/step_graph.rs new file mode 100644 index 000000000000..b1db9e61fda7 --- /dev/null +++ b/src/bootstrap/src/utils/step_graph.rs @@ -0,0 +1,176 @@ +use std::collections::{HashMap, HashSet}; +use std::fmt::Debug; +use std::io::BufWriter; + +use crate::core::builder::{AnyDebug, Step}; + +/// Records the executed steps and their dependencies in a directed graph, +/// which can then be rendered into a DOT file for visualization. +/// +/// The graph visualizes the first execution of a step with a solid edge, +/// and cached executions of steps with a dashed edge. +/// If you only want to see first executions, you can modify the code in `DotGraph` to +/// always set `cached: false`. +#[derive(Default)] +pub struct StepGraph { + /// We essentially store one graph per dry run mode. + graphs: HashMap, +} + +impl StepGraph { + pub fn register_step_execution( + &mut self, + step: &S, + parent: Option<&Box>, + dry_run: bool, + ) { + let key = get_graph_key(dry_run); + let graph = self.graphs.entry(key.to_string()).or_insert_with(|| DotGraph::default()); + + // The debug output of the step sort of serves as the unique identifier of it. + // We use it to access the node ID of parents to generate edges. + // We could probably also use addresses on the heap from the `Box`, but this seems less + // magical. + let node_key = render_step(step); + + let label = if let Some(metadata) = step.metadata() { + format!( + "{}{} [{}]", + metadata.get_name(), + metadata.get_stage().map(|s| format!(" stage {s}")).unwrap_or_default(), + metadata.get_target() + ) + } else { + let type_name = std::any::type_name::(); + type_name + .strip_prefix("bootstrap::core::") + .unwrap_or(type_name) + .strip_prefix("build_steps::") + .unwrap_or(type_name) + .to_string() + }; + + let node = Node { label, tooltip: node_key.clone() }; + let node_handle = graph.add_node(node_key, node); + + if let Some(parent) = parent { + let parent_key = render_step(parent); + if let Some(src_node_handle) = graph.get_handle_by_key(&parent_key) { + graph.add_edge(src_node_handle, node_handle); + } + } + } + + pub fn register_cached_step( + &mut self, + step: &S, + parent: &Box, + dry_run: bool, + ) { + let key = get_graph_key(dry_run); + let graph = self.graphs.get_mut(key).unwrap(); + + let node_key = render_step(step); + let parent_key = render_step(parent); + + if let Some(src_node_handle) = graph.get_handle_by_key(&parent_key) { + if let Some(dst_node_handle) = graph.get_handle_by_key(&node_key) { + graph.add_cached_edge(src_node_handle, dst_node_handle); + } + } + } + + pub fn store_to_dot_files(self) { + for (key, graph) in self.graphs.into_iter() { + let filename = format!("bootstrap-steps{key}.dot"); + graph.render(&filename).unwrap(); + } + } +} + +fn get_graph_key(dry_run: bool) -> &'static str { + if dry_run { ".dryrun" } else { "" } +} + +struct Node { + label: String, + tooltip: String, +} + +#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +struct NodeHandle(usize); + +#[derive(PartialEq, Eq, Hash, PartialOrd, Ord)] +struct Edge { + src: NodeHandle, + dst: NodeHandle, + cached: bool, +} + +// We could use a library for this, but they either: +// - require lifetimes, which gets annoying (dot_writer) +// - don't support tooltips (dot_graph) +// - have a lot of dependencies (graphviz_rust) +// - only have SVG export (layout-rs) +// - use a builder pattern that is very annoying to use here (tabbycat) +#[derive(Default)] +struct DotGraph { + nodes: Vec, + /// The `NodeHandle` represents an index within `self.nodes` + edges: HashSet, + key_to_index: HashMap, +} + +impl DotGraph { + fn add_node(&mut self, key: String, node: Node) -> NodeHandle { + let handle = NodeHandle(self.nodes.len()); + self.nodes.push(node); + self.key_to_index.insert(key, handle); + handle + } + + fn add_edge(&mut self, src: NodeHandle, dst: NodeHandle) { + self.edges.insert(Edge { src, dst, cached: false }); + } + + fn add_cached_edge(&mut self, src: NodeHandle, dst: NodeHandle) { + self.edges.insert(Edge { src, dst, cached: true }); + } + + fn get_handle_by_key(&self, key: &str) -> Option { + self.key_to_index.get(key).copied() + } + + fn render(&self, path: &str) -> std::io::Result<()> { + use std::io::Write; + + let mut file = BufWriter::new(std::fs::File::create(path)?); + writeln!(file, "digraph bootstrap_steps {{")?; + for (index, node) in self.nodes.iter().enumerate() { + writeln!( + file, + r#"{index} [label="{}", tooltip="{}"]"#, + escape(&node.label), + escape(&node.tooltip) + )?; + } + + let mut edges: Vec<&Edge> = self.edges.iter().collect(); + edges.sort(); + for edge in edges { + let style = if edge.cached { "dashed" } else { "solid" }; + writeln!(file, r#"{} -> {} [style="{style}"]"#, edge.src.0, edge.dst.0)?; + } + + writeln!(file, "}}") + } +} + +fn render_step(step: &dyn Debug) -> String { + format!("{step:?}") +} + +/// Normalizes the string so that it can be rendered into a DOT file. +fn escape(input: &str) -> String { + input.replace("\"", "\\\"") +} diff --git a/src/doc/rustc-dev-guide/src/building/bootstrapping/debugging-bootstrap.md b/src/doc/rustc-dev-guide/src/building/bootstrapping/debugging-bootstrap.md index c9c0d64a604e..9c5ebbd36c46 100644 --- a/src/doc/rustc-dev-guide/src/building/bootstrapping/debugging-bootstrap.md +++ b/src/doc/rustc-dev-guide/src/building/bootstrapping/debugging-bootstrap.md @@ -123,6 +123,12 @@ if [#96176][cleanup-compiler-for] is resolved. [cleanup-compiler-for]: https://github.com/rust-lang/rust/issues/96176 +### Rendering step graph + +When you run bootstrap with the `BOOTSTRAP_TRACING` environment variable configured, bootstrap will automatically output a DOT file that shows all executed steps and their dependencies. The files will have a prefix `bootstrap-steps`. You can use e.g. `xdot` to visualize the file or e.g. `dot -Tsvg` to convert the DOT file to a SVG file. + +A separate DOT file will be outputted for dry-run and non-dry-run execution. + ### Using `tracing` in bootstrap Both `tracing::*` macros and the `tracing::instrument` proc-macro attribute need to be gated behind `tracing` feature. Examples: From 2f4b40fe4ebd61943ed10f25e6406be6ad68f18e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 1 Aug 2025 15:14:58 +0200 Subject: [PATCH 0426/1134] Do not render both cached and uncached edge between two steps --- src/bootstrap/src/utils/step_graph.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/utils/step_graph.rs b/src/bootstrap/src/utils/step_graph.rs index b1db9e61fda7..c45825a42223 100644 --- a/src/bootstrap/src/utils/step_graph.rs +++ b/src/bootstrap/src/utils/step_graph.rs @@ -100,10 +100,12 @@ struct Node { #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] struct NodeHandle(usize); +/// Represents a dependency between two bootstrap steps. #[derive(PartialEq, Eq, Hash, PartialOrd, Ord)] struct Edge { src: NodeHandle, dst: NodeHandle, + // Was the corresponding execution of a step cached, or was the step actually executed? cached: bool, } @@ -134,7 +136,11 @@ impl DotGraph { } fn add_cached_edge(&mut self, src: NodeHandle, dst: NodeHandle) { - self.edges.insert(Edge { src, dst, cached: true }); + // There's no point in rendering both cached and uncached edge + let uncached = Edge { src, dst, cached: false }; + if !self.edges.contains(&uncached) { + self.edges.insert(Edge { src, dst, cached: true }); + } } fn get_handle_by_key(&self, key: &str) -> Option { From 4f94bbf13d21c6707510ca4faa2cf90683fd1369 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Sat, 2 Aug 2025 10:49:47 +0200 Subject: [PATCH 0427/1134] drive-by cleanup: fix outdated documentation --- compiler/rustc_middle/src/ty/sty.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 806079788615..72474a605669 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1456,7 +1456,7 @@ impl<'tcx> Ty<'tcx> { } } - /// Returns the type and mutability of `*ty`. + /// Returns the type of `*ty`. /// /// The parameter `explicit` indicates if this is an *explicit* dereference. /// Some types -- notably raw ptrs -- can only be dereferenced explicitly. From 8b65f3d0e8991fb68b843968229a84e8e8c09e75 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Sat, 2 Aug 2025 10:49:47 +0200 Subject: [PATCH 0428/1134] properly reject tail calls to `&FnPtr` or `&FnDef` --- .../rustc_mir_build/src/check_tail_calls.rs | 51 ++++++++++++++++++- .../explicit-tail-calls/callee_is_ref.fixed | 26 ++++++++++ tests/ui/explicit-tail-calls/callee_is_ref.rs | 26 ++++++++++ .../explicit-tail-calls/callee_is_ref.stderr | 38 ++++++++++++++ .../ui/explicit-tail-calls/callee_is_weird.rs | 29 +++++++++++ .../callee_is_weird.stderr | 26 ++++++++++ 6 files changed, 194 insertions(+), 2 deletions(-) create mode 100644 tests/ui/explicit-tail-calls/callee_is_ref.fixed create mode 100644 tests/ui/explicit-tail-calls/callee_is_ref.rs create mode 100644 tests/ui/explicit-tail-calls/callee_is_ref.stderr create mode 100644 tests/ui/explicit-tail-calls/callee_is_weird.rs create mode 100644 tests/ui/explicit-tail-calls/callee_is_weird.stderr diff --git a/compiler/rustc_mir_build/src/check_tail_calls.rs b/compiler/rustc_mir_build/src/check_tail_calls.rs index 6ed100899d8c..b4c8b20e50f9 100644 --- a/compiler/rustc_mir_build/src/check_tail_calls.rs +++ b/compiler/rustc_mir_build/src/check_tail_calls.rs @@ -95,9 +95,15 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { // So we have to check for them in this weird way... let parent = self.tcx.parent(did); if self.tcx.fn_trait_kind_from_def_id(parent).is_some() - && args.first().and_then(|arg| arg.as_type()).is_some_and(Ty::is_closure) + && let Some(this) = args.first() + && let Some(this) = this.as_type() { - self.report_calling_closure(&self.thir[fun], args[1].as_type().unwrap(), expr); + if this.is_closure() { + self.report_calling_closure(&self.thir[fun], args[1].as_type().unwrap(), expr); + } else { + // This can happen when tail calling `Box` that wraps a function + self.report_nonfn_callee(fn_span, self.thir[fun].span, this); + } // Tail calling is likely to cause unrelated errors (ABI, argument mismatches), // skip them, producing an error about calling a closure is enough. @@ -109,6 +115,13 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { } } + let (ty::FnDef(..) | ty::FnPtr(..)) = ty.kind() else { + self.report_nonfn_callee(fn_span, self.thir[fun].span, ty); + + // `fn_sig` below panics otherwise + return; + }; + // Erase regions since tail calls don't care about lifetimes let callee_sig = self.tcx.normalize_erasing_late_bound_regions(self.typing_env, ty.fn_sig(self.tcx)); @@ -294,6 +307,40 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { self.found_errors = Err(err); } + fn report_nonfn_callee(&mut self, call_sp: Span, fun_sp: Span, ty: Ty<'_>) { + let mut err = self + .tcx + .dcx() + .struct_span_err( + call_sp, + "tail calls can only be performed with function definitions or pointers", + ) + .with_note(format!("callee has type `{ty}`")); + + let mut ty = ty; + let mut refs = 0; + while ty.is_box() || ty.is_ref() { + ty = ty.builtin_deref(false).unwrap(); + refs += 1; + } + + if refs > 0 && ty.is_fn() { + let thing = if ty.is_fn_ptr() { "pointer" } else { "definition" }; + + let derefs = + std::iter::once('(').chain(std::iter::repeat_n('*', refs)).collect::(); + + err.multipart_suggestion( + format!("consider dereferencing the expression to get a function {thing}"), + vec![(fun_sp.shrink_to_lo(), derefs), (fun_sp.shrink_to_hi(), ")".to_owned())], + Applicability::MachineApplicable, + ); + } + + let err = err.emit(); + self.found_errors = Err(err); + } + fn report_abi_mismatch(&mut self, sp: Span, caller_abi: ExternAbi, callee_abi: ExternAbi) { let err = self .tcx diff --git a/tests/ui/explicit-tail-calls/callee_is_ref.fixed b/tests/ui/explicit-tail-calls/callee_is_ref.fixed new file mode 100644 index 000000000000..7525e5c5df84 --- /dev/null +++ b/tests/ui/explicit-tail-calls/callee_is_ref.fixed @@ -0,0 +1,26 @@ +//@ run-rustfix +#![feature(explicit_tail_calls)] +#![expect(incomplete_features)] + +fn f() {} + +fn g() { + become (*(&f))() //~ error: tail calls can only be performed with function definitions or pointers +} + +fn h() { + let table = [f as fn()]; + if let Some(fun) = table.get(0) { + become (*fun)(); //~ error: tail calls can only be performed with function definitions or pointers + } +} + +fn i() { + become (***Box::new(&mut &f))(); //~ error: tail calls can only be performed with function definitions or pointers +} + +fn main() { + g(); + h(); + i(); +} diff --git a/tests/ui/explicit-tail-calls/callee_is_ref.rs b/tests/ui/explicit-tail-calls/callee_is_ref.rs new file mode 100644 index 000000000000..36bf9efb9522 --- /dev/null +++ b/tests/ui/explicit-tail-calls/callee_is_ref.rs @@ -0,0 +1,26 @@ +//@ run-rustfix +#![feature(explicit_tail_calls)] +#![expect(incomplete_features)] + +fn f() {} + +fn g() { + become (&f)() //~ error: tail calls can only be performed with function definitions or pointers +} + +fn h() { + let table = [f as fn()]; + if let Some(fun) = table.get(0) { + become fun(); //~ error: tail calls can only be performed with function definitions or pointers + } +} + +fn i() { + become Box::new(&mut &f)(); //~ error: tail calls can only be performed with function definitions or pointers +} + +fn main() { + g(); + h(); + i(); +} diff --git a/tests/ui/explicit-tail-calls/callee_is_ref.stderr b/tests/ui/explicit-tail-calls/callee_is_ref.stderr new file mode 100644 index 000000000000..4a2ff465e682 --- /dev/null +++ b/tests/ui/explicit-tail-calls/callee_is_ref.stderr @@ -0,0 +1,38 @@ +error: tail calls can only be performed with function definitions or pointers + --> $DIR/callee_is_ref.rs:8:12 + | +LL | become (&f)() + | ^^^^^^ + | + = note: callee has type `&fn() {f}` +help: consider dereferencing the expression to get a function definition + | +LL | become (*(&f))() + | ++ + + +error: tail calls can only be performed with function definitions or pointers + --> $DIR/callee_is_ref.rs:14:16 + | +LL | become fun(); + | ^^^^^ + | + = note: callee has type `&fn()` +help: consider dereferencing the expression to get a function pointer + | +LL | become (*fun)(); + | ++ + + +error: tail calls can only be performed with function definitions or pointers + --> $DIR/callee_is_ref.rs:19:12 + | +LL | become Box::new(&mut &f)(); + | ^^^^^^^^^^^^^^^^^^^ + | + = note: callee has type `Box<&mut &fn() {f}>` +help: consider dereferencing the expression to get a function definition + | +LL | become (***Box::new(&mut &f))(); + | ++++ + + +error: aborting due to 3 previous errors + diff --git a/tests/ui/explicit-tail-calls/callee_is_weird.rs b/tests/ui/explicit-tail-calls/callee_is_weird.rs new file mode 100644 index 000000000000..b3ca878c232c --- /dev/null +++ b/tests/ui/explicit-tail-calls/callee_is_weird.rs @@ -0,0 +1,29 @@ +#![feature(explicit_tail_calls, exclusive_wrapper, fn_traits, unboxed_closures)] +#![expect(incomplete_features)] + +fn f() {} + +fn g() { + become std::sync::Exclusive::new(f)() //~ error: tail calls can only be performed with function definitions or pointers +} + +fn h() { + become (&mut &std::sync::Exclusive::new(f))() //~ error: tail calls can only be performed with function definitions or pointers +} + +fn i() { + struct J; + + impl FnOnce<()> for J { + type Output = (); + extern "rust-call" fn call_once(self, (): ()) -> Self::Output {} + } + + become J(); //~ error: tail calls can only be performed with function definitions or pointers +} + +fn main() { + g(); + h(); + i(); +} diff --git a/tests/ui/explicit-tail-calls/callee_is_weird.stderr b/tests/ui/explicit-tail-calls/callee_is_weird.stderr new file mode 100644 index 000000000000..a4e5a38ce332 --- /dev/null +++ b/tests/ui/explicit-tail-calls/callee_is_weird.stderr @@ -0,0 +1,26 @@ +error: tail calls can only be performed with function definitions or pointers + --> $DIR/callee_is_weird.rs:7:12 + | +LL | become std::sync::Exclusive::new(f)() + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: callee has type `Exclusive` + +error: tail calls can only be performed with function definitions or pointers + --> $DIR/callee_is_weird.rs:11:12 + | +LL | become (&mut &std::sync::Exclusive::new(f))() + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: callee has type `Exclusive` + +error: tail calls can only be performed with function definitions or pointers + --> $DIR/callee_is_weird.rs:22:12 + | +LL | become J(); + | ^^^ + | + = note: callee has type `J` + +error: aborting due to 3 previous errors + From e3ed3e0f1c8156b0958c7653f001a8d99d5990f6 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Mon, 4 Aug 2025 09:41:08 +0200 Subject: [PATCH 0429/1134] small refactor of `InterpResult` - don't need type alias to default type argument - `Residual` impl allows to use more std APIs (like `<[T; N]>::try_map`) --- compiler/rustc_middle/src/lib.rs | 1 + .../rustc_middle/src/mir/interpret/error.rs | 41 ++++++++++--------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index 803b645c8f76..e5cc23c213d2 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -57,6 +57,7 @@ #![feature(sized_hierarchy)] #![feature(try_blocks)] #![feature(try_trait_v2)] +#![feature(try_trait_v2_residual)] #![feature(try_trait_v2_yeet)] #![feature(type_alias_impl_trait)] #![feature(yeet_expr)] diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 3e895c6b2809..77427a12d118 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -793,36 +793,37 @@ impl Drop for Guard { /// We also make things panic if this type is ever implicitly dropped. #[derive(Debug)] #[must_use] -pub struct InterpResult_<'tcx, T> { +pub struct InterpResult<'tcx, T = ()> { res: Result>, guard: Guard, } -// Type alias to be able to set a default type argument. -pub type InterpResult<'tcx, T = ()> = InterpResult_<'tcx, T>; - -impl<'tcx, T> ops::Try for InterpResult_<'tcx, T> { +impl<'tcx, T> ops::Try for InterpResult<'tcx, T> { type Output = T; - type Residual = InterpResult_<'tcx, convert::Infallible>; + type Residual = InterpResult<'tcx, convert::Infallible>; #[inline] fn from_output(output: Self::Output) -> Self { - InterpResult_::new(Ok(output)) + InterpResult::new(Ok(output)) } #[inline] fn branch(self) -> ops::ControlFlow { match self.disarm() { Ok(v) => ops::ControlFlow::Continue(v), - Err(e) => ops::ControlFlow::Break(InterpResult_::new(Err(e))), + Err(e) => ops::ControlFlow::Break(InterpResult::new(Err(e))), } } } -impl<'tcx, T> ops::FromResidual for InterpResult_<'tcx, T> { +impl<'tcx, T> ops::Residual for InterpResult<'tcx, convert::Infallible> { + type TryType = InterpResult<'tcx, T>; +} + +impl<'tcx, T> ops::FromResidual for InterpResult<'tcx, T> { #[inline] #[track_caller] - fn from_residual(residual: InterpResult_<'tcx, convert::Infallible>) -> Self { + fn from_residual(residual: InterpResult<'tcx, convert::Infallible>) -> Self { match residual.disarm() { Err(e) => Self::new(Err(e)), } @@ -830,7 +831,7 @@ impl<'tcx, T> ops::FromResidual for InterpResult_<'tcx, T> { } // Allow `yeet`ing `InterpError` in functions returning `InterpResult_`. -impl<'tcx, T> ops::FromResidual>> for InterpResult_<'tcx, T> { +impl<'tcx, T> ops::FromResidual>> for InterpResult<'tcx, T> { #[inline] fn from_residual(ops::Yeet(e): ops::Yeet>) -> Self { Self::new(Err(e.into())) @@ -840,7 +841,7 @@ impl<'tcx, T> ops::FromResidual>> for InterpResu // Allow `?` on `Result<_, InterpError>` in functions returning `InterpResult_`. // This is useful e.g. for `option.ok_or_else(|| err_ub!(...))`. impl<'tcx, T, E: Into>> ops::FromResidual> - for InterpResult_<'tcx, T> + for InterpResult<'tcx, T> { #[inline] fn from_residual(residual: Result) -> Self { @@ -863,7 +864,7 @@ impl<'tcx, T, V: FromIterator> FromIterator> for Interp } } -impl<'tcx, T> InterpResult_<'tcx, T> { +impl<'tcx, T> InterpResult<'tcx, T> { #[inline(always)] fn new(res: Result>) -> Self { Self { res, guard: Guard } @@ -890,7 +891,7 @@ impl<'tcx, T> InterpResult_<'tcx, T> { #[inline] pub fn map(self, f: impl FnOnce(T) -> U) -> InterpResult<'tcx, U> { - InterpResult_::new(self.disarm().map(f)) + InterpResult::new(self.disarm().map(f)) } #[inline] @@ -898,7 +899,7 @@ impl<'tcx, T> InterpResult_<'tcx, T> { self, f: impl FnOnce(InterpErrorInfo<'tcx>) -> InterpErrorInfo<'tcx>, ) -> InterpResult<'tcx, T> { - InterpResult_::new(self.disarm().map_err(f)) + InterpResult::new(self.disarm().map_err(f)) } #[inline] @@ -906,7 +907,7 @@ impl<'tcx, T> InterpResult_<'tcx, T> { self, f: impl FnOnce(InterpErrorKind<'tcx>) -> InterpErrorKind<'tcx>, ) -> InterpResult<'tcx, T> { - InterpResult_::new(self.disarm().map_err(|mut e| { + InterpResult::new(self.disarm().map_err(|mut e| { e.0.kind = f(e.0.kind); e })) @@ -914,7 +915,7 @@ impl<'tcx, T> InterpResult_<'tcx, T> { #[inline] pub fn inspect_err_kind(self, f: impl FnOnce(&InterpErrorKind<'tcx>)) -> InterpResult<'tcx, T> { - InterpResult_::new(self.disarm().inspect_err(|e| f(&e.0.kind))) + InterpResult::new(self.disarm().inspect_err(|e| f(&e.0.kind))) } #[inline] @@ -937,7 +938,7 @@ impl<'tcx, T> InterpResult_<'tcx, T> { #[inline] pub fn and_then(self, f: impl FnOnce(T) -> InterpResult<'tcx, U>) -> InterpResult<'tcx, U> { - InterpResult_::new(self.disarm().and_then(|t| f(t).disarm())) + InterpResult::new(self.disarm().and_then(|t| f(t).disarm())) } /// Returns success if both `self` and `other` succeed, while ensuring we don't @@ -952,7 +953,7 @@ impl<'tcx, T> InterpResult_<'tcx, T> { // Discard the other error. drop(other.disarm()); // Return `self`. - InterpResult_::new(Err(e)) + InterpResult::new(Err(e)) } } } @@ -960,5 +961,5 @@ impl<'tcx, T> InterpResult_<'tcx, T> { #[inline(always)] pub fn interp_ok<'tcx, T>(x: T) -> InterpResult<'tcx, T> { - InterpResult_::new(Ok(x)) + InterpResult::new(Ok(x)) } From 7e3bb00fa7433ed00db0ca74c5174d8a87292556 Mon Sep 17 00:00:00 2001 From: Boxy Date: Mon, 4 Aug 2025 10:28:55 +0100 Subject: [PATCH 0430/1134] Update RELEASES.md Co-authored-by: alexey semenyuk --- RELEASES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index bb8fd41f2bb6..2c8dfcf7b5d6 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -98,7 +98,7 @@ Cargo Rustdoc ----- -- [On mobile, make the sidebar full width and linewrap](https://github.com/rust-lang/rust/pull/139831). This makes long section and item names much easier to deal with on mobile. +- [On mobile, make the sidebar full width and linewrap](https://github.com/rust-lang/rust/pull/139831). This makes long section and item names much easier to deal with on mobile. From 6b805102c0d91e0659c673986b5e75e6094665b3 Mon Sep 17 00:00:00 2001 From: Boxy Date: Mon, 4 Aug 2025 10:29:01 +0100 Subject: [PATCH 0431/1134] Update RELEASES.md Co-authored-by: alexey semenyuk --- RELEASES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index 2c8dfcf7b5d6..540fea8292aa 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -59,7 +59,7 @@ Libraries Stabilized APIs --------------- -- [Allow `NonZero`](https://github.com/rust-lang/rust/pull/141001) +- [`NonZero`](https://doc.rust-lang.org/stable/std/num/struct.NonZero.html) - Many intrinsics for x86, not enumerated here - [AVX512 intrinsics](https://github.com/rust-lang/rust/issues/111137) - [`SHA512`, `SM3` and `SM4` intrinsics](https://github.com/rust-lang/rust/issues/126624) From cf7b67420b9927c6154b43bab17917183d931f93 Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Mon, 4 Aug 2025 09:41:08 +0200 Subject: [PATCH 0432/1134] add `project_fields` helper function --- .../rustc_const_eval/src/interpret/projection.rs | 9 +++++++++ .../rustc_const_eval/src/interpret/visitor.rs | 15 +++++++-------- compiler/rustc_const_eval/src/lib.rs | 1 + .../rustc_const_eval/src/util/caller_location.rs | 10 +++++----- 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/projection.rs b/compiler/rustc_const_eval/src/interpret/projection.rs index f72c44180814..d05871bfc773 100644 --- a/compiler/rustc_const_eval/src/interpret/projection.rs +++ b/compiler/rustc_const_eval/src/interpret/projection.rs @@ -199,6 +199,15 @@ where base.offset_with_meta(offset, OffsetMode::Inbounds, meta, field_layout, self) } + /// Projects multiple fields at once. See [`Self::project_field`] for details. + pub fn project_fields, const N: usize>( + &self, + base: &P, + fields: [FieldIdx; N], + ) -> InterpResult<'tcx, [P; N]> { + fields.try_map(|field| self.project_field(base, field)) + } + /// Downcasting to an enum variant. pub fn project_downcast>( &self, diff --git a/compiler/rustc_const_eval/src/interpret/visitor.rs b/compiler/rustc_const_eval/src/interpret/visitor.rs index a27b66461315..82c50fac6c0e 100644 --- a/compiler/rustc_const_eval/src/interpret/visitor.rs +++ b/compiler/rustc_const_eval/src/interpret/visitor.rs @@ -121,25 +121,24 @@ pub trait ValueVisitor<'tcx, M: Machine<'tcx>>: Sized { // `Box` has two fields: the pointer we care about, and the allocator. assert_eq!(v.layout().fields.count(), 2, "`Box` must have exactly 2 fields"); - let (unique_ptr, alloc) = ( - self.ecx().project_field(v, FieldIdx::ZERO)?, - self.ecx().project_field(v, FieldIdx::ONE)?, - ); + let [unique_ptr, alloc] = + self.ecx().project_fields(v, [FieldIdx::ZERO, FieldIdx::ONE])?; + // Unfortunately there is some type junk in the way here: `unique_ptr` is a `Unique`... // (which means another 2 fields, the second of which is a `PhantomData`) assert_eq!(unique_ptr.layout().fields.count(), 2); - let (nonnull_ptr, phantom) = ( - self.ecx().project_field(&unique_ptr, FieldIdx::ZERO)?, - self.ecx().project_field(&unique_ptr, FieldIdx::ONE)?, - ); + let [nonnull_ptr, phantom] = + self.ecx().project_fields(&unique_ptr, [FieldIdx::ZERO, FieldIdx::ONE])?; assert!( phantom.layout().ty.ty_adt_def().is_some_and(|adt| adt.is_phantom_data()), "2nd field of `Unique` should be PhantomData but is {:?}", phantom.layout().ty, ); + // ... that contains a `NonNull`... (gladly, only a single field here) assert_eq!(nonnull_ptr.layout().fields.count(), 1); let raw_ptr = self.ecx().project_field(&nonnull_ptr, FieldIdx::ZERO)?; // the actual raw ptr + // ... whose only field finally is a raw ptr we can dereference. self.visit_box(ty, &raw_ptr)?; diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index bf7a79dcb20f..3840cdf75750 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -2,6 +2,7 @@ #![allow(internal_features)] #![allow(rustc::diagnostic_outside_of_impl)] #![doc(rust_logo)] +#![feature(array_try_map)] #![feature(assert_matches)] #![feature(box_patterns)] #![feature(decl_macro)] diff --git a/compiler/rustc_const_eval/src/util/caller_location.rs b/compiler/rustc_const_eval/src/util/caller_location.rs index c437934eaabe..5249b32eca46 100644 --- a/compiler/rustc_const_eval/src/util/caller_location.rs +++ b/compiler/rustc_const_eval/src/util/caller_location.rs @@ -42,12 +42,12 @@ fn alloc_caller_location<'tcx>( let location = ecx.allocate(loc_layout, MemoryKind::CallerLocation).unwrap(); // Initialize fields. - ecx.write_immediate(filename, &ecx.project_field(&location, FieldIdx::from_u32(0)).unwrap()) - .expect("writing to memory we just allocated cannot fail"); - ecx.write_scalar(line, &ecx.project_field(&location, FieldIdx::from_u32(1)).unwrap()) - .expect("writing to memory we just allocated cannot fail"); - ecx.write_scalar(col, &ecx.project_field(&location, FieldIdx::from_u32(2)).unwrap()) + let [filename_field, line_field, col_field] = + ecx.project_fields(&location, [0, 1, 2].map(FieldIdx::from_u32)).unwrap(); + ecx.write_immediate(filename, &filename_field) .expect("writing to memory we just allocated cannot fail"); + ecx.write_scalar(line, &line_field).expect("writing to memory we just allocated cannot fail"); + ecx.write_scalar(col, &col_field).expect("writing to memory we just allocated cannot fail"); location } From ac28b5b93a834662f6a51139c262b71c04e16bf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 4 Aug 2025 12:21:27 +0200 Subject: [PATCH 0433/1134] Fix splitting dylib paths --- src/bootstrap/src/core/build_steps/test.rs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 218a6f563e4f..1d5b1cea604e 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -4,7 +4,7 @@ //! However, this contains ~all test parts we expect people to be able to build and run locally. use std::collections::HashSet; -use std::env::join_paths; +use std::env::split_paths; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::{env, fs, iter}; @@ -34,8 +34,8 @@ use crate::core::config::flags::{Subcommand, get_completion}; use crate::utils::build_stamp::{self, BuildStamp}; use crate::utils::exec::{BootstrapCommand, command}; use crate::utils::helpers::{ - self, LldThreads, add_rustdoc_cargo_linker_args, dylib_path, dylib_path_var, linker_args, - linker_flags, t, target_supports_cranelift_backend, up_to_date, + self, LldThreads, add_dylib_path, add_rustdoc_cargo_linker_args, dylib_path, dylib_path_var, + linker_args, linker_flags, t, target_supports_cranelift_backend, up_to_date, }; use crate::utils::render_tests::{add_flags_and_try_run_tests, try_run_tests}; use crate::{CLang, CodegenBackendKind, DocTests, GitRepo, Mode, PathSet, debug, envify}; @@ -380,16 +380,14 @@ impl Step for Cargo { // libdir. That causes issues in cargo test, because the programs that cargo compiles are // incorrectly picking that libdir, even though they should be picking the // `tested_compiler`'s libdir. We thus have to override the precedence here. - let existing_dylib_path = cargo + let mut existing_dylib_paths = cargo .get_envs() .find(|(k, _)| *k == OsStr::new(dylib_path_var())) .and_then(|(_, v)| v) - .unwrap_or(OsStr::new("")); - cargo.env( - dylib_path_var(), - join_paths([builder.rustc_libdir(tested_compiler).as_ref(), existing_dylib_path]) - .unwrap_or_default(), - ); + .map(|value| split_paths(value).collect::>()) + .unwrap_or_default(); + existing_dylib_paths.insert(0, builder.rustc_libdir(tested_compiler)); + add_dylib_path(existing_dylib_paths, &mut cargo); // Cargo's test suite uses `CARGO_RUSTC_CURRENT_DIR` to determine the path that `file!` is // relative to. Cargo no longer sets this env var, so we have to do that. This has to be the From d2cfe486f0e856d6828a544b12b0b8b1f8277260 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Mon, 4 Aug 2025 16:41:10 +0500 Subject: [PATCH 0434/1134] remove feature gate --- library/core/src/num/uint_macros.rs | 4 ++-- library/std/src/lib.rs | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 584cd60fbe5c..bf5dc43f4073 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -850,7 +850,6 @@ macro_rules! uint_impl { /// # Examples /// /// ``` - /// #![feature(unsigned_signed_diff)] #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")] #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")] #[doc = concat!( @@ -888,7 +887,8 @@ macro_rules! uint_impl { "::MAX), Some(0));" )] /// ``` - #[unstable(feature = "unsigned_signed_diff", issue = "126041")] + #[stable(feature = "unsigned_signed_diff", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "unsigned_signed_diff", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> { let res = self.wrapping_sub(rhs) as $SignedT; diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 77301d7228ea..5ceb2b309554 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -319,7 +319,6 @@ #![feature(try_blocks)] #![feature(try_trait_v2)] #![feature(type_alias_impl_trait)] -#![feature(unsigned_signed_diff)] // tidy-alphabetical-end // // Library features (core): From affe2c4376a77aedbca077fd0ca0b3e898c8e214 Mon Sep 17 00:00:00 2001 From: Robert Serrano Kobylyansky Date: Mon, 4 Aug 2025 13:08:29 +0100 Subject: [PATCH 0435/1134] Update installation.md The `--enable-offload` and `--enable--enzyme` arguments don't seem to work. Changing them to `--enable-llvm-offload` and `--enable-llvm-enzyme` resulted in the `boostrap.toml` file generating succesfully. --- src/doc/rustc-dev-guide/src/offload/installation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/rustc-dev-guide/src/offload/installation.md b/src/doc/rustc-dev-guide/src/offload/installation.md index 1e792de3c8ce..b376e962ff63 100644 --- a/src/doc/rustc-dev-guide/src/offload/installation.md +++ b/src/doc/rustc-dev-guide/src/offload/installation.md @@ -8,7 +8,7 @@ First you need to clone and configure the Rust repository: ```bash git clone git@github.com:rust-lang/rust cd rust -./configure --enable-llvm-link-shared --release-channel=nightly --enable-llvm-assertions --enable-offload --enable-enzyme --enable-clang --enable-lld --enable-option-checking --enable-ninja --disable-docs +./configure --enable-llvm-link-shared --release-channel=nightly --enable-llvm-assertions --enable-llvm-offload --enable-llvm-enzyme --enable-clang --enable-lld --enable-option-checking --enable-ninja --disable-docs ``` Afterwards you can build rustc using: From 51f60d113980889e11e094199e047d99e669e6aa Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Mon, 4 Aug 2025 17:27:25 +0800 Subject: [PATCH 0436/1134] Remove `tcp-stress.rs` test This stress test was originally introduced in 65cca4bd3fa0abe1000662014b3e3ea1420728f5 to detect a UAF in libuv (see RUST-12823), but we no longer use libuv, so remove this test as it was causing flaky timeout failures. See RUST-144878 for discussion. --- tests/ui/threads-sendsync/tcp-stress.rs | 64 ------------------------- 1 file changed, 64 deletions(-) delete mode 100644 tests/ui/threads-sendsync/tcp-stress.rs diff --git a/tests/ui/threads-sendsync/tcp-stress.rs b/tests/ui/threads-sendsync/tcp-stress.rs deleted file mode 100644 index b2f76a55fb97..000000000000 --- a/tests/ui/threads-sendsync/tcp-stress.rs +++ /dev/null @@ -1,64 +0,0 @@ -//@ run-pass -//@ ignore-android needs extra network permissions -//@ needs-threads -//@ ignore-netbsd system ulimit (Too many open files) -//@ ignore-openbsd system ulimit (Too many open files) - -use std::io::prelude::*; -use std::net::{TcpListener, TcpStream}; -use std::process; -use std::sync::mpsc::channel; -use std::thread::{self, Builder}; -use std::time::Duration; - -const TARGET_CNT: usize = 200; - -fn main() { - // This test has a chance to time out, try to not let it time out - thread::spawn(move || -> () { - thread::sleep(Duration::from_secs(30)); - process::exit(1); - }); - - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - thread::spawn(move || -> () { - loop { - let mut stream = match listener.accept() { - Ok(stream) => stream.0, - Err(_) => continue, - }; - let _ = stream.read(&mut [0]); - let _ = stream.write(&[2]); - } - }); - - let (tx, rx) = channel(); - - let mut spawned_cnt = 0; - for _ in 0..TARGET_CNT { - let tx = tx.clone(); - let res = Builder::new().stack_size(64 * 1024).spawn(move || { - match TcpStream::connect(addr) { - Ok(mut stream) => { - let _ = stream.write(&[1]); - let _ = stream.read(&mut [0]); - } - Err(..) => {} - } - tx.send(()).unwrap(); - }); - if let Ok(_) = res { - spawned_cnt += 1; - }; - } - - // Wait for all clients to exit, but don't wait for the server to exit. The - // server just runs infinitely. - drop(tx); - for _ in 0..spawned_cnt { - rx.recv().unwrap(); - } - assert_eq!(spawned_cnt, TARGET_CNT); - process::exit(0); -} From b7f5392946d77d46994ba08261c09005fb2118c6 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Mon, 4 Aug 2025 18:25:34 +0500 Subject: [PATCH 0437/1134] remove begin prefix --- library/std/src/panicking.rs | 2 +- .../function_calls/exported_symbol_bad_unwind2.both.stderr | 4 ++-- .../exported_symbol_bad_unwind2.definition.stderr | 4 ++-- src/tools/miri/tests/fail/panic/abort_unwind.stderr | 4 ++-- src/tools/miri/tests/fail/panic/double_panic.stderr | 4 ++-- src/tools/miri/tests/fail/panic/panic_abort1.stderr | 4 ++-- src/tools/miri/tests/fail/panic/panic_abort2.stderr | 4 ++-- src/tools/miri/tests/fail/panic/panic_abort3.stderr | 4 ++-- src/tools/miri/tests/fail/panic/panic_abort4.stderr | 4 ++-- src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr | 4 ++-- src/tools/miri/tests/fail/terminate-terminator.stderr | 4 ++-- src/tools/miri/tests/fail/unwind-action-terminate.stderr | 4 ++-- src/tools/miri/tests/panic/panic1.stderr | 2 +- 13 files changed, 24 insertions(+), 24 deletions(-) diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 7873049d20bf..3bd2c634e630 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -627,7 +627,7 @@ pub fn panicking() -> bool { /// Entry point of panics from the core crate (`panic_impl` lang item). #[cfg(not(any(test, doctest)))] #[panic_handler] -pub fn begin_panic_handler(info: &core::panic::PanicInfo<'_>) -> ! { +pub fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! { struct FormatStringPayload<'a> { inner: &'a core::panic::PanicMessage<'a>, string: Option, diff --git a/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.both.stderr b/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.both.stderr index deec81f7e51b..b182758d5ff3 100644 --- a/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.both.stderr +++ b/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.both.stderr @@ -18,8 +18,8 @@ LL | ABORT() = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_nounwind` at RUSTLIB/core/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_cannot_unwind` at RUSTLIB/core/src/panicking.rs:LL:CC note: inside `nounwind` diff --git a/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.definition.stderr b/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.definition.stderr index deec81f7e51b..b182758d5ff3 100644 --- a/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.definition.stderr +++ b/src/tools/miri/tests/fail/function_calls/exported_symbol_bad_unwind2.definition.stderr @@ -18,8 +18,8 @@ LL | ABORT() = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_nounwind` at RUSTLIB/core/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_cannot_unwind` at RUSTLIB/core/src/panicking.rs:LL:CC note: inside `nounwind` diff --git a/src/tools/miri/tests/fail/panic/abort_unwind.stderr b/src/tools/miri/tests/fail/panic/abort_unwind.stderr index 81d560c27ec7..d0d9f840079c 100644 --- a/src/tools/miri/tests/fail/panic/abort_unwind.stderr +++ b/src/tools/miri/tests/fail/panic/abort_unwind.stderr @@ -18,8 +18,8 @@ LL | ABORT() = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_nounwind` at RUSTLIB/core/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_cannot_unwind` at RUSTLIB/core/src/panicking.rs:LL:CC = note: inside `std::panic::abort_unwind::<{closure@tests/fail/panic/abort_unwind.rs:LL:CC}, ()>` at RUSTLIB/core/src/panic.rs:LL:CC diff --git a/src/tools/miri/tests/fail/panic/double_panic.stderr b/src/tools/miri/tests/fail/panic/double_panic.stderr index bc6cce93d41e..4b352744bafc 100644 --- a/src/tools/miri/tests/fail/panic/double_panic.stderr +++ b/src/tools/miri/tests/fail/panic/double_panic.stderr @@ -21,8 +21,8 @@ LL | ABORT() = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_nounwind_nobacktrace` at RUSTLIB/core/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_in_cleanup` at RUSTLIB/core/src/panicking.rs:LL:CC note: inside `main` diff --git a/src/tools/miri/tests/fail/panic/panic_abort1.stderr b/src/tools/miri/tests/fail/panic/panic_abort1.stderr index 61bc9a7a4959..bb9b96b89f76 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort1.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort1.stderr @@ -17,8 +17,8 @@ LL | ABORT() = note: inside `std::panicking::rust_panic` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC note: inside `main` --> tests/fail/panic/panic_abort1.rs:LL:CC | diff --git a/src/tools/miri/tests/fail/panic/panic_abort2.stderr b/src/tools/miri/tests/fail/panic/panic_abort2.stderr index a7a42f8174e5..8f0efd7f1e2b 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort2.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort2.stderr @@ -17,8 +17,8 @@ LL | ABORT() = note: inside `std::panicking::rust_panic` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC note: inside `main` --> tests/fail/panic/panic_abort2.rs:LL:CC | diff --git a/src/tools/miri/tests/fail/panic/panic_abort3.stderr b/src/tools/miri/tests/fail/panic/panic_abort3.stderr index ba1f11065ead..5862054331aa 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort3.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort3.stderr @@ -17,8 +17,8 @@ LL | ABORT() = note: inside `std::panicking::rust_panic` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC note: inside `main` --> tests/fail/panic/panic_abort3.rs:LL:CC | diff --git a/src/tools/miri/tests/fail/panic/panic_abort4.stderr b/src/tools/miri/tests/fail/panic/panic_abort4.stderr index 1464c1fcc7c9..0e9afff8ca08 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort4.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort4.stderr @@ -17,8 +17,8 @@ LL | ABORT() = note: inside `std::panicking::rust_panic` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC note: inside `main` --> tests/fail/panic/panic_abort4.rs:LL:CC | diff --git a/src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr b/src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr index b893220426c9..71b7bbf01540 100644 --- a/src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr +++ b/src/tools/miri/tests/fail/ptr_swap_nonoverlapping.stderr @@ -16,8 +16,8 @@ LL | ABORT() = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC note: inside `main` --> tests/fail/ptr_swap_nonoverlapping.rs:LL:CC | diff --git a/src/tools/miri/tests/fail/terminate-terminator.stderr b/src/tools/miri/tests/fail/terminate-terminator.stderr index a0ee75e5dd27..2e6ef8481b3a 100644 --- a/src/tools/miri/tests/fail/terminate-terminator.stderr +++ b/src/tools/miri/tests/fail/terminate-terminator.stderr @@ -20,8 +20,8 @@ LL | ABORT() = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_nounwind` at RUSTLIB/core/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_cannot_unwind` at RUSTLIB/core/src/panicking.rs:LL:CC note: inside `has_cleanup` diff --git a/src/tools/miri/tests/fail/unwind-action-terminate.stderr b/src/tools/miri/tests/fail/unwind-action-terminate.stderr index 5fa485752a48..726d90f26238 100644 --- a/src/tools/miri/tests/fail/unwind-action-terminate.stderr +++ b/src/tools/miri/tests/fail/unwind-action-terminate.stderr @@ -18,8 +18,8 @@ LL | ABORT() = note: inside `std::sys::pal::PLATFORM::abort_internal` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC = note: inside `std::panicking::rust_panic_with_hook` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside closure at RUSTLIB/std/src/panicking.rs:LL:CC - = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::begin_panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC - = note: inside `std::panicking::begin_panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC + = note: inside `std::sys::backtrace::__rust_end_short_backtrace::<{closure@std::panicking::panic_handler::{closure#0}}, !>` at RUSTLIB/std/src/sys/backtrace.rs:LL:CC + = note: inside `std::panicking::panic_handler` at RUSTLIB/std/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_nounwind` at RUSTLIB/core/src/panicking.rs:LL:CC = note: inside `core::panicking::panic_cannot_unwind` at RUSTLIB/core/src/panicking.rs:LL:CC note: inside `panic_abort` diff --git a/src/tools/miri/tests/panic/panic1.stderr b/src/tools/miri/tests/panic/panic1.stderr index 130bc7737a49..8e596add8987 100644 --- a/src/tools/miri/tests/panic/panic1.stderr +++ b/src/tools/miri/tests/panic/panic1.stderr @@ -2,7 +2,7 @@ thread 'main' panicked at tests/panic/panic1.rs:LL:CC: panicking from libstd stack backtrace: - 0: std::panicking::begin_panic_handler + 0: std::panicking::panic_handler at RUSTLIB/std/src/panicking.rs:LL:CC 1: std::rt::panic_fmt at RUSTLIB/core/src/panicking.rs:LL:CC From d857d54110fcdf72c71312cf38186b9d66c52df8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 4 Aug 2025 15:43:50 +0200 Subject: [PATCH 0438/1134] Print CGU reuse statistics when `-Zprint-mono-items` is enabled --- compiler/rustc_codegen_ssa/src/assert_module_sources.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs index 3710625ac12d..43e1e135a666 100644 --- a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs +++ b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs @@ -69,6 +69,15 @@ pub fn assert_module_sources(tcx: TyCtxt<'_>, set_reuse: &dyn Fn(&mut CguReuseTr set_reuse(&mut ams.cgu_reuse_tracker); + if tcx.sess.opts.unstable_opts.print_mono_items + && let Some(data) = &ams.cgu_reuse_tracker.data + { + data.actual_reuse.items().all(|(cgu, reuse)| { + println!("CGU_REUSE {cgu} {reuse}"); + true + }); + } + ams.cgu_reuse_tracker.check_expected_reuse(tcx.sess); }); } From 75e20afb822e628b66fc4f45d567d3db22c0f82d Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 4 Aug 2025 16:06:56 +0200 Subject: [PATCH 0439/1134] Add new `test::print_merged_doctests_times` used by rustdoc to display more detailed time information and add new `OutputFormatter::write_merged_doctests_times` method to handle it --- library/test/src/console.rs | 26 +++++++++++++++----------- library/test/src/formatters/json.rs | 11 +++++++++++ library/test/src/formatters/junit.rs | 10 ++++++++++ library/test/src/formatters/mod.rs | 5 +++++ library/test/src/formatters/pretty.rs | 10 ++++++++++ library/test/src/formatters/terse.rs | 10 ++++++++++ library/test/src/lib.rs | 15 +++++++++++++++ 7 files changed, 76 insertions(+), 11 deletions(-) diff --git a/library/test/src/console.rs b/library/test/src/console.rs index 8f29f1dada52..13b2b3d502c8 100644 --- a/library/test/src/console.rs +++ b/library/test/src/console.rs @@ -281,23 +281,15 @@ fn on_test_event( Ok(()) } -/// A simple console test runner. -/// Runs provided tests reporting process and results to the stdout. -pub fn run_tests_console(opts: &TestOpts, tests: Vec) -> io::Result { +pub(crate) fn get_formatter(opts: &TestOpts, max_name_len: usize) -> Box { let output = match term::stdout() { None => OutputLocation::Raw(io::stdout()), Some(t) => OutputLocation::Pretty(t), }; - let max_name_len = tests - .iter() - .max_by_key(|t| len_if_padded(t)) - .map(|t| t.desc.name.as_slice().len()) - .unwrap_or(0); - let is_multithreaded = opts.test_threads.unwrap_or_else(get_concurrency) > 1; - let mut out: Box = match opts.format { + match opts.format { OutputFormat::Pretty => Box::new(PrettyFormatter::new( output, opts.use_color(), @@ -310,7 +302,19 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec) -> io::Resu } OutputFormat::Json => Box::new(JsonFormatter::new(output)), OutputFormat::Junit => Box::new(JunitFormatter::new(output)), - }; + } +} + +/// A simple console test runner. +/// Runs provided tests reporting process and results to the stdout. +pub fn run_tests_console(opts: &TestOpts, tests: Vec) -> io::Result { + let max_name_len = tests + .iter() + .max_by_key(|t| len_if_padded(t)) + .map(|t| t.desc.name.as_slice().len()) + .unwrap_or(0); + + let mut out = get_formatter(opts, max_name_len); let mut st = ConsoleTestState::new(opts)?; // Prevent the usage of `Instant` in some cases: diff --git a/library/test/src/formatters/json.rs b/library/test/src/formatters/json.rs index 92c1c0716f1f..4a101f00d74b 100644 --- a/library/test/src/formatters/json.rs +++ b/library/test/src/formatters/json.rs @@ -215,6 +215,17 @@ impl OutputFormatter for JsonFormatter { Ok(state.failed == 0) } + + fn write_merged_doctests_times( + &mut self, + total_time: f64, + compilation_time: f64, + ) -> io::Result<()> { + let newline = "\n"; + self.writeln_message(&format!( + r#"{{ "type": "report", "total_time": {total_time}, "compilation_time": {compilation_time} }}{newline}"#, + )) + } } /// A formatting utility used to print strings with characters in need of escaping. diff --git a/library/test/src/formatters/junit.rs b/library/test/src/formatters/junit.rs index 84153a9d05b5..1566f1cb1dac 100644 --- a/library/test/src/formatters/junit.rs +++ b/library/test/src/formatters/junit.rs @@ -182,6 +182,16 @@ impl OutputFormatter for JunitFormatter { Ok(state.failed == 0) } + + fn write_merged_doctests_times( + &mut self, + total_time: f64, + compilation_time: f64, + ) -> io::Result<()> { + self.write_message(&format!( + "\n", + )) + } } fn parse_class_name(desc: &TestDesc) -> (String, String) { diff --git a/library/test/src/formatters/mod.rs b/library/test/src/formatters/mod.rs index f1225fecfef1..c97cdb16a507 100644 --- a/library/test/src/formatters/mod.rs +++ b/library/test/src/formatters/mod.rs @@ -33,6 +33,11 @@ pub(crate) trait OutputFormatter { state: &ConsoleTestState, ) -> io::Result<()>; fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result; + fn write_merged_doctests_times( + &mut self, + total_time: f64, + compilation_time: f64, + ) -> io::Result<()>; } pub(crate) fn write_stderr_delimiter(test_output: &mut Vec, test_name: &TestName) { diff --git a/library/test/src/formatters/pretty.rs b/library/test/src/formatters/pretty.rs index bf3fc40db411..5836138644aa 100644 --- a/library/test/src/formatters/pretty.rs +++ b/library/test/src/formatters/pretty.rs @@ -303,4 +303,14 @@ impl OutputFormatter for PrettyFormatter { Ok(success) } + + fn write_merged_doctests_times( + &mut self, + total_time: f64, + compilation_time: f64, + ) -> io::Result<()> { + self.write_plain(format!( + "all doctests ran in {total_time:.2}s; merged doctests compilation took {compilation_time:.2}s\n", + )) + } } diff --git a/library/test/src/formatters/terse.rs b/library/test/src/formatters/terse.rs index b28120ab56e6..0720f06e174f 100644 --- a/library/test/src/formatters/terse.rs +++ b/library/test/src/formatters/terse.rs @@ -295,4 +295,14 @@ impl OutputFormatter for TerseFormatter { Ok(success) } + + fn write_merged_doctests_times( + &mut self, + total_time: f64, + compilation_time: f64, + ) -> io::Result<()> { + self.write_plain(format!( + "all doctests ran in {total_time:.2}s; merged doctests compilation took {compilation_time:.2}s\n", + )) + } } diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 1190bb56b97a..d554807bbde7 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -244,6 +244,21 @@ fn make_owned_test(test: &&TestDescAndFn) -> TestDescAndFn { } } +/// Public API used by rustdoc to display the `total` and `compilation` times in the expected +/// format. +pub fn print_merged_doctests_times(args: &[String], total_time: f64, compilation_time: f64) { + let opts = match cli::parse_opts(args) { + Some(Ok(o)) => o, + Some(Err(msg)) => { + eprintln!("error: {msg}"); + process::exit(ERROR_EXIT_CODE); + } + None => return, + }; + let mut formatter = console::get_formatter(&opts, 0); + formatter.write_merged_doctests_times(total_time, compilation_time).unwrap(); +} + /// Invoked when unit tests terminate. Returns `Result::Err` if the test is /// considered a failure. By default, invokes `report()` and checks for a `0` /// result. From 0708b6a1e685f140f653fa5f77a3c1318f0f74ff Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Mon, 4 Aug 2025 18:25:46 +0500 Subject: [PATCH 0440/1134] Fix not showing deprecated lints --- util/gh-pages/script.js | 1 + 1 file changed, 1 insertion(+) diff --git a/util/gh-pages/script.js b/util/gh-pages/script.js index d32049675319..cfc5fb7b27ca 100644 --- a/util/gh-pages/script.js +++ b/util/gh-pages/script.js @@ -208,6 +208,7 @@ const LEVEL_FILTERS_DEFAULT = { allow: true, warn: true, deny: true, + none: true, }; const APPLICABILITIES_FILTER_DEFAULT = { Unspecified: true, From d85a64531673c42ef8a7e214305751f27da53bac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Mon, 4 Aug 2025 16:22:05 +0200 Subject: [PATCH 0441/1134] Require approval from t-infra instead of t-release on tier bumps --- src/doc/rustc/src/target-tier-policy.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/doc/rustc/src/target-tier-policy.md b/src/doc/rustc/src/target-tier-policy.md index a0acfdf0e4ab..28d3dc32a63e 100644 --- a/src/doc/rustc/src/target-tier-policy.md +++ b/src/doc/rustc/src/target-tier-policy.md @@ -534,10 +534,10 @@ tests, and will reject patches that fail to build or pass the testsuite on a target. We hold tier 1 targets to our highest standard of requirements. A proposed new tier 1 target must be reviewed and approved by the compiler team -based on these requirements. In addition, the release team must approve the -viability and value of supporting the target. For a tier 1 target, this will +based on these requirements. In addition, the infra team must approve the +viability of supporting the target. For a tier 1 target, this will typically take place via a full RFC proposing the target, to be jointly -reviewed and approved by the compiler team and release team. +reviewed and approved by the compiler team and infra team. In addition, the infrastructure team must approve the integration of the target into Continuous Integration (CI), and the tier 1 CI-related requirements. This @@ -617,7 +617,7 @@ including the infrastructure team in the RFC proposing the target. A tier 1 target may be demoted if it no longer meets these requirements but still meets the requirements for a lower tier. Any proposal for demotion of a tier 1 target requires a full RFC process, with approval by the compiler and -release teams. Any such proposal will be communicated widely to the Rust +infra teams. Any such proposal will be communicated widely to the Rust community, both when initially proposed and before being dropped from a stable release. A tier 1 target is highly unlikely to be directly removed without first being demoted to tier 2 or tier 3. (The amount of time between such @@ -628,7 +628,7 @@ planned and scheduled action.) Raising the baseline expectations of a tier 1 target (such as the minimum CPU features or OS version required) requires the approval of the compiler and -release teams, and should be widely communicated as well, but does not +infra teams, and should be widely communicated as well, but does not necessarily require a full RFC. ### Tier 1 with host tools @@ -638,11 +638,11 @@ host (such as `rustc` and `cargo`). This allows the target to be used as a development platform, not just a compilation target. A proposed new tier 1 target with host tools must be reviewed and approved by -the compiler team based on these requirements. In addition, the release team -must approve the viability and value of supporting host tools for the target. +the compiler team based on these requirements. In addition, the infra team +must approve the viability of supporting host tools for the target. For a tier 1 target, this will typically take place via a full RFC proposing the target, to be jointly reviewed and approved by the compiler team and -release team. +infra team. In addition, the infrastructure team must approve the integration of the target's host tools into Continuous Integration (CI), and the CI-related @@ -697,7 +697,7 @@ target with host tools may be demoted (including having its host tools dropped, or being demoted to tier 2 with host tools) if it no longer meets these requirements but still meets the requirements for a lower tier. Any proposal for demotion of a tier 1 target (with or without host tools) requires a full -RFC process, with approval by the compiler and release teams. Any such proposal +RFC process, with approval by the compiler and infra teams. Any such proposal will be communicated widely to the Rust community, both when initially proposed and before being dropped from a stable release. From 6e75abd0aa4f22f6291f1a25ff81e0c6b959ad26 Mon Sep 17 00:00:00 2001 From: Ayush Singh Date: Sun, 20 Jul 2025 22:35:43 +0530 Subject: [PATCH 0442/1134] std: sys: io: io_slice: Add UEFI types UEFI networking APIs do support vectored read/write. While the types for UDP4, UDP6, TCP4 and TCP6 are defined separately, they are essentially the same C struct. So we can map IoSlice and IoSliceMut to have the same binary representation. Since all UEFI networking types for read/write are DSTs, `IoSlice` and `IoSliceMut` will need to be copied to the end of the transmit/receive structures. So having the same binary representation just allows us to do a single memcpy instead of having to loop and set the DST. Signed-off-by: Ayush Singh --- library/std/src/sys/io/io_slice/uefi.rs | 74 +++++++++++++++ library/std/src/sys/io/mod.rs | 3 + library/std/src/sys/pal/uefi/tests.rs | 119 ++++++++++++++++++++++++ 3 files changed, 196 insertions(+) create mode 100644 library/std/src/sys/io/io_slice/uefi.rs diff --git a/library/std/src/sys/io/io_slice/uefi.rs b/library/std/src/sys/io/io_slice/uefi.rs new file mode 100644 index 000000000000..909cfbea0b7b --- /dev/null +++ b/library/std/src/sys/io/io_slice/uefi.rs @@ -0,0 +1,74 @@ +//! A buffer type used with `Write::write_vectored` for UEFI Networking APIs. Vectored writing to +//! File is not supported as of UEFI Spec 2.11. + +use crate::marker::PhantomData; +use crate::slice; + +#[derive(Copy, Clone)] +#[repr(C)] +pub struct IoSlice<'a> { + len: u32, + data: *const u8, + _p: PhantomData<&'a [u8]>, +} + +impl<'a> IoSlice<'a> { + #[inline] + pub fn new(buf: &'a [u8]) -> IoSlice<'a> { + let len = buf.len().try_into().unwrap(); + Self { len, data: buf.as_ptr(), _p: PhantomData } + } + + #[inline] + pub fn advance(&mut self, n: usize) { + self.len = u32::try_from(n) + .ok() + .and_then(|n| self.len.checked_sub(n)) + .expect("advancing IoSlice beyond its length"); + unsafe { self.data = self.data.add(n) }; + } + + #[inline] + pub const fn as_slice(&self) -> &'a [u8] { + unsafe { slice::from_raw_parts(self.data, self.len as usize) } + } +} + +#[repr(C)] +pub struct IoSliceMut<'a> { + len: u32, + data: *mut u8, + _p: PhantomData<&'a mut [u8]>, +} + +impl<'a> IoSliceMut<'a> { + #[inline] + pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> { + let len = buf.len().try_into().unwrap(); + Self { len, data: buf.as_mut_ptr(), _p: PhantomData } + } + + #[inline] + pub fn advance(&mut self, n: usize) { + self.len = u32::try_from(n) + .ok() + .and_then(|n| self.len.checked_sub(n)) + .expect("advancing IoSlice beyond its length"); + unsafe { self.data = self.data.add(n) }; + } + + #[inline] + pub fn as_slice(&self) -> &[u8] { + unsafe { slice::from_raw_parts(self.data, self.len as usize) } + } + + #[inline] + pub const fn into_slice(self) -> &'a mut [u8] { + unsafe { slice::from_raw_parts_mut(self.data, self.len as usize) } + } + + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [u8] { + unsafe { slice::from_raw_parts_mut(self.data, self.len as usize) } + } +} diff --git a/library/std/src/sys/io/mod.rs b/library/std/src/sys/io/mod.rs index 4d0365d42fd9..ae75f4d97b43 100644 --- a/library/std/src/sys/io/mod.rs +++ b/library/std/src/sys/io/mod.rs @@ -11,6 +11,9 @@ mod io_slice { } else if #[cfg(target_os = "wasi")] { mod wasi; pub use wasi::*; + } else if #[cfg(target_os = "uefi")] { + mod uefi; + pub use uefi::*; } else { mod unsupported; pub use unsupported::*; diff --git a/library/std/src/sys/pal/uefi/tests.rs b/library/std/src/sys/pal/uefi/tests.rs index 38658cc4e9ac..49e75a1a70d7 100644 --- a/library/std/src/sys/pal/uefi/tests.rs +++ b/library/std/src/sys/pal/uefi/tests.rs @@ -1,5 +1,6 @@ use super::alloc::*; use super::time::*; +use crate::io::{IoSlice, IoSliceMut}; use crate::time::Duration; #[test] @@ -39,3 +40,121 @@ fn epoch() { }; assert_eq!(system_time_internal::uefi_time_to_duration(t), Duration::new(0, 0)); } + +// UEFI IoSlice and IoSliceMut Tests +// +// Strictly speaking, vectored read/write types for UDP4, UDP6, TCP4, TCP6 are defined +// separately in the UEFI Spec. However, they have the same signature. These tests just ensure +// that `IoSlice` and `IoSliceMut` are compatible with the vectored types for all the +// networking protocols. + +unsafe fn to_slice(val: &T) -> &[u8] { + let len = size_of_val(val); + unsafe { crate::slice::from_raw_parts(crate::ptr::from_ref(val).cast(), len) } +} + +#[test] +fn io_slice_single() { + let mut data = [0, 1, 2, 3, 4]; + + let tcp4_frag = r_efi::protocols::tcp4::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let tcp6_frag = r_efi::protocols::tcp6::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let udp4_frag = r_efi::protocols::udp4::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let udp6_frag = r_efi::protocols::udp6::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let io_slice = IoSlice::new(&data); + + unsafe { + assert_eq!(to_slice(&io_slice), to_slice(&tcp4_frag)); + assert_eq!(to_slice(&io_slice), to_slice(&tcp6_frag)); + assert_eq!(to_slice(&io_slice), to_slice(&udp4_frag)); + assert_eq!(to_slice(&io_slice), to_slice(&udp6_frag)); + } +} + +#[test] +fn io_slice_mut_single() { + let mut data = [0, 1, 2, 3, 4]; + + let tcp4_frag = r_efi::protocols::tcp4::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let tcp6_frag = r_efi::protocols::tcp6::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let udp4_frag = r_efi::protocols::udp4::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let udp6_frag = r_efi::protocols::udp6::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let io_slice_mut = IoSliceMut::new(&mut data); + + unsafe { + assert_eq!(to_slice(&io_slice_mut), to_slice(&tcp4_frag)); + assert_eq!(to_slice(&io_slice_mut), to_slice(&tcp6_frag)); + assert_eq!(to_slice(&io_slice_mut), to_slice(&udp4_frag)); + assert_eq!(to_slice(&io_slice_mut), to_slice(&udp6_frag)); + } +} + +#[test] +fn io_slice_multi() { + let mut data = [0, 1, 2, 3, 4]; + + let tcp4_frag = r_efi::protocols::tcp4::FragmentData { + fragment_length: data.len().try_into().unwrap(), + fragment_buffer: data.as_mut_ptr().cast(), + }; + let rhs = + [tcp4_frag.clone(), tcp4_frag.clone(), tcp4_frag.clone(), tcp4_frag.clone(), tcp4_frag]; + let lhs = [ + IoSlice::new(&data), + IoSlice::new(&data), + IoSlice::new(&data), + IoSlice::new(&data), + IoSlice::new(&data), + ]; + + unsafe { + assert_eq!(to_slice(&lhs), to_slice(&rhs)); + } +} + +#[test] +fn io_slice_basic() { + let data = [0, 1, 2, 3, 4]; + let mut io_slice = IoSlice::new(&data); + + assert_eq!(data, io_slice.as_slice()); + io_slice.advance(2); + assert_eq!(&data[2..], io_slice.as_slice()); +} + +#[test] +fn io_slice_mut_basic() { + let data = [0, 1, 2, 3, 4]; + let mut data_clone = [0, 1, 2, 3, 4]; + let mut io_slice_mut = IoSliceMut::new(&mut data_clone); + + assert_eq!(data, io_slice_mut.as_slice()); + assert_eq!(data, io_slice_mut.as_mut_slice()); + + io_slice_mut.advance(2); + assert_eq!(&data[2..], io_slice_mut.into_slice()); +} From 5b22c0c1edeee30f59b5e3e015f5a2279add821b Mon Sep 17 00:00:00 2001 From: Fayti1703 Date: Mon, 4 Aug 2025 16:38:31 +0200 Subject: [PATCH 0443/1134] Remove rogue comma from infallible_try_from lint message --- clippy_lints/src/infallible_try_from.rs | 2 +- tests/ui/infallible_try_from.stderr | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/infallible_try_from.rs b/clippy_lints/src/infallible_try_from.rs index aa6fc78dbbcf..589c294a678a 100644 --- a/clippy_lints/src/infallible_try_from.rs +++ b/clippy_lints/src/infallible_try_from.rs @@ -71,7 +71,7 @@ impl<'tcx> LateLintPass<'tcx> for InfallibleTryFrom { cx, INFALLIBLE_TRY_FROM, span, - "infallible TryFrom impl; consider implementing From, instead", + "infallible TryFrom impl; consider implementing From instead", ); } } diff --git a/tests/ui/infallible_try_from.stderr b/tests/ui/infallible_try_from.stderr index 705b1188489c..d1e0d9e7d3bb 100644 --- a/tests/ui/infallible_try_from.stderr +++ b/tests/ui/infallible_try_from.stderr @@ -1,4 +1,4 @@ -error: infallible TryFrom impl; consider implementing From, instead +error: infallible TryFrom impl; consider implementing From instead --> tests/ui/infallible_try_from.rs:8:1 | LL | impl TryFrom for MyStruct { @@ -10,7 +10,7 @@ LL | type Error = !; = note: `-D clippy::infallible-try-from` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::infallible_try_from)]` -error: infallible TryFrom impl; consider implementing From, instead +error: infallible TryFrom impl; consider implementing From instead --> tests/ui/infallible_try_from.rs:16:1 | LL | impl TryFrom for MyStruct { From f6ce4ac9d38fca2df5bc408de8f4c2567d2f2709 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 2 Aug 2025 17:36:34 +0000 Subject: [PATCH 0444/1134] Anonymize binders in tail call sig --- compiler/rustc_mir_build/src/check_tail_calls.rs | 6 +++++- tests/ui/explicit-tail-calls/higher-ranked-arg.rs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 tests/ui/explicit-tail-calls/higher-ranked-arg.rs diff --git a/compiler/rustc_mir_build/src/check_tail_calls.rs b/compiler/rustc_mir_build/src/check_tail_calls.rs index 6ed100899d8c..036e20c22b8f 100644 --- a/compiler/rustc_mir_build/src/check_tail_calls.rs +++ b/compiler/rustc_mir_build/src/check_tail_calls.rs @@ -60,9 +60,13 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { let BodyTy::Fn(caller_sig) = self.thir.body_type else { span_bug!( call.span, - "`become` outside of functions should have been disallowed by hit_typeck" + "`become` outside of functions should have been disallowed by hir_typeck" ) }; + // While the `caller_sig` does have its regions erased, it does not have its + // binders anonymized. We call `erase_regions` once again to anonymize any binders + // within the signature, such as in function pointer or `dyn Trait` args. + let caller_sig = self.tcx.erase_regions(caller_sig); let ExprKind::Scope { value, .. } = call.kind else { span_bug!(call.span, "expected scope, found: {call:?}") diff --git a/tests/ui/explicit-tail-calls/higher-ranked-arg.rs b/tests/ui/explicit-tail-calls/higher-ranked-arg.rs new file mode 100644 index 000000000000..e60686ab5111 --- /dev/null +++ b/tests/ui/explicit-tail-calls/higher-ranked-arg.rs @@ -0,0 +1,13 @@ +// Regression test for . +//@ check-pass + +#![feature(explicit_tail_calls)] +#![expect(incomplete_features)] + +fn foo(x: fn(&i32)) { + become bar(x); +} + +fn bar(_: fn(&i32)) {} + +fn main() {} From c7ea022166d2b6d55c3f69bbf69a31b0d7b053e2 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 4 Aug 2025 16:24:41 +0000 Subject: [PATCH 0445/1134] Enforce tail call type is related to body return type in borrowck --- compiler/rustc_borrowck/src/type_check/mod.rs | 10 +++++++--- .../ret-ty-borrowck-constraints.rs | 16 ++++++++++++++++ .../ret-ty-borrowck-constraints.stderr | 10 ++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.rs create mode 100644 tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.stderr diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index f5fedbf95c1c..91973f33bd32 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -845,9 +845,13 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ); } - if let TerminatorKind::Call { destination, target, .. } = term.kind { - self.check_call_dest(term, &sig, destination, target, term_location); - } + let (destination, target) = + if let TerminatorKind::Call { destination, target, .. } = term.kind { + (destination, target) + } else { + (RETURN_PLACE.into(), Some(BasicBlock::ZERO)) + }; + self.check_call_dest(term, &sig, destination, target, term_location); // The ordinary liveness rules will ensure that all // regions in the type of the callee are live here. We diff --git a/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.rs b/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.rs new file mode 100644 index 000000000000..111ae849c0f6 --- /dev/null +++ b/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.rs @@ -0,0 +1,16 @@ +#![feature(explicit_tail_calls)] +#![expect(incomplete_features)] + +fn link(x: &str) -> &'static str { + become passthrough(x); + //~^ ERROR lifetime may not live long enough +} + +fn passthrough(t: T) -> T { t } + +fn main() { + let x = String::from("hello, world"); + let s = link(&x); + drop(x); + println!("{s}"); +} diff --git a/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.stderr b/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.stderr new file mode 100644 index 000000000000..26a8e1f0122a --- /dev/null +++ b/tests/ui/explicit-tail-calls/ret-ty-borrowck-constraints.stderr @@ -0,0 +1,10 @@ +error: lifetime may not live long enough + --> $DIR/ret-ty-borrowck-constraints.rs:5:5 + | +LL | fn link(x: &str) -> &'static str { + | - let's call the lifetime of this reference `'1` +LL | become passthrough(x); + | ^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static` + +error: aborting due to 1 previous error + From 904e2af3a97e81637b9816d71411d52e26bd1550 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 1 Aug 2025 18:25:57 +0200 Subject: [PATCH 0446/1134] Port `#[coroutine]` to the new attribute system Related to https://github.com/rust-lang/rust/issues/131229#issue-2565886367. --- compiler/rustc_ast_lowering/src/expr.rs | 18 ++++++------------ .../rustc_attr_parsing/src/attributes/body.rs | 15 +++++++++++++++ .../rustc_attr_parsing/src/attributes/mod.rs | 1 + compiler/rustc_attr_parsing/src/context.rs | 2 ++ .../rustc_hir/src/attrs/data_structures.rs | 3 +++ .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 10 +++++----- tests/ui/attributes/malformed-attrs.stderr | 15 +++++++++------ 8 files changed, 42 insertions(+), 23 deletions(-) create mode 100644 compiler/rustc_attr_parsing/src/attributes/body.rs diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 1245d4897547..fb42cfea30b4 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -98,7 +98,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } let expr_hir_id = self.lower_node_id(e.id); - self.lower_attrs(expr_hir_id, &e.attrs, e.span); + let attrs = self.lower_attrs(expr_hir_id, &e.attrs, e.span); let kind = match &e.kind { ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), @@ -232,10 +232,10 @@ impl<'hir> LoweringContext<'_, 'hir> { *fn_arg_span, ), None => self.lower_expr_closure( + attrs, binder, *capture_clause, e.id, - expr_hir_id, *constness, *movability, fn_decl, @@ -1052,10 +1052,10 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_expr_closure( &mut self, + attrs: &[rustc_hir::Attribute], binder: &ClosureBinder, capture_clause: CaptureBy, closure_id: NodeId, - closure_hir_id: hir::HirId, constness: Const, movability: Movability, decl: &FnDecl, @@ -1067,15 +1067,9 @@ impl<'hir> LoweringContext<'_, 'hir> { let (binder_clause, generic_params) = self.lower_closure_binder(binder); let (body_id, closure_kind) = self.with_new_scopes(fn_decl_span, move |this| { - let mut coroutine_kind = if this - .attrs - .get(&closure_hir_id.local_id) - .is_some_and(|attrs| attrs.iter().any(|attr| attr.has_name(sym::coroutine))) - { - Some(hir::CoroutineKind::Coroutine(Movability::Movable)) - } else { - None - }; + + let mut coroutine_kind = find_attr!(attrs, AttributeKind::Coroutine(_) => hir::CoroutineKind::Coroutine(Movability::Movable)); + // FIXME(contracts): Support contracts on closures? let body_id = this.lower_fn_body(decl, None, |this| { this.coroutine_kind = coroutine_kind; diff --git a/compiler/rustc_attr_parsing/src/attributes/body.rs b/compiler/rustc_attr_parsing/src/attributes/body.rs new file mode 100644 index 000000000000..ab9330216f6c --- /dev/null +++ b/compiler/rustc_attr_parsing/src/attributes/body.rs @@ -0,0 +1,15 @@ +//! Attributes that can be found in function body. + +use rustc_hir::attrs::AttributeKind; +use rustc_span::{Symbol, sym}; + +use super::{NoArgsAttributeParser, OnDuplicate}; +use crate::context::Stage; + +pub(crate) struct CoroutineParser; + +impl NoArgsAttributeParser for CoroutineParser { + const PATH: &[Symbol] = &[sym::coroutine]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const CREATE: fn(rustc_span::Span) -> AttributeKind = |span| AttributeKind::Coroutine(span); +} diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index c574ef78bdf7..f7946ade6d2b 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -26,6 +26,7 @@ use crate::parser::ArgParser; use crate::session_diagnostics::UnusedMultiple; pub(crate) mod allow_unstable; +pub(crate) mod body; pub(crate) mod cfg; pub(crate) mod cfg_old; pub(crate) mod codegen_attrs; diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index b51db9b4b9e3..ec74f6fd1c6f 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -16,6 +16,7 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym}; use crate::attributes::allow_unstable::{ AllowConstFnUnstableParser, AllowInternalUnstableParser, UnstableFeatureBoundParser, }; +use crate::attributes::body::CoroutineParser; use crate::attributes::codegen_attrs::{ ColdParser, CoverageParser, ExportNameParser, NakedParser, NoMangleParser, OptimizeParser, TargetFeatureParser, TrackCallerParser, UsedParser, @@ -184,6 +185,7 @@ attribute_parsers!( Single>, Single>, Single>, + Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 80618422b56d..d9d2ec48948e 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -297,6 +297,9 @@ pub enum AttributeKind { /// Represents `#[const_trait]`. ConstTrait(Span), + /// Represents `#[coroutine]`. + Coroutine(Span), + /// Represents `#[coverage(..)]`. Coverage(Span, CoverageAttrKind), diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 9644a597a311..b66e5bbeabe7 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -28,6 +28,7 @@ impl AttributeKind { ConstStability { .. } => Yes, ConstStabilityIndirect => No, ConstTrait(..) => No, + Coroutine(..) => No, Coverage(..) => No, DenyExplicitImpl(..) => No, Deprecation { .. } => Yes, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 2663d5fe99c7..890028d977d3 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -324,6 +324,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { &Attribute::Parsed(AttributeKind::Coverage(attr_span, _)) => { self.check_coverage(attr_span, span, target) } + &Attribute::Parsed(AttributeKind::Coroutine(attr_span)) => { + self.check_coroutine(attr_span, target) + } Attribute::Unparsed(attr_item) => { style = Some(attr_item.style); match attr.path().as_slice() { @@ -390,9 +393,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { [sym::autodiff_forward, ..] | [sym::autodiff_reverse, ..] => { self.check_autodiff(hir_id, attr, span, target) } - [sym::coroutine, ..] => { - self.check_coroutine(attr, target); - } [sym::linkage, ..] => self.check_linkage(attr, span, target), [ // ok @@ -2651,11 +2651,11 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - fn check_coroutine(&self, attr: &Attribute, target: Target) { + fn check_coroutine(&self, attr_span: Span, target: Target) { match target { Target::Closure => return, _ => { - self.dcx().emit_err(errors::CoroutineOnNonClosure { span: attr.span() }); + self.dcx().emit_err(errors::CoroutineOnNonClosure { span: attr_span }); } } } diff --git a/tests/ui/attributes/malformed-attrs.stderr b/tests/ui/attributes/malformed-attrs.stderr index 1b51075b4e88..e8ae4715398f 100644 --- a/tests/ui/attributes/malformed-attrs.stderr +++ b/tests/ui/attributes/malformed-attrs.stderr @@ -55,12 +55,6 @@ error: malformed `patchable_function_entry` attribute input LL | #[patchable_function_entry] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[patchable_function_entry(prefix_nops = m, entry_nops = n)]` -error: malformed `coroutine` attribute input - --> $DIR/malformed-attrs.rs:108:5 - | -LL | #[coroutine = 63] || {} - | ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[coroutine]` - error: malformed `must_not_suspend` attribute input --> $DIR/malformed-attrs.rs:129:1 | @@ -436,6 +430,15 @@ LL | #[proc_macro = 18] | | didn't expect any arguments here | help: must be of the form: `#[proc_macro]` +error[E0565]: malformed `coroutine` attribute input + --> $DIR/malformed-attrs.rs:108:5 + | +LL | #[coroutine = 63] || {} + | ^^^^^^^^^^^^----^ + | | | + | | didn't expect any arguments here + | help: must be of the form: `#[coroutine]` + error[E0565]: malformed `proc_macro_attribute` attribute input --> $DIR/malformed-attrs.rs:113:1 | From b4f404b581a3e93c146ca2ea711fa03dca77327b Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 4 Aug 2025 17:23:56 +0200 Subject: [PATCH 0447/1134] Fix wrong font being used for tooltips `i` icons --- src/librustdoc/html/static/css/rustdoc.css | 4 ++++ tests/rustdoc-gui/notable-trait.goml | 4 ++-- tests/rustdoc-gui/src/test_docs/lib.rs | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index 99b3da8b2cd4..c48863b4681e 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -1838,6 +1838,10 @@ instead, we check that it's not a "finger" cursor. border-right: 3px solid var(--target-border-color); } +a.tooltip { + font-family: var(--font-family); +} + .code-header a.tooltip { color: inherit; margin-right: 15px; diff --git a/tests/rustdoc-gui/notable-trait.goml b/tests/rustdoc-gui/notable-trait.goml index 7fc70e0675df..423a273fde74 100644 --- a/tests/rustdoc-gui/notable-trait.goml +++ b/tests/rustdoc-gui/notable-trait.goml @@ -8,10 +8,10 @@ define-function: ( [x, i_x], block { // Checking they have the same y position. - compare-elements-position: ( + compare-elements-position-near: ( "//*[@id='method.create_an_iterator_from_read']//a[normalize-space()='NotableStructWithLongName']", "//*[@id='method.create_an_iterator_from_read']//*[@class='tooltip']", - ["y"], + {"y": 1}, ) // Checking they don't have the same x position. compare-elements-position-false: ( diff --git a/tests/rustdoc-gui/src/test_docs/lib.rs b/tests/rustdoc-gui/src/test_docs/lib.rs index e8afe8b56872..623f5b33e9bc 100644 --- a/tests/rustdoc-gui/src/test_docs/lib.rs +++ b/tests/rustdoc-gui/src/test_docs/lib.rs @@ -767,3 +767,17 @@ pub mod impls_indent { pub fn bar() {} } } + +pub mod tooltips { + pub struct X; + + impl X { + pub fn bar() -> Vec { + Vec::new() + } + } + + pub fn bar() -> Vec { + Vec::new() + } +} From 22607491bb944a715a15c15749f563986e6984bf Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 4 Aug 2025 17:41:48 +0200 Subject: [PATCH 0448/1134] Add GUI regression test for tooltips `i` icons --- tests/rustdoc-gui/tooltips.goml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 tests/rustdoc-gui/tooltips.goml diff --git a/tests/rustdoc-gui/tooltips.goml b/tests/rustdoc-gui/tooltips.goml new file mode 100644 index 000000000000..6e79196be273 --- /dev/null +++ b/tests/rustdoc-gui/tooltips.goml @@ -0,0 +1,15 @@ +// This test checks that the right font is applied to the `i` tooltip element. + +define-function: ( + "check-font", + [path], + block { + go-to: "file://" + |DOC_PATH| + "/test_docs/" + |path| + assert-css: ( + "a.tooltip", {"font-family": '"Source Serif 4", NanumBarunGothic, serif'}, ALL, + ) + } +) + +call-function: ("check-font", {"path": "tooltips/fn.bar.html"}) +call-function: ("check-font", {"path": "tooltips/struct.X.html"}) From 91e606b715ac4e8f59fac86d42ec2ad23f4ef169 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 28 Feb 2025 23:37:37 +0000 Subject: [PATCH 0449/1134] Tweak auto trait errors Make suggestions to remove params and super traits tool-only, and make the suggestion span more accurate. ``` error[E0567]: auto traits cannot have generic parameters --> $DIR/auto-trait-validation.rs:6:19 | LL | auto trait Generic {} | -------^^^ | | | auto trait cannot have generic parameters error[E0568]: auto traits cannot have super traits or lifetime bounds --> $DIR/auto-trait-validation.rs:8:20 | LL | auto trait Bound : Copy {} | ----- ^^^^ | | | auto traits cannot have super traits or lifetime bounds ``` ``` error[E0380]: auto traits cannot have associated items --> $DIR/issue-23080.rs:5:8 | LL | unsafe auto trait Trait { | ----- auto traits cannot have associated items LL | fn method(&self) { | ^^^^^^ ``` --- compiler/rustc_ast_passes/messages.ftl | 2 +- .../rustc_ast_passes/src/ast_validation.rs | 16 +++-- compiler/rustc_ast_passes/src/errors.rs | 9 +-- tests/ui/auto-traits/assoc-ty.current.stderr | 2 +- tests/ui/auto-traits/assoc-ty.next.stderr | 2 +- .../auto-traits/auto-trait-validation.fixed | 11 ++++ tests/ui/auto-traits/auto-trait-validation.rs | 15 +++++ .../auto-traits/auto-trait-validation.stderr | 65 ++++++++++++++++--- .../ui/auto-traits/bad-generics-on-dyn.stderr | 2 +- tests/ui/auto-traits/has-arguments.stderr | 2 +- tests/ui/auto-traits/issue-117789.stderr | 2 +- .../auto-traits/issue-23080-2.current.stderr | 2 +- .../ui/auto-traits/issue-23080-2.next.stderr | 2 +- tests/ui/auto-traits/issue-23080.stderr | 11 ++-- tests/ui/auto-traits/issue-84075.stderr | 2 +- .../typeck-auto-trait-no-supertraits-2.stderr | 6 +- .../typeck-auto-trait-no-supertraits.stderr | 4 +- tests/ui/methods/issues/issue-105732.stderr | 2 +- .../supertrait-auto-trait.stderr | 4 +- 19 files changed, 118 insertions(+), 43 deletions(-) diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index af93d55c8982..9b9c1105e47f 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -40,7 +40,7 @@ ast_passes_auto_generic = auto traits cannot have generic parameters ast_passes_auto_items = auto traits cannot have associated items .label = {ast_passes_auto_items} - .suggestion = remove these associated items + .suggestion = remove the associated items ast_passes_auto_super_lifetime = auto traits cannot have super traits or lifetime bounds .label = {ast_passes_auto_super_lifetime} diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 895a457ec1d5..e99e5cc4ae65 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -699,19 +699,23 @@ impl<'a> AstValidator<'a> { } } - fn deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) { + fn deny_super_traits(&self, bounds: &GenericBounds, ident: Span) { if let [.., last] = &bounds[..] { - let span = ident_span.shrink_to_hi().to(last.span()); - self.dcx().emit_err(errors::AutoTraitBounds { span, ident: ident_span }); + let span = bounds.iter().map(|b| b.span()).collect(); + let removal = ident.shrink_to_hi().to(last.span()); + self.dcx().emit_err(errors::AutoTraitBounds { span, removal, ident }); } } - fn deny_where_clause(&self, where_clause: &WhereClause, ident_span: Span) { + fn deny_where_clause(&self, where_clause: &WhereClause, ident: Span) { if !where_clause.predicates.is_empty() { // FIXME: The current diagnostic is misleading since it only talks about // super trait and lifetime bounds while we should just say “bounds”. - self.dcx() - .emit_err(errors::AutoTraitBounds { span: where_clause.span, ident: ident_span }); + self.dcx().emit_err(errors::AutoTraitBounds { + span: vec![where_clause.span], + removal: where_clause.span, + ident, + }); } } diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index fd4b2528541e..2e3b1510755f 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -344,7 +344,7 @@ pub(crate) struct ModuleNonAscii { #[diag(ast_passes_auto_generic, code = E0567)] pub(crate) struct AutoTraitGeneric { #[primary_span] - #[suggestion(code = "", applicability = "machine-applicable")] + #[suggestion(code = "", applicability = "machine-applicable", style = "tool-only")] pub span: Span, #[label] pub ident: Span, @@ -354,8 +354,9 @@ pub(crate) struct AutoTraitGeneric { #[diag(ast_passes_auto_super_lifetime, code = E0568)] pub(crate) struct AutoTraitBounds { #[primary_span] - #[suggestion(code = "", applicability = "machine-applicable")] - pub span: Span, + pub span: Vec, + #[suggestion(code = "", applicability = "machine-applicable", style = "tool-only")] + pub removal: Span, #[label] pub ident: Span, } @@ -365,7 +366,7 @@ pub(crate) struct AutoTraitBounds { pub(crate) struct AutoTraitItems { #[primary_span] pub spans: Vec, - #[suggestion(code = "", applicability = "machine-applicable")] + #[suggestion(code = "", applicability = "machine-applicable", style = "tool-only")] pub total: Span, #[label] pub ident: Span, diff --git a/tests/ui/auto-traits/assoc-ty.current.stderr b/tests/ui/auto-traits/assoc-ty.current.stderr index 77a1c8fb654f..d793ae665267 100644 --- a/tests/ui/auto-traits/assoc-ty.current.stderr +++ b/tests/ui/auto-traits/assoc-ty.current.stderr @@ -5,7 +5,7 @@ LL | auto trait Trait { | ----- auto traits cannot have associated items LL | LL | type Output; - | -----^^^^^^- help: remove these associated items + | ^^^^^^ error[E0658]: auto traits are experimental and possibly buggy --> $DIR/assoc-ty.rs:8:1 diff --git a/tests/ui/auto-traits/assoc-ty.next.stderr b/tests/ui/auto-traits/assoc-ty.next.stderr index 4ce00d174756..a41f7d992785 100644 --- a/tests/ui/auto-traits/assoc-ty.next.stderr +++ b/tests/ui/auto-traits/assoc-ty.next.stderr @@ -5,7 +5,7 @@ LL | auto trait Trait { | ----- auto traits cannot have associated items LL | LL | type Output; - | -----^^^^^^- help: remove these associated items + | ^^^^^^ error[E0658]: auto traits are experimental and possibly buggy --> $DIR/assoc-ty.rs:8:1 diff --git a/tests/ui/auto-traits/auto-trait-validation.fixed b/tests/ui/auto-traits/auto-trait-validation.fixed index 8a445448c858..b24dc1cb2c3d 100644 --- a/tests/ui/auto-traits/auto-trait-validation.fixed +++ b/tests/ui/auto-traits/auto-trait-validation.fixed @@ -11,4 +11,15 @@ auto trait LifetimeBound {} //~^ ERROR auto traits cannot have super traits or lifetime bounds [E0568] auto trait MyTrait { } //~^ ERROR auto traits cannot have associated items [E0380] +auto trait AssocTy { } +//~^ ERROR auto traits cannot have associated items [E0380] +auto trait All { + //~^ ERROR auto traits cannot have generic parameters [E0567] + +} +// We can't test both generic params and super-traits because the suggestion span overlaps. +auto trait All2 { + //~^ ERROR auto traits cannot have super traits or lifetime bounds [E0568] + +} fn main() {} diff --git a/tests/ui/auto-traits/auto-trait-validation.rs b/tests/ui/auto-traits/auto-trait-validation.rs index b5e7505d86a2..9665e5bc3932 100644 --- a/tests/ui/auto-traits/auto-trait-validation.rs +++ b/tests/ui/auto-traits/auto-trait-validation.rs @@ -11,4 +11,19 @@ auto trait LifetimeBound : 'static {} //~^ ERROR auto traits cannot have super traits or lifetime bounds [E0568] auto trait MyTrait { fn foo() {} } //~^ ERROR auto traits cannot have associated items [E0380] +auto trait AssocTy { type Bar; } +//~^ ERROR auto traits cannot have associated items [E0380] +auto trait All<'a, T> { + //~^ ERROR auto traits cannot have generic parameters [E0567] + type Bar; + //~^ ERROR auto traits cannot have associated items [E0380] + fn foo() {} +} +// We can't test both generic params and super-traits because the suggestion span overlaps. +auto trait All2: Copy + 'static { + //~^ ERROR auto traits cannot have super traits or lifetime bounds [E0568] + type Bar; + //~^ ERROR auto traits cannot have associated items [E0380] + fn foo() {} +} fn main() {} diff --git a/tests/ui/auto-traits/auto-trait-validation.stderr b/tests/ui/auto-traits/auto-trait-validation.stderr index a6e5ac54869d..60757db6d1ed 100644 --- a/tests/ui/auto-traits/auto-trait-validation.stderr +++ b/tests/ui/auto-traits/auto-trait-validation.stderr @@ -2,23 +2,23 @@ error[E0567]: auto traits cannot have generic parameters --> $DIR/auto-trait-validation.rs:6:19 | LL | auto trait Generic {} - | -------^^^ help: remove the parameters + | -------^^^ | | | auto trait cannot have generic parameters error[E0568]: auto traits cannot have super traits or lifetime bounds - --> $DIR/auto-trait-validation.rs:8:17 + --> $DIR/auto-trait-validation.rs:8:20 | LL | auto trait Bound : Copy {} - | -----^^^^^^^ help: remove the super traits or lifetime bounds + | ----- ^^^^ | | | auto traits cannot have super traits or lifetime bounds error[E0568]: auto traits cannot have super traits or lifetime bounds - --> $DIR/auto-trait-validation.rs:10:25 + --> $DIR/auto-trait-validation.rs:10:28 | LL | auto trait LifetimeBound : 'static {} - | -------------^^^^^^^^^^ help: remove the super traits or lifetime bounds + | ------------- ^^^^^^^ | | | auto traits cannot have super traits or lifetime bounds @@ -26,12 +26,59 @@ error[E0380]: auto traits cannot have associated items --> $DIR/auto-trait-validation.rs:12:25 | LL | auto trait MyTrait { fn foo() {} } - | ------- ---^^^----- - | | | - | | help: remove these associated items + | ------- ^^^ + | | + | auto traits cannot have associated items + +error[E0380]: auto traits cannot have associated items + --> $DIR/auto-trait-validation.rs:14:27 + | +LL | auto trait AssocTy { type Bar; } + | ------- ^^^ + | | | auto traits cannot have associated items -error: aborting due to 4 previous errors +error[E0567]: auto traits cannot have generic parameters + --> $DIR/auto-trait-validation.rs:16:15 + | +LL | auto trait All<'a, T> { + | ---^^^^^^^ + | | + | auto trait cannot have generic parameters + +error[E0380]: auto traits cannot have associated items + --> $DIR/auto-trait-validation.rs:18:10 + | +LL | auto trait All<'a, T> { + | --- auto traits cannot have associated items +LL | +LL | type Bar; + | ^^^ +LL | +LL | fn foo() {} + | ^^^ + +error[E0568]: auto traits cannot have super traits or lifetime bounds + --> $DIR/auto-trait-validation.rs:23:18 + | +LL | auto trait All2: Copy + 'static { + | ---- ^^^^ ^^^^^^^ + | | + | auto traits cannot have super traits or lifetime bounds + +error[E0380]: auto traits cannot have associated items + --> $DIR/auto-trait-validation.rs:25:10 + | +LL | auto trait All2: Copy + 'static { + | ---- auto traits cannot have associated items +LL | +LL | type Bar; + | ^^^ +LL | +LL | fn foo() {} + | ^^^ + +error: aborting due to 9 previous errors Some errors have detailed explanations: E0380, E0567, E0568. For more information about an error, try `rustc --explain E0380`. diff --git a/tests/ui/auto-traits/bad-generics-on-dyn.stderr b/tests/ui/auto-traits/bad-generics-on-dyn.stderr index 06c7cbcd76da..a6977c2037e7 100644 --- a/tests/ui/auto-traits/bad-generics-on-dyn.stderr +++ b/tests/ui/auto-traits/bad-generics-on-dyn.stderr @@ -2,7 +2,7 @@ error[E0567]: auto traits cannot have generic parameters --> $DIR/bad-generics-on-dyn.rs:3:18 | LL | auto trait Trait1<'a> {} - | ------^^^^ help: remove the parameters + | ------^^^^ | | | auto trait cannot have generic parameters diff --git a/tests/ui/auto-traits/has-arguments.stderr b/tests/ui/auto-traits/has-arguments.stderr index b8a680e6a5ca..5228b6d2d1ac 100644 --- a/tests/ui/auto-traits/has-arguments.stderr +++ b/tests/ui/auto-traits/has-arguments.stderr @@ -2,7 +2,7 @@ error[E0567]: auto traits cannot have generic parameters --> $DIR/has-arguments.rs:3:18 | LL | auto trait Trait1<'outer> {} - | ------^^^^^^^^ help: remove the parameters + | ------^^^^^^^^ | | | auto trait cannot have generic parameters diff --git a/tests/ui/auto-traits/issue-117789.stderr b/tests/ui/auto-traits/issue-117789.stderr index 99efb2134175..1e047c7d2e07 100644 --- a/tests/ui/auto-traits/issue-117789.stderr +++ b/tests/ui/auto-traits/issue-117789.stderr @@ -2,7 +2,7 @@ error[E0567]: auto traits cannot have generic parameters --> $DIR/issue-117789.rs:1:17 | LL | auto trait Trait