From e836a2f5ff6d3317db06891feb3087e6164c282b Mon Sep 17 00:00:00 2001 From: Jonathan Gruner Date: Thu, 24 Apr 2025 21:14:47 +0200 Subject: [PATCH 001/809] 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 002/809] 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 8c6eea85a171bdd54811f5562884e8e706da34ce Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Sat, 8 Feb 2025 19:47:27 -0500 Subject: [PATCH 003/809] 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 004/809] 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 005/809] 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 006/809] 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 30721b0e909d7451a37bbb4ae371e1c909a0cbaf Mon Sep 17 00:00:00 2001 From: jyn Date: Mon, 26 May 2025 20:10:17 -0400 Subject: [PATCH 007/809] 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 9e9c9170a50ba34a3cb66540a2079884b92ed480 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Sun, 8 Jun 2025 00:49:00 +0800 Subject: [PATCH 008/809] 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 009/809] 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 | 27 ++++++++++++++----- tests/ui/iter_on_single_items.rs | 27 ++++++++++++++----- 3 files changed, 44 insertions(+), 16 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!() - } - some_func(Some(5).into_iter()); + fn takes_into_iter(_: impl IntoIterator) {} - const C: fn(IntoIter) -> IntoIter = as IntoIterator>::into_iter; - C(Some(5).into_iter()); + fn let_stmt() { + macro_rules! x { + ($e:expr) => { + let _: IntoIter = $e; + }; + } + x!(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!() - } - some_func(Some(5).into_iter()); + fn takes_into_iter(_: impl IntoIterator) {} - const C: fn(IntoIter) -> IntoIter = as IntoIterator>::into_iter; - C(Some(5).into_iter()); + fn let_stmt() { + macro_rules! x { + ($e:expr) => { + let _: IntoIter = $e; + }; + } + x!(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 010/809] 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 011/809] 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 012/809] 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 013/809] 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 014/809] 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 31b9de6965d955bc95d107ed2e58a75a3d902488 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Fri, 20 Jun 2025 15:49:14 +0800 Subject: [PATCH 015/809] 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())), + })); + + 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; + } } - // 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); - } + 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 016/809] 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 017/809] 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 fa5895ea8c39cb2d8f7078ccd4e78a41aeb2eb84 Mon Sep 17 00:00:00 2001 From: Boxy Date: Wed, 25 Jun 2025 12:29:04 +0100 Subject: [PATCH 018/809] 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 019/809] 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 0920486fa6c0a3c08e23a867b1e6ca6a5563849b Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Sun, 29 Jun 2025 22:28:39 +0200 Subject: [PATCH 020/809] 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 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 021/809] 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 022/809] 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 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 023/809] 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 024/809] 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 025/809] 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 026/809] 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 027/809] 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 028/809] 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 029/809] 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 030/809] 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 031/809] 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 222ebd0535bcaeda021702bef63e25cfcaa47e5b Mon Sep 17 00:00:00 2001 From: yanglsh Date: Wed, 25 Jun 2025 21:27:02 +0800 Subject: [PATCH 032/809] 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 033/809] 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 e55baf9f7ada72ed9f661194065154a09aab3a9e Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 2 Jul 2025 11:12:54 +0200 Subject: [PATCH 034/809] 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 b7d27822e3e295c34aacf389962ebe872697b9f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 17 Jul 2025 09:15:17 +0200 Subject: [PATCH 035/809] Remove install Rust script from CI Windows ARM images should contain Rust now. --- .github/workflows/ci.yml | 3 --- src/ci/scripts/install-rust.sh | 15 --------------- 2 files changed, 18 deletions(-) delete mode 100755 src/ci/scripts/install-rust.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc8ac539a3a0..9d0278739281 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -152,9 +152,6 @@ jobs: - name: show the current environment run: src/ci/scripts/dump-environment.sh - - name: install rust - run: src/ci/scripts/install-rust.sh - - name: install awscli run: src/ci/scripts/install-awscli.sh diff --git a/src/ci/scripts/install-rust.sh b/src/ci/scripts/install-rust.sh deleted file mode 100755 index e4aee98c9fb2..000000000000 --- a/src/ci/scripts/install-rust.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -# The Arm64 Windows Runner does not have Rust already installed -# https://github.com/actions/partner-runner-images/issues/77 - -set -euo pipefail -IFS=$'\n\t' - -source "$(cd "$(dirname "$0")" && pwd)/../shared.sh" - -if [[ "${CI_JOB_NAME}" = *aarch64* ]] && isWindows; then - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \ - sh -s -- -y -q --default-host aarch64-pc-windows-msvc - ciCommandAddPath "${USERPROFILE}/.cargo/bin" -fi From 48df86f37ddf2904b60f31744e52f56234e4d95c Mon Sep 17 00:00:00 2001 From: yanglsh Date: Tue, 15 Jul 2025 22:55:41 +0800 Subject: [PATCH 036/809] 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 037/809] 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 038/809] 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 039/809] 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 040/809] 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 | 31 +-- .../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, 200 insertions(+), 195 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; +fn runner_command(runner: &str) -> Command { + let mut it = runner.split_whitespace(); + let mut cmd = Command::new(it.next().unwrap()); + cmd.args(it); + + cmd +} + 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); - - cmd - } - 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()); +) -> std::io::Result<()> { + let Some(current) = constraints.next() else { + return generate_rust_test_loop(w, intrinsic, indentation, &name, PASSES); + }; - 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) + 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 { - let arguments = intrinsic.arguments(); - let constraints = arguments - .iter() - .filter(|i| i.has_constraint()) - .collect_vec(); - +) -> std::io::Result<()> { + trace!("generating `{}`", intrinsic.name()); 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(), - ) + + writeln!(w, "pub fn run_{}() {{", intrinsic.name())?; + + // Define the arrays of arguments. + let arguments = intrinsic.arguments(); + 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(), + )?; + + 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 041/809] 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 042/809] 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 043/809] 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 | 124 ++++++++++-------- .../src/common/intrinsic_helpers.rs | 3 - 4 files changed, 72 insertions(+), 82 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); - }; +/// 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![]]; - 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}}}")?; + 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 044/809] 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 045/809] fix `collapsable_else_if` when the inner `if` is in parens --- clippy_lints/src/collapsible_if.rs | 56 ++++++++++++++--------------- 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, 104 insertions(+), 29 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(); - - continue; - } - - break; + 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(); } - (start.with_hi(span.lo()), - span, - end.with_lo(span.hi())) + (start.with_hi(span.lo()), span, end.with_lo(span.hi())) +} + +fn peel_parens_str(snippet: &str) -> Option<(usize, &str, usize)> { + let trimmed = snippet.trim(); + if !(trimmed.starts_with('(') && trimmed.ends_with(')')) { + return None; + } + + 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 8acdee7bab65254f7cfc8f5e03ad180e65a45e9b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 19 Jul 2025 13:16:42 +0200 Subject: [PATCH 046/809] don't halt execution when we write to a read-only file --- src/tools/miri/src/shims/files.rs | 11 ++++++++++- src/tools/miri/tests/pass/shims/fs.rs | 4 ++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/tools/miri/src/shims/files.rs b/src/tools/miri/src/shims/files.rs index 606d1ffbea6c..f7419b6bca29 100644 --- a/src/tools/miri/src/shims/files.rs +++ b/src/tools/miri/src/shims/files.rs @@ -1,7 +1,7 @@ use std::any::Any; use std::collections::BTreeMap; use std::fs::{File, Metadata}; -use std::io::{IsTerminal, Seek, SeekFrom, Write}; +use std::io::{ErrorKind, IsTerminal, Seek, SeekFrom, Write}; use std::marker::CoercePointee; use std::ops::Deref; use std::rc::{Rc, Weak}; @@ -334,6 +334,15 @@ impl FileDescription for FileHandle { ) -> InterpResult<'tcx> { assert!(communicate_allowed, "isolation should have prevented even opening a file"); + if !self.writable { + // Linux hosts return EBADF here which we can't translate via the platform-independent + // code since it does not map to any `io::ErrorKind` -- so if we don't do anything + // special, we'd throw an "unsupported error code" here. Windows returns something that + // gets translated to `PermissionDenied`. That seems like a good value so let's just use + // this everywhere, even if it means behavior on Unix targets does not match the real + // thing. + return finish.call(ecx, Err(ErrorKind::PermissionDenied.into())); + } let result = ecx.write_to_host(&self.file, len, ptr)?; finish.call(ecx, result) } diff --git a/src/tools/miri/tests/pass/shims/fs.rs b/src/tools/miri/tests/pass/shims/fs.rs index 9d5725773e64..5e54cc382381 100644 --- a/src/tools/miri/tests/pass/shims/fs.rs +++ b/src/tools/miri/tests/pass/shims/fs.rs @@ -66,6 +66,10 @@ fn test_file() { assert!(!file.is_terminal()); + // Writing to a file opened for reading should error (and not stop interpretation). std does not + // categorize the error so we don't check for details. + file.write(&[]).unwrap_err(); + // Removing file should succeed. remove_file(&path).unwrap(); } From fe420251223e50b17577aad1e146ee66ec653a15 Mon Sep 17 00:00:00 2001 From: usamoi Date: Thu, 17 Jul 2025 20:50:49 +0800 Subject: [PATCH 047/809] update `Atomic*::from_ptr` and `Atomic*::as_ptr` docs --- library/core/src/sync/atomic.rs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 04c8d1473b04..c010b4d5a0b7 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -563,8 +563,8 @@ impl AtomicBool { /// `align_of::() == 1`). /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not - /// allowed to mix atomic and non-atomic accesses, or atomic accesses of different sizes, - /// without synchronization. + /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different + /// sizes, without synchronization. /// /// [valid]: crate::ptr#safety /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses @@ -1246,7 +1246,7 @@ impl AtomicBool { /// atomic types work with interior mutability. All modifications of an atomic change the value /// through a shared reference, and can do so safely as long as they use atomic operations. Any /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same - /// restriction: operations on it must be atomic. + /// restriction in [Memory model for atomic accesses]. /// /// # Examples /// @@ -1264,6 +1264,8 @@ impl AtomicBool { /// } /// # } /// ``` + /// + /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses #[inline] #[stable(feature = "atomic_as_ptr", since = "1.70.0")] #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] @@ -1519,8 +1521,8 @@ impl AtomicPtr { /// can be bigger than `align_of::<*mut T>()`). /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not - /// allowed to mix atomic and non-atomic accesses, or atomic accesses of different sizes, - /// without synchronization. + /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different + /// sizes, without synchronization. /// /// [valid]: crate::ptr#safety /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses @@ -2488,7 +2490,7 @@ impl AtomicPtr { /// atomic types work with interior mutability. All modifications of an atomic change the value /// through a shared reference, and can do so safely as long as they use atomic operations. Any /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same - /// restriction: operations on it must be atomic. + /// restriction in [Memory model for atomic accesses]. /// /// # Examples /// @@ -2507,6 +2509,8 @@ impl AtomicPtr { /// my_atomic_op(atomic.as_ptr()); /// } /// ``` + /// + /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses #[inline] #[stable(feature = "atomic_as_ptr", since = "1.70.0")] #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] @@ -2696,8 +2700,8 @@ macro_rules! atomic_int { }] /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not - /// allowed to mix atomic and non-atomic accesses, or atomic accesses of different sizes, - /// without synchronization. + /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different + /// sizes, without synchronization. /// /// [valid]: crate::ptr#safety /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses @@ -3618,7 +3622,7 @@ macro_rules! atomic_int { /// atomic types work with interior mutability. All modifications of an atomic change the value /// through a shared reference, and can do so safely as long as they use atomic operations. Any /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same - /// restriction: operations on it must be atomic. + /// restriction in [Memory model for atomic accesses]. /// /// # Examples /// @@ -3638,6 +3642,8 @@ macro_rules! atomic_int { /// } /// # } /// ``` + /// + /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses #[inline] #[stable(feature = "atomic_as_ptr", since = "1.70.0")] #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] From 5b2c61edbe508163ad11cde0f35278417d7c26b3 Mon Sep 17 00:00:00 2001 From: Alisa Sireneva Date: Sat, 19 Jul 2025 18:18:01 +0300 Subject: [PATCH 048/809] 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 d3fc02caf5798f3af0e5294aee804496a480aa3e Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 19 Jul 2025 13:16:23 +0200 Subject: [PATCH 049/809] non-deterministically truncate reads/writes --- src/tools/miri/src/shims/files.rs | 5 ++ src/tools/miri/src/shims/unix/fd.rs | 21 ++++- .../miri/src/shims/unix/linux_like/eventfd.rs | 5 ++ src/tools/miri/src/shims/windows/fs.rs | 22 ++--- .../fail-dep/libc/libc-epoll-data-race.rs | 7 +- .../libc-read-and-uninit-premature-eof.rs | 8 +- .../libc/libc_epoll_block_two_thread.rs | 3 +- .../libc/socketpair_block_read_twice.rs | 25 +++--- .../libc/socketpair_block_read_twice.stderr | 4 +- .../libc/socketpair_block_write_twice.rs | 29 ++++--- .../libc/socketpair_block_write_twice.stderr | 4 +- .../pass-dep/libc/libc-epoll-blocking.rs | 7 +- .../pass-dep/libc/libc-epoll-no-blocking.rs | 44 +++++----- src/tools/miri/tests/pass-dep/libc/libc-fs.rs | 49 +++++++---- .../miri/tests/pass-dep/libc/libc-pipe.rs | 42 ++++++---- .../tests/pass-dep/libc/libc-socketpair.rs | 81 ++++++++++++------- src/tools/miri/tests/pass/shims/fs.rs | 28 ++++++- src/tools/miri/tests/pass/shims/pipe.rs | 4 +- src/tools/miri/tests/utils/fs.rs | 2 +- src/tools/miri/tests/utils/libc.rs | 44 ++++++++++ 20 files changed, 312 insertions(+), 122 deletions(-) create mode 100644 src/tools/miri/tests/utils/libc.rs diff --git a/src/tools/miri/src/shims/files.rs b/src/tools/miri/src/shims/files.rs index f7419b6bca29..0d4642c6ad0e 100644 --- a/src/tools/miri/src/shims/files.rs +++ b/src/tools/miri/src/shims/files.rs @@ -167,6 +167,11 @@ pub trait FileDescription: std::fmt::Debug + FileDescriptionExt { throw_unsup_format!("cannot write to {}", self.name()); } + /// Determines whether this FD non-deterministically has its reads and writes shortened. + fn nondet_short_accesses(&self) -> bool { + true + } + /// Seeks to the given offset (which can be relative to the beginning, end, or current position). /// Returns the new position from the start of the stream. fn seek<'tcx>( diff --git a/src/tools/miri/src/shims/unix/fd.rs b/src/tools/miri/src/shims/unix/fd.rs index 71102d9f2f33..b420955501c8 100644 --- a/src/tools/miri/src/shims/unix/fd.rs +++ b/src/tools/miri/src/shims/unix/fd.rs @@ -4,6 +4,7 @@ use std::io; use std::io::ErrorKind; +use rand::Rng; use rustc_abi::Size; use crate::helpers::check_min_vararg_count; @@ -263,9 +264,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return this.set_last_error_and_return(LibcError("EBADF"), dest); }; + // Non-deterministically decide to further reduce the count, simulating a partial read (but + // never to 0, that has different behavior). + let count = + if fd.nondet_short_accesses() && count >= 2 && this.machine.rng.get_mut().random() { + count / 2 + } else { + count + }; + trace!("read: FD mapped to {fd:?}"); // We want to read at most `count` bytes. We are sure that `count` is not negative - // because it was a target's `usize`. Also we are sure that its smaller than + // because it was a target's `usize`. Also we are sure that it's smaller than // `usize::MAX` because it is bounded by the host's `isize`. let finish = { @@ -328,6 +338,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return this.set_last_error_and_return(LibcError("EBADF"), dest); }; + // Non-deterministically decide to further reduce the count, simulating a partial write (but + // never to 0, that has different behavior). + let count = + if fd.nondet_short_accesses() && count >= 2 && this.machine.rng.get_mut().random() { + count / 2 + } else { + count + }; + let finish = { let dest = dest.clone(); callback!( diff --git a/src/tools/miri/src/shims/unix/linux_like/eventfd.rs b/src/tools/miri/src/shims/unix/linux_like/eventfd.rs index ee7deb8d3830..2d35ef064db8 100644 --- a/src/tools/miri/src/shims/unix/linux_like/eventfd.rs +++ b/src/tools/miri/src/shims/unix/linux_like/eventfd.rs @@ -37,6 +37,11 @@ impl FileDescription for EventFd { "event" } + fn nondet_short_accesses(&self) -> bool { + // We always read and write exactly one `u64`. + false + } + fn close<'tcx>( self, _communicate_allowed: bool, diff --git a/src/tools/miri/src/shims/windows/fs.rs b/src/tools/miri/src/shims/windows/fs.rs index 72e016c12e94..e4ec1b0130c9 100644 --- a/src/tools/miri/src/shims/windows/fs.rs +++ b/src/tools/miri/src/shims/windows/fs.rs @@ -462,6 +462,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; let io_status_info = this.project_field_named(&io_status_block, "Information")?; + // It seems like short writes are not a thing on Windows, so we don't truncate `count` here. + // FIXME: if we are on a Unix host, short host writes are still visible to the program! + let finish = { let io_status = io_status.clone(); let io_status_info = io_status_info.clone(); @@ -491,7 +494,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }} ) }; - desc.write(this.machine.communicate(), buf, count.try_into().unwrap(), this, finish)?; // Return status is written to `dest` and `io_status_block` on callback completion. @@ -556,6 +558,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; let io_status_info = this.project_field_named(&io_status_block, "Information")?; + let fd = match handle { + Handle::File(fd) => fd, + _ => this.invalid_handle("NtWriteFile")?, + }; + + let Some(desc) = this.machine.fds.get(fd) else { this.invalid_handle("NtReadFile")? }; + + // It seems like short reads are not a thing on Windows, so we don't truncate `count` here. + // FIXME: if we are on a Unix host, short host reads are still visible to the program! + let finish = { let io_status = io_status.clone(); let io_status_info = io_status_info.clone(); @@ -585,14 +597,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }} ) }; - - let fd = match handle { - Handle::File(fd) => fd, - _ => this.invalid_handle("NtWriteFile")?, - }; - - let Some(desc) = this.machine.fds.get(fd) else { this.invalid_handle("NtReadFile")? }; - desc.read(this.machine.communicate(), buf, count.try_into().unwrap(), this, finish)?; // See NtWriteFile for commentary on this diff --git a/src/tools/miri/tests/fail-dep/libc/libc-epoll-data-race.rs b/src/tools/miri/tests/fail-dep/libc/libc-epoll-data-race.rs index 314ce90cfb5d..f6ec5be61bb6 100644 --- a/src/tools/miri/tests/fail-dep/libc/libc-epoll-data-race.rs +++ b/src/tools/miri/tests/fail-dep/libc/libc-epoll-data-race.rs @@ -10,6 +10,9 @@ use std::convert::TryInto; use std::thread; use std::thread::spawn; +#[path = "../../utils/libc.rs"] +mod libc_utils; + #[track_caller] fn check_epoll_wait(epfd: i32, expected_notifications: &[(u32, u64)]) { let epoll_event = libc::epoll_event { events: 0, u64: 0 }; @@ -69,12 +72,12 @@ fn main() { unsafe { VAL_ONE = 41 }; let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds_a[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds_a[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); unsafe { VAL_TWO = 51 }; - let res = unsafe { libc::write(fds_b[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds_b[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); }); thread::yield_now(); diff --git a/src/tools/miri/tests/fail-dep/libc/libc-read-and-uninit-premature-eof.rs b/src/tools/miri/tests/fail-dep/libc/libc-read-and-uninit-premature-eof.rs index 1dc334486c3a..e2fd6463a116 100644 --- a/src/tools/miri/tests/fail-dep/libc/libc-read-and-uninit-premature-eof.rs +++ b/src/tools/miri/tests/fail-dep/libc/libc-read-and-uninit-premature-eof.rs @@ -10,6 +10,9 @@ use std::mem::MaybeUninit; #[path = "../../utils/mod.rs"] mod utils; +#[path = "../../utils/libc.rs"] +mod libc_utils; + fn main() { let path = utils::prepare_with_content("fail-libc-read-and-uninit-premature-eof.txt", &[1u8, 2, 3]); @@ -18,8 +21,9 @@ fn main() { let fd = libc::open(cpath.as_ptr(), libc::O_RDONLY); assert_ne!(fd, -1); let mut buf: MaybeUninit<[u8; 4]> = std::mem::MaybeUninit::uninit(); - // Read 4 bytes from a 3-byte file. - assert_eq!(libc::read(fd, buf.as_mut_ptr().cast::(), 4), 3); + // Read as much as we can from a 3-byte file. + let res = libc_utils::read_all(fd, buf.as_mut_ptr().cast::(), 4); + assert!(res == 3); buf.assume_init(); //~ERROR: encountered uninitialized memory, but expected an integer assert_eq!(libc::close(fd), 0); } diff --git a/src/tools/miri/tests/fail-dep/libc/libc_epoll_block_two_thread.rs b/src/tools/miri/tests/fail-dep/libc/libc_epoll_block_two_thread.rs index f6f2e2b93121..054cb812d9e8 100644 --- a/src/tools/miri/tests/fail-dep/libc/libc_epoll_block_two_thread.rs +++ b/src/tools/miri/tests/fail-dep/libc/libc_epoll_block_two_thread.rs @@ -75,9 +75,10 @@ fn main() { }); let thread3 = spawn(move || { + // Just a single write, so we only wake up one of them. let data = "abcde".as_bytes().as_ptr(); let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; - assert_eq!(res, 5); + assert!(res > 0 && res <= 5); }); thread1.join().unwrap(); diff --git a/src/tools/miri/tests/fail-dep/libc/socketpair_block_read_twice.rs b/src/tools/miri/tests/fail-dep/libc/socketpair_block_read_twice.rs index b38398595002..0fecfb8f663f 100644 --- a/src/tools/miri/tests/fail-dep/libc/socketpair_block_read_twice.rs +++ b/src/tools/miri/tests/fail-dep/libc/socketpair_block_read_twice.rs @@ -4,6 +4,7 @@ // test_race depends on a deterministic schedule. //@compile-flags: -Zmiri-deterministic-concurrency //@error-in-other-file: deadlock +//@require-annotations-for-level: error use std::thread; @@ -22,24 +23,26 @@ fn main() { assert_eq!(res, 0); let thread1 = thread::spawn(move || { // Let this thread block on read. - let mut buf: [u8; 3] = [0; 3]; + let mut buf: [u8; 1] = [0; 1]; let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; - assert_eq!(res, 3); - assert_eq!(&buf, "abc".as_bytes()); + assert_eq!(res, buf.len().cast_signed()); + assert_eq!(&buf, "a".as_bytes()); }); let thread2 = thread::spawn(move || { // Let this thread block on read. - let mut buf: [u8; 3] = [0; 3]; - let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; - //~^ERROR: deadlocked - assert_eq!(res, 3); - assert_eq!(&buf, "abc".as_bytes()); + let mut buf: [u8; 1] = [0; 1]; + let res = unsafe { + libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) + //~^ERROR: deadlock + }; + assert_eq!(res, buf.len().cast_signed()); + assert_eq!(&buf, "a".as_bytes()); }); let thread3 = thread::spawn(move || { // Unblock thread1 by writing something. - let data = "abc".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 3) }; - assert_eq!(res, 3); + let data = "a".as_bytes(); + let res = unsafe { libc::write(fds[0], data.as_ptr() as *const libc::c_void, data.len()) }; + assert_eq!(res, data.len().cast_signed()); }); thread1.join().unwrap(); thread2.join().unwrap(); diff --git a/src/tools/miri/tests/fail-dep/libc/socketpair_block_read_twice.stderr b/src/tools/miri/tests/fail-dep/libc/socketpair_block_read_twice.stderr index 9f19a60e6ae2..99d242ec7daf 100644 --- a/src/tools/miri/tests/fail-dep/libc/socketpair_block_read_twice.stderr +++ b/src/tools/miri/tests/fail-dep/libc/socketpair_block_read_twice.stderr @@ -23,8 +23,8 @@ error: the evaluated program deadlocked error: the evaluated program deadlocked --> tests/fail-dep/libc/socketpair_block_read_twice.rs:LL:CC | -LL | let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; - | ^ this thread got stuck here +LL | libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) + | ^ this thread got stuck here | = note: BACKTRACE on thread `unnamed-ID`: = note: inside closure at tests/fail-dep/libc/socketpair_block_read_twice.rs:LL:CC diff --git a/src/tools/miri/tests/fail-dep/libc/socketpair_block_write_twice.rs b/src/tools/miri/tests/fail-dep/libc/socketpair_block_write_twice.rs index 7d84d87ebbb1..048938c091e3 100644 --- a/src/tools/miri/tests/fail-dep/libc/socketpair_block_write_twice.rs +++ b/src/tools/miri/tests/fail-dep/libc/socketpair_block_write_twice.rs @@ -4,16 +4,20 @@ // test_race depends on a deterministic schedule. //@compile-flags: -Zmiri-deterministic-concurrency //@error-in-other-file: deadlock +//@require-annotations-for-level: error use std::thread; +#[path = "../../utils/libc.rs"] +mod libc_utils; + // Test the behaviour of a thread being blocked on write, get unblocked, then blocked again. // The expected execution is // 1. Thread 1 blocks. // 2. Thread 2 blocks. // 3. Thread 3 unblocks both thread 1 and thread 2. -// 4. Thread 1 reads. +// 4. Thread 1 writes. // 5. Thread 2's `write` can never complete -> deadlocked. fn main() { let mut fds = [-1, -1]; @@ -21,27 +25,28 @@ fn main() { assert_eq!(res, 0); let arr1: [u8; 212992] = [1; 212992]; // Exhaust the space in the buffer so the subsequent write will block. - let res = unsafe { libc::write(fds[0], arr1.as_ptr() as *const libc::c_void, 212992) }; + let res = + unsafe { libc_utils::write_all(fds[0], arr1.as_ptr() as *const libc::c_void, 212992) }; assert_eq!(res, 212992); let thread1 = thread::spawn(move || { - let data = "abc".as_bytes().as_ptr(); + let data = "a".as_bytes(); // The write below will be blocked because the buffer is already full. - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 3) }; - assert_eq!(res, 3); + let res = unsafe { libc::write(fds[0], data.as_ptr() as *const libc::c_void, data.len()) }; + assert_eq!(res, data.len().cast_signed()); }); let thread2 = thread::spawn(move || { - let data = "abc".as_bytes().as_ptr(); + let data = "a".as_bytes(); // The write below will be blocked because the buffer is already full. - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 3) }; - //~^ERROR: deadlocked - assert_eq!(res, 3); + let res = unsafe { libc::write(fds[0], data.as_ptr() as *const libc::c_void, data.len()) }; + //~^ERROR: deadlock + assert_eq!(res, data.len().cast_signed()); }); let thread3 = thread::spawn(move || { // Unblock thread1 by freeing up some space. - let mut buf: [u8; 3] = [0; 3]; + let mut buf: [u8; 1] = [0; 1]; let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; - assert_eq!(res, 3); - assert_eq!(buf, [1, 1, 1]); + assert_eq!(res, buf.len().cast_signed()); + assert_eq!(buf, [1]); }); thread1.join().unwrap(); thread2.join().unwrap(); diff --git a/src/tools/miri/tests/fail-dep/libc/socketpair_block_write_twice.stderr b/src/tools/miri/tests/fail-dep/libc/socketpair_block_write_twice.stderr index b29cd70f35e4..f766500d331d 100644 --- a/src/tools/miri/tests/fail-dep/libc/socketpair_block_write_twice.stderr +++ b/src/tools/miri/tests/fail-dep/libc/socketpair_block_write_twice.stderr @@ -23,8 +23,8 @@ error: the evaluated program deadlocked error: the evaluated program deadlocked --> tests/fail-dep/libc/socketpair_block_write_twice.rs:LL:CC | -LL | let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 3) }; - | ^ this thread got stuck here +LL | let res = unsafe { libc::write(fds[0], data.as_ptr() as *const libc::c_void, data.len()) }; + | ^ this thread got stuck here | = note: BACKTRACE on thread `unnamed-ID`: = note: inside closure at tests/fail-dep/libc/socketpair_block_write_twice.rs:LL:CC diff --git a/src/tools/miri/tests/pass-dep/libc/libc-epoll-blocking.rs b/src/tools/miri/tests/pass-dep/libc/libc-epoll-blocking.rs index 54ebfa9d198d..c97206487a10 100644 --- a/src/tools/miri/tests/pass-dep/libc/libc-epoll-blocking.rs +++ b/src/tools/miri/tests/pass-dep/libc/libc-epoll-blocking.rs @@ -6,6 +6,9 @@ use std::convert::TryInto; use std::thread; use std::thread::spawn; +#[path = "../../utils/libc.rs"] +mod libc_utils; + // This is a set of testcases for blocking epoll. fn main() { @@ -97,7 +100,7 @@ fn test_epoll_block_then_unblock() { let thread1 = spawn(move || { thread::yield_now(); let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); }); check_epoll_wait::<1>(epfd, &[(expected_event, expected_value)], 10); @@ -130,7 +133,7 @@ fn test_notification_after_timeout() { // Trigger epoll notification after timeout. let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); // Check the result of the notification. diff --git a/src/tools/miri/tests/pass-dep/libc/libc-epoll-no-blocking.rs b/src/tools/miri/tests/pass-dep/libc/libc-epoll-no-blocking.rs index dc3ab2828faa..7130790b86d6 100644 --- a/src/tools/miri/tests/pass-dep/libc/libc-epoll-no-blocking.rs +++ b/src/tools/miri/tests/pass-dep/libc/libc-epoll-no-blocking.rs @@ -2,6 +2,9 @@ use std::convert::TryInto; +#[path = "../../utils/libc.rs"] +mod libc_utils; + fn main() { test_epoll_socketpair(); test_epoll_socketpair_both_sides(); @@ -64,7 +67,7 @@ fn test_epoll_socketpair() { // Write to fd[0] let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); // Register fd[1] with EPOLLIN|EPOLLOUT|EPOLLET|EPOLLRDHUP @@ -85,7 +88,7 @@ fn test_epoll_socketpair() { // Write some more to fd[0]. let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); // This did not change the readiness of fd[1]. And yet, we're seeing the event reported @@ -153,7 +156,7 @@ fn test_epoll_ctl_del() { // Write to fd[0] let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); // Register fd[1] with EPOLLIN|EPOLLOUT|EPOLLET @@ -182,7 +185,7 @@ fn test_two_epoll_instance() { // Write to the socketpair. let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); // Register one side of the socketpair with EPOLLIN | EPOLLOUT | EPOLLET. @@ -224,7 +227,7 @@ fn test_two_same_fd_in_same_epoll_instance() { // Write to the socketpair. let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); //Two notification should be received. @@ -243,7 +246,7 @@ fn test_epoll_eventfd() { // Write to the eventfd instance. let sized_8_data: [u8; 8] = 1_u64.to_ne_bytes(); - let res = unsafe { libc::write(fd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; + let res = unsafe { libc_utils::write_all(fd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; assert_eq!(res, 8); // Create an epoll instance. @@ -282,7 +285,7 @@ fn test_epoll_socketpair_both_sides() { // Write to fds[1]. let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); //Two notification should be received. @@ -297,7 +300,8 @@ fn test_epoll_socketpair_both_sides() { // Read from fds[0]. let mut buf: [u8; 5] = [0; 5]; - let res = unsafe { libc::read(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; assert_eq!(res, 5); assert_eq!(buf, "abcde".as_bytes()); @@ -325,7 +329,7 @@ fn test_closed_fd() { // Write to the eventfd instance. let sized_8_data: [u8; 8] = 1_u64.to_ne_bytes(); - let res = unsafe { libc::write(fd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; + let res = unsafe { libc_utils::write_all(fd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; assert_eq!(res, 8); // Close the eventfd. @@ -371,7 +375,8 @@ fn test_not_fully_closed_fd() { // Write to the eventfd instance to produce notification. let sized_8_data: [u8; 8] = 1_u64.to_ne_bytes(); - let res = unsafe { libc::write(newfd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; + let res = + unsafe { libc_utils::write_all(newfd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; assert_eq!(res, 8); // Close the dupped fd. @@ -391,7 +396,7 @@ fn test_event_overwrite() { // Write to the eventfd instance. let sized_8_data: [u8; 8] = 1_u64.to_ne_bytes(); - let res = unsafe { libc::write(fd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; + let res = unsafe { libc_utils::write_all(fd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; assert_eq!(res, 8); // Create an epoll instance. @@ -445,7 +450,7 @@ fn test_socketpair_read() { // Write 5 bytes to fds[1]. let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); //Two notification should be received. @@ -460,7 +465,8 @@ fn test_socketpair_read() { // Read 3 bytes from fds[0]. let mut buf: [u8; 3] = [0; 3]; - let res = unsafe { libc::read(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; assert_eq!(res, 3); assert_eq!(buf, "abc".as_bytes()); @@ -478,7 +484,8 @@ fn test_socketpair_read() { // Read until the buffer is empty. let mut buf: [u8; 2] = [0; 2]; - let res = unsafe { libc::read(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; assert_eq!(res, 2); assert_eq!(buf, "de".as_bytes()); @@ -510,8 +517,9 @@ fn test_no_notification_for_unregister_flag() { // Write to fd[1]. let data = "abcde".as_bytes().as_ptr(); - let res: i32 = - unsafe { libc::write(fds[1], data as *const libc::c_void, 5).try_into().unwrap() }; + let res: i32 = unsafe { + libc_utils::write_all(fds[1], data as *const libc::c_void, 5).try_into().unwrap() + }; assert_eq!(res, 5); // Check result from epoll_wait. Since we didn't register EPOLLIN flag, the notification won't @@ -546,7 +554,7 @@ fn test_socketpair_epollerr() { // Write to fd[0] let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); // Close fds[1]. @@ -717,6 +725,6 @@ fn test_issue_3858() { // Write to the eventfd instance. let sized_8_data: [u8; 8] = 1_u64.to_ne_bytes(); - let res = unsafe { libc::write(fd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; + let res = unsafe { libc_utils::write_all(fd, sized_8_data.as_ptr() as *const libc::c_void, 8) }; assert_eq!(res, 8); } diff --git a/src/tools/miri/tests/pass-dep/libc/libc-fs.rs b/src/tools/miri/tests/pass-dep/libc/libc-fs.rs index 0ff48c389e85..86cf2a041f06 100644 --- a/src/tools/miri/tests/pass-dep/libc/libc-fs.rs +++ b/src/tools/miri/tests/pass-dep/libc/libc-fs.rs @@ -14,6 +14,9 @@ use std::path::PathBuf; #[path = "../../utils/mod.rs"] mod utils; +#[path = "../../utils/libc.rs"] +mod libc_utils; + fn main() { test_dup(); test_dup_stdout_stderr(); @@ -74,8 +77,8 @@ fn test_dup_stdout_stderr() { unsafe { let new_stdout = libc::fcntl(1, libc::F_DUPFD, 0); let new_stderr = libc::fcntl(2, libc::F_DUPFD, 0); - libc::write(new_stdout, bytes.as_ptr() as *const libc::c_void, bytes.len()); - libc::write(new_stderr, bytes.as_ptr() as *const libc::c_void, bytes.len()); + libc_utils::write_all(new_stdout, bytes.as_ptr() as *const libc::c_void, bytes.len()); + libc_utils::write_all(new_stderr, bytes.as_ptr() as *const libc::c_void, bytes.len()); } } @@ -92,16 +95,24 @@ fn test_dup() { let new_fd2 = libc::dup2(fd, 8); let mut first_buf = [0u8; 4]; - libc::read(fd, first_buf.as_mut_ptr() as *mut libc::c_void, 4); - assert_eq!(&first_buf, b"dup "); + let first_len = libc::read(fd, first_buf.as_mut_ptr() as *mut libc::c_void, 4); + assert!(first_len > 0); + let first_len = first_len as usize; + assert_eq!(first_buf[..first_len], bytes[..first_len]); + let remaining_bytes = &bytes[first_len..]; let mut second_buf = [0u8; 4]; - libc::read(new_fd, second_buf.as_mut_ptr() as *mut libc::c_void, 4); - assert_eq!(&second_buf, b"and "); + let second_len = libc::read(new_fd, second_buf.as_mut_ptr() as *mut libc::c_void, 4); + assert!(second_len > 0); + let second_len = second_len as usize; + assert_eq!(second_buf[..second_len], remaining_bytes[..second_len]); + let remaining_bytes = &remaining_bytes[second_len..]; let mut third_buf = [0u8; 4]; - libc::read(new_fd2, third_buf.as_mut_ptr() as *mut libc::c_void, 4); - assert_eq!(&third_buf, b"dup2"); + let third_len = libc::read(new_fd2, third_buf.as_mut_ptr() as *mut libc::c_void, 4); + assert!(third_len > 0); + let third_len = third_len as usize; + assert_eq!(third_buf[..third_len], remaining_bytes[..third_len]); } } @@ -145,7 +156,7 @@ fn test_ftruncate>( let bytes = b"hello"; let path = utils::prepare("miri_test_libc_fs_ftruncate.txt"); let mut file = File::create(&path).unwrap(); - file.write(bytes).unwrap(); + file.write_all(bytes).unwrap(); file.sync_all().unwrap(); assert_eq!(file.metadata().unwrap().len(), 5); @@ -402,10 +413,10 @@ fn test_read_and_uninit() { unsafe { let fd = libc::open(cpath.as_ptr(), libc::O_RDONLY); assert_ne!(fd, -1); - let mut buf: MaybeUninit<[u8; 2]> = std::mem::MaybeUninit::uninit(); - assert_eq!(libc::read(fd, buf.as_mut_ptr().cast::(), 2), 2); + let mut buf: MaybeUninit = std::mem::MaybeUninit::uninit(); + assert_eq!(libc::read(fd, buf.as_mut_ptr().cast::(), 1), 1); let buf = buf.assume_init(); - assert_eq!(buf, [1, 2]); + assert_eq!(buf, 1); assert_eq!(libc::close(fd), 0); } remove_file(&path).unwrap(); @@ -413,14 +424,22 @@ fn test_read_and_uninit() { { // We test that if we requested to read 4 bytes, but actually read 3 bytes, then // 3 bytes (not 4) will be overwritten, and remaining byte will be left as-is. - let path = utils::prepare_with_content("pass-libc-read-and-uninit-2.txt", &[1u8, 2, 3]); + let data = [1u8, 2, 3]; + let path = utils::prepare_with_content("pass-libc-read-and-uninit-2.txt", &data); let cpath = CString::new(path.clone().into_os_string().into_encoded_bytes()).unwrap(); unsafe { let fd = libc::open(cpath.as_ptr(), libc::O_RDONLY); assert_ne!(fd, -1); let mut buf = [42u8; 5]; - assert_eq!(libc::read(fd, buf.as_mut_ptr().cast::(), 4), 3); - assert_eq!(buf, [1, 2, 3, 42, 42]); + let res = libc::read(fd, buf.as_mut_ptr().cast::(), 4); + assert!(res > 0 && res < 4); + for i in 0..buf.len() { + assert_eq!( + buf[i], + if i < res as usize { data[i] } else { 42 }, + "wrong result at pos {i}" + ); + } assert_eq!(libc::close(fd), 0); } remove_file(&path).unwrap(); diff --git a/src/tools/miri/tests/pass-dep/libc/libc-pipe.rs b/src/tools/miri/tests/pass-dep/libc/libc-pipe.rs index bc755af864c5..ffbcf633b987 100644 --- a/src/tools/miri/tests/pass-dep/libc/libc-pipe.rs +++ b/src/tools/miri/tests/pass-dep/libc/libc-pipe.rs @@ -2,6 +2,10 @@ // test_race depends on a deterministic schedule. //@compile-flags: -Zmiri-deterministic-concurrency use std::thread; + +#[path = "../../utils/libc.rs"] +mod libc_utils; + fn main() { test_pipe(); test_pipe_threaded(); @@ -26,21 +30,29 @@ fn test_pipe() { // Read size == data available in buffer. let data = "12345".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); let mut buf3: [u8; 5] = [0; 5]; - let res = unsafe { libc::read(fds[0], buf3.as_mut_ptr().cast(), buf3.len() as libc::size_t) }; + let res = unsafe { + libc_utils::read_all(fds[0], buf3.as_mut_ptr().cast(), buf3.len() as libc::size_t) + }; assert_eq!(res, 5); assert_eq!(buf3, "12345".as_bytes()); // Read size > data available in buffer. - let data = "123".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 3) }; + let data = "123".as_bytes(); + let res = unsafe { libc_utils::write_all(fds[1], data.as_ptr() as *const libc::c_void, 3) }; assert_eq!(res, 3); let mut buf4: [u8; 5] = [0; 5]; let res = unsafe { libc::read(fds[0], buf4.as_mut_ptr().cast(), buf4.len() as libc::size_t) }; - assert_eq!(res, 3); - assert_eq!(&buf4[0..3], "123".as_bytes()); + assert!(res > 0 && res <= 3); + let res = res as usize; + assert_eq!(buf4[..res], data[..res]); + if res < 3 { + // Drain the rest from the read end. + let res = unsafe { libc_utils::read_all(fds[0], buf4[res..].as_mut_ptr().cast(), 3 - res) }; + assert!(res > 0); + } } fn test_pipe_threaded() { @@ -51,7 +63,7 @@ fn test_pipe_threaded() { let thread1 = thread::spawn(move || { let mut buf: [u8; 5] = [0; 5]; let res: i64 = unsafe { - libc::read(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) + libc_utils::read_all(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) .try_into() .unwrap() }; @@ -60,7 +72,7 @@ fn test_pipe_threaded() { }); thread::yield_now(); let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); thread1.join().unwrap(); @@ -68,11 +80,12 @@ fn test_pipe_threaded() { let thread2 = thread::spawn(move || { thread::yield_now(); let data = "12345".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); }); let mut buf: [u8; 5] = [0; 5]; - let res = unsafe { libc::read(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; assert_eq!(res, 5); assert_eq!(buf, "12345".as_bytes()); thread2.join().unwrap(); @@ -90,7 +103,7 @@ fn test_race() { // write() from the main thread will occur before the read() here // because preemption is disabled and the main thread yields after write(). let res: i32 = unsafe { - libc::read(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) + libc_utils::read_all(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) .try_into() .unwrap() }; @@ -101,7 +114,7 @@ fn test_race() { }); unsafe { VAL = 1 }; let data = "a".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 1) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 1) }; assert_eq!(res, 1); thread::yield_now(); thread1.join().unwrap(); @@ -186,11 +199,12 @@ fn test_pipe_fcntl_threaded() { // the socket is now "non-blocking", the shim needs to deal correctly // with threads that were blocked before the socket was made non-blocking. let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); }); // The `read` below will block. - let res = unsafe { libc::read(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; thread1.join().unwrap(); assert_eq!(res, 5); } diff --git a/src/tools/miri/tests/pass-dep/libc/libc-socketpair.rs b/src/tools/miri/tests/pass-dep/libc/libc-socketpair.rs index c36f6b112244..9c211ffbdbe4 100644 --- a/src/tools/miri/tests/pass-dep/libc/libc-socketpair.rs +++ b/src/tools/miri/tests/pass-dep/libc/libc-socketpair.rs @@ -6,6 +6,10 @@ #![allow(static_mut_refs)] use std::thread; + +#[path = "../../utils/libc.rs"] +mod libc_utils; + fn main() { test_socketpair(); test_socketpair_threaded(); @@ -22,54 +26,71 @@ fn test_socketpair() { // Read size == data available in buffer. let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); let mut buf: [u8; 5] = [0; 5]; - let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; assert_eq!(res, 5); assert_eq!(buf, "abcde".as_bytes()); // Read size > data available in buffer. - let data = "abc".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 3) }; + let data = "abc".as_bytes(); + let res = unsafe { libc_utils::write_all(fds[0], data.as_ptr() as *const libc::c_void, 3) }; assert_eq!(res, 3); let mut buf2: [u8; 5] = [0; 5]; let res = unsafe { libc::read(fds[1], buf2.as_mut_ptr().cast(), buf2.len() as libc::size_t) }; - assert_eq!(res, 3); - assert_eq!(&buf2[0..3], "abc".as_bytes()); + assert!(res > 0 && res <= 3); + let res = res as usize; + assert_eq!(buf2[..res], data[..res]); + if res < 3 { + // Drain the rest from the read end. + let res = unsafe { libc_utils::read_all(fds[1], buf2[res..].as_mut_ptr().cast(), 3 - res) }; + assert!(res > 0); + } // Test read and write from another direction. // Read size == data available in buffer. let data = "12345".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); let mut buf3: [u8; 5] = [0; 5]; - let res = unsafe { libc::read(fds[0], buf3.as_mut_ptr().cast(), buf3.len() as libc::size_t) }; + let res = unsafe { + libc_utils::read_all(fds[0], buf3.as_mut_ptr().cast(), buf3.len() as libc::size_t) + }; assert_eq!(res, 5); assert_eq!(buf3, "12345".as_bytes()); // Read size > data available in buffer. - let data = "123".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 3) }; + let data = "123".as_bytes(); + let res = unsafe { libc_utils::write_all(fds[1], data.as_ptr() as *const libc::c_void, 3) }; assert_eq!(res, 3); let mut buf4: [u8; 5] = [0; 5]; let res = unsafe { libc::read(fds[0], buf4.as_mut_ptr().cast(), buf4.len() as libc::size_t) }; - assert_eq!(res, 3); - assert_eq!(&buf4[0..3], "123".as_bytes()); + assert!(res > 0 && res <= 3); + let res = res as usize; + assert_eq!(buf4[..res], data[..res]); + if res < 3 { + // Drain the rest from the read end. + let res = unsafe { libc_utils::read_all(fds[0], buf4[res..].as_mut_ptr().cast(), 3 - res) }; + assert!(res > 0); + } // Test when happens when we close one end, with some data in the buffer. - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 3) }; + let res = unsafe { libc_utils::write_all(fds[0], data.as_ptr() as *const libc::c_void, 3) }; assert_eq!(res, 3); unsafe { libc::close(fds[0]) }; // Reading the other end should return that data, then EOF. let mut buf: [u8; 5] = [0; 5]; - let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; assert_eq!(res, 3); assert_eq!(&buf[0..3], "123".as_bytes()); - let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; assert_eq!(res, 0); // 0-sized read: EOF. // Writing the other end should emit EPIPE. - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 1) }; + let res = unsafe { libc_utils::write_all(fds[1], data.as_ptr() as *const libc::c_void, 1) }; assert_eq!(res, -1); assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EPIPE)); } @@ -82,7 +103,7 @@ fn test_socketpair_threaded() { let thread1 = thread::spawn(move || { let mut buf: [u8; 5] = [0; 5]; let res: i64 = unsafe { - libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) + libc_utils::read_all(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) .try_into() .unwrap() }; @@ -91,7 +112,7 @@ fn test_socketpair_threaded() { }); thread::yield_now(); let data = "abcde".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 5) }; assert_eq!(res, 5); thread1.join().unwrap(); @@ -99,11 +120,12 @@ fn test_socketpair_threaded() { let thread2 = thread::spawn(move || { thread::yield_now(); let data = "12345".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[1], data as *const libc::c_void, 5) }; + let res = unsafe { libc_utils::write_all(fds[1], data as *const libc::c_void, 5) }; assert_eq!(res, 5); }); let mut buf: [u8; 5] = [0; 5]; - let res = unsafe { libc::read(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = + unsafe { libc_utils::read_all(fds[0], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; assert_eq!(res, 5); assert_eq!(buf, "12345".as_bytes()); thread2.join().unwrap(); @@ -119,7 +141,7 @@ fn test_race() { // write() from the main thread will occur before the read() here // because preemption is disabled and the main thread yields after write(). let res: i32 = unsafe { - libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) + libc_utils::read_all(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) .try_into() .unwrap() }; @@ -130,7 +152,7 @@ fn test_race() { }); unsafe { VAL = 1 }; let data = "a".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 1) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 1) }; assert_eq!(res, 1); thread::yield_now(); thread1.join().unwrap(); @@ -144,14 +166,16 @@ fn test_blocking_read() { let thread1 = thread::spawn(move || { // Let this thread block on read. let mut buf: [u8; 3] = [0; 3]; - let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = unsafe { + libc_utils::read_all(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) + }; assert_eq!(res, 3); assert_eq!(&buf, "abc".as_bytes()); }); let thread2 = thread::spawn(move || { // Unblock thread1 by doing writing something. let data = "abc".as_bytes().as_ptr(); - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 3) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 3) }; assert_eq!(res, 3); }); thread1.join().unwrap(); @@ -165,18 +189,21 @@ fn test_blocking_write() { assert_eq!(res, 0); let arr1: [u8; 212992] = [1; 212992]; // Exhaust the space in the buffer so the subsequent write will block. - let res = unsafe { libc::write(fds[0], arr1.as_ptr() as *const libc::c_void, 212992) }; + let res = + unsafe { libc_utils::write_all(fds[0], arr1.as_ptr() as *const libc::c_void, 212992) }; assert_eq!(res, 212992); let thread1 = thread::spawn(move || { let data = "abc".as_bytes().as_ptr(); // The write below will be blocked because the buffer is already full. - let res = unsafe { libc::write(fds[0], data as *const libc::c_void, 3) }; + let res = unsafe { libc_utils::write_all(fds[0], data as *const libc::c_void, 3) }; assert_eq!(res, 3); }); let thread2 = thread::spawn(move || { // Unblock thread1 by freeing up some space. let mut buf: [u8; 3] = [0; 3]; - let res = unsafe { libc::read(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) }; + let res = unsafe { + libc_utils::read_all(fds[1], buf.as_mut_ptr().cast(), buf.len() as libc::size_t) + }; assert_eq!(res, 3); assert_eq!(buf, [1, 1, 1]); }); diff --git a/src/tools/miri/tests/pass/shims/fs.rs b/src/tools/miri/tests/pass/shims/fs.rs index 5e54cc382381..e7f11c54704d 100644 --- a/src/tools/miri/tests/pass/shims/fs.rs +++ b/src/tools/miri/tests/pass/shims/fs.rs @@ -17,6 +17,10 @@ mod utils; fn main() { test_path_conversion(); test_file(); + // Partial reads/writes are apparently not a thing on Windows. + if cfg!(not(windows)) { + test_file_partial_reads_writes(); + } test_file_create_new(); test_metadata(); test_seek(); @@ -53,7 +57,7 @@ fn test_file() { file.write(&mut []).unwrap(); assert_eq!(file.metadata().unwrap().len(), 0); - file.write(bytes).unwrap(); + file.write_all(bytes).unwrap(); assert_eq!(file.metadata().unwrap().len(), bytes.len() as u64); // Test opening, reading and closing a file. let mut file = File::open(&path).unwrap(); @@ -74,6 +78,28 @@ fn test_file() { remove_file(&path).unwrap(); } +fn test_file_partial_reads_writes() { + let path = utils::prepare_with_content("miri_test_fs_file.txt", b"abcdefg"); + + // Ensure we sometimes do incomplete writes. + let got_short_write = (0..16).any(|_| { + let _ = remove_file(&path); // FIXME(win, issue #4483): errors if the file already exists + let mut file = File::create(&path).unwrap(); + file.write(&[0; 4]).unwrap() != 4 + }); + assert!(got_short_write); + // Ensure we sometimes do incomplete reads. + let got_short_read = (0..16).any(|_| { + let mut file = File::open(&path).unwrap(); + let mut buf = [0; 4]; + file.read(&mut buf).unwrap() != 4 + }); + assert!(got_short_read); + + // Clean up + remove_file(&path).unwrap(); +} + fn test_file_clone() { let bytes = b"Hello, World!\n"; let path = utils::prepare_with_content("miri_test_fs_file_clone.txt", bytes); diff --git a/src/tools/miri/tests/pass/shims/pipe.rs b/src/tools/miri/tests/pass/shims/pipe.rs index c47feb8774ad..4915e54c533f 100644 --- a/src/tools/miri/tests/pass/shims/pipe.rs +++ b/src/tools/miri/tests/pass/shims/pipe.rs @@ -4,8 +4,8 @@ use std::io::{Read, Write, pipe}; fn main() { let (mut ping_rx, mut ping_tx) = pipe().unwrap(); - ping_tx.write(b"hello").unwrap(); + ping_tx.write_all(b"hello").unwrap(); let mut buf: [u8; 5] = [0; 5]; - ping_rx.read(&mut buf).unwrap(); + ping_rx.read_exact(&mut buf).unwrap(); assert_eq!(&buf, "hello".as_bytes()); } diff --git a/src/tools/miri/tests/utils/fs.rs b/src/tools/miri/tests/utils/fs.rs index 7340908626fd..7d75b3fced3c 100644 --- a/src/tools/miri/tests/utils/fs.rs +++ b/src/tools/miri/tests/utils/fs.rs @@ -1,6 +1,6 @@ use std::ffi::OsString; -use std::fs; use std::path::PathBuf; +use std::{fs, io}; use super::miri_extern; diff --git a/src/tools/miri/tests/utils/libc.rs b/src/tools/miri/tests/utils/libc.rs new file mode 100644 index 000000000000..1a3cd067c04b --- /dev/null +++ b/src/tools/miri/tests/utils/libc.rs @@ -0,0 +1,44 @@ +//! Utils that need libc. +#![allow(dead_code)] + +pub unsafe fn read_all( + fd: libc::c_int, + buf: *mut libc::c_void, + count: libc::size_t, +) -> libc::ssize_t { + assert!(count > 0); + let mut read_so_far = 0; + while read_so_far < count { + let res = libc::read(fd, buf.add(read_so_far), count - read_so_far); + if res < 0 { + return res; + } + if res == 0 { + // EOF + break; + } + read_so_far += res as libc::size_t; + } + return read_so_far as libc::ssize_t; +} + +pub unsafe fn write_all( + fd: libc::c_int, + buf: *const libc::c_void, + count: libc::size_t, +) -> libc::ssize_t { + assert!(count > 0); + let mut written_so_far = 0; + while written_so_far < count { + let res = libc::write(fd, buf.add(written_so_far), count - written_so_far); + if res < 0 { + return res; + } + if res == 0 { + // EOF? + break; + } + written_so_far += res as libc::size_t; + } + return written_so_far as libc::ssize_t; +} From 41199f39d89135408763eee492fd2a5270828030 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Sat, 19 Jul 2025 11:17:38 -0700 Subject: [PATCH 050/809] `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 9e50049157eb783ad7bf40c3f4e0cff1f8f2d3bf Mon Sep 17 00:00:00 2001 From: Jason Newcomb Date: Sun, 20 Jul 2025 09:43:45 -0400 Subject: [PATCH 051/809] 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 72ba7c594d3fb9730daa361327aea1a14f096b6e Mon Sep 17 00:00:00 2001 From: The Miri Cronjob Bot Date: Mon, 21 Jul 2025 05:01:50 +0000 Subject: [PATCH 052/809] Preparing for merge from rustc --- 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 d734ec333a5c..f6b7efe51a12 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -6707bf0f59485cf054ac1095725df43220e4be20 +460259d14de0274b97b8801e08cb2fe5f16fdac5 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 053/809] 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 054/809] 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 055/809] 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 056/809] 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 057/809] 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 058/809] 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 059/809] 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 060/809] 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 061/809] 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 062/809] 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 063/809] 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 6f06667ba9a46852dd4f0d2a390e74a39858353d Mon Sep 17 00:00:00 2001 From: The Miri Cronjob Bot Date: Tue, 22 Jul 2025 04:59:16 +0000 Subject: [PATCH 064/809] Preparing for merge from rustc --- 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 f6b7efe51a12..bd902ca1fd5a 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -460259d14de0274b97b8801e08cb2fe5f16fdac5 +9748d87dc70a9a6725c5dbd76ce29d04752b4f90 From af8cb1da142645c1d546e7c9ad66b17b50e16ffe Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 21 Jul 2025 14:22:51 +0200 Subject: [PATCH 065/809] 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 0494311b9c09fc72a17d040299eebdb189e582d2 Mon Sep 17 00:00:00 2001 From: Marijn Schouten Date: Tue, 22 Jul 2025 11:45:05 +0000 Subject: [PATCH 066/809] miropt: clippy fixes --- src/tools/miropt-test-tools/src/lib.rs | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/tools/miropt-test-tools/src/lib.rs b/src/tools/miropt-test-tools/src/lib.rs index 41b53d2ad0e9..10769c9c8abf 100644 --- a/src/tools/miropt-test-tools/src/lib.rs +++ b/src/tools/miropt-test-tools/src/lib.rs @@ -34,7 +34,7 @@ fn output_file_suffix(testfile: &Path, bit_width: u32, panic_strategy: PanicStra let mut suffix = String::new(); if each_bit_width { - suffix.push_str(&format!(".{}bit", bit_width)); + suffix.push_str(&format!(".{bit_width}bit")); } if each_panic_strategy { match panic_strategy { @@ -51,7 +51,7 @@ pub fn files_for_miropt_test( panic_strategy: PanicStrategy, ) -> MiroptTest { let mut out = Vec::new(); - let test_file_contents = fs::read_to_string(&testfile).unwrap(); + let test_file_contents = fs::read_to_string(testfile).unwrap(); let test_dir = testfile.parent().unwrap(); let test_crate = testfile.file_stem().unwrap().to_str().unwrap().replace('-', "_"); @@ -76,10 +76,10 @@ pub fn files_for_miropt_test( if test_name.ends_with(".diff") { let trimmed = test_name.trim_end_matches(".diff"); - passes.push(trimmed.split('.').last().unwrap().to_owned()); - let test_against = format!("{}.after.mir", trimmed); - from_file = format!("{}.before.mir", trimmed); - expected_file = format!("{}{}.diff", trimmed, suffix); + passes.push(trimmed.split('.').next_back().unwrap().to_owned()); + let test_against = format!("{trimmed}.after.mir"); + from_file = format!("{trimmed}.before.mir"); + expected_file = format!("{trimmed}{suffix}.diff"); assert!(test_names.next().is_none(), "two mir pass names specified for MIR diff"); to_file = Some(test_against); } else if let Some(first_pass) = test_names.next() { @@ -92,10 +92,9 @@ pub fn files_for_miropt_test( } assert!(test_names.next().is_none(), "three mir pass names specified for MIR diff"); - expected_file = - format!("{}{}.{}-{}.diff", test_name, suffix, first_pass, second_pass); - let second_file = format!("{}.{}.mir", test_name, second_pass); - from_file = format!("{}.{}.mir", test_name, first_pass); + expected_file = format!("{test_name}{suffix}.{first_pass}-{second_pass}.diff"); + let second_file = format!("{test_name}.{second_pass}.mir"); + from_file = format!("{test_name}.{first_pass}.mir"); to_file = Some(second_file); } else { // Allow-list for file extensions that can be produced by MIR dumps. @@ -112,7 +111,7 @@ pub fn files_for_miropt_test( ) } - expected_file = format!("{}{}.{}", test_name_wo_ext, suffix, test_name_ext); + expected_file = format!("{test_name_wo_ext}{suffix}.{test_name_ext}"); from_file = test_name.to_string(); assert!(test_names.next().is_none(), "two mir pass names specified for MIR dump"); to_file = None; @@ -123,7 +122,7 @@ pub fn files_for_miropt_test( ); }; if !expected_file.starts_with(&test_crate) { - expected_file = format!("{}.{}", test_crate, expected_file); + expected_file = format!("{test_crate}.{expected_file}"); } let expected_file = test_dir.join(expected_file); From 39ef6a96ad6d4d3340a3597e1efe9755d52c690b Mon Sep 17 00:00:00 2001 From: Marijn Schouten Date: Tue, 22 Jul 2025 11:45:38 +0000 Subject: [PATCH 067/809] miropt: move to edition 2024 --- src/tools/miropt-test-tools/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miropt-test-tools/Cargo.toml b/src/tools/miropt-test-tools/Cargo.toml index 09b4c7d16dce..3eb5020968d3 100644 --- a/src/tools/miropt-test-tools/Cargo.toml +++ b/src/tools/miropt-test-tools/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "miropt-test-tools" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] From d466953088a41ce98acfcd53961ef07b887f074a Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Tue, 22 Jul 2025 11:03:49 -0400 Subject: [PATCH 068/809] 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 069/809] 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 070/809] 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 071/809] 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 072/809] 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 073/809] 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 074/809] 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 075/809] 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 076/809] 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 077/809] 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 078/809] 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 079/809] 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 080/809] 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 293f95fb0cd27970e147697aa9500acdc22fd0e6 Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 11 Jul 2025 13:45:51 -0500 Subject: [PATCH 081/809] add regression test for RUST-143222 --- .../reexport/auxiliary/wrap-unnamable-type.rs | 12 ++++++++++++ .../rustdoc/reexport/wrapped-unnamble-type-143222.rs | 12 ++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs create mode 100644 tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs diff --git a/tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs b/tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs new file mode 100644 index 000000000000..8ce0a0de5448 --- /dev/null +++ b/tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs @@ -0,0 +1,12 @@ +pub trait Assoc { + type Ty; +} + +pub struct Foo(::Ty); + +const _: () = { + impl crate::Assoc for Foo { + type Ty = Bar; + } + pub struct Bar; +}; diff --git a/tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs b/tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs new file mode 100644 index 000000000000..005a5c0b98ad --- /dev/null +++ b/tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs @@ -0,0 +1,12 @@ +//@ compile-flags: -Z normalize-docs --document-private-items -Zunstable-options --show-type-layout +//@ aux-build:wrap-unnamable-type.rs +//@ build-aux-docs + +#![crate_name = "foo"] + +extern crate wrap_unnamable_type as helper; +//extern crate helper; +//@ has 'foo/struct.Foo.html' +//@ !hasraw - '_/struct.Bar.html' +#[doc(inline)] +pub use helper::Foo; From 4762694e4a4d04295c578a344d217e34067c608c Mon Sep 17 00:00:00 2001 From: binarycat Date: Sat, 12 Jul 2025 15:05:30 -0500 Subject: [PATCH 082/809] rustdoc: never try to link to unnamable types --- src/librustdoc/html/format.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index be8a2d511e91..f4cf819fc59d 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -368,6 +368,8 @@ pub(crate) enum HrefError { Private, // Not in external cache, href link should be in same page NotInExternalCache, + /// Refers to an unnamable item, such as one defined within a function or const block. + UnnamableItem, } /// This function is to get the external macro path because they are not in the cache used in @@ -498,7 +500,13 @@ fn url_parts( builder.extend(module_fqp.iter().copied()); Ok(builder) } - ExternalLocation::Local => Ok(href_relative_parts(module_fqp, relative_to)), + ExternalLocation::Local => { + if module_fqp.iter().any(|sym| sym.as_str() == "_") { + Err(HrefError::UnnamableItem) + } else { + Ok(href_relative_parts(module_fqp, relative_to)) + } + } ExternalLocation::Unknown => Err(HrefError::DocumentationNotBuilt), } } From 94700f8f3fd4fc3f3a0e563aa94d4a399691d88f Mon Sep 17 00:00:00 2001 From: binarycat Date: Mon, 14 Jul 2025 12:31:58 -0500 Subject: [PATCH 083/809] fix regression test --- tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs | 2 +- tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs b/tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs index 8ce0a0de5448..7f8e346c8bea 100644 --- a/tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs +++ b/tests/rustdoc/reexport/auxiliary/wrap-unnamable-type.rs @@ -4,7 +4,7 @@ pub trait Assoc { pub struct Foo(::Ty); -const _: () = { +const _X: () = { impl crate::Assoc for Foo { type Ty = Bar; } diff --git a/tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs b/tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs index 005a5c0b98ad..9a8893786f5f 100644 --- a/tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs +++ b/tests/rustdoc/reexport/wrapped-unnamble-type-143222.rs @@ -2,11 +2,15 @@ //@ aux-build:wrap-unnamable-type.rs //@ build-aux-docs +// regression test for https://github.com/rust-lang/rust/issues/143222 +// makes sure normalizing docs does not cause us to link to unnamable types +// in cross-crate reexports. + #![crate_name = "foo"] extern crate wrap_unnamable_type as helper; -//extern crate helper; + //@ has 'foo/struct.Foo.html' -//@ !hasraw - '_/struct.Bar.html' +//@ !hasraw - 'struct.Bar.html' #[doc(inline)] pub use helper::Foo; From f57283d6141fcc430e739fc2ad633e8997a66310 Mon Sep 17 00:00:00 2001 From: binarycat Date: Tue, 15 Jul 2025 16:06:03 -0500 Subject: [PATCH 084/809] rustdoc: actually never link to unnamable types --- src/librustdoc/html/format.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index f4cf819fc59d..90d385aa1359 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -481,6 +481,20 @@ fn generate_item_def_id_path( Ok((url_parts, shortty, fqp)) } +/// Checks if the given defid refers to an item that is unnamable, such as one defined in a const block. +fn is_unnamable(tcx: TyCtxt<'_>, did: DefId) -> bool { + let mut cur_did = did; + while let Some(parent) = tcx.opt_parent(cur_did) { + match tcx.def_kind(parent) { + // items defined in these can be linked to + DefKind::Mod | DefKind::Impl { .. } | DefKind::ForeignMod => cur_did = parent, + // everything else does not have docs generated for it + _ => return true, + } + } + return false; +} + fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] { if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] } } @@ -500,13 +514,7 @@ fn url_parts( builder.extend(module_fqp.iter().copied()); Ok(builder) } - ExternalLocation::Local => { - if module_fqp.iter().any(|sym| sym.as_str() == "_") { - Err(HrefError::UnnamableItem) - } else { - Ok(href_relative_parts(module_fqp, relative_to)) - } - } + ExternalLocation::Local => Ok(href_relative_parts(module_fqp, relative_to)), ExternalLocation::Unknown => Err(HrefError::DocumentationNotBuilt), } } @@ -560,6 +568,9 @@ pub(crate) fn href_with_root_path( } _ => original_did, }; + if is_unnamable(cx.tcx(), did) { + return Err(HrefError::UnnamableItem); + } let cache = cx.cache(); let relative_to = &cx.current; From 05a62c8a1172795709219aa5afc833eb1ab57c25 Mon Sep 17 00:00:00 2001 From: binarycat Date: Sat, 19 Jul 2025 14:26:47 -0500 Subject: [PATCH 085/809] impl items are never unnamable --- src/librustdoc/html/format.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 90d385aa1359..457af8e994d7 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -486,8 +486,14 @@ fn is_unnamable(tcx: TyCtxt<'_>, did: DefId) -> bool { let mut cur_did = did; while let Some(parent) = tcx.opt_parent(cur_did) { match tcx.def_kind(parent) { - // items defined in these can be linked to - DefKind::Mod | DefKind::Impl { .. } | DefKind::ForeignMod => cur_did = parent, + // items defined in these can be linked to, as long as they are visible + DefKind::Mod | DefKind::ForeignMod => cur_did = parent, + // items in impls can be linked to, + // as long as we can link to the item the impl is on. + // since associated traits are not a thing, + // it should not be possible to refer to an impl item if + // the base type is not namable. + DefKind::Impl { .. } => return false, // everything else does not have docs generated for it _ => return true, } From 45231fa599583edc95843aaa4f23b12f762e01e7 Mon Sep 17 00:00:00 2001 From: Predrag Gruevski Date: Wed, 23 Jul 2025 00:00:01 +0000 Subject: [PATCH 086/809] [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 08d77873df5670e875c5ca18a6717a56436687a0 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 19 Jul 2025 09:45:56 +0200 Subject: [PATCH 087/809] CI: add windows-arm runner --- src/tools/miri/.github/workflows/ci.yml | 8 ++++++++ src/tools/miri/cargo-miri/src/phases.rs | 8 ++++---- src/tools/miri/ci/ci.sh | 12 ++++++++---- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index 11c0f08debe6..1af443803910 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -45,6 +45,8 @@ jobs: os: macos-latest - host_target: i686-pc-windows-msvc os: windows-latest + - host_target: aarch64-pc-windows-msvc + os: windows-11-arm runs-on: ${{ matrix.os }} env: HOST_TARGET: ${{ matrix.host_target }} @@ -63,6 +65,12 @@ 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 }}" diff --git a/src/tools/miri/cargo-miri/src/phases.rs b/src/tools/miri/cargo-miri/src/phases.rs index b72b974bdbdd..efb9053f69a5 100644 --- a/src/tools/miri/cargo-miri/src/phases.rs +++ b/src/tools/miri/cargo-miri/src/phases.rs @@ -1,9 +1,9 @@ //! Implements the various phases of `cargo miri run/test`. use std::env; -use std::fs::{self, File}; +use std::fs::File; use std::io::BufReader; -use std::path::{Path, PathBuf}; +use std::path::{self, Path, PathBuf}; use std::process::Command; use rustc_version::VersionMeta; @@ -222,12 +222,12 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { // that to be the Miri driver, but acting as rustc, in host mode. // // In `main`, we need the value of `RUSTC` to distinguish RUSTC_WRAPPER invocations from rustdoc - // or TARGET_RUNNER invocations, so we canonicalize it here to make it exceedingly unlikely that + // or TARGET_RUNNER invocations, so we make it absolute to make it exceedingly unlikely that // there would be a collision with other invocations of cargo-miri (as rustdoc or as runner). We // explicitly do this even if RUSTC_STAGE is set, since for these builds we do *not* want the // bootstrap `rustc` thing in our way! Instead, we have MIRI_HOST_SYSROOT to use for host // builds. - cmd.env("RUSTC", fs::canonicalize(find_miri()).unwrap()); + cmd.env("RUSTC", path::absolute(find_miri()).unwrap()); // In case we get invoked as RUSTC without the wrapper, let's be a host rustc. This makes no // sense for cross-interpretation situations, but without the wrapper, this will use the host // sysroot, so asking it to behave like a target build makes even less sense. diff --git a/src/tools/miri/ci/ci.sh b/src/tools/miri/ci/ci.sh index 5767d1782795..b66530e77b8a 100755 --- a/src/tools/miri/ci/ci.sh +++ b/src/tools/miri/ci/ci.sh @@ -142,7 +142,6 @@ case $HOST_TARGET in # Host GC_STRESS=1 MIR_OPT=1 MANY_SEEDS=64 TEST_BENCH=1 CARGO_MIRI_ENV=1 run_tests # Extra tier 1 - MANY_SEEDS=64 TEST_TARGET=i686-unknown-linux-gnu run_tests MANY_SEEDS=64 TEST_TARGET=x86_64-apple-darwin run_tests MANY_SEEDS=64 TEST_TARGET=x86_64-pc-windows-gnu run_tests ;; @@ -161,8 +160,6 @@ case $HOST_TARGET in aarch64-unknown-linux-gnu) # Host GC_STRESS=1 MIR_OPT=1 MANY_SEEDS=64 TEST_BENCH=1 CARGO_MIRI_ENV=1 run_tests - # Extra tier 1 candidate - MANY_SEEDS=64 TEST_TARGET=aarch64-pc-windows-msvc run_tests # Extra tier 2 MANY_SEEDS=16 TEST_TARGET=arm-unknown-linux-gnueabi run_tests # 32bit ARM MANY_SEEDS=16 TEST_TARGET=aarch64-pc-windows-gnullvm run_tests # gnullvm ABI @@ -189,13 +186,20 @@ case $HOST_TARGET in ;; i686-pc-windows-msvc) # Host - # Without GC_STRESS as this is the slowest runner. + # Without GC_STRESS as this is a very slow runner. MIR_OPT=1 MANY_SEEDS=64 TEST_BENCH=1 run_tests # Extra tier 1 # We really want to ensure a Linux target works on a Windows host, # and a 64bit target works on a 32bit host. TEST_TARGET=x86_64-unknown-linux-gnu run_tests ;; + aarch64-pc-windows-msvc) + # Host + # Without GC_STRESS as this is a very slow runner. + MIR_OPT=1 MANY_SEEDS=64 TEST_BENCH=1 CARGO_MIRI_ENV=1 run_tests + # Extra tier 1 + MANY_SEEDS=64 TEST_TARGET=i686-unknown-linux-gnu run_tests + ;; *) echo "FATAL: unknown host target: $HOST_TARGET" exit 1 From efcae7d31d30ba8d8c806fbb8dea634e78d7b969 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 19 Jul 2025 22:38:57 +0200 Subject: [PATCH 088/809] 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 089/809] 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 a6c10939acdadf274e67f97f1e605b4e563a8c7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 23 Jul 2025 09:24:52 +0200 Subject: [PATCH 090/809] Init josh-sync config file --- src/tools/miri/josh-sync.toml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 src/tools/miri/josh-sync.toml diff --git a/src/tools/miri/josh-sync.toml b/src/tools/miri/josh-sync.toml new file mode 100644 index 000000000000..86208b3742d2 --- /dev/null +++ b/src/tools/miri/josh-sync.toml @@ -0,0 +1,2 @@ +repo = "miri" +filter = ":rev(75dd959a3a40eb5b4574f8d2e23aa6efbeb33573:prefix=src/tools/miri):/src/tools/miri" From a61657e9d477914b27529bb2fe6dbb1d76e5ae1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 23 Jul 2025 09:24:58 +0200 Subject: [PATCH 091/809] Remove Josh code from `miri-script` --- src/tools/miri/miri-script/Cargo.lock | 90 +------- src/tools/miri/miri-script/Cargo.toml | 1 - src/tools/miri/miri-script/src/commands.rs | 229 +-------------------- src/tools/miri/miri-script/src/main.rs | 22 +- 4 files changed, 6 insertions(+), 336 deletions(-) diff --git a/src/tools/miri/miri-script/Cargo.lock b/src/tools/miri/miri-script/Cargo.lock index a049bfcbccd6..044a678869e2 100644 --- a/src/tools/miri/miri-script/Cargo.lock +++ b/src/tools/miri/miri-script/Cargo.lock @@ -116,27 +116,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" -[[package]] -name = "directories" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.60.2", -] - [[package]] name = "dunce" version = "1.0.5" @@ -165,17 +144,6 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" -[[package]] -name = "getrandom" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.11.1+wasi-snapshot-preview1", -] - [[package]] name = "getrandom" version = "0.3.3" @@ -185,7 +153,7 @@ dependencies = [ "cfg-if", "libc", "r-efi", - "wasi 0.14.2+wasi-0.2.4", + "wasi", ] [[package]] @@ -221,16 +189,6 @@ version = "0.2.174" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" -[[package]] -name = "libredox" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1580801010e535496706ba011c15f8532df6b42297d2e471fec38ceadd8c0638" -dependencies = [ - "bitflags", - "libc", -] - [[package]] name = "linux-raw-sys" version = "0.9.4" @@ -249,7 +207,6 @@ version = "0.1.0" dependencies = [ "anyhow", "clap", - "directories", "dunce", "itertools", "path_macro", @@ -275,12 +232,6 @@ version = "1.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad" -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - [[package]] name = "path_macro" version = "1.0.0" @@ -311,17 +262,6 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" -[[package]] -name = "redox_users" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" -dependencies = [ - "getrandom 0.2.16", - "libredox", - "thiserror", -] - [[package]] name = "rustc_version" version = "0.4.1" @@ -427,32 +367,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" dependencies = [ "fastrand", - "getrandom 0.3.3", + "getrandom", "once_cell", "rustix", "windows-sys 0.59.0", ] -[[package]] -name = "thiserror" -version = "2.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "unicode-ident" version = "1.0.18" @@ -475,12 +395,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - [[package]] name = "wasi" version = "0.14.2+wasi-0.2.4" diff --git a/src/tools/miri/miri-script/Cargo.toml b/src/tools/miri/miri-script/Cargo.toml index b3f82cd1d504..39858880e8c6 100644 --- a/src/tools/miri/miri-script/Cargo.toml +++ b/src/tools/miri/miri-script/Cargo.toml @@ -22,7 +22,6 @@ anyhow = "1.0" xshell = "0.2.6" rustc_version = "0.4" dunce = "1.0.4" -directories = "6" serde = "1" serde_json = "1" serde_derive = "1" diff --git a/src/tools/miri/miri-script/src/commands.rs b/src/tools/miri/miri-script/src/commands.rs index 9aaad9ca04a9..017e461cd807 100644 --- a/src/tools/miri/miri-script/src/commands.rs +++ b/src/tools/miri/miri-script/src/commands.rs @@ -2,11 +2,9 @@ use std::collections::BTreeMap; use std::ffi::{OsStr, OsString}; use std::fmt::Write as _; use std::fs::{self, File}; -use std::io::{self, BufRead, BufReader, BufWriter, Write as _}; -use std::ops::Not; +use std::io::{self, BufRead, BufReader, BufWriter}; use std::path::PathBuf; -use std::time::Duration; -use std::{env, net, process}; +use std::{env, process}; use anyhow::{Context, Result, anyhow, bail}; use path_macro::path; @@ -18,11 +16,6 @@ use xshell::{Shell, cmd}; use crate::Command; use crate::util::*; -/// Used for rustc syncs. -const JOSH_FILTER: &str = - ":rev(75dd959a3a40eb5b4574f8d2e23aa6efbeb33573:prefix=src/tools/miri):/src/tools/miri"; -const JOSH_PORT: u16 = 42042; - impl MiriEnv { /// Prepares the environment: builds miri and cargo-miri and a sysroot. /// Returns the location of the sysroot. @@ -99,66 +92,6 @@ impl Command { Ok(()) } - fn start_josh() -> Result { - // Determine cache directory. - let local_dir = { - let user_dirs = - directories::ProjectDirs::from("org", "rust-lang", "miri-josh").unwrap(); - user_dirs.cache_dir().to_owned() - }; - - // Start josh, silencing its output. - let mut cmd = process::Command::new("josh-proxy"); - cmd.arg("--local").arg(local_dir); - cmd.arg("--remote").arg("https://github.com"); - cmd.arg("--port").arg(JOSH_PORT.to_string()); - cmd.arg("--no-background"); - cmd.stdout(process::Stdio::null()); - cmd.stderr(process::Stdio::null()); - let josh = cmd.spawn().context("failed to start josh-proxy, make sure it is installed")?; - - // Create a wrapper that stops it on drop. - struct Josh(process::Child); - impl Drop for Josh { - fn drop(&mut self) { - #[cfg(unix)] - { - // Try to gracefully shut it down. - process::Command::new("kill") - .args(["-s", "INT", &self.0.id().to_string()]) - .output() - .expect("failed to SIGINT josh-proxy"); - // Sadly there is no "wait with timeout"... so we just give it some time to finish. - std::thread::sleep(Duration::from_millis(100)); - // Now hopefully it is gone. - if self.0.try_wait().expect("failed to wait for josh-proxy").is_some() { - return; - } - } - // If that didn't work (or we're not on Unix), kill it hard. - eprintln!( - "I have to kill josh-proxy the hard way, let's hope this does not break anything." - ); - self.0.kill().expect("failed to SIGKILL josh-proxy"); - } - } - - // Wait until the port is open. We try every 10ms until 1s passed. - for _ in 0..100 { - // This will generally fail immediately when the port is still closed. - let josh_ready = net::TcpStream::connect_timeout( - &net::SocketAddr::from(([127, 0, 0, 1], JOSH_PORT)), - Duration::from_millis(1), - ); - if josh_ready.is_ok() { - return Ok(Josh(josh)); - } - // Not ready yet. - std::thread::sleep(Duration::from_millis(10)); - } - bail!("Even after waiting for 1s, josh-proxy is still not available.") - } - pub fn exec(self) -> Result<()> { // First, and crucially only once, run the auto-actions -- but not for all commands. match &self { @@ -170,11 +103,7 @@ impl Command { | Command::Fmt { .. } | Command::Doc { .. } | Command::Clippy { .. } => Self::auto_actions()?, - | Command::Toolchain { .. } - | Command::Bench { .. } - | Command::RustcPull { .. } - | Command::RustcPush { .. } - | Command::Squash => {} + | Command::Toolchain { .. } | Command::Bench { .. } | Command::Squash => {} } // Then run the actual command. match self { @@ -191,8 +120,6 @@ impl Command { Command::Bench { target, no_install, save_baseline, load_baseline, benches } => Self::bench(target, no_install, save_baseline, load_baseline, benches), Command::Toolchain { flags } => Self::toolchain(flags), - Command::RustcPull { commit } => Self::rustc_pull(commit.clone()), - Command::RustcPush { github_user, branch } => Self::rustc_push(github_user, branch), Command::Squash => Self::squash(), } } @@ -233,156 +160,6 @@ impl Command { Ok(()) } - fn rustc_pull(commit: Option) -> Result<()> { - let sh = Shell::new()?; - sh.change_dir(miri_dir()?); - let commit = commit.map(Result::Ok).unwrap_or_else(|| { - let rust_repo_head = - cmd!(sh, "git ls-remote https://github.com/rust-lang/rust/ HEAD").read()?; - rust_repo_head - .split_whitespace() - .next() - .map(|front| front.trim().to_owned()) - .ok_or_else(|| anyhow!("Could not obtain Rust repo HEAD from remote.")) - })?; - // Make sure the repo is clean. - if cmd!(sh, "git status --untracked-files=no --porcelain").read()?.is_empty().not() { - bail!("working directory must be clean before running `./miri rustc-pull`"); - } - // Make sure josh is running. - let josh = Self::start_josh()?; - let josh_url = - format!("http://localhost:{JOSH_PORT}/rust-lang/rust.git@{commit}{JOSH_FILTER}.git"); - - // Update rust-version file. As a separate commit, since making it part of - // the merge has confused the heck out of josh in the past. - // We pass `--no-verify` to avoid running git hooks like `./miri fmt` that could in turn - // trigger auto-actions. - // We do this before the merge so that if there are merge conflicts, we have - // the right rust-version file while resolving them. - sh.write_file("rust-version", format!("{commit}\n"))?; - const PREPARING_COMMIT_MESSAGE: &str = "Preparing for merge from rustc"; - cmd!(sh, "git commit rust-version --no-verify -m {PREPARING_COMMIT_MESSAGE}") - .run() - .context("FAILED to commit rust-version file, something went wrong")?; - - // Fetch given rustc commit. - cmd!(sh, "git fetch {josh_url}") - .run() - .inspect_err(|_| { - // Try to un-do the previous `git commit`, to leave the repo in the state we found it. - cmd!(sh, "git reset --hard HEAD^") - .run() - .expect("FAILED to clean up again after failed `git fetch`, sorry for that"); - }) - .context("FAILED to fetch new commits, something went wrong (committing the rust-version file has been undone)")?; - - // This should not add any new root commits. So count those before and after merging. - let num_roots = || -> Result { - Ok(cmd!(sh, "git rev-list HEAD --max-parents=0 --count") - .read() - .context("failed to determine the number of root commits")? - .parse::()?) - }; - let num_roots_before = num_roots()?; - - // Merge the fetched commit. - const MERGE_COMMIT_MESSAGE: &str = "Merge from rustc"; - cmd!(sh, "git merge FETCH_HEAD --no-verify --no-ff -m {MERGE_COMMIT_MESSAGE}") - .run() - .context("FAILED to merge new commits, something went wrong")?; - - // Check that the number of roots did not increase. - if num_roots()? != num_roots_before { - bail!("Josh created a new root commit. This is probably not the history you want."); - } - - drop(josh); - Ok(()) - } - - fn rustc_push(github_user: String, branch: String) -> Result<()> { - let sh = Shell::new()?; - sh.change_dir(miri_dir()?); - let base = sh.read_file("rust-version")?.trim().to_owned(); - // Make sure the repo is clean. - if cmd!(sh, "git status --untracked-files=no --porcelain").read()?.is_empty().not() { - bail!("working directory must be clean before running `./miri rustc-push`"); - } - // Make sure josh is running. - let josh = Self::start_josh()?; - let josh_url = - format!("http://localhost:{JOSH_PORT}/{github_user}/rust.git{JOSH_FILTER}.git"); - - // Find a repo we can do our preparation in. - if let Ok(rustc_git) = env::var("RUSTC_GIT") { - // If rustc_git is `Some`, we'll use an existing fork for the branch updates. - sh.change_dir(rustc_git); - } else { - // Otherwise, do this in the local Miri repo. - println!( - "This will pull a copy of the rust-lang/rust history into this Miri checkout, growing it by about 1GB." - ); - print!( - "To avoid that, abort now and set the `RUSTC_GIT` environment variable to an existing rustc checkout. Proceed? [y/N] " - ); - std::io::stdout().flush()?; - let mut answer = String::new(); - std::io::stdin().read_line(&mut answer)?; - if answer.trim().to_lowercase() != "y" { - std::process::exit(1); - } - }; - // Prepare the branch. Pushing works much better if we use as base exactly - // the commit that we pulled from last time, so we use the `rust-version` - // file to find out which commit that would be. - println!("Preparing {github_user}/rust (base: {base})..."); - if cmd!(sh, "git fetch https://github.com/{github_user}/rust {branch}") - .ignore_stderr() - .read() - .is_ok() - { - println!( - "The branch '{branch}' seems to already exist in 'https://github.com/{github_user}/rust'. Please delete it and try again." - ); - std::process::exit(1); - } - cmd!(sh, "git fetch https://github.com/rust-lang/rust {base}").run()?; - cmd!(sh, "git push https://github.com/{github_user}/rust {base}:refs/heads/{branch}") - .ignore_stdout() - .ignore_stderr() // silence the "create GitHub PR" message - .run()?; - println!(); - - // Do the actual push. - sh.change_dir(miri_dir()?); - println!("Pushing miri changes..."); - cmd!(sh, "git push {josh_url} HEAD:{branch}").run()?; - println!(); - - // Do a round-trip check to make sure the push worked as expected. - cmd!(sh, "git fetch {josh_url} {branch}").ignore_stderr().read()?; - let head = cmd!(sh, "git rev-parse HEAD").read()?; - let fetch_head = cmd!(sh, "git rev-parse FETCH_HEAD").read()?; - if head != fetch_head { - bail!( - "Josh created a non-roundtrip push! Do NOT merge this into rustc!\n\ - Expected {head}, got {fetch_head}." - ); - } - println!( - "Confirmed that the push round-trips back to Miri properly. Please create a rustc PR:" - ); - println!( - // Open PR with `subtree update` title to silence the `no-merges` triagebot check - // See https://github.com/rust-lang/rust/pull/114157 - " https://github.com/rust-lang/rust/compare/{github_user}:{branch}?quick_pull=1&title=Miri+subtree+update&body=r?+@ghost" - ); - - drop(josh); - Ok(()) - } - fn squash() -> Result<()> { let sh = Shell::new()?; sh.change_dir(miri_dir()?); diff --git a/src/tools/miri/miri-script/src/main.rs b/src/tools/miri/miri-script/src/main.rs index e41df662ca28..761ec5979faf 100644 --- a/src/tools/miri/miri-script/src/main.rs +++ b/src/tools/miri/miri-script/src/main.rs @@ -142,25 +142,6 @@ pub enum Command { #[arg(trailing_var_arg = true, allow_hyphen_values = true)] flags: Vec, }, - /// Pull and merge Miri changes from the rustc repo. - /// - /// The fetched commit is stored in the `rust-version` file, so the next `./miri toolchain` will - /// install the rustc that just got pulled. - RustcPull { - /// The commit to fetch (default: latest rustc commit). - commit: Option, - }, - /// Push Miri changes back to the rustc repo. - /// - /// This will pull a copy of the rustc history into the Miri repo, unless you set the RUSTC_GIT - /// env var to an existing clone of the rustc repo. - RustcPush { - /// The Github user that owns the rustc fork to which we should push. - github_user: String, - /// The branch to push to. - #[arg(default_value = "miri-sync")] - branch: String, - }, /// Squash the commits of the current feature branch into one. Squash, } @@ -184,8 +165,7 @@ impl Command { flags.extend(remainder); Ok(()) } - Self::Bench { .. } | Self::RustcPull { .. } | Self::RustcPush { .. } | Self::Squash => - bail!("unexpected \"--\" found in arguments"), + Self::Bench { .. } | Self::Squash => bail!("unexpected \"--\" found in arguments"), } } } From cb27ff0715723d174e244b1465b7386c20910f5b Mon Sep 17 00:00:00 2001 From: klensy Date: Wed, 23 Jul 2025 11:40:44 +0300 Subject: [PATCH 092/809] 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 093/809] 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 094/809] 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 095/809] 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 096/809] 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 097/809] 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 e685e90513f8a43dd75b7c5f88980666c48000b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 23 Jul 2025 09:25:02 +0200 Subject: [PATCH 098/809] Update `CONTRIBUTING.md` --- src/tools/miri/CONTRIBUTING.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/tools/miri/CONTRIBUTING.md b/src/tools/miri/CONTRIBUTING.md index 637c0dd2fdf1..7d78fdddbad3 100644 --- a/src/tools/miri/CONTRIBUTING.md +++ b/src/tools/miri/CONTRIBUTING.md @@ -297,14 +297,14 @@ You can also directly run Miri on a Rust source file: ## Advanced topic: Syncing with the rustc repo -We use the [`josh` proxy](https://github.com/josh-project/josh) to transmit changes between the +We use the [`josh-sync`](https://github.com/rust-lang/josh-sync) tool to transmit changes between the rustc and Miri repositories. You can install it as follows: ```sh -cargo +stable install josh-proxy --git https://github.com/josh-project/josh --tag r24.10.04 +cargo install --locked --git https://github.com/rust-lang/josh-sync ``` -Josh will automatically be started and stopped by `./miri`. +The commands below will automatically install and manage the [Josh](https://github.com/josh-project/josh) proxy that performs the actual work. ### Importing changes from the rustc repo @@ -312,10 +312,12 @@ Josh will automatically be started and stopped by `./miri`. We assume we start on an up-to-date master branch in the Miri repo. +1) First, create a branch for the pull, e.g. `git checkout -b rustup` +2) Then run the following: ```sh # Fetch and merge rustc side of the history. Takes ca 5 min the first time. # This will also update the `rustc-version` file. -./miri rustc-pull +rustc-josh-sync pull # Update local toolchain and apply formatting. ./miri toolchain && ./miri fmt git commit -am "rustup" @@ -328,12 +330,12 @@ needed. ### Exporting changes to the rustc repo -We will use the josh proxy to push to your fork of rustc. Run the following in the Miri repo, +We will use the `josh-sync` tool to push to your fork of rustc. Run the following in the Miri repo, assuming we are on an up-to-date master branch: ```sh # Push the Miri changes to your rustc fork (substitute your github handle for YOUR_NAME). -./miri rustc-push YOUR_NAME miri +rustc-josh-sync push miri YOUR_NAME ``` This will create a new branch called `miri` in your fork, and the output should include a link that From 0b88bea0d5169af3b3f9326274bda8b9c4a31823 Mon Sep 17 00:00:00 2001 From: Jake Goulding Date: Wed, 23 Jul 2025 11:35:50 -0400 Subject: [PATCH 099/809] Move `dist-apple-various` from x86_64 to aarch64 `macos-13` is going away soonish. --- src/ci/github-actions/jobs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml index 0a6ebe44b3d7..e16f00547c19 100644 --- a/src/ci/github-actions/jobs.yml +++ b/src/ci/github-actions/jobs.yml @@ -478,7 +478,7 @@ auto: NO_LLVM_ASSERTIONS: 1 NO_DEBUG_ASSERTIONS: 1 NO_OVERFLOW_CHECKS: 1 - <<: *job-macos + <<: *job-macos-m1 - name: x86_64-apple-1 env: From 288a5654514938b973a75e0e1de64ee702170661 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Wed, 23 Jul 2025 09:14:12 -0700 Subject: [PATCH 100/809] 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 48963fa8c2855e267c7ea92e6379ecc793df20d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 23 Jul 2025 09:34:36 +0200 Subject: [PATCH 101/809] Update CI workflow --- src/tools/miri/.github/workflows/ci.yml | 35 +++++++++++++++++-------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index 11c0f08debe6..75f3792bca24 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -147,27 +147,40 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 256 # get a bit more of the history - - name: install josh-proxy - run: cargo +stable install josh-proxy --git https://github.com/josh-project/josh --tag r24.10.04 + - name: install josh-sync + run: cargo +stable install --locked --git https://github.com/rust-lang/josh-sync - name: setup bot git name and email run: | git config --global user.name 'The Miri Cronjob Bot' git config --global user.email 'miri@cron.bot' - name: Install nightly toolchain run: rustup toolchain install nightly --profile minimal - - name: get changes from rustc - run: ./miri rustc-pull - name: Install rustup-toolchain-install-master run: cargo install -f rustup-toolchain-install-master - - name: format changes (if any) - run: | - ./miri toolchain - ./miri fmt --check || (./miri fmt && git commit -am "fmt") - name: Push changes to a branch and create PR run: | - # `git diff --exit-code` "succeeds" if the diff is empty. - if git diff --exit-code HEAD^; then echo "Nothing changed in rustc, skipping PR"; exit 0; fi - # The diff is non-empty, create a PR. + # Temporarily disable early exit to examine the status code of rustc-josh-sync + set +e + rustc-josh-sync pull + exitcode=$? + set -e + + # If there were no changes to pull, rustc-josh-sync returns status code 2 + # In that case skip the rest of the job + if [ $exitcode -eq 2 ]; then + echo "Nothing changed in rustc, skipping PR" + exit 0 + elif [ $exitcode -ne 0 ]; then + # If return code was not 0 or 2, rustc-josh-sync actually failed + echo "rustc-josh-sync failed" + exit ${exitcode} + fi + + # Format changes + ./miri toolchain + ./miri fmt --check || (./miri fmt && git commit -am "fmt") + + # Create a PR BRANCH="rustup-$(date -u +%Y-%m-%d)" git switch -c $BRANCH git push -u origin $BRANCH From 8664aa72dcd274be80f24b395bac8cbf10bf93ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 23 Jul 2025 22:00:50 +0200 Subject: [PATCH 102/809] Remove Zulip API keys and use `set -x` --- src/tools/miri/.github/workflows/ci.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index 75f3792bca24..73c5936cd994 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -159,20 +159,22 @@ jobs: run: cargo install -f rustup-toolchain-install-master - name: Push changes to a branch and create PR run: | + # Make it easier to see what happens. + set -x # Temporarily disable early exit to examine the status code of rustc-josh-sync set +e rustc-josh-sync pull exitcode=$? set -e - # If there were no changes to pull, rustc-josh-sync returns status code 2 - # In that case skip the rest of the job + # If there were no changes to pull, rustc-josh-sync returns status code 2. + # In that case, skip the rest of the job. if [ $exitcode -eq 2 ]; then echo "Nothing changed in rustc, skipping PR" exit 0 elif [ $exitcode -ne 0 ]; then # If return code was not 0 or 2, rustc-josh-sync actually failed - echo "rustc-josh-sync failed" + echo "error: rustc-josh-sync failed" exit ${exitcode} fi @@ -187,8 +189,6 @@ jobs: 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 }} - ZULIP_BOT_EMAIL: ${{ secrets.ZULIP_BOT_EMAIL }} - ZULIP_API_TOKEN: ${{ secrets.ZULIP_API_TOKEN }} cron-fail-notify: name: cronjob failure notification From 477814a3e4e33993a2f37c906747a0c2b1e4102e Mon Sep 17 00:00:00 2001 From: Zachary S Date: Sat, 19 Jul 2025 01:09:06 -0500 Subject: [PATCH 103/809] Document (internally) that `Range*<&T> as RangeBounds` impls are intentionally not `T: ?Sized`, and document (publically) an alternative. --- library/core/src/ops/range.rs | 30 ++++++++++++++++++++++++++++++ library/core/src/range.rs | 18 ++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index ad3b6439a610..f33a33e6b752 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -1141,6 +1141,12 @@ impl<'a, T: ?Sized + 'a> RangeBounds for (Bound<&'a T>, Bound<&'a T>) { } } +// This impl intentionally does not have `T: ?Sized`; +// see https://github.com/rust-lang/rust/pull/61584 for discussion of why. +// +/// If you need to use this implementation where `T` is unsized, +/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound], +/// i.e. replace `start..` with `(Bound::Included(start), Bound::Unbounded)`. #[stable(feature = "collections_range", since = "1.28.0")] impl RangeBounds for RangeFrom<&T> { fn start_bound(&self) -> Bound<&T> { @@ -1151,6 +1157,12 @@ impl RangeBounds for RangeFrom<&T> { } } +// This impl intentionally does not have `T: ?Sized`; +// see https://github.com/rust-lang/rust/pull/61584 for discussion of why. +// +/// If you need to use this implementation where `T` is unsized, +/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound], +/// i.e. replace `..end` with `(Bound::Unbounded, Bound::Excluded(end))`. #[stable(feature = "collections_range", since = "1.28.0")] impl RangeBounds for RangeTo<&T> { fn start_bound(&self) -> Bound<&T> { @@ -1161,6 +1173,12 @@ impl RangeBounds for RangeTo<&T> { } } +// This impl intentionally does not have `T: ?Sized`; +// see https://github.com/rust-lang/rust/pull/61584 for discussion of why. +// +/// If you need to use this implementation where `T` is unsized, +/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound], +/// i.e. replace `start..end` with `(Bound::Included(start), Bound::Excluded(end))`. #[stable(feature = "collections_range", since = "1.28.0")] impl RangeBounds for Range<&T> { fn start_bound(&self) -> Bound<&T> { @@ -1171,6 +1189,12 @@ impl RangeBounds for Range<&T> { } } +// This impl intentionally does not have `T: ?Sized`; +// see https://github.com/rust-lang/rust/pull/61584 for discussion of why. +// +/// If you need to use this implementation where `T` is unsized, +/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound], +/// i.e. replace `start..=end` with `(Bound::Included(start), Bound::Included(end))`. #[stable(feature = "collections_range", since = "1.28.0")] impl RangeBounds for RangeInclusive<&T> { fn start_bound(&self) -> Bound<&T> { @@ -1181,6 +1205,12 @@ impl RangeBounds for RangeInclusive<&T> { } } +// This impl intentionally does not have `T: ?Sized`; +// see https://github.com/rust-lang/rust/pull/61584 for discussion of why. +// +/// If you need to use this implementation where `T` is unsized, +/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound], +/// i.e. replace `..=end` with `(Bound::Unbounded, Bound::Included(end))`. #[stable(feature = "collections_range", since = "1.28.0")] impl RangeBounds for RangeToInclusive<&T> { fn start_bound(&self) -> Bound<&T> { diff --git a/library/core/src/range.rs b/library/core/src/range.rs index 5cd7956291ca..7158fa0fcf06 100644 --- a/library/core/src/range.rs +++ b/library/core/src/range.rs @@ -167,6 +167,12 @@ impl RangeBounds for Range { } } +// This impl intentionally does not have `T: ?Sized`; +// see https://github.com/rust-lang/rust/pull/61584 for discussion of why. +// +/// If you need to use this implementation where `T` is unsized, +/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound], +/// i.e. replace `start..end` with `(Bound::Included(start), Bound::Excluded(end))`. #[unstable(feature = "new_range_api", issue = "125687")] impl RangeBounds for Range<&T> { fn start_bound(&self) -> Bound<&T> { @@ -346,6 +352,12 @@ impl RangeBounds for RangeInclusive { } } +// This impl intentionally does not have `T: ?Sized`; +// see https://github.com/rust-lang/rust/pull/61584 for discussion of why. +// +/// If you need to use this implementation where `T` is unsized, +/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound], +/// i.e. replace `start..=end` with `(Bound::Included(start), Bound::Included(end))`. #[unstable(feature = "new_range_api", issue = "125687")] impl RangeBounds for RangeInclusive<&T> { fn start_bound(&self) -> Bound<&T> { @@ -491,6 +503,12 @@ impl RangeBounds for RangeFrom { } } +// This impl intentionally does not have `T: ?Sized`; +// see https://github.com/rust-lang/rust/pull/61584 for discussion of why. +// +/// If you need to use this implementation where `T` is unsized, +/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound], +/// i.e. replace `start..` with `(Bound::Included(start), Bound::Unbounded)`. #[unstable(feature = "new_range_api", issue = "125687")] impl RangeBounds for RangeFrom<&T> { fn start_bound(&self) -> Bound<&T> { From fcc7824b883bd9bba8e588fbe61d45dc427ea18e Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 01:20:55 -0500 Subject: [PATCH 104/809] 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 105/809] 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 d622bfd47746fd95ce2779cd21c68739e683f2c6 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 22 Jul 2025 15:58:42 +0200 Subject: [PATCH 106/809] Display total time and compilation time of merged doctests --- src/librustdoc/doctest.rs | 84 ++++++++++++++++++++++++++------ src/librustdoc/doctest/runner.rs | 11 +++-- 2 files changed, 77 insertions(+), 18 deletions(-) diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 38ba6b4503dc..a4284d93dfb9 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -11,7 +11,8 @@ use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; -use std::{panic, str}; +use std::time::{Duration, Instant}; +use std::{fmt, panic, str}; pub(crate) use make::{BuildDocTestBuilder, DocTestBuilder}; pub(crate) use markdown::test as test_markdown; @@ -36,6 +37,50 @@ use crate::config::{Options as RustdocOptions, OutputFormat}; use crate::html::markdown::{ErrorCodes, Ignore, LangString, MdRelLine}; use crate::lint::init_lints; +/// Type used to display times (compilation and total) information for merged doctests. +struct MergedDoctestTimes { + total_time: Instant, + /// Total time spent compiling all merged doctests. + compilation_time: Duration, + /// This field is used to keep track of how many merged doctests we (tried to) compile. + added_compilation_times: usize, +} + +impl MergedDoctestTimes { + fn new() -> Self { + Self { + total_time: Instant::now(), + compilation_time: Duration::default(), + added_compilation_times: 0, + } + } + + fn add_compilation_time(&mut self, duration: Duration) { + self.compilation_time += duration; + self.added_compilation_times += 1; + } + + fn display_times(&self) { + // If no merged doctest was compiled, then there is nothing to display since the numbers + // displayed by `libtest` for standalone tests are already accurate (they include both + // compilation and runtime). + if self.added_compilation_times > 0 { + println!("{self}"); + } + } +} + +impl fmt::Display for MergedDoctestTimes { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "all doctests ran in {:.2}s; merged doctests compilation took {:.2}s", + self.total_time.elapsed().as_secs_f64(), + self.compilation_time.as_secs_f64(), + ) + } +} + /// Options that apply to all doctests in a crate or Markdown file (for `rustdoc foo.md`). #[derive(Clone)] pub(crate) struct GlobalTestOptions { @@ -295,6 +340,7 @@ pub(crate) fn run_tests( let mut nb_errors = 0; let mut ran_edition_tests = 0; + let mut times = MergedDoctestTimes::new(); let target_str = rustdoc_options.target.to_string(); for (MergeableTestKey { edition, global_crate_attrs_hash }, mut doctests) in mergeable_tests { @@ -314,13 +360,15 @@ pub(crate) fn run_tests( for (doctest, scraped_test) in &doctests { tests_runner.add_test(doctest, scraped_test, &target_str); } - if let Ok(success) = tests_runner.run_merged_tests( + let (duration, ret) = tests_runner.run_merged_tests( rustdoc_test_options, edition, &opts, &test_args, rustdoc_options, - ) { + ); + times.add_compilation_time(duration); + if let Ok(success) = ret { ran_edition_tests += 1; if !success { nb_errors += 1; @@ -354,11 +402,13 @@ pub(crate) fn run_tests( test::test_main_with_exit_callback(&test_args, standalone_tests, None, || { // We ensure temp dir destructor is called. std::mem::drop(temp_dir.take()); + times.display_times(); }); } if nb_errors != 0 { // We ensure temp dir destructor is called. std::mem::drop(temp_dir); + times.display_times(); // libtest::ERROR_EXIT_CODE is not public but it's the same value. std::process::exit(101); } @@ -496,16 +546,19 @@ impl RunnableDocTest { /// /// This is the function that calculates the compiler command line, invokes the compiler, then /// invokes the test or tests in a separate executable (if applicable). +/// +/// Returns a tuple containing the `Duration` of the compilation and the `Result` of the test. fn run_test( doctest: RunnableDocTest, rustdoc_options: &RustdocOptions, supports_color: bool, report_unused_externs: impl Fn(UnusedExterns), -) -> Result<(), TestFailure> { +) -> (Duration, Result<(), TestFailure>) { let langstr = &doctest.langstr; // Make sure we emit well-formed executable names for our target. let rust_out = add_exe_suffix("rust_out".to_owned(), &rustdoc_options.target); let output_file = doctest.test_opts.outdir.path().join(rust_out); + let instant = Instant::now(); // Common arguments used for compiling the doctest runner. // On merged doctests, the compiler is invoked twice: once for the test code itself, @@ -589,7 +642,7 @@ fn run_test( if std::fs::write(&input_file, &doctest.full_test_code).is_err() { // If we cannot write this file for any reason, we leave. All combined tests will be // tested as standalone tests. - return Err(TestFailure::CompileError); + return (Duration::default(), Err(TestFailure::CompileError)); } if !rustdoc_options.nocapture { // If `nocapture` is disabled, then we don't display rustc's output when compiling @@ -660,7 +713,7 @@ fn run_test( if std::fs::write(&runner_input_file, merged_test_code).is_err() { // If we cannot write this file for any reason, we leave. All combined tests will be // tested as standalone tests. - return Err(TestFailure::CompileError); + return (instant.elapsed(), Err(TestFailure::CompileError)); } if !rustdoc_options.nocapture { // If `nocapture` is disabled, then we don't display rustc's output when compiling @@ -713,7 +766,7 @@ fn run_test( let _bomb = Bomb(&out); match (output.status.success(), langstr.compile_fail) { (true, true) => { - return Err(TestFailure::UnexpectedCompilePass); + return (instant.elapsed(), Err(TestFailure::UnexpectedCompilePass)); } (true, false) => {} (false, true) => { @@ -729,17 +782,18 @@ fn run_test( .collect(); if !missing_codes.is_empty() { - return Err(TestFailure::MissingErrorCodes(missing_codes)); + return (instant.elapsed(), Err(TestFailure::MissingErrorCodes(missing_codes))); } } } (false, false) => { - return Err(TestFailure::CompileError); + return (instant.elapsed(), Err(TestFailure::CompileError)); } } + let duration = instant.elapsed(); if doctest.no_run { - return Ok(()); + return (duration, Ok(())); } // Run the code! @@ -771,17 +825,17 @@ fn run_test( cmd.output() }; match result { - Err(e) => return Err(TestFailure::ExecutionError(e)), + Err(e) => return (duration, Err(TestFailure::ExecutionError(e))), Ok(out) => { if langstr.should_panic && out.status.success() { - return Err(TestFailure::UnexpectedRunPass); + return (duration, Err(TestFailure::UnexpectedRunPass)); } else if !langstr.should_panic && !out.status.success() { - return Err(TestFailure::ExecutionFailure(out)); + return (duration, Err(TestFailure::ExecutionFailure(out))); } } } - Ok(()) + (duration, Ok(())) } /// Converts a path intended to use as a command to absolute if it is @@ -1071,7 +1125,7 @@ fn doctest_run_fn( no_run: scraped_test.no_run(&rustdoc_options), merged_test_code: None, }; - let res = + let (_, res) = run_test(runnable_test, &rustdoc_options, doctest.supports_color, report_unused_externs); if let Err(err) = res { diff --git a/src/librustdoc/doctest/runner.rs b/src/librustdoc/doctest/runner.rs index f0914474c793..fcfa424968e4 100644 --- a/src/librustdoc/doctest/runner.rs +++ b/src/librustdoc/doctest/runner.rs @@ -1,4 +1,5 @@ use std::fmt::Write; +use std::time::Duration; use rustc_data_structures::fx::FxIndexSet; use rustc_span::edition::Edition; @@ -67,6 +68,10 @@ impl DocTestRunner { self.nb_tests += 1; } + /// Returns a tuple containing the `Duration` of the compilation and the `Result` of the test. + /// + /// If compilation failed, it will return `Err`, otherwise it will return `Ok` containing if + /// the test ran successfully. pub(crate) fn run_merged_tests( &mut self, test_options: IndividualTestOptions, @@ -74,7 +79,7 @@ impl DocTestRunner { opts: &GlobalTestOptions, test_args: &[String], rustdoc_options: &RustdocOptions, - ) -> Result { + ) -> (Duration, Result) { let mut code = "\ #![allow(unused_extern_crates)] #![allow(internal_features)] @@ -204,9 +209,9 @@ std::process::Termination::report(test::test_main(test_args, tests, None)) no_run: false, merged_test_code: Some(code), }; - let ret = + let (duration, ret) = run_test(runnable_test, rustdoc_options, self.supports_color, |_: UnusedExterns| {}); - if let Err(TestFailure::CompileError) = ret { Err(()) } else { Ok(ret.is_ok()) } + (duration, if let Err(TestFailure::CompileError) = ret { Err(()) } else { Ok(ret.is_ok()) }) } } From 64e3078bbd6b5ac7246735c9ee0a16a091e6f45f Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 22 Jul 2025 16:00:25 +0200 Subject: [PATCH 107/809] Update rustdoc ui tests --- tests/rustdoc-ui/2024-doctests-checks.rs | 2 + tests/rustdoc-ui/2024-doctests-checks.stdout | 5 +- .../2024-doctests-crate-attribute.rs | 2 + .../2024-doctests-crate-attribute.stdout | 5 +- tests/rustdoc-ui/doctest/dead-code-2024.rs | 2 + .../rustdoc-ui/doctest/dead-code-2024.stdout | 11 +-- tests/rustdoc-ui/doctest/dead-code-items.rs | 2 + .../rustdoc-ui/doctest/dead-code-items.stdout | 83 ++++++++++--------- .../rustdoc-ui/doctest/dead-code-module-2.rs | 2 + .../doctest/dead-code-module-2.stdout | 13 +-- tests/rustdoc-ui/doctest/dead-code-module.rs | 2 + .../doctest/dead-code-module.stdout | 11 +-- .../doctest/doctest-output-include-fail.rs | 2 + .../doctest-output-include-fail.stdout | 1 + .../doctest/edition-2024-error-output.rs | 2 + .../doctest/edition-2024-error-output.stdout | 7 +- .../doctest/failed-doctest-should-panic.rs | 2 + .../failed-doctest-should-panic.stdout | 9 +- ...iled-doctest-test-crate.edition2015.stdout | 8 +- ...iled-doctest-test-crate.edition2024.stdout | 9 +- .../doctest/failed-doctest-test-crate.rs | 2 + ...th-include-bytes-132203.edition2015.stdout | 8 +- ...th-include-bytes-132203.edition2024.stdout | 1 + .../relative-path-include-bytes-132203.rs | 2 + tests/rustdoc-ui/doctest/stdout-and-stderr.rs | 2 + .../doctest/stdout-and-stderr.stdout | 19 +++-- tests/rustdoc-ui/doctest/wrong-ast-2024.rs | 2 + .../rustdoc-ui/doctest/wrong-ast-2024.stdout | 15 ++-- 28 files changed, 135 insertions(+), 96 deletions(-) diff --git a/tests/rustdoc-ui/2024-doctests-checks.rs b/tests/rustdoc-ui/2024-doctests-checks.rs index 0c3a11771f34..61f90fe62310 100644 --- a/tests/rustdoc-ui/2024-doctests-checks.rs +++ b/tests/rustdoc-ui/2024-doctests-checks.rs @@ -3,6 +3,8 @@ //@ compile-flags: --test --test-args=--test-threads=1 //@ normalize-stdout: "tests/rustdoc-ui" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ normalize-stdout: ".rs:\d+:\d+" -> ".rs:$$LINE:$$COL" /// ``` diff --git a/tests/rustdoc-ui/2024-doctests-checks.stdout b/tests/rustdoc-ui/2024-doctests-checks.stdout index 534fe466fe70..c86eafd61b91 100644 --- a/tests/rustdoc-ui/2024-doctests-checks.stdout +++ b/tests/rustdoc-ui/2024-doctests-checks.stdout @@ -1,12 +1,13 @@ running 1 test -test $DIR/2024-doctests-checks.rs - Foo (line 8) ... ok +test $DIR/2024-doctests-checks.rs - Foo (line 10) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME running 1 test -test $DIR/2024-doctests-checks.rs - Foo (line 15) ... ok +test $DIR/2024-doctests-checks.rs - Foo (line 17) ... ok test result: ok. 1 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/tests/rustdoc-ui/2024-doctests-crate-attribute.rs b/tests/rustdoc-ui/2024-doctests-crate-attribute.rs index c9887cbc63ba..416d50cb0701 100644 --- a/tests/rustdoc-ui/2024-doctests-crate-attribute.rs +++ b/tests/rustdoc-ui/2024-doctests-crate-attribute.rs @@ -4,6 +4,8 @@ //@ normalize-stdout: "tests/rustdoc-ui" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" //@ normalize-stdout: ".rs:\d+:\d+" -> ".rs:$$LINE:$$COL" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" /// This doctest is used to ensure that if a crate attribute is present, /// it will not be part of the merged doctests. diff --git a/tests/rustdoc-ui/2024-doctests-crate-attribute.stdout b/tests/rustdoc-ui/2024-doctests-crate-attribute.stdout index c084ac4522e8..20618426312e 100644 --- a/tests/rustdoc-ui/2024-doctests-crate-attribute.stdout +++ b/tests/rustdoc-ui/2024-doctests-crate-attribute.stdout @@ -1,12 +1,13 @@ running 1 test -test $DIR/2024-doctests-crate-attribute.rs - Foo (line 20) ... ok +test $DIR/2024-doctests-crate-attribute.rs - Foo (line 22) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME running 1 test -test $DIR/2024-doctests-crate-attribute.rs - Foo (line 11) ... ok +test $DIR/2024-doctests-crate-attribute.rs - Foo (line 13) ... ok test result: ok. 1 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/tests/rustdoc-ui/doctest/dead-code-2024.rs b/tests/rustdoc-ui/doctest/dead-code-2024.rs index 079d44570bba..e02d2601c588 100644 --- a/tests/rustdoc-ui/doctest/dead-code-2024.rs +++ b/tests/rustdoc-ui/doctest/dead-code-2024.rs @@ -4,6 +4,8 @@ //@ compile-flags:--test //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 #![doc(test(attr(allow(unused_variables), deny(warnings))))] diff --git a/tests/rustdoc-ui/doctest/dead-code-2024.stdout b/tests/rustdoc-ui/doctest/dead-code-2024.stdout index a943a177e10b..bf9cd65200b2 100644 --- a/tests/rustdoc-ui/doctest/dead-code-2024.stdout +++ b/tests/rustdoc-ui/doctest/dead-code-2024.stdout @@ -1,18 +1,18 @@ running 1 test -test $DIR/dead-code-2024.rs - f (line 13) - compile ... FAILED +test $DIR/dead-code-2024.rs - f (line 15) - compile ... FAILED failures: ----- $DIR/dead-code-2024.rs - f (line 13) stdout ---- +---- $DIR/dead-code-2024.rs - f (line 15) stdout ---- error: trait `T` is never used - --> $DIR/dead-code-2024.rs:14:7 + --> $DIR/dead-code-2024.rs:16:7 | LL | trait T { fn f(); } | ^ | note: the lint level is defined here - --> $DIR/dead-code-2024.rs:12:9 + --> $DIR/dead-code-2024.rs:14:9 | LL | #![deny(warnings)] | ^^^^^^^^ @@ -23,7 +23,8 @@ error: aborting due to 1 previous error Couldn't compile the test. failures: - $DIR/dead-code-2024.rs - f (line 13) + $DIR/dead-code-2024.rs - f (line 15) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/dead-code-items.rs b/tests/rustdoc-ui/doctest/dead-code-items.rs index 015504cbcedb..ff59bfaabc47 100644 --- a/tests/rustdoc-ui/doctest/dead-code-items.rs +++ b/tests/rustdoc-ui/doctest/dead-code-items.rs @@ -4,6 +4,8 @@ //@ compile-flags:--test --test-args=--test-threads=1 //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 #![doc(test(attr(deny(warnings))))] diff --git a/tests/rustdoc-ui/doctest/dead-code-items.stdout b/tests/rustdoc-ui/doctest/dead-code-items.stdout index 4b9d8be94dd3..ecfe09f09ce2 100644 --- a/tests/rustdoc-ui/doctest/dead-code-items.stdout +++ b/tests/rustdoc-ui/doctest/dead-code-items.stdout @@ -1,30 +1,30 @@ running 13 tests -test $DIR/dead-code-items.rs - A (line 32) - compile ... ok -test $DIR/dead-code-items.rs - A (line 88) - compile ... ok -test $DIR/dead-code-items.rs - A::field (line 39) - compile ... FAILED -test $DIR/dead-code-items.rs - A::method (line 94) - compile ... ok -test $DIR/dead-code-items.rs - C (line 22) - compile ... FAILED -test $DIR/dead-code-items.rs - Enum (line 70) - compile ... FAILED -test $DIR/dead-code-items.rs - Enum::Variant1 (line 77) - compile ... FAILED -test $DIR/dead-code-items.rs - MyTrait (line 103) - compile ... FAILED -test $DIR/dead-code-items.rs - MyTrait::my_trait_fn (line 110) - compile ... FAILED -test $DIR/dead-code-items.rs - S (line 14) - compile ... ok -test $DIR/dead-code-items.rs - U (line 48) - compile ... ok -test $DIR/dead-code-items.rs - U::field (line 55) - compile ... FAILED -test $DIR/dead-code-items.rs - U::field2 (line 61) - compile ... ok +test $DIR/dead-code-items.rs - A (line 34) - compile ... ok +test $DIR/dead-code-items.rs - A (line 90) - compile ... ok +test $DIR/dead-code-items.rs - A::field (line 41) - compile ... FAILED +test $DIR/dead-code-items.rs - A::method (line 96) - compile ... ok +test $DIR/dead-code-items.rs - C (line 24) - compile ... FAILED +test $DIR/dead-code-items.rs - Enum (line 72) - compile ... FAILED +test $DIR/dead-code-items.rs - Enum::Variant1 (line 79) - compile ... FAILED +test $DIR/dead-code-items.rs - MyTrait (line 105) - compile ... FAILED +test $DIR/dead-code-items.rs - MyTrait::my_trait_fn (line 112) - compile ... FAILED +test $DIR/dead-code-items.rs - S (line 16) - compile ... ok +test $DIR/dead-code-items.rs - U (line 50) - compile ... ok +test $DIR/dead-code-items.rs - U::field (line 57) - compile ... FAILED +test $DIR/dead-code-items.rs - U::field2 (line 63) - compile ... ok failures: ----- $DIR/dead-code-items.rs - A::field (line 39) stdout ---- +---- $DIR/dead-code-items.rs - A::field (line 41) stdout ---- error: trait `DeadCodeInField` is never used - --> $DIR/dead-code-items.rs:40:7 + --> $DIR/dead-code-items.rs:42:7 | LL | trait DeadCodeInField {} | ^^^^^^^^^^^^^^^ | note: the lint level is defined here - --> $DIR/dead-code-items.rs:38:9 + --> $DIR/dead-code-items.rs:40:9 | LL | #![deny(dead_code)] | ^^^^^^^^^ @@ -32,15 +32,15 @@ LL | #![deny(dead_code)] error: aborting due to 1 previous error Couldn't compile the test. ----- $DIR/dead-code-items.rs - C (line 22) stdout ---- +---- $DIR/dead-code-items.rs - C (line 24) stdout ---- error: unused variable: `unused_error` - --> $DIR/dead-code-items.rs:23:5 + --> $DIR/dead-code-items.rs:25:5 | LL | let unused_error = 5; | ^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused_error` | note: the lint level is defined here - --> $DIR/dead-code-items.rs:20:9 + --> $DIR/dead-code-items.rs:22:9 | LL | #![deny(warnings)] | ^^^^^^^^ @@ -49,15 +49,15 @@ LL | #![deny(warnings)] error: aborting due to 1 previous error Couldn't compile the test. ----- $DIR/dead-code-items.rs - Enum (line 70) stdout ---- +---- $DIR/dead-code-items.rs - Enum (line 72) stdout ---- error: unused variable: `not_dead_code_but_unused` - --> $DIR/dead-code-items.rs:71:5 + --> $DIR/dead-code-items.rs:73:5 | LL | let not_dead_code_but_unused = 5; | ^^^^^^^^^^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_not_dead_code_but_unused` | note: the lint level is defined here - --> $DIR/dead-code-items.rs:68:9 + --> $DIR/dead-code-items.rs:70:9 | LL | #![deny(warnings)] | ^^^^^^^^ @@ -66,15 +66,15 @@ LL | #![deny(warnings)] error: aborting due to 1 previous error Couldn't compile the test. ----- $DIR/dead-code-items.rs - Enum::Variant1 (line 77) stdout ---- +---- $DIR/dead-code-items.rs - Enum::Variant1 (line 79) stdout ---- error: unused variable: `unused_in_variant` - --> $DIR/dead-code-items.rs:80:17 + --> $DIR/dead-code-items.rs:82:17 | LL | fn main() { let unused_in_variant = 5; } | ^^^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused_in_variant` | note: the lint level is defined here - --> $DIR/dead-code-items.rs:75:9 + --> $DIR/dead-code-items.rs:77:9 | LL | #![deny(warnings)] | ^^^^^^^^ @@ -83,15 +83,15 @@ LL | #![deny(warnings)] error: aborting due to 1 previous error Couldn't compile the test. ----- $DIR/dead-code-items.rs - MyTrait (line 103) stdout ---- +---- $DIR/dead-code-items.rs - MyTrait (line 105) stdout ---- error: trait `StillDeadCodeAtMyTrait` is never used - --> $DIR/dead-code-items.rs:104:7 + --> $DIR/dead-code-items.rs:106:7 | LL | trait StillDeadCodeAtMyTrait { } | ^^^^^^^^^^^^^^^^^^^^^^ | note: the lint level is defined here - --> $DIR/dead-code-items.rs:102:9 + --> $DIR/dead-code-items.rs:104:9 | LL | #![deny(dead_code)] | ^^^^^^^^^ @@ -99,15 +99,15 @@ LL | #![deny(dead_code)] error: aborting due to 1 previous error Couldn't compile the test. ----- $DIR/dead-code-items.rs - MyTrait::my_trait_fn (line 110) stdout ---- +---- $DIR/dead-code-items.rs - MyTrait::my_trait_fn (line 112) stdout ---- error: unused variable: `unused_in_impl` - --> $DIR/dead-code-items.rs:113:17 + --> $DIR/dead-code-items.rs:115:17 | LL | fn main() { let unused_in_impl = 5; } | ^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused_in_impl` | note: the lint level is defined here - --> $DIR/dead-code-items.rs:108:9 + --> $DIR/dead-code-items.rs:110:9 | LL | #![deny(warnings)] | ^^^^^^^^ @@ -116,15 +116,15 @@ LL | #![deny(warnings)] error: aborting due to 1 previous error Couldn't compile the test. ----- $DIR/dead-code-items.rs - U::field (line 55) stdout ---- +---- $DIR/dead-code-items.rs - U::field (line 57) stdout ---- error: trait `DeadCodeInUnionField` is never used - --> $DIR/dead-code-items.rs:56:7 + --> $DIR/dead-code-items.rs:58:7 | LL | trait DeadCodeInUnionField {} | ^^^^^^^^^^^^^^^^^^^^ | note: the lint level is defined here - --> $DIR/dead-code-items.rs:54:9 + --> $DIR/dead-code-items.rs:56:9 | LL | #![deny(dead_code)] | ^^^^^^^^^ @@ -134,13 +134,14 @@ error: aborting due to 1 previous error Couldn't compile the test. failures: - $DIR/dead-code-items.rs - A::field (line 39) - $DIR/dead-code-items.rs - C (line 22) - $DIR/dead-code-items.rs - Enum (line 70) - $DIR/dead-code-items.rs - Enum::Variant1 (line 77) - $DIR/dead-code-items.rs - MyTrait (line 103) - $DIR/dead-code-items.rs - MyTrait::my_trait_fn (line 110) - $DIR/dead-code-items.rs - U::field (line 55) + $DIR/dead-code-items.rs - A::field (line 41) + $DIR/dead-code-items.rs - C (line 24) + $DIR/dead-code-items.rs - Enum (line 72) + $DIR/dead-code-items.rs - Enum::Variant1 (line 79) + $DIR/dead-code-items.rs - MyTrait (line 105) + $DIR/dead-code-items.rs - MyTrait::my_trait_fn (line 112) + $DIR/dead-code-items.rs - U::field (line 57) test result: FAILED. 6 passed; 7 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/dead-code-module-2.rs b/tests/rustdoc-ui/doctest/dead-code-module-2.rs index de7b11b91ec5..fd9c313ec9a4 100644 --- a/tests/rustdoc-ui/doctest/dead-code-module-2.rs +++ b/tests/rustdoc-ui/doctest/dead-code-module-2.rs @@ -4,6 +4,8 @@ //@ compile-flags:--test //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 #![doc(test(attr(allow(unused_variables))))] diff --git a/tests/rustdoc-ui/doctest/dead-code-module-2.stdout b/tests/rustdoc-ui/doctest/dead-code-module-2.stdout index d44068dcbf5d..cf737996d5c9 100644 --- a/tests/rustdoc-ui/doctest/dead-code-module-2.stdout +++ b/tests/rustdoc-ui/doctest/dead-code-module-2.stdout @@ -1,24 +1,24 @@ running 1 test -test $DIR/dead-code-module-2.rs - g (line 24) - compile ... ok +test $DIR/dead-code-module-2.rs - g (line 26) - compile ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME running 1 test -test $DIR/dead-code-module-2.rs - my_mod::f (line 16) - compile ... FAILED +test $DIR/dead-code-module-2.rs - my_mod::f (line 18) - compile ... FAILED failures: ----- $DIR/dead-code-module-2.rs - my_mod::f (line 16) stdout ---- +---- $DIR/dead-code-module-2.rs - my_mod::f (line 18) stdout ---- error: trait `T` is never used - --> $DIR/dead-code-module-2.rs:17:7 + --> $DIR/dead-code-module-2.rs:19:7 | LL | trait T { fn f(); } | ^ | note: the lint level is defined here - --> $DIR/dead-code-module-2.rs:15:9 + --> $DIR/dead-code-module-2.rs:17:9 | LL | #![deny(warnings)] | ^^^^^^^^ @@ -29,7 +29,8 @@ error: aborting due to 1 previous error Couldn't compile the test. failures: - $DIR/dead-code-module-2.rs - my_mod::f (line 16) + $DIR/dead-code-module-2.rs - my_mod::f (line 18) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/dead-code-module.rs b/tests/rustdoc-ui/doctest/dead-code-module.rs index f825749a6a25..d3103ad28e9b 100644 --- a/tests/rustdoc-ui/doctest/dead-code-module.rs +++ b/tests/rustdoc-ui/doctest/dead-code-module.rs @@ -4,6 +4,8 @@ //@ compile-flags:--test //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 mod my_mod { diff --git a/tests/rustdoc-ui/doctest/dead-code-module.stdout b/tests/rustdoc-ui/doctest/dead-code-module.stdout index b5ccf225d25c..83c6af3775e0 100644 --- a/tests/rustdoc-ui/doctest/dead-code-module.stdout +++ b/tests/rustdoc-ui/doctest/dead-code-module.stdout @@ -1,18 +1,18 @@ running 1 test -test $DIR/dead-code-module.rs - my_mod::f (line 14) - compile ... FAILED +test $DIR/dead-code-module.rs - my_mod::f (line 16) - compile ... FAILED failures: ----- $DIR/dead-code-module.rs - my_mod::f (line 14) stdout ---- +---- $DIR/dead-code-module.rs - my_mod::f (line 16) stdout ---- error: trait `T` is never used - --> $DIR/dead-code-module.rs:15:7 + --> $DIR/dead-code-module.rs:17:7 | LL | trait T { fn f(); } | ^ | note: the lint level is defined here - --> $DIR/dead-code-module.rs:13:9 + --> $DIR/dead-code-module.rs:15:9 | LL | #![deny(warnings)] | ^^^^^^^^ @@ -23,7 +23,8 @@ error: aborting due to 1 previous error Couldn't compile the test. failures: - $DIR/dead-code-module.rs - my_mod::f (line 14) + $DIR/dead-code-module.rs - my_mod::f (line 16) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/doctest-output-include-fail.rs b/tests/rustdoc-ui/doctest/doctest-output-include-fail.rs index a47bac3daefe..2f0d6756b27f 100644 --- a/tests/rustdoc-ui/doctest/doctest-output-include-fail.rs +++ b/tests/rustdoc-ui/doctest/doctest-output-include-fail.rs @@ -2,6 +2,8 @@ //@ compile-flags:--test --test-args=--test-threads=1 //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 // https://github.com/rust-lang/rust/issues/130470 diff --git a/tests/rustdoc-ui/doctest/doctest-output-include-fail.stdout b/tests/rustdoc-ui/doctest/doctest-output-include-fail.stdout index 22d15f8743c6..ceaf60b12015 100644 --- a/tests/rustdoc-ui/doctest/doctest-output-include-fail.stdout +++ b/tests/rustdoc-ui/doctest/doctest-output-include-fail.stdout @@ -22,3 +22,4 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/edition-2024-error-output.rs b/tests/rustdoc-ui/doctest/edition-2024-error-output.rs index 82a85debcd19..e1e57ad01cdd 100644 --- a/tests/rustdoc-ui/doctest/edition-2024-error-output.rs +++ b/tests/rustdoc-ui/doctest/edition-2024-error-output.rs @@ -6,6 +6,8 @@ //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "panicked at .+rs:" -> "panicked at $$TMP:" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ rustc-env:RUST_BACKTRACE=0 //@ failure-status: 101 diff --git a/tests/rustdoc-ui/doctest/edition-2024-error-output.stdout b/tests/rustdoc-ui/doctest/edition-2024-error-output.stdout index 273d70712373..ab6aca239afb 100644 --- a/tests/rustdoc-ui/doctest/edition-2024-error-output.stdout +++ b/tests/rustdoc-ui/doctest/edition-2024-error-output.stdout @@ -1,10 +1,10 @@ running 1 test -test $DIR/edition-2024-error-output.rs - (line 12) ... FAILED +test $DIR/edition-2024-error-output.rs - (line 14) ... FAILED failures: ----- $DIR/edition-2024-error-output.rs - (line 12) stdout ---- +---- $DIR/edition-2024-error-output.rs - (line 14) stdout ---- Test executable failed (exit status: 101). stderr: @@ -18,7 +18,8 @@ note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: - $DIR/edition-2024-error-output.rs - (line 12) + $DIR/edition-2024-error-output.rs - (line 14) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/failed-doctest-should-panic.rs b/tests/rustdoc-ui/doctest/failed-doctest-should-panic.rs index 793f86546610..0504c3dc7303 100644 --- a/tests/rustdoc-ui/doctest/failed-doctest-should-panic.rs +++ b/tests/rustdoc-ui/doctest/failed-doctest-should-panic.rs @@ -5,6 +5,8 @@ //@ compile-flags:--test //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 /// ```should_panic diff --git a/tests/rustdoc-ui/doctest/failed-doctest-should-panic.stdout b/tests/rustdoc-ui/doctest/failed-doctest-should-panic.stdout index 2b04b77c9dc5..9047fe0dcdd9 100644 --- a/tests/rustdoc-ui/doctest/failed-doctest-should-panic.stdout +++ b/tests/rustdoc-ui/doctest/failed-doctest-should-panic.stdout @@ -1,14 +1,15 @@ running 1 test -test $DIR/failed-doctest-should-panic.rs - Foo (line 10) - should panic ... FAILED +test $DIR/failed-doctest-should-panic.rs - Foo (line 12) - should panic ... FAILED failures: ----- $DIR/failed-doctest-should-panic.rs - Foo (line 10) stdout ---- -note: test did not panic as expected at $DIR/failed-doctest-should-panic.rs:10:0 +---- $DIR/failed-doctest-should-panic.rs - Foo (line 12) stdout ---- +note: test did not panic as expected at $DIR/failed-doctest-should-panic.rs:12:0 failures: - $DIR/failed-doctest-should-panic.rs - Foo (line 10) + $DIR/failed-doctest-should-panic.rs - Foo (line 12) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/failed-doctest-test-crate.edition2015.stdout b/tests/rustdoc-ui/doctest/failed-doctest-test-crate.edition2015.stdout index ce767fb8443d..d80c0da323d3 100644 --- a/tests/rustdoc-ui/doctest/failed-doctest-test-crate.edition2015.stdout +++ b/tests/rustdoc-ui/doctest/failed-doctest-test-crate.edition2015.stdout @@ -1,12 +1,12 @@ running 1 test -test $DIR/failed-doctest-test-crate.rs - m (line 14) ... FAILED +test $DIR/failed-doctest-test-crate.rs - m (line 16) ... FAILED failures: ----- $DIR/failed-doctest-test-crate.rs - m (line 14) stdout ---- +---- $DIR/failed-doctest-test-crate.rs - m (line 16) stdout ---- error[E0432]: unresolved import `test` - --> $DIR/failed-doctest-test-crate.rs:15:5 + --> $DIR/failed-doctest-test-crate.rs:17:5 | LL | use test::*; | ^^^^ use of unresolved module or unlinked crate `test` @@ -22,7 +22,7 @@ For more information about this error, try `rustc --explain E0432`. Couldn't compile the test. failures: - $DIR/failed-doctest-test-crate.rs - m (line 14) + $DIR/failed-doctest-test-crate.rs - m (line 16) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc-ui/doctest/failed-doctest-test-crate.edition2024.stdout b/tests/rustdoc-ui/doctest/failed-doctest-test-crate.edition2024.stdout index 80642e93bbde..724bb9bee62d 100644 --- a/tests/rustdoc-ui/doctest/failed-doctest-test-crate.edition2024.stdout +++ b/tests/rustdoc-ui/doctest/failed-doctest-test-crate.edition2024.stdout @@ -1,12 +1,12 @@ running 1 test -test $DIR/failed-doctest-test-crate.rs - m (line 14) ... FAILED +test $DIR/failed-doctest-test-crate.rs - m (line 16) ... FAILED failures: ----- $DIR/failed-doctest-test-crate.rs - m (line 14) stdout ---- +---- $DIR/failed-doctest-test-crate.rs - m (line 16) stdout ---- error[E0432]: unresolved import `test` - --> $DIR/failed-doctest-test-crate.rs:15:5 + --> $DIR/failed-doctest-test-crate.rs:17:5 | LL | use test::*; | ^^^^ use of unresolved module or unlinked crate `test` @@ -19,7 +19,8 @@ For more information about this error, try `rustc --explain E0432`. Couldn't compile the test. failures: - $DIR/failed-doctest-test-crate.rs - m (line 14) + $DIR/failed-doctest-test-crate.rs - m (line 16) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/failed-doctest-test-crate.rs b/tests/rustdoc-ui/doctest/failed-doctest-test-crate.rs index 6966d3df11ce..75f7ac396f55 100644 --- a/tests/rustdoc-ui/doctest/failed-doctest-test-crate.rs +++ b/tests/rustdoc-ui/doctest/failed-doctest-test-crate.rs @@ -7,6 +7,8 @@ //@ compile-flags:--test //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 /// diff --git a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2015.stdout b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2015.stdout index ff26e7e32318..0d00a9fc9c45 100644 --- a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2015.stdout +++ b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2015.stdout @@ -1,12 +1,12 @@ running 1 test -test $DIR/relative-path-include-bytes-132203.rs - (line 18) ... FAILED +test $DIR/relative-path-include-bytes-132203.rs - (line 20) ... FAILED failures: ----- $DIR/relative-path-include-bytes-132203.rs - (line 18) stdout ---- +---- $DIR/relative-path-include-bytes-132203.rs - (line 20) stdout ---- error: couldn't read `$DIR/relative-dir-empty-file`: $FILE_NOT_FOUND_MSG (os error 2) - --> $DIR/relative-path-include-bytes-132203.rs:19:9 + --> $DIR/relative-path-include-bytes-132203.rs:21:9 | LL | let x = include_bytes!("relative-dir-empty-file"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -16,7 +16,7 @@ error: aborting due to 1 previous error Couldn't compile the test. failures: - $DIR/relative-path-include-bytes-132203.rs - (line 18) + $DIR/relative-path-include-bytes-132203.rs - (line 20) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2024.stdout b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2024.stdout index e4c657030819..fa5bd7c93fa3 100644 --- a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2024.stdout +++ b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2024.stdout @@ -4,3 +4,4 @@ test $DIR/auxiliary/relative-dir.md - (line 1) ... ok test result: ok. 1 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/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.rs b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.rs index ceacd69a5fd5..321edc3ee843 100644 --- a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.rs +++ b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.rs @@ -9,6 +9,8 @@ //@ normalize-stdout: "tests.rustdoc-ui.doctest." -> "$$DIR/" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" //@ normalize-stdout: "`: .* \(os error 2\)" -> "`: $$FILE_NOT_FOUND_MSG (os error 2)" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" // https://github.com/rust-lang/rust/issues/132203 // This version, because it's edition2024, passes thanks to the new diff --git a/tests/rustdoc-ui/doctest/stdout-and-stderr.rs b/tests/rustdoc-ui/doctest/stdout-and-stderr.rs index 9b0c69d88391..a4eda8c7f836 100644 --- a/tests/rustdoc-ui/doctest/stdout-and-stderr.rs +++ b/tests/rustdoc-ui/doctest/stdout-and-stderr.rs @@ -9,6 +9,8 @@ //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" //@ normalize-stdout: "panicked at .+rs:" -> "panicked at $$TMP:" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 //@ rustc-env:RUST_BACKTRACE=0 diff --git a/tests/rustdoc-ui/doctest/stdout-and-stderr.stdout b/tests/rustdoc-ui/doctest/stdout-and-stderr.stdout index b2febe1344f6..a35a4d7c3cb8 100644 --- a/tests/rustdoc-ui/doctest/stdout-and-stderr.stdout +++ b/tests/rustdoc-ui/doctest/stdout-and-stderr.stdout @@ -1,12 +1,12 @@ running 3 tests -test $DIR/stdout-and-stderr.rs - (line 15) ... FAILED -test $DIR/stdout-and-stderr.rs - (line 20) ... FAILED -test $DIR/stdout-and-stderr.rs - (line 24) ... FAILED +test $DIR/stdout-and-stderr.rs - (line 17) ... FAILED +test $DIR/stdout-and-stderr.rs - (line 22) ... FAILED +test $DIR/stdout-and-stderr.rs - (line 26) ... FAILED failures: ----- $DIR/stdout-and-stderr.rs - (line 15) stdout ---- +---- $DIR/stdout-and-stderr.rs - (line 17) stdout ---- Test executable failed (exit status: 101). stdout: @@ -21,7 +21,7 @@ assertion `left == right` failed note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ----- $DIR/stdout-and-stderr.rs - (line 20) stdout ---- +---- $DIR/stdout-and-stderr.rs - (line 22) stdout ---- Test executable failed (exit status: 101). stderr: @@ -33,14 +33,15 @@ assertion `left == right` failed note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ----- $DIR/stdout-and-stderr.rs - (line 24) stdout ---- +---- $DIR/stdout-and-stderr.rs - (line 26) stdout ---- Test executable failed (exit status: 1). failures: - $DIR/stdout-and-stderr.rs - (line 15) - $DIR/stdout-and-stderr.rs - (line 20) - $DIR/stdout-and-stderr.rs - (line 24) + $DIR/stdout-and-stderr.rs - (line 17) + $DIR/stdout-and-stderr.rs - (line 22) + $DIR/stdout-and-stderr.rs - (line 26) test result: FAILED. 0 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME diff --git a/tests/rustdoc-ui/doctest/wrong-ast-2024.rs b/tests/rustdoc-ui/doctest/wrong-ast-2024.rs index 3b4fb3f34433..df30e01b25ed 100644 --- a/tests/rustdoc-ui/doctest/wrong-ast-2024.rs +++ b/tests/rustdoc-ui/doctest/wrong-ast-2024.rs @@ -3,6 +3,8 @@ //@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" //@ normalize-stdout: ".rs:\d+:\d+" -> ".rs:$$LINE:$$COL" +//@ normalize-stdout: "ran in \d+\.\d+s" -> "ran in $$TIME" +//@ normalize-stdout: "compilation took \d+\.\d+s" -> "compilation took $$TIME" //@ failure-status: 101 /// ``` diff --git a/tests/rustdoc-ui/doctest/wrong-ast-2024.stdout b/tests/rustdoc-ui/doctest/wrong-ast-2024.stdout index 62e1fb10b9f4..13567b41e51f 100644 --- a/tests/rustdoc-ui/doctest/wrong-ast-2024.stdout +++ b/tests/rustdoc-ui/doctest/wrong-ast-2024.stdout @@ -1,17 +1,17 @@ running 1 test -test $DIR/wrong-ast-2024.rs - three (line 18) - should panic ... ok +test $DIR/wrong-ast-2024.rs - three (line 20) - should panic ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME running 2 tests -test $DIR/wrong-ast-2024.rs - one (line 8) ... FAILED -test $DIR/wrong-ast-2024.rs - two (line 13) ... FAILED +test $DIR/wrong-ast-2024.rs - one (line 10) ... FAILED +test $DIR/wrong-ast-2024.rs - two (line 15) ... FAILED failures: ----- $DIR/wrong-ast-2024.rs - one (line 8) stdout ---- +---- $DIR/wrong-ast-2024.rs - one (line 10) stdout ---- error[E0758]: unterminated block comment --> $DIR/wrong-ast-2024.rs:$LINE:$COL | @@ -22,7 +22,7 @@ error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0758`. Couldn't compile the test. ----- $DIR/wrong-ast-2024.rs - two (line 13) stdout ---- +---- $DIR/wrong-ast-2024.rs - two (line 15) stdout ---- error: unexpected closing delimiter: `}` --> $DIR/wrong-ast-2024.rs:$LINE:$COL | @@ -34,8 +34,9 @@ error: aborting due to 1 previous error Couldn't compile the test. failures: - $DIR/wrong-ast-2024.rs - one (line 8) - $DIR/wrong-ast-2024.rs - two (line 13) + $DIR/wrong-ast-2024.rs - one (line 10) + $DIR/wrong-ast-2024.rs - two (line 15) test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME +all doctests ran in $TIME; merged doctests compilation took $TIME From 83aea652e444bd246600bb1b7a39b92482366bd2 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 04:05:41 -0500 Subject: [PATCH 108/809] 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 5e1ffef03c79a92143b87edd660a147d889e17d9 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 24 Jul 2025 09:14:46 +0000 Subject: [PATCH 109/809] Improve unit_tests tidy lint Make it clearer where unit tests are allowed and restrict standard library unit tests inside the same package to std_detect, std and test. --- src/tools/tidy/src/main.rs | 6 +-- src/tools/tidy/src/unit_tests.rs | 84 ++++++++++++++++++++------------ 2 files changed, 57 insertions(+), 33 deletions(-) diff --git a/src/tools/tidy/src/main.rs b/src/tools/tidy/src/main.rs index 13b20f33bd0f..1a32372d2093 100644 --- a/src/tools/tidy/src/main.rs +++ b/src/tools/tidy/src/main.rs @@ -127,9 +127,9 @@ fn main() { check!(pal, &library_path); // Checks that need to be done for both the compiler and std libraries. - check!(unit_tests, &src_path); - check!(unit_tests, &compiler_path); - check!(unit_tests, &library_path); + check!(unit_tests, &src_path, false); + check!(unit_tests, &compiler_path, false); + check!(unit_tests, &library_path, true); if bins::check_filesystem_support(&[&root_path], &output_directory) { check!(bins, &root_path); diff --git a/src/tools/tidy/src/unit_tests.rs b/src/tools/tidy/src/unit_tests.rs index df9146b51474..90da1bc765a9 100644 --- a/src/tools/tidy/src/unit_tests.rs +++ b/src/tools/tidy/src/unit_tests.rs @@ -1,44 +1,60 @@ //! Tidy check to ensure `#[test]` and `#[bench]` are not used directly inside -//! `core` or `alloc`. +//! of the standard library. //! //! `core` and `alloc` cannot be tested directly due to duplicating lang items. //! All tests and benchmarks must be written externally in //! `{coretests,alloctests}/{tests,benches}`. //! -//! Outside of `core` and `alloc`, tests and benchmarks should be outlined into -//! separate files named `tests.rs` or `benches.rs`, or directories named +//! Outside of the standard library, tests and benchmarks should be outlined +//! into separate files named `tests.rs` or `benches.rs`, or directories named //! `tests` or `benches` unconfigured during normal build. use std::path::Path; use crate::walk::{filter_dirs, walk}; -pub fn check(root_path: &Path, bad: &mut bool) { - let core = root_path.join("core"); - let core_copy = core.clone(); - let is_core = move |path: &Path| path.starts_with(&core); - let alloc = root_path.join("alloc"); - let alloc_copy = alloc.clone(); - let is_alloc = move |path: &Path| path.starts_with(&alloc); - +pub fn check(root_path: &Path, stdlib: bool, bad: &mut bool) { let skip = move |path: &Path, is_dir| { let file_name = path.file_name().unwrap_or_default(); + + // Skip excluded directories and non-rust files if is_dir { - filter_dirs(path) - || path.ends_with("src/doc") - || (file_name == "tests" || file_name == "benches") - && !is_core(path) - && !is_alloc(path) + if filter_dirs(path) || path.ends_with("src/doc") { + return true; + } } else { let extension = path.extension().unwrap_or_default(); - extension != "rs" - || (file_name == "tests.rs" || file_name == "benches.rs") - && !is_core(path) - && !is_alloc(path) - // Tests which use non-public internals and, as such, need to - // have the types in the same crate as the tests themselves. See - // the comment in alloctests/lib.rs. - || path.ends_with("library/alloc/src/collections/btree/borrow/tests.rs") + if extension != "rs" { + return true; + } + } + + // Tests in a separate package are always allowed + if is_dir && file_name != "tests" && file_name.as_encoded_bytes().ends_with(b"tests") { + return true; + } + + if !stdlib { + // Outside of the standard library tests may also be in separate files in the same crate + if is_dir { + if file_name == "tests" || file_name == "benches" { + return true; + } + } else { + if file_name == "tests.rs" || file_name == "benches.rs" { + return true; + } + } + } + + if is_dir { + // FIXME remove those exceptions once no longer necessary + file_name == "std_detect" || file_name == "std" || file_name == "test" + } else { + // Tests which use non-public internals and, as such, need to + // have the types in the same crate as the tests themselves. See + // the comment in alloctests/lib.rs. + path.ends_with("library/alloc/src/collections/btree/borrow/tests.rs") || path.ends_with("library/alloc/src/collections/btree/map/tests.rs") || path.ends_with("library/alloc/src/collections/btree/node/tests.rs") || path.ends_with("library/alloc/src/collections/btree/set/tests.rs") @@ -50,22 +66,30 @@ pub fn check(root_path: &Path, bad: &mut bool) { walk(root_path, skip, &mut |entry, contents| { let path = entry.path(); - let is_core = path.starts_with(&core_copy); - let is_alloc = path.starts_with(&alloc_copy); + let package = path + .strip_prefix(root_path) + .unwrap() + .components() + .next() + .unwrap() + .as_os_str() + .to_str() + .unwrap(); for (i, line) in contents.lines().enumerate() { let line = line.trim(); let is_test = || line.contains("#[test]") && !line.contains("`#[test]"); let is_bench = || line.contains("#[bench]") && !line.contains("`#[bench]"); let manual_skip = line.contains("//tidy:skip"); if !line.starts_with("//") && (is_test() || is_bench()) && !manual_skip { - let explanation = if is_core { - "`core` unit tests and benchmarks must be placed into `coretests`" - } else if is_alloc { - "`alloc` unit tests and benchmarks must be placed into `alloctests`" + let explanation = if stdlib { + format!( + "`{package}` unit tests and benchmarks must be placed into `{package}tests`" + ) } else { "unit tests and benchmarks must be placed into \ separate files or directories named \ `tests.rs`, `benches.rs`, `tests` or `benches`" + .to_owned() }; let name = if is_test() { "test" } else { "bench" }; tidy_error!( From c5d7021cddd97a4ec8dd64f878711ec983986fcd Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 24 Jul 2025 09:15:28 +0000 Subject: [PATCH 110/809] Disable unit tests for stdlib packages that don't contain any --- library/rustc-std-workspace-alloc/Cargo.toml | 3 +++ library/rustc-std-workspace-core/Cargo.toml | 3 +++ library/rustc-std-workspace-std/Cargo.toml | 3 +++ library/sysroot/Cargo.toml | 2 ++ library/windows_targets/Cargo.toml | 5 +++++ 5 files changed, 16 insertions(+) diff --git a/library/rustc-std-workspace-alloc/Cargo.toml b/library/rustc-std-workspace-alloc/Cargo.toml index 5a177808d1bd..a5b51059119c 100644 --- a/library/rustc-std-workspace-alloc/Cargo.toml +++ b/library/rustc-std-workspace-alloc/Cargo.toml @@ -9,6 +9,9 @@ edition = "2024" [lib] path = "lib.rs" +test = false +bench = false +doc = false [dependencies] alloc = { path = "../alloc" } diff --git a/library/rustc-std-workspace-core/Cargo.toml b/library/rustc-std-workspace-core/Cargo.toml index 1ddc112380f1..d68965c63457 100644 --- a/library/rustc-std-workspace-core/Cargo.toml +++ b/library/rustc-std-workspace-core/Cargo.toml @@ -11,6 +11,9 @@ edition = "2024" [lib] path = "lib.rs" +test = false +bench = false +doc = false [dependencies] core = { path = "../core", public = true } diff --git a/library/rustc-std-workspace-std/Cargo.toml b/library/rustc-std-workspace-std/Cargo.toml index f70994e1f886..6079dc85d906 100644 --- a/library/rustc-std-workspace-std/Cargo.toml +++ b/library/rustc-std-workspace-std/Cargo.toml @@ -9,6 +9,9 @@ edition = "2024" [lib] path = "lib.rs" +test = false +bench = false +doc = false [dependencies] std = { path = "../std" } diff --git a/library/sysroot/Cargo.toml b/library/sysroot/Cargo.toml index 032f5272a9cd..2952556f699d 100644 --- a/library/sysroot/Cargo.toml +++ b/library/sysroot/Cargo.toml @@ -6,6 +6,8 @@ version = "0.0.0" edition = "2024" [lib] +test = false +bench = false # make sure this crate isn't included in public standard library docs doc = false diff --git a/library/windows_targets/Cargo.toml b/library/windows_targets/Cargo.toml index 705c9e043811..1c804a0ab391 100644 --- a/library/windows_targets/Cargo.toml +++ b/library/windows_targets/Cargo.toml @@ -4,6 +4,11 @@ description = "A drop-in replacement for the real windows-targets crate for use version = "0.0.0" edition = "2024" +[lib] +test = false +bench = false +doc = false + [features] # Enable using raw-dylib for Windows imports. # This will eventually be the default. From 5c4abe9ca022cff5fa8d334423a34a8cdc356f05 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 04:49:46 -0500 Subject: [PATCH 111/809] 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 fd114d465a7facfd7be01a290bf42ae6a1e9d649 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 24 Jul 2025 14:00:15 +0200 Subject: [PATCH 112/809] make the missing-MIR message more clear --- src/tools/miri/src/eval.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index 3c80e60b772a..f78908aba8ed 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -334,8 +334,8 @@ pub fn create_ecx<'tcx>( helpers::try_resolve_path(tcx, &["core", "ascii", "escape_default"], Namespace::ValueNS); if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) { tcx.dcx().fatal( - "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing. \ - Use `cargo miri setup` to prepare a sysroot that is suitable for Miri." + "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing.\n\ + Note that directly invoking the `miri` binary is not supported; please use `cargo miri` instead." ); } From d636a6590ce1429ff011e04bb0b4d393dc382226 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Thu, 24 Jul 2025 17:15:36 +0500 Subject: [PATCH 113/809] moved 35 tests to organized locations --- .../issue-11709.rs => block-result/blocks-without-results.rs} | 0 .../issue-12033.rs => borrowck/refcell-borrow-comparison.rs} | 0 .../ui/{issues/issue-12127.rs => closures/fnonce-moved-twice.rs} | 0 .../{issues/issue-11958.rs => closures/moved-upvar-mut-rebind.rs} | 0 .../issue-12860.rs => collections/hashset-connected-border.rs} | 0 .../vec-macro-in-static-array.rs} | 0 .../format-message-windows-ffi.rs} | 0 .../{issues/issue-13105.rs => fn/anonymous-parameters-trait.rs} | 0 tests/ui/{issues/issue-12729.rs => imports/use-in-impl-scope.rs} | 0 .../{issues/issue-12677.rs => iterators/bytes-iterator-clone.rs} | 0 .../issue-13167.rs => iterators/phf-map-entries-iterator.rs} | 0 .../issue-13058.rs => lifetimes/iterator-trait-lifetime-error.rs} | 0 .../struct-lifetime-field-assignment.rs} | 0 .../{issues/issue-12863.rs => match/function-in-pattern-error.rs} | 0 .../issue-13027.rs => match/guard-literal-range-shadow.rs} | 0 .../ui/{issues/issue-11844.rs => match/option-result-mismatch.rs} | 0 .../issue-13466.rs => match/option-result-type-param-mismatch.rs} | 0 tests/ui/{issues/issue-12567.rs => match/slice-move-out-error.rs} | 0 .../issue-11869.rs => match/string-literal-match-patterns.rs} | 0 .../{issues/issue-12285.rs => match/struct-reference-patterns.rs} | 0 .../issue-12920.rs => panics/explicit-panic-unreachable.rs} | 0 .../ui/{issues/issue-13202.rs => panics/unwrap-or-panic-input.rs} | 0 .../issue-13407.rs => privacy/private-unit-struct-assignment.rs} | 0 .../issue-13214.rs => statics/enum-with-static-str-variant.rs} | 0 .../issue-12041.rs => threads/moved-value-in-thread-loop.rs} | 0 .../{issues/issue-12744.rs => traits/any-trait-object-debug.rs} | 0 .../issue-13204.rs => traits/default-method-lifetime-params.rs} | 0 .../{issues/issue-13264.rs => traits/deref-chain-method-calls.rs} | 0 .../{issues/issue-13434.rs => traits/fnonce-repro-trait-impl.rs} | 0 .../{issues/issue-13323.rs => traits/matcher-trait-equality.rs} | 0 .../{issues/issue-11820.rs => traits/reference-clone-noclone.rs} | 0 .../isize-usize-mismatch-error.rs} | 0 .../issue-12909.rs => type-inference/type-collect-inference.rs} | 0 .../issue-11771.rs => type-inference/unit-type-add-error.rs} | 0 .../{issues/issue-11740.rs => unsafe/unsafe-transmute-in-find.rs} | 0 35 files changed, 0 insertions(+), 0 deletions(-) rename tests/ui/{issues/issue-11709.rs => block-result/blocks-without-results.rs} (100%) rename tests/ui/{issues/issue-12033.rs => borrowck/refcell-borrow-comparison.rs} (100%) rename tests/ui/{issues/issue-12127.rs => closures/fnonce-moved-twice.rs} (100%) rename tests/ui/{issues/issue-11958.rs => closures/moved-upvar-mut-rebind.rs} (100%) rename tests/ui/{issues/issue-12860.rs => collections/hashset-connected-border.rs} (100%) rename tests/ui/{issues/issue-13446.rs => const-generics/vec-macro-in-static-array.rs} (100%) rename tests/ui/{issues/issue-13259-windows-tcb-trash.rs => extern/format-message-windows-ffi.rs} (100%) rename tests/ui/{issues/issue-13105.rs => fn/anonymous-parameters-trait.rs} (100%) rename tests/ui/{issues/issue-12729.rs => imports/use-in-impl-scope.rs} (100%) rename tests/ui/{issues/issue-12677.rs => iterators/bytes-iterator-clone.rs} (100%) rename tests/ui/{issues/issue-13167.rs => iterators/phf-map-entries-iterator.rs} (100%) rename tests/ui/{issues/issue-13058.rs => lifetimes/iterator-trait-lifetime-error.rs} (100%) rename tests/ui/{issues/issue-13405.rs => lifetimes/struct-lifetime-field-assignment.rs} (100%) rename tests/ui/{issues/issue-12863.rs => match/function-in-pattern-error.rs} (100%) rename tests/ui/{issues/issue-13027.rs => match/guard-literal-range-shadow.rs} (100%) rename tests/ui/{issues/issue-11844.rs => match/option-result-mismatch.rs} (100%) rename tests/ui/{issues/issue-13466.rs => match/option-result-type-param-mismatch.rs} (100%) rename tests/ui/{issues/issue-12567.rs => match/slice-move-out-error.rs} (100%) rename tests/ui/{issues/issue-11869.rs => match/string-literal-match-patterns.rs} (100%) rename tests/ui/{issues/issue-12285.rs => match/struct-reference-patterns.rs} (100%) rename tests/ui/{issues/issue-12920.rs => panics/explicit-panic-unreachable.rs} (100%) rename tests/ui/{issues/issue-13202.rs => panics/unwrap-or-panic-input.rs} (100%) rename tests/ui/{issues/issue-13407.rs => privacy/private-unit-struct-assignment.rs} (100%) rename tests/ui/{issues/issue-13214.rs => statics/enum-with-static-str-variant.rs} (100%) rename tests/ui/{issues/issue-12041.rs => threads/moved-value-in-thread-loop.rs} (100%) rename tests/ui/{issues/issue-12744.rs => traits/any-trait-object-debug.rs} (100%) rename tests/ui/{issues/issue-13204.rs => traits/default-method-lifetime-params.rs} (100%) rename tests/ui/{issues/issue-13264.rs => traits/deref-chain-method-calls.rs} (100%) rename tests/ui/{issues/issue-13434.rs => traits/fnonce-repro-trait-impl.rs} (100%) rename tests/ui/{issues/issue-13323.rs => traits/matcher-trait-equality.rs} (100%) rename tests/ui/{issues/issue-11820.rs => traits/reference-clone-noclone.rs} (100%) rename tests/ui/{issues/issue-13359.rs => type-inference/isize-usize-mismatch-error.rs} (100%) rename tests/ui/{issues/issue-12909.rs => type-inference/type-collect-inference.rs} (100%) rename tests/ui/{issues/issue-11771.rs => type-inference/unit-type-add-error.rs} (100%) rename tests/ui/{issues/issue-11740.rs => unsafe/unsafe-transmute-in-find.rs} (100%) diff --git a/tests/ui/issues/issue-11709.rs b/tests/ui/block-result/blocks-without-results.rs similarity index 100% rename from tests/ui/issues/issue-11709.rs rename to tests/ui/block-result/blocks-without-results.rs diff --git a/tests/ui/issues/issue-12033.rs b/tests/ui/borrowck/refcell-borrow-comparison.rs similarity index 100% rename from tests/ui/issues/issue-12033.rs rename to tests/ui/borrowck/refcell-borrow-comparison.rs diff --git a/tests/ui/issues/issue-12127.rs b/tests/ui/closures/fnonce-moved-twice.rs similarity index 100% rename from tests/ui/issues/issue-12127.rs rename to tests/ui/closures/fnonce-moved-twice.rs diff --git a/tests/ui/issues/issue-11958.rs b/tests/ui/closures/moved-upvar-mut-rebind.rs similarity index 100% rename from tests/ui/issues/issue-11958.rs rename to tests/ui/closures/moved-upvar-mut-rebind.rs diff --git a/tests/ui/issues/issue-12860.rs b/tests/ui/collections/hashset-connected-border.rs similarity index 100% rename from tests/ui/issues/issue-12860.rs rename to tests/ui/collections/hashset-connected-border.rs diff --git a/tests/ui/issues/issue-13446.rs b/tests/ui/const-generics/vec-macro-in-static-array.rs similarity index 100% rename from tests/ui/issues/issue-13446.rs rename to tests/ui/const-generics/vec-macro-in-static-array.rs diff --git a/tests/ui/issues/issue-13259-windows-tcb-trash.rs b/tests/ui/extern/format-message-windows-ffi.rs similarity index 100% rename from tests/ui/issues/issue-13259-windows-tcb-trash.rs rename to tests/ui/extern/format-message-windows-ffi.rs diff --git a/tests/ui/issues/issue-13105.rs b/tests/ui/fn/anonymous-parameters-trait.rs similarity index 100% rename from tests/ui/issues/issue-13105.rs rename to tests/ui/fn/anonymous-parameters-trait.rs diff --git a/tests/ui/issues/issue-12729.rs b/tests/ui/imports/use-in-impl-scope.rs similarity index 100% rename from tests/ui/issues/issue-12729.rs rename to tests/ui/imports/use-in-impl-scope.rs diff --git a/tests/ui/issues/issue-12677.rs b/tests/ui/iterators/bytes-iterator-clone.rs similarity index 100% rename from tests/ui/issues/issue-12677.rs rename to tests/ui/iterators/bytes-iterator-clone.rs diff --git a/tests/ui/issues/issue-13167.rs b/tests/ui/iterators/phf-map-entries-iterator.rs similarity index 100% rename from tests/ui/issues/issue-13167.rs rename to tests/ui/iterators/phf-map-entries-iterator.rs diff --git a/tests/ui/issues/issue-13058.rs b/tests/ui/lifetimes/iterator-trait-lifetime-error.rs similarity index 100% rename from tests/ui/issues/issue-13058.rs rename to tests/ui/lifetimes/iterator-trait-lifetime-error.rs diff --git a/tests/ui/issues/issue-13405.rs b/tests/ui/lifetimes/struct-lifetime-field-assignment.rs similarity index 100% rename from tests/ui/issues/issue-13405.rs rename to tests/ui/lifetimes/struct-lifetime-field-assignment.rs diff --git a/tests/ui/issues/issue-12863.rs b/tests/ui/match/function-in-pattern-error.rs similarity index 100% rename from tests/ui/issues/issue-12863.rs rename to tests/ui/match/function-in-pattern-error.rs diff --git a/tests/ui/issues/issue-13027.rs b/tests/ui/match/guard-literal-range-shadow.rs similarity index 100% rename from tests/ui/issues/issue-13027.rs rename to tests/ui/match/guard-literal-range-shadow.rs diff --git a/tests/ui/issues/issue-11844.rs b/tests/ui/match/option-result-mismatch.rs similarity index 100% rename from tests/ui/issues/issue-11844.rs rename to tests/ui/match/option-result-mismatch.rs diff --git a/tests/ui/issues/issue-13466.rs b/tests/ui/match/option-result-type-param-mismatch.rs similarity index 100% rename from tests/ui/issues/issue-13466.rs rename to tests/ui/match/option-result-type-param-mismatch.rs diff --git a/tests/ui/issues/issue-12567.rs b/tests/ui/match/slice-move-out-error.rs similarity index 100% rename from tests/ui/issues/issue-12567.rs rename to tests/ui/match/slice-move-out-error.rs diff --git a/tests/ui/issues/issue-11869.rs b/tests/ui/match/string-literal-match-patterns.rs similarity index 100% rename from tests/ui/issues/issue-11869.rs rename to tests/ui/match/string-literal-match-patterns.rs diff --git a/tests/ui/issues/issue-12285.rs b/tests/ui/match/struct-reference-patterns.rs similarity index 100% rename from tests/ui/issues/issue-12285.rs rename to tests/ui/match/struct-reference-patterns.rs diff --git a/tests/ui/issues/issue-12920.rs b/tests/ui/panics/explicit-panic-unreachable.rs similarity index 100% rename from tests/ui/issues/issue-12920.rs rename to tests/ui/panics/explicit-panic-unreachable.rs diff --git a/tests/ui/issues/issue-13202.rs b/tests/ui/panics/unwrap-or-panic-input.rs similarity index 100% rename from tests/ui/issues/issue-13202.rs rename to tests/ui/panics/unwrap-or-panic-input.rs diff --git a/tests/ui/issues/issue-13407.rs b/tests/ui/privacy/private-unit-struct-assignment.rs similarity index 100% rename from tests/ui/issues/issue-13407.rs rename to tests/ui/privacy/private-unit-struct-assignment.rs diff --git a/tests/ui/issues/issue-13214.rs b/tests/ui/statics/enum-with-static-str-variant.rs similarity index 100% rename from tests/ui/issues/issue-13214.rs rename to tests/ui/statics/enum-with-static-str-variant.rs diff --git a/tests/ui/issues/issue-12041.rs b/tests/ui/threads/moved-value-in-thread-loop.rs similarity index 100% rename from tests/ui/issues/issue-12041.rs rename to tests/ui/threads/moved-value-in-thread-loop.rs diff --git a/tests/ui/issues/issue-12744.rs b/tests/ui/traits/any-trait-object-debug.rs similarity index 100% rename from tests/ui/issues/issue-12744.rs rename to tests/ui/traits/any-trait-object-debug.rs diff --git a/tests/ui/issues/issue-13204.rs b/tests/ui/traits/default-method-lifetime-params.rs similarity index 100% rename from tests/ui/issues/issue-13204.rs rename to tests/ui/traits/default-method-lifetime-params.rs diff --git a/tests/ui/issues/issue-13264.rs b/tests/ui/traits/deref-chain-method-calls.rs similarity index 100% rename from tests/ui/issues/issue-13264.rs rename to tests/ui/traits/deref-chain-method-calls.rs diff --git a/tests/ui/issues/issue-13434.rs b/tests/ui/traits/fnonce-repro-trait-impl.rs similarity index 100% rename from tests/ui/issues/issue-13434.rs rename to tests/ui/traits/fnonce-repro-trait-impl.rs diff --git a/tests/ui/issues/issue-13323.rs b/tests/ui/traits/matcher-trait-equality.rs similarity index 100% rename from tests/ui/issues/issue-13323.rs rename to tests/ui/traits/matcher-trait-equality.rs diff --git a/tests/ui/issues/issue-11820.rs b/tests/ui/traits/reference-clone-noclone.rs similarity index 100% rename from tests/ui/issues/issue-11820.rs rename to tests/ui/traits/reference-clone-noclone.rs diff --git a/tests/ui/issues/issue-13359.rs b/tests/ui/type-inference/isize-usize-mismatch-error.rs similarity index 100% rename from tests/ui/issues/issue-13359.rs rename to tests/ui/type-inference/isize-usize-mismatch-error.rs diff --git a/tests/ui/issues/issue-12909.rs b/tests/ui/type-inference/type-collect-inference.rs similarity index 100% rename from tests/ui/issues/issue-12909.rs rename to tests/ui/type-inference/type-collect-inference.rs diff --git a/tests/ui/issues/issue-11771.rs b/tests/ui/type-inference/unit-type-add-error.rs similarity index 100% rename from tests/ui/issues/issue-11771.rs rename to tests/ui/type-inference/unit-type-add-error.rs diff --git a/tests/ui/issues/issue-11740.rs b/tests/ui/unsafe/unsafe-transmute-in-find.rs similarity index 100% rename from tests/ui/issues/issue-11740.rs rename to tests/ui/unsafe/unsafe-transmute-in-find.rs From 43c3e1bb97186d598dc7066706bd66cf5a383cfb Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 24 Jul 2025 01:18:46 -0500 Subject: [PATCH 114/809] 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 115/809] 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 b481c5b8ba322612fb3bc167e323f7a548a2390c Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 24 Jul 2025 13:01:08 +0000 Subject: [PATCH 116/809] std_detect testing improvements * Fix riscv testing. Previously the mod tests; would be looking for src/detect/os/tests.rs. * Replace a test with an unnamed const item. It is testing that no warnings are emitted. It doesn't contain any checks that need to run at runtime. Replacing the test allows removing the tidy:skip directive for test locations. --- library/std_detect/src/detect/macros.rs | 5 ++--- library/std_detect/src/detect/os/riscv.rs | 1 + src/tools/tidy/src/unit_tests.rs | 3 +-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/library/std_detect/src/detect/macros.rs b/library/std_detect/src/detect/macros.rs index c2a006d3753a..17140e15653d 100644 --- a/library/std_detect/src/detect/macros.rs +++ b/library/std_detect/src/detect/macros.rs @@ -131,14 +131,13 @@ macro_rules! features { }; } - #[test] //tidy:skip #[deny(unexpected_cfgs)] #[deny(unfulfilled_lint_expectations)] - fn unexpected_cfgs() { + const _: () = { $( check_cfg_feature!($feature, $feature_lit $(, without cfg check: $feature_cfg_check)? $(: $($target_feature_lit),*)?); )* - } + }; /// Each variant denotes a position in a bitset for a particular feature. /// diff --git a/library/std_detect/src/detect/os/riscv.rs b/library/std_detect/src/detect/os/riscv.rs index 46b7dd71eb35..dc9a4036d86a 100644 --- a/library/std_detect/src/detect/os/riscv.rs +++ b/library/std_detect/src/detect/os/riscv.rs @@ -135,4 +135,5 @@ pub(crate) fn imply_features(mut value: cache::Initializer) -> cache::Initialize } #[cfg(test)] +#[path = "riscv/tests.rs"] mod tests; diff --git a/src/tools/tidy/src/unit_tests.rs b/src/tools/tidy/src/unit_tests.rs index 90da1bc765a9..3d14a4673193 100644 --- a/src/tools/tidy/src/unit_tests.rs +++ b/src/tools/tidy/src/unit_tests.rs @@ -79,8 +79,7 @@ pub fn check(root_path: &Path, stdlib: bool, bad: &mut bool) { let line = line.trim(); let is_test = || line.contains("#[test]") && !line.contains("`#[test]"); let is_bench = || line.contains("#[bench]") && !line.contains("`#[bench]"); - let manual_skip = line.contains("//tidy:skip"); - if !line.starts_with("//") && (is_test() || is_bench()) && !manual_skip { + if !line.starts_with("//") && (is_test() || is_bench()) { let explanation = if stdlib { format!( "`{package}` unit tests and benchmarks must be placed into `{package}tests`" From a383fb0c738967ea8c6af200d8f4a37c751427c1 Mon Sep 17 00:00:00 2001 From: WANG Rui Date: Thu, 9 Jan 2025 20:35:49 +0800 Subject: [PATCH 117/809] 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 118/809] 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 119/809] 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 120/809] 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 121/809] 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 122/809] 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 123/809] 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 effcd540608f4e58f17a2161a6c8344c0a92f8cf Mon Sep 17 00:00:00 2001 From: Jens Reidel Date: Thu, 24 Jul 2025 18:22:51 +0200 Subject: [PATCH 124/809] Make tier 3 musl targets link dynamically by default Since we don't build std for these and don't provide any support for them, these can trivially be changed to link dynamically by default. Signed-off-by: Jens Reidel --- .../rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs | 1 - .../src/spec/targets/mips64_unknown_linux_muslabi64.rs | 2 -- .../src/spec/targets/powerpc64_unknown_linux_musl.rs | 2 -- .../rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs | 2 -- .../src/spec/targets/powerpc_unknown_linux_muslspe.rs | 2 -- .../src/spec/targets/riscv32gc_unknown_linux_musl.rs | 2 -- .../rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs | 2 -- .../src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs | 2 -- 8 files changed, 15 deletions(-) diff --git a/compiler/rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs index f7416a7e0fde..1abf0537cda7 100644 --- a/compiler/rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs @@ -7,7 +7,6 @@ pub(crate) fn target() -> Target { // FIXME: HVX length defaults are per-CPU base.features = "-small-data,+hvx-length128b".into(); - base.crt_static_default = false; base.has_rpath = true; base.linker_flavor = LinkerFlavor::Unix(Cc::Yes); diff --git a/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_muslabi64.rs b/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_muslabi64.rs index f95ce7563549..94ecd3590a93 100644 --- a/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_muslabi64.rs +++ b/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_muslabi64.rs @@ -23,8 +23,6 @@ pub(crate) fn target() -> Target { abi: "abi64".into(), endian: Endian::Big, mcount: "_mcount".into(), - // FIXME(compiler-team#422): musl targets should be dynamically linked by default. - crt_static_default: true, llvm_abiname: "n64".into(), ..base }, diff --git a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_musl.rs index 4dc76f0936c9..482b6790dadc 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_musl.rs @@ -10,8 +10,6 @@ pub(crate) fn target() -> Target { base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64"]); base.max_atomic_width = Some(64); base.stack_probes = StackProbeType::Inline; - // FIXME(compiler-team#422): musl targets should be dynamically linked by default. - base.crt_static_default = true; base.abi = "elfv2".into(); base.llvm_abiname = "elfv2".into(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs index 316b62d941b4..f39142d01018 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs @@ -9,8 +9,6 @@ pub(crate) fn target() -> Target { base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32"]); base.max_atomic_width = Some(32); base.stack_probes = StackProbeType::Inline; - // FIXME(compiler-team#422): musl targets should be dynamically linked by default. - base.crt_static_default = true; Target { llvm_target: "powerpc-unknown-linux-musl".into(), diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_muslspe.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_muslspe.rs index 30d0d9cb60a7..8ddb45483b3b 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_muslspe.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_muslspe.rs @@ -9,8 +9,6 @@ pub(crate) fn target() -> Target { base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-mspe"]); base.max_atomic_width = Some(32); base.stack_probes = StackProbeType::Inline; - // FIXME(compiler-team#422): musl targets should be dynamically linked by default. - base.crt_static_default = true; Target { llvm_target: "powerpc-unknown-linux-muslspe".into(), diff --git a/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_musl.rs index 938b39b10c64..eb592cca1c81 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_musl.rs @@ -23,8 +23,6 @@ pub(crate) fn target() -> Target { llvm_abiname: "ilp32d".into(), max_atomic_width: Some(32), supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]), - // FIXME(compiler-team#422): musl targets should be dynamically linked by default. - crt_static_default: true, ..base::linux_musl::opts() }, } diff --git a/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs index e9522ac760e1..0cdbb626739d 100644 --- a/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs @@ -13,8 +13,6 @@ pub(crate) fn target() -> Target { base.stack_probes = StackProbeType::Inline; base.supported_sanitizers = SanitizerSet::ADDRESS | SanitizerSet::LEAK | SanitizerSet::MEMORY | SanitizerSet::THREAD; - // FIXME(compiler-team#422): musl targets should be dynamically linked by default. - base.crt_static_default = true; Target { llvm_target: "s390x-unknown-linux-musl".into(), diff --git a/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs b/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs index 81c502bfeada..e026595439f4 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs @@ -27,8 +27,6 @@ pub(crate) fn target() -> Target { features: "+v7,+thumb-mode,+thumb2,+vfp3,+neon".into(), max_atomic_width: Some(64), mcount: "\u{1}mcount".into(), - // FIXME(compiler-team#422): musl targets should be dynamically linked by default. - crt_static_default: true, ..base::linux_musl::opts() }, } From 6017fe65968cbe044e1f9a0638376e788829736b Mon Sep 17 00:00:00 2001 From: binarycat Date: Thu, 24 Jul 2025 12:27:00 -0500 Subject: [PATCH 125/809] 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 126/809] 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 127/809] 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 128/809] 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 129/809] 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 130/809] 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 131/809] 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 132/809] 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 133/809] loongarch: Use unified data types for SIMD intrinsics --- .../src/loongarch64/lasx/generated.rs | 4441 +++++++++-------- .../core_arch/src/loongarch64/lasx/types.rs | 159 +- .../src/loongarch64/lsx/generated.rs | 4321 ++++++++-------- .../core_arch/src/loongarch64/lsx/types.rs | 161 +- .../crates/stdarch-gen-loongarch/src/main.rs | 224 +- 5 files changed, 4782 insertions(+), 4524 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); - - /// LOONGARCH-specific 256-bit wide vector of 4 packed `f64`. - pub struct v4f64(4 x pub(crate) f64); } + +#[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]); + +// 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); - - /// LOONGARCH-specific 128-bit wide vector of 4 packed `f32`. - pub struct v4f32(4 x pub(crate) f32); - - /// LOONGARCH-specific 128-bit wide vector of 2 packed `f64`. - pub struct v2f64(2 x pub(crate) f64); + /// 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); } + +#[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]); + +// 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 a2320b25533df01d9b96707187b64e03595c9bee Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 1 Oct 2023 14:46:12 +0000 Subject: [PATCH 134/809] Remove eval_always from check_private_in_public. --- compiler/rustc_middle/src/query/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b0d579a546fe..587349d4cf41 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1391,7 +1391,6 @@ rustc_queries! { desc { "checking effective visibilities" } } query check_private_in_public(_: ()) { - eval_always desc { "checking for private elements in public interfaces" } } From 0258894b762a163df714a86589a9e8158b354499 Mon Sep 17 00:00:00 2001 From: The Miri Cronjob Bot Date: Fri, 25 Jul 2025 05:01:00 +0000 Subject: [PATCH 135/809] Prepare for merging from rust-lang/rust This updates the rust-version file to b56aaec52bc0fa35591a872fb4aac81f606e265c. --- 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 bd902ca1fd5a..634ce1fa0628 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -9748d87dc70a9a6725c5dbd76ce29d04752b4f90 +b56aaec52bc0fa35591a872fb4aac81f606e265c From 0dba9f539f92c2abe7a8d3997a91e6884caa1fcf Mon Sep 17 00:00:00 2001 From: The Miri Cronjob Bot Date: Fri, 25 Jul 2025 05:08:59 +0000 Subject: [PATCH 136/809] fmt --- src/tools/miri/src/machine.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 7271d3f619c7..142c6ddf9330 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -76,13 +76,8 @@ pub struct FrameExtra<'tcx> { impl<'tcx> std::fmt::Debug for FrameExtra<'tcx> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Omitting `timing`, it does not support `Debug`. - let FrameExtra { - borrow_tracker, - catch_unwind, - timing: _, - is_user_relevant, - data_race, - } = self; + let FrameExtra { borrow_tracker, catch_unwind, timing: _, is_user_relevant, data_race } = + self; f.debug_struct("FrameData") .field("borrow_tracker", borrow_tracker) .field("catch_unwind", catch_unwind) From 60b054533fb607d0fac9716c1a6b94e9efa3b7a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Fri, 25 Jul 2025 08:27:18 +0200 Subject: [PATCH 137/809] Fix cronjob Zulip message --- src/tools/miri/.github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index 9f74642f0f15..e2e81370c600 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -219,7 +219,7 @@ jobs: It would appear that the [Miri cron job build]('"https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"') failed. This likely means that rustc changed the miri directory and - we now need to do a [`./miri rustc-pull`](https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md#importing-changes-from-the-rustc-repo). + we now need to do a [`rustc-josh-sync pull`](https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md#importing-changes-from-the-rustc-repo). Would you mind investigating this issue? From 2a81b4fad6bc5d089808d10cd880de040339cea6 Mon Sep 17 00:00:00 2001 From: Stypox Date: Tue, 22 Jul 2025 13:43:30 +0200 Subject: [PATCH 138/809] Use i64 for tracing chrome "id" Perfetto gives an error if an id does not fit in an 64-bit signed integer in 2's complement. --- src/tools/miri/src/bin/log/tracing_chrome.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/tools/miri/src/bin/log/tracing_chrome.rs b/src/tools/miri/src/bin/log/tracing_chrome.rs index 5a96633c99e8..3379816550cf 100644 --- a/src/tools/miri/src/bin/log/tracing_chrome.rs +++ b/src/tools/miri/src/bin/log/tracing_chrome.rs @@ -12,6 +12,7 @@ //! ```rust //! tracing::info_span!("my_span", tracing_separate_thread = tracing::field::Empty, /* ... */) //! ``` +//! - use i64 instead of u64 for the "id" in [ChromeLayer::get_root_id] to be compatible with Perfetto //! //! Depending on the tracing-chrome crate from crates.io is unfortunately not possible, since it //! depends on `tracing_core` which conflicts with rustc_private's `tracing_core` (meaning it would @@ -285,9 +286,9 @@ struct Callsite { } enum Message { - Enter(f64, Callsite, Option), + Enter(f64, Callsite, Option), Event(f64, Callsite), - Exit(f64, Callsite, Option), + Exit(f64, Callsite, Option), NewThread(usize, String), Flush, Drop, @@ -519,14 +520,17 @@ where } } - fn get_root_id(&self, span: SpanRef) -> Option { + fn get_root_id(&self, span: SpanRef) -> Option { + // Returns `Option` instead of `Option` because apparently Perfetto gives an + // error if an id does not fit in a 64-bit signed integer in 2's complement. We cast the + // span id from `u64` to `i64` with wraparound, since negative values are fine. match self.trace_style { TraceStyle::Threaded => { if span.fields().field("tracing_separate_thread").is_some() { // assign an independent "id" to spans with argument "tracing_separate_thread", // so they appear a separate trace line in trace visualization tools, see // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.jh64i9l3vwa1 - Some(span.id().into_u64()) + Some(span.id().into_u64().cast_signed()) // the comment above explains the cast } else { None } @@ -539,6 +543,7 @@ where .unwrap_or(span) .id() .into_u64() + .cast_signed() // the comment above explains the cast ), } } From 00de833b60b6198f092901e1b2f6a10e6f3a89da Mon Sep 17 00:00:00 2001 From: Stypox Date: Tue, 22 Jul 2025 13:45:37 +0200 Subject: [PATCH 139/809] Fix missing $ in enter_trace_span! --- src/tools/miri/src/helpers.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index ccfff7fa94bd..6e80bc5da9eb 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -1465,7 +1465,7 @@ pub struct MaybeEnteredTraceSpan { #[macro_export] macro_rules! enter_trace_span { ($name:ident :: $subname:ident $($tt:tt)*) => {{ - enter_trace_span!(stringify!($name), $name = %stringify!(subname) $($tt)*) + enter_trace_span!(stringify!($name), $name = %stringify!($subname) $($tt)*) }}; ($($tt:tt)*) => { From c7b81f38f8f5dee79be0fbddfba551eea3f98bf8 Mon Sep 17 00:00:00 2001 From: Stypox Date: Tue, 22 Jul 2025 18:42:11 +0200 Subject: [PATCH 140/809] Fix double "fatal error: " in message --- src/tools/miri/src/bin/log/setup.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/src/bin/log/setup.rs b/src/tools/miri/src/bin/log/setup.rs index da0ba528b2c4..a9392d010f8e 100644 --- a/src/tools/miri/src/bin/log/setup.rs +++ b/src/tools/miri/src/bin/log/setup.rs @@ -60,7 +60,7 @@ fn init_logger_once(early_dcx: &EarlyDiagCtxt) { #[cfg(not(feature = "tracing"))] { crate::fatal_error!( - "fatal error: cannot enable MIRI_TRACING since Miri was not built with the \"tracing\" feature" + "Cannot enable MIRI_TRACING since Miri was not built with the \"tracing\" feature" ); } From d2ba3c8672b09373311c930733f64aa10a4799a0 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 25 Jul 2025 08:43:37 +0200 Subject: [PATCH 141/809] fix target json --- src/tools/miri/tests/x86_64-unknown-kernel.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/tests/x86_64-unknown-kernel.json b/src/tools/miri/tests/x86_64-unknown-kernel.json index 8da67d3a1c6b..a5eaceb4f68e 100644 --- a/src/tools/miri/tests/x86_64-unknown-kernel.json +++ b/src/tools/miri/tests/x86_64-unknown-kernel.json @@ -2,7 +2,7 @@ "llvm-target": "x86_64-unknown-none", "target-endian": "little", "target-pointer-width": "64", - "target-c-int-width": "32", + "target-c-int-width": 32, "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128", "arch": "x86_64", "os": "none", From 90bb5cacb5c1a5fe20ba821d28e7eb7a21e35d09 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Thu, 24 Jul 2025 18:29:09 +0500 Subject: [PATCH 142/809] 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 27e2709f3e8d8f03b05704bc7e3e9110dd64397b Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Tue, 22 Jul 2025 14:05:03 +0000 Subject: [PATCH 143/809] Improve coordinator channel handling Remove usage of Any, reduce visibility of fields and remove unused backend arguments. --- compiler/rustc_codegen_ssa/src/back/write.rs | 49 +++++++++----------- compiler/rustc_codegen_ssa/src/base.rs | 16 ++----- 2 files changed, 25 insertions(+), 40 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 7be274df1d41..a41cbd306d0c 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -1,4 +1,3 @@ -use std::any::Any; use std::assert_matches::assert_matches; use std::marker::PhantomData; use std::path::{Path, PathBuf}; @@ -372,8 +371,6 @@ pub struct CodegenContext { /// The incremental compilation session directory, or None if we are not /// compiling incrementally pub incr_comp_session_dir: Option, - /// Channel back to the main control thread to send messages to - pub coordinator_send: Sender>, /// `true` if the codegen should be run in parallel. /// /// Depends on [`ExtraBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`. @@ -1122,10 +1119,10 @@ fn start_executing_work( autodiff_items: &[AutoDiffItem], shared_emitter: SharedEmitter, codegen_worker_send: Sender, - coordinator_receive: Receiver>, + coordinator_receive: Receiver>, regular_config: Arc, allocator_config: Arc, - tx_to_llvm_workers: Sender>, + tx_to_llvm_workers: Sender>, ) -> thread::JoinHandle> { let coordinator_send = tx_to_llvm_workers; let sess = tcx.sess; @@ -1153,7 +1150,7 @@ fn start_executing_work( let coordinator_send2 = coordinator_send.clone(); let helper = jobserver::client() .into_helper_thread(move |token| { - drop(coordinator_send2.send(Box::new(Message::Token::(token)))); + drop(coordinator_send2.send(Message::Token::(token))); }) .expect("failed to spawn helper thread"); @@ -1187,7 +1184,6 @@ fn start_executing_work( remark: sess.opts.cg.remark.clone(), remark_dir, incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()), - coordinator_send, expanded_args: tcx.sess.expanded_args.clone(), diag_emitter: shared_emitter.clone(), output_filenames: Arc::clone(tcx.output_filenames(())), @@ -1423,7 +1419,7 @@ fn start_executing_work( let (item, _) = work_items.pop().expect("queue empty - queue_full_enough() broken?"); main_thread_state = MainThreadState::Lending; - spawn_work(&cgcx, &mut llvm_start_time, item); + spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item); } } } else if codegen_state == Completed { @@ -1502,7 +1498,7 @@ fn start_executing_work( MainThreadState::Idle => { if let Some((item, _)) = work_items.pop() { main_thread_state = MainThreadState::Lending; - spawn_work(&cgcx, &mut llvm_start_time, item); + spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item); } else { // There is no unstarted work, so let the main thread // take over for a running worker. Otherwise the @@ -1538,7 +1534,7 @@ fn start_executing_work( while running_with_own_token < tokens.len() && let Some((item, _)) = work_items.pop() { - spawn_work(&cgcx, &mut llvm_start_time, item); + spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item); running_with_own_token += 1; } } @@ -1546,8 +1542,7 @@ fn start_executing_work( // Relinquish accidentally acquired extra tokens. tokens.truncate(running_with_own_token); - let msg = coordinator_receive.recv().unwrap(); - match *msg.downcast::>().ok().unwrap() { + match coordinator_receive.recv().unwrap() { // Save the token locally and the next turn of the loop will use // this to spawn a new unit of work, or it may get dropped // immediately if we have no more work to spawn. @@ -1769,6 +1764,7 @@ pub(crate) struct WorkerFatalError; fn spawn_work<'a, B: ExtraBackendMethods>( cgcx: &'a CodegenContext, + coordinator_send: Sender>, llvm_start_time: &mut Option>, work: WorkItem, ) { @@ -1782,7 +1778,7 @@ fn spawn_work<'a, B: ExtraBackendMethods>( // Set up a destructor which will fire off a message that we're done as // we exit. struct Bomb { - coordinator_send: Sender>, + coordinator_send: Sender>, result: Option, FatalError>>, } impl Drop for Bomb { @@ -1794,11 +1790,11 @@ fn spawn_work<'a, B: ExtraBackendMethods>( } None => Message::WorkItem:: { result: Err(None) }, }; - drop(self.coordinator_send.send(Box::new(msg))); + drop(self.coordinator_send.send(msg)); } } - let mut bomb = Bomb:: { coordinator_send: cgcx.coordinator_send.clone(), result: None }; + let mut bomb = Bomb:: { coordinator_send, result: None }; // Execute the work itself, and if it finishes successfully then flag // ourselves as a success as well. @@ -2003,7 +1999,7 @@ impl SharedEmitterMain { } pub struct Coordinator { - pub sender: Sender>, + sender: Sender>, future: Option>>, // Only used for the Message type. phantom: PhantomData, @@ -2020,7 +2016,7 @@ impl Drop for Coordinator { if let Some(future) = self.future.take() { // If we haven't joined yet, signal to the coordinator that it should spawn no more // work, and wait for worker threads to finish. - drop(self.sender.send(Box::new(Message::CodegenAborted::))); + drop(self.sender.send(Message::CodegenAborted::)); drop(future.join()); } } @@ -2079,7 +2075,7 @@ impl OngoingCodegen { pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) { self.wait_for_signal_to_codegen_item(); self.check_for_errors(tcx.sess); - drop(self.coordinator.sender.send(Box::new(Message::CodegenComplete::))); + drop(self.coordinator.sender.send(Message::CodegenComplete::)); } pub(crate) fn check_for_errors(&self, sess: &Session) { @@ -2100,28 +2096,25 @@ impl OngoingCodegen { } pub(crate) fn submit_codegened_module_to_llvm( - _backend: &B, - tx_to_llvm_workers: &Sender>, + coordinator: &Coordinator, module: ModuleCodegen, cost: u64, ) { let llvm_work_item = WorkItem::Optimize(module); - drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone:: { llvm_work_item, cost }))); + drop(coordinator.sender.send(Message::CodegenDone:: { llvm_work_item, cost })); } pub(crate) fn submit_post_lto_module_to_llvm( - _backend: &B, - tx_to_llvm_workers: &Sender>, + coordinator: &Coordinator, module: CachedModuleCodegen, ) { let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module); - drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone:: { llvm_work_item, cost: 0 }))); + drop(coordinator.sender.send(Message::CodegenDone:: { llvm_work_item, cost: 0 })); } pub(crate) fn submit_pre_lto_module_to_llvm( - _backend: &B, tcx: TyCtxt<'_>, - tx_to_llvm_workers: &Sender>, + coordinator: &Coordinator, module: CachedModuleCodegen, ) { let filename = pre_lto_bitcode_filename(&module.name); @@ -2135,10 +2128,10 @@ pub(crate) fn submit_pre_lto_module_to_llvm( }) }; // Schedule the module to be loaded - drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule:: { + drop(coordinator.sender.send(Message::AddImportOnlyModule:: { module_data: SerializedModule::FromUncompressedFile(mmap), work_product: module.source, - }))); + })); } fn pre_lto_bitcode_filename(module_name: &str) -> String { diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 833456abb8ab..a5807c56e317 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -702,8 +702,7 @@ pub fn codegen_crate( // These modules are generally cheap and won't throw off scheduling. let cost = 0; submit_codegened_module_to_llvm( - &backend, - &ongoing_codegen.coordinator.sender, + &ongoing_codegen.coordinator, ModuleCodegen::new_allocator(llmod_id, module_llvm), cost, ); @@ -800,18 +799,12 @@ pub fn codegen_crate( // compilation hang on post-monomorphization errors. tcx.dcx().abort_if_errors(); - submit_codegened_module_to_llvm( - &backend, - &ongoing_codegen.coordinator.sender, - module, - cost, - ); + submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost); } CguReuse::PreLto => { submit_pre_lto_module_to_llvm( - &backend, tcx, - &ongoing_codegen.coordinator.sender, + &ongoing_codegen.coordinator, CachedModuleCodegen { name: cgu.name().to_string(), source: cgu.previous_work_product(tcx), @@ -820,8 +813,7 @@ pub fn codegen_crate( } CguReuse::PostLto => { submit_post_lto_module_to_llvm( - &backend, - &ongoing_codegen.coordinator.sender, + &ongoing_codegen.coordinator, CachedModuleCodegen { name: cgu.name().to_string(), source: cgu.previous_work_product(tcx), From fe2eeabe27ce3d5b871ab903e65b4707ad015764 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Fri, 25 Jul 2025 09:42:18 +0000 Subject: [PATCH 144/809] Use the object crate rather than LLVM for extracting bitcode sections --- compiler/rustc_codegen_llvm/messages.ftl | 2 +- compiler/rustc_codegen_llvm/src/back/lto.rs | 31 +++++------------ compiler/rustc_codegen_llvm/src/errors.rs | 2 +- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 7 ---- .../rustc_llvm/llvm-wrapper/PassWrapper.cpp | 34 ------------------- 5 files changed, 10 insertions(+), 66 deletions(-) diff --git a/compiler/rustc_codegen_llvm/messages.ftl b/compiler/rustc_codegen_llvm/messages.ftl index 3d5f17a60345..ce9a51b539d8 100644 --- a/compiler/rustc_codegen_llvm/messages.ftl +++ b/compiler/rustc_codegen_llvm/messages.ftl @@ -12,7 +12,7 @@ codegen_llvm_from_llvm_optimization_diag = {$filename}:{$line}:{$column} {$pass_ codegen_llvm_load_bitcode = failed to load bitcode of module "{$name}" codegen_llvm_load_bitcode_with_llvm_err = failed to load bitcode of module "{$name}": {$llvm_err} -codegen_llvm_lto_bitcode_from_rlib = failed to get bitcode from object file for LTO ({$llvm_err}) +codegen_llvm_lto_bitcode_from_rlib = failed to get bitcode from object file for LTO ({$err}) codegen_llvm_mismatch_data_layout = data-layout for target `{$rustc_target}`, `{$rustc_layout}`, differs from LLVM target's `{$llvm_target}` default layout, `{$llvm_layout}` diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index 767835c34f02..cac7d49b74a5 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use std::{io, iter, slice}; use object::read::archive::ArchiveFile; +use object::{Object, ObjectSection}; use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared}; use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput}; use rustc_codegen_ssa::traits::*; @@ -105,31 +106,15 @@ fn get_bitcode_slice_from_object_data<'a>( // name" which in the public API for sections gets treated as part of the section name, but // internally in MachOObjectFile.cpp gets treated separately. let section_name = bitcode_section_name(cgcx).to_str().unwrap().trim_start_matches("__LLVM,"); - let mut len = 0; - let data = unsafe { - llvm::LLVMRustGetSliceFromObjectDataByName( - obj.as_ptr(), - obj.len(), - section_name.as_ptr(), - section_name.len(), - &mut len, - ) - }; - if !data.is_null() { - assert!(len != 0); - let bc = unsafe { slice::from_raw_parts(data, len) }; - // `bc` must be a sub-slice of `obj`. - assert!(obj.as_ptr() <= bc.as_ptr()); - assert!(bc[bc.len()..bc.len()].as_ptr() <= obj[obj.len()..obj.len()].as_ptr()); + let obj = + object::File::parse(obj).map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })?; - Ok(bc) - } else { - assert!(len == 0); - Err(LtoBitcodeFromRlib { - llvm_err: llvm::last_error().unwrap_or_else(|| "unknown LLVM error".to_string()), - }) - } + let section = obj + .section_by_name(section_name) + .ok_or_else(|| LtoBitcodeFromRlib { err: format!("Can't find section {section_name}") })?; + + section.data().map_err(|err| LtoBitcodeFromRlib { err: err.to_string() }) } /// Performs fat LTO by merging all modules into a single one and returning it diff --git a/compiler/rustc_codegen_llvm/src/errors.rs b/compiler/rustc_codegen_llvm/src/errors.rs index 2a889888a39b..627b0c9ff3b3 100644 --- a/compiler/rustc_codegen_llvm/src/errors.rs +++ b/compiler/rustc_codegen_llvm/src/errors.rs @@ -39,7 +39,7 @@ pub(crate) struct AutoDiffWithoutEnable; #[derive(Diagnostic)] #[diag(codegen_llvm_lto_bitcode_from_rlib)] pub(crate) struct LtoBitcodeFromRlib { - pub llvm_err: String, + pub err: String, } #[derive(Diagnostic)] diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index edfb29dd1be7..0d0cb5f139ee 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -2612,13 +2612,6 @@ unsafe extern "C" { len: usize, Identifier: *const c_char, ) -> Option<&Module>; - pub(crate) fn LLVMRustGetSliceFromObjectDataByName( - data: *const u8, - len: usize, - name: *const u8, - name_len: usize, - out_len: &mut usize, - ) -> *const u8; pub(crate) fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>; pub(crate) fn LLVMRustLinkerAdd( diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index a2e4d7306cbf..8c34052770e6 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -1650,40 +1650,6 @@ extern "C" LLVMModuleRef LLVMRustParseBitcodeForLTO(LLVMContextRef Context, return wrap(std::move(*SrcOrError).release()); } -// Find a section of an object file by name. Fail if the section is missing or -// empty. -extern "C" const char *LLVMRustGetSliceFromObjectDataByName(const char *data, - size_t len, - const char *name, - size_t name_len, - size_t *out_len) { - *out_len = 0; - auto Name = StringRef(name, name_len); - auto Data = StringRef(data, len); - auto Buffer = MemoryBufferRef(Data, ""); // The id is unused. - file_magic Type = identify_magic(Buffer.getBuffer()); - Expected> ObjFileOrError = - object::ObjectFile::createObjectFile(Buffer, Type); - if (!ObjFileOrError) { - LLVMRustSetLastError(toString(ObjFileOrError.takeError()).c_str()); - return nullptr; - } - for (const object::SectionRef &Sec : (*ObjFileOrError)->sections()) { - Expected SecName = Sec.getName(); - if (SecName && *SecName == Name) { - Expected SectionOrError = Sec.getContents(); - if (!SectionOrError) { - LLVMRustSetLastError(toString(SectionOrError.takeError()).c_str()); - return nullptr; - } - *out_len = SectionOrError->size(); - return SectionOrError->data(); - } - } - LLVMRustSetLastError("could not find requested section"); - return nullptr; -} - // Computes the LTO cache key for the provided 'ModId' in the given 'Data', // storing the result in 'KeyOut'. // Currently, this cache key is a SHA-1 hash of anything that could affect From 0b323eacd4c4cf99d18bd75ad02b2139dd990297 Mon Sep 17 00:00:00 2001 From: lcnr Date: Thu, 24 Jul 2025 14:53:13 +0000 Subject: [PATCH 145/809] uniquify root goals during HIR typeck --- .../rustc_hir_typeck/src/typeck_root_ctxt.rs | 7 +- compiler/rustc_infer/src/infer/at.rs | 2 + compiler/rustc_infer/src/infer/context.rs | 4 ++ compiler/rustc_infer/src/infer/mod.rs | 38 +++++++++- .../src/canonicalizer.rs | 72 +++++++++++++------ .../src/solve/eval_ctxt/canonical.rs | 2 + .../src/solve/eval_ctxt/mod.rs | 5 +- .../rustc_next_trait_solver/src/solve/mod.rs | 2 - compiler/rustc_type_ir/src/infer_ctxt.rs | 4 ++ tests/crashes/139409.rs | 12 ---- ...iguity-due-to-uniquification-1.next.stderr | 19 +++++ .../ambiguity-due-to-uniquification-1.rs | 17 +++++ ...iguity-due-to-uniquification-2.next.stderr | 17 +++++ .../ambiguity-due-to-uniquification-2.rs | 20 ++++++ 14 files changed, 180 insertions(+), 41 deletions(-) delete mode 100644 tests/crashes/139409.rs create mode 100644 tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-1.next.stderr create mode 100644 tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-1.rs create mode 100644 tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-2.next.stderr create mode 100644 tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-2.rs diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index 9f4ab8ca5d41..20844dee7932 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -85,8 +85,11 @@ impl<'tcx> TypeckRootCtxt<'tcx> { pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self { let hir_owner = tcx.local_def_id_to_hir_id(def_id).owner; - let infcx = - tcx.infer_ctxt().ignoring_regions().build(TypingMode::typeck_for_body(tcx, def_id)); + let infcx = tcx + .infer_ctxt() + .ignoring_regions() + .in_hir_typeck() + .build(TypingMode::typeck_for_body(tcx, def_id)); let typeck_results = RefCell::new(ty::TypeckResults::new(hir_owner)); let fulfillment_cx = RefCell::new(>::new(&infcx)); diff --git a/compiler/rustc_infer/src/infer/at.rs b/compiler/rustc_infer/src/infer/at.rs index 5fe795bd23a1..ad19cdef4e75 100644 --- a/compiler/rustc_infer/src/infer/at.rs +++ b/compiler/rustc_infer/src/infer/at.rs @@ -71,6 +71,7 @@ impl<'tcx> InferCtxt<'tcx> { tcx: self.tcx, typing_mode: self.typing_mode, considering_regions: self.considering_regions, + in_hir_typeck: self.in_hir_typeck, skip_leak_check: self.skip_leak_check, inner: self.inner.clone(), lexical_region_resolutions: self.lexical_region_resolutions.clone(), @@ -95,6 +96,7 @@ impl<'tcx> InferCtxt<'tcx> { tcx: self.tcx, typing_mode, considering_regions: self.considering_regions, + in_hir_typeck: self.in_hir_typeck, skip_leak_check: self.skip_leak_check, inner: self.inner.clone(), lexical_region_resolutions: self.lexical_region_resolutions.clone(), diff --git a/compiler/rustc_infer/src/infer/context.rs b/compiler/rustc_infer/src/infer/context.rs index bb9c88500936..21e999b080d5 100644 --- a/compiler/rustc_infer/src/infer/context.rs +++ b/compiler/rustc_infer/src/infer/context.rs @@ -22,6 +22,10 @@ impl<'tcx> rustc_type_ir::InferCtxtLike for InferCtxt<'tcx> { self.next_trait_solver } + fn in_hir_typeck(&self) -> bool { + self.in_hir_typeck + } + fn typing_mode(&self) -> ty::TypingMode<'tcx> { self.typing_mode() } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 2d269e320b64..17c587c5e7fd 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -244,9 +244,28 @@ pub struct InferCtxt<'tcx> { typing_mode: TypingMode<'tcx>, /// Whether this inference context should care about region obligations in - /// the root universe. Most notably, this is used during hir typeck as region + /// the root universe. Most notably, this is used during HIR typeck as region /// solving is left to borrowck instead. pub considering_regions: bool, + /// Whether this inference context is used by HIR typeck. If so, we uniquify regions + /// with `-Znext-solver`. This is necessary as borrowck will start by replacing each + /// occurance of a free region with a unique inference variable so if HIR typeck + /// ends up depending on two regions being equal we'd get unexpected mismatches + /// between HIR typeck and MIR typeck, resulting in an ICE. + /// + /// The trait solver sometimes depends on regions being identical. As a concrete example + /// the trait solver ignores other candidates if one candidate exists without any constraints. + /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now, but if we replace + /// each occurance of `'a` with a unique region the goal now equates these regions. + /// + /// See the tests in trait-system-refactor-initiative#27 for concrete examples. + /// + /// FIXME(-Znext-solver): This is insufficient in theory as a goal `T: Trait` + /// may rely on the two occurances of `?x` being identical. If `?x` gets inferred to a + /// type containing regions, this will no longer be the case. We can handle this case + /// by storing goals which hold while still depending on inference vars and then + /// reproving them before writeback. + pub in_hir_typeck: bool, /// If set, this flag causes us to skip the 'leak check' during /// higher-ranked subtyping operations. This flag is a temporary one used @@ -506,6 +525,7 @@ pub struct TypeOutlivesConstraint<'tcx> { pub struct InferCtxtBuilder<'tcx> { tcx: TyCtxt<'tcx>, considering_regions: bool, + in_hir_typeck: bool, skip_leak_check: bool, /// Whether we should use the new trait solver in the local inference context, /// which affects things like which solver is used in `predicate_may_hold`. @@ -518,6 +538,7 @@ impl<'tcx> TyCtxt<'tcx> { InferCtxtBuilder { tcx: self, considering_regions: true, + in_hir_typeck: false, skip_leak_check: false, next_trait_solver: self.next_trait_solver_globally(), } @@ -535,6 +556,11 @@ impl<'tcx> InferCtxtBuilder<'tcx> { self } + pub fn in_hir_typeck(mut self) -> Self { + self.in_hir_typeck = true; + self + } + pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self { self.skip_leak_check = skip_leak_check; self @@ -568,12 +594,18 @@ impl<'tcx> InferCtxtBuilder<'tcx> { } pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> { - let InferCtxtBuilder { tcx, considering_regions, skip_leak_check, next_trait_solver } = - *self; + let InferCtxtBuilder { + tcx, + considering_regions, + in_hir_typeck, + skip_leak_check, + next_trait_solver, + } = *self; InferCtxt { tcx, typing_mode, considering_regions, + in_hir_typeck, skip_leak_check, inner: RefCell::new(InferCtxtInner::new()), lexical_region_resolutions: RefCell::new(None), diff --git a/compiler/rustc_next_trait_solver/src/canonicalizer.rs b/compiler/rustc_next_trait_solver/src/canonicalizer.rs index a418aa82100c..1bc35e599c70 100644 --- a/compiler/rustc_next_trait_solver/src/canonicalizer.rs +++ b/compiler/rustc_next_trait_solver/src/canonicalizer.rs @@ -19,6 +19,20 @@ const NEEDS_CANONICAL: TypeFlags = TypeFlags::from_bits( ) .unwrap(); +#[derive(Debug, Clone, Copy)] +enum CanonicalizeInputKind { + /// When canonicalizing the `param_env`, we keep `'static` as merging + /// trait candidates relies on it when deciding whether a where-bound + /// is trivial. + ParamEnv, + /// When canonicalizing predicates, we don't keep `'static`. If we're + /// currently outside of the trait solver and canonicalize the root goal + /// during HIR typeck, we replace each occurance of a region with a + /// unique region variable. See the comment on `InferCtxt::in_hir_typeck` + /// for more details. + Predicate { is_hir_typeck_root_goal: bool }, +} + /// Whether we're canonicalizing a query input or the query response. /// /// When canonicalizing an input we're in the context of the caller @@ -26,10 +40,7 @@ const NEEDS_CANONICAL: TypeFlags = TypeFlags::from_bits( /// query. #[derive(Debug, Clone, Copy)] enum CanonicalizeMode { - /// When canonicalizing the `param_env`, we keep `'static` as merging - /// trait candidates relies on it when deciding whether a where-bound - /// is trivial. - Input { keep_static: bool }, + Input(CanonicalizeInputKind), /// FIXME: We currently return region constraints referring to /// placeholders and inference variables from a binder instantiated /// inside of the query. @@ -122,7 +133,7 @@ impl<'a, D: SolverDelegate, I: Interner> Canonicalizer<'a, D, I> { let mut variables = Vec::new(); let mut env_canonicalizer = Canonicalizer { delegate, - canonicalize_mode: CanonicalizeMode::Input { keep_static: true }, + canonicalize_mode: CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv), variables: &mut variables, variable_lookup_table: Default::default(), @@ -154,7 +165,7 @@ impl<'a, D: SolverDelegate, I: Interner> Canonicalizer<'a, D, I> { } else { let mut env_canonicalizer = Canonicalizer { delegate, - canonicalize_mode: CanonicalizeMode::Input { keep_static: true }, + canonicalize_mode: CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv), variables, variable_lookup_table: Default::default(), @@ -180,6 +191,7 @@ impl<'a, D: SolverDelegate, I: Interner> Canonicalizer<'a, D, I> { pub fn canonicalize_input>( delegate: &'a D, variables: &'a mut Vec, + is_hir_typeck_root_goal: bool, input: QueryInput, ) -> ty::Canonical> { // First canonicalize the `param_env` while keeping `'static` @@ -189,7 +201,9 @@ impl<'a, D: SolverDelegate, I: Interner> Canonicalizer<'a, D, I> { // while *mostly* reusing the canonicalizer from above. let mut rest_canonicalizer = Canonicalizer { delegate, - canonicalize_mode: CanonicalizeMode::Input { keep_static: false }, + canonicalize_mode: CanonicalizeMode::Input(CanonicalizeInputKind::Predicate { + is_hir_typeck_root_goal, + }), variables, variable_lookup_table, @@ -296,7 +310,7 @@ impl<'a, D: SolverDelegate, I: Interner> Canonicalizer<'a, D, I> { } } - fn cached_fold_ty(&mut self, t: I::Ty) -> I::Ty { + fn inner_fold_ty(&mut self, t: I::Ty) -> I::Ty { let kind = match t.kind() { ty::Infer(i) => match i { ty::TyVar(vid) => { @@ -413,10 +427,10 @@ impl, I: Interner> TypeFolder for Canonicaliz // We don't canonicalize `ReStatic` in the `param_env` as we use it // when checking whether a `ParamEnv` candidate is global. ty::ReStatic => match self.canonicalize_mode { - CanonicalizeMode::Input { keep_static: false } => { + CanonicalizeMode::Input(CanonicalizeInputKind::Predicate { .. }) => { CanonicalVarKind::Region(ty::UniverseIndex::ROOT) } - CanonicalizeMode::Input { keep_static: true } + CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv) | CanonicalizeMode::Response { .. } => return r, }, @@ -428,12 +442,12 @@ impl, I: Interner> TypeFolder for Canonicaliz // `ReErased`. We may be able to short-circuit registering region // obligations if we encounter a `ReErased` on one side, for example. ty::ReErased | ty::ReError(_) => match self.canonicalize_mode { - CanonicalizeMode::Input { .. } => CanonicalVarKind::Region(ty::UniverseIndex::ROOT), + CanonicalizeMode::Input(_) => CanonicalVarKind::Region(ty::UniverseIndex::ROOT), CanonicalizeMode::Response { .. } => return r, }, ty::ReEarlyParam(_) | ty::ReLateParam(_) => match self.canonicalize_mode { - CanonicalizeMode::Input { .. } => CanonicalVarKind::Region(ty::UniverseIndex::ROOT), + CanonicalizeMode::Input(_) => CanonicalVarKind::Region(ty::UniverseIndex::ROOT), CanonicalizeMode::Response { .. } => { panic!("unexpected region in response: {r:?}") } @@ -441,7 +455,7 @@ impl, I: Interner> TypeFolder for Canonicaliz ty::RePlaceholder(placeholder) => match self.canonicalize_mode { // We canonicalize placeholder regions as existentials in query inputs. - CanonicalizeMode::Input { .. } => CanonicalVarKind::Region(ty::UniverseIndex::ROOT), + CanonicalizeMode::Input(_) => CanonicalVarKind::Region(ty::UniverseIndex::ROOT), CanonicalizeMode::Response { max_input_universe } => { // If we have a placeholder region inside of a query, it must be from // a new universe. @@ -459,9 +473,7 @@ impl, I: Interner> TypeFolder for Canonicaliz "region vid should have been resolved fully before canonicalization" ); match self.canonicalize_mode { - CanonicalizeMode::Input { keep_static: _ } => { - CanonicalVarKind::Region(ty::UniverseIndex::ROOT) - } + CanonicalizeMode::Input(_) => CanonicalVarKind::Region(ty::UniverseIndex::ROOT), CanonicalizeMode::Response { .. } => { CanonicalVarKind::Region(self.delegate.universe_of_lt(vid).unwrap()) } @@ -469,16 +481,34 @@ impl, I: Interner> TypeFolder for Canonicaliz } }; - let var = self.get_or_insert_bound_var(r, kind); + let var = if let CanonicalizeMode::Input(CanonicalizeInputKind::Predicate { + is_hir_typeck_root_goal: true, + }) = self.canonicalize_mode + { + let var = ty::BoundVar::from(self.variables.len()); + self.variables.push(r.into()); + self.var_kinds.push(kind); + var + } else { + self.get_or_insert_bound_var(r, kind) + }; Region::new_anon_bound(self.cx(), self.binder_index, var) } fn fold_ty(&mut self, t: I::Ty) -> I::Ty { - if let Some(&ty) = self.cache.get(&(self.binder_index, t)) { + if let CanonicalizeMode::Input(CanonicalizeInputKind::Predicate { + is_hir_typeck_root_goal: true, + }) = self.canonicalize_mode + { + // If we're canonicalizing a root goal during HIR typeck, we + // must not use the `cache` as we want to map each occurrence + // of a region to a unique existential variable. + self.inner_fold_ty(t) + } else if let Some(&ty) = self.cache.get(&(self.binder_index, t)) { ty } else { - let res = self.cached_fold_ty(t); + let res = self.inner_fold_ty(t); let old = self.cache.insert((self.binder_index, t), res); assert_eq!(old, None); res @@ -541,9 +571,9 @@ impl, I: Interner> TypeFolder for Canonicaliz fn fold_clauses(&mut self, c: I::Clauses) -> I::Clauses { match self.canonicalize_mode { - CanonicalizeMode::Input { keep_static: true } + CanonicalizeMode::Input(CanonicalizeInputKind::ParamEnv) | CanonicalizeMode::Response { max_input_universe: _ } => {} - CanonicalizeMode::Input { keep_static: false } => { + CanonicalizeMode::Input(CanonicalizeInputKind::Predicate { .. }) => { panic!("erasing 'static in env") } } diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs index 5ed316aa6b13..de1330ca82a4 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs @@ -55,6 +55,7 @@ where /// for each bound variable. pub(super) fn canonicalize_goal( &self, + is_hir_typeck_root_goal: bool, goal: Goal, ) -> (Vec, CanonicalInput) { // We only care about one entry per `OpaqueTypeKey` here, @@ -67,6 +68,7 @@ where let canonical = Canonicalizer::canonicalize_input( self.delegate, &mut orig_values, + is_hir_typeck_root_goal, QueryInput { goal, predefined_opaques_in_body: self diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index ce9b794d40d3..053ccf285cf0 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -447,7 +447,10 @@ where )); } - let (orig_values, canonical_goal) = self.canonicalize_goal(goal); + let is_hir_typeck_root_goal = matches!(goal_evaluation_kind, GoalEvaluationKind::Root) + && self.delegate.in_hir_typeck(); + + let (orig_values, canonical_goal) = self.canonicalize_goal(is_hir_typeck_root_goal, goal); let mut goal_evaluation = self.inspect.new_goal_evaluation(goal, &orig_values, goal_evaluation_kind); let canonical_result = self.search_graph.evaluate_goal( diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index 5ea3f0d10617..f39426c7689d 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -252,8 +252,6 @@ where return None; } - // FIXME(-Znext-solver): Add support to merge region constraints in - // responses to deal with trait-system-refactor-initiative#27. let one = responses[0]; if responses[1..].iter().all(|&resp| resp == one) { return Some(one); diff --git a/compiler/rustc_type_ir/src/infer_ctxt.rs b/compiler/rustc_type_ir/src/infer_ctxt.rs index e86a2305e233..b4873c8c71cb 100644 --- a/compiler/rustc_type_ir/src/infer_ctxt.rs +++ b/compiler/rustc_type_ir/src/infer_ctxt.rs @@ -148,6 +148,10 @@ pub trait InferCtxtLike: Sized { true } + fn in_hir_typeck(&self) -> bool { + false + } + fn typing_mode(&self) -> TypingMode; fn universe(&self) -> ty::UniverseIndex; diff --git a/tests/crashes/139409.rs b/tests/crashes/139409.rs deleted file mode 100644 index 68cbfa153deb..000000000000 --- a/tests/crashes/139409.rs +++ /dev/null @@ -1,12 +0,0 @@ -//@ known-bug: #139409 -//@ compile-flags: -Znext-solver=globally - -fn main() { - trait B {} - impl B for () {} - trait D: B + B { - fn f(&self) {} - } - impl D for () {} - (&() as &dyn D<&(), &()>).f() -} diff --git a/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-1.next.stderr b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-1.next.stderr new file mode 100644 index 000000000000..141a07b4be7c --- /dev/null +++ b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-1.next.stderr @@ -0,0 +1,19 @@ +error[E0283]: type annotations needed: cannot satisfy `dyn D<&(), &()>: B<&()>` + --> $DIR/ambiguity-due-to-uniquification-1.rs:15:31 + | +LL | (&() as &dyn D<&(), &()>).f() + | ^ + | + = note: cannot satisfy `dyn D<&(), &()>: B<&()>` + = help: the trait `B` is implemented for `()` +note: required by a bound in `D::f` + --> $DIR/ambiguity-due-to-uniquification-1.rs:10:16 + | +LL | trait D: B + B { + | ^^^^ required by this bound in `D::f` +LL | fn f(&self) {} + | - required by a bound in this associated function + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0283`. diff --git a/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-1.rs b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-1.rs new file mode 100644 index 000000000000..cfdf74046fbd --- /dev/null +++ b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-1.rs @@ -0,0 +1,17 @@ +//@ revisions: current next +//@[next] compile-flags: -Znext-solver +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[current] check-pass + +// Regression test for #139409 and trait-system-refactor-initiative#27. + +trait B {} +impl B for () {} +trait D: B + B { + fn f(&self) {} +} +impl D for () {} +fn main() { + (&() as &dyn D<&(), &()>).f() + //[next]~^ ERROR type annotations needed: cannot satisfy `dyn D<&(), &()>: B<&()>` +} diff --git a/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-2.next.stderr b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-2.next.stderr new file mode 100644 index 000000000000..3b4788899969 --- /dev/null +++ b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-2.next.stderr @@ -0,0 +1,17 @@ +error[E0283]: type annotations needed: cannot satisfy `impl Trait<'x> + Trait<'y>: Trait<'y>` + --> $DIR/ambiguity-due-to-uniquification-2.rs:16:23 + | +LL | impls_trait::<'y, _>(foo::<'x, 'y>()); + | ^ + | + = note: cannot satisfy `impl Trait<'x> + Trait<'y>: Trait<'y>` + = help: the trait `Trait<'t>` is implemented for `()` +note: required by a bound in `impls_trait` + --> $DIR/ambiguity-due-to-uniquification-2.rs:13:23 + | +LL | fn impls_trait<'x, T: Trait<'x>>(_: T) {} + | ^^^^^^^^^ required by this bound in `impls_trait` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0283`. diff --git a/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-2.rs b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-2.rs new file mode 100644 index 000000000000..2a9a8b80cc06 --- /dev/null +++ b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-2.rs @@ -0,0 +1,20 @@ +//@ revisions: current next +//@[next] compile-flags: -Znext-solver +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[current] check-pass + +// Regression test from trait-system-refactor-initiative#27. + +trait Trait<'t> {} +impl<'t> Trait<'t> for () {} + +fn foo<'x, 'y>() -> impl Trait<'x> + Trait<'y> {} + +fn impls_trait<'x, T: Trait<'x>>(_: T) {} + +fn bar<'x, 'y>() { + impls_trait::<'y, _>(foo::<'x, 'y>()); + //[next]~^ ERROR type annotations needed: cannot satisfy `impl Trait<'x> + Trait<'y>: Trait<'y>` +} + +fn main() {} From da4687bafe4ff78a9816797c3b74b6bcc0c5a3bc Mon Sep 17 00:00:00 2001 From: Alisa Sireneva Date: Fri, 25 Jul 2025 16:09:29 +0300 Subject: [PATCH 146/809] 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 147/809] 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 | 151 +++++++--- clippy_lints/src/ineffective_open_options.rs | 100 +++---- 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 | 188 +++++-------- .../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 | 52 ++-- 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 | 94 ++++--- .../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 | 266 +++++++++--------- util/gh-pages/script.js | 27 +- util/gh-pages/style.css | 88 +++--- 166 files changed, 3824 insertions(+), 1159 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 - } else if let Some(parent_def_id) = tcx.opt_parent(def_id) { - self.get_def_id_version(tcx, parent_def_id) + let (feature, stability_level) = if needs_const { + tcx.lookup_const_stability(def_id) + .map(|stability| (stability.feature, stability.level)) + .unzip() } else { - RustcVersion { + 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_availability(tcx, parent_def_id, needs_const) + } else { + 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; - - 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); - } - receiver = recv; - } - - if let Some(write_span) = write - && append.is_some() + 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) { - 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, - ); + 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 + } + }); + + 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, + ); + } } } } 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; + 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() + } + + 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; + }; + + 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, + ); + } + return; } - if let ty::Ref(_, ty, ..) = arg_ty.kind() - && ty.is_str() - && can_be_static_str(cx, arg) - { - return false; - } - true + + 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, + ); } - - // 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, - } - } - - 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, - } - } - - if args.len() != 1 || name != sym::expect || !is_call(&args[0].kind) { - return; - } - - 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, - ); - } - 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()"); - } - - 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 @@ -37,59 +37,65 @@ error: function call inside of `expect` 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 - | -LL | Some("foo").expect(&get_string()); - | ^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| { panic!("{}", get_string()) })` - -error: function call inside of `expect` - --> tests/ui/expect_fun_call.rs:95:21 - | -LL | Some("foo").expect(get_string().as_ref()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| { panic!("{}", get_string()) })` - error: function call inside of `expect` --> tests/ui/expect_fun_call.rs:97:21 | -LL | Some("foo").expect(get_string().as_str()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| { panic!("{}", get_string()) })` +LL | Some("foo").expect(&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:99:21 + | +LL | Some("foo").expect(get_string().as_ref()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", get_string()))` + +error: function call inside of `expect` + --> tests/ui/expect_fun_call.rs:101:21 + | +LL | Some("foo").expect(get_string().as_str()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", get_string()))` + +error: function call inside of `expect` + --> 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:107:16 + --> 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: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: 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:100: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: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:116:5 + --> 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: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: `#[must_use] 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 { + | 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 - | -LL | let _ = ..=11 - 1; - | ^^^^^^^^^ help: use: `..11` - | - = note: `-D clippy::range-minus-one` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::range_minus_one)]` - -error: an exclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:51:13 - | -LL | let _ = ..=(11 - 1); - | ^^^^^^^^^^^ help: use: `..11` - -error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:53:13 - | -LL | let _ = (1..11 + 1); - | ^^^^^^^^^^^ help: use: `(1..=11)` - -error: an inclusive range would be more readable - --> tests/ui/range_plus_minus_one.rs:55:13 - | -LL | let _ = (f() + 1)..(f() + 1); - | ^^^^^^^^^^^^^^^^^^^^ help: use: `((f() + 1)..=f())` - error: an inclusive range would be more readable --> tests/ui/range_plus_minus_one.rs:60:14 | LL | for _ in 1..ONE + ONE {} | ^^^^^^^^^^^^ help: use: `1..=ONE` -error: aborting due to 9 previous errors +error: an inclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:70:5 + | +LL | (1..10 + 1).for_each(|_| {}); + | ^^^^^^^^^^^ help: use: `(1..=10)` + +error: an inclusive range would be more readable + --> tests/ui/range_plus_minus_one.rs:75:5 + | +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:80:17 + | +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:86:16 + | +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:90:15 + | +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 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 @@ Otherwise, have a great day =^.^= {# #}
{# #} - {# #} +

Clippy Lints

{# #} {# #} -
{# #} - - {% for lint in lints %} -
{# #} - {# #} - {# #} - -
{# #} -
{{Self::markdown(lint.docs)}}
{# #} -
- {# Applicability #} -
{# #} - Applicability: {#+ #} - {{ lint.applicability_str() }} {# #} - (?) {# #} -
- {# Clippy version #} -
{# #} - {% if lint.group == "deprecated" %}Deprecated{% else %} Added{% endif +%} in: {#+ #} - {{lint.version}} {# #} -
- {# Open related issues #} -
{# #} - Related Issues {# #} -
- - {# Jump to source #} - {% if let Some(id_location) = lint.id_location %} -
{# #} - View Source {# #} -
- {% endif %} -
{# #} +
{# #} +
{# #} + {# #} + {# #} + {# #} + {# #} + {# #}
{# #} -
- {% endfor %} -
{# #} +
{# #} +
{# #} + {# #} + {# #} +
{# #} + {# #} + + {% for lint in lints %} +
{# #} + {# #} + {# #} + +
{# #} +
{{Self::markdown(lint.docs)}}
{# #} +
+ {# Applicability #} +
{# #} + Applicability: {#+ #} + {{ lint.applicability_str() }} {# #} + (?) {# #} +
+ {# Clippy version #} +
{# #} + {% if lint.group == "deprecated" %}Deprecated{% else %} Added{% endif +%} in: {#+ #} + {{lint.version}} {# #} +
+ {# Open related issues #} +
{# #} + Related Issues {# #} +
+ + {# Jump to source #} + {% if let Some(id_location) = lint.id_location %} +
{# #} + View Source {# #} +
+ {% endif %} +
{# #} +
{# #} +
+ {% endfor %} {# #} 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(); - -function updateLintCount() { - const allLints = filters.getAllLints().filter(lint => lint.group != "deprecated"); - const totalLints = allLints.length; - - const countElement = document.getElementById("lint-count"); - if (countElement) { - countElement.innerText = `Total number: ${totalLints}`; - } -} 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); + border: 0; + border-bottom: 1px solid var(--theme-popup-border); + padding-bottom: 19px; + border-radius: 0; } -.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); -} -.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 9f38ca97eab53ba2f431a48bec2343ef52335714 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Fri, 18 Jul 2025 22:00:30 +0500 Subject: [PATCH 148/809] move 28 tests --- .../issue-10396.rs => array-slice-vec/array-pattern-matching.rs} | 0 .../issue-11205.rs => array-slice-vec/trait-object-arrays.rs} | 0 .../issue-11192.rs => borrowck/closure-borrow-conflict.rs} | 0 .../issue-11085.rs => cfg/conditional-compilation-struct.rs} | 0 .../ui/{issues/issue-10718.rs => closures/fnonce-closure-call.rs} | 0 .../{issues/issue-10734.rs => drop/conditional-drop-behavior.rs} | 0 .../{issues/issue-10802.rs => drop/trait-object-drop-behavior.rs} | 0 .../issue-10764.rs => extern/extern-rust-fn-type-error.rs} | 0 .../{issues/issue-10877.rs => extern/foreign-fn-pattern-error.rs} | 0 tests/ui/{issues/issue-10767.rs => fn/boxed-fn-pointer.rs} | 0 .../{issues/issue-10436.rs => generics/generic-type-inference.rs} | 0 .../ui/{issues/issue-10806.rs => imports/empty-use-statements.rs} | 0 .../issue-10291.rs => lifetimes/closure-lifetime-bounds-error.rs} | 0 .../issue-11374.rs => lifetimes/container-lifetime-error.rs} | 0 .../issue-10228.rs => lifetimes/enum-lifetime-container.rs} | 0 .../issue-10412.rs => lifetimes/keyword-self-lifetime-error.rs} | 0 .../{issues/issue-10902.rs => lifetimes/trait-lifetime-bounds.rs} | 0 tests/ui/{issues/issue-10853.rs => lint/inner-doc-attributes.rs} | 0 tests/ui/{issues/issue-10638.rs => parser/comment-parsing.rs} | 0 .../{issues/issue-10683.rs => pattern/ascii-lowercase-match.rs} | 0 .../issue-10545.rs => privacy/private-struct-access-error.rs} | 0 .../issue-11267.rs => structs/mutable-unit-struct-borrow.rs} | 0 .../issue-10456.rs => traits/blanket-impl-trait-object.rs} | 0 .../issue-10465.rs => traits/missing-trait-method-error.rs} | 0 .../issue-106755.rs => traits/negative-positive-impl-conflict.rs} | 0 .../issue-102964.rs => type-alias/mismatched-rc-foo-types.rs} | 0 .../issue-11047.rs => type-alias/static-method-type-alias.rs} | 0 .../issue-11004.rs => unsafe/raw-pointer-field-access-error.rs} | 0 28 files changed, 0 insertions(+), 0 deletions(-) rename tests/ui/{issues/issue-10396.rs => array-slice-vec/array-pattern-matching.rs} (100%) rename tests/ui/{issues/issue-11205.rs => array-slice-vec/trait-object-arrays.rs} (100%) rename tests/ui/{issues/issue-11192.rs => borrowck/closure-borrow-conflict.rs} (100%) rename tests/ui/{issues/issue-11085.rs => cfg/conditional-compilation-struct.rs} (100%) rename tests/ui/{issues/issue-10718.rs => closures/fnonce-closure-call.rs} (100%) rename tests/ui/{issues/issue-10734.rs => drop/conditional-drop-behavior.rs} (100%) rename tests/ui/{issues/issue-10802.rs => drop/trait-object-drop-behavior.rs} (100%) rename tests/ui/{issues/issue-10764.rs => extern/extern-rust-fn-type-error.rs} (100%) rename tests/ui/{issues/issue-10877.rs => extern/foreign-fn-pattern-error.rs} (100%) rename tests/ui/{issues/issue-10767.rs => fn/boxed-fn-pointer.rs} (100%) rename tests/ui/{issues/issue-10436.rs => generics/generic-type-inference.rs} (100%) rename tests/ui/{issues/issue-10806.rs => imports/empty-use-statements.rs} (100%) rename tests/ui/{issues/issue-10291.rs => lifetimes/closure-lifetime-bounds-error.rs} (100%) rename tests/ui/{issues/issue-11374.rs => lifetimes/container-lifetime-error.rs} (100%) rename tests/ui/{issues/issue-10228.rs => lifetimes/enum-lifetime-container.rs} (100%) rename tests/ui/{issues/issue-10412.rs => lifetimes/keyword-self-lifetime-error.rs} (100%) rename tests/ui/{issues/issue-10902.rs => lifetimes/trait-lifetime-bounds.rs} (100%) rename tests/ui/{issues/issue-10853.rs => lint/inner-doc-attributes.rs} (100%) rename tests/ui/{issues/issue-10638.rs => parser/comment-parsing.rs} (100%) rename tests/ui/{issues/issue-10683.rs => pattern/ascii-lowercase-match.rs} (100%) rename tests/ui/{issues/issue-10545.rs => privacy/private-struct-access-error.rs} (100%) rename tests/ui/{issues/issue-11267.rs => structs/mutable-unit-struct-borrow.rs} (100%) rename tests/ui/{issues/issue-10456.rs => traits/blanket-impl-trait-object.rs} (100%) rename tests/ui/{issues/issue-10465.rs => traits/missing-trait-method-error.rs} (100%) rename tests/ui/{issues/issue-106755.rs => traits/negative-positive-impl-conflict.rs} (100%) rename tests/ui/{issues/issue-102964.rs => type-alias/mismatched-rc-foo-types.rs} (100%) rename tests/ui/{issues/issue-11047.rs => type-alias/static-method-type-alias.rs} (100%) rename tests/ui/{issues/issue-11004.rs => unsafe/raw-pointer-field-access-error.rs} (100%) diff --git a/tests/ui/issues/issue-10396.rs b/tests/ui/array-slice-vec/array-pattern-matching.rs similarity index 100% rename from tests/ui/issues/issue-10396.rs rename to tests/ui/array-slice-vec/array-pattern-matching.rs diff --git a/tests/ui/issues/issue-11205.rs b/tests/ui/array-slice-vec/trait-object-arrays.rs similarity index 100% rename from tests/ui/issues/issue-11205.rs rename to tests/ui/array-slice-vec/trait-object-arrays.rs diff --git a/tests/ui/issues/issue-11192.rs b/tests/ui/borrowck/closure-borrow-conflict.rs similarity index 100% rename from tests/ui/issues/issue-11192.rs rename to tests/ui/borrowck/closure-borrow-conflict.rs diff --git a/tests/ui/issues/issue-11085.rs b/tests/ui/cfg/conditional-compilation-struct.rs similarity index 100% rename from tests/ui/issues/issue-11085.rs rename to tests/ui/cfg/conditional-compilation-struct.rs diff --git a/tests/ui/issues/issue-10718.rs b/tests/ui/closures/fnonce-closure-call.rs similarity index 100% rename from tests/ui/issues/issue-10718.rs rename to tests/ui/closures/fnonce-closure-call.rs diff --git a/tests/ui/issues/issue-10734.rs b/tests/ui/drop/conditional-drop-behavior.rs similarity index 100% rename from tests/ui/issues/issue-10734.rs rename to tests/ui/drop/conditional-drop-behavior.rs diff --git a/tests/ui/issues/issue-10802.rs b/tests/ui/drop/trait-object-drop-behavior.rs similarity index 100% rename from tests/ui/issues/issue-10802.rs rename to tests/ui/drop/trait-object-drop-behavior.rs diff --git a/tests/ui/issues/issue-10764.rs b/tests/ui/extern/extern-rust-fn-type-error.rs similarity index 100% rename from tests/ui/issues/issue-10764.rs rename to tests/ui/extern/extern-rust-fn-type-error.rs diff --git a/tests/ui/issues/issue-10877.rs b/tests/ui/extern/foreign-fn-pattern-error.rs similarity index 100% rename from tests/ui/issues/issue-10877.rs rename to tests/ui/extern/foreign-fn-pattern-error.rs diff --git a/tests/ui/issues/issue-10767.rs b/tests/ui/fn/boxed-fn-pointer.rs similarity index 100% rename from tests/ui/issues/issue-10767.rs rename to tests/ui/fn/boxed-fn-pointer.rs diff --git a/tests/ui/issues/issue-10436.rs b/tests/ui/generics/generic-type-inference.rs similarity index 100% rename from tests/ui/issues/issue-10436.rs rename to tests/ui/generics/generic-type-inference.rs diff --git a/tests/ui/issues/issue-10806.rs b/tests/ui/imports/empty-use-statements.rs similarity index 100% rename from tests/ui/issues/issue-10806.rs rename to tests/ui/imports/empty-use-statements.rs diff --git a/tests/ui/issues/issue-10291.rs b/tests/ui/lifetimes/closure-lifetime-bounds-error.rs similarity index 100% rename from tests/ui/issues/issue-10291.rs rename to tests/ui/lifetimes/closure-lifetime-bounds-error.rs diff --git a/tests/ui/issues/issue-11374.rs b/tests/ui/lifetimes/container-lifetime-error.rs similarity index 100% rename from tests/ui/issues/issue-11374.rs rename to tests/ui/lifetimes/container-lifetime-error.rs diff --git a/tests/ui/issues/issue-10228.rs b/tests/ui/lifetimes/enum-lifetime-container.rs similarity index 100% rename from tests/ui/issues/issue-10228.rs rename to tests/ui/lifetimes/enum-lifetime-container.rs diff --git a/tests/ui/issues/issue-10412.rs b/tests/ui/lifetimes/keyword-self-lifetime-error.rs similarity index 100% rename from tests/ui/issues/issue-10412.rs rename to tests/ui/lifetimes/keyword-self-lifetime-error.rs diff --git a/tests/ui/issues/issue-10902.rs b/tests/ui/lifetimes/trait-lifetime-bounds.rs similarity index 100% rename from tests/ui/issues/issue-10902.rs rename to tests/ui/lifetimes/trait-lifetime-bounds.rs diff --git a/tests/ui/issues/issue-10853.rs b/tests/ui/lint/inner-doc-attributes.rs similarity index 100% rename from tests/ui/issues/issue-10853.rs rename to tests/ui/lint/inner-doc-attributes.rs diff --git a/tests/ui/issues/issue-10638.rs b/tests/ui/parser/comment-parsing.rs similarity index 100% rename from tests/ui/issues/issue-10638.rs rename to tests/ui/parser/comment-parsing.rs diff --git a/tests/ui/issues/issue-10683.rs b/tests/ui/pattern/ascii-lowercase-match.rs similarity index 100% rename from tests/ui/issues/issue-10683.rs rename to tests/ui/pattern/ascii-lowercase-match.rs diff --git a/tests/ui/issues/issue-10545.rs b/tests/ui/privacy/private-struct-access-error.rs similarity index 100% rename from tests/ui/issues/issue-10545.rs rename to tests/ui/privacy/private-struct-access-error.rs diff --git a/tests/ui/issues/issue-11267.rs b/tests/ui/structs/mutable-unit-struct-borrow.rs similarity index 100% rename from tests/ui/issues/issue-11267.rs rename to tests/ui/structs/mutable-unit-struct-borrow.rs diff --git a/tests/ui/issues/issue-10456.rs b/tests/ui/traits/blanket-impl-trait-object.rs similarity index 100% rename from tests/ui/issues/issue-10456.rs rename to tests/ui/traits/blanket-impl-trait-object.rs diff --git a/tests/ui/issues/issue-10465.rs b/tests/ui/traits/missing-trait-method-error.rs similarity index 100% rename from tests/ui/issues/issue-10465.rs rename to tests/ui/traits/missing-trait-method-error.rs diff --git a/tests/ui/issues/issue-106755.rs b/tests/ui/traits/negative-positive-impl-conflict.rs similarity index 100% rename from tests/ui/issues/issue-106755.rs rename to tests/ui/traits/negative-positive-impl-conflict.rs diff --git a/tests/ui/issues/issue-102964.rs b/tests/ui/type-alias/mismatched-rc-foo-types.rs similarity index 100% rename from tests/ui/issues/issue-102964.rs rename to tests/ui/type-alias/mismatched-rc-foo-types.rs diff --git a/tests/ui/issues/issue-11047.rs b/tests/ui/type-alias/static-method-type-alias.rs similarity index 100% rename from tests/ui/issues/issue-11047.rs rename to tests/ui/type-alias/static-method-type-alias.rs diff --git a/tests/ui/issues/issue-11004.rs b/tests/ui/unsafe/raw-pointer-field-access-error.rs similarity index 100% rename from tests/ui/issues/issue-11004.rs rename to tests/ui/unsafe/raw-pointer-field-access-error.rs From e9959aa74e23eb340d6c9e9a4eab807be03b028f Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Fri, 18 Jul 2025 22:06:07 +0500 Subject: [PATCH 149/809] comments --- tests/ui/README.md | 4 ++++ ...flict.rs => closure-borrow-conflict-11192.rs} | 2 ++ .../closure-borrow-conflict-11192.stderr} | 2 +- ...s => conditional-compilation-struct-11085.rs} | 2 ++ .../trait-object-arrays-11205.rs} | 2 ++ .../primary-fluent-bundle-missing.rs} | 2 ++ .../primary-fluent-bundle-missing.stderr} | 12 ++++++------ ...rop-behavior.rs => conditional-drop-10734.rs} | 2 ++ ...op-behavior.rs => trait-object-drop-10802.rs} | 2 ++ ...ror.rs => extern-rust-fn-type-error-10764.rs} | 2 ++ .../extern-rust-fn-type-error-10764.stderr} | 4 ++-- ...rror.rs => foreign-fn-pattern-error-10877.rs} | 2 ++ .../foreign-fn-pattern-error-10877.stderr} | 8 ++++---- tests/ui/fn/boxed-fn-pointer.rs | 7 ------- ...=> use-declaration-no-path-segment-prefix.rs} | 2 ++ .../fnonce-closure-call.rs | 2 ++ .../generic-type-inference-10436.rs} | 2 ++ .../array-pattern-matching-10396.rs} | 2 ++ ...error.rs => closure-lifetime-bounds-10291.rs} | 2 ++ .../closure-lifetime-bounds-10291.stderr} | 2 +- ...rror.rs => container-lifetime-error-11374.rs} | 2 ++ .../container-lifetime-error-11374.stderr} | 6 +++--- ...ainer.rs => enum-lifetime-container-10228.rs} | 2 ++ ...r.rs => keyword-self-lifetime-error-10412.rs} | 2 ++ .../keyword-self-lifetime-error-10412.stderr} | 16 ++++++++-------- ...ruct-vs-struct-with-fields-borrowck-10902.rs} | 2 ++ ...rs => missing-doc-unsugard-doc-attr-10853.rs} | 2 ++ ...comment-parsing.rs => doc-comment-parsing.rs} | 2 ++ ...ture-match-scrutinee-temporary-drop-10683.rs} | 2 ++ ....rs => struct-field-and-impl-expose-10545.rs} | 2 ++ .../struct-field-and-impl-expose-10545.stderr} | 4 ++-- ...ow.rs => mutable-unit-struct-borrow-11267.rs} | 2 ++ ...ect.rs => blanket-impl-trait-object-10456.rs} | 2 ++ ...nested-mod-trait-method-lookup-leak-10465.rs} | 2 ++ ...ed-mod-trait-method-lookup-leak-10465.stderr} | 2 +- ...ed-rc-foo-types.rs => dummy-binder-102964.rs} | 2 ++ .../dummy-binder-102964.stderr} | 2 +- ...lias.rs => static-method-type-alias-11047.rs} | 2 ++ .../ui/unsafe/raw-pointer-field-access-error.rs | 2 ++ .../raw-pointer-field-access-error.stderr} | 4 ++-- 40 files changed, 89 insertions(+), 38 deletions(-) rename tests/ui/borrowck/{closure-borrow-conflict.rs => closure-borrow-conflict-11192.rs} (85%) rename tests/ui/{issues/issue-11192.stderr => borrowck/closure-borrow-conflict-11192.stderr} (92%) rename tests/ui/cfg/{conditional-compilation-struct.rs => conditional-compilation-struct-11085.rs} (88%) rename tests/ui/{array-slice-vec/trait-object-arrays.rs => coercion/trait-object-arrays-11205.rs} (95%) rename tests/ui/{traits/negative-positive-impl-conflict.rs => diagnostics-infra/primary-fluent-bundle-missing.rs} (89%) rename tests/ui/{issues/issue-106755.stderr => diagnostics-infra/primary-fluent-bundle-missing.stderr} (84%) rename tests/ui/drop/{conditional-drop-behavior.rs => conditional-drop-10734.rs} (93%) rename tests/ui/drop/{trait-object-drop-behavior.rs => trait-object-drop-10802.rs} (93%) rename tests/ui/extern/{extern-rust-fn-type-error.rs => extern-rust-fn-type-error-10764.rs} (59%) rename tests/ui/{issues/issue-10764.stderr => extern/extern-rust-fn-type-error-10764.stderr} (83%) rename tests/ui/extern/{foreign-fn-pattern-error.rs => foreign-fn-pattern-error-10877.rs} (87%) rename tests/ui/{issues/issue-10877.stderr => extern/foreign-fn-pattern-error-10877.stderr} (79%) delete mode 100644 tests/ui/fn/boxed-fn-pointer.rs rename tests/ui/imports/{empty-use-statements.rs => use-declaration-no-path-segment-prefix.rs} (87%) rename tests/ui/{closures => inference}/fnonce-closure-call.rs (57%) rename tests/ui/{generics/generic-type-inference.rs => inference/generic-type-inference-10436.rs} (77%) rename tests/ui/{array-slice-vec/array-pattern-matching.rs => lifetimes/array-pattern-matching-10396.rs} (71%) rename tests/ui/lifetimes/{closure-lifetime-bounds-error.rs => closure-lifetime-bounds-10291.rs} (72%) rename tests/ui/{issues/issue-10291.stderr => lifetimes/closure-lifetime-bounds-10291.stderr} (87%) rename tests/ui/lifetimes/{container-lifetime-error.rs => container-lifetime-error-11374.rs} (89%) rename tests/ui/{issues/issue-11374.stderr => lifetimes/container-lifetime-error-11374.stderr} (86%) rename tests/ui/lifetimes/{enum-lifetime-container.rs => enum-lifetime-container-10228.rs} (80%) rename tests/ui/lifetimes/{keyword-self-lifetime-error.rs => keyword-self-lifetime-error-10412.rs} (91%) rename tests/ui/{issues/issue-10412.stderr => lifetimes/keyword-self-lifetime-error-10412.stderr} (76%) rename tests/ui/lifetimes/{trait-lifetime-bounds.rs => tuple-struct-vs-struct-with-fields-borrowck-10902.rs} (87%) rename tests/ui/lint/{inner-doc-attributes.rs => missing-doc-unsugard-doc-attr-10853.rs} (68%) rename tests/ui/parser/{comment-parsing.rs => doc-comment-parsing.rs} (74%) rename tests/ui/pattern/{ascii-lowercase-match.rs => premature-match-scrutinee-temporary-drop-10683.rs} (68%) rename tests/ui/privacy/{private-struct-access-error.rs => struct-field-and-impl-expose-10545.rs} (59%) rename tests/ui/{issues/issue-10545.stderr => privacy/struct-field-and-impl-expose-10545.stderr} (73%) rename tests/ui/structs/{mutable-unit-struct-borrow.rs => mutable-unit-struct-borrow-11267.rs} (82%) rename tests/ui/traits/{blanket-impl-trait-object.rs => blanket-impl-trait-object-10456.rs} (81%) rename tests/ui/traits/{missing-trait-method-error.rs => nested-mod-trait-method-lookup-leak-10465.rs} (80%) rename tests/ui/{issues/issue-10465.stderr => traits/nested-mod-trait-method-lookup-leak-10465.stderr} (88%) rename tests/ui/type-alias/{mismatched-rc-foo-types.rs => dummy-binder-102964.rs} (75%) rename tests/ui/{issues/issue-102964.stderr => type-alias/dummy-binder-102964.stderr} (93%) rename tests/ui/type-alias/{static-method-type-alias.rs => static-method-type-alias-11047.rs} (87%) rename tests/ui/{issues/issue-11004.stderr => unsafe/raw-pointer-field-access-error.stderr} (85%) diff --git a/tests/ui/README.md b/tests/ui/README.md index b635b6326fce..3630ce9285da 100644 --- a/tests/ui/README.md +++ b/tests/ui/README.md @@ -412,6 +412,10 @@ These tests revolve around command-line flags which change the way error/warning Exercises `#[diagnostic::*]` namespaced attributes. See [RFC 3368 Diagnostic attribute namespace](https://github.com/rust-lang/rfcs/blob/master/text/3368-diagnostic-attribute-namespace.md). +## `tests/ui/diagnostics-infra` + +This directory contains tests and infrastructure related to the diagnostics system, including support for translatable diagnostics + ## `tests/ui/diagnostic-width/`: `--diagnostic-width` Everything to do with `--diagnostic-width`. diff --git a/tests/ui/borrowck/closure-borrow-conflict.rs b/tests/ui/borrowck/closure-borrow-conflict-11192.rs similarity index 85% rename from tests/ui/borrowck/closure-borrow-conflict.rs rename to tests/ui/borrowck/closure-borrow-conflict-11192.rs index 1a3d8c9fe586..dff70d62d6f4 100644 --- a/tests/ui/borrowck/closure-borrow-conflict.rs +++ b/tests/ui/borrowck/closure-borrow-conflict-11192.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11192 + struct Foo { x: isize } diff --git a/tests/ui/issues/issue-11192.stderr b/tests/ui/borrowck/closure-borrow-conflict-11192.stderr similarity index 92% rename from tests/ui/issues/issue-11192.stderr rename to tests/ui/borrowck/closure-borrow-conflict-11192.stderr index a8a18c49549d..f1df635276b4 100644 --- a/tests/ui/issues/issue-11192.stderr +++ b/tests/ui/borrowck/closure-borrow-conflict-11192.stderr @@ -1,5 +1,5 @@ error[E0502]: cannot borrow `*ptr` as immutable because it is also borrowed as mutable - --> $DIR/issue-11192.rs:20:10 + --> $DIR/closure-borrow-conflict-11192.rs:22:10 | LL | let mut test = |foo: &Foo| { | ----------- mutable borrow occurs here diff --git a/tests/ui/cfg/conditional-compilation-struct.rs b/tests/ui/cfg/conditional-compilation-struct-11085.rs similarity index 88% rename from tests/ui/cfg/conditional-compilation-struct.rs rename to tests/ui/cfg/conditional-compilation-struct-11085.rs index c3f13199b308..cd6dded54d30 100644 --- a/tests/ui/cfg/conditional-compilation-struct.rs +++ b/tests/ui/cfg/conditional-compilation-struct-11085.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11085 + //@ run-pass #![allow(dead_code)] diff --git a/tests/ui/array-slice-vec/trait-object-arrays.rs b/tests/ui/coercion/trait-object-arrays-11205.rs similarity index 95% rename from tests/ui/array-slice-vec/trait-object-arrays.rs rename to tests/ui/coercion/trait-object-arrays-11205.rs index 8530514f0edf..45d69dce3238 100644 --- a/tests/ui/array-slice-vec/trait-object-arrays.rs +++ b/tests/ui/coercion/trait-object-arrays-11205.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11205 + //@ run-pass #![allow(dead_code)] diff --git a/tests/ui/traits/negative-positive-impl-conflict.rs b/tests/ui/diagnostics-infra/primary-fluent-bundle-missing.rs similarity index 89% rename from tests/ui/traits/negative-positive-impl-conflict.rs rename to tests/ui/diagnostics-infra/primary-fluent-bundle-missing.rs index d7e7122ebda1..f2965778431c 100644 --- a/tests/ui/traits/negative-positive-impl-conflict.rs +++ b/tests/ui/diagnostics-infra/primary-fluent-bundle-missing.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/106755 + //@ compile-flags:-Ztranslate-lang=en_US #![feature(negative_impls)] diff --git a/tests/ui/issues/issue-106755.stderr b/tests/ui/diagnostics-infra/primary-fluent-bundle-missing.stderr similarity index 84% rename from tests/ui/issues/issue-106755.stderr rename to tests/ui/diagnostics-infra/primary-fluent-bundle-missing.stderr index da6b8c5c5632..1dc31e161a76 100644 --- a/tests/ui/issues/issue-106755.stderr +++ b/tests/ui/diagnostics-infra/primary-fluent-bundle-missing.stderr @@ -1,5 +1,5 @@ error[E0751]: found both positive and negative implementation of trait `Send` for type `TestType<_>`: - --> $DIR/issue-106755.rs:13:1 + --> $DIR/primary-fluent-bundle-missing.rs:15:1 | LL | unsafe impl Send for TestType {} | ------------------------------------------------------ positive implementation here @@ -8,7 +8,7 @@ LL | impl !Send for TestType {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ negative implementation here error[E0119]: conflicting implementations of trait `Send` for type `TestType<_>` - --> $DIR/issue-106755.rs:17:1 + --> $DIR/primary-fluent-bundle-missing.rs:19:1 | LL | unsafe impl Send for TestType {} | ------------------------------------------------------ first implementation here @@ -17,26 +17,26 @@ LL | unsafe impl Send for TestType {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `TestType<_>` error[E0367]: `!Send` impl requires `T: MyTrait` but the struct it is implemented for does not - --> $DIR/issue-106755.rs:13:9 + --> $DIR/primary-fluent-bundle-missing.rs:15:9 | LL | impl !Send for TestType {} | ^^^^^^^ | note: the implementor must specify the same requirement - --> $DIR/issue-106755.rs:9:1 + --> $DIR/primary-fluent-bundle-missing.rs:11:1 | LL | struct TestType(::std::marker::PhantomData); | ^^^^^^^^^^^^^^^^^^ error[E0366]: `!Send` impls cannot be specialized - --> $DIR/issue-106755.rs:19:1 + --> $DIR/primary-fluent-bundle-missing.rs:21:1 | LL | impl !Send for TestType {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `i32` is not a generic parameter note: use the same sequence of generic lifetime, type and const parameters as the struct definition - --> $DIR/issue-106755.rs:9:1 + --> $DIR/primary-fluent-bundle-missing.rs:11:1 | LL | struct TestType(::std::marker::PhantomData); | ^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/drop/conditional-drop-behavior.rs b/tests/ui/drop/conditional-drop-10734.rs similarity index 93% rename from tests/ui/drop/conditional-drop-behavior.rs rename to tests/ui/drop/conditional-drop-10734.rs index 6d815aeca076..25f492bf9e08 100644 --- a/tests/ui/drop/conditional-drop-behavior.rs +++ b/tests/ui/drop/conditional-drop-10734.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10734 + //@ run-pass #![allow(non_upper_case_globals)] diff --git a/tests/ui/drop/trait-object-drop-behavior.rs b/tests/ui/drop/trait-object-drop-10802.rs similarity index 93% rename from tests/ui/drop/trait-object-drop-behavior.rs rename to tests/ui/drop/trait-object-drop-10802.rs index eca701ce98c9..a8a955ad8334 100644 --- a/tests/ui/drop/trait-object-drop-behavior.rs +++ b/tests/ui/drop/trait-object-drop-10802.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10802 + //@ run-pass #![allow(dead_code)] diff --git a/tests/ui/extern/extern-rust-fn-type-error.rs b/tests/ui/extern/extern-rust-fn-type-error-10764.rs similarity index 59% rename from tests/ui/extern/extern-rust-fn-type-error.rs rename to tests/ui/extern/extern-rust-fn-type-error-10764.rs index bb915f58d9d2..f172f6e6b7d9 100644 --- a/tests/ui/extern/extern-rust-fn-type-error.rs +++ b/tests/ui/extern/extern-rust-fn-type-error-10764.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10764 + fn f(_: extern "Rust" fn()) {} extern "C" fn bar() {} diff --git a/tests/ui/issues/issue-10764.stderr b/tests/ui/extern/extern-rust-fn-type-error-10764.stderr similarity index 83% rename from tests/ui/issues/issue-10764.stderr rename to tests/ui/extern/extern-rust-fn-type-error-10764.stderr index f3bd0100a72a..fa72d7dd6b2f 100644 --- a/tests/ui/issues/issue-10764.stderr +++ b/tests/ui/extern/extern-rust-fn-type-error-10764.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-10764.rs:4:15 + --> $DIR/extern-rust-fn-type-error-10764.rs:6:15 | LL | fn main() { f(bar) } | - ^^^ expected "Rust" fn, found "C" fn @@ -9,7 +9,7 @@ LL | fn main() { f(bar) } = note: expected fn pointer `fn()` found fn item `extern "C" fn() {bar}` note: function defined here - --> $DIR/issue-10764.rs:1:4 + --> $DIR/extern-rust-fn-type-error-10764.rs:3:4 | LL | fn f(_: extern "Rust" fn()) {} | ^ --------------------- diff --git a/tests/ui/extern/foreign-fn-pattern-error.rs b/tests/ui/extern/foreign-fn-pattern-error-10877.rs similarity index 87% rename from tests/ui/extern/foreign-fn-pattern-error.rs rename to tests/ui/extern/foreign-fn-pattern-error-10877.rs index 15a383175b97..9a047d4f34e7 100644 --- a/tests/ui/extern/foreign-fn-pattern-error.rs +++ b/tests/ui/extern/foreign-fn-pattern-error-10877.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10877 + struct Foo { x: isize, } diff --git a/tests/ui/issues/issue-10877.stderr b/tests/ui/extern/foreign-fn-pattern-error-10877.stderr similarity index 79% rename from tests/ui/issues/issue-10877.stderr rename to tests/ui/extern/foreign-fn-pattern-error-10877.stderr index bd3797cba558..cab7b6ab06be 100644 --- a/tests/ui/issues/issue-10877.stderr +++ b/tests/ui/extern/foreign-fn-pattern-error-10877.stderr @@ -1,23 +1,23 @@ error[E0130]: patterns aren't allowed in foreign function declarations - --> $DIR/issue-10877.rs:5:12 + --> $DIR/foreign-fn-pattern-error-10877.rs:7:12 | LL | fn foo(1: ()); | ^ pattern not allowed in foreign function error[E0130]: patterns aren't allowed in foreign function declarations - --> $DIR/issue-10877.rs:7:12 + --> $DIR/foreign-fn-pattern-error-10877.rs:9:12 | LL | fn bar((): isize); | ^^ pattern not allowed in foreign function error[E0130]: patterns aren't allowed in foreign function declarations - --> $DIR/issue-10877.rs:9:12 + --> $DIR/foreign-fn-pattern-error-10877.rs:11:12 | LL | fn baz(Foo { x }: isize); | ^^^^^^^^^ pattern not allowed in foreign function error[E0130]: patterns aren't allowed in foreign function declarations - --> $DIR/issue-10877.rs:11:12 + --> $DIR/foreign-fn-pattern-error-10877.rs:13:12 | LL | fn qux((x, y): ()); | ^^^^^^ pattern not allowed in foreign function diff --git a/tests/ui/fn/boxed-fn-pointer.rs b/tests/ui/fn/boxed-fn-pointer.rs deleted file mode 100644 index 2060d15b4c78..000000000000 --- a/tests/ui/fn/boxed-fn-pointer.rs +++ /dev/null @@ -1,7 +0,0 @@ -//@ run-pass - -pub fn main() { - fn f() { - } - let _: Box = Box::new(f as fn()); -} diff --git a/tests/ui/imports/empty-use-statements.rs b/tests/ui/imports/use-declaration-no-path-segment-prefix.rs similarity index 87% rename from tests/ui/imports/empty-use-statements.rs rename to tests/ui/imports/use-declaration-no-path-segment-prefix.rs index 31315dc7c93a..f7fbc084ebfe 100644 --- a/tests/ui/imports/empty-use-statements.rs +++ b/tests/ui/imports/use-declaration-no-path-segment-prefix.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10806 + //@ edition: 2015 //@ run-pass #![allow(unused_imports)] diff --git a/tests/ui/closures/fnonce-closure-call.rs b/tests/ui/inference/fnonce-closure-call.rs similarity index 57% rename from tests/ui/closures/fnonce-closure-call.rs rename to tests/ui/inference/fnonce-closure-call.rs index 68ac0bbe49fb..262a193609fc 100644 --- a/tests/ui/closures/fnonce-closure-call.rs +++ b/tests/ui/inference/fnonce-closure-call.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10718 + //@ run-pass fn f(p: F) { diff --git a/tests/ui/generics/generic-type-inference.rs b/tests/ui/inference/generic-type-inference-10436.rs similarity index 77% rename from tests/ui/generics/generic-type-inference.rs rename to tests/ui/inference/generic-type-inference-10436.rs index 672aa2464dc1..456a9b86c347 100644 --- a/tests/ui/generics/generic-type-inference.rs +++ b/tests/ui/inference/generic-type-inference-10436.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10436 + //@ run-pass fn works(x: T) -> Vec { vec![x] } diff --git a/tests/ui/array-slice-vec/array-pattern-matching.rs b/tests/ui/lifetimes/array-pattern-matching-10396.rs similarity index 71% rename from tests/ui/array-slice-vec/array-pattern-matching.rs rename to tests/ui/lifetimes/array-pattern-matching-10396.rs index 082216d557cf..5fc141bc4601 100644 --- a/tests/ui/array-slice-vec/array-pattern-matching.rs +++ b/tests/ui/lifetimes/array-pattern-matching-10396.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10396 + //@ check-pass #![allow(dead_code)] #[derive(Debug)] diff --git a/tests/ui/lifetimes/closure-lifetime-bounds-error.rs b/tests/ui/lifetimes/closure-lifetime-bounds-10291.rs similarity index 72% rename from tests/ui/lifetimes/closure-lifetime-bounds-error.rs rename to tests/ui/lifetimes/closure-lifetime-bounds-10291.rs index 31b9e1240461..42dc6c2cafad 100644 --- a/tests/ui/lifetimes/closure-lifetime-bounds-error.rs +++ b/tests/ui/lifetimes/closure-lifetime-bounds-10291.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10291 + fn test<'x>(x: &'x isize) { drop:: FnMut(&'z isize) -> &'z isize>>(Box::new(|z| { x diff --git a/tests/ui/issues/issue-10291.stderr b/tests/ui/lifetimes/closure-lifetime-bounds-10291.stderr similarity index 87% rename from tests/ui/issues/issue-10291.stderr rename to tests/ui/lifetimes/closure-lifetime-bounds-10291.stderr index 68ed9a0de5d5..34f8ca40871f 100644 --- a/tests/ui/issues/issue-10291.stderr +++ b/tests/ui/lifetimes/closure-lifetime-bounds-10291.stderr @@ -1,5 +1,5 @@ error: lifetime may not live long enough - --> $DIR/issue-10291.rs:3:9 + --> $DIR/closure-lifetime-bounds-10291.rs:5:9 | LL | fn test<'x>(x: &'x isize) { | -- lifetime `'x` defined here diff --git a/tests/ui/lifetimes/container-lifetime-error.rs b/tests/ui/lifetimes/container-lifetime-error-11374.rs similarity index 89% rename from tests/ui/lifetimes/container-lifetime-error.rs rename to tests/ui/lifetimes/container-lifetime-error-11374.rs index 60ee256c65a9..59d13d04e466 100644 --- a/tests/ui/lifetimes/container-lifetime-error.rs +++ b/tests/ui/lifetimes/container-lifetime-error-11374.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11374 + use std::io::{self, Read}; use std::vec; diff --git a/tests/ui/issues/issue-11374.stderr b/tests/ui/lifetimes/container-lifetime-error-11374.stderr similarity index 86% rename from tests/ui/issues/issue-11374.stderr rename to tests/ui/lifetimes/container-lifetime-error-11374.stderr index 3ae5cfc79f87..a29b5ae137c2 100644 --- a/tests/ui/issues/issue-11374.stderr +++ b/tests/ui/lifetimes/container-lifetime-error-11374.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-11374.rs:27:15 + --> $DIR/container-lifetime-error-11374.rs:29:15 | LL | c.read_to(v); | ------- ^ expected `&mut [u8]`, found `Vec<_>` @@ -9,7 +9,7 @@ LL | c.read_to(v); = note: expected mutable reference `&mut [u8]` found struct `Vec<_>` note: method defined here - --> $DIR/issue-11374.rs:13:12 + --> $DIR/container-lifetime-error-11374.rs:15:12 | LL | pub fn read_to(&mut self, vec: &mut [u8]) { | ^^^^^^^ -------------- @@ -19,7 +19,7 @@ LL | c.read_to(&mut v); | ++++ error[E0515]: cannot return value referencing local variable `r` - --> $DIR/issue-11374.rs:20:5 + --> $DIR/container-lifetime-error-11374.rs:22:5 | LL | Container::wrap(&mut r as &mut dyn io::Read) | ^^^^^^^^^^^^^^^^------^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/lifetimes/enum-lifetime-container.rs b/tests/ui/lifetimes/enum-lifetime-container-10228.rs similarity index 80% rename from tests/ui/lifetimes/enum-lifetime-container.rs rename to tests/ui/lifetimes/enum-lifetime-container-10228.rs index a59ccf926f9c..ebbefb619c61 100644 --- a/tests/ui/lifetimes/enum-lifetime-container.rs +++ b/tests/ui/lifetimes/enum-lifetime-container-10228.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10228 + //@ run-pass #![allow(dead_code)] #![allow(unused_variables)] diff --git a/tests/ui/lifetimes/keyword-self-lifetime-error.rs b/tests/ui/lifetimes/keyword-self-lifetime-error-10412.rs similarity index 91% rename from tests/ui/lifetimes/keyword-self-lifetime-error.rs rename to tests/ui/lifetimes/keyword-self-lifetime-error-10412.rs index 68ce0c2ea3cb..a5b303df2fd4 100644 --- a/tests/ui/lifetimes/keyword-self-lifetime-error.rs +++ b/tests/ui/lifetimes/keyword-self-lifetime-error-10412.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10412 + trait Serializable<'self, T> { //~^ ERROR lifetimes cannot use keyword names fn serialize(val: &'self T) -> Vec; //~ ERROR lifetimes cannot use keyword names diff --git a/tests/ui/issues/issue-10412.stderr b/tests/ui/lifetimes/keyword-self-lifetime-error-10412.stderr similarity index 76% rename from tests/ui/issues/issue-10412.stderr rename to tests/ui/lifetimes/keyword-self-lifetime-error-10412.stderr index c74ba1306cc4..236bdf1ac854 100644 --- a/tests/ui/issues/issue-10412.stderr +++ b/tests/ui/lifetimes/keyword-self-lifetime-error-10412.stderr @@ -1,47 +1,47 @@ error: lifetimes cannot use keyword names - --> $DIR/issue-10412.rs:1:20 + --> $DIR/keyword-self-lifetime-error-10412.rs:3:20 | LL | trait Serializable<'self, T> { | ^^^^^ error: lifetimes cannot use keyword names - --> $DIR/issue-10412.rs:3:24 + --> $DIR/keyword-self-lifetime-error-10412.rs:5:24 | LL | fn serialize(val: &'self T) -> Vec; | ^^^^^ error: lifetimes cannot use keyword names - --> $DIR/issue-10412.rs:4:37 + --> $DIR/keyword-self-lifetime-error-10412.rs:6:37 | LL | fn deserialize(repr: &[u8]) -> &'self T; | ^^^^^ error: lifetimes cannot use keyword names - --> $DIR/issue-10412.rs:7:6 + --> $DIR/keyword-self-lifetime-error-10412.rs:9:6 | LL | impl<'self> Serializable for &'self str { | ^^^^^ error: lifetimes cannot use keyword names - --> $DIR/issue-10412.rs:7:36 + --> $DIR/keyword-self-lifetime-error-10412.rs:9:36 | LL | impl<'self> Serializable for &'self str { | ^^^^^ error: lifetimes cannot use keyword names - --> $DIR/issue-10412.rs:11:24 + --> $DIR/keyword-self-lifetime-error-10412.rs:13:24 | LL | fn serialize(val: &'self str) -> Vec { | ^^^^^ error: lifetimes cannot use keyword names - --> $DIR/issue-10412.rs:15:37 + --> $DIR/keyword-self-lifetime-error-10412.rs:17:37 | LL | fn deserialize(repr: &[u8]) -> &'self str { | ^^^^^ error[E0726]: implicit elided lifetime not allowed here - --> $DIR/issue-10412.rs:7:13 + --> $DIR/keyword-self-lifetime-error-10412.rs:9:13 | LL | impl<'self> Serializable for &'self str { | ^^^^^^^^^^^^^^^^^ expected lifetime parameter diff --git a/tests/ui/lifetimes/trait-lifetime-bounds.rs b/tests/ui/lifetimes/tuple-struct-vs-struct-with-fields-borrowck-10902.rs similarity index 87% rename from tests/ui/lifetimes/trait-lifetime-bounds.rs rename to tests/ui/lifetimes/tuple-struct-vs-struct-with-fields-borrowck-10902.rs index 7cdf8808aa02..97c0d0bf554e 100644 --- a/tests/ui/lifetimes/trait-lifetime-bounds.rs +++ b/tests/ui/lifetimes/tuple-struct-vs-struct-with-fields-borrowck-10902.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10902 + //@ check-pass #![allow(dead_code)] diff --git a/tests/ui/lint/inner-doc-attributes.rs b/tests/ui/lint/missing-doc-unsugard-doc-attr-10853.rs similarity index 68% rename from tests/ui/lint/inner-doc-attributes.rs rename to tests/ui/lint/missing-doc-unsugard-doc-attr-10853.rs index 4c22393d9c0a..ec13ae997878 100644 --- a/tests/ui/lint/inner-doc-attributes.rs +++ b/tests/ui/lint/missing-doc-unsugard-doc-attr-10853.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10853 + //@ check-pass #![deny(missing_docs)] diff --git a/tests/ui/parser/comment-parsing.rs b/tests/ui/parser/doc-comment-parsing.rs similarity index 74% rename from tests/ui/parser/comment-parsing.rs rename to tests/ui/parser/doc-comment-parsing.rs index c6c6939bda53..00f6b0e09a89 100644 --- a/tests/ui/parser/comment-parsing.rs +++ b/tests/ui/parser/doc-comment-parsing.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10638 + //@ run-pass pub fn main() { diff --git a/tests/ui/pattern/ascii-lowercase-match.rs b/tests/ui/pattern/premature-match-scrutinee-temporary-drop-10683.rs similarity index 68% rename from tests/ui/pattern/ascii-lowercase-match.rs rename to tests/ui/pattern/premature-match-scrutinee-temporary-drop-10683.rs index 5657ec1864b2..a4dfa56117c2 100644 --- a/tests/ui/pattern/ascii-lowercase-match.rs +++ b/tests/ui/pattern/premature-match-scrutinee-temporary-drop-10683.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10683 + //@ run-pass static NAME: &'static str = "hello world"; diff --git a/tests/ui/privacy/private-struct-access-error.rs b/tests/ui/privacy/struct-field-and-impl-expose-10545.rs similarity index 59% rename from tests/ui/privacy/private-struct-access-error.rs rename to tests/ui/privacy/struct-field-and-impl-expose-10545.rs index acd071496190..8a8c8240c2d0 100644 --- a/tests/ui/privacy/private-struct-access-error.rs +++ b/tests/ui/privacy/struct-field-and-impl-expose-10545.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10545 + mod a { struct S; impl S { } diff --git a/tests/ui/issues/issue-10545.stderr b/tests/ui/privacy/struct-field-and-impl-expose-10545.stderr similarity index 73% rename from tests/ui/issues/issue-10545.stderr rename to tests/ui/privacy/struct-field-and-impl-expose-10545.stderr index 9aa042171748..ddf87d1d23ad 100644 --- a/tests/ui/issues/issue-10545.stderr +++ b/tests/ui/privacy/struct-field-and-impl-expose-10545.stderr @@ -1,11 +1,11 @@ error[E0603]: struct `S` is private - --> $DIR/issue-10545.rs:6:14 + --> $DIR/struct-field-and-impl-expose-10545.rs:8:14 | LL | fn foo(_: a::S) { | ^ private struct | note: the struct `S` is defined here - --> $DIR/issue-10545.rs:2:5 + --> $DIR/struct-field-and-impl-expose-10545.rs:4:5 | LL | struct S; | ^^^^^^^^^ diff --git a/tests/ui/structs/mutable-unit-struct-borrow.rs b/tests/ui/structs/mutable-unit-struct-borrow-11267.rs similarity index 82% rename from tests/ui/structs/mutable-unit-struct-borrow.rs rename to tests/ui/structs/mutable-unit-struct-borrow-11267.rs index 036ad1d54edc..d96c4a4e79bc 100644 --- a/tests/ui/structs/mutable-unit-struct-borrow.rs +++ b/tests/ui/structs/mutable-unit-struct-borrow-11267.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11267 + //@ run-pass // Tests that unary structs can be mutably borrowed. diff --git a/tests/ui/traits/blanket-impl-trait-object.rs b/tests/ui/traits/blanket-impl-trait-object-10456.rs similarity index 81% rename from tests/ui/traits/blanket-impl-trait-object.rs rename to tests/ui/traits/blanket-impl-trait-object-10456.rs index 51c740fd7293..f84214317746 100644 --- a/tests/ui/traits/blanket-impl-trait-object.rs +++ b/tests/ui/traits/blanket-impl-trait-object-10456.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10456 + //@ check-pass pub struct Foo; diff --git a/tests/ui/traits/missing-trait-method-error.rs b/tests/ui/traits/nested-mod-trait-method-lookup-leak-10465.rs similarity index 80% rename from tests/ui/traits/missing-trait-method-error.rs rename to tests/ui/traits/nested-mod-trait-method-lookup-leak-10465.rs index d899c3ffa912..d5a500900ff0 100644 --- a/tests/ui/traits/missing-trait-method-error.rs +++ b/tests/ui/traits/nested-mod-trait-method-lookup-leak-10465.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/10465 + pub mod a { pub trait A { fn foo(&self); diff --git a/tests/ui/issues/issue-10465.stderr b/tests/ui/traits/nested-mod-trait-method-lookup-leak-10465.stderr similarity index 88% rename from tests/ui/issues/issue-10465.stderr rename to tests/ui/traits/nested-mod-trait-method-lookup-leak-10465.stderr index 0f46ebe505aa..ffd8fd39250d 100644 --- a/tests/ui/issues/issue-10465.stderr +++ b/tests/ui/traits/nested-mod-trait-method-lookup-leak-10465.stderr @@ -1,5 +1,5 @@ error[E0599]: no method named `foo` found for reference `&B` in the current scope - --> $DIR/issue-10465.rs:17:15 + --> $DIR/nested-mod-trait-method-lookup-leak-10465.rs:19:15 | LL | b.foo(); | ^^^ method not found in `&B` diff --git a/tests/ui/type-alias/mismatched-rc-foo-types.rs b/tests/ui/type-alias/dummy-binder-102964.rs similarity index 75% rename from tests/ui/type-alias/mismatched-rc-foo-types.rs rename to tests/ui/type-alias/dummy-binder-102964.rs index 43ff23600766..6b6fa3ed5e33 100644 --- a/tests/ui/type-alias/mismatched-rc-foo-types.rs +++ b/tests/ui/type-alias/dummy-binder-102964.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/102964 + use std::rc::Rc; type Foo<'a, T> = &'a dyn Fn(&T); type RcFoo<'a, T> = Rc>; diff --git a/tests/ui/issues/issue-102964.stderr b/tests/ui/type-alias/dummy-binder-102964.stderr similarity index 93% rename from tests/ui/issues/issue-102964.stderr rename to tests/ui/type-alias/dummy-binder-102964.stderr index 0e2761f3f57b..fc32cabaf71a 100644 --- a/tests/ui/issues/issue-102964.stderr +++ b/tests/ui/type-alias/dummy-binder-102964.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-102964.rs:5:41 + --> $DIR/dummy-binder-102964.rs:7:41 | LL | fn bar_function(function: Foo) -> RcFoo { | ------------ ^^^^^^^^ expected `Rc<&dyn Fn(&T)>`, found `()` diff --git a/tests/ui/type-alias/static-method-type-alias.rs b/tests/ui/type-alias/static-method-type-alias-11047.rs similarity index 87% rename from tests/ui/type-alias/static-method-type-alias.rs rename to tests/ui/type-alias/static-method-type-alias-11047.rs index 6e1b2856afcd..efb336fb4f76 100644 --- a/tests/ui/type-alias/static-method-type-alias.rs +++ b/tests/ui/type-alias/static-method-type-alias-11047.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11047 + //@ run-pass // Test that static methods can be invoked on `type` aliases diff --git a/tests/ui/unsafe/raw-pointer-field-access-error.rs b/tests/ui/unsafe/raw-pointer-field-access-error.rs index 0c34554c12d1..04b45b2d3c68 100644 --- a/tests/ui/unsafe/raw-pointer-field-access-error.rs +++ b/tests/ui/unsafe/raw-pointer-field-access-error.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11004 + use std::mem; struct A { x: i32, y: f64 } diff --git a/tests/ui/issues/issue-11004.stderr b/tests/ui/unsafe/raw-pointer-field-access-error.stderr similarity index 85% rename from tests/ui/issues/issue-11004.stderr rename to tests/ui/unsafe/raw-pointer-field-access-error.stderr index 6d157c911302..e9a205a5fa64 100644 --- a/tests/ui/issues/issue-11004.stderr +++ b/tests/ui/unsafe/raw-pointer-field-access-error.stderr @@ -1,5 +1,5 @@ error[E0609]: no field `x` on type `*mut A` - --> $DIR/issue-11004.rs:7:21 + --> $DIR/raw-pointer-field-access-error.rs:9:21 | LL | let x : i32 = n.x; | ^ unknown field @@ -10,7 +10,7 @@ LL | let x : i32 = (*n).x; | ++ + error[E0609]: no field `y` on type `*mut A` - --> $DIR/issue-11004.rs:8:21 + --> $DIR/raw-pointer-field-access-error.rs:10:21 | LL | let y : f64 = n.y; | ^ unknown field From 5b8c61494f85a58759dad04194c8353de07d75e1 Mon Sep 17 00:00:00 2001 From: Alisa Sireneva Date: Fri, 25 Jul 2025 21:03:09 +0300 Subject: [PATCH 150/809] 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 151/809] 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 dad982633c935ae70fbc5f9b1c0f4f845606c551 Mon Sep 17 00:00:00 2001 From: beepster4096 <19316085+beepster4096@users.noreply.github.com> Date: Tue, 8 Jul 2025 15:01:54 -0700 Subject: [PATCH 152/809] fix box destructor generation --- .../rustc_mir_transform/src/elaborate_drop.rs | 53 ++--- ...al_drop_allocator.main.ElaborateDrops.diff | 186 ++++++++++++++++++ .../mir-opt/box_conditional_drop_allocator.rs | 38 ++++ .../ui/drop/box-conditional-drop-allocator.rs | 43 ++++ 4 files changed, 294 insertions(+), 26 deletions(-) create mode 100644 tests/mir-opt/box_conditional_drop_allocator.main.ElaborateDrops.diff create mode 100644 tests/mir-opt/box_conditional_drop_allocator.rs create mode 100644 tests/ui/drop/box-conditional-drop-allocator.rs diff --git a/compiler/rustc_mir_transform/src/elaborate_drop.rs b/compiler/rustc_mir_transform/src/elaborate_drop.rs index de96b1f255a6..7d4e9412564b 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drop.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drop.rs @@ -761,24 +761,36 @@ where let skip_contents = adt.is_union() || adt.is_manually_drop(); let contents_drop = if skip_contents { - (self.succ, self.unwind, self.dropline) + if adt.has_dtor(self.tcx()) { + // the top-level drop flag is usually cleared by open_drop_for_adt_contents + // types with destructors still need an empty drop ladder to clear it + + // currently no rust types can trigger this path in a context where drop flags exist + // however, a future box-like "DerefMove" trait would allow it + self.drop_ladder_bottom() + } else { + (self.succ, self.unwind, self.dropline) + } } else { self.open_drop_for_adt_contents(adt, args) }; - if adt.is_box() { - // we need to drop the inside of the box before running the destructor - let succ = self.destructor_call_block_sync((contents_drop.0, contents_drop.1)); - let unwind = contents_drop - .1 - .map(|unwind| self.destructor_call_block_sync((unwind, Unwind::InCleanup))); - let dropline = contents_drop - .2 - .map(|dropline| self.destructor_call_block_sync((dropline, contents_drop.1))); + if adt.has_dtor(self.tcx()) { + let destructor_block = if adt.is_box() { + // we need to drop the inside of the box before running the destructor + let succ = self.destructor_call_block_sync((contents_drop.0, contents_drop.1)); + let unwind = contents_drop + .1 + .map(|unwind| self.destructor_call_block_sync((unwind, Unwind::InCleanup))); + let dropline = contents_drop + .2 + .map(|dropline| self.destructor_call_block_sync((dropline, contents_drop.1))); + self.open_drop_for_box_contents(adt, args, succ, unwind, dropline) + } else { + self.destructor_call_block(contents_drop) + }; - self.open_drop_for_box_contents(adt, args, succ, unwind, dropline) - } else if adt.has_dtor(self.tcx()) { - self.destructor_call_block(contents_drop) + self.drop_flag_test_block(destructor_block, contents_drop.0, contents_drop.1) } else { contents_drop.0 } @@ -982,12 +994,7 @@ where unwind.is_cleanup(), ); - let destructor_block = self.elaborator.patch().new_block(result); - - let block_start = Location { block: destructor_block, statement_index: 0 }; - self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow); - - self.drop_flag_test_block(destructor_block, succ, unwind) + self.elaborator.patch().new_block(result) } fn destructor_call_block( @@ -1002,13 +1009,7 @@ where && !unwind.is_cleanup() && ty.is_async_drop(self.tcx(), self.elaborator.typing_env()) { - let destructor_block = - self.build_async_drop(self.place, ty, None, succ, unwind, dropline, true); - - let block_start = Location { block: destructor_block, statement_index: 0 }; - self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow); - - self.drop_flag_test_block(destructor_block, succ, unwind) + self.build_async_drop(self.place, ty, None, succ, unwind, dropline, true) } else { self.destructor_call_block_sync((succ, unwind)) } diff --git a/tests/mir-opt/box_conditional_drop_allocator.main.ElaborateDrops.diff b/tests/mir-opt/box_conditional_drop_allocator.main.ElaborateDrops.diff new file mode 100644 index 000000000000..6f6c239d7c83 --- /dev/null +++ b/tests/mir-opt/box_conditional_drop_allocator.main.ElaborateDrops.diff @@ -0,0 +1,186 @@ +- // MIR for `main` before ElaborateDrops ++ // MIR for `main` after ElaborateDrops + + fn main() -> () { + let mut _0: (); + let _1: std::boxed::Box; + let mut _2: HasDrop; + let mut _3: DropAllocator; + let mut _4: bool; + let _5: (); + let mut _6: HasDrop; + let _7: (); + let mut _8: std::boxed::Box; ++ let mut _9: bool; ++ let mut _10: &mut std::boxed::Box; ++ let mut _11: (); ++ let mut _12: &mut std::boxed::Box; ++ let mut _13: (); ++ let mut _14: *const HasDrop; ++ let mut _15: &mut std::boxed::Box; ++ let mut _16: (); ++ let mut _17: *const HasDrop; + scope 1 { + debug b => _1; + } + + bb0: { ++ _9 = const false; + StorageLive(_1); + StorageLive(_2); + _2 = HasDrop; + StorageLive(_3); + _3 = DropAllocator; + _1 = Box::::new_in(move _2, move _3) -> [return: bb1, unwind: bb11]; + } + + bb1: { ++ _9 = const true; + StorageDead(_3); + StorageDead(_2); + StorageLive(_4); + _4 = const true; + switchInt(move _4) -> [0: bb4, otherwise: bb2]; + } + + bb2: { + StorageLive(_5); + StorageLive(_6); + _6 = move (*_1); + _5 = std::mem::drop::(move _6) -> [return: bb3, unwind: bb9]; + } + + bb3: { + StorageDead(_6); + StorageDead(_5); + _0 = const (); + goto -> bb6; + } + + bb4: { + StorageLive(_7); + StorageLive(_8); ++ _9 = const false; + _8 = move _1; + _7 = std::mem::drop::>(move _8) -> [return: bb5, unwind: bb8]; + } + + bb5: { + StorageDead(_8); + StorageDead(_7); + _0 = const (); + goto -> bb6; + } + + bb6: { + StorageDead(_4); +- drop(_1) -> [return: bb7, unwind continue]; ++ goto -> bb23; + } + + bb7: { ++ _9 = const false; + StorageDead(_1); + return; + } + + bb8 (cleanup): { +- drop(_8) -> [return: bb10, unwind terminate(cleanup)]; ++ goto -> bb10; + } + + bb9 (cleanup): { +- drop(_6) -> [return: bb10, unwind terminate(cleanup)]; ++ goto -> bb10; + } + + bb10 (cleanup): { +- drop(_1) -> [return: bb13, unwind terminate(cleanup)]; ++ goto -> bb29; + } + + bb11 (cleanup): { +- drop(_3) -> [return: bb12, unwind terminate(cleanup)]; ++ goto -> bb12; + } + + bb12 (cleanup): { +- drop(_2) -> [return: bb13, unwind terminate(cleanup)]; ++ goto -> bb13; + } + + bb13 (cleanup): { + resume; ++ } ++ ++ bb14: { ++ _9 = const false; ++ goto -> bb7; ++ } ++ ++ bb15 (cleanup): { ++ drop((_1.1: DropAllocator)) -> [return: bb13, unwind terminate(cleanup)]; ++ } ++ ++ bb16 (cleanup): { ++ switchInt(copy _9) -> [0: bb13, otherwise: bb15]; ++ } ++ ++ bb17: { ++ drop((_1.1: DropAllocator)) -> [return: bb14, unwind: bb13]; ++ } ++ ++ bb18: { ++ switchInt(copy _9) -> [0: bb14, otherwise: bb17]; ++ } ++ ++ bb19: { ++ _10 = &mut _1; ++ _11 = as Drop>::drop(move _10) -> [return: bb18, unwind: bb16]; ++ } ++ ++ bb20 (cleanup): { ++ _12 = &mut _1; ++ _13 = as Drop>::drop(move _12) -> [return: bb16, unwind terminate(cleanup)]; ++ } ++ ++ bb21: { ++ goto -> bb19; ++ } ++ ++ bb22: { ++ _14 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const HasDrop (Transmute); ++ goto -> bb21; ++ } ++ ++ bb23: { ++ switchInt(copy _9) -> [0: bb18, otherwise: bb22]; ++ } ++ ++ bb24 (cleanup): { ++ drop((_1.1: DropAllocator)) -> [return: bb13, unwind terminate(cleanup)]; ++ } ++ ++ bb25 (cleanup): { ++ switchInt(copy _9) -> [0: bb13, otherwise: bb24]; ++ } ++ ++ bb26 (cleanup): { ++ _15 = &mut _1; ++ _16 = as Drop>::drop(move _15) -> [return: bb25, unwind terminate(cleanup)]; ++ } ++ ++ bb27 (cleanup): { ++ goto -> bb26; ++ } ++ ++ bb28 (cleanup): { ++ _17 = copy ((_1.0: std::ptr::Unique).0: std::ptr::NonNull) as *const HasDrop (Transmute); ++ goto -> bb27; ++ } ++ ++ bb29 (cleanup): { ++ switchInt(copy _9) -> [0: bb25, otherwise: bb28]; + } + } + diff --git a/tests/mir-opt/box_conditional_drop_allocator.rs b/tests/mir-opt/box_conditional_drop_allocator.rs new file mode 100644 index 000000000000..b8a9d5e5c4c2 --- /dev/null +++ b/tests/mir-opt/box_conditional_drop_allocator.rs @@ -0,0 +1,38 @@ +// skip-filecheck +//@ test-mir-pass: ElaborateDrops +#![feature(allocator_api)] + +// Regression test for #131082. +// Testing that the allocator of a Box is dropped in conditional drops + +use std::alloc::{AllocError, Allocator, Global, Layout}; +use std::ptr::NonNull; + +struct DropAllocator; + +unsafe impl Allocator for DropAllocator { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + Global.allocate(layout) + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + Global.deallocate(ptr, layout); + } +} +impl Drop for DropAllocator { + fn drop(&mut self) {} +} + +struct HasDrop; +impl Drop for HasDrop { + fn drop(&mut self) {} +} + +// EMIT_MIR box_conditional_drop_allocator.main.ElaborateDrops.diff +fn main() { + let b = Box::new_in(HasDrop, DropAllocator); + if true { + drop(*b); + } else { + drop(b); + } +} diff --git a/tests/ui/drop/box-conditional-drop-allocator.rs b/tests/ui/drop/box-conditional-drop-allocator.rs new file mode 100644 index 000000000000..8f78da16473e --- /dev/null +++ b/tests/ui/drop/box-conditional-drop-allocator.rs @@ -0,0 +1,43 @@ +//@ run-pass +#![feature(allocator_api)] + +// Regression test for #131082. +// Testing that the allocator of a Box is dropped in conditional drops + +use std::alloc::{AllocError, Allocator, Global, Layout}; +use std::cell::Cell; +use std::ptr::NonNull; + +struct DropCheckingAllocator<'a>(&'a Cell); + +unsafe impl Allocator for DropCheckingAllocator<'_> { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + Global.allocate(layout) + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + Global.deallocate(ptr, layout); + } +} +impl Drop for DropCheckingAllocator<'_> { + fn drop(&mut self) { + self.0.set(true); + } +} + +struct HasDrop; +impl Drop for HasDrop { + fn drop(&mut self) {} +} + +fn main() { + let dropped = Cell::new(false); + { + let b = Box::new_in(HasDrop, DropCheckingAllocator(&dropped)); + if true { + drop(*b); + } else { + drop(b); + } + } + assert!(dropped.get()); +} From c6d740d37ec21bc3429283f03037ee49e9dea44b Mon Sep 17 00:00:00 2001 From: beepster4096 <19316085+beepster4096@users.noreply.github.com> Date: Tue, 8 Jul 2025 15:57:15 -0700 Subject: [PATCH 153/809] async drop tests for box --- .../async-drop/async-drop-box-allocator.rs | 134 ++++++++++++++++++ .../async-drop-box-allocator.run.stdout | 6 + .../async-await/async-drop/async-drop-box.rs | 109 ++++++++++++++ .../async-drop/async-drop-box.run.stdout | 6 + 4 files changed, 255 insertions(+) create mode 100644 tests/ui/async-await/async-drop/async-drop-box-allocator.rs create mode 100644 tests/ui/async-await/async-drop/async-drop-box-allocator.run.stdout create mode 100644 tests/ui/async-await/async-drop/async-drop-box.rs create mode 100644 tests/ui/async-await/async-drop/async-drop-box.run.stdout diff --git a/tests/ui/async-await/async-drop/async-drop-box-allocator.rs b/tests/ui/async-await/async-drop/async-drop-box-allocator.rs new file mode 100644 index 000000000000..86ebf8a0ffd1 --- /dev/null +++ b/tests/ui/async-await/async-drop/async-drop-box-allocator.rs @@ -0,0 +1,134 @@ +//@ run-pass +//@ check-run-results +// struct `Foo` has both sync and async drop. +// It's used as the allocator of a `Box` which is conditionally moved out of. +// Sync version is called in sync context, async version is called in async function. + +#![feature(async_drop, allocator_api)] +#![allow(incomplete_features)] + +use std::mem::ManuallyDrop; + +//@ edition: 2021 + +#[inline(never)] +fn myprintln(msg: &str, my_resource_handle: usize) { + println!("{} : {}", msg, my_resource_handle); +} + +use std::{ + future::{Future, async_drop_in_place, AsyncDrop}, + pin::{pin, Pin}, + sync::{mpsc, Arc}, + task::{Context, Poll, Wake, Waker}, + alloc::{AllocError, Allocator, Global, Layout}, + ptr::NonNull, +}; + +struct Foo { + my_resource_handle: usize, +} + +impl Foo { + fn new(my_resource_handle: usize) -> Self { + let out = Foo { + my_resource_handle, + }; + myprintln("Foo::new()", my_resource_handle); + out + } +} + +impl Drop for Foo { + fn drop(&mut self) { + myprintln("Foo::drop()", self.my_resource_handle); + } +} + +impl AsyncDrop for Foo { + async fn drop(self: Pin<&mut Self>) { + myprintln("Foo::async drop()", self.my_resource_handle); + } +} + +unsafe impl Allocator for Foo { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + Global.allocate(layout) + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + Global.deallocate(ptr, layout); + } +} + +struct HasDrop; +impl Drop for HasDrop { + fn drop(&mut self) {} +} + +fn main() { + { + let b = Box::new_in(HasDrop, Foo::new(7)); + + if true { + let _x = *b; + } else { + let _y = b; + } + } + println!("Middle"); + block_on(bar(10)); + println!("Done") +} + +async fn bar(ident_base: usize) { + let b = Box::new_in(HasDrop, Foo::new(ident_base)); + + if true { + let _x = *b; + } else { + let _y = b; + } +} + +fn block_on(fut_unpin: F) -> F::Output +where + F: Future, +{ + let mut fut_pin = pin!(ManuallyDrop::new(fut_unpin)); + let mut fut: Pin<&mut F> = unsafe { + Pin::map_unchecked_mut(fut_pin.as_mut(), |x| &mut **x) + }; + let (waker, rx) = simple_waker(); + let mut context = Context::from_waker(&waker); + let rv = loop { + match fut.as_mut().poll(&mut context) { + Poll::Ready(out) => break out, + // expect wake in polls + Poll::Pending => rx.try_recv().unwrap(), + } + }; + let drop_fut_unpin = unsafe { async_drop_in_place(fut.get_unchecked_mut()) }; + let mut drop_fut: Pin<&mut _> = pin!(drop_fut_unpin); + loop { + match drop_fut.as_mut().poll(&mut context) { + Poll::Ready(()) => break, + Poll::Pending => rx.try_recv().unwrap(), + } + } + rv +} + +fn simple_waker() -> (Waker, mpsc::Receiver<()>) { + struct SimpleWaker { + tx: std::sync::mpsc::Sender<()>, + } + + impl Wake for SimpleWaker { + fn wake(self: Arc) { + self.tx.send(()).unwrap(); + } + } + + let (tx, rx) = mpsc::channel(); + (Waker::from(Arc::new(SimpleWaker { tx })), rx) +} diff --git a/tests/ui/async-await/async-drop/async-drop-box-allocator.run.stdout b/tests/ui/async-await/async-drop/async-drop-box-allocator.run.stdout new file mode 100644 index 000000000000..cb7d0b0fea59 --- /dev/null +++ b/tests/ui/async-await/async-drop/async-drop-box-allocator.run.stdout @@ -0,0 +1,6 @@ +Foo::new() : 7 +Foo::drop() : 7 +Middle +Foo::new() : 10 +Foo::async drop() : 10 +Done diff --git a/tests/ui/async-await/async-drop/async-drop-box.rs b/tests/ui/async-await/async-drop/async-drop-box.rs new file mode 100644 index 000000000000..0a6ed412863a --- /dev/null +++ b/tests/ui/async-await/async-drop/async-drop-box.rs @@ -0,0 +1,109 @@ +//@ run-pass +//@ check-run-results +// struct `Foo` has both sync and async drop. +// `Foo` is always inside `Box` +// Sync version is called in sync context, async version is called in async function. + +//@ known-bug: #143658 +// async version is never actually called + +#![feature(async_drop)] +#![allow(incomplete_features)] + +use std::mem::ManuallyDrop; + +//@ edition: 2021 + +#[inline(never)] +fn myprintln(msg: &str, my_resource_handle: usize) { + println!("{} : {}", msg, my_resource_handle); +} + +use std::{ + future::{Future, async_drop_in_place, AsyncDrop}, + pin::{pin, Pin}, + sync::{mpsc, Arc}, + task::{Context, Poll, Wake, Waker}, +}; + +struct Foo { + my_resource_handle: usize, +} + +impl Foo { + fn new(my_resource_handle: usize) -> Self { + let out = Foo { + my_resource_handle, + }; + myprintln("Foo::new()", my_resource_handle); + out + } +} + +impl Drop for Foo { + fn drop(&mut self) { + myprintln("Foo::drop()", self.my_resource_handle); + } +} + +impl AsyncDrop for Foo { + async fn drop(self: Pin<&mut Self>) { + myprintln("Foo::async drop()", self.my_resource_handle); + } +} + +fn main() { + { + let _ = Box::new(Foo::new(7)); + } + println!("Middle"); + block_on(bar(10)); + println!("Done") +} + +async fn bar(ident_base: usize) { + let _first = Box::new(Foo::new(ident_base)); +} + +fn block_on(fut_unpin: F) -> F::Output +where + F: Future, +{ + let mut fut_pin = pin!(ManuallyDrop::new(fut_unpin)); + let mut fut: Pin<&mut F> = unsafe { + Pin::map_unchecked_mut(fut_pin.as_mut(), |x| &mut **x) + }; + let (waker, rx) = simple_waker(); + let mut context = Context::from_waker(&waker); + let rv = loop { + match fut.as_mut().poll(&mut context) { + Poll::Ready(out) => break out, + // expect wake in polls + Poll::Pending => rx.try_recv().unwrap(), + } + }; + let drop_fut_unpin = unsafe { async_drop_in_place(fut.get_unchecked_mut()) }; + let mut drop_fut: Pin<&mut _> = pin!(drop_fut_unpin); + loop { + match drop_fut.as_mut().poll(&mut context) { + Poll::Ready(()) => break, + Poll::Pending => rx.try_recv().unwrap(), + } + } + rv +} + +fn simple_waker() -> (Waker, mpsc::Receiver<()>) { + struct SimpleWaker { + tx: std::sync::mpsc::Sender<()>, + } + + impl Wake for SimpleWaker { + fn wake(self: Arc) { + self.tx.send(()).unwrap(); + } + } + + let (tx, rx) = mpsc::channel(); + (Waker::from(Arc::new(SimpleWaker { tx })), rx) +} diff --git a/tests/ui/async-await/async-drop/async-drop-box.run.stdout b/tests/ui/async-await/async-drop/async-drop-box.run.stdout new file mode 100644 index 000000000000..a2dab2ba992b --- /dev/null +++ b/tests/ui/async-await/async-drop/async-drop-box.run.stdout @@ -0,0 +1,6 @@ +Foo::new() : 7 +Foo::drop() : 7 +Middle +Foo::new() : 10 +Foo::drop() : 10 +Done From ba55f20f4341ef5836c1f83beb0f2906e0600dc4 Mon Sep 17 00:00:00 2001 From: beepster4096 <19316085+beepster4096@users.noreply.github.com> Date: Fri, 18 Jul 2025 13:11:03 -0700 Subject: [PATCH 154/809] span_bug instead of handling currently impossible drop case --- .../rustc_mir_transform/src/elaborate_drop.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_mir_transform/src/elaborate_drop.rs b/compiler/rustc_mir_transform/src/elaborate_drop.rs index 7d4e9412564b..df4853c1dcbb 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drop.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drop.rs @@ -761,16 +761,17 @@ where let skip_contents = adt.is_union() || adt.is_manually_drop(); let contents_drop = if skip_contents { - if adt.has_dtor(self.tcx()) { + if adt.has_dtor(self.tcx()) && self.elaborator.get_drop_flag(self.path).is_some() { // the top-level drop flag is usually cleared by open_drop_for_adt_contents - // types with destructors still need an empty drop ladder to clear it + // types with destructors would still need an empty drop ladder to clear it - // currently no rust types can trigger this path in a context where drop flags exist - // however, a future box-like "DerefMove" trait would allow it - self.drop_ladder_bottom() - } else { - (self.succ, self.unwind, self.dropline) + // however, these types are only open dropped in `DropShimElaborator` + // which does not have drop flags + // a future box-like "DerefMove" trait would allow for this case to happen + span_bug!(self.source_info.span, "open dropping partially moved union"); } + + (self.succ, self.unwind, self.dropline) } else { self.open_drop_for_adt_contents(adt, args) }; From ccc2f78c3767e68005b0c873f31f79ef6680a3de Mon Sep 17 00:00:00 2001 From: beepster4096 <19316085+beepster4096@users.noreply.github.com> Date: Fri, 25 Jul 2025 13:42:45 -0700 Subject: [PATCH 155/809] add //@ needs-unwind to test --- tests/mir-opt/box_conditional_drop_allocator.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/mir-opt/box_conditional_drop_allocator.rs b/tests/mir-opt/box_conditional_drop_allocator.rs index b8a9d5e5c4c2..9471be14c877 100644 --- a/tests/mir-opt/box_conditional_drop_allocator.rs +++ b/tests/mir-opt/box_conditional_drop_allocator.rs @@ -1,5 +1,6 @@ // skip-filecheck //@ test-mir-pass: ElaborateDrops +//@ needs-unwind #![feature(allocator_api)] // Regression test for #131082. From 03986e640cc5a3ca70259484a6f271831c0bc241 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Fri, 25 Jul 2025 22:51:39 +0200 Subject: [PATCH 156/809] 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 e497abcfc23880d7a5ade1a423b910f023eed8a4 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Thu, 23 Jan 2025 20:14:53 +0000 Subject: [PATCH 157/809] Add stabilization template and revise docs --- .../src/implementing_new_features.md | 19 ++++++ .../src/stabilization_guide.md | 62 ++++++++----------- .../src/stabilization_report_template.md | 54 ++++++++++++++++ 3 files changed, 99 insertions(+), 36 deletions(-) create mode 100644 src/doc/rustc-dev-guide/src/stabilization_report_template.md 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 5d0e875cbc18..10d404c6aace 100644 --- a/src/doc/rustc-dev-guide/src/implementing_new_features.md +++ b/src/doc/rustc-dev-guide/src/implementing_new_features.md @@ -206,3 +206,22 @@ tests/ui/feature-gates/ --bless`. [here]: ./stabilization_guide.md [tracking issue]: #tracking-issues [add-feature-gate]: ./feature-gates.md#adding-a-feature-gate + +## Call for testing + +Once the implementation is complete, the feature will be available to nightly users, but not yet part of stable Rust. This is a good time to write a blog post on [one of the Rust blogs](https://github.com/rust-lang/blog.rust-lang.org/) and issue a call for testing (here are two example [blog](https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing.html) [posts](https://blog.rust-lang.org/2024/09/05/impl-trait-capture-rules.html) to give you the idea). The post should highlight how the feature works, what areas you'd like people to play with, and how they can supply feedback. + +## Affiliated work + +Once the feature is supported by rustc, there is other associated work that needs to be done to give users a complete experience: + +* Extending rustfmt to format any new syntax; +* Extending rust-analyzer; +* Documenting the feature in the Rust reference; +* ... + +## Stabilization + +The final step in the feature lifecycle is [stabilization][stab], which is when the feature becomes available to all Rust users. At this point, backwards incompatible changes are no longer permitted (modulo soundness bugs and inference changes; see the lang team's [defined semver policies](https://rust-lang.github.io/rfcs/1122-language-semver.html) for full details). To learn more about stabilization, see the [stabilization guide][stab]. + +[stab]: ./stabilization_guide.md diff --git a/src/doc/rustc-dev-guide/src/stabilization_guide.md b/src/doc/rustc-dev-guide/src/stabilization_guide.md index f875c68745f6..213280ccea86 100644 --- a/src/doc/rustc-dev-guide/src/stabilization_guide.md +++ b/src/doc/rustc-dev-guide/src/stabilization_guide.md @@ -43,44 +43,14 @@ has completed. Meanwhile, we can proceed to the next step. ## Write a stabilization report -Find the tracking issue of the feature, and create a short -stabilization report. Essentially this would be a brief summary -of the feature plus some links to test cases showing it works -as expected, along with a list of edge cases that came up -and were considered. This is a minimal "due diligence" that -we do before stabilizing. +Author a stabilization report using the [template found in this repository][srt]. +Stabilization reports summarize the work that has been done since the RFC. +The [template][srt] includes a series of questions that aim to surface interconnections between this feature and the various Rust teams (lang, types, etc) and also to identify items that are commonly overlooked. -The report should contain: +[srt]: ./stabilization_report_template.md -- A summary, showing examples (e.g. code snippets) what is - enabled by this feature. -- Links to test cases in our test suite regarding this feature - and describe the feature's behavior on encountering edge cases. -- Links to the documentations (the PRs we have made in the - previous steps). -- Any other relevant information. -- The resolutions of any unresolved questions if the stabilization - is for an RFC. - -Examples of stabilization reports can be found in -[rust-lang/rust#44494][report1] and [rust-lang/rust#28237][report2] (these links -will bring you directly to the comment containing the stabilization report). - -[report1]: https://github.com/rust-lang/rust/issues/44494#issuecomment-360191474 -[report2]: https://github.com/rust-lang/rust/issues/28237#issuecomment-363374130 - -## FCP - -If any member of the team responsible for tracking this -feature agrees with stabilizing this feature, they will -start the FCP (final-comment-period) process by commenting - -```text -@rfcbot fcp merge -``` - -The rest of the team members will review the proposal. If the final -decision is to stabilize, we proceed to do the actual code modification. +The stabilization report is typically posted as the main comment on the stabilization PR (see the next section). +If you'd like to develop the stabilization report incrementally, we recommend adding it to ## Stabilization PR @@ -194,3 +164,23 @@ if something { /* XXX */ } [Rust by Example]: https://github.com/rust-lang/rust-by-example [`Unstable Book`]: https://doc.rust-lang.org/unstable-book/index.html [`src/doc/unstable-book`]: https://github.com/rust-lang/rust/tree/master/src/doc/unstable-book + +## Lang team nomination + +When you feel the PR is ready for consideration by the lang team, you can [nominate the PR](https://lang-team.rust-lang.org/how_to/nominate.html) to get it on the list for discussion in the next meeting. You should also cc the other interacting teams to review the report: + +* `@rust-lang/types`, to look for type system interactions +* `@rust-lang/compiler`, to vouch for implementation quality +* `@rust-lang/opsem`, but only if this feature interacts with unsafe code and can create undefined behavior +* `@rust-lang/libs-api`, but only if there are additions to the standard library + +## FCP proposed on the PR + +Finally, some member of the team responsible for tracking this feature agrees with stabilizing this feature, will +start the FCP (final-comment-period) process by commenting + +```text +@rfcbot fcp merge +``` + +The rest of the team members will review the proposal. If the final decision is to stabilize, the PR will be reviewed by the compiler team like any other PR. diff --git a/src/doc/rustc-dev-guide/src/stabilization_report_template.md b/src/doc/rustc-dev-guide/src/stabilization_report_template.md new file mode 100644 index 000000000000..28d5ce0cc8fd --- /dev/null +++ b/src/doc/rustc-dev-guide/src/stabilization_report_template.md @@ -0,0 +1,54 @@ +# Stabilization report template + +> **What is this?** This is a template to use for [stabilization reports](./stabilization_guide.md). It consists of a series of questions that aim to provide the information most commonly needed and to help reviewers be more likely to identify potential problems up front. Not all parts of the template will apply to all stabilizations. Feel free to put N/A if a question doesn't seem to apply to your case. + +## General design + +### What is the RFC for this feature and what changes have occurred to the user-facing design since the RFC was finalized? + +### What behavior are we committing to that has been controversial? Summarize the major arguments pro/con. + +### Are there extensions to this feature that remain unstable? How do we know that we are not accidentally committing to those? + +## Has a call-for-testing period been conducted? If so, what feedback was received? + +## Implementation quality + +### Summarize the major parts of the implementation and provide links into the code (or to PRs) + +An example for async closures: https://rustc-dev-guide.rust-lang.org/coroutine-closures.html + +### Summarize existing test coverage of this feature + +- What does the test coverage landscape for this feature look like? + - (Positive/negative) Behavioral tests? + - (Positive/negative) Interface tests? (e.g. compiler cli interface) + - Maybe link to test folders or individual tests (ui/codegen/assembly/run-make tests, etc.) + - Are there any (intentional/unintentional) gaps in test coverage? + +### What outstanding bugs in the issue tracker involve this feature? Are they stabilization-blocking? + +### Summarize contributors to the feature by name for recognition and assuredness that people involved in the feature agree with stabilization + +### What FIXMEs are still in the code for that feature and why is it ok to leave them there? + +### Which tools need to be adjusted to support this feature. Has this work been done? + +*Consider rustdoc, clippy, rust-analyzer, rustfmt, rustup, docs.rs.* + +## Type system and execution rules + +### What compilation-time checks are done that are needed to prevent undefined behavior? + +(Be sure to link to tests demonstrating that these tests are being done.) + +### Can users use this feature to introduce undefined behavior? (Describe.) + +### What updates are needed to the reference/specification? (link to PRs when they exist) + +## Common interactions + +### Does this feature introduce new expressions and can they produce temporaries? What are the lifetimes of those temporaries? + +### What other unstable features may be exposed by this feature? + From 857f46eb393896e0240969f6c6b204ac015d60a9 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Thu, 23 Jan 2025 16:48:34 -0500 Subject: [PATCH 158/809] Address review feedback Co-authored-by: lcnr Co-authored-by: Ralf Jung Co-authored-by: waffle --- src/doc/rustc-dev-guide/src/implementing_new_features.md | 2 +- src/doc/rustc-dev-guide/src/stabilization_guide.md | 2 +- .../rustc-dev-guide/src/stabilization_report_template.md | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) 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 10d404c6aace..0b153d98ab52 100644 --- a/src/doc/rustc-dev-guide/src/implementing_new_features.md +++ b/src/doc/rustc-dev-guide/src/implementing_new_features.md @@ -209,7 +209,7 @@ tests/ui/feature-gates/ --bless`. ## Call for testing -Once the implementation is complete, the feature will be available to nightly users, but not yet part of stable Rust. This is a good time to write a blog post on [one of the Rust blogs](https://github.com/rust-lang/blog.rust-lang.org/) and issue a call for testing (here are two example [blog](https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing.html) [posts](https://blog.rust-lang.org/2024/09/05/impl-trait-capture-rules.html) to give you the idea). The post should highlight how the feature works, what areas you'd like people to play with, and how they can supply feedback. +Once the implementation is complete, the feature will be available to nightly users, but not yet part of stable Rust. This is a good time to write a blog post on [one of the Rust blogs](https://github.com/rust-lang/blog.rust-lang.org/) and issue a call for testing (here are three [example](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html) [blog](https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing.html) [posts](https://blog.rust-lang.org/2024/09/05/impl-trait-capture-rules.html) to give you the idea). The post should highlight how the feature works, what areas you'd like people to play with, and how they can supply feedback. ## Affiliated work diff --git a/src/doc/rustc-dev-guide/src/stabilization_guide.md b/src/doc/rustc-dev-guide/src/stabilization_guide.md index 213280ccea86..f993bcac8b81 100644 --- a/src/doc/rustc-dev-guide/src/stabilization_guide.md +++ b/src/doc/rustc-dev-guide/src/stabilization_guide.md @@ -52,7 +52,7 @@ The [template][srt] includes a series of questions that aim to surface interconn The stabilization report is typically posted as the main comment on the stabilization PR (see the next section). If you'd like to develop the stabilization report incrementally, we recommend adding it to -## Stabilization PR +## Stabilization PR for a language feature *This is for stabilizing language features. If you are stabilizing a library feature, see [the stabilization chapter of the std dev guide][std-guide-stabilization] instead.* diff --git a/src/doc/rustc-dev-guide/src/stabilization_report_template.md b/src/doc/rustc-dev-guide/src/stabilization_report_template.md index 28d5ce0cc8fd..b5d3fc68bfb5 100644 --- a/src/doc/rustc-dev-guide/src/stabilization_report_template.md +++ b/src/doc/rustc-dev-guide/src/stabilization_report_template.md @@ -28,10 +28,10 @@ An example for async closures: https://rustc-dev-guide.rust-lang.org/coroutine-c ### What outstanding bugs in the issue tracker involve this feature? Are they stabilization-blocking? -### Summarize contributors to the feature by name for recognition and assuredness that people involved in the feature agree with stabilization - ### What FIXMEs are still in the code for that feature and why is it ok to leave them there? +### Summarize contributors to the feature by name for recognition and assuredness that people involved in the feature agree with stabilization + ### Which tools need to be adjusted to support this feature. Has this work been done? *Consider rustdoc, clippy, rust-analyzer, rustfmt, rustup, docs.rs.* @@ -42,7 +42,7 @@ An example for async closures: https://rustc-dev-guide.rust-lang.org/coroutine-c (Be sure to link to tests demonstrating that these tests are being done.) -### Can users use this feature to introduce undefined behavior? (Describe.) +### Can users use this feature to introduce undefined behavior, or use this feature to break the abstraction of Rust and expose the underlying assembly-level implementation? (Describe.) ### What updates are needed to the reference/specification? (link to PRs when they exist) From 7547b15acb98d96a656c0cb17174b50097919afc Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 19 Jun 2025 17:33:15 +0800 Subject: [PATCH 159/809] Address review feedback - Address Call for Testing review feedback - Address Affiliated work review feedback - Drop "stabilization is easy" part - Fix broken feature gate examples - Elaborate on stabilization report summarization aspects - Recommend waiting a bit for team nominations - Make Stabilization Template markdown copy friendly - Register stabilization report template - Drop unfinished sentence - Clarify stabilization report template is for language features - Add test coverage elaboration - Add UB checks / opt question - Amend test coverage explanation - Mention OSS nightly users --- src/doc/rustc-dev-guide/src/SUMMARY.md | 3 +- .../src/implementing_new_features.md | 32 +++++- .../src/stabilization_guide.md | 33 +++--- .../src/stabilization_report_template.md | 107 +++++++++++++----- 4 files changed, 124 insertions(+), 51 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/SUMMARY.md b/src/doc/rustc-dev-guide/src/SUMMARY.md index 651e2925ad50..e3c0d50fcc73 100644 --- a/src/doc/rustc-dev-guide/src/SUMMARY.md +++ b/src/doc/rustc-dev-guide/src/SUMMARY.md @@ -53,7 +53,8 @@ - [Walkthrough: a typical contribution](./walkthrough.md) - [Implementing new language features](./implementing_new_features.md) - [Stability attributes](./stability.md) -- [Stabilizing Features](./stabilization_guide.md) +- [Stabilizing language features](./stabilization_guide.md) + - [Stabilization report template](./stabilization_report_template.md) - [Feature Gates](./feature-gates.md) - [Coding conventions](./conventions.md) - [Procedures for breaking changes](./bug-fix-procedure.md) 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 0b153d98ab52..0f02e1e9f0c7 100644 --- a/src/doc/rustc-dev-guide/src/implementing_new_features.md +++ b/src/doc/rustc-dev-guide/src/implementing_new_features.md @@ -209,19 +209,39 @@ tests/ui/feature-gates/ --bless`. ## Call for testing -Once the implementation is complete, the feature will be available to nightly users, but not yet part of stable Rust. This is a good time to write a blog post on [one of the Rust blogs](https://github.com/rust-lang/blog.rust-lang.org/) and issue a call for testing (here are three [example](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html) [blog](https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing.html) [posts](https://blog.rust-lang.org/2024/09/05/impl-trait-capture-rules.html) to give you the idea). The post should highlight how the feature works, what areas you'd like people to play with, and how they can supply feedback. +Once the implementation is complete, the feature will be available to nightly users, but not yet part of stable Rust. This is a good time to write a blog post on [the main Rust blog][rust-blog] and issue a **Call for Testing**. + +Some example Call for Testing blog posts: + +1. [The push for GATs stabilization](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push/) +2. [Changes to `impl Trait` in Rust 2024](https://blog.rust-lang.org/2024/09/05/impl-trait-capture-rules.html) +3. [Async Closures MVP: Call for Testing!](https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing/) + +Alternatively, [*This Week in Rust*][twir] has a [call-for-testing section][twir-cft]. Example: + +- [Call for testing on boolean literals as cfg predicates](https://github.com/rust-lang/rust/issues/131204#issuecomment-2569314526). + +Which option to choose might depend on how significant the language change is, though note that [*This Week in Rust*][twir]'s Call for Testing section might be less visible than a dedicated post on the main Rust blog. ## Affiliated work -Once the feature is supported by rustc, there is other associated work that needs to be done to give users a complete experience: +Once the feature is supported by rustc, there is other associated work that needs to be done to give users a complete experience. Think of it as the *language toolchain* developer experience, which doesn't only comprise of the language or compiler in isolation. -* Extending rustfmt to format any new syntax; -* Extending rust-analyzer; -* Documenting the feature in the Rust reference; -* ... +- Documenting the language feature in the [Rust Reference][reference]. +- (If applicable) Extending [`rustfmt`] to format any new syntax. +- (If applicable) Extending [`rust-analyzer`]. This can depend on the nature of the language feature, as some features don't need to be blocked on *full* support. + - A blocking concern is when a language feature degrades the user experience simply by existing before its support is implemented in [`rust-analyzer`]. + - Example blocking concern: new syntax that [`rust-analyzer`] can't parse -> bogus diagnostics, type inference changes -> bogus diagnostics. ## Stabilization The final step in the feature lifecycle is [stabilization][stab], which is when the feature becomes available to all Rust users. At this point, backwards incompatible changes are no longer permitted (modulo soundness bugs and inference changes; see the lang team's [defined semver policies](https://rust-lang.github.io/rfcs/1122-language-semver.html) for full details). To learn more about stabilization, see the [stabilization guide][stab]. + [stab]: ./stabilization_guide.md +[rust-blog]: https://github.com/rust-lang/blog.rust-lang.org/ +[twir]: https://github.com/rust-lang/this-week-in-rust +[twir-cft]: https://this-week-in-rust.org/blog/2025/01/22/this-week-in-rust-583/#calls-for-testing +[`rustfmt`]: https://github.com/rust-lang/rustfmt +[`rust-analyzer`]: https://github.com/rust-lang/rust-analyzer +[reference]: https://github.com/rust-lang/reference diff --git a/src/doc/rustc-dev-guide/src/stabilization_guide.md b/src/doc/rustc-dev-guide/src/stabilization_guide.md index f993bcac8b81..98a6fcf8caf6 100644 --- a/src/doc/rustc-dev-guide/src/stabilization_guide.md +++ b/src/doc/rustc-dev-guide/src/stabilization_guide.md @@ -44,24 +44,24 @@ has completed. Meanwhile, we can proceed to the next step. ## Write a stabilization report Author a stabilization report using the [template found in this repository][srt]. -Stabilization reports summarize the work that has been done since the RFC. -The [template][srt] includes a series of questions that aim to surface interconnections between this feature and the various Rust teams (lang, types, etc) and also to identify items that are commonly overlooked. + +Stabilization reports summarize: + +- The main design decisions and deviations since the RFC was accepted, particularly decisions that were FCP'd or otherwise accepted by the language team. + - Quite often, the final stabilized language feature can have significant design deviations from the original RFC text. +- The work that has been done since the RFC was accepted, acknowledging the main contributors that helped drive the language feature forward. + +The [*Stabilization Template*][srt] includes a series of questions that aim to surface interconnections between this feature and the various Rust teams (lang, types, etc) and also to identify items that are commonly overlooked. [srt]: ./stabilization_report_template.md The stabilization report is typically posted as the main comment on the stabilization PR (see the next section). -If you'd like to develop the stabilization report incrementally, we recommend adding it to ## Stabilization PR for a language feature *This is for stabilizing language features. If you are stabilizing a library feature, see [the stabilization chapter of the std dev guide][std-guide-stabilization] instead.* -Once we have decided to stabilize a feature, we need to have -a PR that actually makes that stabilization happen. These kinds -of PRs are a great way to get involved in Rust, as they take -you on a little tour through the source code. - Here is a general guide to how to stabilize a feature -- every feature is different, of course, so some features may require steps beyond what this guide talks about. @@ -121,8 +121,7 @@ same `compiler/rustc_ast_passes/src/feature_gate.rs`. For example, you might see code like this: ```rust,ignore -gate_feature_post!(&self, pub_restricted, span, - "`pub(restricted)` syntax is experimental"); +gate_all!(pub_restricted, "`pub(restricted)` syntax is experimental"); ``` This `gate_feature_post!` macro prints an error if the @@ -132,7 +131,7 @@ now that `#[pub_restricted]` is stable. For more subtle features, you may find code like this: ```rust,ignore -if self.tcx.sess.features.borrow().pub_restricted { /* XXX */ } +if self.tcx.features().async_fn_in_dyn_trait() { /* XXX */ } ``` This `pub_restricted` field (obviously named after the feature) @@ -165,14 +164,16 @@ if something { /* XXX */ } [`Unstable Book`]: https://doc.rust-lang.org/unstable-book/index.html [`src/doc/unstable-book`]: https://github.com/rust-lang/rust/tree/master/src/doc/unstable-book -## Lang team nomination +## Team nominations -When you feel the PR is ready for consideration by the lang team, you can [nominate the PR](https://lang-team.rust-lang.org/how_to/nominate.html) to get it on the list for discussion in the next meeting. You should also cc the other interacting teams to review the report: +After the stabilization PR is opened with the stabilization report, wait a bit for potential immediate comments. When such immediate comments "simmer down" and you feel the PR is ready for consideration by the lang team, you can [nominate the PR](https://lang-team.rust-lang.org/how_to/nominate.html) to get it on the list for discussion in the next meeting. You should also cc the other interacting teams when applicable to review the language feature being stabilized and the stabilization report: * `@rust-lang/types`, to look for type system interactions -* `@rust-lang/compiler`, to vouch for implementation quality -* `@rust-lang/opsem`, but only if this feature interacts with unsafe code and can create undefined behavior -* `@rust-lang/libs-api`, but only if there are additions to the standard library +* `@rust-lang/compiler`, to review implementation robustness +* `@rust-lang/opsem`, if this feature interacts with unsafe code and can create undefined behavior +* `@rust-lang/libs-api`, if there are additions to the standard library that affects standard library API or their guarantees + +If you are not an organization member, you can simply ask your assigned reviewer to cc the relevant teams on your behalf. ## FCP proposed on the PR diff --git a/src/doc/rustc-dev-guide/src/stabilization_report_template.md b/src/doc/rustc-dev-guide/src/stabilization_report_template.md index b5d3fc68bfb5..90437ee7adca 100644 --- a/src/doc/rustc-dev-guide/src/stabilization_report_template.md +++ b/src/doc/rustc-dev-guide/src/stabilization_report_template.md @@ -1,54 +1,105 @@ # Stabilization report template -> **What is this?** This is a template to use for [stabilization reports](./stabilization_guide.md). It consists of a series of questions that aim to provide the information most commonly needed and to help reviewers be more likely to identify potential problems up front. Not all parts of the template will apply to all stabilizations. Feel free to put N/A if a question doesn't seem to apply to your case. +> **What is this?** +> +> This is a template to use for [stabilization reports](./stabilization_guide.md) of **language features**. It consists of a series of questions that aim to provide the information most commonly needed and to help reviewers be more likely to identify potential problems up front. Not all parts of the template will apply to all stabilizations. Feel free to put N/A if a question doesn't seem to apply to your case. +> +> You can copy the following template after the separator and edit it as Markdown, replacing the *TODO* placeholders with answers. -## General design +--- -### What is the RFC for this feature and what changes have occurred to the user-facing design since the RFC was finalized? +> ## General design -### What behavior are we committing to that has been controversial? Summarize the major arguments pro/con. +> ### What is the RFC for this feature and what changes have occurred to the user-facing design since the RFC was finalized? -### Are there extensions to this feature that remain unstable? How do we know that we are not accidentally committing to those? +*TODO* -## Has a call-for-testing period been conducted? If so, what feedback was received? +> ### What behavior are we committing to that has been controversial? Summarize the major arguments pro/con. -## Implementation quality +*TODO* -### Summarize the major parts of the implementation and provide links into the code (or to PRs) +> ### Are there extensions to this feature that remain unstable? How do we know that we are not accidentally committing to those? -An example for async closures: https://rustc-dev-guide.rust-lang.org/coroutine-closures.html +*TODO* -### Summarize existing test coverage of this feature +> ## Has a Call for Testing period been conducted? If so, what feedback was received? +> +> Does any OSS nightly users use this feature? For instance, a useful indication might be "search for `#![feature(FEATURE_NAME)]` and had `N` results". -- What does the test coverage landscape for this feature look like? - - (Positive/negative) Behavioral tests? - - (Positive/negative) Interface tests? (e.g. compiler cli interface) - - Maybe link to test folders or individual tests (ui/codegen/assembly/run-make tests, etc.) - - Are there any (intentional/unintentional) gaps in test coverage? +*TODO* -### What outstanding bugs in the issue tracker involve this feature? Are they stabilization-blocking? +> ## Implementation quality -### What FIXMEs are still in the code for that feature and why is it ok to leave them there? +*TODO* -### Summarize contributors to the feature by name for recognition and assuredness that people involved in the feature agree with stabilization +> ### Summarize the major parts of the implementation and provide links into the code (or to PRs) +> +> An example for async closures: . -### Which tools need to be adjusted to support this feature. Has this work been done? +*TODO* -*Consider rustdoc, clippy, rust-analyzer, rustfmt, rustup, docs.rs.* +> ### Summarize existing test coverage of this feature +> +> Consider what the "edges" of this feature are. We're particularly interested in seeing tests that assure us about exactly what nearby things we're not stabilizing. +> +> Within each test, include a comment at the top describing the purpose of the test and what set of invariants it intends to demonstrate. This is a great help to those reviewing the tests at stabilization time. +> +> - What does the test coverage landscape for this feature look like? +> - Tests for compiler errors when you use the feature wrongly or make mistakes? +> - Tests for the feature itself: +> - Limits of the feature (so failing compilation) +> - Exercises of edge cases of the feature +> - Tests that checks the feature works as expected (where applicable, `//@ run-pass`). +> - Are there any intentional gaps in test coverage? +> +> Link to test folders or individual tests (ui/codegen/assembly/run-make tests, etc.). -## Type system and execution rules +*TODO* -### What compilation-time checks are done that are needed to prevent undefined behavior? +> ### What outstanding bugs in the issue tracker involve this feature? Are they stabilization-blocking? -(Be sure to link to tests demonstrating that these tests are being done.) +*TODO* -### Can users use this feature to introduce undefined behavior, or use this feature to break the abstraction of Rust and expose the underlying assembly-level implementation? (Describe.) +> ### What FIXMEs are still in the code for that feature and why is it ok to leave them there? -### What updates are needed to the reference/specification? (link to PRs when they exist) +*TODO* -## Common interactions +> ### Summarize contributors to the feature by name for recognition and assuredness that people involved in the feature agree with stabilization -### Does this feature introduce new expressions and can they produce temporaries? What are the lifetimes of those temporaries? +*TODO* -### What other unstable features may be exposed by this feature? +> ### Which tools need to be adjusted to support this feature. Has this work been done? +> +> Consider rustdoc, clippy, rust-analyzer, rustfmt, rustup, docs.rs. +*TODO* + +> ## Type system and execution rules + +> ### What compilation-time checks are done that are needed to prevent undefined behavior? +> +> (Be sure to link to tests demonstrating that these tests are being done.) + +*TODO* + +> ### Does the feature's implementation need checks to prevent UB or is it sound by default and needs opt in in places to perform the dangerous/unsafe operations? If it is not sound by default, what is the rationale? + +*TODO* + +> ### Can users use this feature to introduce undefined behavior, or use this feature to break the abstraction of Rust and expose the underlying assembly-level implementation? (Describe.) + +*TODO* + +> ### What updates are needed to the reference/specification? (link to PRs when they exist) + +*TODO* + +> ## Common interactions + +> ### Does this feature introduce new expressions and can they produce temporaries? What are the lifetimes of those temporaries? + +*TODO* + +> ### What other unstable features may be exposed by this feature? + +*TODO* From 64604ad1daf897ea206da257eec88e5e851946ac Mon Sep 17 00:00:00 2001 From: Travis Cross Date: Wed, 23 Jul 2025 06:16:25 +0000 Subject: [PATCH 160/809] Revise content on lang feature processes Let's revise both the new content in this PR as well as the remaining text in the relevant chapters so as to better describe our current processes related to language features and their stabilizations. For the new stabilization report template, based on reviewing its early use and well as reviewing earlier stabilization reports, we've revised it editorially and added questions designed to capture additional details to which we commonly want people to speak. --- .../src/implementing_new_features.md | 191 ++++-------- .../src/stabilization_guide.md | 141 ++++----- .../src/stabilization_report_template.md | 282 ++++++++++++++---- 3 files changed, 342 insertions(+), 272 deletions(-) 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 0f02e1e9f0c7..76cf2386c826 100644 --- a/src/doc/rustc-dev-guide/src/implementing_new_features.md +++ b/src/doc/rustc-dev-guide/src/implementing_new_features.md @@ -2,145 +2,91 @@ -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. +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].** +**NOTE: This section is for *language* features, not *library* features, which use [a different process].** -See also [the Rust Language Design Team's procedures][lang-propose] for -proposing changes to the language. +See also [the Rust Language Design Team's procedures][lang-propose] for proposing changes to the language. [a different process]: ./stability.md [lang-propose]: https://lang-team.rust-lang.org/how_to/propose.html ## The @rfcbot FCP process -When the change is small and uncontroversial, then it can be done -with just writing a PR and getting an r+ from someone who knows that -part of the code. However, if the change is potentially controversial, -it would be a bad idea to push it without consensus from the rest -of the team (both in the "distributed system" sense to make sure -you don't break anything you don't know about, and in the social -sense to avoid PR fights). +When the change is small, uncontroversial, non-breaking, and does not affect the stable language in any user-observable ways or add any new unstable features, then it can be done with just writing a PR and getting an r+ from someone who knows that part of the code. However, if not, more must be done. Even for compiler-internal work, it would be a bad idea to push a controversial change without consensus from the rest of the team (both in the "distributed system" sense to make sure you don't break anything you don't know about, and in the social sense to avoid PR fights). -If such a change seems to be too small to require a full formal RFC process -(e.g., a small standard library addition, a big refactoring of the code, a -"technically-breaking" change, or a "big bugfix" that basically amounts to a -small feature) but is still too controversial or big to get by with a single r+, -you can propose a final comment period (FCP). Or, if you're not on the relevant -team (and thus don't have @rfcbot permissions), ask someone who is to start one; -unless they have a concern themselves, they should. +For changes that need the consensus of a team, we us the process of proposing a final comment period (FCP). If you're not on the relevant team (and thus don't have @rfcbot permissions), ask someone who is to start one; unless they have a concern themselves, they should. -Again, the FCP process is only needed if you need consensus – if you -don't think anyone would have a problem with your change, it's OK to -get by with only an r+. For example, it is OK to add or modify -unstable command-line flags or attributes without an FCP for -compiler development or standard library use, as long as you don't -expect them to be in wide use in the nightly ecosystem. -Some teams have lighter weight processes that they use in scenarios -like this; for example, the compiler team recommends -filing a Major Change Proposal ([MCP][mcp]) as a lightweight way to -garner support and feedback without requiring full consensus. +The FCP process is only needed if you need consensus – if no processes require consensus for your change and you don't think anyone would have a problem with it, it's OK to rely on only an r+. For example, it is OK to add or modify unstable command-line flags or attributes in the reserved compiler-internal `rustc_` namespace without an FCP for compiler development or standard library use, as long as you don't expect them to be in wide use in the nightly ecosystem. Some teams have lighter weight processes that they use in scenarios like this; for example, the compiler team recommends filing a Major Change Proposal ([MCP][mcp]) as a lightweight way to garner support and feedback without requiring full consensus. [mcp]: https://forge.rust-lang.org/compiler/proposals-and-stabilization.html#how-do-i-submit-an-mcp -You don't need to have the implementation fully ready for r+ to propose an FCP, -but it is generally a good idea to have at least a proof -of concept so that people can see what you are talking about. +You don't need to have the implementation fully ready for r+ to propose an FCP, but it is generally a good idea to have at least a proof of concept so that people can see what you are talking about. -When an FCP is proposed, it requires all members of the team to sign off the -FCP. After they all do so, there's a 10-day-long "final comment period" (hence -the name) where everybody can comment, and if no concerns are raised, the -PR/issue gets FCP approval. +When an FCP is proposed, it requires all members of the team to sign off on the FCP. After they all do so, there's a 10-day-long "final comment period" (hence the name) where everybody can comment, and if no concerns are raised, the PR/issue gets FCP approval. ## The logistics of writing features -There are a few "logistic" hoops you might need to go through in -order to implement a feature in a working way. +There are a few "logistical" hoops you might need to go through in order to implement a feature in a working way. ### Warning Cycles -In some cases, a feature or bugfix might break some existing programs -in some edge cases. In that case, you might want to do a crater run -to assess the impact and possibly add a future-compatibility lint, -similar to those used for -[edition-gated lints](diagnostics.md#edition-gated-lints). +In some cases, a feature or bugfix might break some existing programs in some edge cases. In that case, you'll want to do a crater run to assess the impact and possibly add a future-compatibility lint, similar to those used for [edition-gated lints](diagnostics.md#edition-gated-lints). ### Stability -We [value the stability of Rust]. Code that works and runs on stable -should (mostly) not break. Because of that, we don't want to release -a feature to the world with only team consensus and code review - -we want to gain real-world experience on using that feature on nightly, -and we might want to change the feature based on that experience. +We [value the stability of Rust]. Code that works and runs on stable should (mostly) not break. Because of that, we don't want to release a feature to the world with only team consensus and code review - we want to gain real-world experience on using that feature on nightly, and we might want to change the feature based on that experience. -To allow for that, we must make sure users don't accidentally depend -on that new feature - otherwise, especially if experimentation takes -time or is delayed and the feature takes the trains to stable, -it would end up de facto stable and we'll not be able to make changes -in it without breaking people's code. +To allow for that, we must make sure users don't accidentally depend on that new feature - otherwise, especially if experimentation takes time or is delayed and the feature takes the trains to stable, it would end up de facto stable and we'll not be able to make changes in it without breaking people's code. -The way we do that is that we make sure all new features are feature -gated - they can't be used without enabling a feature gate -(`#[feature(foo)]`), which can't be done in a stable/beta compiler. -See the [stability in code] section for the technical details. +The way we do that is that we make sure all new features are feature gated - they can't be used without enabling a feature gate (`#[feature(foo)]`), which can't be done in a stable/beta compiler. See the [stability in code] section for the technical details. -Eventually, after we gain enough experience using the feature, -make the necessary changes, and are satisfied, we expose it to -the world using the stabilization process described [here]. -Until then, the feature is not set in stone: every part of the -feature can be changed, or the feature might be completely -rewritten or removed. Features are not supposed to gain tenure -by being unstable and unchanged for a year. +Eventually, after we gain enough experience using the feature, make the necessary changes, and are satisfied, we expose it to the world using the stabilization process described [here]. Until then, the feature is not set in stone: every part of the feature can be changed, or the feature might be completely rewritten or removed. Features do not gain tenure by being unstable and unchanged for long periods of time. ### Tracking Issues -To keep track of the status of an unstable feature, the -experience we get while using it on nightly, and of the -concerns that block its stabilization, every feature-gate -needs a tracking issue. General discussions about the feature should be done on the tracking issue. +To keep track of the status of an unstable feature, the experience we get while using it on +nightly, and of the concerns that block its stabilization, every feature-gate needs a tracking +issue. When creating issues and PRs related to the feature, reference this tracking issue, and when there are updates about the feature's progress, post those to the tracking issue. -For features that have an RFC, you should use the RFC's -tracking issue for the feature. +For features that are part of an accept RFC or approved lang experiment, use the tracking issue for that. -For other features, you'll have to make a tracking issue -for that feature. The issue title should be "Tracking issue -for YOUR FEATURE". Use the ["Tracking Issue" issue template][template]. +For other features, create a tracking issue for that feature. The issue title should be "Tracking issue for YOUR FEATURE". Use the ["Tracking Issue" issue template][template]. [template]: https://github.com/rust-lang/rust/issues/new?template=tracking_issue.md +### Lang experiments + +To land in the compiler, features that have user-visible effects on the language (even unstable ones) must either be part of an accepted RFC or an approved [lang experiment]. + +To propose a new lang experiment, open an issue in `rust-lang/rust` that describes the motivation and the intended solution. If it's accepted, this issue will become the tracking issue for the experiment, so use the tracking issue [template] while also including these other details. Nominate the issue for the lang team and CC `@rust-lang/lang` and `@rust-lang/lang-advisors`. When the experiment is approved, the tracking issue will be marked as `B-experimental`. + +Feature flags related to a lang experiment must be marked as `incomplete` until an RFC is accepted for the feature. + +[lang experiment]: https://lang-team.rust-lang.org/how_to/experiment.html + ## Stability in code -The below steps needs to be followed in order to implement -a new unstable feature: +The below steps needs to be followed in order to implement a new unstable feature: -1. Open a [tracking issue] - - if you have an RFC, you can use the tracking issue for the RFC. +1. Open or identify the [tracking issue]. For features that are part of an accept RFC or approved lang experiment, use the tracking issue for that. - The tracking issue should be labeled with at least `C-tracking-issue`. - For a language feature, a label `F-feature_name` should be added as well. + Label the tracking issue with `C-tracking-issue` and the relevant `F-feature_name` label (adding that label if needed). -1. Pick a name for the feature gate (for RFCs, use the name - in the RFC). +1. Pick a name for the feature gate (for RFCs, use the name in the RFC). 1. Add the feature name to `rustc_span/src/symbol.rs` in the `Symbols {...}` block. Note that this block must be in alphabetical order. -1. Add a feature gate declaration to `rustc_feature/src/unstable.rs` in the unstable - `declare_features` block. +1. Add a feature gate declaration to `rustc_feature/src/unstable.rs` in the unstable `declare_features` block. ```rust ignore /// description of feature (unstable, $feature_name, "CURRENT_RUSTC_VERSION", Some($tracking_issue_number)) ``` - If you haven't yet - opened a tracking issue (e.g. because you want initial feedback on whether the feature is likely - to be accepted), you can temporarily use `None` - but make sure to update it before the PR is - merged! + If you haven't yet opened a tracking issue (e.g. because you want initial feedback on whether the feature is likely to be accepted), you can temporarily use `None` - but make sure to update it before the PR is merged! For example: @@ -149,9 +95,7 @@ a new unstable feature: (unstable, non_ascii_idents, "CURRENT_RUSTC_VERSION", Some(55467), None), ``` - Features can be marked as incomplete, and trigger the warn-by-default [`incomplete_features` - lint] - by setting their type to `incomplete`: + Features can be marked as incomplete, and trigger the warn-by-default [`incomplete_features` lint] by setting their type to `incomplete`: [`incomplete_features` lint]: https://doc.rust-lang.org/rustc/lints/listing/warn-by-default.html#incomplete-features @@ -160,42 +104,27 @@ a new unstable feature: (incomplete, deref_patterns, "CURRENT_RUSTC_VERSION", Some(87121), None), ``` - To avoid [semantic merge conflicts], please use `CURRENT_RUSTC_VERSION` instead of `1.70` or - another explicit version number. + Feature flags related to a lang experiment must be marked as `incomplete` until an RFC is accepted for the feature. + + To avoid [semantic merge conflicts], use `CURRENT_RUSTC_VERSION` instead of `1.70` or another explicit version number. [semantic merge conflicts]: https://bors.tech/essay/2017/02/02/pitch/ -1. Prevent usage of the new feature unless the feature gate is set. - You can check it in most places in the compiler using the - expression `tcx.features().$feature_name()` +1. Prevent usage of the new feature unless the feature gate is set. You can check it in most places in the compiler using the expression `tcx.features().$feature_name()`. - If the feature gate is not set, you should either maintain - the pre-feature behavior or raise an error, depending on - what makes sense. Errors should generally use [`rustc_session::parse::feature_err`]. - For an example of adding an error, see [#81015]. + If the feature gate is not set, you should either maintain the pre-feature behavior or raise an error, depending on what makes sense. Errors should generally use [`rustc_session::parse::feature_err`]. For an example of adding an error, see [#81015]. - For features introducing new syntax, pre-expansion gating should be used instead. - During parsing, when the new syntax is parsed, the symbol must be inserted to the - current crate's [`GatedSpans`] via `self.sess.gated_span.gate(sym::my_feature, span)`. - - After being inserted to the gated spans, the span must be checked in the - [`rustc_ast_passes::feature_gate::check_crate`] function, which actually denies - features. Exactly how it is gated depends on the exact type of feature, but most - likely will use the `gate_all!()` macro. + For features introducing new syntax, pre-expansion gating should be used instead. During parsing, when the new syntax is parsed, the symbol must be inserted to the current crate's [`GatedSpans`] via `self.sess.gated_span.gate(sym::my_feature, span)`. -1. Add a test to ensure the feature cannot be used without - a feature gate, by creating `tests/ui/feature-gates/feature-gate-$feature_name.rs`. - You can generate the corresponding `.stderr` file by running `./x test -tests/ui/feature-gates/ --bless`. + After being inserted to the gated spans, the span must be checked in the [`rustc_ast_passes::feature_gate::check_crate`] function, which actually denies features. Exactly how it is gated depends on the exact type of feature, but most likely will use the `gate_all!()` macro. -1. Add a section to the unstable book, in - `src/doc/unstable-book/src/language-features/$feature_name.md`. +1. Add a test to ensure the feature cannot be used without a feature gate, by creating `tests/ui/feature-gates/feature-gate-$feature_name.rs`. You can generate the corresponding `.stderr` file by running `./x test tests/ui/feature-gates/ --bless`. -1. Write a lot of tests for the new feature, preferably in `tests/ui/$feature_name/`. - PRs without tests will not be accepted! +1. Add a section to the unstable book, in `src/doc/unstable-book/src/language-features/$feature_name.md`. -1. Get your PR reviewed and land it. You have now successfully - implemented a feature in Rust! +1. Write a lot of tests for the new feature, preferably in `tests/ui/$feature_name/`. PRs without tests will not be accepted! + +1. Get your PR reviewed and land it. You have now successfully implemented a feature in Rust! [`GatedSpans`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/parse/struct.GatedSpans.html [#81015]: https://github.com/rust-lang/rust/pull/81015 @@ -209,33 +138,33 @@ tests/ui/feature-gates/ --bless`. ## Call for testing -Once the implementation is complete, the feature will be available to nightly users, but not yet part of stable Rust. This is a good time to write a blog post on [the main Rust blog][rust-blog] and issue a **Call for Testing**. +Once the implementation is complete, the feature will be available to nightly users but not yet part of stable Rust. This is a good time to write a blog post on [the main Rust blog][rust-blog] and issue a "call for testing". -Some example Call for Testing blog posts: +Some earlier such blog posts include: 1. [The push for GATs stabilization](https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push/) 2. [Changes to `impl Trait` in Rust 2024](https://blog.rust-lang.org/2024/09/05/impl-trait-capture-rules.html) 3. [Async Closures MVP: Call for Testing!](https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing/) -Alternatively, [*This Week in Rust*][twir] has a [call-for-testing section][twir-cft]. Example: +Alternatively, [*This Week in Rust*][twir] has a [section][twir-cft] for this. One example of this having been used is: -- [Call for testing on boolean literals as cfg predicates](https://github.com/rust-lang/rust/issues/131204#issuecomment-2569314526). +- [Call for testing on boolean literals as cfg predicates](https://github.com/rust-lang/rust/issues/131204#issuecomment-2569314526) -Which option to choose might depend on how significant the language change is, though note that [*This Week in Rust*][twir]'s Call for Testing section might be less visible than a dedicated post on the main Rust blog. +Which option to choose might depend on how significant the language change is, though note that the [*This Week in Rust*][twir] section might be less visible than a dedicated post on the main Rust blog. -## Affiliated work +## Polishing -Once the feature is supported by rustc, there is other associated work that needs to be done to give users a complete experience. Think of it as the *language toolchain* developer experience, which doesn't only comprise of the language or compiler in isolation. +Giving users a polished experience means more than just implementing the feature in rustc. We need to think about all of the tools and resources that we ship. This work includes: - Documenting the language feature in the [Rust Reference][reference]. -- (If applicable) Extending [`rustfmt`] to format any new syntax. -- (If applicable) Extending [`rust-analyzer`]. This can depend on the nature of the language feature, as some features don't need to be blocked on *full* support. - - A blocking concern is when a language feature degrades the user experience simply by existing before its support is implemented in [`rust-analyzer`]. - - Example blocking concern: new syntax that [`rust-analyzer`] can't parse -> bogus diagnostics, type inference changes -> bogus diagnostics. +- Extending [`rustfmt`] to format any new syntax (if applicable). +- Extending [`rust-analyzer`] (if applicable). The extent of this work can depend on the nature of the language feature, as some features don't need to be blocked on *full* support. + - When a language feature degrades the user experience simply by existing before support is implemented in [`rust-analyzer`], that may lead the lang team to raise a blocking concern. + - Examples of such might include new syntax that [`rust-analyzer`] can't parse or type inference changes it doesn't understand when those lead to bogus diagnostics. ## Stabilization -The final step in the feature lifecycle is [stabilization][stab], which is when the feature becomes available to all Rust users. At this point, backwards incompatible changes are no longer permitted (modulo soundness bugs and inference changes; see the lang team's [defined semver policies](https://rust-lang.github.io/rfcs/1122-language-semver.html) for full details). To learn more about stabilization, see the [stabilization guide][stab]. +The final step in the feature lifecycle is [stabilization][stab], which is when the feature becomes available to all Rust users. At this point, backward incompatible changes are generally no longer permitted (see the lang team's [defined semver policies](https://rust-lang.github.io/rfcs/1122-language-semver.html) for details). To learn more about stabilization, see the [stabilization guide][stab]. [stab]: ./stabilization_guide.md diff --git a/src/doc/rustc-dev-guide/src/stabilization_guide.md b/src/doc/rustc-dev-guide/src/stabilization_guide.md index 98a6fcf8caf6..f155272e5a2c 100644 --- a/src/doc/rustc-dev-guide/src/stabilization_guide.md +++ b/src/doc/rustc-dev-guide/src/stabilization_guide.md @@ -1,90 +1,66 @@ # Request for stabilization -**NOTE**: this page is about stabilizing *language* features. -For stabilizing *library* features, see [Stabilizing a library feature]. +**NOTE**: This page is about stabilizing *language* features. For stabilizing *library* features, see [Stabilizing a library feature]. [Stabilizing a library feature]: ./stability.md#stabilizing-a-library-feature -Once an unstable feature has been well-tested with no outstanding -concern, anyone may push for its stabilization. It involves the -following steps: +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. + +[lang experiment]: https://lang-team.rust-lang.org/how_to/experiment.html + ## Documentation PRs -If any documentation for this feature exists, it should be -in the [`Unstable Book`], located at [`src/doc/unstable-book`]. -If it exists, the page for the feature gate should be removed. +The feature might be documented in the [`Unstable Book`], located at [`src/doc/unstable-book`]. Remove the page for the feature gate if it exists. Integrate any useful parts of that documentation in other places. -If there was documentation there, integrating it into the -existing documentation is needed. +Places that may need updated documentation include: -If there wasn't documentation there, it needs to be added. +- [The Reference]: This must be updated, in full detail, and a member of the lang-docs team must review and approve the PR before the stabilization can be merged. +- [The Book]: This is updated as needed. If you're not sure, please open an issue on this repository and it can be discussed. +- Standard library documentation: This is updated as needed. Language features often don't need this, but if it's a feature that changes how idiomatic examples are written, such as when `?` was added to the language, updating these in the library documentation is important. Review also the keyword documentation and ABI documentation in the standard library, as these sometimes needs updates for language changes. +- [Rust by Example]: This is updated as needed. -Places that may need updated documentation: - -- [The Reference]: This must be updated, in full detail. -- [The Book]: This may or may not need updating, depends. - If you're not sure, please open an issue on this repository - and it can be discussed. -- standard library documentation: As needed. Language features - often don't need this, but if it's a feature that changes - how good examples are written, such as when `?` was added - to the language, updating examples is important. -- [Rust by Example]: As needed. - -Prepare PRs to update documentation involving this new feature -for repositories mentioned above. Maintainers of these repositories -will keep these PRs open until the whole stabilization process -has completed. Meanwhile, we can proceed to the next step. +Prepare PRs to update documentation involving this new feature for the repositories mentioned above. Maintainers of these repositories will keep these PRs open until the whole stabilization process has completed. Meanwhile, we can proceed to the next step. ## Write a stabilization report Author a stabilization report using the [template found in this repository][srt]. -Stabilization reports summarize: +The stabilization reports summarizes: -- The main design decisions and deviations since the RFC was accepted, particularly decisions that were FCP'd or otherwise accepted by the language team. - - Quite often, the final stabilized language feature can have significant design deviations from the original RFC text. +- The main design decisions and deviations since the RFC was accepted, including both decisions that were FCP'd or otherwise accepted by the language team as well as those being presented to the lang team for the first time. + - Often, the final stabilized language feature has significant design deviations from the original RFC. That's OK, but these deviations must be highlighted and explained carefully. - The work that has been done since the RFC was accepted, acknowledging the main contributors that helped drive the language feature forward. -The [*Stabilization Template*][srt] includes a series of questions that aim to surface interconnections between this feature and the various Rust teams (lang, types, etc) and also to identify items that are commonly overlooked. +The [*Stabilization Template*][srt] includes a series of questions that aim to surface connections between this feature and lang's subteams (e.g. types, opsem, lang-docs, etc.) and to identify items that are commonly overlooked. [srt]: ./stabilization_report_template.md The stabilization report is typically posted as the main comment on the stabilization PR (see the next section). -## Stabilization PR for a language feature +## Stabilization PR -*This is for stabilizing language features. If you are stabilizing a library -feature, see [the stabilization chapter of the std dev guide][std-guide-stabilization] instead.* +Every feature is different, and some may require steps beyond what this guide discusses. -Here is a general guide to how to stabilize a feature -- -every feature is different, of course, so some features may -require steps beyond what this guide talks about. - -Note: Before we stabilize any feature, it's the rule that it -should appear in the documentation. +Before the stabilization will be considered by the lang team, there must be a complete PR to the Reference describing the feature, and before the stabilization PR will be merged, this PR must have been reviewed and approved by the lang-docs team. ### Updating the feature-gate listing -There is a central listing of unstable feature-gates in -[`compiler/rustc_feature/src/unstable.rs`]. Search for the `declare_features!` -macro. There should be an entry for the feature you are aiming -to stabilize, something like (this example is taken from -[rust-lang/rust#32409]: +There is a central listing of unstable feature-gates in [`compiler/rustc_feature/src/unstable.rs`]. Search for the `declare_features!` macro. There should be an entry for the feature you are aiming to stabilize, something like (this example is taken from [rust-lang/rust#32409]: ```rust,ignore // pub(restricted) visibilities (RFC 1422) (unstable, pub_restricted, "CURRENT_RUSTC_VERSION", Some(32409)), ``` -The above line should be moved to [`compiler/rustc_feature/src/accepted.rs`]. -Entries in the `declare_features!` call are sorted, so find the correct place. -When it is done, it should look like: +The above line should be moved to [`compiler/rustc_feature/src/accepted.rs`]. Entries in the `declare_features!` call are sorted, so find the correct place. When it is done, it should look like: ```rust,ignore // pub(restricted) visibilities (RFC 1422) @@ -92,41 +68,23 @@ When it is done, it should look like: // note that we changed this ``` -(Even though you will encounter version numbers in the file of past changes, -you should not put the rustc version you expect your stabilization to happen in, -but instead `CURRENT_RUSTC_VERSION`) +(Even though you will encounter version numbers in the file of past changes, you should not put the rustc version you expect your stabilization to happen in, but instead use `CURRENT_RUSTC_VERSION`.) ### Removing existing uses of the feature-gate -Next search for the feature string (in this case, `pub_restricted`) -in the codebase to find where it appears. Change uses of -`#![feature(XXX)]` from the `std` and any rustc crates (this includes test folders -under `library/` and `compiler/` but not the toplevel `tests/` one) to be -`#![cfg_attr(bootstrap, feature(XXX))]`. This includes the feature-gate -only for stage0, which is built using the current beta (this is -needed because the feature is still unstable in the current beta). +Next, search for the feature string (in this case, `pub_restricted`) in the codebase to find where it appears. Change uses of `#![feature(XXX)]` from the `std` and any rustc crates (this includes test folders under `library/` and `compiler/` but not the toplevel `tests/` one) to be `#![cfg_attr(bootstrap, feature(XXX))]`. This includes the feature-gate only for stage0, which is built using the current beta (this is needed because the feature is still unstable in the current beta). -Also, remove those strings from any tests (e.g. under `tests/`). If there are tests -specifically targeting the feature-gate (i.e., testing that the -feature-gate is required to use the feature, but nothing else), -simply remove the test. +Also, remove those strings from any tests (e.g. under `tests/`). If there are tests specifically targeting the feature-gate (i.e., testing that the feature-gate is required to use the feature, but nothing else), simply remove the test. ### Do not require the feature-gate to use the feature -Most importantly, remove the code which flags an error if the -feature-gate is not present (since the feature is now considered -stable). If the feature can be detected because it employs some -new syntax, then a common place for that code to be is in the -same `compiler/rustc_ast_passes/src/feature_gate.rs`. -For example, you might see code like this: +Most importantly, remove the code which flags an error if the feature-gate is not present (since the feature is now considered stable). If the feature can be detected because it employs some new syntax, then a common place for that code to be is in `compiler/rustc_ast_passes/src/feature_gate.rs`. For example, you might see code like this: ```rust,ignore gate_all!(pub_restricted, "`pub(restricted)` syntax is experimental"); ``` -This `gate_feature_post!` macro prints an error if the -`pub_restricted` feature is not enabled. It is not needed -now that `#[pub_restricted]` is stable. +This `gate_feature_post!` macro prints an error if the `pub_restricted` feature is not enabled. It is not needed now that `#[pub_restricted]` is stable. For more subtle features, you may find code like this: @@ -134,11 +92,7 @@ For more subtle features, you may find code like this: if self.tcx.features().async_fn_in_dyn_trait() { /* XXX */ } ``` -This `pub_restricted` field (obviously named after the feature) -would ordinarily be false if the feature flag is not present -and true if it is. So transform the code to assume that the field -is true. In this case, that would mean removing the `if` and -leaving just the `/* XXX */`. +This `pub_restricted` field (named after the feature) would ordinarily be false if the feature flag is not present and true if it is. So transform the code to assume that the field is true. In this case, that would mean removing the `if` and leaving just the `/* XXX */`. ```rust,ignore if self.tcx.sess.features.borrow().pub_restricted { /* XXX */ } @@ -166,22 +120,37 @@ if something { /* XXX */ } ## Team nominations -After the stabilization PR is opened with the stabilization report, wait a bit for potential immediate comments. When such immediate comments "simmer down" and you feel the PR is ready for consideration by the lang team, you can [nominate the PR](https://lang-team.rust-lang.org/how_to/nominate.html) to get it on the list for discussion in the next meeting. You should also cc the other interacting teams when applicable to review the language feature being stabilized and the stabilization report: +When opening the stabilization PR, CC the lang team and its advisors (`@rust-lang/lang @rust-lang/lang-advisors`) and any other teams to whom the feature is relevant, e.g.: -* `@rust-lang/types`, to look for type system interactions -* `@rust-lang/compiler`, to review implementation robustness -* `@rust-lang/opsem`, if this feature interacts with unsafe code and can create undefined behavior -* `@rust-lang/libs-api`, if there are additions to the standard library that affects standard library API or their guarantees +- `@rust-lang/types`, for type system interactions. +- `@rust-lang/opsem`, for interactions with unsafe code. +- `@rust-lang/compiler`, for implementation robustness. +- `@rust-lang/libs-api`, for changes to the standard library API or its guarantees. +- `@rust-lang/lang-docs`, for questions about how this should be documented in the Reference. -If you are not an organization member, you can simply ask your assigned reviewer to cc the relevant teams on your behalf. +After the stabilization PR is opened with the stabilization report, wait a bit for any immediate comments. When such comments "simmer down" and you feel the PR is ready for consideration by the lang team, [nominate the PR](https://lang-team.rust-lang.org/how_to/nominate.html) to get it on the agenda for consideration in an upcoming lang meeting. -## FCP proposed on the PR +If you are not a `rust-lang` organization member, you can ask your assigned reviewer to CC the relevant teams on your behalf. -Finally, some member of the team responsible for tracking this feature agrees with stabilizing this feature, will -start the FCP (final-comment-period) process by commenting +## Propose FCP on the PR + +After the lang team and other relevant teams review the stabilization, and after you have answered any questions they may have had, a member of one of the teams may propose to accept the stabilization by commenting: ```text @rfcbot fcp merge ``` -The rest of the team members will review the proposal. If the final decision is to stabilize, the PR will be reviewed by the compiler team like any other PR. +Once enough team members have reviewed, the PR will move into a "final comment period" (FCP). If no new concerns are raised, this period will complete and the PR can be merged after implementation review in the usual way. + +## Reviewing and merging stabilizations + +On a stabilization, before giving it the `r+`, ensure that the PR: + +- Matches what the team proposed for stabilization and what is documented in the Reference PR. +- Includes any changes the team decided to request along the way in order to resolve or avoid concerns. +- Is otherwise exactly what is described in the stabilization report and in any relevant RFCs or prior lang FCPs. +- Does not expose on stable behaviors other than those specified, accepted for stabilization, and documented in the Reference. +- Has sufficient tests to convincingly demonstrate these things. +- Is accompanied by a PR to the Reference than has been reviewed and approved by a member of lang-docs. + +In particular, when reviewing the PR, keep an eye out for any user-visible details that the lang team failed to consider and specify. If you find one, describe it and nominate the PR for the lang team. diff --git a/src/doc/rustc-dev-guide/src/stabilization_report_template.md b/src/doc/rustc-dev-guide/src/stabilization_report_template.md index 90437ee7adca..793f7d7e45cf 100644 --- a/src/doc/rustc-dev-guide/src/stabilization_report_template.md +++ b/src/doc/rustc-dev-guide/src/stabilization_report_template.md @@ -1,105 +1,277 @@ # Stabilization report template -> **What is this?** -> -> This is a template to use for [stabilization reports](./stabilization_guide.md) of **language features**. It consists of a series of questions that aim to provide the information most commonly needed and to help reviewers be more likely to identify potential problems up front. Not all parts of the template will apply to all stabilizations. Feel free to put N/A if a question doesn't seem to apply to your case. -> -> You can copy the following template after the separator and edit it as Markdown, replacing the *TODO* placeholders with answers. +## What is this? + +This is a template for [stabilization reports](./stabilization_guide.md) of **language features**. The questions aim to solicit the details most often needed. These details help reviewers to identify potential problems upfront. Not all parts of the template will apply to every stabilization. If a question doesn't apply, explain briefly why. + +Copy everything after the separator and edit it as Markdown. Replace each *TODO* with your answer. --- -> ## General design +# Stabilization report -> ### What is the RFC for this feature and what changes have occurred to the user-facing design since the RFC was finalized? +## Summary -*TODO* - -> ### What behavior are we committing to that has been controversial? Summarize the major arguments pro/con. - -*TODO* - -> ### Are there extensions to this feature that remain unstable? How do we know that we are not accidentally committing to those? - -*TODO* - -> ## Has a Call for Testing period been conducted? If so, what feedback was received? +> Remind us what this feature is and what value it provides. Tell the story of what led up to this stabilization. > -> Does any OSS nightly users use this feature? For instance, a useful indication might be "search for `#![feature(FEATURE_NAME)]` and had `N` results". - -*TODO* - -> ## Implementation quality - -*TODO* - -> ### Summarize the major parts of the implementation and provide links into the code (or to PRs) +> E.g., see: > -> An example for async closures: . +> - [Stabilize AFIT/RPITIT](https://web.archive.org/web/20250329190642/https://github.com/rust-lang/rust/pull/115822) +> - [Stabilize RTN](https://web.archive.org/web/20250321214601/https://github.com/rust-lang/rust/pull/138424) +> - [Stabilize ATPIT](https://web.archive.org/web/20250124214256/https://github.com/rust-lang/rust/pull/120700) +> - [Stabilize opaque type precise capturing](https://web.archive.org/web/20250312173538/https://github.com/rust-lang/rust/pull/127672) *TODO* -> ### Summarize existing test coverage of this feature +Tracking: + +- *TODO* (Link to tracking issue.) + +Reference PRs: + +- *TODO* (Link to Reference PRs.) + +cc @rust-lang/lang @rust-lang/lang-advisors + +### What is stabilized + +> Describe each behavior being stabilized and give a short example of code that will now be accepted. + +```rust +todo!() +``` + +### What isn't stabilized + +> Describe any parts of the feature not being stabilized. Talk about what we might want to do later and what doors are being left open for that. If what we're not stabilizing might lead to surprises for users, talk about that in particular. + +## Design + +### Reference + +> What updates are needed to the Reference? Link to each PR. If the Reference is missing content needed for describing this feature, discuss that. + +- *TODO* + +### RFC history + +> What RFCs have been accepted for this feature? + +- *TODO* + +### Answers to unresolved questions + +> What questions were left unresolved by the RFC? How have they been answered? Link to any relevant lang decisions. + +*TODO* + +### Post-RFC changes + +> What other user-visible changes have occurred since the RFC was accepted? Describe both changes that the lang team accepted (and link to those decisions) as well as changes that are being presented to the team for the first time in this stabilization report. + +*TODO* + +### Key points + +> What decisions have been most difficult and what behaviors to be stabilized have proved most contentious? Summarize the major arguments on all sides and link to earlier documents and discussions. + +*TODO* + +### Nightly extensions + +> Are there extensions to this feature that remain unstable? How do we know that we are not accidentally committing to those? + +*TODO* + +### Doors closed + +> What doors does this stabilization close for later changes to the language? E.g., does this stabilization make any other RFCs, lang experiments, or known in-flight proposals more difficult or impossible to do later? + +## Feedback + +### Call for testing + +> Has a "call for testing" been done? If so, what feedback was received? + +*TODO* + +### Nightly use + +> Do any known nightly users use this feature? Counting instances of `#![feature(FEATURE_NAME)]` on GitHub with grep might be informative. + +*TODO* + +## Implementation + +### Major parts + +> Summarize the major parts of the implementation and provide links into the code and to relevant PRs. > -> Consider what the "edges" of this feature are. We're particularly interested in seeing tests that assure us about exactly what nearby things we're not stabilizing. +> See, e.g., this breakdown of the major parts of async closures: > -> Within each test, include a comment at the top describing the purpose of the test and what set of invariants it intends to demonstrate. This is a great help to those reviewing the tests at stabilization time. +> - + +*TODO* + +### Coverage + +> Summarize the test coverage of this feature. > -> - What does the test coverage landscape for this feature look like? -> - Tests for compiler errors when you use the feature wrongly or make mistakes? -> - Tests for the feature itself: -> - Limits of the feature (so failing compilation) -> - Exercises of edge cases of the feature -> - Tests that checks the feature works as expected (where applicable, `//@ run-pass`). -> - Are there any intentional gaps in test coverage? +> Consider what the "edges" of this feature are. We're particularly interested in seeing tests that assure us about exactly what nearby things we're not stabilizing. Tests should of course comprehensively demonstrate that the feature works. Think too about demonstrating the diagnostics seen when common mistakes are made and the feature is used incorrectly. > -> Link to test folders or individual tests (ui/codegen/assembly/run-make tests, etc.). +> Within each test, include a comment at the top describing the purpose of the test and what set of invariants it intends to demonstrate. This is a great help to our review. +> +> Describe any known or intentional gaps in test coverage. +> +> Contextualize and link to test folders and individual tests. *TODO* -> ### What outstanding bugs in the issue tracker involve this feature? Are they stabilization-blocking? +### Outstanding bugs + +> What outstanding bugs involve this feature? List them. Should any block the stabilization? Discuss why or why not. *TODO* -> ### What FIXMEs are still in the code for that feature and why is it ok to leave them there? +- *TODO* +- *TODO* +- *TODO* + +### Outstanding FIXMEs + +> What FIXMEs are still in the code for that feature and why is it OK to leave them there? *TODO* -> ### Summarize contributors to the feature by name for recognition and assuredness that people involved in the feature agree with stabilization +### Tool changes + +> What changes must be made to our other tools to support this feature. Has this work been done? Link to any relevant PRs and issues. + +- [ ] rustfmt + - *TODO* +- [ ] rust-analyzer + - *TODO* +- [ ] rustdoc (both JSON and HTML) + - *TODO* +- [ ] cargo + - *TODO* +- [ ] clippy + - *TODO* +- [ ] rustup + - *TODO* +- [ ] docs.rs + - *TODO* *TODO* -> ### Which tools need to be adjusted to support this feature. Has this work been done? -> -> Consider rustdoc, clippy, rust-analyzer, rustfmt, rustup, docs.rs. +### Breaking changes + +> If this stabilization represents a known breaking change, link to the crater report, the analysis of the crater report, and to all PRs we've made to ecosystem projects affected by this breakage. Discuss any limitations of what we're able to know about or to fix. *TODO* -> ## Type system and execution rules +Crater report: -> ### What compilation-time checks are done that are needed to prevent undefined behavior? -> -> (Be sure to link to tests demonstrating that these tests are being done.) +- *TODO* + +Crater analysis: + +- *TODO* + +PRs to affected crates: + +- *TODO* +- *TODO* +- *TODO* + +## Type system, opsem + +### Compile-time checks + +> What compilation-time checks are done that are needed to prevent undefined behavior? +> +> Link to tests demonstrating that these checks are being done. *TODO* -> ### Does the feature's implementation need checks to prevent UB or is it sound by default and needs opt in in places to perform the dangerous/unsafe operations? If it is not sound by default, what is the rationale? +- *TODO* +- *TODO* +- *TODO* + +### Type system rules + +> What type system rules are enforced for this feature and what is the purpose of each? *TODO* -> ### Can users use this feature to introduce undefined behavior, or use this feature to break the abstraction of Rust and expose the underlying assembly-level implementation? (Describe.) +### Sound by default? + +> Does the feature's implementation need specific checks to prevent UB, or is it sound by default and need specific opt-in to perform the dangerous/unsafe operations? If it is not sound by default, what is the rationale? *TODO* -> ### What updates are needed to the reference/specification? (link to PRs when they exist) +### Breaks the AM? + +> Can users use this feature to introduce undefined behavior, or use this feature to break the abstraction of Rust and expose the underlying assembly-level implementation? Describe this if so. *TODO* -> ## Common interactions +## Common interactions -> ### Does this feature introduce new expressions and can they produce temporaries? What are the lifetimes of those temporaries? +### Temporaries + +> Does this feature introduce new expressions that can produce temporaries? What are the scopes of those temporaries? *TODO* -> ### What other unstable features may be exposed by this feature? +### Drop order + +> Does this feature raise questions about the order in which we should drop values? Talk about the decisions made here and how they're consistent with our earlier decisions. *TODO* + +### Pre-expansion / post-expansion + +> Does this feature raise questions about what should be accepted pre-expansion (e.g. in code covered by `#[cfg(false)]`) versus what should be accepted post-expansion? What decisions were made about this? + +*TODO* + +### Edition hygiene + +> If this feature is gated on an edition, how do we decide, in the context of the edition hygiene of tokens, whether to accept or reject code. E.g., what token do we use to decide? + +*TODO* + +### SemVer implications + +> Does this feature create any new ways in which library authors must take care to prevent breaking downstreams when making minor-version releases? Describe these. Are these new hazards "major" or "minor" according to [RFC 1105](https://rust-lang.github.io/rfcs/1105-api-evolution.html)? + +*TODO* + +### Exposing other features + +> Are there any other unstable features whose behavior may be exposed by this feature in any way? What features present the highest risk of that? + +*TODO* + +## History + +> List issues and PRs that are important for understanding how we got here. + +- *TODO* +- *TODO* +- *TODO* + +## Acknowledgments + +> Summarize contributors to the feature by name for recognition and so that those people are notified about the stabilization. Does anyone who worked on this *not* think it should be stabilized right now? We'd like to hear about that if so. + +*TODO* + +## Open items + +> List any known items that have not yet been completed and that should be before this is stabilized. + +- [ ] *TODO* +- [ ] *TODO* +- [ ] *TODO* From a448837045326d7c33059dc3aa2d1d87529dcf3d 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 161/809] Implement support for explicit tail calls in the MIR block builders and the LLVM codegen backend. --- compiler/rustc_codegen_gcc/messages.ftl | 2 + compiler/rustc_codegen_gcc/src/builder.rs | 15 ++++ compiler/rustc_codegen_gcc/src/errors.rs | 4 + compiler/rustc_codegen_llvm/src/builder.rs | 25 ++++++- compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 11 +++ compiler/rustc_codegen_ssa/src/mir/block.rs | 73 ++++++++++++++++--- .../rustc_codegen_ssa/src/traits/builder.rs | 12 +++ .../rustc_llvm/llvm-wrapper/RustWrapper.cpp | 26 +++++++ tests/codegen-llvm/become-musttail.rs | 18 +++++ tests/ui/explicit-tail-calls/recursion-etc.rs | 17 +++++ 10 files changed, 191 insertions(+), 12 deletions(-) create mode 100644 tests/codegen-llvm/become-musttail.rs create mode 100644 tests/ui/explicit-tail-calls/recursion-etc.rs diff --git a/compiler/rustc_codegen_gcc/messages.ftl b/compiler/rustc_codegen_gcc/messages.ftl index a70ac08f01ae..b9b77b7d18c6 100644 --- a/compiler/rustc_codegen_gcc/messages.ftl +++ b/compiler/rustc_codegen_gcc/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/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index a4ec4bf8deac..4aee211e2efa 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/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/compiler/rustc_codegen_gcc/src/errors.rs b/compiler/rustc_codegen_gcc/src/errors.rs index 0aa16bd88b43..b252c39c0c05 100644 --- a/compiler/rustc_codegen_gcc/src/errors.rs +++ b/compiler/rustc_codegen_gcc/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; diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 0ade9edb0d2e..e8d903058294 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -15,6 +15,7 @@ use rustc_codegen_ssa::mir::place::PlaceRef; use rustc_codegen_ssa::traits::*; use rustc_data_structures::small_c_str::SmallCStr; use rustc_hir::def_id::DefId; +use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::ty::layout::{ FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers, @@ -24,7 +25,7 @@ use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_sanitizers::{cfi, kcfi}; use rustc_session::config::OptLevel; use rustc_span::Span; -use rustc_target::callconv::FnAbi; +use rustc_target::callconv::{FnAbi, PassMode}; use rustc_target::spec::{HasTargetSpec, SanitizerSet, Target}; use smallvec::SmallVec; use tracing::{debug, instrument}; @@ -1431,6 +1432,28 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, '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>, + ) { + let call = self.call(llty, fn_attrs, Some(fn_abi), llfn, args, funclet, instance); + llvm::LLVMRustSetTailCallKind(call, llvm::TailCallKind::MustTail); + + match &fn_abi.ret.mode { + PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(), + PassMode::Direct(_) | PassMode::Pair { .. } => self.ret(call), + mode @ PassMode::Cast { .. } => { + bug!("Encountered `PassMode::{mode:?}` during codegen") + } + } + } + fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value { unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) } } diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index edfb29dd1be7..9d4bd70549b4 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -97,6 +97,16 @@ pub(crate) enum ModuleFlagMergeBehavior { // Consts for the LLVM CallConv type, pre-cast to usize. +#[derive(Copy, Clone, PartialEq, Debug)] +#[repr(C)] +#[allow(dead_code)] +pub(crate) enum TailCallKind { + None = 0, + Tail = 1, + MustTail = 2, + NoTail = 3, +} + /// LLVM CallingConv::ID. Should we wrap this? /// /// See @@ -1186,6 +1196,7 @@ unsafe extern "C" { pub(crate) safe fn LLVMIsGlobalConstant(GlobalVar: &Value) -> Bool; pub(crate) safe fn LLVMSetGlobalConstant(GlobalVar: &Value, IsConstant: Bool); pub(crate) safe fn LLVMSetTailCall(CallInst: &Value, IsTailCall: Bool); + pub(crate) safe fn LLVMRustSetTailCallKind(CallInst: &Value, Kind: TailCallKind); // Operations on attributes pub(crate) fn LLVMCreateStringAttribute( diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index bde63fd501aa..e96590441fa4 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -35,6 +35,14 @@ enum MergingSucc { True, } +/// Indicates to the call terminator codegen whether a cal +/// is a normal call or an explicit tail call. +#[derive(Debug, PartialEq)] +enum CallKind { + Normal, + Tail, +} + /// Used by `FunctionCx::codegen_terminator` for emitting common patterns /// e.g., creating a basic block, calling a function, etc. struct TerminatorCodegenHelper<'tcx> { @@ -160,6 +168,7 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { mut unwind: mir::UnwindAction, lifetime_ends_after_call: &[(Bx::Value, Size)], instance: Option>, + kind: CallKind, mergeable_succ: bool, ) -> MergingSucc { let tcx = bx.tcx(); @@ -221,6 +230,11 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { } }; + if kind == CallKind::Tail { + bx.tail_call(fn_ty, fn_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance); + return MergingSucc::False; + } + if let Some(unwind_block) = unwind_block { let ret_llbb = if let Some((_, target)) = destination { fx.llbb(target) @@ -659,6 +673,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { unwind, &[], Some(drop_instance), + CallKind::Normal, !maybe_null && mergeable_succ, ) } @@ -747,8 +762,19 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item); // Codegen the actual panic invoke/call. - let merging_succ = - helper.do_call(self, bx, fn_abi, llfn, &args, None, unwind, &[], Some(instance), false); + let merging_succ = helper.do_call( + self, + bx, + fn_abi, + llfn, + &args, + None, + unwind, + &[], + Some(instance), + CallKind::Normal, + false, + ); assert_eq!(merging_succ, MergingSucc::False); MergingSucc::False } @@ -777,6 +803,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { mir::UnwindAction::Unreachable, &[], Some(instance), + CallKind::Normal, false, ); assert_eq!(merging_succ, MergingSucc::False); @@ -845,6 +872,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { unwind, &[], Some(instance), + CallKind::Normal, mergeable_succ, )) } @@ -860,6 +888,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { target: Option, unwind: mir::UnwindAction, fn_span: Span, + kind: CallKind, mergeable_succ: bool, ) -> MergingSucc { let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info }; @@ -1003,8 +1032,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // We still need to call `make_return_dest` even if there's no `target`, since // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited, // and `make_return_dest` adds the return-place indirect pointer to `llargs`. - let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs); - let destination = target.map(|target| (return_dest, target)); + let destination = match kind { + CallKind::Normal => { + let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs); + target.map(|target| (return_dest, target)) + } + CallKind::Tail => None, + }; // Split the rust-call tupled arguments off. let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall @@ -1020,6 +1054,14 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // to generate `lifetime_end` when the call returns. let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new(); 'make_args: for (i, arg) in first_args.iter().enumerate() { + if kind == CallKind::Tail && matches!(fn_abi.args[i].mode, PassMode::Indirect { .. }) { + // FIXME: https://github.com/rust-lang/rust/pull/144232#discussion_r2218543841 + span_bug!( + fn_span, + "arguments using PassMode::Indirect are currently not supported for tail calls" + ); + } + let mut op = self.codegen_operand(bx, &arg.node); if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) { @@ -1147,6 +1189,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { unwind, &lifetime_ends_after_call, instance, + kind, mergeable_succ, ) } @@ -1388,15 +1431,23 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { target, unwind, fn_span, + CallKind::Normal, mergeable_succ(), ), - mir::TerminatorKind::TailCall { .. } => { - // FIXME(explicit_tail_calls): implement tail calls in ssa backend - span_bug!( - terminator.source_info.span, - "`TailCall` terminator is not yet supported by `rustc_codegen_ssa`" - ) - } + mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self + .codegen_call_terminator( + helper, + bx, + terminator, + func, + args, + mir::Place::from(mir::RETURN_PLACE), + None, + mir::UnwindAction::Unreachable, + fn_span, + CallKind::Tail, + mergeable_succ(), + ), mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => { bug!("coroutine ops in codegen") } diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 979456a6ba70..4b18146863bf 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -595,6 +595,18 @@ pub trait BuilderMethods<'a, 'tcx>: funclet: Option<&Self::Funclet>, instance: Option>, ) -> Self::Value; + + 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>, + ); + fn zext(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; fn apply_attrs_to_cleanup_callsite(&mut self, llret: Self::Value); diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index 82568ed4ae17..8e1c18eb56b4 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -1986,3 +1986,29 @@ extern "C" void LLVMRustSetNoSanitizeHWAddress(LLVMValueRef Global) { MD.NoHWAddress = true; GV.setSanitizerMetadata(MD); } + +enum class LLVMRustTailCallKind { + None = 0, + Tail = 1, + MustTail = 2, + NoTail = 3 +}; + +extern "C" void LLVMRustSetTailCallKind(LLVMValueRef Call, + LLVMRustTailCallKind Kind) { + CallInst *CI = unwrap(Call); + switch (Kind) { + case LLVMRustTailCallKind::None: + CI->setTailCallKind(CallInst::TCK_None); + break; + case LLVMRustTailCallKind::Tail: + CI->setTailCallKind(CallInst::TCK_Tail); + break; + case LLVMRustTailCallKind::MustTail: + CI->setTailCallKind(CallInst::TCK_MustTail); + break; + case LLVMRustTailCallKind::NoTail: + CI->setTailCallKind(CallInst::TCK_NoTail); + break; + } +} diff --git a/tests/codegen-llvm/become-musttail.rs b/tests/codegen-llvm/become-musttail.rs new file mode 100644 index 000000000000..07f335719104 --- /dev/null +++ b/tests/codegen-llvm/become-musttail.rs @@ -0,0 +1,18 @@ +//@ compile-flags: -C opt-level=0 -Cpanic=abort -C no-prepopulate-passes +//@ needs-unwind + +#![crate_type = "lib"] +#![feature(explicit_tail_calls)] + +// CHECK-LABEL: define {{.*}}@fibonacci( +#[no_mangle] +#[inline(never)] +pub fn fibonacci(n: u64, a: u64, b: u64) -> u64 { + // CHECK: musttail call {{.*}}@fibonacci( + // CHECK-NEXT: ret i64 + match n { + 0 => a, + 1 => b, + _ => become fibonacci(n - 1, b, a + b), + } +} diff --git a/tests/ui/explicit-tail-calls/recursion-etc.rs b/tests/ui/explicit-tail-calls/recursion-etc.rs new file mode 100644 index 000000000000..8c89ceb7869a --- /dev/null +++ b/tests/ui/explicit-tail-calls/recursion-etc.rs @@ -0,0 +1,17 @@ +//@ run-pass +#![expect(incomplete_features)] +#![feature(explicit_tail_calls)] + +use std::hint::black_box; + +pub fn count(curr: u64, top: u64) -> u64 { + if black_box(curr) >= top { + curr + } else { + become count(curr + 1, top) + } +} + +fn main() { + println!("{}", count(0, black_box(1000000))); +} 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 162/809] 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 7f7d343400de843c12f880b02ea1a7b22ccc7379 Mon Sep 17 00:00:00 2001 From: okaneco <47607823+okaneco@users.noreply.github.com> Date: Fri, 25 Jul 2025 18:35:53 -0400 Subject: [PATCH 163/809] str: Mark unstable `round_char_boundary` feature functions as const Mark `floor_char_boundary`, `ceil_char_boundary` const Simplify the implementations, reducing the number of arithmetic operations --- library/core/src/str/mod.rs | 38 ++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 029abf175391..c40af4de7e03 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -407,17 +407,22 @@ impl str { /// ``` #[unstable(feature = "round_char_boundary", issue = "93743")] #[inline] - pub fn floor_char_boundary(&self, index: usize) -> usize { + pub const fn floor_char_boundary(&self, index: usize) -> usize { if index >= self.len() { self.len() } else { - let lower_bound = index.saturating_sub(3); - let new_index = self.as_bytes()[lower_bound..=index] - .iter() - .rposition(|b| b.is_utf8_char_boundary()); + let mut i = index; + while i > 0 { + if self.as_bytes()[i].is_utf8_char_boundary() { + break; + } + i -= 1; + } - // SAFETY: we know that the character boundary will be within four bytes - unsafe { lower_bound + new_index.unwrap_unchecked() } + // The character boundary will be within four bytes of the index + debug_assert!(i >= index.saturating_sub(3)); + + i } } @@ -445,15 +450,22 @@ impl str { /// ``` #[unstable(feature = "round_char_boundary", issue = "93743")] #[inline] - pub fn ceil_char_boundary(&self, index: usize) -> usize { + pub const fn ceil_char_boundary(&self, index: usize) -> usize { if index >= self.len() { self.len() } else { - let upper_bound = Ord::min(index + 4, self.len()); - self.as_bytes()[index..upper_bound] - .iter() - .position(|b| b.is_utf8_char_boundary()) - .map_or(upper_bound, |pos| pos + index) + let mut i = index; + while i < self.len() { + if self.as_bytes()[i].is_utf8_char_boundary() { + break; + } + i += 1; + } + + // The character boundary will be within four bytes of the index + debug_assert!(i <= index + 3); + + i } } From 3352dfc4a232fa6f38db3ea3ed465f56e6c8f85b Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Fri, 25 Jul 2025 17:27:08 -0700 Subject: [PATCH 164/809] 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 165/809] 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 166/809] 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 167/809] 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 168/809] 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 d88bdc9927ade8747484a9a8e80ac55a63dbcc40 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 26 Jul 2025 09:38:38 +0200 Subject: [PATCH 169/809] CI: run apt update before installing anything --- src/tools/miri/.github/workflows/ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index e2e81370c600..c47f9695624b 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -52,6 +52,10 @@ jobs: HOST_TARGET: ${{ matrix.host_target }} steps: - uses: actions/checkout@v4 + - name: apt update + if: ${{ startsWith(matrix.os, 'ubuntu') }} + # The runners seem to have outdated apt repos sometimes + run: sudo apt update - name: install qemu if: ${{ matrix.qemu }} run: sudo apt install qemu-user qemu-user-binfmt From e910c0e7e6338bdc4c63b584bfff3f2abf1c3896 Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Fri, 28 Mar 2025 12:27:04 -0400 Subject: [PATCH 170/809] 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 171/809] 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 948f7798d70b6adb6a490b8867e155dadebd3f0e 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 172/809] 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. --- compiler/rustc_codegen_gcc/src/back/write.rs | 9 ---- compiler/rustc_codegen_gcc/src/lib.rs | 8 ---- compiler/rustc_codegen_llvm/src/back/write.rs | 23 ---------- compiler/rustc_codegen_llvm/src/lib.rs | 7 ---- compiler/rustc_codegen_ssa/src/back/write.rs | 42 +++---------------- .../rustc_codegen_ssa/src/traits/write.rs | 6 --- compiler/rustc_session/src/options.rs | 2 - 7 files changed, 6 insertions(+), 91 deletions(-) diff --git a/compiler/rustc_codegen_gcc/src/back/write.rs b/compiler/rustc_codegen_gcc/src/back/write.rs index 113abe70805b..c1231142c658 100644 --- a/compiler/rustc_codegen_gcc/src/back/write.rs +++ b/compiler/rustc_codegen_gcc/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/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index 71765c511381..a31206825007 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/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 diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 6f8fba2a30dc..85a06f457ebe 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -796,29 +796,6 @@ pub(crate) fn optimize( Ok(()) } -pub(crate) fn link( - cgcx: &CodegenContext, - dcx: DiagCtxtHandle<'_>, - mut modules: Vec>, -) -> Result, FatalError> { - use super::lto::{Linker, ModuleBuffer}; - // Sort the modules by name to ensure deterministic behavior. - modules.sort_by(|a, b| a.name.cmp(&b.name)); - let (first, elements) = - modules.split_first().expect("Bug! modules must contain at least one module."); - - let mut linker = Linker::new(first.module_llvm.llmod()); - for module in elements { - let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name); - let buffer = ModuleBuffer::new(module.module_llvm.llmod()); - linker - .add(buffer.data()) - .map_err(|()| llvm_err(dcx, LlvmError::SerializeModule { name: &module.name }))?; - } - drop(linker); - Ok(modules.remove(0)) -} - pub(crate) fn codegen( cgcx: &CodegenContext, module: ModuleCodegen, diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 8b1913cfa756..ca84b6de8b11 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -168,13 +168,6 @@ impl WriteBackendMethods for LlvmCodegenBackend { let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap(); print!("{stats}"); } - fn run_link( - cgcx: &CodegenContext, - dcx: DiagCtxtHandle<'_>, - modules: Vec>, - ) -> Result, FatalError> { - back::write::link(cgcx, dcx, modules) - } fn run_and_optimize_fat_lto( cgcx: &CodegenContext, exported_symbols_for_lto: &[String], diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index a41cbd306d0c..6773d3e24e94 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -797,10 +797,6 @@ pub(crate) enum WorkItemResult { /// The backend has finished compiling a CGU, nothing more required. Finished(CompiledModule), - /// The backend has finished compiling a CGU, which now needs linking - /// because `-Zcombine-cgu` was specified. - NeedsLink(ModuleCodegen), - /// The backend has finished compiling a CGU, which now needs to go through /// fat LTO. NeedsFatLto(FatLtoInput), @@ -884,7 +880,10 @@ fn execute_optimize_work_item( }; match lto_type { - ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config), + ComputedLtoType::No => { + let module = B::codegen(cgcx, module, module_config)?; + Ok(WorkItemResult::Finished(module)) + } ComputedLtoType::Thin => { let (name, thin_buffer) = B::prepare_thin(module, false); if let Some(path) = bitcode { @@ -1024,20 +1023,8 @@ fn execute_thin_lto_work_item( module_config: &ModuleConfig, ) -> Result, FatalError> { let module = B::optimize_thin(cgcx, module)?; - finish_intra_module_work(cgcx, module, module_config) -} - -fn finish_intra_module_work( - cgcx: &CodegenContext, - module: ModuleCodegen, - module_config: &ModuleConfig, -) -> Result, FatalError> { - if !cgcx.opts.unstable_opts.combine_cgu || module.kind == ModuleKind::Allocator { - let module = B::codegen(cgcx, module, module_config)?; - Ok(WorkItemResult::Finished(module)) - } else { - Ok(WorkItemResult::NeedsLink(module)) - } + let module = B::codegen(cgcx, module, module_config)?; + Ok(WorkItemResult::Finished(module)) } /// Messages sent to the coordinator. @@ -1343,7 +1330,6 @@ fn start_executing_work( // through codegen and LLVM. let mut compiled_modules = vec![]; let mut compiled_allocator_module = None; - let mut needs_link = Vec::new(); let mut needs_fat_lto = Vec::new(); let mut needs_thin_lto = Vec::new(); let mut lto_import_only_modules = Vec::new(); @@ -1625,7 +1611,6 @@ fn start_executing_work( Ok(WorkItemResult::Finished(compiled_module)) => { match compiled_module.kind { ModuleKind::Regular => { - assert!(needs_link.is_empty()); compiled_modules.push(compiled_module); } ModuleKind::Allocator => { @@ -1634,10 +1619,6 @@ fn start_executing_work( } } } - Ok(WorkItemResult::NeedsLink(module)) => { - assert!(compiled_modules.is_empty()); - needs_link.push(module); - } Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => { assert!(!started_lto); assert!(needs_thin_lto.is_empty()); @@ -1674,17 +1655,6 @@ fn start_executing_work( return Err(()); } - let needs_link = mem::take(&mut needs_link); - if !needs_link.is_empty() { - assert!(compiled_modules.is_empty()); - let dcx = cgcx.create_dcx(); - let dcx = dcx.handle(); - let module = B::run_link(&cgcx, dcx, needs_link).map_err(|_| ())?; - let module = - B::codegen(&cgcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())?; - compiled_modules.push(module); - } - // Drop to print timings drop(llvm_start_time); diff --git a/compiler/rustc_codegen_ssa/src/traits/write.rs b/compiler/rustc_codegen_ssa/src/traits/write.rs index 8e78cbe1963b..f391c198e1a1 100644 --- a/compiler/rustc_codegen_ssa/src/traits/write.rs +++ b/compiler/rustc_codegen_ssa/src/traits/write.rs @@ -16,12 +16,6 @@ pub trait WriteBackendMethods: Clone + 'static { type ThinData: Send + Sync; type ThinBuffer: ThinBufferMethods; - /// Merge all modules into main_module and returning it - fn run_link( - cgcx: &CodegenContext, - dcx: DiagCtxtHandle<'_>, - modules: Vec>, - ) -> Result, FatalError>; /// Performs fat LTO by merging all modules into a single one, running autodiff /// if necessary and running any further optimizations fn run_and_optimize_fat_lto( diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 5f1973b31a1b..44b35e8921ec 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -2168,8 +2168,6 @@ options! { "hash algorithm of source files used to check freshness in cargo (`blake3` or `sha256`)"), codegen_backend: Option = (None, parse_opt_string, [TRACKED], "the backend to use"), - combine_cgu: bool = (false, parse_bool, [TRACKED], - "combine CGUs into a single one"), contract_checks: Option = (None, parse_opt_bool, [TRACKED], "emit runtime checks for contract pre- and post-conditions (default: no)"), coverage_options: CoverageOptions = (CoverageOptions::default(), parse_coverage_options, [TRACKED], 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 173/809] 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 174/809] 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 175/809] 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 a1f5a6d781d65949fe08c149a695d4cd926cc755 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sat, 26 Jul 2025 00:47:33 +0000 Subject: [PATCH 176/809] Perform check_private_in_public by module. --- compiler/rustc_interface/src/passes.rs | 4 +- compiler/rustc_middle/src/query/mod.rs | 7 +- compiler/rustc_privacy/src/lib.rs | 4 +- .../ui/privacy/private-in-public-warn.stderr | 72 +++++++++---------- tests/ui/privacy/projections.stderr | 26 +++---- 5 files changed, 59 insertions(+), 54 deletions(-) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index fb6897c7d895..aaabf7df42d7 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -1147,7 +1147,9 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) { parallel!( { - tcx.ensure_ok().check_private_in_public(()); + tcx.par_hir_for_each_module(|module| { + tcx.ensure_ok().check_private_in_public(module) + }) }, { tcx.par_hir_for_each_module(|module| { diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 587349d4cf41..7a625f4fee73 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1390,8 +1390,11 @@ rustc_queries! { eval_always desc { "checking effective visibilities" } } - query check_private_in_public(_: ()) { - desc { "checking for private elements in public interfaces" } + query check_private_in_public(module_def_id: LocalModDefId) { + desc { |tcx| + "checking for private elements in public interfaces for {}", + describe_as_module(module_def_id, tcx) + } } query reachable_set(_: ()) -> &'tcx LocalDefIdSet { diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 6fd2b7fc12f0..1a062c63a6fe 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1854,12 +1854,12 @@ fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities { tcx.arena.alloc(visitor.effective_visibilities) } -fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) { +fn check_private_in_public(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { let effective_visibilities = tcx.effective_visibilities(()); // Check for private types in public interfaces. let mut checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities }; - let crate_items = tcx.hir_crate_items(()); + let crate_items = tcx.hir_module_items(module_def_id); for id in crate_items.free_items() { checker.check_item(id); } diff --git a/tests/ui/privacy/private-in-public-warn.stderr b/tests/ui/privacy/private-in-public-warn.stderr index 86f6be85a071..edcffaf6b70a 100644 --- a/tests/ui/privacy/private-in-public-warn.stderr +++ b/tests/ui/privacy/private-in-public-warn.stderr @@ -93,6 +93,42 @@ LL | struct Priv; LL | type Alias = Priv; | ^^^^^^^^^^ can't leak private type +error: type `types::Priv` is more private than the item `types::ES` + --> $DIR/private-in-public-warn.rs:27:9 + | +LL | pub static ES: Priv; + | ^^^^^^^^^^^^^^^^^^^ static `types::ES` is reachable at visibility `pub(crate)` + | +note: but type `types::Priv` is only usable at visibility `pub(self)` + --> $DIR/private-in-public-warn.rs:9:5 + | +LL | struct Priv; + | ^^^^^^^^^^^ + +error: type `types::Priv` is more private than the item `types::ef1` + --> $DIR/private-in-public-warn.rs:28:9 + | +LL | pub fn ef1(arg: Priv); + | ^^^^^^^^^^^^^^^^^^^^^^ function `types::ef1` is reachable at visibility `pub(crate)` + | +note: but type `types::Priv` is only usable at visibility `pub(self)` + --> $DIR/private-in-public-warn.rs:9:5 + | +LL | struct Priv; + | ^^^^^^^^^^^ + +error: type `types::Priv` is more private than the item `types::ef2` + --> $DIR/private-in-public-warn.rs:29:9 + | +LL | pub fn ef2() -> Priv; + | ^^^^^^^^^^^^^^^^^^^^^ function `types::ef2` is reachable at visibility `pub(crate)` + | +note: but type `types::Priv` is only usable at visibility `pub(self)` + --> $DIR/private-in-public-warn.rs:9:5 + | +LL | struct Priv; + | ^^^^^^^^^^^ + error: trait `traits::PrivTr` is more private than the item `traits::Alias` --> $DIR/private-in-public-warn.rs:42:5 | @@ -359,42 +395,6 @@ note: but type `Priv2` is only usable at visibility `pub(self)` LL | struct Priv2; | ^^^^^^^^^^^^ -error: type `types::Priv` is more private than the item `types::ES` - --> $DIR/private-in-public-warn.rs:27:9 - | -LL | pub static ES: Priv; - | ^^^^^^^^^^^^^^^^^^^ static `types::ES` is reachable at visibility `pub(crate)` - | -note: but type `types::Priv` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:9:5 - | -LL | struct Priv; - | ^^^^^^^^^^^ - -error: type `types::Priv` is more private than the item `types::ef1` - --> $DIR/private-in-public-warn.rs:28:9 - | -LL | pub fn ef1(arg: Priv); - | ^^^^^^^^^^^^^^^^^^^^^^ function `types::ef1` is reachable at visibility `pub(crate)` - | -note: but type `types::Priv` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:9:5 - | -LL | struct Priv; - | ^^^^^^^^^^^ - -error: type `types::Priv` is more private than the item `types::ef2` - --> $DIR/private-in-public-warn.rs:29:9 - | -LL | pub fn ef2() -> Priv; - | ^^^^^^^^^^^^^^^^^^^^^ function `types::ef2` is reachable at visibility `pub(crate)` - | -note: but type `types::Priv` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:9:5 - | -LL | struct Priv; - | ^^^^^^^^^^^ - warning: bounds on generic parameters in type aliases are not enforced --> $DIR/private-in-public-warn.rs:42:23 | diff --git a/tests/ui/privacy/projections.stderr b/tests/ui/privacy/projections.stderr index 010d77998e34..addb6a075a28 100644 --- a/tests/ui/privacy/projections.stderr +++ b/tests/ui/privacy/projections.stderr @@ -1,16 +1,3 @@ -warning: type `Priv` is more private than the item `Leak` - --> $DIR/projections.rs:3:5 - | -LL | pub type Leak = Priv; - | ^^^^^^^^^^^^^ type alias `Leak` is reachable at visibility `pub(crate)` - | -note: but type `Priv` is only usable at visibility `pub(self)` - --> $DIR/projections.rs:2:5 - | -LL | struct Priv; - | ^^^^^^^^^^^ - = note: `#[warn(private_interfaces)]` on by default - error[E0446]: private type `Priv` in public interface --> $DIR/projections.rs:24:5 | @@ -29,6 +16,19 @@ LL | struct Priv; LL | type A = T::A; | ^^^^^^^^^^^^^^^^ can't leak private type +warning: type `Priv` is more private than the item `Leak` + --> $DIR/projections.rs:3:5 + | +LL | pub type Leak = Priv; + | ^^^^^^^^^^^^^ type alias `Leak` is reachable at visibility `pub(crate)` + | +note: but type `Priv` is only usable at visibility `pub(self)` + --> $DIR/projections.rs:2:5 + | +LL | struct Priv; + | ^^^^^^^^^^^ + = note: `#[warn(private_interfaces)]` on by default + error: type `Priv` is private --> $DIR/projections.rs:14:15 | From 75420b62ffd516705dda1327a26f4f27818a189f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Jul 2025 00:27:04 +0000 Subject: [PATCH 177/809] cargo update compiler & tools dependencies: Locking 3 packages to latest compatible versions Updating ipc-channel v0.20.0 -> v0.20.1 Updating rand v0.9.1 -> v0.9.2 Updating redox_syscall v0.5.13 -> v0.5.16 note: pass `--verbose` to see 37 unchanged dependencies behind latest library dependencies: Locking 1 package to latest compatible version Updating rand v0.9.1 -> v0.9.2 note: pass `--verbose` to see 2 unchanged dependencies behind latest rustbook dependencies: Locking 1 package to latest compatible version Updating redox_syscall v0.5.13 -> v0.5.16 --- Cargo.lock | 26 +++++++++++++------------- library/Cargo.lock | 4 ++-- src/tools/rustbook/Cargo.lock | 4 ++-- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9e0561199ab7..d8d5211dd901 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1890,16 +1890,16 @@ dependencies = [ [[package]] name = "ipc-channel" -version = "0.20.0" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b1c98b70019c830a1fc39cecfe1f60ff99c4122f0a189697c810c90ec545c14" +checksum = "1700f6b8b9f00cdd675f32fbb3a5be882213140dfe045805273221ca266c43f8" dependencies = [ "bincode", "crossbeam-channel", "fnv", "libc", "mio", - "rand 0.9.1", + "rand 0.9.2", "serde", "tempfile", "uuid", @@ -2329,7 +2329,7 @@ dependencies = [ "libloading", "measureme", "nix", - "rand 0.9.1", + "rand 0.9.2", "regex", "rustc_version", "serde", @@ -2962,9 +2962,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.1" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.3", @@ -3048,9 +3048,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.13" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d04b7d0ee6b4a0207a0a7adb104d23ecb0b47d6beae7152d0fa34b692b29fd6" +checksum = "7251471db004e509f4e75a62cca9435365b5ec7bcdff530d612ac7c87c44a792" dependencies = [ "bitflags", ] @@ -3245,7 +3245,7 @@ name = "rustc_abi" version = "0.0.0" dependencies = [ "bitflags", - "rand 0.9.1", + "rand 0.9.2", "rand_xoshiro", "rustc_data_structures", "rustc_hashes", @@ -3880,7 +3880,7 @@ dependencies = [ name = "rustc_incremental" version = "0.0.0" dependencies = [ - "rand 0.9.1", + "rand 0.9.2", "rustc_ast", "rustc_data_structures", "rustc_errors", @@ -4493,7 +4493,7 @@ dependencies = [ "bitflags", "getopts", "libc", - "rand 0.9.1", + "rand 0.9.2", "rustc_abi", "rustc_ast", "rustc_data_structures", @@ -4578,7 +4578,7 @@ dependencies = [ "crossbeam-deque", "crossbeam-utils", "libc", - "rand 0.9.1", + "rand 0.9.2", "rand_xorshift", "scoped-tls", "smallvec", @@ -5284,7 +5284,7 @@ version = "0.1.0" dependencies = [ "indicatif", "num", - "rand 0.9.1", + "rand 0.9.2", "rand_chacha 0.9.0", "rayon", ] diff --git a/library/Cargo.lock b/library/Cargo.lock index 94720397fdfe..a9a611fe1ed5 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -237,9 +237,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.1" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" dependencies = [ "rand_core", ] diff --git a/src/tools/rustbook/Cargo.lock b/src/tools/rustbook/Cargo.lock index e363668d4620..5f30c75732c7 100644 --- a/src/tools/rustbook/Cargo.lock +++ b/src/tools/rustbook/Cargo.lock @@ -1343,9 +1343,9 @@ checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" [[package]] name = "redox_syscall" -version = "0.5.13" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d04b7d0ee6b4a0207a0a7adb104d23ecb0b47d6beae7152d0fa34b692b29fd6" +checksum = "7251471db004e509f4e75a62cca9435365b5ec7bcdff530d612ac7c87c44a792" dependencies = [ "bitflags 2.9.1", ] From 474315828b5a6eca321b2e2816829ccd530b210b Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Sat, 26 Jul 2025 16:51:58 -0500 Subject: [PATCH 178/809] 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 179/809] 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 180/809] 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 3d3534d179ecd1d1a8bbaa4aad5488db67c4242d Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Sun, 27 Jul 2025 12:13:45 +0530 Subject: [PATCH 181/809] add download context --- src/bootstrap/src/core/download.rs | 37 ++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index 373fcd52052e..19adfab3f367 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -852,6 +852,43 @@ download-rustc = false } } +/// Only should be used for pre config initialization downloads. +pub(crate) struct DownloadContext<'a> { + host_target: TargetSelection, + out: &'a Path, + patch_binaries_for_nix: Option, + exec_ctx: &'a ExecutionContext, + verbose: bool, + stage0_metadata: &'a build_helper::stage0_parser::Stage0, + llvm_assertions: bool, + bootstrap_cache_path: &'a Option, + is_running_on_ci: bool, + dry_run: bool, +} + +impl<'a> AsRef> for DownloadContext<'a> { + fn as_ref(&self) -> &DownloadContext<'a> { + self + } +} + +impl<'a> From<&'a Config> for DownloadContext<'a> { + fn from(value: &'a Config) -> Self { + DownloadContext { + host_target: value.host_target, + out: &value.out, + patch_binaries_for_nix: value.patch_binaries_for_nix, + exec_ctx: &value.exec_ctx, + verbose: value.verbose > 0, + stage0_metadata: &value.stage0_metadata, + llvm_assertions: value.llvm_assertions, + bootstrap_cache_path: &value.bootstrap_cache_path, + is_running_on_ci: value.is_running_on_ci, + dry_run: value.dry_run(), + } + } +} + fn path_is_dylib(path: &Path) -> bool { // The .so is not necessarily the extension, it might be libLLVM.so.18.1 path.to_str().is_some_and(|path| path.contains(".so")) From 861de92f947d9431f641afc2d589b366521f091d Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Sun, 27 Jul 2025 12:15:08 +0530 Subject: [PATCH 182/809] move utility methods out of config impl --- src/bootstrap/src/core/download.rs | 979 +++++++++++++++-------------- 1 file changed, 518 insertions(+), 461 deletions(-) diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index 19adfab3f367..f3a10048b655 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -7,9 +7,9 @@ use std::sync::OnceLock; use xz2::bufread::XzDecoder; -use crate::core::config::BUILDER_CONFIG_FILENAME; +use crate::core::config::{BUILDER_CONFIG_FILENAME, TargetSelection}; use crate::utils::build_stamp::BuildStamp; -use crate::utils::exec::command; +use crate::utils::exec::{ExecutionContext, command}; use crate::utils::helpers::{exe, hex_encode, move_file}; use crate::{Config, t}; @@ -24,17 +24,6 @@ fn extract_curl_version(out: String) -> semver::Version { .unwrap_or(semver::Version::new(1, 0, 0)) } -fn curl_version(config: &Config) -> semver::Version { - let mut curl = command("curl"); - curl.arg("-V"); - let curl = curl.run_capture_stdout(config); - if curl.is_failure() { - return semver::Version::new(1, 0, 0); - } - let output = curl.stdout(); - extract_curl_version(output) -} - /// Generic helpers that are useful anywhere in bootstrap. impl Config { pub fn is_verbose(&self) -> bool { @@ -49,10 +38,7 @@ impl Config { } pub(crate) fn remove(&self, f: &Path) { - if self.dry_run() { - return; - } - fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}")); + remove(self.dry_run(), f); } /// Create a temporary directory in `out` and return its path. @@ -68,49 +54,7 @@ impl Config { /// Whether or not `fix_bin_or_dylib` needs to be run; can only be true /// on NixOS fn should_fix_bins_and_dylibs(&self) -> bool { - let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| { - let uname = command("uname").allow_failure().arg("-s").run_capture_stdout(self); - if uname.is_failure() { - return false; - } - let output = uname.stdout(); - if !output.starts_with("Linux") { - return false; - } - // If the user has asked binaries to be patched for Nix, then - // don't check for NixOS or `/lib`. - // NOTE: this intentionally comes after the Linux check: - // - patchelf only works with ELF files, so no need to run it on Mac or Windows - // - On other Unix systems, there is no stable syscall interface, so Nix doesn't manage the global libc. - if let Some(explicit_value) = self.patch_binaries_for_nix { - return explicit_value; - } - - // Use `/etc/os-release` instead of `/etc/NIXOS`. - // The latter one does not exist on NixOS when using tmpfs as root. - let is_nixos = match File::open("/etc/os-release") { - Err(e) if e.kind() == ErrorKind::NotFound => false, - Err(e) => panic!("failed to access /etc/os-release: {e}"), - Ok(os_release) => BufReader::new(os_release).lines().any(|l| { - let l = l.expect("reading /etc/os-release"); - matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"") - }), - }; - if !is_nixos { - let in_nix_shell = env::var("IN_NIX_SHELL"); - if let Ok(in_nix_shell) = in_nix_shell { - eprintln!( - "The IN_NIX_SHELL environment variable is `{in_nix_shell}`; \ - you may need to set `patch-binaries-for-nix=true` in bootstrap.toml" - ); - } - } - is_nixos - }); - if val { - eprintln!("INFO: You seem to be using Nix."); - } - val + should_fix_bins_and_dylibs(self.patch_binaries_for_nix, &self.exec_ctx) } /// Modifies the interpreter section of 'fname' to fix the dynamic linker, @@ -121,259 +65,22 @@ impl Config { /// /// Please see for more information fn fix_bin_or_dylib(&self, fname: &Path) { - assert_eq!(SHOULD_FIX_BINS_AND_DYLIBS.get(), Some(&true)); - println!("attempting to patch {}", fname.display()); - - // Only build `.nix-deps` once. - static NIX_DEPS_DIR: OnceLock = OnceLock::new(); - let mut nix_build_succeeded = true; - let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| { - // Run `nix-build` to "build" each dependency (which will likely reuse - // the existing `/nix/store` copy, or at most download a pre-built copy). - // - // Importantly, we create a gc-root called `.nix-deps` in the `build/` - // directory, but still reference the actual `/nix/store` path in the rpath - // as it makes it significantly more robust against changes to the location of - // the `.nix-deps` location. - // - // bintools: Needed for the path of `ld-linux.so` (via `nix-support/dynamic-linker`). - // zlib: Needed as a system dependency of `libLLVM-*.so`. - // patchelf: Needed for patching ELF binaries (see doc comment above). - let nix_deps_dir = self.out.join(".nix-deps"); - const NIX_EXPR: &str = " - with (import {}); - symlinkJoin { - name = \"rust-stage0-dependencies\"; - paths = [ - zlib - patchelf - stdenv.cc.bintools - ]; - } - "; - nix_build_succeeded = command("nix-build") - .allow_failure() - .args([Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir]) - .run_capture_stdout(self) - .is_success(); - nix_deps_dir - }); - if !nix_build_succeeded { - return; - } - - let mut patchelf = command(nix_deps_dir.join("bin/patchelf")); - patchelf.args(&[ - OsString::from("--add-rpath"), - OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")), - ]); - if !path_is_dylib(fname) { - // Finally, set the correct .interp for binaries - let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker"); - let dynamic_linker = t!(fs::read_to_string(dynamic_linker_path)); - patchelf.args(["--set-interpreter", dynamic_linker.trim_end()]); - } - patchelf.arg(fname); - let _ = patchelf.allow_failure().run_capture_stdout(self); + fix_bin_or_dylib(&self.out, fname, &self.exec_ctx); } fn download_file(&self, url: &str, dest_path: &Path, help_on_error: &str) { - self.verbose(|| println!("download {url}")); - // Use a temporary file in case we crash while downloading, to avoid a corrupt download in cache/. - let tempfile = self.tempdir().join(dest_path.file_name().unwrap()); - // While bootstrap itself only supports http and https downloads, downstream forks might - // need to download components from other protocols. The match allows them adding more - // protocols without worrying about merge conflicts if we change the HTTP implementation. - match url.split_once("://").map(|(proto, _)| proto) { - Some("http") | Some("https") => { - self.download_http_with_retries(&tempfile, url, help_on_error) - } - Some(other) => panic!("unsupported protocol {other} in {url}"), - None => panic!("no protocol in {url}"), - } - t!( - move_file(&tempfile, dest_path), - format!("failed to rename {tempfile:?} to {dest_path:?}") - ); - } - - fn download_http_with_retries(&self, tempfile: &Path, url: &str, help_on_error: &str) { - println!("downloading {url}"); - // Try curl. If that fails and we are on windows, fallback to PowerShell. - // options should be kept in sync with - // src/bootstrap/src/core/download.rs - // for consistency - let mut curl = command("curl").allow_failure(); - curl.args([ - // follow redirect - "--location", - // timeout if speed is < 10 bytes/sec for > 30 seconds - "--speed-time", - "30", - "--speed-limit", - "10", - // timeout if cannot connect within 30 seconds - "--connect-timeout", - "30", - // output file - "--output", - tempfile.to_str().unwrap(), - // if there is an error, don't restart the download, - // instead continue where it left off. - "--continue-at", - "-", - // retry up to 3 times. note that this means a maximum of 4 - // attempts will be made, since the first attempt isn't a *re*try. - "--retry", - "3", - // show errors, even if --silent is specified - "--show-error", - // set timestamp of downloaded file to that of the server - "--remote-time", - // fail on non-ok http status - "--fail", - ]); - // Don't print progress in CI; the \r wrapping looks bad and downloads don't take long enough for progress to be useful. - if self.is_running_on_ci { - curl.arg("--silent"); - } else { - curl.arg("--progress-bar"); - } - // --retry-all-errors was added in 7.71.0, don't use it if curl is old. - if curl_version(self) >= semver::Version::new(7, 71, 0) { - curl.arg("--retry-all-errors"); - } - curl.arg(url); - if !curl.run(self) { - if self.host_target.contains("windows-msvc") { - eprintln!("Fallback to PowerShell"); - for _ in 0..3 { - let powershell = command("PowerShell.exe").allow_failure().args([ - "/nologo", - "-Command", - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;", - &format!( - "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')", - url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"), - ), - ]).run_capture_stdout(self); - - if powershell.is_failure() { - return; - } - - eprintln!("\nspurious failure, trying again"); - } - } - if !help_on_error.is_empty() { - eprintln!("{help_on_error}"); - } - crate::exit!(1); - } + let dwn_ctx: DownloadContext<'_> = self.into(); + download_file(dwn_ctx, url, dest_path, help_on_error); } fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) { - eprintln!("extracting {} to {}", tarball.display(), dst.display()); - if !dst.exists() { - t!(fs::create_dir_all(dst)); - } - - // `tarball` ends with `.tar.xz`; strip that suffix - // example: `rust-dev-nightly-x86_64-unknown-linux-gnu` - let uncompressed_filename = - Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap(); - let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap()); - - // decompress the file - let data = t!(File::open(tarball), format!("file {} not found", tarball.display())); - let decompressor = XzDecoder::new(BufReader::new(data)); - - let mut tar = tar::Archive::new(decompressor); - - let is_ci_rustc = dst.ends_with("ci-rustc"); - let is_ci_llvm = dst.ends_with("ci-llvm"); - - // `compile::Sysroot` needs to know the contents of the `rustc-dev` tarball to avoid adding - // it to the sysroot unless it was explicitly requested. But parsing the 100 MB tarball is slow. - // Cache the entries when we extract it so we only have to read it once. - let mut recorded_entries = if is_ci_rustc { recorded_entries(dst, pattern) } else { None }; - - for member in t!(tar.entries()) { - let mut member = t!(member); - let original_path = t!(member.path()).into_owned(); - // skip the top-level directory - if original_path == directory_prefix { - continue; - } - let mut short_path = t!(original_path.strip_prefix(directory_prefix)); - let is_builder_config = short_path.to_str() == Some(BUILDER_CONFIG_FILENAME); - - if !(short_path.starts_with(pattern) - || ((is_ci_rustc || is_ci_llvm) && is_builder_config)) - { - continue; - } - short_path = short_path.strip_prefix(pattern).unwrap_or(short_path); - let dst_path = dst.join(short_path); - self.verbose(|| { - println!("extracting {} to {}", original_path.display(), dst.display()) - }); - if !t!(member.unpack_in(dst)) { - panic!("path traversal attack ??"); - } - if let Some(record) = &mut recorded_entries { - t!(writeln!(record, "{}", short_path.to_str().unwrap())); - } - let src_path = dst.join(original_path); - if src_path.is_dir() && dst_path.exists() { - continue; - } - t!(move_file(src_path, dst_path)); - } - let dst_dir = dst.join(directory_prefix); - if dst_dir.exists() { - t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display())); - } + unpack(self.verbose > 0, tarball, dst, pattern); } /// Returns whether the SHA256 checksum of `path` matches `expected`. + #[cfg(test)] pub(crate) fn verify(&self, path: &Path, expected: &str) -> bool { - use sha2::Digest; - - self.verbose(|| println!("verifying {}", path.display())); - - if self.dry_run() { - return false; - } - - let mut hasher = sha2::Sha256::new(); - - let file = t!(File::open(path)); - let mut reader = BufReader::new(file); - - loop { - let buffer = t!(reader.fill_buf()); - let l = buffer.len(); - // break if EOF - if l == 0 { - break; - } - hasher.update(buffer); - reader.consume(l); - } - - let checksum = hex_encode(hasher.finalize().as_slice()); - let verified = checksum == expected; - - if !verified { - println!( - "invalid checksum: \n\ - found: {checksum}\n\ - expected: {expected}", - ); - } - - verified + verify(self.verbose > 0, self.dry_run(), path, expected) } } @@ -388,6 +95,7 @@ fn recorded_entries(dst: &Path, pattern: &str) -> Option> { Some(BufWriter::new(t!(File::create(dst.join(name))))) } +#[derive(Clone)] enum DownloadSource { CI, Dist, @@ -420,61 +128,11 @@ impl Config { cargo_clippy } - #[cfg(test)] - pub(crate) fn maybe_download_rustfmt(&self) -> Option { - Some(PathBuf::new()) - } - /// NOTE: rustfmt is a completely different toolchain than the bootstrap compiler, so it can't /// reuse target directories or artifacts - #[cfg(not(test))] pub(crate) fn maybe_download_rustfmt(&self) -> Option { - use build_helper::stage0_parser::VersionMetadata; - - if self.dry_run() { - return Some(PathBuf::new()); - } - - let VersionMetadata { date, version } = self.stage0_metadata.rustfmt.as_ref()?; - let channel = format!("{version}-{date}"); - - let host = self.host_target; - let bin_root = self.out.join(host).join("rustfmt"); - let rustfmt_path = bin_root.join("bin").join(exe("rustfmt", host)); - let rustfmt_stamp = BuildStamp::new(&bin_root).with_prefix("rustfmt").add_stamp(channel); - if rustfmt_path.exists() && rustfmt_stamp.is_up_to_date() { - return Some(rustfmt_path); - } - - self.download_component( - DownloadSource::Dist, - format!("rustfmt-{version}-{build}.tar.xz", build = host.triple), - "rustfmt-preview", - date, - "rustfmt", - ); - self.download_component( - DownloadSource::Dist, - format!("rustc-{version}-{build}.tar.xz", build = host.triple), - "rustc", - date, - "rustfmt", - ); - - if self.should_fix_bins_and_dylibs() { - self.fix_bin_or_dylib(&bin_root.join("bin").join("rustfmt")); - self.fix_bin_or_dylib(&bin_root.join("bin").join("cargo-fmt")); - let lib_dir = bin_root.join("lib"); - for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) { - let lib = t!(lib); - if path_is_dylib(&lib.path()) { - self.fix_bin_or_dylib(&lib.path()); - } - } - } - - t!(rustfmt_stamp.write()); - Some(rustfmt_path) + let dwn_ctx: DownloadContext<'_> = self.into(); + maybe_download_rustfmt(dwn_ctx) } pub(crate) fn ci_rust_std_contents(&self) -> Vec { @@ -514,28 +172,9 @@ impl Config { ); } - #[cfg(test)] - pub(crate) fn download_beta_toolchain(&self) {} - - #[cfg(not(test))] pub(crate) fn download_beta_toolchain(&self) { - self.verbose(|| println!("downloading stage0 beta artifacts")); - - let date = &self.stage0_metadata.compiler.date; - let version = &self.stage0_metadata.compiler.version; - let extra_components = ["cargo"]; - - let download_beta_component = |config: &Config, filename, prefix: &_, date: &_| { - config.download_component(DownloadSource::Dist, filename, prefix, date, "stage0") - }; - - self.download_toolchain( - version, - "stage0", - date, - &extra_components, - download_beta_component, - ); + let dwn_ctx: DownloadContext<'_> = self.into(); + download_beta_toolchain(dwn_ctx); } fn download_toolchain( @@ -607,91 +246,8 @@ impl Config { key: &str, destination: &str, ) { - if self.dry_run() { - return; - } - - let cache_dst = - self.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| self.out.join("cache")); - - let cache_dir = cache_dst.join(key); - if !cache_dir.exists() { - t!(fs::create_dir_all(&cache_dir)); - } - - let bin_root = self.out.join(self.host_target).join(destination); - let tarball = cache_dir.join(&filename); - let (base_url, url, should_verify) = match mode { - DownloadSource::CI => { - let dist_server = if self.llvm_assertions { - self.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone() - } else { - self.stage0_metadata.config.artifacts_server.clone() - }; - let url = format!( - "{}/{filename}", - key.strip_suffix(&format!("-{}", self.llvm_assertions)).unwrap() - ); - (dist_server, url, false) - } - DownloadSource::Dist => { - let dist_server = env::var("RUSTUP_DIST_SERVER") - .unwrap_or(self.stage0_metadata.config.dist_server.to_string()); - // NOTE: make `dist` part of the URL because that's how it's stored in src/stage0 - (dist_server, format!("dist/{key}/{filename}"), true) - } - }; - - // For the stage0 compiler, put special effort into ensuring the checksums are valid. - let checksum = if should_verify { - let error = format!( - "src/stage0 doesn't contain a checksum for {url}. \ - Pre-built artifacts might not be available for this \ - target at this time, see https://doc.rust-lang.org/nightly\ - /rustc/platform-support.html for more information." - ); - let sha256 = self.stage0_metadata.checksums_sha256.get(&url).expect(&error); - if tarball.exists() { - if self.verify(&tarball, sha256) { - self.unpack(&tarball, &bin_root, prefix); - return; - } else { - self.verbose(|| { - println!( - "ignoring cached file {} due to failed verification", - tarball.display() - ) - }); - self.remove(&tarball); - } - } - Some(sha256) - } else if tarball.exists() { - self.unpack(&tarball, &bin_root, prefix); - return; - } else { - None - }; - - let mut help_on_error = ""; - if destination == "ci-rustc" { - help_on_error = "ERROR: failed to download pre-built rustc from CI - -NOTE: old builds get deleted after a certain time -HELP: if trying to compile an old commit of rustc, disable `download-rustc` in bootstrap.toml: - -[rust] -download-rustc = false -"; - } - self.download_file(&format!("{base_url}/{url}"), &tarball, help_on_error); - if let Some(sha256) = checksum - && !self.verify(&tarball, sha256) - { - panic!("failed to verify {}", tarball.display()); - } - - self.unpack(&tarball, &bin_root, prefix); + let dwn_ctx: DownloadContext<'_> = self.into(); + download_component(dwn_ctx, mode, filename, prefix, key, destination); } #[cfg(test)] @@ -934,3 +490,504 @@ pub(crate) fn is_download_ci_available(target_triple: &str, llvm_assertions: boo SUPPORTED_PLATFORMS.contains(&target_triple) } } + +fn download_toolchain<'a>( + dwn_ctx: impl AsRef>, + version: &str, + sysroot: &str, + stamp_key: &str, + extra_components: &[&str], + destination: &str, + mode: DownloadSource, +) { + let dwn_ctx = dwn_ctx.as_ref(); + let host = dwn_ctx.host_target.triple; + let bin_root = dwn_ctx.out.join(host).join(sysroot); + let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key); + + if !bin_root.join("bin").join(exe("rustc", dwn_ctx.host_target)).exists() + || !rustc_stamp.is_up_to_date() + { + if bin_root.exists() { + t!(fs::remove_dir_all(&bin_root)); + } + let filename = format!("rust-std-{version}-{host}.tar.xz"); + let pattern = format!("rust-std-{host}"); + download_component(dwn_ctx, mode.clone(), filename, &pattern, stamp_key, destination); + let filename = format!("rustc-{version}-{host}.tar.xz"); + download_component(dwn_ctx, mode.clone(), filename, "rustc", stamp_key, destination); + + for component in extra_components { + let filename = format!("{component}-{version}-{host}.tar.xz"); + download_component(dwn_ctx, mode.clone(), filename, component, stamp_key, destination); + } + + if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) { + fix_bin_or_dylib(dwn_ctx.out, &bin_root.join("bin").join("rustc"), dwn_ctx.exec_ctx); + fix_bin_or_dylib(dwn_ctx.out, &bin_root.join("bin").join("rustdoc"), dwn_ctx.exec_ctx); + fix_bin_or_dylib( + dwn_ctx.out, + &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"), + dwn_ctx.exec_ctx, + ); + let lib_dir = bin_root.join("lib"); + for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) { + let lib = t!(lib); + if path_is_dylib(&lib.path()) { + fix_bin_or_dylib(dwn_ctx.out, &lib.path(), dwn_ctx.exec_ctx); + } + } + } + + t!(rustc_stamp.write()); + } +} + +pub(crate) fn remove(dry_run: bool, f: &Path) { + if dry_run { + return; + } + fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}")); +} + +fn fix_bin_or_dylib(out: &Path, fname: &Path, exec_ctx: &ExecutionContext) { + assert_eq!(SHOULD_FIX_BINS_AND_DYLIBS.get(), Some(&true)); + println!("attempting to patch {}", fname.display()); + + // Only build `.nix-deps` once. + static NIX_DEPS_DIR: OnceLock = OnceLock::new(); + let mut nix_build_succeeded = true; + let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| { + // Run `nix-build` to "build" each dependency (which will likely reuse + // the existing `/nix/store` copy, or at most download a pre-built copy). + // + // Importantly, we create a gc-root called `.nix-deps` in the `build/` + // directory, but still reference the actual `/nix/store` path in the rpath + // as it makes it significantly more robust against changes to the location of + // the `.nix-deps` location. + // + // bintools: Needed for the path of `ld-linux.so` (via `nix-support/dynamic-linker`). + // zlib: Needed as a system dependency of `libLLVM-*.so`. + // patchelf: Needed for patching ELF binaries (see doc comment above). + let nix_deps_dir = out.join(".nix-deps"); + const NIX_EXPR: &str = " + with (import {}); + symlinkJoin { + name = \"rust-stage0-dependencies\"; + paths = [ + zlib + patchelf + stdenv.cc.bintools + ]; + } + "; + nix_build_succeeded = command("nix-build") + .allow_failure() + .args([Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir]) + .run_capture_stdout(exec_ctx) + .is_success(); + nix_deps_dir + }); + if !nix_build_succeeded { + return; + } + + let mut patchelf = command(nix_deps_dir.join("bin/patchelf")); + patchelf.args(&[ + OsString::from("--add-rpath"), + OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")), + ]); + if !path_is_dylib(fname) { + // Finally, set the correct .interp for binaries + let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker"); + let dynamic_linker = t!(fs::read_to_string(dynamic_linker_path)); + patchelf.args(["--set-interpreter", dynamic_linker.trim_end()]); + } + patchelf.arg(fname); + let _ = patchelf.allow_failure().run_capture_stdout(exec_ctx); +} + +fn should_fix_bins_and_dylibs( + patch_binaries_for_nix: Option, + exec_ctx: &ExecutionContext, +) -> bool { + let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| { + let uname = command("uname").allow_failure().arg("-s").run_capture_stdout(exec_ctx); + if uname.is_failure() { + return false; + } + let output = uname.stdout(); + if !output.starts_with("Linux") { + return false; + } + // If the user has asked binaries to be patched for Nix, then + // don't check for NixOS or `/lib`. + // NOTE: this intentionally comes after the Linux check: + // - patchelf only works with ELF files, so no need to run it on Mac or Windows + // - On other Unix systems, there is no stable syscall interface, so Nix doesn't manage the global libc. + if let Some(explicit_value) = patch_binaries_for_nix { + return explicit_value; + } + + // Use `/etc/os-release` instead of `/etc/NIXOS`. + // The latter one does not exist on NixOS when using tmpfs as root. + let is_nixos = match File::open("/etc/os-release") { + Err(e) if e.kind() == ErrorKind::NotFound => false, + Err(e) => panic!("failed to access /etc/os-release: {e}"), + Ok(os_release) => BufReader::new(os_release).lines().any(|l| { + let l = l.expect("reading /etc/os-release"); + matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"") + }), + }; + if !is_nixos { + let in_nix_shell = env::var("IN_NIX_SHELL"); + if let Ok(in_nix_shell) = in_nix_shell { + eprintln!( + "The IN_NIX_SHELL environment variable is `{in_nix_shell}`; \ + you may need to set `patch-binaries-for-nix=true` in bootstrap.toml" + ); + } + } + is_nixos + }); + if val { + eprintln!("INFO: You seem to be using Nix."); + } + val +} + +fn download_component<'a>( + dwn_ctx: impl AsRef>, + mode: DownloadSource, + filename: String, + prefix: &str, + key: &str, + destination: &str, +) { + let dwn_ctx = dwn_ctx.as_ref(); + + if dwn_ctx.dry_run { + return; + } + + let cache_dst = + dwn_ctx.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| dwn_ctx.out.join("cache")); + + let cache_dir = cache_dst.join(key); + if !cache_dir.exists() { + t!(fs::create_dir_all(&cache_dir)); + } + + let bin_root = dwn_ctx.out.join(dwn_ctx.host_target).join(destination); + let tarball = cache_dir.join(&filename); + let (base_url, url, should_verify) = match mode { + DownloadSource::CI => { + let dist_server = if dwn_ctx.llvm_assertions { + dwn_ctx.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone() + } else { + dwn_ctx.stage0_metadata.config.artifacts_server.clone() + }; + let url = format!( + "{}/{filename}", + key.strip_suffix(&format!("-{}", dwn_ctx.llvm_assertions)).unwrap() + ); + (dist_server, url, false) + } + DownloadSource::Dist => { + let dist_server = env::var("RUSTUP_DIST_SERVER") + .unwrap_or(dwn_ctx.stage0_metadata.config.dist_server.to_string()); + // NOTE: make `dist` part of the URL because that's how it's stored in src/stage0 + (dist_server, format!("dist/{key}/{filename}"), true) + } + }; + + // For the stage0 compiler, put special effort into ensuring the checksums are valid. + let checksum = if should_verify { + let error = format!( + "src/stage0 doesn't contain a checksum for {url}. \ + Pre-built artifacts might not be available for this \ + target at this time, see https://doc.rust-lang.org/nightly\ + /rustc/platform-support.html for more information." + ); + let sha256 = dwn_ctx.stage0_metadata.checksums_sha256.get(&url).expect(&error); + if tarball.exists() { + if verify(dwn_ctx.verbose, dwn_ctx.dry_run, &tarball, sha256) { + unpack(dwn_ctx.verbose, &tarball, &bin_root, prefix); + return; + } else { + if dwn_ctx.verbose { + println!( + "ignoring cached file {} due to failed verification", + tarball.display() + ) + } + remove(dwn_ctx.dry_run, &tarball); + } + } + Some(sha256) + } else if tarball.exists() { + unpack(dwn_ctx.verbose, &tarball, &bin_root, prefix); + return; + } else { + None + }; + + let mut help_on_error = ""; + if destination == "ci-rustc" { + help_on_error = "ERROR: failed to download pre-built rustc from CI + +NOTE: old builds get deleted after a certain time +HELP: if trying to compile an old commit of rustc, disable `download-rustc` in bootstrap.toml: + +[rust] +download-rustc = false +"; + } + download_file(dwn_ctx, &format!("{base_url}/{url}"), &tarball, help_on_error); + if let Some(sha256) = checksum + && !verify(dwn_ctx.verbose, dwn_ctx.dry_run, &tarball, sha256) + { + panic!("failed to verify {}", tarball.display()); + } + + unpack(dwn_ctx.verbose, &tarball, &bin_root, prefix); +} + +pub(crate) fn verify(verbose: bool, dry_run: bool, path: &Path, expected: &str) -> bool { + use sha2::Digest; + + if verbose { + println!("verifying {}", path.display()); + } + + if dry_run { + return false; + } + + let mut hasher = sha2::Sha256::new(); + + let file = t!(File::open(path)); + let mut reader = BufReader::new(file); + + loop { + let buffer = t!(reader.fill_buf()); + let l = buffer.len(); + // break if EOF + if l == 0 { + break; + } + hasher.update(buffer); + reader.consume(l); + } + + let checksum = hex_encode(hasher.finalize().as_slice()); + let verified = checksum == expected; + + if !verified { + println!( + "invalid checksum: \n\ + found: {checksum}\n\ + expected: {expected}", + ); + } + + verified +} + +fn unpack(verbose: bool, tarball: &Path, dst: &Path, pattern: &str) { + eprintln!("extracting {} to {}", tarball.display(), dst.display()); + if !dst.exists() { + t!(fs::create_dir_all(dst)); + } + + // `tarball` ends with `.tar.xz`; strip that suffix + // example: `rust-dev-nightly-x86_64-unknown-linux-gnu` + let uncompressed_filename = + Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap(); + let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap()); + + // decompress the file + let data = t!(File::open(tarball), format!("file {} not found", tarball.display())); + let decompressor = XzDecoder::new(BufReader::new(data)); + + let mut tar = tar::Archive::new(decompressor); + + let is_ci_rustc = dst.ends_with("ci-rustc"); + let is_ci_llvm = dst.ends_with("ci-llvm"); + + // `compile::Sysroot` needs to know the contents of the `rustc-dev` tarball to avoid adding + // it to the sysroot unless it was explicitly requested. But parsing the 100 MB tarball is slow. + // Cache the entries when we extract it so we only have to read it once. + let mut recorded_entries = if is_ci_rustc { recorded_entries(dst, pattern) } else { None }; + + for member in t!(tar.entries()) { + let mut member = t!(member); + let original_path = t!(member.path()).into_owned(); + // skip the top-level directory + if original_path == directory_prefix { + continue; + } + let mut short_path = t!(original_path.strip_prefix(directory_prefix)); + let is_builder_config = short_path.to_str() == Some(BUILDER_CONFIG_FILENAME); + + if !(short_path.starts_with(pattern) || ((is_ci_rustc || is_ci_llvm) && is_builder_config)) + { + continue; + } + short_path = short_path.strip_prefix(pattern).unwrap_or(short_path); + let dst_path = dst.join(short_path); + if verbose { + println!("extracting {} to {}", original_path.display(), dst.display()); + } + + if !t!(member.unpack_in(dst)) { + panic!("path traversal attack ??"); + } + if let Some(record) = &mut recorded_entries { + t!(writeln!(record, "{}", short_path.to_str().unwrap())); + } + let src_path = dst.join(original_path); + if src_path.is_dir() && dst_path.exists() { + continue; + } + t!(move_file(src_path, dst_path)); + } + let dst_dir = dst.join(directory_prefix); + if dst_dir.exists() { + t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display())); + } +} + +fn download_file<'a>( + dwn_ctx: impl AsRef>, + url: &str, + dest_path: &Path, + help_on_error: &str, +) { + let dwn_ctx = dwn_ctx.as_ref(); + + if dwn_ctx.verbose { + println!("download {url}"); + } + // Use a temporary file in case we crash while downloading, to avoid a corrupt download in cache/. + let tempfile = tempdir(dwn_ctx.out).join(dest_path.file_name().unwrap()); + // While bootstrap itself only supports http and https downloads, downstream forks might + // need to download components from other protocols. The match allows them adding more + // protocols without worrying about merge conflicts if we change the HTTP implementation. + match url.split_once("://").map(|(proto, _)| proto) { + Some("http") | Some("https") => download_http_with_retries( + dwn_ctx.host_target, + dwn_ctx.is_running_on_ci, + dwn_ctx.exec_ctx, + &tempfile, + url, + help_on_error, + ), + Some(other) => panic!("unsupported protocol {other} in {url}"), + None => panic!("no protocol in {url}"), + } + t!(move_file(&tempfile, dest_path), format!("failed to rename {tempfile:?} to {dest_path:?}")); +} + +/// Create a temporary directory in `out` and return its path. +/// +/// NOTE: this temporary directory is shared between all steps; +/// if you need an empty directory, create a new subdirectory inside it. +pub(crate) fn tempdir(out: &Path) -> PathBuf { + let tmp = out.join("tmp"); + t!(fs::create_dir_all(&tmp)); + tmp +} + +fn download_http_with_retries( + host_target: TargetSelection, + is_running_on_ci: bool, + exec_ctx: &ExecutionContext, + tempfile: &Path, + url: &str, + help_on_error: &str, +) { + println!("downloading {url}"); + // Try curl. If that fails and we are on windows, fallback to PowerShell. + // options should be kept in sync with + // src/bootstrap/src/core/download.rs + // for consistency + let mut curl = command("curl").allow_failure(); + curl.args([ + // follow redirect + "--location", + // timeout if speed is < 10 bytes/sec for > 30 seconds + "--speed-time", + "30", + "--speed-limit", + "10", + // timeout if cannot connect within 30 seconds + "--connect-timeout", + "30", + // output file + "--output", + tempfile.to_str().unwrap(), + // if there is an error, don't restart the download, + // instead continue where it left off. + "--continue-at", + "-", + // retry up to 3 times. note that this means a maximum of 4 + // attempts will be made, since the first attempt isn't a *re*try. + "--retry", + "3", + // show errors, even if --silent is specified + "--show-error", + // set timestamp of downloaded file to that of the server + "--remote-time", + // fail on non-ok http status + "--fail", + ]); + // Don't print progress in CI; the \r wrapping looks bad and downloads don't take long enough for progress to be useful. + if is_running_on_ci { + curl.arg("--silent"); + } else { + curl.arg("--progress-bar"); + } + // --retry-all-errors was added in 7.71.0, don't use it if curl is old. + if curl_version(exec_ctx) >= semver::Version::new(7, 71, 0) { + curl.arg("--retry-all-errors"); + } + curl.arg(url); + if !curl.run(exec_ctx) { + if host_target.contains("windows-msvc") { + eprintln!("Fallback to PowerShell"); + for _ in 0..3 { + let powershell = command("PowerShell.exe").allow_failure().args([ + "/nologo", + "-Command", + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;", + &format!( + "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')", + url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"), + ), + ]).run_capture_stdout(exec_ctx); + + if powershell.is_failure() { + return; + } + + eprintln!("\nspurious failure, trying again"); + } + } + if !help_on_error.is_empty() { + eprintln!("{help_on_error}"); + } + crate::exit!(1); + } +} + +fn curl_version(exec_ctx: &ExecutionContext) -> semver::Version { + let mut curl = command("curl"); + curl.arg("-V"); + let curl = curl.run_capture_stdout(exec_ctx); + if curl.is_failure() { + return semver::Version::new(1, 0, 0); + } + let output = curl.stdout(); + extract_curl_version(output) +} From 8facd063f93d5640790b200fca4454d2c76c5305 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Sun, 27 Jul 2025 12:16:03 +0530 Subject: [PATCH 183/809] move download_beta_toolchain out of impl as its used during config initialization --- src/bootstrap/src/core/download.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index f3a10048b655..7e4ae6ebd7e8 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -491,6 +491,31 @@ pub(crate) fn is_download_ci_available(target_triple: &str, llvm_assertions: boo } } +#[cfg(test)] +pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef>) {} + +#[cfg(not(test))] +pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef>) { + let dwn_ctx = dwn_ctx.as_ref(); + if dwn_ctx.verbose { + println!("downloading stage0 beta artifacts"); + } + + let date = dwn_ctx.stage0_metadata.compiler.date.clone(); + let version = dwn_ctx.stage0_metadata.compiler.version.clone(); + let extra_components = ["cargo"]; + let sysroot = "stage0"; + download_toolchain( + dwn_ctx, + &version, + sysroot, + &date, + &extra_components, + "stage0", + DownloadSource::Dist, + ); +} + fn download_toolchain<'a>( dwn_ctx: impl AsRef>, version: &str, From 19dc195ac2db97874020a423e690d1edf7f1d8fe Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Sun, 27 Jul 2025 12:17:11 +0530 Subject: [PATCH 184/809] move download_rustfmt out of impl as its used during config initialization --- src/bootstrap/src/core/download.rs | 66 ++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index 7e4ae6ebd7e8..745acb04275a 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -491,6 +491,72 @@ pub(crate) fn is_download_ci_available(target_triple: &str, llvm_assertions: boo } } +#[cfg(test)] +pub(crate) fn maybe_download_rustfmt<'a>( + dwn_ctx: impl AsRef>, +) -> Option { + Some(PathBuf::new()) +} + +/// NOTE: rustfmt is a completely different toolchain than the bootstrap compiler, so it can't +/// reuse target directories or artifacts +#[cfg(not(test))] +pub(crate) fn maybe_download_rustfmt<'a>( + dwn_ctx: impl AsRef>, +) -> Option { + use build_helper::stage0_parser::VersionMetadata; + + let dwn_ctx = dwn_ctx.as_ref(); + + if dwn_ctx.dry_run { + return Some(PathBuf::new()); + } + + let VersionMetadata { date, version } = dwn_ctx.stage0_metadata.rustfmt.as_ref()?; + let channel = format!("{version}-{date}"); + + let host = dwn_ctx.host_target; + let bin_root = dwn_ctx.out.join(host).join("rustfmt"); + let rustfmt_path = bin_root.join("bin").join(exe("rustfmt", host)); + let rustfmt_stamp = BuildStamp::new(&bin_root).with_prefix("rustfmt").add_stamp(channel); + if rustfmt_path.exists() && rustfmt_stamp.is_up_to_date() { + return Some(rustfmt_path); + } + + download_component( + dwn_ctx, + DownloadSource::Dist, + format!("rustfmt-{version}-{build}.tar.xz", build = host.triple), + "rustfmt-preview", + date, + "rustfmt", + ); + + download_component( + dwn_ctx, + DownloadSource::Dist, + format!("rustc-{version}-{build}.tar.xz", build = host.triple), + "rustc", + date, + "rustfmt", + ); + + if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) { + fix_bin_or_dylib(dwn_ctx.out, &bin_root.join("bin").join("rustfmt"), dwn_ctx.exec_ctx); + fix_bin_or_dylib(dwn_ctx.out, &bin_root.join("bin").join("cargo-fmt"), dwn_ctx.exec_ctx); + let lib_dir = bin_root.join("lib"); + for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) { + let lib = t!(lib); + if path_is_dylib(&lib.path()) { + fix_bin_or_dylib(dwn_ctx.out, &lib.path(), dwn_ctx.exec_ctx); + } + } + } + + t!(rustfmt_stamp.write()); + Some(rustfmt_path) +} + #[cfg(test)] pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef>) {} From c78f3aedfc262c95b08d944c878976dcc133dcf3 Mon Sep 17 00:00:00 2001 From: yanglsh Date: Sun, 27 Jul 2025 15:13:34 +0800 Subject: [PATCH 185/809] 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 23e294262bb5a03eb12ae9d0724c7efdc4516b17 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 27 Jul 2025 12:13:24 +0200 Subject: [PATCH 186/809] call_function helper: dont ICE on return type mismatches --- src/tools/miri/src/helpers.rs | 5 ++- .../tests/fail/shims/ctor_wrong_ret_type.rs | 39 +++++++++++++++++++ .../fail/shims/ctor_wrong_ret_type.stderr | 12 ++++++ 3 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 src/tools/miri/tests/fail/shims/ctor_wrong_ret_type.rs create mode 100644 src/tools/miri/tests/fail/shims/ctor_wrong_ret_type.stderr diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index 6e80bc5da9eb..53e4e5c4c533 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -437,7 +437,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// For now, arguments must be scalars (so that the caller does not have to know the layout). /// /// If you do not provide a return place, a dangling zero-sized place will be created - /// for your convenience. + /// for your convenience. This is only valid if the return type is `()`. fn call_function( &mut self, f: ty::Instance<'tcx>, @@ -452,7 +452,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let mir = this.load_mir(f.def, None)?; let dest = match dest { Some(dest) => dest.clone(), - None => MPlaceTy::fake_alloc_zst(this.layout_of(mir.return_ty())?), + None => MPlaceTy::fake_alloc_zst(this.machine.layouts.unit), }; // Construct a function pointer type representing the caller perspective. @@ -465,6 +465,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ); let caller_fn_abi = this.fn_abi_of_fn_ptr(ty::Binder::dummy(sig), ty::List::empty())?; + // This will also show proper errors if there is any ABI mismatch. this.init_stack_frame( f, mir, diff --git a/src/tools/miri/tests/fail/shims/ctor_wrong_ret_type.rs b/src/tools/miri/tests/fail/shims/ctor_wrong_ret_type.rs new file mode 100644 index 000000000000..1e10f682e71e --- /dev/null +++ b/src/tools/miri/tests/fail/shims/ctor_wrong_ret_type.rs @@ -0,0 +1,39 @@ +unsafe extern "C" fn ctor() -> i32 { + //~^ERROR: calling a function with return type i32 passing return place of type () + 0 +} + +#[rustfmt::skip] +macro_rules! ctor { + ($ident:ident = $ctor:ident) => { + #[cfg_attr( + all(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "haiku", + target_os = "illumos", + target_os = "netbsd", + target_os = "openbsd", + target_os = "solaris", + target_os = "none", + target_family = "wasm", + )), + link_section = ".init_array" + )] + #[cfg_attr(windows, link_section = ".CRT$XCU")] + #[cfg_attr( + any(target_os = "macos", target_os = "ios"), + // We do not set the `mod_init_funcs` flag here since ctor/inventory also do not do + // that. See . + link_section = "__DATA,__mod_init_func" + )] + #[used] + static $ident: unsafe extern "C" fn() -> i32 = $ctor; + }; +} + +ctor! { CTOR = ctor } + +fn main() {} diff --git a/src/tools/miri/tests/fail/shims/ctor_wrong_ret_type.stderr b/src/tools/miri/tests/fail/shims/ctor_wrong_ret_type.stderr new file mode 100644 index 000000000000..664bfbd32db2 --- /dev/null +++ b/src/tools/miri/tests/fail/shims/ctor_wrong_ret_type.stderr @@ -0,0 +1,12 @@ +error: Undefined Behavior: calling a function with return type i32 passing return place of type () + | + = note: Undefined Behavior occurred here + = note: (no span available) + = 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 + = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets + = help: if you think this code should be accepted anyway, please report an issue with Miri + = note: BACKTRACE: + +error: aborting due to 1 previous error + From 49eda8edd5c99e4c65c687fff0b8e194eb339a23 Mon Sep 17 00:00:00 2001 From: godzie44 Date: Thu, 24 Jul 2025 16:30:22 +0300 Subject: [PATCH 187/809] fix(debuginfo): disable overflow check for recursive non-enum types --- .../src/debuginfo/metadata/type_map.rs | 4 +-- .../debuginfo-cyclic-structure.rs | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 tests/codegen-llvm/debuginfo-cyclic-structure.rs diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs index 56fb12d3c22e..d1502d2b1e62 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs @@ -285,8 +285,8 @@ pub(super) fn build_type_with_children<'ll, 'tcx>( // Item(T), // } // ``` - let is_expanding_recursive = - debug_context(cx).adt_stack.borrow().iter().any(|(parent_def_id, parent_args)| { + let is_expanding_recursive = adt_def.is_enum() + && debug_context(cx).adt_stack.borrow().iter().any(|(parent_def_id, parent_args)| { if def_id == *parent_def_id { args.iter().zip(parent_args.iter()).any(|(arg, parent_arg)| { if let (Some(arg), Some(parent_arg)) = (arg.as_type(), parent_arg.as_type()) diff --git a/tests/codegen-llvm/debuginfo-cyclic-structure.rs b/tests/codegen-llvm/debuginfo-cyclic-structure.rs new file mode 100644 index 000000000000..b8cc54477415 --- /dev/null +++ b/tests/codegen-llvm/debuginfo-cyclic-structure.rs @@ -0,0 +1,32 @@ +//@ compile-flags:-g -Copt-level=0 -C panic=abort + +// Check that debug information exists for structures containing loops (cyclic references). +// Previously it may incorrectly prune member information during recursive type inference check. + +// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Arc { + buffer: Box>, +} +struct Shared { + shared: Arc>>, +} +struct Handle { + shared: Shared, +} +struct Core { + inner: Arc>>, +} + +#[no_mangle] +extern "C" fn test() { + let с = Core { inner: Arc::new(Inner { buffer: Box::new(MaybeUninit::uninit()) }) }; + std::hint::black_box(с); +} From 24e2b4832bfa0bf1b60159af0ae11b15de55590e Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 27 Jul 2025 21:19:07 +1000 Subject: [PATCH 188/809] coverage: Infer `instances_used` from `pgo_func_name_var_map` In obscure circumstances, we would sometimes emit a covfun record for a function with no physical coverage counters, causing `llvm-cov` to fail with the cryptic error message: malformed instrumentation profile data: function name is empty We can eliminate this mismatch by removing `instances_used` entirely, and instead inferring its contents from the keys of `pgo_func_name_var_map`. This makes it impossible for a "used" function to lack a PGO name entry. --- .../src/coverageinfo/mapgen.rs | 12 +++------ .../src/coverageinfo/mod.rs | 27 ++++++++++++------- 2 files changed, 21 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index a9be833a6439..8c9dfcfd18c2 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -46,21 +46,17 @@ pub(crate) fn finalize(cx: &mut CodegenCx<'_, '_>) { debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name()); // FIXME(#132395): Can this be none even when coverage is enabled? - let instances_used = match cx.coverage_cx { - Some(ref cx) => cx.instances_used.borrow(), - None => return, - }; + let Some(ref coverage_cx) = cx.coverage_cx else { return }; - let mut covfun_records = instances_used - .iter() - .copied() + let mut covfun_records = coverage_cx + .instances_used() + .into_iter() // Sort by symbol name, so that the global file table is built in an // order that doesn't depend on the stable-hash-based order in which // instances were visited during codegen. .sorted_by_cached_key(|&instance| tcx.symbol_name(instance).name) .filter_map(|instance| prepare_covfun_record(tcx, instance, true)) .collect::>(); - drop(instances_used); // In a single designated CGU, also prepare covfun records for functions // in this crate that were instrumented for coverage, but are unused. diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index eefbd7cf6c48..35c322326f8e 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -5,7 +5,7 @@ use rustc_abi::Size; use rustc_codegen_ssa::traits::{ BuilderMethods, ConstCodegenMethods, CoverageInfoBuilderMethods, MiscCodegenMethods, }; -use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; +use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::ty::Instance; use tracing::{debug, instrument}; @@ -20,9 +20,14 @@ mod mapgen; /// Extra per-CGU context/state needed for coverage instrumentation. pub(crate) struct CguCoverageContext<'ll, 'tcx> { - /// Coverage data for each instrumented function identified by DefId. - pub(crate) instances_used: RefCell>>, - pub(crate) pgo_func_name_var_map: RefCell, &'ll llvm::Value>>, + /// Associates function instances with an LLVM global that holds the + /// function's symbol name, as needed by LLVM coverage intrinsics. + /// + /// Instances in this map are also considered "used" for the purposes of + /// emitting covfun records. Every covfun record holds a hash of its + /// symbol name, and `llvm-cov` will exit fatally if it can't resolve that + /// hash back to an entry in the binary's `__llvm_prf_names` linker section. + pub(crate) pgo_func_name_var_map: RefCell, &'ll llvm::Value>>, pub(crate) mcdc_condition_bitmap_map: RefCell, Vec<&'ll llvm::Value>>>, covfun_section_name: OnceCell, @@ -31,7 +36,6 @@ pub(crate) struct CguCoverageContext<'ll, 'tcx> { impl<'ll, 'tcx> CguCoverageContext<'ll, 'tcx> { pub(crate) fn new() -> Self { Self { - instances_used: RefCell::>::default(), pgo_func_name_var_map: Default::default(), mcdc_condition_bitmap_map: Default::default(), covfun_section_name: Default::default(), @@ -53,6 +57,14 @@ impl<'ll, 'tcx> CguCoverageContext<'ll, 'tcx> { .and_then(|bitmap_map| bitmap_map.get(decision_depth as usize)) .copied() // Dereference Option<&&Value> to Option<&Value> } + + /// Returns the list of instances considered "used" in this CGU, as + /// inferred from the keys of `pgo_func_name_var_map`. + pub(crate) fn instances_used(&self) -> Vec> { + // Collecting into a Vec is way easier than trying to juggle RefCell + // projections, and this should only run once per CGU anyway. + self.pgo_func_name_var_map.borrow().keys().copied().collect::>() + } } impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { @@ -151,11 +163,6 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { return; }; - // Mark the instance as used in this CGU, for coverage purposes. - // This includes functions that were not partitioned into this CGU, - // but were MIR-inlined into one of this CGU's functions. - coverage_cx.instances_used.borrow_mut().insert(instance); - match *kind { CoverageKind::SpanMarker | CoverageKind::BlockMarker { .. } => unreachable!( "marker statement {kind:?} should have been removed by CleanupPostBorrowck" From 89b6b0b6a482cb0d632f54f14936def9c034570d Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 27 Jul 2025 21:29:48 +1000 Subject: [PATCH 189/809] coverage: Clarify that getting a PGO name also makes a function "used" --- compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index 35c322326f8e..119237abd6b8 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -90,7 +90,10 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// string, to hold the function name passed to LLVM intrinsic /// `instrprof.increment()`. The `Value` is only created once per instance. /// Multiple invocations with the same instance return the same `Value`. - fn get_pgo_func_name_var(&self, instance: Instance<'tcx>) -> &'ll llvm::Value { + /// + /// This has the side-effect of causing coverage codegen to consider this + /// function "used", making it eligible to emit an associated covfun record. + fn ensure_pgo_func_name_var(&self, instance: Instance<'tcx>) -> &'ll llvm::Value { debug!("getting pgo_func_name_var for instance={:?}", instance); let mut pgo_func_name_var_map = self.coverage_cx().pgo_func_name_var_map.borrow_mut(); pgo_func_name_var_map.entry(instance).or_insert_with(|| { @@ -114,7 +117,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { return; } - let fn_name = self.get_pgo_func_name_var(instance); + let fn_name = self.ensure_pgo_func_name_var(instance); let hash = self.const_u64(function_coverage_info.function_source_hash); let bitmap_bits = self.const_u32(function_coverage_info.mcdc_bitmap_bits as u32); self.mcdc_parameters(fn_name, hash, bitmap_bits); @@ -170,7 +173,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { CoverageKind::VirtualCounter { bcb } if let Some(&id) = ids_info.phys_counter_for_node.get(&bcb) => { - let fn_name = bx.get_pgo_func_name_var(instance); + let fn_name = bx.ensure_pgo_func_name_var(instance); let hash = bx.const_u64(function_coverage_info.function_source_hash); let num_counters = bx.const_u32(ids_info.num_counters); let index = bx.const_u32(id.as_u32()); @@ -200,7 +203,7 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { "bitmap index of the decision out of range" ); - let fn_name = bx.get_pgo_func_name_var(instance); + let fn_name = bx.ensure_pgo_func_name_var(instance); let hash = bx.const_u64(function_coverage_info.function_source_hash); let bitmap_index = bx.const_u32(bitmap_idx); bx.mcdc_tvbitmap_update(fn_name, hash, bitmap_index, cond_bitmap); From 81fc22753e3e75dae62a5837c2b641c0fbd57cde Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Fri, 25 Jul 2025 22:32:41 +0200 Subject: [PATCH 190/809] 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 fd65b7e6646edd72549bf83386f381ba2cf7fc0b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 27 Jul 2025 13:34:55 +0200 Subject: [PATCH 191/809] introduce a macro for shim signature checking Co-Authored-By: geetanshjuneja --- src/tools/miri/src/helpers.rs | 213 +-------- src/tools/miri/src/intrinsics/atomic.rs | 2 +- src/tools/miri/src/intrinsics/mod.rs | 22 +- src/tools/miri/src/intrinsics/simd.rs | 5 +- src/tools/miri/src/lib.rs | 2 + src/tools/miri/src/shims/aarch64.rs | 5 +- src/tools/miri/src/shims/backtrace.rs | 8 +- src/tools/miri/src/shims/foreign_items.rs | 90 ++-- src/tools/miri/src/shims/mod.rs | 1 + src/tools/miri/src/shims/sig.rs | 265 ++++++++++ .../src/shims/unix/android/foreign_items.rs | 11 +- .../miri/src/shims/unix/android/thread.rs | 4 +- src/tools/miri/src/shims/unix/fd.rs | 2 +- .../miri/src/shims/unix/foreign_items.rs | 451 +++++++----------- .../src/shims/unix/freebsd/foreign_items.rs | 26 +- src/tools/miri/src/shims/unix/fs.rs | 2 +- .../src/shims/unix/linux/foreign_items.rs | 39 +- .../miri/src/shims/unix/linux_like/sync.rs | 2 +- .../miri/src/shims/unix/linux_like/syscall.rs | 4 +- .../src/shims/unix/macos/foreign_items.rs | 71 +-- .../src/shims/unix/solarish/foreign_items.rs | 34 +- src/tools/miri/src/shims/unwind.rs | 6 +- .../miri/src/shims/wasi/foreign_items.rs | 6 +- .../miri/src/shims/windows/foreign_items.rs | 147 +++--- src/tools/miri/src/shims/x86/aesni.rs | 14 +- src/tools/miri/src/shims/x86/avx.rs | 50 +- src/tools/miri/src/shims/x86/avx2.rs | 57 ++- src/tools/miri/src/shims/x86/bmi.rs | 2 +- src/tools/miri/src/shims/x86/gfni.rs | 9 +- src/tools/miri/src/shims/x86/mod.rs | 11 +- src/tools/miri/src/shims/x86/sha.rs | 6 +- src/tools/miri/src/shims/x86/sse.rs | 24 +- src/tools/miri/src/shims/x86/sse2.rs | 40 +- src/tools/miri/src/shims/x86/sse3.rs | 5 +- src/tools/miri/src/shims/x86/sse41.rs | 28 +- src/tools/miri/src/shims/x86/sse42.rs | 14 +- src/tools/miri/src/shims/x86/ssse3.rs | 17 +- 37 files changed, 900 insertions(+), 795 deletions(-) create mode 100644 src/tools/miri/src/shims/sig.rs diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index 6e80bc5da9eb..0c96ddf00db4 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -3,7 +3,7 @@ use std::time::Duration; use std::{cmp, iter}; use rand::RngCore; -use rustc_abi::{Align, CanonAbi, ExternAbi, FieldIdx, FieldsShape, Size, Variants}; +use rustc_abi::{Align, ExternAbi, FieldIdx, FieldsShape, Size, Variants}; use rustc_apfloat::Float; use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_hir::Safety; @@ -14,11 +14,10 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::dependency_format::Linkage; use rustc_middle::middle::exported_symbols::ExportedSymbol; use rustc_middle::ty::layout::{LayoutOf, MaybeResult, TyAndLayout}; -use rustc_middle::ty::{self, Binder, FloatTy, FnSig, IntTy, Ty, TyCtxt, UintTy}; +use rustc_middle::ty::{self, FloatTy, IntTy, Ty, TyCtxt, UintTy}; use rustc_session::config::CrateType; use rustc_span::{Span, Symbol}; use rustc_symbol_mangling::mangle_internal_symbol; -use rustc_target::callconv::FnAbi; use crate::*; @@ -437,7 +436,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// For now, arguments must be scalars (so that the caller does not have to know the layout). /// /// If you do not provide a return place, a dangling zero-sized place will be created - /// for your convenience. + /// for your convenience. This is only valid if the return type is `()`. fn call_function( &mut self, f: ty::Instance<'tcx>, @@ -452,7 +451,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let mir = this.load_mir(f.def, None)?; let dest = match dest { Some(dest) => dest.clone(), - None => MPlaceTy::fake_alloc_zst(this.layout_of(mir.return_ty())?), + None => MPlaceTy::fake_alloc_zst(this.machine.layouts.unit), }; // Construct a function pointer type representing the caller perspective. @@ -465,6 +464,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ); let caller_fn_abi = this.fn_abi_of_fn_ptr(ty::Binder::dummy(sig), ty::List::empty())?; + // This will also show proper errors if there is any ABI mismatch. this.init_stack_frame( f, mir, @@ -929,21 +929,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { self.read_c_str_with_char_size(ptr, wchar_t.size, wchar_t.align.abi) } - /// Check that the calling convention is what we expect. - fn check_callconv<'a>( - &self, - fn_abi: &FnAbi<'tcx, Ty<'tcx>>, - exp_abi: CanonAbi, - ) -> InterpResult<'a, ()> { - if fn_abi.conv != exp_abi { - throw_ub_format!( - r#"calling a function with calling convention "{exp_abi}" using caller calling convention "{}""#, - fn_abi.conv - ); - } - interp_ok(()) - } - fn frame_in_std(&self) -> bool { let this = self.eval_context_ref(); let frame = this.frame(); @@ -967,161 +952,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { crate_name == "std" || crate_name == "std_miri_test" } - fn check_abi_and_shim_symbol_clash( - &mut self, - abi: &FnAbi<'tcx, Ty<'tcx>>, - exp_abi: CanonAbi, - link_name: Symbol, - ) -> InterpResult<'tcx, ()> { - self.check_callconv(abi, exp_abi)?; - if let Some((body, instance)) = self.eval_context_mut().lookup_exported_symbol(link_name)? { - // If compiler-builtins is providing the symbol, then don't treat it as a clash. - // We'll use our built-in implementation in `emulate_foreign_item_inner` for increased - // performance. Note that this means we won't catch any undefined behavior in - // compiler-builtins when running other crates, but Miri can still be run on - // compiler-builtins itself (or any crate that uses it as a normal dependency) - if self.eval_context_ref().tcx.is_compiler_builtins(instance.def_id().krate) { - return interp_ok(()); - } - - throw_machine_stop!(TerminationInfo::SymbolShimClashing { - link_name, - span: body.span.data(), - }) - } - interp_ok(()) - } - - fn check_shim<'a, const N: usize>( - &mut self, - abi: &FnAbi<'tcx, Ty<'tcx>>, - exp_abi: CanonAbi, - link_name: Symbol, - args: &'a [OpTy<'tcx>], - ) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> { - self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?; - - if abi.c_variadic { - throw_ub_format!( - "calling a non-variadic function with a variadic caller-side signature" - ); - } - if let Ok(ops) = args.try_into() { - return interp_ok(ops); - } - throw_ub_format!( - "incorrect number of arguments for `{link_name}`: got {}, expected {}", - args.len(), - N - ) - } - - /// Check that the given `caller_fn_abi` matches the expected ABI described by - /// `callee_abi`, `callee_input_tys`, `callee_output_ty`, and then returns the list of - /// arguments. - fn check_shim_abi<'a, const N: usize>( - &mut self, - link_name: Symbol, - caller_fn_abi: &FnAbi<'tcx, Ty<'tcx>>, - callee_abi: ExternAbi, - callee_input_tys: [Ty<'tcx>; N], - callee_output_ty: Ty<'tcx>, - caller_args: &'a [OpTy<'tcx>], - ) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> { - let this = self.eval_context_mut(); - let mut inputs_and_output = callee_input_tys.to_vec(); - inputs_and_output.push(callee_output_ty); - let fn_sig_binder = Binder::dummy(FnSig { - inputs_and_output: this.machine.tcx.mk_type_list(&inputs_and_output), - c_variadic: false, - // This does not matter for the ABI. - safety: Safety::Safe, - abi: callee_abi, - }); - let callee_fn_abi = this.fn_abi_of_fn_ptr(fn_sig_binder, Default::default())?; - - this.check_abi_and_shim_symbol_clash(caller_fn_abi, callee_fn_abi.conv, link_name)?; - - if caller_fn_abi.c_variadic { - throw_ub_format!( - "ABI mismatch: calling a non-variadic function with a variadic caller-side signature" - ); - } - - if callee_fn_abi.fixed_count != caller_fn_abi.fixed_count { - throw_ub_format!( - "ABI mismatch: expected {} arguments, found {} arguments ", - callee_fn_abi.fixed_count, - caller_fn_abi.fixed_count - ); - } - - if callee_fn_abi.can_unwind && !caller_fn_abi.can_unwind { - throw_ub_format!( - "ABI mismatch: callee may unwind, but caller-side signature prohibits unwinding", - ); - } - - if !this.check_argument_compat(&caller_fn_abi.ret, &callee_fn_abi.ret)? { - throw_ub!(AbiMismatchReturn { - caller_ty: caller_fn_abi.ret.layout.ty, - callee_ty: callee_fn_abi.ret.layout.ty - }); - } - - if let Some(index) = caller_fn_abi - .args - .iter() - .zip(callee_fn_abi.args.iter()) - .map(|(caller_arg, callee_arg)| this.check_argument_compat(caller_arg, callee_arg)) - .collect::>>()? - .into_iter() - .position(|b| !b) - { - throw_ub!(AbiMismatchArgument { - caller_ty: caller_fn_abi.args[index].layout.ty, - callee_ty: callee_fn_abi.args[index].layout.ty - }); - } - - if let Ok(ops) = caller_args.try_into() { - return interp_ok(ops); - } - unreachable!() - } - - /// Check shim for variadic function. - /// Returns a tuple that consisting of an array of fixed args, and a slice of varargs. - fn check_shim_variadic<'a, const N: usize>( - &mut self, - abi: &FnAbi<'tcx, Ty<'tcx>>, - exp_abi: CanonAbi, - link_name: Symbol, - args: &'a [OpTy<'tcx>], - ) -> InterpResult<'tcx, (&'a [OpTy<'tcx>; N], &'a [OpTy<'tcx>])> - where - &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>, - { - self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?; - - if !abi.c_variadic { - throw_ub_format!( - "calling a variadic function with a non-variadic caller-side signature" - ); - } - if abi.fixed_count != u32::try_from(N).unwrap() { - throw_ub_format!( - "incorrect number of fixed arguments for variadic function `{}`: got {}, expected {N}", - link_name.as_str(), - abi.fixed_count - ) - } - if let Some(args) = args.split_first_chunk() { - return interp_ok(args); - } - panic!("mismatch between signature and `args` slice"); - } - /// Mark a machine allocation that was just created as immutable. fn mark_immutable(&mut self, mplace: &MPlaceTy<'tcx>) { let this = self.eval_context_mut(); @@ -1317,39 +1147,6 @@ impl<'tcx> MiriMachine<'tcx> { } } -/// Check that the number of args is what we expect. -pub fn check_intrinsic_arg_count<'a, 'tcx, const N: usize>( - args: &'a [OpTy<'tcx>], -) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> -where - &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>, -{ - if let Ok(ops) = args.try_into() { - return interp_ok(ops); - } - throw_ub_format!( - "incorrect number of arguments for intrinsic: got {}, expected {}", - args.len(), - N - ) -} - -/// Check that the number of varargs is at least the minimum what we expect. -/// Fixed args should not be included. -pub fn check_min_vararg_count<'a, 'tcx, const N: usize>( - name: &'a str, - args: &'a [OpTy<'tcx>], -) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> { - if let Some((ops, _)) = args.split_first_chunk() { - return interp_ok(ops); - } - throw_ub_format!( - "not enough variadic arguments for `{name}`: got {}, expected at least {}", - args.len(), - N - ) -} - pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> { throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!( "{name} not available when isolation is enabled", diff --git a/src/tools/miri/src/intrinsics/atomic.rs b/src/tools/miri/src/intrinsics/atomic.rs index 0a59a707a101..bcc3e9ec885f 100644 --- a/src/tools/miri/src/intrinsics/atomic.rs +++ b/src/tools/miri/src/intrinsics/atomic.rs @@ -2,7 +2,7 @@ use rustc_middle::mir::BinOp; use rustc_middle::ty::AtomicOrdering; use rustc_middle::{mir, ty}; -use self::helpers::check_intrinsic_arg_count; +use super::check_intrinsic_arg_count; use crate::*; pub enum AtomicOp { diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index 4efa7dd4dcf8..b5e81460773b 100644 --- a/src/tools/miri/src/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -14,11 +14,28 @@ use rustc_middle::ty::{self, FloatTy, ScalarInt}; use rustc_span::{Symbol, sym}; use self::atomic::EvalContextExt as _; -use self::helpers::{ToHost, ToSoft, check_intrinsic_arg_count}; +use self::helpers::{ToHost, ToSoft}; use self::simd::EvalContextExt as _; use crate::math::{IeeeExt, apply_random_float_error_ulp}; use crate::*; +/// Check that the number of args is what we expect. +fn check_intrinsic_arg_count<'a, 'tcx, const N: usize>( + args: &'a [OpTy<'tcx>], +) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> +where + &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>, +{ + if let Ok(ops) = args.try_into() { + return interp_ok(ops); + } + throw_ub_format!( + "incorrect number of arguments for intrinsic: got {}, expected {}", + args.len(), + N + ) +} + impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn call_intrinsic( @@ -114,7 +131,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )); } "catch_unwind" => { - this.handle_catch_unwind(args, dest, ret)?; + let [try_fn, data, catch_fn] = check_intrinsic_arg_count(args)?; + this.handle_catch_unwind(try_fn, data, catch_fn, dest, ret)?; // This pushed a stack frame, don't jump to `ret`. return interp_ok(EmulateItemResult::AlreadyJumped); } diff --git a/src/tools/miri/src/intrinsics/simd.rs b/src/tools/miri/src/intrinsics/simd.rs index e63992aa95f9..b26516c0ff0e 100644 --- a/src/tools/miri/src/intrinsics/simd.rs +++ b/src/tools/miri/src/intrinsics/simd.rs @@ -6,9 +6,8 @@ use rustc_middle::ty::FloatTy; use rustc_middle::{mir, ty}; use rustc_span::{Symbol, sym}; -use crate::helpers::{ - ToHost, ToSoft, bool_to_simd_element, check_intrinsic_arg_count, simd_element_to_bool, -}; +use super::check_intrinsic_arg_count; +use crate::helpers::{ToHost, ToSoft, bool_to_simd_element, simd_element_to_bool}; use crate::*; #[derive(Copy, Clone)] diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index ae70257653c8..507d4f7b4289 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -7,6 +7,7 @@ #![feature(never_type)] #![feature(try_blocks)] #![feature(io_error_more)] +#![feature(if_let_guard)] #![feature(variant_count)] #![feature(yeet_expr)] #![feature(nonzero_ops)] @@ -158,6 +159,7 @@ pub use crate::shims::foreign_items::{DynSym, EvalContextExt as _}; pub use crate::shims::io_error::{EvalContextExt as _, IoError, LibcError}; pub use crate::shims::os_str::EvalContextExt as _; pub use crate::shims::panic::EvalContextExt as _; +pub use crate::shims::sig::EvalContextExt as _; pub use crate::shims::time::EvalContextExt as _; pub use crate::shims::tls::TlsData; pub use crate::shims::unwind::{CatchUnwindData, EvalContextExt as _}; diff --git a/src/tools/miri/src/shims/aarch64.rs b/src/tools/miri/src/shims/aarch64.rs index 44ad5081ad57..6e422b4ab716 100644 --- a/src/tools/miri/src/shims/aarch64.rs +++ b/src/tools/miri/src/shims/aarch64.rs @@ -20,7 +20,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let unprefixed_name = link_name.as_str().strip_prefix("llvm.aarch64.").unwrap(); match unprefixed_name { "isb" => { - let [arg] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [arg] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let arg = this.read_scalar(arg)?.to_i32()?; match arg { // SY ("full system scope") @@ -38,7 +38,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `left` input, the second half of the output from the `right` input. // https://developer.arm.com/architectures/instruction-sets/intrinsics/vpmaxq_u8 "neon.umaxp.v16i8" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; diff --git a/src/tools/miri/src/shims/backtrace.rs b/src/tools/miri/src/shims/backtrace.rs index 18d60915d205..bd3914b652ac 100644 --- a/src/tools/miri/src/shims/backtrace.rs +++ b/src/tools/miri/src/shims/backtrace.rs @@ -15,7 +15,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); - let [flags] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [flags] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let flags = this.read_scalar(flags)?.to_u64()?; if flags != 0 { @@ -37,7 +37,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let ptr_ty = this.machine.layouts.mut_raw_ptr.ty; let ptr_layout = this.layout_of(ptr_ty)?; - let [flags, buf] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [flags, buf] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let flags = this.read_scalar(flags)?.to_u64()?; let buf_place = this.deref_pointer_as(buf, ptr_layout)?; @@ -117,7 +117,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); - let [ptr, flags] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [ptr, flags] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let flags = this.read_scalar(flags)?.to_u64()?; @@ -195,7 +195,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let this = self.eval_context_mut(); let [ptr, flags, name_ptr, filename_ptr] = - this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let flags = this.read_scalar(flags)?.to_u64()?; if flags != 0 { diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs index 94cda57658a1..21545b680299 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -288,16 +288,17 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // Miri-specific extern functions "miri_start_unwind" => { - let [payload] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [payload] = + this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; this.handle_miri_start_unwind(payload)?; return interp_ok(EmulateItemResult::NeedsUnwind); } "miri_run_provenance_gc" => { - let [] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; this.run_provenance_gc(); } "miri_get_alloc_id" => { - let [ptr] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let ptr = this.read_pointer(ptr)?; let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| { err_machine_stop!(TerminationInfo::Abort(format!( @@ -307,7 +308,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?; } "miri_print_borrow_state" => { - let [id, show_unnamed] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [id, show_unnamed] = + this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let id = this.read_scalar(id)?.to_u64()?; let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?; if let Some(id) = std::num::NonZero::new(id).map(AllocId) @@ -322,7 +324,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // This associates a name to a tag. Very useful for debugging, and also makes // tests more strict. let [ptr, nth_parent, name] = - this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let ptr = this.read_pointer(ptr)?; let nth_parent = this.read_scalar(nth_parent)?.to_u8()?; let name = this.read_immediate(name)?; @@ -335,7 +337,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { this.give_pointer_debug_name(ptr, nth_parent, &name)?; } "miri_static_root" => { - let [ptr] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let ptr = this.read_pointer(ptr)?; let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?; if offset != Size::ZERO { @@ -346,7 +348,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { this.machine.static_roots.push(alloc_id); } "miri_host_to_target_path" => { - let [ptr, out, out_size] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [ptr, out, out_size] = + this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let ptr = this.read_pointer(ptr)?; let out = this.read_pointer(out)?; let out_size = this.read_scalar(out_size)?.to_target_usize(this)?; @@ -382,7 +385,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // Writes some bytes to the interpreter's stdout/stderr. See the // README for details. "miri_write_to_stdout" | "miri_write_to_stderr" => { - let [msg] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [msg] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let msg = this.read_immediate(msg)?; let msg = this.read_byte_slice(&msg)?; // Note: we're ignoring errors writing to host stdout/stderr. @@ -396,7 +399,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { "miri_promise_symbolic_alignment" => { use rustc_abi::AlignFromBytesError; - let [ptr, align] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [ptr, align] = + this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let ptr = this.read_pointer(ptr)?; let align = this.read_target_usize(align)?; if !align.is_power_of_two() { @@ -437,12 +441,12 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // Aborting the process. "exit" => { - let [code] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [code] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let code = this.read_scalar(code)?.to_i32()?; throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false }); } "abort" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; throw_machine_stop!(TerminationInfo::Abort( "the program aborted execution".to_owned() )) @@ -450,7 +454,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // Standard C allocation "malloc" => { - let [size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [size] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let size = this.read_target_usize(size)?; if size <= this.max_size_of_val().bytes() { let res = this.malloc(size, AllocInit::Uninit)?; @@ -464,7 +468,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } } "calloc" => { - let [items, elem_size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [items, elem_size] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let items = this.read_target_usize(items)?; let elem_size = this.read_target_usize(elem_size)?; if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) { @@ -479,12 +484,13 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } } "free" => { - let [ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.read_pointer(ptr)?; this.free(ptr)?; } "realloc" => { - let [old_ptr, new_size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [old_ptr, new_size] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let old_ptr = this.read_pointer(old_ptr)?; let new_size = this.read_target_usize(new_size)?; if new_size <= this.max_size_of_val().bytes() { @@ -504,7 +510,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { let default = |ecx: &mut MiriInterpCx<'tcx>| { // Only call `check_shim` when `#[global_allocator]` isn't used. When that // macro is used, we act like no shim exists, so that the exported function can run. - let [size, align] = ecx.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [size, align] = + ecx.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let size = ecx.read_target_usize(size)?; let align = ecx.read_target_usize(align)?; @@ -537,7 +544,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { return this.emulate_allocator(|this| { // See the comment for `__rust_alloc` why `check_shim` is only called in the // default case. - let [size, align] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [size, align] = + this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let size = this.read_target_usize(size)?; let align = this.read_target_usize(align)?; @@ -559,7 +567,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // See the comment for `__rust_alloc` why `check_shim` is only called in the // default case. let [ptr, old_size, align] = - ecx.check_shim(abi, CanonAbi::Rust, link_name, args)?; + ecx.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let ptr = ecx.read_pointer(ptr)?; let old_size = ecx.read_target_usize(old_size)?; let align = ecx.read_target_usize(align)?; @@ -590,7 +598,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // See the comment for `__rust_alloc` why `check_shim` is only called in the // default case. let [ptr, old_size, align, new_size] = - this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let ptr = this.read_pointer(ptr)?; let old_size = this.read_target_usize(old_size)?; let align = this.read_target_usize(align)?; @@ -613,20 +621,21 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } name if name == this.mangle_internal_symbol("__rust_no_alloc_shim_is_unstable_v2") => { // This is a no-op shim that only exists to prevent making the allocator shims instantly stable. - let [] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; } name if name == this.mangle_internal_symbol("__rust_alloc_error_handler_should_panic_v2") => { // Gets the value of the `oom` option. - let [] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?; let val = this.tcx.sess.opts.unstable_opts.oom.should_panic(); this.write_int(val, dest)?; } // C memory handling functions "memcmp" => { - let [left, right, n] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, n] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let left = this.read_pointer(left)?; let right = this.read_pointer(right)?; let n = Size::from_bytes(this.read_target_usize(n)?); @@ -650,7 +659,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(Scalar::from_i32(result), dest)?; } "memrchr" => { - let [ptr, val, num] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, val, num] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.read_pointer(ptr)?; let val = this.read_scalar(val)?.to_i32()?; let num = this.read_target_usize(num)?; @@ -676,7 +686,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } } "memchr" => { - let [ptr, val, num] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, val, num] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.read_pointer(ptr)?; let val = this.read_scalar(val)?.to_i32()?; let num = this.read_target_usize(num)?; @@ -699,7 +710,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } } "strlen" => { - let [ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.read_pointer(ptr)?; // This reads at least 1 byte, so we are already enforcing that this is a valid pointer. let n = this.read_c_str(ptr)?.len(); @@ -709,7 +720,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; } "wcslen" => { - let [ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.read_pointer(ptr)?; // This reads at least 1 byte, so we are already enforcing that this is a valid pointer. let n = this.read_wchar_t_str(ptr)?.len(); @@ -719,7 +730,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; } "memcpy" => { - let [ptr_dest, ptr_src, n] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr_dest, ptr_src, n] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr_dest = this.read_pointer(ptr_dest)?; let ptr_src = this.read_pointer(ptr_src)?; let n = this.read_target_usize(n)?; @@ -733,7 +745,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_pointer(ptr_dest, dest)?; } "strcpy" => { - let [ptr_dest, ptr_src] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr_dest, ptr_src] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr_dest = this.read_pointer(ptr_dest)?; let ptr_src = this.read_pointer(ptr_src)?; @@ -764,7 +777,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { | "erff" | "erfcf" => { - let [f] = this.check_shim(abi, CanonAbi::C , link_name, args)?; + let [f] = this.check_shim_sig_lenient(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(); @@ -802,7 +815,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { | "atan2f" | "fdimf" => { - let [f1, f2] = this.check_shim(abi, CanonAbi::C , link_name, args)?; + let [f1, f2] = this.check_shim_sig_lenient(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 @@ -841,7 +854,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { | "erf" | "erfc" => { - let [f] = this.check_shim(abi, CanonAbi::C , link_name, args)?; + let [f] = this.check_shim_sig_lenient(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(); @@ -879,7 +892,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { | "atan2" | "fdim" => { - let [f1, f2] = this.check_shim(abi, CanonAbi::C , link_name, args)?; + let [f1, f2] = this.check_shim_sig_lenient(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 @@ -908,7 +921,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { | "ldexp" | "scalbn" => { - let [x, exp] = this.check_shim(abi, CanonAbi::C , link_name, args)?; + let [x, exp] = this.check_shim_sig_lenient(abi, CanonAbi::C , link_name, args)?; // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same. let x = this.read_scalar(x)?.to_f64()?; let exp = this.read_scalar(exp)?.to_i32()?; @@ -918,7 +931,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "lgammaf_r" => { - let [x, signp] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [x, signp] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let x = this.read_scalar(x)?.to_f32()?; let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?; @@ -934,7 +947,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "lgamma_r" => { - let [x, signp] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [x, signp] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let x = this.read_scalar(x)?.to_f64()?; let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?; @@ -952,7 +965,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // LLVM intrinsics "llvm.prefetch" => { - let [p, rw, loc, ty] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [p, rw, loc, ty] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let _ = this.read_pointer(p)?; let rw = this.read_scalar(rw)?.to_i32()?; @@ -979,7 +993,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement the x86 `_mm{,256,512}_popcnt_epi{8,16,32,64}` and wasm // `{i,u}8x16_popcnt` functions. name if name.starts_with("llvm.ctpop.v") => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (op, op_len) = this.project_to_simd(op)?; let (dest, dest_len) = this.project_to_simd(dest)?; @@ -1015,7 +1029,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } // FIXME: Move this to an `arm` submodule. "llvm.arm.hint" if this.tcx.sess.target.arch == "arm" => { - let [arg] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [arg] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let arg = this.read_scalar(arg)?.to_i32()?; // Note that different arguments might have different target feature requirements. match arg { diff --git a/src/tools/miri/src/shims/mod.rs b/src/tools/miri/src/shims/mod.rs index 2a7709829ee6..7f594d4fdd6b 100644 --- a/src/tools/miri/src/shims/mod.rs +++ b/src/tools/miri/src/shims/mod.rs @@ -18,6 +18,7 @@ pub mod global_ctor; pub mod io_error; pub mod os_str; pub mod panic; +pub mod sig; pub mod time; pub mod tls; pub mod unwind; diff --git a/src/tools/miri/src/shims/sig.rs b/src/tools/miri/src/shims/sig.rs new file mode 100644 index 000000000000..8dd08055c7ea --- /dev/null +++ b/src/tools/miri/src/shims/sig.rs @@ -0,0 +1,265 @@ +//! Everything related to checking the signature of shim invocations. + +use rustc_abi::{CanonAbi, ExternAbi}; +use rustc_hir::Safety; +use rustc_middle::ty::{Binder, FnSig, Ty}; +use rustc_span::Symbol; +use rustc_target::callconv::FnAbi; + +use crate::*; + +/// Describes the expected signature of a shim. +pub struct ShimSig<'tcx, const ARGS: usize> { + pub abi: ExternAbi, + pub args: [Ty<'tcx>; ARGS], + pub ret: Ty<'tcx>, +} + +/// Construct a `ShimSig` with convenient syntax: +/// ```rust,ignore +/// shim_sig!(this, extern "C" fn (*const T, i32) -> usize) +/// ``` +#[macro_export] +macro_rules! shim_sig { + (extern $abi:literal fn($($arg:ty),*) -> $ret:ty) => { + |this| $crate::shims::sig::ShimSig { + abi: std::str::FromStr::from_str($abi).expect("incorrect abi specified"), + args: [$(shim_sig_arg!(this, $arg)),*], + ret: shim_sig_arg!(this, $ret), + } + }; +} + +/// Helper for `shim_sig!`. +#[macro_export] +macro_rules! shim_sig_arg { + // Unfortuantely we cannot take apart a `ty`-typed token at compile time, + // so we have to stringify it and match at runtime. + ($this:ident, $x:ty) => {{ + match stringify!($x) { + "i8" => $this.tcx.types.i8, + "i16" => $this.tcx.types.i16, + "i32" => $this.tcx.types.i32, + "i64" => $this.tcx.types.i64, + "i128" => $this.tcx.types.i128, + "isize" => $this.tcx.types.isize, + "u8" => $this.tcx.types.u8, + "u16" => $this.tcx.types.u16, + "u32" => $this.tcx.types.u32, + "u64" => $this.tcx.types.u64, + "u128" => $this.tcx.types.u128, + "usize" => $this.tcx.types.usize, + "()" => $this.tcx.types.unit, + "*const _" => $this.machine.layouts.const_raw_ptr.ty, + "*mut _" => $this.machine.layouts.mut_raw_ptr.ty, + ty if let Some(libc_ty) = ty.strip_prefix("libc::") => $this.libc_ty_layout(libc_ty).ty, + ty => panic!("unsupported signature type {ty:?}"), + } + }}; +} + +/// Helper function to compare two ABIs. +fn check_shim_abi<'tcx>( + this: &MiriInterpCx<'tcx>, + callee_abi: &FnAbi<'tcx, Ty<'tcx>>, + caller_abi: &FnAbi<'tcx, Ty<'tcx>>, +) -> InterpResult<'tcx> { + if callee_abi.conv != caller_abi.conv { + throw_ub_format!( + r#"calling a function with calling convention "{callee}" using caller calling convention "{caller}""#, + callee = callee_abi.conv, + caller = caller_abi.conv, + ); + } + if callee_abi.can_unwind && !caller_abi.can_unwind { + throw_ub_format!( + "ABI mismatch: callee may unwind, but caller-side signature prohibits unwinding", + ); + } + if caller_abi.c_variadic && !callee_abi.c_variadic { + throw_ub_format!( + "ABI mismatch: calling a non-variadic function with a variadic caller-side signature" + ); + } + if !caller_abi.c_variadic && callee_abi.c_variadic { + throw_ub_format!( + "ABI mismatch: calling a variadic function with a non-variadic caller-side signature" + ); + } + + if callee_abi.fixed_count != caller_abi.fixed_count { + throw_ub_format!( + "ABI mismatch: expected {} arguments, found {} arguments ", + callee_abi.fixed_count, + caller_abi.fixed_count + ); + } + + if !this.check_argument_compat(&caller_abi.ret, &callee_abi.ret)? { + throw_ub!(AbiMismatchReturn { + caller_ty: caller_abi.ret.layout.ty, + callee_ty: callee_abi.ret.layout.ty + }); + } + + for (idx, (caller_arg, callee_arg)) in + caller_abi.args.iter().zip(callee_abi.args.iter()).enumerate() + { + if !this.check_argument_compat(caller_arg, callee_arg)? { + throw_ub!(AbiMismatchArgument { + caller_ty: caller_abi.args[idx].layout.ty, + callee_ty: callee_abi.args[idx].layout.ty + }); + } + } + + interp_ok(()) +} + +fn check_shim_symbol_clash<'tcx>( + this: &mut MiriInterpCx<'tcx>, + link_name: Symbol, +) -> InterpResult<'tcx, ()> { + if let Some((body, instance)) = this.lookup_exported_symbol(link_name)? { + // If compiler-builtins is providing the symbol, then don't treat it as a clash. + // We'll use our built-in implementation in `emulate_foreign_item_inner` for increased + // performance. Note that this means we won't catch any undefined behavior in + // compiler-builtins when running other crates, but Miri can still be run on + // compiler-builtins itself (or any crate that uses it as a normal dependency) + if this.tcx.is_compiler_builtins(instance.def_id().krate) { + return interp_ok(()); + } + + throw_machine_stop!(TerminationInfo::SymbolShimClashing { + link_name, + span: body.span.data(), + }) + } + interp_ok(()) +} + +impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} +pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { + fn check_shim_sig_lenient<'a, const N: usize>( + &mut self, + abi: &FnAbi<'tcx, Ty<'tcx>>, + exp_abi: CanonAbi, + link_name: Symbol, + args: &'a [OpTy<'tcx>], + ) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> { + let this = self.eval_context_mut(); + check_shim_symbol_clash(this, link_name)?; + + if abi.conv != exp_abi { + throw_ub_format!( + r#"calling a function with calling convention "{exp_abi}" using caller calling convention "{}""#, + abi.conv + ); + } + if abi.c_variadic { + throw_ub_format!( + "calling a non-variadic function with a variadic caller-side signature" + ); + } + + if let Ok(ops) = args.try_into() { + return interp_ok(ops); + } + throw_ub_format!( + "incorrect number of arguments for `{link_name}`: got {}, expected {}", + args.len(), + N + ) + } + + /// Check that the given `caller_fn_abi` matches the expected ABI described by `shim_sig`, and + /// then returns the list of arguments. + fn check_shim_sig<'a, const N: usize>( + &mut self, + shim_sig: fn(&MiriInterpCx<'tcx>) -> ShimSig<'tcx, N>, + link_name: Symbol, + caller_fn_abi: &FnAbi<'tcx, Ty<'tcx>>, + caller_args: &'a [OpTy<'tcx>], + ) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> { + let this = self.eval_context_mut(); + let shim_sig = shim_sig(this); + + // Compute full callee ABI. + let mut inputs_and_output = Vec::with_capacity(N.strict_add(1)); + inputs_and_output.extend(&shim_sig.args); + inputs_and_output.push(shim_sig.ret); + let fn_sig_binder = Binder::dummy(FnSig { + inputs_and_output: this.machine.tcx.mk_type_list(&inputs_and_output), + c_variadic: false, + // This does not matter for the ABI. + safety: Safety::Safe, + abi: shim_sig.abi, + }); + let callee_fn_abi = this.fn_abi_of_fn_ptr(fn_sig_binder, Default::default())?; + + // Check everything. + check_shim_abi(this, callee_fn_abi, caller_fn_abi)?; + check_shim_symbol_clash(this, link_name)?; + + // Return arguments. + if let Ok(ops) = caller_args.try_into() { + return interp_ok(ops); + } + unreachable!() + } + + /// Check shim for variadic function. + /// Returns a tuple that consisting of an array of fixed args, and a slice of varargs. + fn check_shim_sig_variadic_lenient<'a, const N: usize>( + &mut self, + abi: &FnAbi<'tcx, Ty<'tcx>>, + exp_abi: CanonAbi, + link_name: Symbol, + args: &'a [OpTy<'tcx>], + ) -> InterpResult<'tcx, (&'a [OpTy<'tcx>; N], &'a [OpTy<'tcx>])> + where + &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>, + { + let this = self.eval_context_mut(); + check_shim_symbol_clash(this, link_name)?; + + if abi.conv != exp_abi { + throw_ub_format!( + r#"calling a function with calling convention "{exp_abi}" using caller calling convention "{}""#, + abi.conv + ); + } + if !abi.c_variadic { + throw_ub_format!( + "calling a variadic function with a non-variadic caller-side signature" + ); + } + if abi.fixed_count != u32::try_from(N).unwrap() { + throw_ub_format!( + "incorrect number of fixed arguments for variadic function `{}`: got {}, expected {N}", + link_name.as_str(), + abi.fixed_count + ) + } + if let Some(args) = args.split_first_chunk() { + return interp_ok(args); + } + panic!("mismatch between signature and `args` slice"); + } +} + +/// Check that the number of varargs is at least the minimum what we expect. +/// Fixed args should not be included. +pub fn check_min_vararg_count<'a, 'tcx, const N: usize>( + name: &'a str, + args: &'a [OpTy<'tcx>], +) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> { + if let Some((ops, _)) = args.split_first_chunk() { + return interp_ok(ops); + } + throw_ub_format!( + "not enough variadic arguments for `{name}`: got {}, expected at least {}", + args.len(), + N + ) +} diff --git a/src/tools/miri/src/shims/unix/android/foreign_items.rs b/src/tools/miri/src/shims/unix/android/foreign_items.rs index 690b5295681d..04c5d28838bb 100644 --- a/src/tools/miri/src/shims/unix/android/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/android/foreign_items.rs @@ -26,29 +26,30 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // epoll, eventfd "epoll_create1" => { - let [flag] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [flag] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.epoll_create1(flag)?; this.write_scalar(result, dest)?; } "epoll_ctl" => { - let [epfd, op, fd, event] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [epfd, op, fd, event] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.epoll_ctl(epfd, op, fd, event)?; this.write_scalar(result, dest)?; } "epoll_wait" => { let [epfd, events, maxevents, timeout] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.epoll_wait(epfd, events, maxevents, timeout, dest)?; } "eventfd" => { - let [val, flag] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [val, flag] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.eventfd(val, flag)?; this.write_scalar(result, dest)?; } // Miscellaneous "__errno" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let errno_place = this.last_error_place()?; this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; } diff --git a/src/tools/miri/src/shims/unix/android/thread.rs b/src/tools/miri/src/shims/unix/android/thread.rs index 5d17d6c8517b..4e7b21d7d944 100644 --- a/src/tools/miri/src/shims/unix/android/thread.rs +++ b/src/tools/miri/src/shims/unix/android/thread.rs @@ -3,7 +3,7 @@ use rustc_middle::ty::Ty; use rustc_span::Symbol; use rustc_target::callconv::FnAbi; -use crate::helpers::check_min_vararg_count; +use crate::shims::sig::check_min_vararg_count; use crate::shims::unix::thread::{EvalContextExt as _, ThreadNameResult}; use crate::*; @@ -16,7 +16,7 @@ pub fn prctl<'tcx>( args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let ([op], varargs) = ecx.check_shim_variadic(abi, CanonAbi::C, link_name, args)?; + let ([op], varargs) = ecx.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?; // FIXME: Use constants once https://github.com/rust-lang/libc/pull/3941 backported to the 0.2 branch. let pr_set_name = 15; diff --git a/src/tools/miri/src/shims/unix/fd.rs b/src/tools/miri/src/shims/unix/fd.rs index b420955501c8..e226a55d8b1e 100644 --- a/src/tools/miri/src/shims/unix/fd.rs +++ b/src/tools/miri/src/shims/unix/fd.rs @@ -7,8 +7,8 @@ use std::io::ErrorKind; use rand::Rng; use rustc_abi::Size; -use crate::helpers::check_min_vararg_count; use crate::shims::files::FileDescription; +use crate::shims::sig::check_min_vararg_count; use crate::shims::unix::linux_like::epoll::EpollReadyEvents; use crate::shims::unix::*; use crate::*; diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs index 548eabb1b9fd..55906f4eb954 100644 --- a/src/tools/miri/src/shims/unix/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/foreign_items.rs @@ -1,7 +1,7 @@ use std::ffi::OsStr; use std::str; -use rustc_abi::{CanonAbi, ExternAbi, Size}; +use rustc_abi::{CanonAbi, Size}; use rustc_middle::ty::Ty; use rustc_span::Symbol; use rustc_target::callconv::FnAbi; @@ -14,7 +14,7 @@ use self::shims::unix::solarish::foreign_items as solarish; use crate::concurrency::cpu_affinity::CpuAffinityMask; use crate::shims::alloc::EvalContextExt as _; use crate::shims::unix::*; -use crate::*; +use crate::{shim_sig, *}; pub fn is_dyn_sym(name: &str, target_os: &str) -> bool { match name { @@ -111,40 +111,30 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // Environment related shims "getenv" => { - let [name] = this.check_shim_abi( + let [name] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _) -> *mut _), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty], - this.machine.layouts.mut_raw_ptr.ty, args, )?; let result = this.getenv(name)?; this.write_pointer(result, dest)?; } "unsetenv" => { - let [name] = this.check_shim_abi( + let [name] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.unsetenv(name)?; this.write_scalar(result, dest)?; } "setenv" => { - let [name, value, overwrite] = this.check_shim_abi( + let [name, value, overwrite] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _, *const _, i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [ - this.machine.layouts.const_raw_ptr.ty, - this.machine.layouts.const_raw_ptr.ty, - this.tcx.types.i32, - ], - this.tcx.types.i32, args, )?; this.read_scalar(overwrite)?.to_i32()?; @@ -152,48 +142,40 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(result, dest)?; } "getcwd" => { - let [buf, size] = this.check_shim_abi( + let [buf, size] = this.check_shim_sig( + shim_sig!(extern "C" fn(*mut _, usize) -> *mut _), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.mut_raw_ptr.ty, this.tcx.types.usize], - this.machine.layouts.mut_raw_ptr.ty, args, )?; let result = this.getcwd(buf, size)?; this.write_pointer(result, dest)?; } "chdir" => { - let [path] = this.check_shim_abi( + let [path] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.chdir(path)?; this.write_scalar(result, dest)?; } "getpid" => { - let [] = this.check_shim_abi( + let [] = this.check_shim_sig( + shim_sig!(extern "C" fn() -> libc::pid_t), link_name, abi, - ExternAbi::C { unwind: false }, - [], - this.libc_ty_layout("pid_t").ty, args, )?; let result = this.getpid()?; this.write_scalar(result, dest)?; } "sysconf" => { - let [val] = this.check_shim_abi( + let [val] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32) -> isize), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32], - this.tcx.types.isize, args, )?; let result = this.sysconf(val)?; @@ -201,12 +183,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // File descriptors "read" => { - let [fd, buf, count] = this.check_shim_abi( + let [fd, buf, count] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, *mut _, usize) -> isize), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32, this.machine.layouts.mut_raw_ptr.ty, this.tcx.types.usize], - this.tcx.types.isize, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; @@ -215,16 +195,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.read(fd, buf, count, None, dest)?; } "write" => { - let [fd, buf, n] = this.check_shim_abi( + let [fd, buf, n] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, *const _, usize) -> isize), link_name, abi, - ExternAbi::C { unwind: false }, - [ - this.tcx.types.i32, - this.machine.layouts.const_raw_ptr.ty, - this.tcx.types.usize, - ], - this.tcx.types.isize, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; @@ -234,98 +208,64 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write(fd, buf, count, None, dest)?; } "pread" => { - let off_t = this.libc_ty_layout("off_t"); - let [fd, buf, count, offset] = this.check_shim_abi( + let [fd, buf, count, offset] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, *mut _, usize, libc::off_t) -> isize), link_name, abi, - ExternAbi::C { unwind: false }, - [ - this.tcx.types.i32, - this.machine.layouts.mut_raw_ptr.ty, - this.tcx.types.usize, - off_t.ty, - ], - this.tcx.types.isize, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; let buf = this.read_pointer(buf)?; let count = this.read_target_usize(count)?; - let offset = this.read_scalar(offset)?.to_int(off_t.size)?; + let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; this.read(fd, buf, count, Some(offset), dest)?; } "pwrite" => { - let off_t = this.libc_ty_layout("off_t"); - let [fd, buf, n, offset] = this.check_shim_abi( + let [fd, buf, n, offset] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, *const _, usize, libc::off_t) -> isize), link_name, abi, - ExternAbi::C { unwind: false }, - [ - this.tcx.types.i32, - this.machine.layouts.const_raw_ptr.ty, - this.tcx.types.usize, - off_t.ty, - ], - this.tcx.types.isize, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; let buf = this.read_pointer(buf)?; let count = this.read_target_usize(n)?; - let offset = this.read_scalar(offset)?.to_int(off_t.size)?; + let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; trace!("Called pwrite({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset); this.write(fd, buf, count, Some(offset), dest)?; } "pread64" => { - let off64_t = this.libc_ty_layout("off64_t"); - let [fd, buf, count, offset] = this.check_shim_abi( + let [fd, buf, count, offset] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, *mut _, usize, libc::off64_t) -> isize), link_name, abi, - ExternAbi::C { unwind: false }, - [ - this.tcx.types.i32, - this.machine.layouts.mut_raw_ptr.ty, - this.tcx.types.usize, - off64_t.ty, - ], - this.tcx.types.isize, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; let buf = this.read_pointer(buf)?; let count = this.read_target_usize(count)?; - let offset = this.read_scalar(offset)?.to_int(off64_t.size)?; + let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; this.read(fd, buf, count, Some(offset), dest)?; } "pwrite64" => { - let off64_t = this.libc_ty_layout("off64_t"); - let [fd, buf, n, offset] = this.check_shim_abi( + let [fd, buf, n, offset] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, *const _, usize, libc::off64_t) -> isize), link_name, abi, - ExternAbi::C { unwind: false }, - [ - this.tcx.types.i32, - this.machine.layouts.const_raw_ptr.ty, - this.tcx.types.usize, - off64_t.ty, - ], - this.tcx.types.isize, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; let buf = this.read_pointer(buf)?; let count = this.read_target_usize(n)?; - let offset = this.read_scalar(offset)?.to_int(off64_t.size)?; + let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; trace!("Called pwrite64({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset); this.write(fd, buf, count, Some(offset), dest)?; } "close" => { - let [fd] = this.check_shim_abi( + let [fd] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32], - this.tcx.types.i32, args, )?; let result = this.close(fd)?; @@ -333,17 +273,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "fcntl" => { let ([fd_num, cmd], varargs) = - this.check_shim_variadic(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.fcntl(fd_num, cmd, varargs)?; this.write_scalar(result, dest)?; } "dup" => { - let [old_fd] = this.check_shim_abi( + let [old_fd] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32], - this.tcx.types.i32, args, )?; let old_fd = this.read_scalar(old_fd)?.to_i32()?; @@ -351,12 +289,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(new_fd, dest)?; } "dup2" => { - let [old_fd, new_fd] = this.check_shim_abi( + let [old_fd, new_fd] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32, this.tcx.types.i32], - this.tcx.types.i32, args, )?; let old_fd = this.read_scalar(old_fd)?.to_i32()?; @@ -367,12 +303,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "flock" => { // Currently this function does not exist on all Unixes, e.g. on Solaris. this.check_target_os(&["linux", "freebsd", "macos", "illumos"], link_name)?; - let [fd, op] = this.check_shim_abi( + let [fd, op] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32, this.tcx.types.i32], - this.tcx.types.i32, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; @@ -386,230 +320,187 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `open` is variadic, the third argument is only present when the second argument // has O_CREAT (or on linux O_TMPFILE, but miri doesn't support that) set let ([path_raw, flag], varargs) = - this.check_shim_variadic(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.open(path_raw, flag, varargs)?; this.write_scalar(result, dest)?; } "unlink" => { - let [path] = this.check_shim_abi( + let [path] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.unlink(path)?; this.write_scalar(result, dest)?; } "symlink" => { - let [target, linkpath] = this.check_shim_abi( + let [target, linkpath] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _, *const _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty, this.machine.layouts.const_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.symlink(target, linkpath)?; this.write_scalar(result, dest)?; } "rename" => { - let [oldpath, newpath] = this.check_shim_abi( + let [oldpath, newpath] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _, *const _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty, this.machine.layouts.const_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.rename(oldpath, newpath)?; this.write_scalar(result, dest)?; } "mkdir" => { - let [path, mode] = this.check_shim_abi( + let [path, mode] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _, libc::mode_t) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty, this.libc_ty_layout("mode_t").ty], - this.tcx.types.i32, args, )?; let result = this.mkdir(path, mode)?; this.write_scalar(result, dest)?; } "rmdir" => { - let [path] = this.check_shim_abi( + let [path] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.rmdir(path)?; this.write_scalar(result, dest)?; } "opendir" => { - let [name] = this.check_shim_abi( + let [name] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _) -> *mut _), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty], - this.machine.layouts.mut_raw_ptr.ty, args, )?; let result = this.opendir(name)?; this.write_scalar(result, dest)?; } "closedir" => { - let [dirp] = this.check_shim_abi( + let [dirp] = this.check_shim_sig( + shim_sig!(extern "C" fn(*mut _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.mut_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.closedir(dirp)?; this.write_scalar(result, dest)?; } "lseek64" => { - let off64_t = this.libc_ty_layout("off64_t"); - let [fd, offset, whence] = this.check_shim_abi( + let [fd, offset, whence] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, libc::off64_t, i32) -> libc::off64_t), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32, off64_t.ty, this.tcx.types.i32], - off64_t.ty, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; - let offset = this.read_scalar(offset)?.to_int(off64_t.size)?; + let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; let whence = this.read_scalar(whence)?.to_i32()?; this.lseek64(fd, offset, whence, dest)?; } "lseek" => { - let off_t = this.libc_ty_layout("off_t"); - let [fd, offset, whence] = this.check_shim_abi( + let [fd, offset, whence] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, libc::off_t, i32) -> libc::off_t), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32, off_t.ty, this.tcx.types.i32], - off_t.ty, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; - let offset = this.read_scalar(offset)?.to_int(off_t.size)?; + let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; let whence = this.read_scalar(whence)?.to_i32()?; this.lseek64(fd, offset, whence, dest)?; } "ftruncate64" => { - let off64_t = this.libc_ty_layout("off64_t"); - let [fd, length] = this.check_shim_abi( + let [fd, length] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, libc::off64_t) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32, off64_t.ty], - this.tcx.types.i32, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; - let length = this.read_scalar(length)?.to_int(off64_t.size)?; + let length = this.read_scalar(length)?.to_int(length.layout.size)?; let result = this.ftruncate64(fd, length)?; this.write_scalar(result, dest)?; } "ftruncate" => { - let off_t = this.libc_ty_layout("off_t"); - let [fd, length] = this.check_shim_abi( + let [fd, length] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, libc::off_t) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32, off_t.ty], - this.tcx.types.i32, args, )?; let fd = this.read_scalar(fd)?.to_i32()?; - let length = this.read_scalar(length)?.to_int(off_t.size)?; + let length = this.read_scalar(length)?.to_int(length.layout.size)?; let result = this.ftruncate64(fd, length)?; this.write_scalar(result, dest)?; } "fsync" => { - let [fd] = this.check_shim_abi( + let [fd] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32], - this.tcx.types.i32, args, )?; let result = this.fsync(fd)?; this.write_scalar(result, dest)?; } "fdatasync" => { - let [fd] = this.check_shim_abi( + let [fd] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32], - this.tcx.types.i32, args, )?; let result = this.fdatasync(fd)?; this.write_scalar(result, dest)?; } "readlink" => { - let [pathname, buf, bufsize] = this.check_shim_abi( + let [pathname, buf, bufsize] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _, *mut _, usize) -> isize), link_name, abi, - ExternAbi::C { unwind: false }, - [ - this.machine.layouts.const_raw_ptr.ty, - this.machine.layouts.mut_raw_ptr.ty, - this.tcx.types.usize, - ], - this.tcx.types.isize, args, )?; let result = this.readlink(pathname, buf, bufsize)?; this.write_scalar(Scalar::from_target_isize(result, this), dest)?; } "posix_fadvise" => { - let off_t = this.libc_ty_layout("off_t"); - let [fd, offset, len, advice] = this.check_shim_abi( + let [fd, offset, len, advice] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, libc::off_t, libc::off_t, i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.tcx.types.i32, off_t.ty, off_t.ty, this.tcx.types.i32], - this.tcx.types.i32, args, )?; this.read_scalar(fd)?.to_i32()?; - this.read_scalar(offset)?.to_int(off_t.size)?; - this.read_scalar(len)?.to_int(off_t.size)?; + this.read_scalar(offset)?.to_int(offset.layout.size)?; + this.read_scalar(len)?.to_int(len.layout.size)?; this.read_scalar(advice)?.to_i32()?; // fadvise is only informational, we can ignore it. this.write_null(dest)?; } "realpath" => { - let [path, resolved_path] = this.check_shim_abi( + let [path, resolved_path] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _, *mut _) -> *mut _), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty, this.machine.layouts.mut_raw_ptr.ty], - this.machine.layouts.mut_raw_ptr.ty, args, )?; let result = this.realpath(path, resolved_path)?; this.write_scalar(result, dest)?; } "mkstemp" => { - let [template] = this.check_shim_abi( + let [template] = this.check_shim_sig( + shim_sig!(extern "C" fn(*mut _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.mut_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.mkstemp(template)?; @@ -618,29 +509,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Unnamed sockets and pipes "socketpair" => { - let [domain, type_, protocol, sv] = this.check_shim_abi( + let [domain, type_, protocol, sv] = this.check_shim_sig( + shim_sig!(extern "C" fn(i32, i32, i32, *mut _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [ - this.tcx.types.i32, - this.tcx.types.i32, - this.tcx.types.i32, - this.machine.layouts.mut_raw_ptr.ty, - ], - this.tcx.types.i32, args, )?; let result = this.socketpair(domain, type_, protocol, sv)?; this.write_scalar(result, dest)?; } "pipe" => { - let [pipefd] = this.check_shim_abi( + let [pipefd] = this.check_shim_sig( + shim_sig!(extern "C" fn(*mut _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.mut_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.pipe2(pipefd, /*flags*/ None)?; @@ -649,12 +531,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "pipe2" => { // Currently this function does not exist on all Unixes, e.g. on macOS. this.check_target_os(&["linux", "freebsd", "solaris", "illumos"], link_name)?; - let [pipefd, flags] = this.check_shim_abi( + let [pipefd, flags] = this.check_shim_sig( + shim_sig!(extern "C" fn(*mut _, i32) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.mut_raw_ptr.ty, this.tcx.types.i32], - this.tcx.types.i32, args, )?; let result = this.pipe2(pipefd, Some(flags))?; @@ -663,36 +543,30 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Time "gettimeofday" => { - let [tv, tz] = this.check_shim_abi( + let [tv, tz] = this.check_shim_sig( + shim_sig!(extern "C" fn(*mut _, *mut _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.mut_raw_ptr.ty, this.machine.layouts.mut_raw_ptr.ty], - this.tcx.types.i32, args, )?; let result = this.gettimeofday(tv, tz)?; this.write_scalar(result, dest)?; } "localtime_r" => { - let [timep, result_op] = this.check_shim_abi( + let [timep, result_op] = this.check_shim_sig( + shim_sig!(extern "C" fn(*const _, *mut _) -> *mut _), link_name, abi, - ExternAbi::C { unwind: false }, - [this.machine.layouts.const_raw_ptr.ty, this.machine.layouts.mut_raw_ptr.ty], - this.machine.layouts.mut_raw_ptr.ty, args, )?; let result = this.localtime_r(timep, result_op)?; this.write_pointer(result, dest)?; } "clock_gettime" => { - let [clk_id, tp] = this.check_shim_abi( + let [clk_id, tp] = this.check_shim_sig( + shim_sig!(extern "C" fn(libc::clockid_t, *mut _) -> i32), link_name, abi, - ExternAbi::C { unwind: false }, - [this.libc_ty_layout("clockid_t").ty, this.machine.layouts.mut_raw_ptr.ty], - this.tcx.types.i32, args, )?; this.clock_gettime(clk_id, tp, dest)?; @@ -700,20 +574,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Allocation "posix_memalign" => { - let [memptr, align, size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [memptr, align, size] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.posix_memalign(memptr, align, size)?; this.write_scalar(result, dest)?; } "mmap" => { let [addr, length, prot, flags, fd, offset] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?; let ptr = this.mmap(addr, length, prot, flags, fd, offset)?; this.write_scalar(ptr, dest)?; } "munmap" => { - let [addr, length] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [addr, length] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.munmap(addr, length)?; this.write_scalar(result, dest)?; } @@ -721,7 +597,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "reallocarray" => { // Currently this function does not exist on all Unixes, e.g. on macOS. this.check_target_os(&["linux", "freebsd", "android"], link_name)?; - let [ptr, nmemb, size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, nmemb, size] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.read_pointer(ptr)?; let nmemb = this.read_target_usize(nmemb)?; let size = this.read_target_usize(size)?; @@ -744,14 +621,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "aligned_alloc" => { // This is a C11 function, we assume all Unixes have it. // (MSVC explicitly does not support this.) - let [align, size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [align, size] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let res = this.aligned_alloc(align, size)?; this.write_pointer(res, dest)?; } // Dynamic symbol loading "dlsym" => { - let [handle, symbol] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [handle, symbol] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.read_target_usize(handle)?; let symbol = this.read_pointer(symbol)?; let name = this.read_c_str(symbol)?; @@ -767,7 +646,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Thread-local storage "pthread_key_create" => { - let [key, dtor] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [key, dtor] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let key_place = this.deref_pointer_as(key, this.libc_ty_layout("pthread_key_t"))?; let dtor = this.read_pointer(dtor)?; @@ -795,21 +674,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_null(dest)?; } "pthread_key_delete" => { - let [key] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [key] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let key = this.read_scalar(key)?.to_bits(key.layout.size)?; this.machine.tls.delete_tls_key(key)?; // Return success (0) this.write_null(dest)?; } "pthread_getspecific" => { - let [key] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [key] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let key = this.read_scalar(key)?.to_bits(key.layout.size)?; let active_thread = this.active_thread(); let ptr = this.machine.tls.load_tls(key, active_thread, this)?; this.write_scalar(ptr, dest)?; } "pthread_setspecific" => { - let [key, new_ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [key, new_ptr] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let key = this.read_scalar(key)?.to_bits(key.layout.size)?; let active_thread = this.active_thread(); let new_data = this.read_scalar(new_ptr)?; @@ -821,117 +701,124 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Synchronization primitives "pthread_mutexattr_init" => { - let [attr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [attr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_mutexattr_init(attr)?; this.write_null(dest)?; } "pthread_mutexattr_settype" => { - let [attr, kind] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [attr, kind] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.pthread_mutexattr_settype(attr, kind)?; this.write_scalar(result, dest)?; } "pthread_mutexattr_destroy" => { - let [attr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [attr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_mutexattr_destroy(attr)?; this.write_null(dest)?; } "pthread_mutex_init" => { - let [mutex, attr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [mutex, attr] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_mutex_init(mutex, attr)?; this.write_null(dest)?; } "pthread_mutex_lock" => { - let [mutex] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [mutex] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_mutex_lock(mutex, dest)?; } "pthread_mutex_trylock" => { - let [mutex] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [mutex] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.pthread_mutex_trylock(mutex)?; this.write_scalar(result, dest)?; } "pthread_mutex_unlock" => { - let [mutex] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [mutex] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.pthread_mutex_unlock(mutex)?; this.write_scalar(result, dest)?; } "pthread_mutex_destroy" => { - let [mutex] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [mutex] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_mutex_destroy(mutex)?; this.write_int(0, dest)?; } "pthread_rwlock_rdlock" => { - let [rwlock] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_rwlock_rdlock(rwlock, dest)?; } "pthread_rwlock_tryrdlock" => { - let [rwlock] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.pthread_rwlock_tryrdlock(rwlock)?; this.write_scalar(result, dest)?; } "pthread_rwlock_wrlock" => { - let [rwlock] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_rwlock_wrlock(rwlock, dest)?; } "pthread_rwlock_trywrlock" => { - let [rwlock] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.pthread_rwlock_trywrlock(rwlock)?; this.write_scalar(result, dest)?; } "pthread_rwlock_unlock" => { - let [rwlock] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_rwlock_unlock(rwlock)?; this.write_null(dest)?; } "pthread_rwlock_destroy" => { - let [rwlock] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [rwlock] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_rwlock_destroy(rwlock)?; this.write_null(dest)?; } "pthread_condattr_init" => { - let [attr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [attr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_condattr_init(attr)?; this.write_null(dest)?; } "pthread_condattr_setclock" => { - let [attr, clock_id] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [attr, clock_id] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.pthread_condattr_setclock(attr, clock_id)?; this.write_scalar(result, dest)?; } "pthread_condattr_getclock" => { - let [attr, clock_id] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [attr, clock_id] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_condattr_getclock(attr, clock_id)?; this.write_null(dest)?; } "pthread_condattr_destroy" => { - let [attr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [attr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_condattr_destroy(attr)?; this.write_null(dest)?; } "pthread_cond_init" => { - let [cond, attr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [cond, attr] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_cond_init(cond, attr)?; this.write_null(dest)?; } "pthread_cond_signal" => { - let [cond] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [cond] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_cond_signal(cond)?; this.write_null(dest)?; } "pthread_cond_broadcast" => { - let [cond] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [cond] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_cond_broadcast(cond)?; this.write_null(dest)?; } "pthread_cond_wait" => { - let [cond, mutex] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [cond, mutex] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_cond_wait(cond, mutex, dest)?; } "pthread_cond_timedwait" => { - let [cond, mutex, abstime] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [cond, mutex, abstime] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_cond_timedwait(cond, mutex, abstime, dest)?; } "pthread_cond_destroy" => { - let [cond] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [cond] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_cond_destroy(cond)?; this.write_null(dest)?; } @@ -939,31 +826,33 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Threading "pthread_create" => { let [thread, attr, start, arg] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_create(thread, attr, start, arg)?; this.write_null(dest)?; } "pthread_join" => { - let [thread, retval] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, retval] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.pthread_join(thread, retval, dest)?; } "pthread_detach" => { - let [thread] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let res = this.pthread_detach(thread)?; this.write_scalar(res, dest)?; } "pthread_self" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let res = this.pthread_self()?; this.write_scalar(res, dest)?; } "sched_yield" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.sched_yield()?; this.write_null(dest)?; } "nanosleep" => { - let [duration, rem] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [duration, rem] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.nanosleep(duration, rem)?; this.write_scalar(result, dest)?; } @@ -974,14 +863,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { link_name, )?; let [clock_id, flags, req, rem] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.clock_nanosleep(clock_id, flags, req, rem)?; this.write_scalar(result, dest)?; } "sched_getaffinity" => { // Currently this function does not exist on all Unixes, e.g. on macOS. this.check_target_os(&["linux", "freebsd", "android"], link_name)?; - let [pid, cpusetsize, mask] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [pid, cpusetsize, mask] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let pid = this.read_scalar(pid)?.to_u32()?; let cpusetsize = this.read_target_usize(cpusetsize)?; let mask = this.read_pointer(mask)?; @@ -1018,7 +908,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "sched_setaffinity" => { // Currently this function does not exist on all Unixes, e.g. on macOS. this.check_target_os(&["linux", "freebsd", "android"], link_name)?; - let [pid, cpusetsize, mask] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [pid, cpusetsize, mask] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let pid = this.read_scalar(pid)?.to_u32()?; let cpusetsize = this.read_target_usize(cpusetsize)?; let mask = this.read_pointer(mask)?; @@ -1058,13 +949,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Miscellaneous "isatty" => { - let [fd] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [fd] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.isatty(fd)?; this.write_scalar(result, dest)?; } "pthread_atfork" => { let [prepare, parent, child] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.read_pointer(prepare)?; this.read_pointer(parent)?; this.read_pointer(child)?; @@ -1078,7 +969,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { &["linux", "macos", "freebsd", "illumos", "solaris", "android"], link_name, )?; - let [buf, bufsize] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [buf, bufsize] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let buf = this.read_pointer(buf)?; let bufsize = this.read_target_usize(bufsize)?; @@ -1096,7 +988,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "strerror_r" => { - let [errnum, buf, buflen] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [errnum, buf, buflen] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.strerror_r(errnum, buf, buflen)?; this.write_scalar(result, dest)?; } @@ -1108,7 +1001,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { &["linux", "freebsd", "illumos", "solaris", "android"], link_name, )?; - let [ptr, len, flags] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, len, flags] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.read_pointer(ptr)?; let len = this.read_target_usize(len)?; let _flags = this.read_scalar(flags)?.to_i32()?; @@ -1120,7 +1014,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // This function is non-standard but exists with the same signature and // same behavior (eg never fails) on FreeBSD and Solaris/Illumos. this.check_target_os(&["freebsd", "illumos", "solaris"], link_name)?; - let [ptr, len] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, len] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.read_pointer(ptr)?; let len = this.read_target_usize(len)?; this.gen_random(ptr, len)?; @@ -1144,12 +1038,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { link_name, )?; // This function looks and behaves excatly like miri_start_unwind. - let [payload] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [payload] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.handle_miri_start_unwind(payload)?; return interp_ok(EmulateItemResult::NeedsUnwind); } "getuid" | "geteuid" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // For now, just pretend we always have this fixed UID. this.write_int(UID, dest)?; } @@ -1157,7 +1051,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. "pthread_attr_getguardsize" if this.frame_in_std() => { - let [_attr, guard_size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [_attr, guard_size] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let guard_size_layout = this.machine.layouts.usize; let guard_size = this.deref_pointer_as(guard_size, guard_size_layout)?; this.write_scalar( @@ -1170,11 +1065,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "pthread_attr_init" | "pthread_attr_destroy" if this.frame_in_std() => { - let [_] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [_] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_null(dest)?; } "pthread_attr_setstacksize" if this.frame_in_std() => { - let [_, _] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [_, _] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_null(dest)?; } @@ -1182,7 +1077,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // We don't support "pthread_attr_setstack", so we just pretend all stacks have the same values here. // Hence we can mostly ignore the input `attr_place`. let [attr_place, addr_place, size_place] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let _attr_place = this.deref_pointer_as(attr_place, this.libc_ty_layout("pthread_attr_t"))?; let addr_place = this.deref_pointer_as(addr_place, this.machine.layouts.usize)?; @@ -1202,18 +1097,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "signal" | "sigaltstack" if this.frame_in_std() => { - let [_, _] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [_, _] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_null(dest)?; } "sigaction" | "mprotect" if this.frame_in_std() => { - let [_, _, _] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [_, _, _] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_null(dest)?; } "getpwuid_r" | "__posix_getpwuid_r" if this.frame_in_std() => { // getpwuid_r is the standard name, __posix_getpwuid_r is used on solarish let [uid, pwd, buf, buflen, result] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.check_no_isolation("`getpwuid_r`")?; let uid = this.read_scalar(uid)?.to_u32()?; diff --git a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs index 33564a2f84c7..9e247053fbcd 100644 --- a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs @@ -24,7 +24,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // Threading "pthread_setname_np" => { - let [thread, name] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, name] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let max_len = u64::MAX; // FreeBSD does not seem to have a limit. let res = match this.pthread_setname_np( this.read_scalar(thread)?, @@ -39,7 +40,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "pthread_getname_np" => { - let [thread, name, len] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, name, len] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // FreeBSD's pthread_getname_np uses strlcpy, which truncates the resulting value, // but always adds a null terminator (except for zero-sized buffers). // https://github.com/freebsd/freebsd-src/blob/c2d93a803acef634bd0eede6673aeea59e90c277/lib/libthr/thread/thr_info.c#L119-L144 @@ -57,7 +59,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "pthread_getthreadid_np" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.unix_gettid(link_name.as_str())?; this.write_scalar(result, dest)?; } @@ -65,7 +67,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "cpuset_getaffinity" => { // The "same" kind of api as `sched_getaffinity` but more fine grained control for FreeBSD specifically. let [level, which, id, set_size, mask] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let level = this.read_scalar(level)?.to_i32()?; let which = this.read_scalar(which)?.to_i32()?; @@ -129,7 +131,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Synchronization primitives "_umtx_op" => { let [obj, op, val, uaddr, uaddr2] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this._umtx_op(obj, op, val, uaddr, uaddr2, dest)?; } @@ -137,29 +139,30 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // For those, we both intercept `func` and `call@FBSD_1.0` symbols cases // since freebsd 12 the former form can be expected. "stat" | "stat@FBSD_1.0" => { - let [path, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [path, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_stat(path, buf)?; this.write_scalar(result, dest)?; } "lstat" | "lstat@FBSD_1.0" => { - let [path, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [path, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_lstat(path, buf)?; this.write_scalar(result, dest)?; } "fstat" | "fstat@FBSD_1.0" => { - let [fd, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [fd, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_fstat(fd, buf)?; this.write_scalar(result, dest)?; } "readdir_r" | "readdir_r@FBSD_1.0" => { - let [dirp, entry, result] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [dirp, entry, result] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_readdir_r(dirp, entry, result)?; this.write_scalar(result, dest)?; } // Miscellaneous "__error" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let errno_place = this.last_error_place()?; this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; } @@ -167,7 +170,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. "pthread_attr_get_np" if this.frame_in_std() => { - let [_thread, _attr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [_thread, _attr] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_null(dest)?; } diff --git a/src/tools/miri/src/shims/unix/fs.rs b/src/tools/miri/src/shims/unix/fs.rs index 0f2878ad26c8..f9bcacf64c41 100644 --- a/src/tools/miri/src/shims/unix/fs.rs +++ b/src/tools/miri/src/shims/unix/fs.rs @@ -13,9 +13,9 @@ use rustc_abi::Size; use rustc_data_structures::fx::FxHashMap; use self::shims::time::system_time_to_duration; -use crate::helpers::check_min_vararg_count; use crate::shims::files::FileHandle; use crate::shims::os_str::bytes_to_os_str; +use crate::shims::sig::check_min_vararg_count; use crate::shims::unix::fd::{FlockOp, UnixFileDescription}; use crate::*; diff --git a/src/tools/miri/src/shims/unix/linux/foreign_items.rs b/src/tools/miri/src/shims/unix/linux/foreign_items.rs index b3e99e6cc68f..e7e0c3b6ecd9 100644 --- a/src/tools/miri/src/shims/unix/linux/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/linux/foreign_items.rs @@ -37,48 +37,50 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // File related shims "readdir64" => { - let [dirp] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [dirp] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.linux_solarish_readdir64("dirent64", dirp)?; this.write_scalar(result, dest)?; } "sync_file_range" => { let [fd, offset, nbytes, flags] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.sync_file_range(fd, offset, nbytes, flags)?; this.write_scalar(result, dest)?; } "statx" => { let [dirfd, pathname, flags, mask, statxbuf] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.linux_statx(dirfd, pathname, flags, mask, statxbuf)?; this.write_scalar(result, dest)?; } // epoll, eventfd "epoll_create1" => { - let [flag] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [flag] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.epoll_create1(flag)?; this.write_scalar(result, dest)?; } "epoll_ctl" => { - let [epfd, op, fd, event] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [epfd, op, fd, event] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.epoll_ctl(epfd, op, fd, event)?; this.write_scalar(result, dest)?; } "epoll_wait" => { let [epfd, events, maxevents, timeout] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.epoll_wait(epfd, events, maxevents, timeout, dest)?; } "eventfd" => { - let [val, flag] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [val, flag] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.eventfd(val, flag)?; this.write_scalar(result, dest)?; } // Threading "pthread_setname_np" => { - let [thread, name] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, name] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let res = match this.pthread_setname_np( this.read_scalar(thread)?, this.read_scalar(name)?, @@ -93,7 +95,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "pthread_getname_np" => { - let [thread, name, len] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, name, len] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // The function's behavior isn't portable between platforms. // In case of glibc, the length of the output buffer must // be not shorter than TASK_COMM_LEN. @@ -116,7 +119,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "gettid" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.unix_gettid(link_name.as_str())?; this.write_scalar(result, dest)?; } @@ -129,34 +132,35 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Miscellaneous "mmap64" => { let [addr, length, prot, flags, fd, offset] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let offset = this.read_scalar(offset)?.to_i64()?; let ptr = this.mmap(addr, length, prot, flags, fd, offset.into())?; this.write_scalar(ptr, dest)?; } "mremap" => { let ([old_address, old_size, new_size, flags], _) = - this.check_shim_variadic(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?; let ptr = this.mremap(old_address, old_size, new_size, flags)?; this.write_scalar(ptr, dest)?; } "__xpg_strerror_r" => { - let [errnum, buf, buflen] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [errnum, buf, buflen] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.strerror_r(errnum, buf, buflen)?; this.write_scalar(result, dest)?; } "__errno_location" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let errno_place = this.last_error_place()?; this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; } "__libc_current_sigrtmin" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_int(SIGRTMIN, dest)?; } "__libc_current_sigrtmax" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_int(SIGRTMAX, dest)?; } @@ -164,7 +168,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. "pthread_getattr_np" if this.frame_in_std() => { - let [_thread, _attr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [_thread, _attr] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_null(dest)?; } diff --git a/src/tools/miri/src/shims/unix/linux_like/sync.rs b/src/tools/miri/src/shims/unix/linux_like/sync.rs index 9fad74c0241e..5f032c52deeb 100644 --- a/src/tools/miri/src/shims/unix/linux_like/sync.rs +++ b/src/tools/miri/src/shims/unix/linux_like/sync.rs @@ -1,5 +1,5 @@ use crate::concurrency::sync::FutexRef; -use crate::helpers::check_min_vararg_count; +use crate::shims::sig::check_min_vararg_count; use crate::*; struct LinuxFutex { diff --git a/src/tools/miri/src/shims/unix/linux_like/syscall.rs b/src/tools/miri/src/shims/unix/linux_like/syscall.rs index d3534e6e1bc6..106e6c448d06 100644 --- a/src/tools/miri/src/shims/unix/linux_like/syscall.rs +++ b/src/tools/miri/src/shims/unix/linux_like/syscall.rs @@ -3,7 +3,7 @@ use rustc_middle::ty::Ty; use rustc_span::Symbol; use rustc_target::callconv::FnAbi; -use crate::helpers::check_min_vararg_count; +use crate::shims::sig::check_min_vararg_count; use crate::shims::unix::env::EvalContextExt; use crate::shims::unix::linux_like::eventfd::EvalContextExt as _; use crate::shims::unix::linux_like::sync::futex; @@ -16,7 +16,7 @@ pub fn syscall<'tcx>( args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let ([op], varargs) = ecx.check_shim_variadic(abi, CanonAbi::C, link_name, args)?; + let ([op], varargs) = ecx.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?; // The syscall variadic function is legal to call with more arguments than needed, // extra arguments are simply ignored. The important check is that when we use an // argument, we have to also check all arguments *before* it to ensure that they diff --git a/src/tools/miri/src/shims/unix/macos/foreign_items.rs b/src/tools/miri/src/shims/unix/macos/foreign_items.rs index 233037180910..297d903c6ba4 100644 --- a/src/tools/miri/src/shims/unix/macos/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/macos/foreign_items.rs @@ -35,64 +35,67 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // errno "__error" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let errno_place = this.last_error_place()?; this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; } // File related shims "close$NOCANCEL" => { - let [result] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [result] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.close(result)?; this.write_scalar(result, dest)?; } "stat" | "stat64" | "stat$INODE64" => { - let [path, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [path, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_stat(path, buf)?; this.write_scalar(result, dest)?; } "lstat" | "lstat64" | "lstat$INODE64" => { - let [path, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [path, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_lstat(path, buf)?; this.write_scalar(result, dest)?; } "fstat" | "fstat64" | "fstat$INODE64" => { - let [fd, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [fd, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_fstat(fd, buf)?; this.write_scalar(result, dest)?; } "opendir$INODE64" => { - let [name] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [name] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.opendir(name)?; this.write_scalar(result, dest)?; } "readdir_r" | "readdir_r$INODE64" => { - let [dirp, entry, result] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [dirp, entry, result] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_readdir_r(dirp, entry, result)?; this.write_scalar(result, dest)?; } "realpath$DARWIN_EXTSN" => { - let [path, resolved_path] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [path, resolved_path] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.realpath(path, resolved_path)?; this.write_scalar(result, dest)?; } "ioctl" => { let ([fd_num, cmd], varargs) = - this.check_shim_variadic(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_variadic_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.ioctl(fd_num, cmd, varargs)?; this.write_scalar(result, dest)?; } // Environment related shims "_NSGetEnviron" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let environ = this.machine.env_vars.unix().environ(); this.write_pointer(environ, dest)?; } // Random data generation "CCRandomGenerateBytes" => { - let [bytes, count] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [bytes, count] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let bytes = this.read_pointer(bytes)?; let count = this.read_target_usize(count)?; let success = this.eval_libc_i32("kCCSuccess"); @@ -102,28 +105,29 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Time related shims "mach_absolute_time" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.mach_absolute_time()?; this.write_scalar(result, dest)?; } "mach_timebase_info" => { - let [info] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [info] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.mach_timebase_info(info)?; this.write_scalar(result, dest)?; } // Access to command-line arguments "_NSGetArgc" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_pointer(this.machine.argc.expect("machine must be initialized"), dest)?; } "_NSGetArgv" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.write_pointer(this.machine.argv.expect("machine must be initialized"), dest)?; } "_NSGetExecutablePath" => { - let [buf, bufsize] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [buf, bufsize] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.check_no_isolation("`_NSGetExecutablePath`")?; let buf_ptr = this.read_pointer(buf)?; @@ -148,7 +152,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Thread-local storage "_tlv_atexit" => { - let [dtor, data] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [dtor, data] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let dtor = this.read_pointer(dtor)?; let dtor = this.get_ptr_fn(dtor)?.as_instance()?; let data = this.read_scalar(data)?; @@ -158,13 +163,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Querying system information "pthread_get_stackaddr_np" => { - let [thread] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.read_target_usize(thread)?; let stack_addr = Scalar::from_uint(this.machine.stack_addr, this.pointer_size()); this.write_scalar(stack_addr, dest)?; } "pthread_get_stacksize_np" => { - let [thread] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.read_target_usize(thread)?; let stack_size = Scalar::from_uint(this.machine.stack_size, this.pointer_size()); this.write_scalar(stack_size, dest)?; @@ -172,7 +177,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Threading "pthread_setname_np" => { - let [name] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [name] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // The real implementation has logic in two places: // * in userland at https://github.com/apple-oss-distributions/libpthread/blob/c032e0b076700a0a47db75528a282b8d3a06531a/src/pthread.c#L1178-L1200, @@ -199,7 +204,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "pthread_getname_np" => { - let [thread, name, len] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, name, len] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // The function's behavior isn't portable between platforms. // In case of macOS, a truncated name (due to a too small buffer) @@ -223,7 +229,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "pthread_threadid_np" => { - let [thread, tid_ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, tid_ptr] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let res = this.apple_pthread_threadip_np(thread, tid_ptr)?; this.write_scalar(res, dest)?; } @@ -231,7 +238,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Synchronization primitives "os_sync_wait_on_address" => { let [addr_op, value_op, size_op, flags_op] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_sync_wait_on_address( addr_op, value_op, @@ -243,7 +250,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "os_sync_wait_on_address_with_deadline" => { let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_sync_wait_on_address( addr_op, value_op, @@ -255,7 +262,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "os_sync_wait_on_address_with_timeout" => { let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_sync_wait_on_address( addr_op, value_op, @@ -267,36 +274,36 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "os_sync_wake_by_address_any" => { let [addr_op, size_op, flags_op] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_sync_wake_by_address( addr_op, size_op, flags_op, /* all */ false, dest, )?; } "os_sync_wake_by_address_all" => { let [addr_op, size_op, flags_op] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_sync_wake_by_address( addr_op, size_op, flags_op, /* all */ true, dest, )?; } "os_unfair_lock_lock" => { - let [lock_op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_unfair_lock_lock(lock_op)?; } "os_unfair_lock_trylock" => { - let [lock_op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_unfair_lock_trylock(lock_op, dest)?; } "os_unfair_lock_unlock" => { - let [lock_op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_unfair_lock_unlock(lock_op)?; } "os_unfair_lock_assert_owner" => { - let [lock_op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_unfair_lock_assert_owner(lock_op)?; } "os_unfair_lock_assert_not_owner" => { - let [lock_op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [lock_op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.os_unfair_lock_assert_not_owner(lock_op)?; } diff --git a/src/tools/miri/src/shims/unix/solarish/foreign_items.rs b/src/tools/miri/src/shims/unix/solarish/foreign_items.rs index e3d15b89be6d..d7033a65fe22 100644 --- a/src/tools/miri/src/shims/unix/solarish/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/solarish/foreign_items.rs @@ -27,32 +27,34 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // epoll, eventfd (NOT available on Solaris!) "epoll_create1" => { this.assert_target_os("illumos", "epoll_create1"); - let [flag] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [flag] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.epoll_create1(flag)?; this.write_scalar(result, dest)?; } "epoll_ctl" => { this.assert_target_os("illumos", "epoll_ctl"); - let [epfd, op, fd, event] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [epfd, op, fd, event] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.epoll_ctl(epfd, op, fd, event)?; this.write_scalar(result, dest)?; } "epoll_wait" => { this.assert_target_os("illumos", "epoll_wait"); let [epfd, events, maxevents, timeout] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.epoll_wait(epfd, events, maxevents, timeout, dest)?; } "eventfd" => { this.assert_target_os("illumos", "eventfd"); - let [val, flag] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [val, flag] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.eventfd(val, flag)?; this.write_scalar(result, dest)?; } // Threading "pthread_setname_np" => { - let [thread, name] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, name] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // THREAD_NAME_MAX allows a thread name of 31+1 length // https://github.com/illumos/illumos-gate/blob/7671517e13b8123748eda4ef1ee165c6d9dba7fe/usr/src/uts/common/sys/thread.h#L613 let max_len = 32; @@ -70,7 +72,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "pthread_getname_np" => { - let [thread, name, len] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [thread, name, len] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // See https://illumos.org/man/3C/pthread_getname_np for the error codes. let res = match this.pthread_getname_np( this.read_scalar(thread)?, @@ -87,22 +90,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // File related shims "stat" | "stat64" => { - let [path, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [path, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_stat(path, buf)?; this.write_scalar(result, dest)?; } "lstat" | "lstat64" => { - let [path, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [path, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_lstat(path, buf)?; this.write_scalar(result, dest)?; } "fstat" | "fstat64" => { - let [fd, buf] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [fd, buf] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.macos_fbsd_solarish_fstat(fd, buf)?; this.write_scalar(result, dest)?; } "readdir" => { - let [dirp] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [dirp] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.linux_solarish_readdir64("dirent", dirp)?; this.write_scalar(result, dest)?; } @@ -110,20 +113,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Sockets and pipes "__xnet_socketpair" => { let [domain, type_, protocol, sv] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.socketpair(domain, type_, protocol, sv)?; this.write_scalar(result, dest)?; } // Miscellaneous "___errno" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let errno_place = this.last_error_place()?; this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; } "stack_getbounds" => { - let [stack] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [stack] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let stack = this.deref_pointer_as(stack, this.libc_ty_layout("stack_t"))?; this.write_int_fields_named( @@ -141,7 +144,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "pset_info" => { - let [pset, tpe, cpus, list] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [pset, tpe, cpus, list] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // We do not need to handle the current process cpu mask, available_parallelism // implementation pass null anyway. We only care for the number of // cpus. @@ -170,7 +174,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "__sysconf_xpg7" => { - let [val] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [val] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.sysconf(val)?; this.write_scalar(result, dest)?; } diff --git a/src/tools/miri/src/shims/unwind.rs b/src/tools/miri/src/shims/unwind.rs index ba0c50b54b47..0dd2b20487d3 100644 --- a/src/tools/miri/src/shims/unwind.rs +++ b/src/tools/miri/src/shims/unwind.rs @@ -16,7 +16,6 @@ use rustc_abi::ExternAbi; use rustc_middle::mir; use rustc_target::spec::PanicStrategy; -use self::helpers::check_intrinsic_arg_count; use crate::*; /// Holds all of the relevant data for when unwinding hits a `try` frame. @@ -60,7 +59,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Handles the `catch_unwind` intrinsic. fn handle_catch_unwind( &mut self, - args: &[OpTy<'tcx>], + try_fn: &OpTy<'tcx>, + data: &OpTy<'tcx>, + catch_fn: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ret: Option, ) -> InterpResult<'tcx> { @@ -78,7 +79,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // a pointer to `Box`. // Get all the arguments. - let [try_fn, data, catch_fn] = check_intrinsic_arg_count(args)?; let try_fn = this.read_pointer(try_fn)?; let data = this.read_immediate(data)?; let catch_fn = this.read_pointer(catch_fn)?; diff --git a/src/tools/miri/src/shims/wasi/foreign_items.rs b/src/tools/miri/src/shims/wasi/foreign_items.rs index 8d92d0f3381f..bfcdbd8130d8 100644 --- a/src/tools/miri/src/shims/wasi/foreign_items.rs +++ b/src/tools/miri/src/shims/wasi/foreign_items.rs @@ -23,12 +23,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // Allocation "posix_memalign" => { - let [memptr, align, size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [memptr, align, size] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let result = this.posix_memalign(memptr, align, size)?; this.write_scalar(result, dest)?; } "aligned_alloc" => { - let [align, size] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [align, size] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let res = this.aligned_alloc(align, size)?; this.write_pointer(res, dest)?; } diff --git a/src/tools/miri/src/shims/windows/foreign_items.rs b/src/tools/miri/src/shims/windows/foreign_items.rs index 959abc0bacaa..7b13f1d90807 100644 --- a/src/tools/miri/src/shims/windows/foreign_items.rs +++ b/src/tools/miri/src/shims/windows/foreign_items.rs @@ -157,42 +157,44 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // Environment related shims "GetEnvironmentVariableW" => { - let [name, buf, size] = this.check_shim(abi, sys_conv, link_name, args)?; + let [name, buf, size] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.GetEnvironmentVariableW(name, buf, size)?; this.write_scalar(result, dest)?; } "SetEnvironmentVariableW" => { - let [name, value] = this.check_shim(abi, sys_conv, link_name, args)?; + let [name, value] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.SetEnvironmentVariableW(name, value)?; this.write_scalar(result, dest)?; } "GetEnvironmentStringsW" => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.GetEnvironmentStringsW()?; this.write_pointer(result, dest)?; } "FreeEnvironmentStringsW" => { - let [env_block] = this.check_shim(abi, sys_conv, link_name, args)?; + let [env_block] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.FreeEnvironmentStringsW(env_block)?; this.write_scalar(result, dest)?; } "GetCurrentDirectoryW" => { - let [size, buf] = this.check_shim(abi, sys_conv, link_name, args)?; + let [size, buf] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.GetCurrentDirectoryW(size, buf)?; this.write_scalar(result, dest)?; } "SetCurrentDirectoryW" => { - let [path] = this.check_shim(abi, sys_conv, link_name, args)?; + let [path] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.SetCurrentDirectoryW(path)?; this.write_scalar(result, dest)?; } "GetUserProfileDirectoryW" => { - let [token, buf, size] = this.check_shim(abi, sys_conv, link_name, args)?; + let [token, buf, size] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.GetUserProfileDirectoryW(token, buf, size)?; this.write_scalar(result, dest)?; } "GetCurrentProcessId" => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.GetCurrentProcessId()?; this.write_scalar(result, dest)?; } @@ -209,7 +211,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { n, byte_offset, key, - ] = this.check_shim(abi, sys_conv, link_name, args)?; + ] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.NtWriteFile( handle, event, @@ -234,7 +236,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { n, byte_offset, key, - ] = this.check_shim(abi, sys_conv, link_name, args)?; + ] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.NtReadFile( handle, event, @@ -250,7 +252,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "GetFullPathNameW" => { let [filename, size, buffer, filepart] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.check_no_isolation("`GetFullPathNameW`")?; let filename = this.read_pointer(filename)?; @@ -287,7 +289,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { creation_disposition, flags_and_attributes, template_file, - ] = this.check_shim(abi, sys_conv, link_name, args)?; + ] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let handle = this.CreateFileW( file_name, desired_access, @@ -300,18 +302,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(handle.to_scalar(this), dest)?; } "GetFileInformationByHandle" => { - let [handle, info] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle, info] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let res = this.GetFileInformationByHandle(handle, info)?; this.write_scalar(res, dest)?; } "DeleteFileW" => { - let [file_name] = this.check_shim(abi, sys_conv, link_name, args)?; + let [file_name] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let res = this.DeleteFileW(file_name)?; this.write_scalar(res, dest)?; } "SetFilePointerEx" => { let [file, distance_to_move, new_file_pointer, move_method] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let res = this.SetFilePointerEx(file, distance_to_move, new_file_pointer, move_method)?; this.write_scalar(res, dest)?; @@ -319,7 +321,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Allocation "HeapAlloc" => { - let [handle, flags, size] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle, flags, size] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.read_target_isize(handle)?; let flags = this.read_scalar(flags)?.to_u32()?; let size = this.read_target_usize(size)?; @@ -341,7 +344,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_pointer(ptr, dest)?; } "HeapFree" => { - let [handle, flags, ptr] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle, flags, ptr] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.read_target_isize(handle)?; this.read_scalar(flags)?.to_u32()?; let ptr = this.read_pointer(ptr)?; @@ -354,7 +358,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "HeapReAlloc" => { let [handle, flags, old_ptr, size] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.read_target_isize(handle)?; this.read_scalar(flags)?.to_u32()?; let old_ptr = this.read_pointer(old_ptr)?; @@ -374,7 +378,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_pointer(new_ptr, dest)?; } "LocalFree" => { - let [ptr] = this.check_shim(abi, sys_conv, link_name, args)?; + let [ptr] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let ptr = this.read_pointer(ptr)?; // "If the hMem parameter is NULL, LocalFree ignores the parameter and returns NULL." // (https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-localfree) @@ -386,17 +390,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // errno "SetLastError" => { - let [error] = this.check_shim(abi, sys_conv, link_name, args)?; + let [error] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let error = this.read_scalar(error)?; this.set_last_error(error)?; } "GetLastError" => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let last_error = this.get_last_error()?; this.write_scalar(last_error, dest)?; } "RtlNtStatusToDosError" => { - let [status] = this.check_shim(abi, sys_conv, link_name, args)?; + let [status] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let status = this.read_scalar(status)?.to_u32()?; let err = match status { // STATUS_MEDIA_WRITE_PROTECTED => ERROR_WRITE_PROTECT @@ -418,7 +422,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Querying system information "GetSystemInfo" => { // Also called from `page_size` crate. - let [system_info] = this.check_shim(abi, sys_conv, link_name, args)?; + let [system_info] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let system_info = this.deref_pointer_as(system_info, this.windows_ty_layout("SYSTEM_INFO"))?; // Initialize with `0`. @@ -441,19 +445,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // This just creates a key; Windows does not natively support TLS destructors. // Create key and return it. - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let key = this.machine.tls.create_tls_key(None, dest.layout.size)?; this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?; } "TlsGetValue" => { - let [key] = this.check_shim(abi, sys_conv, link_name, args)?; + let [key] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let key = u128::from(this.read_scalar(key)?.to_u32()?); let active_thread = this.active_thread(); let ptr = this.machine.tls.load_tls(key, active_thread, this)?; this.write_scalar(ptr, dest)?; } "TlsSetValue" => { - let [key, new_ptr] = this.check_shim(abi, sys_conv, link_name, args)?; + let [key, new_ptr] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let key = u128::from(this.read_scalar(key)?.to_u32()?); let active_thread = this.active_thread(); let new_data = this.read_scalar(new_ptr)?; @@ -463,7 +467,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_int(1, dest)?; } "TlsFree" => { - let [key] = this.check_shim(abi, sys_conv, link_name, args)?; + let [key] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let key = u128::from(this.read_scalar(key)?.to_u32()?); this.machine.tls.delete_tls_key(key)?; @@ -473,7 +477,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Access to command-line arguments "GetCommandLineW" => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.write_pointer( this.machine.cmd_line.expect("machine must be initialized"), dest, @@ -483,29 +487,30 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Time related shims "GetSystemTimeAsFileTime" | "GetSystemTimePreciseAsFileTime" => { #[allow(non_snake_case)] - let [LPFILETIME] = this.check_shim(abi, sys_conv, link_name, args)?; + let [LPFILETIME] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.GetSystemTimeAsFileTime(link_name.as_str(), LPFILETIME)?; } "QueryPerformanceCounter" => { #[allow(non_snake_case)] - let [lpPerformanceCount] = this.check_shim(abi, sys_conv, link_name, args)?; + let [lpPerformanceCount] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.QueryPerformanceCounter(lpPerformanceCount)?; this.write_scalar(result, dest)?; } "QueryPerformanceFrequency" => { #[allow(non_snake_case)] - let [lpFrequency] = this.check_shim(abi, sys_conv, link_name, args)?; + let [lpFrequency] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.QueryPerformanceFrequency(lpFrequency)?; this.write_scalar(result, dest)?; } "Sleep" => { - let [timeout] = this.check_shim(abi, sys_conv, link_name, args)?; + let [timeout] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.Sleep(timeout)?; } "CreateWaitableTimerExW" => { let [attributes, name, flags, access] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.read_pointer(attributes)?; this.read_pointer(name)?; this.read_scalar(flags)?.to_u32()?; @@ -519,27 +524,28 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Synchronization primitives "InitOnceBeginInitialize" => { let [ptr, flags, pending, context] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.InitOnceBeginInitialize(ptr, flags, pending, context, dest)?; } "InitOnceComplete" => { - let [ptr, flags, context] = this.check_shim(abi, sys_conv, link_name, args)?; + let [ptr, flags, context] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let result = this.InitOnceComplete(ptr, flags, context)?; this.write_scalar(result, dest)?; } "WaitOnAddress" => { let [ptr_op, compare_op, size_op, timeout_op] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.WaitOnAddress(ptr_op, compare_op, size_op, timeout_op, dest)?; } "WakeByAddressSingle" => { - let [ptr_op] = this.check_shim(abi, sys_conv, link_name, args)?; + let [ptr_op] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.WakeByAddressSingle(ptr_op)?; } "WakeByAddressAll" => { - let [ptr_op] = this.check_shim(abi, sys_conv, link_name, args)?; + let [ptr_op] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.WakeByAddressAll(ptr_op)?; } @@ -547,7 +553,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Dynamic symbol loading "GetProcAddress" => { #[allow(non_snake_case)] - let [hModule, lpProcName] = this.check_shim(abi, sys_conv, link_name, args)?; + let [hModule, lpProcName] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.read_target_isize(hModule)?; let name = this.read_c_str(this.read_pointer(lpProcName)?)?; if let Ok(name) = str::from_utf8(name) @@ -563,7 +570,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Threading "CreateThread" => { let [security, stacksize, start, arg, flags, thread] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let thread_id = this.CreateThread(security, stacksize, start, arg, flags, thread)?; @@ -571,12 +578,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(Handle::Thread(thread_id).to_scalar(this), dest)?; } "WaitForSingleObject" => { - let [handle, timeout] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle, timeout] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.WaitForSingleObject(handle, timeout, dest)?; } "GetCurrentProcess" => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.write_scalar( Handle::Pseudo(PseudoHandle::CurrentProcess).to_scalar(this), @@ -584,7 +592,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; } "GetCurrentThread" => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.write_scalar( Handle::Pseudo(PseudoHandle::CurrentThread).to_scalar(this), @@ -592,7 +600,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; } "SetThreadDescription" => { - let [handle, name] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle, name] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let handle = this.read_handle(handle, "SetThreadDescription")?; let name = this.read_wide_str(this.read_pointer(name)?)?; @@ -607,7 +615,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(Scalar::from_u32(0), dest)?; } "GetThreadDescription" => { - let [handle, name_ptr] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle, name_ptr] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let handle = this.read_handle(handle, "GetThreadDescription")?; let name_ptr = this.deref_pointer_as(name_ptr, this.machine.layouts.mut_raw_ptr)?; // the pointer where we should store the ptr to the name @@ -630,7 +639,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "GetThreadId" => { - let [handle] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let handle = this.read_handle(handle, "GetThreadId")?; let thread = match handle { Handle::Thread(thread) => thread, @@ -641,7 +650,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(Scalar::from_u32(tid), dest)?; } "GetCurrentThreadId" => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let thread = this.active_thread(); let tid = this.get_tid(thread); this.write_scalar(Scalar::from_u32(tid), dest)?; @@ -649,7 +658,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Miscellaneous "ExitProcess" => { - let [code] = this.check_shim(abi, sys_conv, link_name, args)?; + let [code] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; // Windows technically uses u32, but we unify everything to a Unix-style i32. let code = this.read_scalar(code)?.to_i32()?; throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false }); @@ -657,7 +666,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "SystemFunction036" => { // used by getrandom 0.1 // This is really 'RtlGenRandom'. - let [ptr, len] = this.check_shim(abi, sys_conv, link_name, args)?; + let [ptr, len] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let ptr = this.read_pointer(ptr)?; let len = this.read_scalar(len)?.to_u32()?; this.gen_random(ptr, len.into())?; @@ -665,7 +674,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "ProcessPrng" => { // used by `std` - let [ptr, len] = this.check_shim(abi, sys_conv, link_name, args)?; + let [ptr, len] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let ptr = this.read_pointer(ptr)?; let len = this.read_target_usize(len)?; this.gen_random(ptr, len)?; @@ -674,7 +683,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "BCryptGenRandom" => { // used by getrandom 0.2 let [algorithm, ptr, len, flags] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let algorithm = this.read_scalar(algorithm)?; let algorithm = algorithm.to_target_usize(this)?; let ptr = this.read_pointer(ptr)?; @@ -708,7 +717,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "GetConsoleScreenBufferInfo" => { // `term` needs this, so we fake it. - let [console, buffer_info] = this.check_shim(abi, sys_conv, link_name, args)?; + let [console, buffer_info] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.read_target_isize(console)?; // FIXME: this should use deref_pointer_as, but CONSOLE_SCREEN_BUFFER_INFO is not in std this.deref_pointer(buffer_info)?; @@ -717,13 +727,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_null(dest)?; } "GetStdHandle" => { - let [which] = this.check_shim(abi, sys_conv, link_name, args)?; + let [which] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let res = this.GetStdHandle(which)?; this.write_scalar(res, dest)?; } "DuplicateHandle" => { let [src_proc, src_handle, target_proc, target_handle, access, inherit, options] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let res = this.DuplicateHandle( src_proc, src_handle, @@ -736,14 +746,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(res, dest)?; } "CloseHandle" => { - let [handle] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let ret = this.CloseHandle(handle)?; this.write_scalar(ret, dest)?; } "GetModuleFileNameW" => { - let [handle, filename, size] = this.check_shim(abi, sys_conv, link_name, args)?; + let [handle, filename, size] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.check_no_isolation("`GetModuleFileNameW`")?; let handle = this.read_handle(handle, "GetModuleFileNameW")?; @@ -777,7 +788,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "FormatMessageW" => { let [flags, module, message_id, language_id, buffer, size, arguments] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; let flags = this.read_scalar(flags)?.to_u32()?; let _module = this.read_pointer(module)?; // seems to contain a module name @@ -812,26 +823,28 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. "GetProcessHeap" if this.frame_in_std() => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; // Just fake a HANDLE // It's fine to not use the Handle type here because its a stub this.write_int(1, dest)?; } "GetModuleHandleA" if this.frame_in_std() => { #[allow(non_snake_case)] - let [_lpModuleName] = this.check_shim(abi, sys_conv, link_name, args)?; + let [_lpModuleName] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; // We need to return something non-null here to make `compat_fn!` work. this.write_int(1, dest)?; } "SetConsoleTextAttribute" if this.frame_in_std() => { #[allow(non_snake_case)] let [_hConsoleOutput, _wAttribute] = - this.check_shim(abi, sys_conv, link_name, args)?; + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; // Pretend these does not exist / nothing happened, by returning zero. this.write_null(dest)?; } "GetConsoleMode" if this.frame_in_std() => { - let [console, mode] = this.check_shim(abi, sys_conv, link_name, args)?; + let [console, mode] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.read_target_isize(console)?; this.deref_pointer_as(mode, this.machine.layouts.u32)?; // Indicate an error. @@ -839,25 +852,27 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "GetFileType" if this.frame_in_std() => { #[allow(non_snake_case)] - let [_hFile] = this.check_shim(abi, sys_conv, link_name, args)?; + let [_hFile] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; // Return unknown file type. this.write_null(dest)?; } "AddVectoredExceptionHandler" if this.frame_in_std() => { #[allow(non_snake_case)] - let [_First, _Handler] = this.check_shim(abi, sys_conv, link_name, args)?; + let [_First, _Handler] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; // Any non zero value works for the stdlib. This is just used for stack overflows anyway. this.write_int(1, dest)?; } "SetThreadStackGuarantee" if this.frame_in_std() => { #[allow(non_snake_case)] - let [_StackSizeInBytes] = this.check_shim(abi, sys_conv, link_name, args)?; + let [_StackSizeInBytes] = + this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; // Any non zero value works for the stdlib. This is just used for stack overflows anyway. this.write_int(1, dest)?; } // this is only callable from std because we know that std ignores the return value "SwitchToThread" if this.frame_in_std() => { - let [] = this.check_shim(abi, sys_conv, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, sys_conv, link_name, args)?; this.yield_active_thread(); @@ -876,7 +891,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ); } // This function looks and behaves excatly like miri_start_unwind. - let [payload] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [payload] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; this.handle_miri_start_unwind(payload)?; return interp_ok(EmulateItemResult::NeedsUnwind); } diff --git a/src/tools/miri/src/shims/x86/aesni.rs b/src/tools/miri/src/shims/x86/aesni.rs index 058ca24e730f..fdd3e78c6105 100644 --- a/src/tools/miri/src/shims/x86/aesni.rs +++ b/src/tools/miri/src/shims/x86/aesni.rs @@ -26,7 +26,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `state` with the corresponding 128-bit key of `key`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdec_si128 "aesdec" | "aesdec.256" | "aesdec.512" => { - let [state, key] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [state, key] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; aes_round(this, state, key, dest, |state, key| { let key = aes::Block::from(key.to_le_bytes()); let mut state = aes::Block::from(state.to_le_bytes()); @@ -42,7 +43,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `state` with the corresponding 128-bit key of `key`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdeclast_si128 "aesdeclast" | "aesdeclast.256" | "aesdeclast.512" => { - let [state, key] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [state, key] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; aes_round(this, state, key, dest, |state, key| { let mut state = aes::Block::from(state.to_le_bytes()); @@ -66,7 +68,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `state` with the corresponding 128-bit key of `key`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesenc_si128 "aesenc" | "aesenc.256" | "aesenc.512" => { - let [state, key] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [state, key] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; aes_round(this, state, key, dest, |state, key| { let key = aes::Block::from(key.to_le_bytes()); let mut state = aes::Block::from(state.to_le_bytes()); @@ -82,7 +85,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `state` with the corresponding 128-bit key of `key`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesenclast_si128 "aesenclast" | "aesenclast.256" | "aesenclast.512" => { - let [state, key] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [state, key] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; aes_round(this, state, key, dest, |state, key| { let mut state = aes::Block::from(state.to_le_bytes()); // `aes::hazmat::cipher_round` does the following operations: @@ -102,7 +106,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement the _mm_aesimc_si128 function. // Performs the AES InvMixColumns operation on `op` "aesimc" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // Transmute to `u128` let op = op.transmute(this.machine.layouts.u128, this)?; let dest = dest.transmute(this.machine.layouts.u128, this)?; diff --git a/src/tools/miri/src/shims/x86/avx.rs b/src/tools/miri/src/shims/x86/avx.rs index 83d23d6ad369..269ce3b51b93 100644 --- a/src/tools/miri/src/shims/x86/avx.rs +++ b/src/tools/miri/src/shims/x86/avx.rs @@ -33,7 +33,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // matches the IEEE min/max operations, while x86 has different // semantics. "min.ps.256" | "max.ps.256" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "min.ps.256" => FloatBinOp::Min, @@ -45,7 +46,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Used to implement _mm256_min_pd and _mm256_max_pd functions. "min.pd.256" | "max.pd.256" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "min.pd.256" => FloatBinOp::Min, @@ -58,21 +60,23 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement the _mm256_round_ps function. // Rounds the elements of `op` according to `rounding`. "round.ps.256" => { - let [op, rounding] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op, rounding] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; round_all::(this, op, rounding, dest)?; } // Used to implement the _mm256_round_pd function. // Rounds the elements of `op` according to `rounding`. "round.pd.256" => { - let [op, rounding] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op, rounding] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; round_all::(this, op, rounding, dest)?; } // Used to implement _mm256_{rcp,rsqrt}_ps functions. // Performs the operations on all components of `op`. "rcp.ps.256" | "rsqrt.ps.256" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "rcp.ps.256" => FloatUnaryOp::Rcp, @@ -84,7 +88,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Used to implement the _mm256_dp_ps function. "dp.ps.256" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; conditional_dot_product(this, left, right, imm, dest)?; } @@ -92,7 +97,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Horizontally add/subtract adjacent floating point values // in `left` and `right`. "hadd.ps.256" | "hadd.pd.256" | "hsub.ps.256" | "hsub.pd.256" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "hadd.ps.256" | "hadd.pd.256" => mir::BinOp::Add, @@ -107,7 +113,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // and `right`. For each component, returns 0 if false or u32::MAX // if true. "cmp.ps.256" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?; @@ -119,7 +126,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // and `right`. For each component, returns 0 if false or u64::MAX // if true. "cmp.pd.256" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?; @@ -130,7 +138,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // and _mm256_cvttpd_epi32 functions. // Converts packed f32/f64 to packed i32. "cvt.ps2dq.256" | "cvtt.ps2dq.256" | "cvt.pd2dq.256" | "cvtt.pd2dq.256" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let rnd = match unprefixed_name { // "current SSE rounding mode", assume nearest @@ -148,7 +156,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // sequence of 4-element arrays, and we shuffle each of these arrays, where // `control` determines which element of the current `data` array is written. "vpermilvar.ps" | "vpermilvar.ps.256" => { - let [data, control] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [data, control] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (data, data_len) = this.project_to_simd(data)?; let (control, control_len) = this.project_to_simd(control)?; @@ -181,7 +190,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // where `right` determines which element of the current `left` array is // written. "vpermilvar.pd" | "vpermilvar.pd.256" => { - let [data, control] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [data, control] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (data, data_len) = this.project_to_simd(data)?; let (control, control_len) = this.project_to_simd(control)?; @@ -213,7 +223,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // For each 128-bit element of `dest`, copies one from `left`, `right` or // zero, according to `imm`. "vperm2f128.ps.256" | "vperm2f128.pd.256" | "vperm2f128.si.256" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; assert_eq!(dest.layout, left.layout); assert_eq!(dest.layout, right.layout); @@ -256,7 +267,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // is one, it is loaded from `ptr.wrapping_add(i)`, otherwise zero is // loaded. "maskload.ps" | "maskload.pd" | "maskload.ps.256" | "maskload.pd.256" => { - let [ptr, mask] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, mask] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; mask_load(this, ptr, mask, dest)?; } @@ -266,7 +277,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // is one, it is stored into `ptr.wapping_add(i)`. // Unlike SSE2's _mm_maskmoveu_si128, these are not non-temporal stores. "maskstore.ps" | "maskstore.pd" | "maskstore.ps.256" | "maskstore.pd.256" => { - let [ptr, mask, value] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, mask, value] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; mask_store(this, ptr, mask, value)?; } @@ -276,7 +288,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // the data crosses a cache line, but for Miri this is just a regular // unaligned read. "ldu.dq.256" => { - let [src_ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [src_ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let src_ptr = this.read_pointer(src_ptr)?; let dest = dest.force_mplace(this)?; @@ -288,7 +300,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Tests `op & mask == 0`, `op & mask == mask` or // `op & mask != 0 && op & mask != mask` "ptestz.256" | "ptestc.256" | "ptestnzc.256" => { - let [op, mask] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op, mask] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (all_zero, masked_set) = test_bits_masked(this, op, mask)?; let res = match unprefixed_name { @@ -311,7 +323,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "vtestz.pd.256" | "vtestc.pd.256" | "vtestnzc.pd.256" | "vtestz.pd" | "vtestc.pd" | "vtestnzc.pd" | "vtestz.ps.256" | "vtestc.ps.256" | "vtestnzc.ps.256" | "vtestz.ps" | "vtestc.ps" | "vtestnzc.ps" => { - let [op, mask] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op, mask] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (direct, negated) = test_high_bits_masked(this, op, mask)?; let res = match unprefixed_name { @@ -333,7 +345,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // compiler, making these functions no-ops. // The only thing that needs to be ensured is the correct calling convention. - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; } _ => return interp_ok(EmulateItemResult::NotSupported), } diff --git a/src/tools/miri/src/shims/x86/avx2.rs b/src/tools/miri/src/shims/x86/avx2.rs index 49d5977078b0..ca80c0eba1e5 100644 --- a/src/tools/miri/src/shims/x86/avx2.rs +++ b/src/tools/miri/src/shims/x86/avx2.rs @@ -28,7 +28,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement the _mm256_abs_epi{8,16,32} functions. // Calculates the absolute value of packed 8/16/32-bit integers. "pabs.b" | "pabs.w" | "pabs.d" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; int_abs(this, op, dest)?; } @@ -36,7 +36,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Horizontally add / add with saturation / subtract adjacent 16/32-bit // integer values in `left` and `right`. "phadd.w" | "phadd.sw" | "phadd.d" | "phsub.w" | "phsub.sw" | "phsub.d" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (which, saturating) = match unprefixed_name { "phadd.w" | "phadd.d" => (mir::BinOp::Add, false), @@ -57,7 +58,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { | "gather.d.pd.256" | "gather.q.pd" | "gather.q.pd.256" | "gather.d.ps" | "gather.d.ps.256" | "gather.q.ps" | "gather.q.ps.256" => { let [src, slice, offsets, mask, scale] = - this.check_shim(abi, CanonAbi::C, link_name, args)?; + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; assert_eq!(dest.layout, src.layout); @@ -114,7 +115,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // intermediate signed 32-bit integers. Horizontally add adjacent pairs of // intermediate 32-bit integers, and pack the results in `dest`. "pmadd.wd" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -150,7 +152,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // the saturating sum of the products with indices `2*i` and `2*i+1` // produces the output at index `i`. "pmadd.ub.sw" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -184,7 +187,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // is one, it is loaded from `ptr.wrapping_add(i)`, otherwise zero is // loaded. "maskload.d" | "maskload.q" | "maskload.d.256" | "maskload.q.256" => { - let [ptr, mask] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, mask] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; mask_load(this, ptr, mask, dest)?; } @@ -194,7 +197,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // is one, it is stored into `ptr.wapping_add(i)`. // Unlike SSE2's _mm_maskmoveu_si128, these are not non-temporal stores. "maskstore.d" | "maskstore.q" | "maskstore.d.256" | "maskstore.q.256" => { - let [ptr, mask, value] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [ptr, mask, value] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; mask_store(this, ptr, mask, value)?; } @@ -205,7 +209,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // offsets specified in `imm`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_mpsadbw_epu8 "mpsadbw" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; mpsadbw(this, left, right, imm, dest)?; } @@ -216,7 +221,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // 1 and then taking the bits `1..=16`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_mulhrs_epi16 "pmul.hr.sw" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; pmulhrsw(this, left, right, dest)?; } @@ -224,7 +230,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Converts two 16-bit integer vectors to a single 8-bit integer // vector with signed saturation. "packsswb" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; packsswb(this, left, right, dest)?; } @@ -232,7 +239,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Converts two 32-bit integer vectors to a single 16-bit integer // vector with signed saturation. "packssdw" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; packssdw(this, left, right, dest)?; } @@ -240,7 +248,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Converts two 16-bit signed integer vectors to a single 8-bit // unsigned integer vector with saturation. "packuswb" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; packuswb(this, left, right, dest)?; } @@ -248,7 +257,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Concatenates two 32-bit signed integer vectors and converts // the result to a 16-bit unsigned integer vector with saturation. "packusdw" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; packusdw(this, left, right, dest)?; } @@ -257,7 +267,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Shuffles `left` using the three low bits of each element of `right` // as indices. "permd" | "permps" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -277,7 +288,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement the _mm256_permute2x128_si256 function. // Shuffles 128-bit blocks of `a` and `b` using `imm` as pattern. "vperm2i128" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; assert_eq!(left.layout.size.bits(), 256); assert_eq!(right.layout.size.bits(), 256); @@ -314,7 +326,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // in `dest`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_sad_epu8 "psad.bw" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -346,7 +359,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Shuffles bytes from `left` using `right` as pattern. // Each 128-bit block is shuffled independently. "pshuf.b" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -377,7 +391,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // is writen to the corresponding output element. // Basically, we multiply `left` with `right.signum()`. "psign.b" | "psign.w" | "psign.d" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; psign(this, left, right, dest)?; } @@ -391,7 +406,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // is copied to remaining bits. "psll.w" | "psrl.w" | "psra.w" | "psll.d" | "psrl.d" | "psra.d" | "psll.q" | "psrl.q" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "psll.w" | "psll.d" | "psll.q" => ShiftOp::Left, @@ -406,7 +422,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // (except _mm{,256}_srav_epi64, which are not available in AVX2). "psllv.d" | "psllv.d.256" | "psllv.q" | "psllv.q.256" | "psrlv.d" | "psrlv.d.256" | "psrlv.q" | "psrlv.q.256" | "psrav.d" | "psrav.d.256" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "psllv.d" | "psllv.d.256" | "psllv.q" | "psllv.q.256" => ShiftOp::Left, diff --git a/src/tools/miri/src/shims/x86/bmi.rs b/src/tools/miri/src/shims/x86/bmi.rs index 80b1b2e16e60..140e31cc5133 100644 --- a/src/tools/miri/src/shims/x86/bmi.rs +++ b/src/tools/miri/src/shims/x86/bmi.rs @@ -35,7 +35,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return interp_ok(EmulateItemResult::NotSupported); } - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let left = this.read_scalar(left)?; let right = this.read_scalar(right)?; diff --git a/src/tools/miri/src/shims/x86/gfni.rs b/src/tools/miri/src/shims/x86/gfni.rs index f83ce560c84e..9a98a80d6dcc 100644 --- a/src/tools/miri/src/shims/x86/gfni.rs +++ b/src/tools/miri/src/shims/x86/gfni.rs @@ -31,14 +31,16 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // See `affine_transform` for details. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=gf2p8affine_ "vgf2p8affineqb.128" | "vgf2p8affineqb.256" | "vgf2p8affineqb.512" => { - let [left, right, imm8] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm8] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; affine_transform(this, left, right, imm8, dest, /* inverse */ false)?; } // Used to implement the `_mm{, 256, 512}_gf2p8affineinv_epi64_epi8` functions. // See `affine_transform` for details. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=gf2p8affineinv "vgf2p8affineinvqb.128" | "vgf2p8affineinvqb.256" | "vgf2p8affineinvqb.512" => { - let [left, right, imm8] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm8] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; affine_transform(this, left, right, imm8, dest, /* inverse */ true)?; } // Used to implement the `_mm{, 256, 512}_gf2p8mul_epi8` functions. @@ -47,7 +49,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // polynomial representation with the reduction polynomial x^8 + x^4 + x^3 + x + 1. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=gf2p8mul "vgf2p8mulb.128" | "vgf2p8mulb.256" | "vgf2p8mulb.512" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; let (dest, dest_len) = this.project_to_simd(dest)?; diff --git a/src/tools/miri/src/shims/x86/mod.rs b/src/tools/miri/src/shims/x86/mod.rs index fbfe459711e0..3324b7b024ac 100644 --- a/src/tools/miri/src/shims/x86/mod.rs +++ b/src/tools/miri/src/shims/x86/mod.rs @@ -45,7 +45,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return interp_ok(EmulateItemResult::NotSupported); } - let [cb_in, a, b] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [cb_in, a, b] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let op = if unprefixed_name.starts_with("add") { mir::BinOp::AddWithOverflow } else { @@ -67,7 +68,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if is_u64 && this.tcx.sess.target.arch != "x86_64" { return interp_ok(EmulateItemResult::NotSupported); } - let [c_in, a, b, out] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [c_in, a, b, out] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let out = this.deref_pointer_as( out, if is_u64 { this.machine.layouts.u64 } else { this.machine.layouts.u32 }, @@ -84,7 +86,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // the instruction behaves like a no-op, so it is always safe to call the // intrinsic. "sse2.pause" => { - let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; // Only exhibit the spin-loop hint behavior when SSE2 is enabled. if this.tcx.sess.unstable_target_features.contains(&Symbol::intern("sse2")) { this.yield_active_thread(); @@ -103,7 +105,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { len = 8; } - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; pclmulqdq(this, left, right, imm, dest, len)?; } diff --git a/src/tools/miri/src/shims/x86/sha.rs b/src/tools/miri/src/shims/x86/sha.rs index d37fad3e6c75..00fe58119e47 100644 --- a/src/tools/miri/src/shims/x86/sha.rs +++ b/src/tools/miri/src/shims/x86/sha.rs @@ -53,7 +53,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match unprefixed_name { // Used to implement the _mm_sha256rnds2_epu32 function. "256rnds2" => { - let [a, b, k] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [a, b, k] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (a_reg, a_len) = this.project_to_simd(a)?; let (b_reg, b_len) = this.project_to_simd(b)?; @@ -74,7 +74,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Used to implement the _mm_sha256msg1_epu32 function. "256msg1" => { - let [a, b] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [a, b] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (a_reg, a_len) = this.project_to_simd(a)?; let (b_reg, b_len) = this.project_to_simd(b)?; @@ -92,7 +92,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Used to implement the _mm_sha256msg2_epu32 function. "256msg2" => { - let [a, b] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [a, b] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (a_reg, a_len) = this.project_to_simd(a)?; let (b_reg, b_len) = this.project_to_simd(b)?; diff --git a/src/tools/miri/src/shims/x86/sse.rs b/src/tools/miri/src/shims/x86/sse.rs index 1ec15d609c68..6d8def5b53fc 100644 --- a/src/tools/miri/src/shims/x86/sse.rs +++ b/src/tools/miri/src/shims/x86/sse.rs @@ -34,7 +34,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Performs the operations on the first component of `left` and // `right` and copies the remaining components from `left`. "min.ss" | "max.ss" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "min.ss" => FloatBinOp::Min, @@ -50,7 +51,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // matches the IEEE min/max operations, while x86 has different // semantics. "min.ps" | "max.ps" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "min.ps" => FloatBinOp::Min, @@ -64,7 +66,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Performs the operations on the first component of `op` and // copies the remaining components from `op`. "rcp.ss" | "rsqrt.ss" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "rcp.ss" => FloatUnaryOp::Rcp, @@ -77,7 +79,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement _mm_{sqrt,rcp,rsqrt}_ps functions. // Performs the operations on all components of `op`. "rcp.ps" | "rsqrt.ps" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "rcp.ps" => FloatUnaryOp::Rcp, @@ -96,7 +98,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // _mm_cmp{eq,lt,le,gt,ge,neq,nlt,nle,ngt,nge,ord,unord}_ss are SSE functions // with hard-coded operations. "cmp.ss" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?; @@ -112,7 +115,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // _mm_cmp{eq,lt,le,gt,ge,neq,nlt,nle,ngt,nge,ord,unord}_ps are SSE functions // with hard-coded operations. "cmp.ps" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?; @@ -125,7 +129,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "comieq.ss" | "comilt.ss" | "comile.ss" | "comigt.ss" | "comige.ss" | "comineq.ss" | "ucomieq.ss" | "ucomilt.ss" | "ucomile.ss" | "ucomigt.ss" | "ucomige.ss" | "ucomineq.ss" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -153,7 +158,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // _mm_cvtss_si64 and _mm_cvttss_si64 functions. // Converts the first component of `op` from f32 to i32/i64. "cvtss2si" | "cvttss2si" | "cvtss2si64" | "cvttss2si64" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (op, _) = this.project_to_simd(op)?; let op = this.read_immediate(&this.project_index(&op, 0)?)?; @@ -181,7 +186,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // are copied from `left`. // https://www.felixcloutier.com/x86/cvtsi2ss "cvtsi2ss" | "cvtsi642ss" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (dest, dest_len) = this.project_to_simd(dest)?; diff --git a/src/tools/miri/src/shims/x86/sse2.rs b/src/tools/miri/src/shims/x86/sse2.rs index d6052f830771..8f53adfb5ecf 100644 --- a/src/tools/miri/src/shims/x86/sse2.rs +++ b/src/tools/miri/src/shims/x86/sse2.rs @@ -41,7 +41,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // intermediate signed 32-bit integers. Horizontally add adjacent pairs of // intermediate 32-bit integers, and pack the results in `dest`. "pmadd.wd" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -79,7 +80,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sad_epu8 "psad.bw" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -117,7 +119,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // is copied to remaining bits. "psll.w" | "psrl.w" | "psra.w" | "psll.d" | "psrl.d" | "psra.d" | "psll.q" | "psrl.q" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "psll.w" | "psll.d" | "psll.q" => ShiftOp::Left, @@ -132,7 +135,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // and _mm_cvttpd_epi32 functions. // Converts packed f32/f64 to packed i32. "cvtps2dq" | "cvttps2dq" | "cvtpd2dq" | "cvttpd2dq" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (op_len, _) = op.layout.ty.simd_size_and_type(*this.tcx); let (dest_len, _) = dest.layout.ty.simd_size_and_type(*this.tcx); @@ -169,7 +172,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Converts two 16-bit integer vectors to a single 8-bit integer // vector with signed saturation. "packsswb.128" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; packsswb(this, left, right, dest)?; } @@ -177,7 +181,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Converts two 16-bit signed integer vectors to a single 8-bit // unsigned integer vector with saturation. "packuswb.128" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; packuswb(this, left, right, dest)?; } @@ -185,7 +190,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Converts two 32-bit integer vectors to a single 16-bit integer // vector with signed saturation. "packssdw.128" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; packssdw(this, left, right, dest)?; } @@ -195,7 +201,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // matches the IEEE min/max operations, while x86 has different // semantics. "min.sd" | "max.sd" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "min.sd" => FloatBinOp::Min, @@ -211,7 +218,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // matches the IEEE min/max operations, while x86 has different // semantics. "min.pd" | "max.pd" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "min.pd" => FloatBinOp::Min, @@ -230,7 +238,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // _mm_cmp{eq,lt,le,gt,ge,neq,nlt,nle,ngt,nge,ord,unord}_sd are SSE2 functions // with hard-coded operations. "cmp.sd" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?; @@ -246,7 +255,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // _mm_cmp{eq,lt,le,gt,ge,neq,nlt,nle,ngt,nge,ord,unord}_pd are SSE2 functions // with hard-coded operations. "cmp.pd" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?; @@ -259,7 +269,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "comieq.sd" | "comilt.sd" | "comile.sd" | "comigt.sd" | "comige.sd" | "comineq.sd" | "ucomieq.sd" | "ucomilt.sd" | "ucomile.sd" | "ucomigt.sd" | "ucomige.sd" | "ucomineq.sd" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -287,7 +298,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // _mm_cvtsd_si64 and _mm_cvttsd_si64 functions. // Converts the first component of `op` from f64 to i32/i64. "cvtsd2si" | "cvttsd2si" | "cvtsd2si64" | "cvttsd2si64" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (op, _) = this.project_to_simd(op)?; let op = this.read_immediate(&this.project_index(&op, 0)?)?; @@ -313,7 +324,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Converts the first f64/f32 from `right` to f32/f64 and copies // the remaining elements from `left` "cvtsd2ss" | "cvtss2sd" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, _) = this.project_to_simd(right)?; diff --git a/src/tools/miri/src/shims/x86/sse3.rs b/src/tools/miri/src/shims/x86/sse3.rs index ebf3cb5c3ee0..0fd8c3bc389b 100644 --- a/src/tools/miri/src/shims/x86/sse3.rs +++ b/src/tools/miri/src/shims/x86/sse3.rs @@ -26,7 +26,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Horizontally add/subtract adjacent floating point values // in `left` and `right`. "hadd.ps" | "hadd.pd" | "hsub.ps" | "hsub.pd" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let which = match unprefixed_name { "hadd.ps" | "hadd.pd" => mir::BinOp::Add, @@ -42,7 +43,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // the data crosses a cache line, but for Miri this is just a regular // unaligned read. "ldu.dq" => { - let [src_ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [src_ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let src_ptr = this.read_pointer(src_ptr)?; let dest = dest.force_mplace(this)?; diff --git a/src/tools/miri/src/shims/x86/sse41.rs b/src/tools/miri/src/shims/x86/sse41.rs index 6797039cf56f..7736b5e443d0 100644 --- a/src/tools/miri/src/shims/x86/sse41.rs +++ b/src/tools/miri/src/shims/x86/sse41.rs @@ -28,7 +28,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // bits `4..=5` if `imm`, and `i`th bit specifies whether element // `i` is zeroed. "insertps" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -63,7 +64,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Concatenates two 32-bit signed integer vectors and converts // the result to a 16-bit unsigned integer vector with saturation. "packusdw" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; packusdw(this, left, right, dest)?; } @@ -73,7 +75,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // products, and conditionally stores the sum in `dest` using the low // 4 bits of `imm`. "dpps" | "dppd" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; conditional_dot_product(this, left, right, imm, dest)?; } @@ -81,14 +84,16 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // functions. Rounds the first element of `right` according to `rounding` // and copies the remaining elements from `left`. "round.ss" => { - let [left, right, rounding] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, rounding] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; round_first::(this, left, right, rounding, dest)?; } // Used to implement the _mm_floor_ps, _mm_ceil_ps and _mm_round_ps // functions. Rounds the elements of `op` according to `rounding`. "round.ps" => { - let [op, rounding] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op, rounding] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; round_all::(this, op, rounding, dest)?; } @@ -96,14 +101,16 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // functions. Rounds the first element of `right` according to `rounding` // and copies the remaining elements from `left`. "round.sd" => { - let [left, right, rounding] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, rounding] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; round_first::(this, left, right, rounding, dest)?; } // Used to implement the _mm_floor_pd, _mm_ceil_pd and _mm_round_pd // functions. Rounds the elements of `op` according to `rounding`. "round.pd" => { - let [op, rounding] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op, rounding] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; round_all::(this, op, rounding, dest)?; } @@ -111,7 +118,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Find the minimum unsinged 16-bit integer in `op` and // returns its value and position. "phminposuw" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (op, op_len) = this.project_to_simd(op)?; let (dest, dest_len) = this.project_to_simd(dest)?; @@ -145,7 +152,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // offsets specified in `imm`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mpsadbw_epu8 "mpsadbw" => { - let [left, right, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; mpsadbw(this, left, right, imm, dest)?; } @@ -154,7 +162,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Tests `(op & mask) == 0`, `(op & mask) == mask` or // `(op & mask) != 0 && (op & mask) != mask` "ptestz" | "ptestc" | "ptestnzc" => { - let [op, mask] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op, mask] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (all_zero, masked_set) = test_bits_masked(this, op, mask)?; let res = match unprefixed_name { diff --git a/src/tools/miri/src/shims/x86/sse42.rs b/src/tools/miri/src/shims/x86/sse42.rs index 7e1e1482ef47..72c5039a12d3 100644 --- a/src/tools/miri/src/shims/x86/sse42.rs +++ b/src/tools/miri/src/shims/x86/sse42.rs @@ -222,7 +222,8 @@ fn deconstruct_args<'tcx>( }; if is_explicit { - let [str1, len1, str2, len2, imm] = ecx.check_shim(abi, CanonAbi::C, link_name, args)?; + let [str1, len1, str2, len2, imm] = + ecx.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let imm = ecx.read_scalar(imm)?.to_u8()?; let default_len = default_len::(imm); @@ -235,7 +236,7 @@ fn deconstruct_args<'tcx>( interp_ok((str1, str2, Some((len1, len2)), imm)) } else { - let [str1, str2, imm] = ecx.check_shim(abi, CanonAbi::C, link_name, args)?; + let [str1, str2, imm] = ecx.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let imm = ecx.read_scalar(imm)?.to_u8()?; let array_layout = array_layout_fn(ecx, imm)?; @@ -385,7 +386,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // search for a null terminator (see `deconstruct_args` for more details). // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=924,925 "pcmpistriz128" | "pcmpistris128" => { - let [str1, str2, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [str1, str2, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let imm = this.read_scalar(imm)?.to_u8()?; let str = if unprefixed_name == "pcmpistris128" { str1 } else { str2 }; @@ -405,7 +407,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // than 16 for byte-sized operands or 8 for word-sized operands. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=1046,1047 "pcmpestriz128" | "pcmpestris128" => { - let [_, len1, _, len2, imm] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [_, len1, _, len2, imm] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let len = if unprefixed_name == "pcmpestris128" { len1 } else { len2 }; let len = this.read_scalar(len)?.to_i32()?; let imm = this.read_scalar(imm)?.to_u8()?; @@ -432,7 +435,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return interp_ok(EmulateItemResult::NotSupported); } - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let left = this.read_scalar(left)?; let right = this.read_scalar(right)?; diff --git a/src/tools/miri/src/shims/x86/ssse3.rs b/src/tools/miri/src/shims/x86/ssse3.rs index 310d6b8f765a..52ad6bd44199 100644 --- a/src/tools/miri/src/shims/x86/ssse3.rs +++ b/src/tools/miri/src/shims/x86/ssse3.rs @@ -25,7 +25,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement the _mm_abs_epi{8,16,32} functions. // Calculates the absolute value of packed 8/16/32-bit integers. "pabs.b.128" | "pabs.w.128" | "pabs.d.128" => { - let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; int_abs(this, op, dest)?; } @@ -33,7 +33,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Shuffles bytes from `left` using `right` as pattern. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shuffle_epi8 "pshuf.b.128" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -62,7 +63,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // integer values in `left` and `right`. "phadd.w.128" | "phadd.sw.128" | "phadd.d.128" | "phsub.w.128" | "phsub.sw.128" | "phsub.d.128" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (which, saturating) = match unprefixed_name { "phadd.w.128" | "phadd.d.128" => (mir::BinOp::Add, false), @@ -81,7 +83,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // produces the output at index `i`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_maddubs_epi16 "pmadd.ub.sw.128" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; let (left, left_len) = this.project_to_simd(left)?; let (right, right_len) = this.project_to_simd(right)?; @@ -116,7 +119,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // 1 and then taking the bits `1..=16`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mulhrs_epi16 "pmul.hr.sw.128" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; pmulhrsw(this, left, right, dest)?; } @@ -126,7 +130,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // is writen to the corresponding output element. // Basically, we multiply `left` with `right.signum()`. "psign.b.128" | "psign.w.128" | "psign.d.128" => { - let [left, right] = this.check_shim(abi, CanonAbi::C, link_name, args)?; + let [left, right] = + this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?; psign(this, left, right, dest)?; } From c07f8bbdc2b2febed3592f112bd004e1a9016904 Mon Sep 17 00:00:00 2001 From: Madhav Madhusoodanan Date: Sun, 27 Jul 2025 18:00:41 +0530 Subject: [PATCH 192/809] chore: handling the case where --generate-only flag is passed --- .../crates/intrinsic-test/src/arm/mod.rs | 45 +++++++++++-------- .../intrinsic-test/src/common/gen_rust.rs | 12 +++-- 2 files changed, 35 insertions(+), 22 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:?}"); + // 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 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:?}"); + 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 193/809] 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 41259050afa0a2e66d739594a27b638266706074 Mon Sep 17 00:00:00 2001 From: Patrick-6 Date: Fri, 14 Mar 2025 09:58:46 +0100 Subject: [PATCH 194/809] Add support for building and linking against genmc --- src/tools/miri/.gitignore | 1 - src/tools/miri/Cargo.lock | 545 ++++++++++++++++++ src/tools/miri/Cargo.toml | 6 +- src/tools/miri/doc/genmc.md | 78 +++ src/tools/miri/etc/rust_analyzer_helix.toml | 1 + src/tools/miri/etc/rust_analyzer_vscode.json | 1 + src/tools/miri/genmc-sys/.gitignore | 1 + src/tools/miri/genmc-sys/Cargo.toml | 17 + src/tools/miri/genmc-sys/build.rs | 268 +++++++++ src/tools/miri/genmc-sys/src/lib.rs | 30 + .../miri/genmc-sys/src_cpp/MiriInterface.cpp | 50 ++ .../miri/genmc-sys/src_cpp/MiriInterface.hpp | 44 ++ src/tools/miri/miri-script/src/commands.rs | 4 +- src/tools/miri/src/bin/miri.rs | 36 +- .../miri/src/concurrency/genmc/config.rs | 32 +- src/tools/miri/src/concurrency/genmc/dummy.rs | 20 +- src/tools/miri/src/concurrency/genmc/mod.rs | 17 +- src/tools/miri/src/concurrency/mod.rs | 12 +- src/tools/miri/src/concurrency/thread.rs | 2 - src/tools/miri/src/eval.rs | 6 +- src/tools/miri/src/machine.rs | 5 +- .../miri/tests/genmc/pass/test_cxx_build.rs | 8 + .../tests/genmc/pass/test_cxx_build.stderr | 6 + src/tools/miri/tests/ui.rs | 14 + 24 files changed, 1161 insertions(+), 43 deletions(-) create mode 100644 src/tools/miri/doc/genmc.md create mode 100644 src/tools/miri/genmc-sys/.gitignore create mode 100644 src/tools/miri/genmc-sys/Cargo.toml create mode 100644 src/tools/miri/genmc-sys/build.rs create mode 100644 src/tools/miri/genmc-sys/src/lib.rs create mode 100644 src/tools/miri/genmc-sys/src_cpp/MiriInterface.cpp create mode 100644 src/tools/miri/genmc-sys/src_cpp/MiriInterface.hpp create mode 100644 src/tools/miri/tests/genmc/pass/test_cxx_build.rs create mode 100644 src/tools/miri/tests/genmc/pass/test_cxx_build.stderr diff --git a/src/tools/miri/.gitignore b/src/tools/miri/.gitignore index ed2d0ba7ba07..4a238dc03134 100644 --- a/src/tools/miri/.gitignore +++ b/src/tools/miri/.gitignore @@ -1,5 +1,4 @@ target -/doc tex/*/out *.dot *.out diff --git a/src/tools/miri/Cargo.lock b/src/tools/miri/Cargo.lock index 0af4181dc154..ece51f2ba74a 100644 --- a/src/tools/miri/Cargo.lock +++ b/src/tools/miri/Cargo.lock @@ -170,6 +170,8 @@ version = "1.2.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "deec109607ca693028562ed836a5f1c4b8bd77755c4e132fc5ce11b0b6211ae7" dependencies = [ + "jobserver", + "libc", "shlex", ] @@ -214,6 +216,52 @@ dependencies = [ "inout", ] +[[package]] +name = "clap" +version = "4.5.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.5.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d" +dependencies = [ + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" + +[[package]] +name = "cmake" +version = "0.1.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" +dependencies = [ + "cc", +] + +[[package]] +name = "codespan-reporting" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81" +dependencies = [ + "serde", + "termcolor", + "unicode-width 0.2.1", +] + [[package]] name = "color-eyre" version = "0.6.5" @@ -313,6 +361,68 @@ dependencies = [ "typenum", ] +[[package]] +name = "cxx" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3523cc02ad831111491dd64b27ad999f1ae189986728e477604e61b81f828df" +dependencies = [ + "cc", + "cxxbridge-cmd", + "cxxbridge-flags", + "cxxbridge-macro", + "foldhash", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "212b754247a6f07b10fa626628c157593f0abf640a3dd04cce2760eca970f909" +dependencies = [ + "cc", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "scratch", + "syn", +] + +[[package]] +name = "cxxbridge-cmd" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a20413ec2e742520ba6837c9324b55ffac24ead47491a6e29f933c5b135a" +dependencies = [ + "clap", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a258b6069020b4e5da6415df94a50ee4f586a6c38b037a180e940a43d06a070d" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8dec184b52be5008d6eaf7e62fc1802caf1ad1227d11b3b7df2c409c7ffc3f4" +dependencies = [ + "indexmap", + "proc-macro2", + "quote", + "rustversion", + "syn", +] + [[package]] name = "directories" version = "6.0.0" @@ -334,12 +444,29 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "encode_unicode" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "errno" version = "0.3.13" @@ -372,6 +499,21 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -382,6 +524,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "genmc-sys" +version = "0.1.0" +dependencies = [ + "cc", + "cmake", + "cxx", + "cxx-build", + "git2", +] + [[package]] name = "getrandom" version = "0.2.16" @@ -411,12 +564,150 @@ version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +[[package]] +name = "git2" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2deb07a133b1520dc1a5690e9bd08950108873d7ed5de38dcc74d3b5ebffa110" +dependencies = [ + "bitflags", + "libc", + "libgit2-sys", + "log", + "openssl-probe", + "openssl-sys", + "url", +] + +[[package]] +name = "hashbrown" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" + +[[package]] +name = "icu_collections" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" + +[[package]] +name = "icu_properties" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "016c619c1eeb94efb86809b015c58f479963de65bdb6253345c1a1276f22e32b" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "potential_utf", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" + +[[package]] +name = "icu_provider" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af" +dependencies = [ + "displaydoc", + "icu_locale_core", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "indenter" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce23b50ad8242c51a442f3ff322d56b02f08852c77e4c0b4d3fd684abc89c683" +[[package]] +name = "indexmap" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe4cd85333e22411419a0bcae1297d25e58c9443848b11dc6a86fefe8c78a661" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "indicatif" version = "0.17.11" @@ -463,6 +754,16 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +[[package]] +name = "jobserver" +version = "0.1.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38f262f097c174adebe41eb73d66ae9c06b2844fb0da69969647bbddd9b0538a" +dependencies = [ + "getrandom 0.3.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.77" @@ -510,6 +811,19 @@ dependencies = [ "cc", ] +[[package]] +name = "libgit2-sys" +version = "0.18.2+1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c42fe03df2bd3c53a3a9c7317ad91d80c81cd1fb0caec8d7cc4cd2bfa10c222" +dependencies = [ + "cc", + "libc", + "libz-sys", + "openssl-sys", + "pkg-config", +] + [[package]] name = "libloading" version = "0.8.8" @@ -530,12 +844,39 @@ dependencies = [ "libc", ] +[[package]] +name = "libz-sys" +version = "1.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b70e7a7df205e92a1a4cd9aaae7898dac0aa555503cc0a649494d0d60e7651d" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "link-cplusplus" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6f6da007f968f9def0d65a05b187e2960183de70c160204ecfccf0ee330212" +dependencies = [ + "cc", +] + [[package]] name = "linux-raw-sys" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" +[[package]] +name = "litemap" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" + [[package]] name = "lock_api" version = "0.4.13" @@ -612,6 +953,7 @@ dependencies = [ "chrono-tz", "colored 3.0.0", "directories", + "genmc-sys", "getrandom 0.3.3", "ipc-channel", "libc", @@ -672,6 +1014,24 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "openssl-sys" +version = "0.9.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90096e2e47630d78b7d1c20952dc621f957103f8bc2c8359ec81290d75238571" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "option-ext" version = "0.2.0" @@ -722,6 +1082,12 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + [[package]] name = "perf-event-open-sys" version = "3.0.0" @@ -755,12 +1121,27 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + [[package]] name = "portable-atomic" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" +[[package]] +name = "potential_utf" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a7c30837279ca13e7c867e9e40053bc68740f988cb07f7ca6df43cc734b585" +dependencies = [ + "zerovec", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -946,6 +1327,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scratch" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f6280af86e5f559536da57a45ebc84948833b3bee313a7dd25232e09c878a52" + [[package]] name = "semver" version = "1.0.26" @@ -1025,6 +1412,18 @@ dependencies = [ "color-eyre", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "syn" version = "2.0.104" @@ -1036,6 +1435,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "tempfile" version = "3.20.0" @@ -1049,6 +1459,15 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -1108,6 +1527,16 @@ dependencies = [ "libc", ] +[[package]] +name = "tinystr" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tracing" version = "0.1.41" @@ -1199,6 +1628,23 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a1a07cc7db3810833284e8d372ccdc6da29741639ecc70c9ec107df0fa6154c" +[[package]] +name = "url" +version = "2.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "uuid" version = "1.17.0" @@ -1216,6 +1662,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -1305,6 +1757,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys 0.59.0", +] + [[package]] name = "windows" version = "0.58.0" @@ -1524,6 +1985,36 @@ dependencies = [ "bitflags", ] +[[package]] +name = "writeable" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" + +[[package]] +name = "yoke" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f41bb01b8226ef4bfd589436a297c53d118f65921786300e427be8d487695cc" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.26" @@ -1543,3 +2034,57 @@ dependencies = [ "quote", "syn", ] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/src/tools/miri/Cargo.toml b/src/tools/miri/Cargo.toml index d293af5cea20..91dadf78a2f7 100644 --- a/src/tools/miri/Cargo.toml +++ b/src/tools/miri/Cargo.toml @@ -48,6 +48,10 @@ nix = { version = "0.30.1", features = ["mman", "ptrace", "signal"], optional = ipc-channel = { version = "0.20.0", optional = true } capstone = { version = "0.13", optional = true } +# FIXME(genmc,macos): Add `target_os = "macos"` once https://github.com/dtolnay/cxx/issues/1535 is fixed. +[target.'cfg(all(target_os = "linux", target_pointer_width = "64", target_endian = "little"))'.dependencies] +genmc-sys = { path = "./genmc-sys/", version = "0.1.0", optional = true } + [dev-dependencies] ui_test = "0.30.2" colored = "3" @@ -66,7 +70,7 @@ harness = false [features] default = ["stack-cache", "native-lib"] -genmc = [] +genmc = ["dep:genmc-sys"] # this enables a GPL dependency! stack-cache = [] stack-cache-consistency-check = ["stack-cache"] tracing = ["serde_json"] diff --git a/src/tools/miri/doc/genmc.md b/src/tools/miri/doc/genmc.md new file mode 100644 index 000000000000..4839919557ec --- /dev/null +++ b/src/tools/miri/doc/genmc.md @@ -0,0 +1,78 @@ +# **(WIP)** Documentation for Miri-GenMC +[GenMC](https://github.com/MPI-SWS/genmc) is a stateless model checker for exploring concurrent executions of a program. + +**NOTE: Currently, no actual GenMC functionality is part of Miri, this is still WIP.** + + + +## Usage + +**IMPORTANT: The license of GenMC and thus the `genmc-sys` crate in the Miri repo is currently "GPL-3.0-or-later", which is NOT compatible with Miri's "MIT OR Apache" license.** + +**IMPORTANT: There should be no distribution of Miri-GenMC until all licensing questions are clarified (the `genmc` feature of Miri is OFF-BY-DEFAULT and should be OFF for all Miri releases).** + +For testing/developing Miri-GenMC (while keeping in mind the licensing issues): +- clone the Miri repo. +- build Miri-GenMC with `./miri build --features=genmc`. +- OR: install Miri-GenMC in the current system with `./miri install --features=genmc` + +Basic usage: +```shell +MIRIFLAGS="-Zmiri-genmc" cargo miri run +``` + + + + + +## Tips + + + +## Limitations + +Some or all of these limitations might get removed in the future: + +- Borrow tracking is currently incompatible (stacked/tree borrows). +- Only Linux is supported for now. +- No 32-bit platform support. +- No cross-platform interpretation. + + + +## Development + +GenMC is written in C++, which complicates development a bit. +For Rust-C++ interop, Miri uses [CXX.rs](https://cxx.rs/), and all handling of C++ code is contained in the `genmc-sys` crate (located in the Miri repository root directory: `miri/genmc-sys/`). + +Building GenMC requires a compiler with C++23 support. + +Currently, building GenMC also requires linking to LLVM, which needs to be installed manually. + +The actual code for GenMC is not contained in the Miri repo itself, but in a [separate GenMC repo](https://github.com/MPI-SWS/genmc) (with different maintainers). +Note that this repo is just a mirror repo. + + + + +### Building the GenMC Library +The build script in the `genmc-sys` crate handles locating, downloading, building and linking the GenMC library. + +To determine which GenMC repo path will be used, the following steps are taken: +- If the env var `GENMC_SRC_PATH` is set, it's value is used as a path to a directory with a GenMC repo (e.g., `GENMC_SRC_PATH="path/to/miri/genmc-sys/genmc-sys-local"`). + - Note that this variable must be set wherever Miri is built, e.g., in the terminal, or in the Rust Analyzer settings. +- If the path `genmc-sys/genmc-src/genmc` exists, try to set the GenMC repo there to the commit we need. +- If the downloaded repo doesn't exist or is missing the commit, the build script will fetch the commit over the network. + - Note that the build script will *not* access the network if any of the steps previous steps succeeds. + +Once we get the path to the repo, the compilation proceeds in two steps: +- Compile GenMC into a library (using cmake). +- Compile the cxx.rs bridge to connect the library to the Rust code. +The first step is where all build settings are made, the relevant ones are then stored in a `config.h` file that can be included in the second compilation step. + +#### Code Formatting +Note that all directories with names starting with `genmc-src` are ignored by `./miri fmt` on purpose. +GenMC also contains Rust files, but they should not be formatted with Miri's formatting rules. +For working on Miri-GenMC locally, placing the GenMC repo into such a path (e.g., `miri/genmc-sys/genmc-src-local`) ensures that it is also exempt from formatting. + + diff --git a/src/tools/miri/etc/rust_analyzer_helix.toml b/src/tools/miri/etc/rust_analyzer_helix.toml index 91e4070478c8..c46b246049ff 100644 --- a/src/tools/miri/etc/rust_analyzer_helix.toml +++ b/src/tools/miri/etc/rust_analyzer_helix.toml @@ -5,6 +5,7 @@ source = "discover" linkedProjects = [ "Cargo.toml", "cargo-miri/Cargo.toml", + "genmc-sys/Cargo.toml", "miri-script/Cargo.toml", ] diff --git a/src/tools/miri/etc/rust_analyzer_vscode.json b/src/tools/miri/etc/rust_analyzer_vscode.json index 6917c6a1fd85..8e647f5331f0 100644 --- a/src/tools/miri/etc/rust_analyzer_vscode.json +++ b/src/tools/miri/etc/rust_analyzer_vscode.json @@ -3,6 +3,7 @@ "rust-analyzer.linkedProjects": [ "Cargo.toml", "cargo-miri/Cargo.toml", + "genmc-sys/Cargo.toml", "miri-script/Cargo.toml", ], "rust-analyzer.check.invocationStrategy": "once", diff --git a/src/tools/miri/genmc-sys/.gitignore b/src/tools/miri/genmc-sys/.gitignore new file mode 100644 index 000000000000..276a053cd055 --- /dev/null +++ b/src/tools/miri/genmc-sys/.gitignore @@ -0,0 +1 @@ +genmc-src*/ diff --git a/src/tools/miri/genmc-sys/Cargo.toml b/src/tools/miri/genmc-sys/Cargo.toml new file mode 100644 index 000000000000..95aef75afc4f --- /dev/null +++ b/src/tools/miri/genmc-sys/Cargo.toml @@ -0,0 +1,17 @@ +[package] +authors = ["Miri Team"] +# The parts in this repo are MIT OR Apache-2.0, but we are linking in +# code from https://github.com/MPI-SWS/genmc which is GPL-3.0-or-later. +license = "(MIT OR Apache-2.0) AND GPL-3.0-or-later" +name = "genmc-sys" +version = "0.1.0" +edition = "2024" + +[dependencies] +cxx = { version = "1.0.160", features = ["c++20"] } + +[build-dependencies] +cc = "1.2.30" +cmake = "0.1.54" +git2 = { version = "0.20.2", default-features = false, features = ["https"] } +cxx-build = { version = "1.0.160", features = ["parallel"] } diff --git a/src/tools/miri/genmc-sys/build.rs b/src/tools/miri/genmc-sys/build.rs new file mode 100644 index 000000000000..16f7b69cc211 --- /dev/null +++ b/src/tools/miri/genmc-sys/build.rs @@ -0,0 +1,268 @@ +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +// Build script for running Miri with GenMC. +// Check out doc/genmc.md for more info. + +/// Path where the downloaded GenMC repository will be stored (relative to the `genmc-sys` directory). +/// Note that this directory is *not* cleaned up automatically by `cargo clean`. +const GENMC_DOWNLOAD_PATH: &str = "./genmc-src/genmc/"; + +/// Name of the library of the GenMC model checker. +const GENMC_MODEL_CHECKER: &str = "genmc_lib"; + +/// Path where the `cxx_bridge!` macro is used to define the Rust-C++ interface. +const RUST_CXX_BRIDGE_FILE_PATH: &str = "src/lib.rs"; + +/// The profile with which to build GenMC. +const GENMC_CMAKE_PROFILE: &str = "RelWithDebInfo"; + +mod downloading { + use std::path::PathBuf; + use std::str::FromStr; + + use git2::{Commit, Oid, Remote, Repository, StatusOptions}; + + use super::GENMC_DOWNLOAD_PATH; + + /// The GenMC repository the we get our commit from. + pub(crate) const GENMC_GITHUB_URL: &str = "https://github.com/MPI-SWS/genmc.git"; + /// The GenMC commit we depend on. It must be available on the specified GenMC repository. + pub(crate) const GENMC_COMMIT: &str = "3438dd2c1202cd4a47ed7881d099abf23e4167ab"; + + pub(crate) fn download_genmc() -> PathBuf { + let Ok(genmc_download_path) = PathBuf::from_str(GENMC_DOWNLOAD_PATH); + let commit_oid = Oid::from_str(GENMC_COMMIT).expect("Commit should be valid."); + + match Repository::open(&genmc_download_path) { + Ok(repo) => { + assert_repo_unmodified(&repo); + let commit = update_local_repo(&repo, commit_oid); + checkout_commit(&repo, &commit); + } + Err(_) => { + let repo = clone_remote_repo(&genmc_download_path); + let Ok(commit) = repo.find_commit(commit_oid) else { + panic!( + "Cloned GenMC repository does not contain required commit '{GENMC_COMMIT}'" + ); + }; + checkout_commit(&repo, &commit); + } + }; + + genmc_download_path + } + + fn get_remote(repo: &Repository) -> Remote<'_> { + let remote = repo.find_remote("origin").unwrap_or_else(|e| { + panic!( + "Could not load commit ({GENMC_COMMIT}) from remote repository '{GENMC_GITHUB_URL}'. Error: {e}" + ); + }); + + // Ensure that the correct remote URL is set. + let remote_url = remote.url(); + if let Some(remote_url) = remote_url + && remote_url == GENMC_GITHUB_URL + { + return remote; + } + + // Update remote URL. + println!( + "cargo::warning=GenMC repository remote URL has changed from '{remote_url:?}' to '{GENMC_GITHUB_URL}'" + ); + repo.remote_set_url("origin", GENMC_GITHUB_URL) + .expect("cannot rename url of remote 'origin'"); + + // Reacquire the `Remote`, since `remote_set_url` doesn't update Remote objects already in memory. + repo.find_remote("origin").unwrap() + } + + // Check if the required commit exists already, otherwise try fetching it. + fn update_local_repo(repo: &Repository, commit_oid: Oid) -> Commit<'_> { + repo.find_commit(commit_oid).unwrap_or_else(|_find_error| { + println!("GenMC repository at path '{GENMC_DOWNLOAD_PATH}' does not contain commit '{GENMC_COMMIT}'."); + // The commit is not in the checkout. Try `git fetch` and hope that we find the commit then. + let mut remote = get_remote(repo); + remote.fetch(&[GENMC_COMMIT], None, None).expect("Failed to fetch from remote."); + + repo.find_commit(commit_oid) + .expect("Remote repository should contain expected commit") + }) + } + + fn clone_remote_repo(genmc_download_path: &PathBuf) -> Repository { + Repository::clone(GENMC_GITHUB_URL, &genmc_download_path).unwrap_or_else(|e| { + panic!("Cannot clone GenMC repo from '{GENMC_GITHUB_URL}': {e:?}"); + }) + } + + /// Set the state of the repo to a specific commit + fn checkout_commit(repo: &Repository, commit: &Commit<'_>) { + repo.checkout_tree(commit.as_object(), None).expect("Failed to checkout"); + repo.set_head_detached(commit.id()).expect("Failed to set HEAD"); + println!("Successfully set checked out commit {commit:?}"); + } + + /// Check that the downloaded repository is unmodified. + /// If it is modified, explain that it shouldn't be, and hint at how to do local development with GenMC. + /// We don't overwrite any changes made to the directory, to prevent data loss. + fn assert_repo_unmodified(repo: &Repository) { + let statuses = repo + .statuses(Some( + StatusOptions::new() + .include_untracked(true) + .include_ignored(false) + .include_unmodified(false), + )) + .expect("should be able to get repository status"); + if statuses.is_empty() { + return; + } + + println!( + "HINT: For local development, set the environment variable 'GENMC_SRC_PATH' to the path of a GenMC repository.", + ); + panic!( + "Downloaded GenMC repository at path '{GENMC_DOWNLOAD_PATH}' has been modified. Please undo any changes made, or delete the '{GENMC_DOWNLOAD_PATH}' directory to have it downloaded again." + ); + } +} + +// FIXME(genmc,llvm): Remove once the LLVM dependency of the GenMC model checker is removed. +/// The linked LLVM version is in the generated `config.h`` file, which we parse and use to link to LLVM. +/// Returns c++ compiler definitions required for building with/including LLVM, and the include path for LLVM headers. +fn link_to_llvm(config_file: &Path) -> (String, String) { + /// Search a string for a line matching `//@VARIABLE_NAME: VARIABLE CONTENT` + fn extract_value<'a>(input: &'a str, name: &str) -> Option<&'a str> { + input + .lines() + .find_map(|line| line.strip_prefix("//@")?.strip_prefix(name)?.strip_prefix(": ")) + } + + let file_content = std::fs::read_to_string(&config_file).unwrap_or_else(|err| { + panic!("GenMC config file ({}) should exist, but got errror {err:?}", config_file.display()) + }); + + let llvm_definitions = extract_value(&file_content, "LLVM_DEFINITIONS") + .expect("Config file should contain LLVM_DEFINITIONS"); + let llvm_include_dirs = extract_value(&file_content, "LLVM_INCLUDE_DIRS") + .expect("Config file should contain LLVM_INCLUDE_DIRS"); + let llvm_library_dir = extract_value(&file_content, "LLVM_LIBRARY_DIR") + .expect("Config file should contain LLVM_LIBRARY_DIR"); + let llvm_config_path = extract_value(&file_content, "LLVM_CONFIG_PATH") + .expect("Config file should contain LLVM_CONFIG_PATH"); + + // Add linker search path. + let lib_dir = PathBuf::from_str(llvm_library_dir).unwrap(); + println!("cargo::rustc-link-search=native={}", lib_dir.display()); + + // Add libraries to link. + let output = std::process::Command::new(llvm_config_path) + .arg("--libs") // Print the libraries to link to (space-separated list) + .output() + .expect("failed to execute llvm-config"); + let llvm_link_libs = + String::try_from(output.stdout).expect("llvm-config output should be a valid string"); + + for link_lib in llvm_link_libs.trim().split(" ") { + let link_lib = + link_lib.strip_prefix("-l").expect("Linker parameter should start with \"-l\""); + println!("cargo::rustc-link-lib=dylib={link_lib}"); + } + + (llvm_definitions.to_string(), llvm_include_dirs.to_string()) +} + +/// Build the GenMC model checker library and the Rust-C++ interop library with cxx.rs +fn compile_cpp_dependencies(genmc_path: &Path) { + // Part 1: + // Compile the GenMC library using cmake. + + let cmakelists_path = genmc_path.join("CMakeLists.txt"); + + // FIXME(genmc,cargo): Switch to using `CARGO_CFG_DEBUG_ASSERTIONS` once https://github.com/rust-lang/cargo/issues/15760 is completed. + // Enable/disable additional debug checks, prints and options for GenMC, based on the Rust profile (debug/release) + let enable_genmc_debug = matches!(std::env::var("PROFILE").as_deref().unwrap(), "debug"); + + let mut config = cmake::Config::new(cmakelists_path); + config.profile(GENMC_CMAKE_PROFILE); + config.define("GENMC_DEBUG", if enable_genmc_debug { "ON" } else { "OFF" }); + + // The actual compilation happens here: + let genmc_install_dir = config.build(); + + // Add the model checker library to be linked and tell GenMC where to find it: + let cmake_lib_dir = genmc_install_dir.join("lib").join("genmc"); + println!("cargo::rustc-link-search=native={}", cmake_lib_dir.display()); + println!("cargo::rustc-link-lib=static={GENMC_MODEL_CHECKER}"); + + // FIXME(genmc,llvm): Remove once the LLVM dependency of the GenMC model checker is removed. + let config_file = genmc_install_dir.join("include").join("genmc").join("config.h"); + let (llvm_definitions, llvm_include_dirs) = link_to_llvm(&config_file); + + // Part 2: + // Compile the cxx_bridge (the link between the Rust and C++ code). + + let genmc_include_dir = genmc_install_dir.join("include").join("genmc"); + + // FIXME(genmc,llvm): remove once LLVM dependency is removed. + // These definitions are parsed into a cmake list and then printed to the config.h file, so they are ';' separated. + let definitions = llvm_definitions.split(";"); + + let mut bridge = cxx_build::bridge("src/lib.rs"); + // FIXME(genmc,cmake): Remove once the GenMC debug setting is available in the config.h file. + if enable_genmc_debug { + bridge.define("ENABLE_GENMC_DEBUG", None); + } + bridge + .flags(definitions) + .opt_level(2) + .debug(true) // Same settings that GenMC uses (default for cmake `RelWithDebInfo`) + .warnings(false) // NOTE: enabling this produces a lot of warnings. + .std("c++23") + .include(genmc_include_dir) + .include(llvm_include_dirs) + .include("./src_cpp") + .file("./src_cpp/MiriInterface.hpp") + .file("./src_cpp/MiriInterface.cpp") + .compile("genmc_interop"); + + // Link the Rust-C++ interface library generated by cxx_build: + println!("cargo::rustc-link-lib=static=genmc_interop"); +} + +fn main() { + // Make sure we don't accidentally distribute a binary with GPL code. + if option_env!("RUSTC_STAGE").is_some() { + panic!( + "genmc should not be enabled in the rustc workspace since it includes a GPL dependency" + ); + } + + // Select which path to use for the GenMC repo: + let genmc_path = if let Ok(genmc_src_path) = std::env::var("GENMC_SRC_PATH") { + let genmc_src_path = + PathBuf::from_str(&genmc_src_path).expect("GENMC_SRC_PATH should contain a valid path"); + assert!( + genmc_src_path.exists(), + "GENMC_SRC_PATH={} does not exist!", + genmc_src_path.display() + ); + genmc_src_path + } else { + downloading::download_genmc() + }; + + // Build all required components: + compile_cpp_dependencies(&genmc_path); + + // Only rebuild if anything changes: + // Note that we don't add the downloaded GenMC repo, since that should never be modified manually. + // Adding that path here would also trigger an unnecessary rebuild after the repo is cloned (since cargo detects that as a file modification). + println!("cargo::rerun-if-changed={RUST_CXX_BRIDGE_FILE_PATH}"); + println!("cargo::rerun-if-changed=./src_cpp"); + println!("cargo::rerun-if-env-changed=GENMC_SRC_PATH"); +} diff --git a/src/tools/miri/genmc-sys/src/lib.rs b/src/tools/miri/genmc-sys/src/lib.rs new file mode 100644 index 000000000000..ab46d729ea16 --- /dev/null +++ b/src/tools/miri/genmc-sys/src/lib.rs @@ -0,0 +1,30 @@ +pub use self::ffi::*; + +impl Default for GenmcParams { + fn default() -> Self { + Self { + print_random_schedule_seed: false, + do_symmetry_reduction: false, + // FIXME(GenMC): Add defaults for remaining parameters + } + } +} + +#[cxx::bridge] +mod ffi { + /// Parameters that will be given to GenMC for setting up the model checker. + /// (The fields of this struct are visible to both Rust and C++) + #[derive(Clone, Debug)] + struct GenmcParams { + pub print_random_schedule_seed: bool, + pub do_symmetry_reduction: bool, + // FIXME(GenMC): Add remaining parameters. + } + unsafe extern "C++" { + include!("MiriInterface.hpp"); + + type MiriGenMCShim; + + fn createGenmcHandle(config: &GenmcParams) -> UniquePtr; + } +} diff --git a/src/tools/miri/genmc-sys/src_cpp/MiriInterface.cpp b/src/tools/miri/genmc-sys/src_cpp/MiriInterface.cpp new file mode 100644 index 000000000000..0827bb3d4074 --- /dev/null +++ b/src/tools/miri/genmc-sys/src_cpp/MiriInterface.cpp @@ -0,0 +1,50 @@ +#include "MiriInterface.hpp" + +#include "genmc-sys/src/lib.rs.h" + +auto MiriGenMCShim::createHandle(const GenmcParams &config) + -> std::unique_ptr +{ + auto conf = std::make_shared(); + + // Miri needs all threads to be replayed, even fully completed ones. + conf->replayCompletedThreads = true; + + // We only support the RC11 memory model for Rust. + conf->model = ModelType::RC11; + + conf->printRandomScheduleSeed = config.print_random_schedule_seed; + + // FIXME(genmc): disable any options we don't support currently: + conf->ipr = false; + conf->disableBAM = true; + conf->instructionCaching = false; + + ERROR_ON(config.do_symmetry_reduction, "Symmetry reduction is currently unsupported in GenMC mode."); + conf->symmetryReduction = config.do_symmetry_reduction; + + // FIXME(genmc): Should there be a way to change this option from Miri? + conf->schedulePolicy = SchedulePolicy::WF; + + // FIXME(genmc): implement estimation mode: + conf->estimate = false; + conf->estimationMax = 1000; + const auto mode = conf->estimate ? GenMCDriver::Mode(GenMCDriver::EstimationMode{}) + : GenMCDriver::Mode(GenMCDriver::VerificationMode{}); + + // Running Miri-GenMC without race detection is not supported. + // Disabling this option also changes the behavior of the replay scheduler to only schedule at atomic operations, which is required with Miri. + // This happens because Miri can generate multiple GenMC events for a single MIR terminator. Without this option, + // the scheduler might incorrectly schedule an atomic MIR terminator because the first event it creates is a non-atomic (e.g., `StorageLive`). + conf->disableRaceDetection = false; + + // Miri can already check for unfreed memory. Also, GenMC cannot distinguish between memory + // that is allowed to leak and memory that is not. + conf->warnUnfreedMemory = false; + + // FIXME(genmc): check config: + // checkConfigOptions(*conf); + + auto driver = std::make_unique(std::move(conf), mode); + return driver; +} diff --git a/src/tools/miri/genmc-sys/src_cpp/MiriInterface.hpp b/src/tools/miri/genmc-sys/src_cpp/MiriInterface.hpp new file mode 100644 index 000000000000..e55522ef4189 --- /dev/null +++ b/src/tools/miri/genmc-sys/src_cpp/MiriInterface.hpp @@ -0,0 +1,44 @@ +#ifndef GENMC_MIRI_INTERFACE_HPP +#define GENMC_MIRI_INTERFACE_HPP + +#include "rust/cxx.h" + +#include "config.h" + +#include "Config/Config.hpp" +#include "Verification/GenMCDriver.hpp" + +#include + +/**** Types available to Miri ****/ + +// Config struct defined on the Rust side and translated to C++ by cxx.rs: +struct GenmcParams; + +struct MiriGenMCShim : private GenMCDriver +{ + +public: + MiriGenMCShim(std::shared_ptr conf, Mode mode /* = VerificationMode{} */) + : GenMCDriver(std::move(conf), nullptr, mode) + { + std::cerr << "C++: GenMC handle created!" << std::endl; + } + + virtual ~MiriGenMCShim() + { + std::cerr << "C++: GenMC handle destroyed!" << std::endl; + } + + static std::unique_ptr createHandle(const GenmcParams &config); +}; + +/**** Functions available to Miri ****/ + +// NOTE: CXX doesn't support exposing static methods to Rust currently, so we expose this function instead. +static inline auto createGenmcHandle(const GenmcParams &config) -> std::unique_ptr +{ + return MiriGenMCShim::createHandle(config); +} + +#endif /* GENMC_MIRI_INTERFACE_HPP */ diff --git a/src/tools/miri/miri-script/src/commands.rs b/src/tools/miri/miri-script/src/commands.rs index 9aaad9ca04a9..7f3bc1bc757d 100644 --- a/src/tools/miri/miri-script/src/commands.rs +++ b/src/tools/miri/miri-script/src/commands.rs @@ -757,8 +757,8 @@ impl Command { if ty.is_file() { name.ends_with(".rs") } else { - // dir or symlink. skip `target` and `.git`. - &name != "target" && &name != ".git" + // dir or symlink. skip `target`, `.git` and `genmc-src*` + &name != "target" && &name != ".git" && !name.starts_with("genmc-src") } }) .filter_ok(|item| item.file_type().is_file()) diff --git a/src/tools/miri/src/bin/miri.rs b/src/tools/miri/src/bin/miri.rs index 89fa980ff646..11d17994cc22 100644 --- a/src/tools/miri/src/bin/miri.rs +++ b/src/tools/miri/src/bin/miri.rs @@ -67,8 +67,6 @@ use crate::log::setup::{deinit_loggers, init_early_loggers, init_late_loggers}; struct MiriCompilerCalls { miri_config: Option, many_seeds: Option, - /// Settings for using GenMC with Miri. - genmc_config: Option, } struct ManySeedsConfig { @@ -77,12 +75,8 @@ struct ManySeedsConfig { } impl MiriCompilerCalls { - fn new( - miri_config: MiriConfig, - many_seeds: Option, - genmc_config: Option, - ) -> Self { - Self { miri_config: Some(miri_config), many_seeds, genmc_config } + fn new(miri_config: MiriConfig, many_seeds: Option) -> Self { + Self { miri_config: Some(miri_config), many_seeds } } } @@ -192,8 +186,8 @@ impl rustc_driver::Callbacks for MiriCompilerCalls { optimizations is usually marginal at best."); } - if let Some(genmc_config) = &self.genmc_config { - let _genmc_ctx = Rc::new(GenmcCtx::new(&config, genmc_config)); + if let Some(_genmc_config) = &config.genmc_config { + let _genmc_ctx = Rc::new(GenmcCtx::new(&config)); todo!("GenMC mode not yet implemented"); }; @@ -487,7 +481,6 @@ fn main() { let mut many_seeds_keep_going = false; let mut miri_config = MiriConfig::default(); miri_config.env = env_snapshot; - let mut genmc_config = None; let mut rustc_args = vec![]; let mut after_dashdash = false; @@ -603,9 +596,7 @@ fn main() { } else if arg == "-Zmiri-many-seeds-keep-going" { many_seeds_keep_going = true; } else if let Some(trimmed_arg) = arg.strip_prefix("-Zmiri-genmc") { - // FIXME(GenMC): Currently, GenMC mode is incompatible with aliasing model checking. - miri_config.borrow_tracker = None; - GenmcConfig::parse_arg(&mut genmc_config, trimmed_arg); + GenmcConfig::parse_arg(&mut miri_config.genmc_config, trimmed_arg); } else if let Some(param) = arg.strip_prefix("-Zmiri-env-forward=") { miri_config.forwarded_env_vars.push(param.to_owned()); } else if let Some(param) = arg.strip_prefix("-Zmiri-env-set=") { @@ -740,13 +731,21 @@ fn main() { many_seeds.map(|seeds| ManySeedsConfig { seeds, keep_going: many_seeds_keep_going }); // Validate settings for data race detection and GenMC mode. - assert_eq!(genmc_config.is_some(), miri_config.genmc_mode); - if genmc_config.is_some() { + if miri_config.genmc_config.is_some() { + // FIXME(genmc): Add checks for currently supported platforms (64bit, target == host) if !miri_config.data_race_detector { fatal_error!("Cannot disable data race detection in GenMC mode (currently)"); } else if !miri_config.weak_memory_emulation { fatal_error!("Cannot disable weak memory emulation in GenMC mode"); } + // FIXME(genmc): Remove once GenMC mode is compatible with borrow tracking: + if miri_config.borrow_tracker.is_some() { + eprintln!( + "warning: Borrow tracking has been disabled, it is not (yet) supported in GenMC mode." + ); + eprintln!(); + miri_config.borrow_tracker = None; + } } else if miri_config.weak_memory_emulation && !miri_config.data_race_detector { fatal_error!( "Weak memory emulation cannot be enabled when the data race detector is disabled" @@ -765,8 +764,5 @@ fn main() { ); } } - run_compiler_and_exit( - &rustc_args, - &mut MiriCompilerCalls::new(miri_config, many_seeds, genmc_config), - ) + run_compiler_and_exit(&rustc_args, &mut MiriCompilerCalls::new(miri_config, many_seeds)) } diff --git a/src/tools/miri/src/concurrency/genmc/config.rs b/src/tools/miri/src/concurrency/genmc/config.rs index f91211a670f6..42591c9ac256 100644 --- a/src/tools/miri/src/concurrency/genmc/config.rs +++ b/src/tools/miri/src/concurrency/genmc/config.rs @@ -1,19 +1,41 @@ -use crate::MiriConfig; +use super::GenmcParams; +/// Configuration for GenMC mode. +/// The `params` field is shared with the C++ side. +/// The remaining options are kept on the Rust side. #[derive(Debug, Default, Clone)] pub struct GenmcConfig { - // TODO: add fields + pub(super) params: GenmcParams, + do_estimation: bool, + // FIXME(GenMC): add remaining options. } impl GenmcConfig { /// Function for parsing command line options for GenMC mode. - /// All GenMC arguments start with the string "-Zmiri-genmc". /// - /// `trimmed_arg` should be the argument to be parsed, with the suffix "-Zmiri-genmc" removed + /// All GenMC arguments start with the string "-Zmiri-genmc". + /// Passing any GenMC argument will enable GenMC mode. + /// + /// `trimmed_arg` should be the argument to be parsed, with the suffix "-Zmiri-genmc" removed. pub fn parse_arg(genmc_config: &mut Option, trimmed_arg: &str) { + // FIXME(genmc,macos): Add `target_os = "macos"` once `https://github.com/dtolnay/cxx/issues/1535` is fixed. + if !cfg!(all( + feature = "genmc", + any(target_os = "linux", target_os = "macos"), + target_pointer_width = "64", + target_endian = "little" + )) { + unimplemented!( + "GenMC mode is not supported on this platform, cannot handle argument: \"-Zmiri-genmc{trimmed_arg}\"" + ); + } if genmc_config.is_none() { *genmc_config = Some(Default::default()); } - todo!("implement parsing of GenMC options") + if trimmed_arg.is_empty() { + return; // this corresponds to "-Zmiri-genmc" + } + // FIXME(GenMC): implement remaining parameters. + todo!(); } } diff --git a/src/tools/miri/src/concurrency/genmc/dummy.rs b/src/tools/miri/src/concurrency/genmc/dummy.rs index 3d0558fb6853..7570f8ba3627 100644 --- a/src/tools/miri/src/concurrency/genmc/dummy.rs +++ b/src/tools/miri/src/concurrency/genmc/dummy.rs @@ -16,7 +16,7 @@ pub struct GenmcCtx {} pub struct GenmcConfig {} impl GenmcCtx { - pub fn new(_miri_config: &MiriConfig, _genmc_config: &GenmcConfig) -> Self { + pub fn new(_miri_config: &MiriConfig) -> Self { unreachable!() } @@ -228,9 +228,21 @@ impl VisitProvenance for GenmcCtx { impl GenmcConfig { pub fn parse_arg(_genmc_config: &mut Option, trimmed_arg: &str) { - unimplemented!( - "GenMC feature im Miri is disabled, cannot handle argument: \"-Zmiri-genmc{trimmed_arg}\"" - ); + // FIXME(genmc,macos): Add `target_os = "macos"` once `https://github.com/dtolnay/cxx/issues/1535` is fixed. + if cfg!(all( + feature = "genmc", + any(target_os = "linux", target_os = "macos"), + target_pointer_width = "64", + target_endian = "little" + )) { + unimplemented!( + "GenMC is disabled, cannot handle argument: \"-Zmiri-genmc{trimmed_arg}\"" + ); + } else { + unimplemented!( + "GenMC mode is not supported on this platform, cannot handle argument: \"-Zmiri-genmc{trimmed_arg}\"" + ); + } } pub fn should_print_graph(&self, _rep: usize) -> bool { diff --git a/src/tools/miri/src/concurrency/genmc/mod.rs b/src/tools/miri/src/concurrency/genmc/mod.rs index 0dfd4b9b80f9..3617775e27ea 100644 --- a/src/tools/miri/src/concurrency/genmc/mod.rs +++ b/src/tools/miri/src/concurrency/genmc/mod.rs @@ -2,6 +2,7 @@ use std::cell::Cell; +use genmc_sys::{GenmcParams, createGenmcHandle}; use rustc_abi::{Align, Size}; use rustc_const_eval::interpret::{InterpCx, InterpResult, interp_ok}; use rustc_middle::mir; @@ -24,9 +25,19 @@ pub struct GenmcCtx { impl GenmcCtx { /// Create a new `GenmcCtx` from a given config. - pub fn new(miri_config: &MiriConfig, genmc_config: &GenmcConfig) -> Self { - assert!(miri_config.genmc_mode); - todo!() + pub fn new(miri_config: &MiriConfig) -> Self { + let genmc_config = miri_config.genmc_config.as_ref().unwrap(); + + let handle = createGenmcHandle(&genmc_config.params); + assert!(!handle.is_null()); + + eprintln!("Miri: GenMC handle creation successful!"); + + drop(handle); + eprintln!("Miri: Dropping GenMC handle successful!"); + + // FIXME(GenMC): implement + std::process::exit(0); } pub fn get_stuck_execution_count(&self) -> usize { diff --git a/src/tools/miri/src/concurrency/mod.rs b/src/tools/miri/src/concurrency/mod.rs index c2ea8a00decd..435615efd9fa 100644 --- a/src/tools/miri/src/concurrency/mod.rs +++ b/src/tools/miri/src/concurrency/mod.rs @@ -8,7 +8,17 @@ mod vector_clock; pub mod weak_memory; // Import either the real genmc adapter or a dummy module. -#[cfg_attr(not(feature = "genmc"), path = "genmc/dummy.rs")] +// On unsupported platforms, we always include the dummy module, even if the `genmc` feature is enabled. +// FIXME(genmc,macos): Add `target_os = "macos"` once `https://github.com/dtolnay/cxx/issues/1535` is fixed. +#[cfg_attr( + not(all( + feature = "genmc", + target_os = "linux", + target_pointer_width = "64", + target_endian = "little" + )), + path = "genmc/dummy.rs" +)] mod genmc; pub use self::data_race_handler::{AllocDataRaceHandler, GlobalDataRaceHandler}; diff --git a/src/tools/miri/src/concurrency/thread.rs b/src/tools/miri/src/concurrency/thread.rs index 878afdf25173..abfee0ee8746 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -677,8 +677,6 @@ trait EvalContextPrivExt<'tcx>: MiriInterpCxExt<'tcx> { fn run_on_stack_empty(&mut self) -> InterpResult<'tcx, Poll<()>> { let this = self.eval_context_mut(); // Inform GenMC that a thread has finished all user code. GenMC needs to know this for scheduling. - // FIXME(GenMC): Thread-local destructors *are* user code, so this is odd. Also now that we - // support pre-main constructors, it can get called there as well. if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() { let thread_id = this.active_thread(); genmc_ctx.handle_thread_stack_empty(thread_id); diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index 3c80e60b772a..8a20b7fab557 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -125,8 +125,8 @@ pub struct MiriConfig { pub data_race_detector: bool, /// Determine if weak memory emulation should be enabled. Requires data race detection to be enabled. pub weak_memory_emulation: bool, - /// Determine if we are running in GenMC mode. In this mode, Miri will explore multiple concurrent executions of the given program. - pub genmc_mode: bool, + /// Determine if we are running in GenMC mode and with which settings. In GenMC mode, Miri will explore multiple concurrent executions of the given program. + pub genmc_config: Option, /// Track when an outdated (weak memory) load happens. pub track_outdated_loads: bool, /// Rate of spurious failures for compare_exchange_weak atomic operations, @@ -192,7 +192,7 @@ impl Default for MiriConfig { track_alloc_accesses: false, data_race_detector: true, weak_memory_emulation: true, - genmc_mode: false, + genmc_config: None, track_outdated_loads: false, cmpxchg_weak_failure_rate: 0.8, // 80% measureme_out: None, diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index ce33c870b4b5..8b7a8a5865a9 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -622,6 +622,9 @@ pub struct MiriMachine<'tcx> { } impl<'tcx> MiriMachine<'tcx> { + /// Create a new MiriMachine. + /// + /// Invariant: `genmc_ctx.is_some() == config.genmc_config.is_some()` pub(crate) fn new( config: &MiriConfig, layout_cx: LayoutCx<'tcx>, @@ -645,7 +648,7 @@ impl<'tcx> MiriMachine<'tcx> { }); let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0)); let borrow_tracker = config.borrow_tracker.map(|bt| bt.instantiate_global_state(config)); - let data_race = if config.genmc_mode { + let data_race = if config.genmc_config.is_some() { // `genmc_ctx` persists across executions, so we don't create a new one here. GlobalDataRaceHandler::Genmc(genmc_ctx.unwrap()) } else if config.data_race_detector { diff --git a/src/tools/miri/tests/genmc/pass/test_cxx_build.rs b/src/tools/miri/tests/genmc/pass/test_cxx_build.rs new file mode 100644 index 000000000000..f621bd9114fa --- /dev/null +++ b/src/tools/miri/tests/genmc/pass/test_cxx_build.rs @@ -0,0 +1,8 @@ +//@compile-flags: -Zmiri-genmc + +#![no_main] + +#[unsafe(no_mangle)] +fn miri_start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} diff --git a/src/tools/miri/tests/genmc/pass/test_cxx_build.stderr b/src/tools/miri/tests/genmc/pass/test_cxx_build.stderr new file mode 100644 index 000000000000..3773dbeff3b4 --- /dev/null +++ b/src/tools/miri/tests/genmc/pass/test_cxx_build.stderr @@ -0,0 +1,6 @@ +warning: Borrow tracking has been disabled, it is not (yet) supported in GenMC mode. + +C++: GenMC handle created! +Miri: GenMC handle creation successful! +C++: GenMC handle destroyed! +Miri: Dropping GenMC handle successful! diff --git a/src/tools/miri/tests/ui.rs b/src/tools/miri/tests/ui.rs index cb915b11b679..73fbe2cc020f 100644 --- a/src/tools/miri/tests/ui.rs +++ b/src/tools/miri/tests/ui.rs @@ -338,6 +338,20 @@ fn main() -> Result<()> { ui(Mode::Fail, "tests/native-lib/fail", &target, WithoutDependencies, tmpdir.path())?; } + // We only enable GenMC tests when the `genmc` feature is enabled, but also only on platforms we support: + // FIXME(genmc,macos): Add `target_os = "macos"` once `https://github.com/dtolnay/cxx/issues/1535` is fixed. + // FIXME(genmc,cross-platform): remove `host == target` check once cross-platform support with GenMC is possible. + if cfg!(all( + feature = "genmc", + target_os = "linux", + target_pointer_width = "64", + target_endian = "little" + )) && host == target + { + ui(Mode::Pass, "tests/genmc/pass", &target, WithDependencies, tmpdir.path())?; + ui(Mode::Fail, "tests/genmc/fail", &target, WithDependencies, tmpdir.path())?; + } + Ok(()) } From 87b8cb06c793620f1f66291200aea1b9bd8c3d89 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 27 Jul 2025 16:34:42 +0200 Subject: [PATCH 195/809] various minor adjustments --- src/tools/miri/doc/genmc.md | 52 +++++++------------ src/tools/miri/genmc-sys/build.rs | 17 +++--- src/tools/miri/src/bin/miri.rs | 9 ++-- .../miri/src/concurrency/genmc/config.rs | 20 +++---- src/tools/miri/src/concurrency/genmc/dummy.rs | 21 +++----- src/tools/miri/src/concurrency/thread.rs | 2 + .../tests/genmc/pass/test_cxx_build.stderr | 3 +- 7 files changed, 47 insertions(+), 77 deletions(-) diff --git a/src/tools/miri/doc/genmc.md b/src/tools/miri/doc/genmc.md index 4839919557ec..5aabe90b5dab 100644 --- a/src/tools/miri/doc/genmc.md +++ b/src/tools/miri/doc/genmc.md @@ -1,5 +1,7 @@ # **(WIP)** Documentation for Miri-GenMC + [GenMC](https://github.com/MPI-SWS/genmc) is a stateless model checker for exploring concurrent executions of a program. +Miri-GenMC integrates that model checker into Miri. **NOTE: Currently, no actual GenMC functionality is part of Miri, this is still WIP.** @@ -7,9 +9,7 @@ ## Usage -**IMPORTANT: The license of GenMC and thus the `genmc-sys` crate in the Miri repo is currently "GPL-3.0-or-later", which is NOT compatible with Miri's "MIT OR Apache" license.** - -**IMPORTANT: There should be no distribution of Miri-GenMC until all licensing questions are clarified (the `genmc` feature of Miri is OFF-BY-DEFAULT and should be OFF for all Miri releases).** +**IMPORTANT: The license of GenMC and thus the `genmc-sys` crate in the Miri repo is currently "GPL-3.0-or-later", so a binary produced with the `genmc` feature is subject to the requirements of the GPL. As long as that remains the case, the `genmc` feature of Miri is OFF-BY-DEFAULT and must be OFF for all Miri releases.** For testing/developing Miri-GenMC (while keeping in mind the licensing issues): - clone the Miri repo. @@ -35,44 +35,28 @@ Some or all of these limitations might get removed in the future: - Borrow tracking is currently incompatible (stacked/tree borrows). - Only Linux is supported for now. -- No 32-bit platform support. -- No cross-platform interpretation. +- No support for 32-bit or big-endian targets. +- No cross-target interpretation. ## Development GenMC is written in C++, which complicates development a bit. -For Rust-C++ interop, Miri uses [CXX.rs](https://cxx.rs/), and all handling of C++ code is contained in the `genmc-sys` crate (located in the Miri repository root directory: `miri/genmc-sys/`). +The prerequisites for building Miri-GenMC are: +- A compiler with C++23 support. +- LLVM developments headers and clang. + -Building GenMC requires a compiler with C++23 support. - -Currently, building GenMC also requires linking to LLVM, which needs to be installed manually. +The actual code for GenMC is not contained in the Miri repo itself, but in a [separate GenMC repo](https://github.com/MPI-SWS/genmc) (with its own maintainers). +These sources need to be available to build Miri-GenMC. +The process for obtaining them is as follows: +- By default, a fixed commit of GenMC is downloaded to `genmc-sys/genmc-src` and built automatically. + (The commit is determined by `GENMC_COMMIT` in `genmc-sys/build.rs`.) +- If you want to overwrite that, set the `GENMC_SRC_PATH` environment variable to a path that contains the GenMC sources. + If you place this directory inside the Miri folder, it is recommended to call it `genmc-src` as that tells `./miri fmt` to avoid + formatting the Rust files inside that folder. -The actual code for GenMC is not contained in the Miri repo itself, but in a [separate GenMC repo](https://github.com/MPI-SWS/genmc) (with different maintainers). -Note that this repo is just a mirror repo. - + - -### Building the GenMC Library -The build script in the `genmc-sys` crate handles locating, downloading, building and linking the GenMC library. - -To determine which GenMC repo path will be used, the following steps are taken: -- If the env var `GENMC_SRC_PATH` is set, it's value is used as a path to a directory with a GenMC repo (e.g., `GENMC_SRC_PATH="path/to/miri/genmc-sys/genmc-sys-local"`). - - Note that this variable must be set wherever Miri is built, e.g., in the terminal, or in the Rust Analyzer settings. -- If the path `genmc-sys/genmc-src/genmc` exists, try to set the GenMC repo there to the commit we need. -- If the downloaded repo doesn't exist or is missing the commit, the build script will fetch the commit over the network. - - Note that the build script will *not* access the network if any of the steps previous steps succeeds. - -Once we get the path to the repo, the compilation proceeds in two steps: -- Compile GenMC into a library (using cmake). -- Compile the cxx.rs bridge to connect the library to the Rust code. -The first step is where all build settings are made, the relevant ones are then stored in a `config.h` file that can be included in the second compilation step. - -#### Code Formatting -Note that all directories with names starting with `genmc-src` are ignored by `./miri fmt` on purpose. -GenMC also contains Rust files, but they should not be formatted with Miri's formatting rules. -For working on Miri-GenMC locally, placing the GenMC repo into such a path (e.g., `miri/genmc-sys/genmc-src-local`) ensures that it is also exempt from formatting. - - diff --git a/src/tools/miri/genmc-sys/build.rs b/src/tools/miri/genmc-sys/build.rs index 16f7b69cc211..f20e0e8d525f 100644 --- a/src/tools/miri/genmc-sys/build.rs +++ b/src/tools/miri/genmc-sys/build.rs @@ -6,7 +6,7 @@ use std::str::FromStr; /// Path where the downloaded GenMC repository will be stored (relative to the `genmc-sys` directory). /// Note that this directory is *not* cleaned up automatically by `cargo clean`. -const GENMC_DOWNLOAD_PATH: &str = "./genmc-src/genmc/"; +const GENMC_DOWNLOAD_PATH: &str = "./genmc-src/"; /// Name of the library of the GenMC model checker. const GENMC_MODEL_CHECKER: &str = "genmc_lib"; @@ -122,11 +122,9 @@ mod downloading { return; } - println!( - "HINT: For local development, set the environment variable 'GENMC_SRC_PATH' to the path of a GenMC repository.", - ); panic!( - "Downloaded GenMC repository at path '{GENMC_DOWNLOAD_PATH}' has been modified. Please undo any changes made, or delete the '{GENMC_DOWNLOAD_PATH}' directory to have it downloaded again." + "Downloaded GenMC repository at path '{GENMC_DOWNLOAD_PATH}' has been modified. Please undo any changes made, or delete the '{GENMC_DOWNLOAD_PATH}' directory to have it downloaded again.\n\ + HINT: For local development, set the environment variable 'GENMC_SRC_PATH' to the path of a GenMC repository." ); } } @@ -194,7 +192,7 @@ fn compile_cpp_dependencies(genmc_path: &Path) { // The actual compilation happens here: let genmc_install_dir = config.build(); - // Add the model checker library to be linked and tell GenMC where to find it: + // Add the model checker library to be linked and tell rustc where to find it: let cmake_lib_dir = genmc_install_dir.join("lib").join("genmc"); println!("cargo::rustc-link-search=native={}", cmake_lib_dir.display()); println!("cargo::rustc-link-lib=static={GENMC_MODEL_CHECKER}"); @@ -260,9 +258,10 @@ fn main() { compile_cpp_dependencies(&genmc_path); // Only rebuild if anything changes: - // Note that we don't add the downloaded GenMC repo, since that should never be modified manually. - // Adding that path here would also trigger an unnecessary rebuild after the repo is cloned (since cargo detects that as a file modification). + // Note that we don't add the downloaded GenMC repo, since that should never be modified + // manually. Adding that path here would also trigger an unnecessary rebuild after the repo is + // cloned (since cargo detects that as a file modification). println!("cargo::rerun-if-changed={RUST_CXX_BRIDGE_FILE_PATH}"); + println!("cargo::rerun-if-changed=./src"); println!("cargo::rerun-if-changed=./src_cpp"); - println!("cargo::rerun-if-env-changed=GENMC_SRC_PATH"); } diff --git a/src/tools/miri/src/bin/miri.rs b/src/tools/miri/src/bin/miri.rs index 11d17994cc22..ae1b25f8857a 100644 --- a/src/tools/miri/src/bin/miri.rs +++ b/src/tools/miri/src/bin/miri.rs @@ -596,7 +596,9 @@ fn main() { } else if arg == "-Zmiri-many-seeds-keep-going" { many_seeds_keep_going = true; } else if let Some(trimmed_arg) = arg.strip_prefix("-Zmiri-genmc") { - GenmcConfig::parse_arg(&mut miri_config.genmc_config, trimmed_arg); + if let Err(msg) = GenmcConfig::parse_arg(&mut miri_config.genmc_config, trimmed_arg) { + fatal_error!("{msg}"); + } } else if let Some(param) = arg.strip_prefix("-Zmiri-env-forward=") { miri_config.forwarded_env_vars.push(param.to_owned()); } else if let Some(param) = arg.strip_prefix("-Zmiri-env-set=") { @@ -732,18 +734,15 @@ fn main() { // Validate settings for data race detection and GenMC mode. if miri_config.genmc_config.is_some() { - // FIXME(genmc): Add checks for currently supported platforms (64bit, target == host) if !miri_config.data_race_detector { fatal_error!("Cannot disable data race detection in GenMC mode (currently)"); } else if !miri_config.weak_memory_emulation { fatal_error!("Cannot disable weak memory emulation in GenMC mode"); } - // FIXME(genmc): Remove once GenMC mode is compatible with borrow tracking: if miri_config.borrow_tracker.is_some() { eprintln!( - "warning: Borrow tracking has been disabled, it is not (yet) supported in GenMC mode." + "warning: borrow tracking has been disabled, it is not (yet) supported in GenMC mode." ); - eprintln!(); miri_config.borrow_tracker = None; } } else if miri_config.weak_memory_emulation && !miri_config.data_race_detector { diff --git a/src/tools/miri/src/concurrency/genmc/config.rs b/src/tools/miri/src/concurrency/genmc/config.rs index 42591c9ac256..c56adab90fe2 100644 --- a/src/tools/miri/src/concurrency/genmc/config.rs +++ b/src/tools/miri/src/concurrency/genmc/config.rs @@ -17,23 +17,17 @@ impl GenmcConfig { /// Passing any GenMC argument will enable GenMC mode. /// /// `trimmed_arg` should be the argument to be parsed, with the suffix "-Zmiri-genmc" removed. - pub fn parse_arg(genmc_config: &mut Option, trimmed_arg: &str) { - // FIXME(genmc,macos): Add `target_os = "macos"` once `https://github.com/dtolnay/cxx/issues/1535` is fixed. - if !cfg!(all( - feature = "genmc", - any(target_os = "linux", target_os = "macos"), - target_pointer_width = "64", - target_endian = "little" - )) { - unimplemented!( - "GenMC mode is not supported on this platform, cannot handle argument: \"-Zmiri-genmc{trimmed_arg}\"" - ); - } + pub fn parse_arg( + genmc_config: &mut Option, + trimmed_arg: &str, + ) -> Result<(), String> { + // FIXME(genmc): Ensure host == target somewhere. + if genmc_config.is_none() { *genmc_config = Some(Default::default()); } if trimmed_arg.is_empty() { - return; // this corresponds to "-Zmiri-genmc" + return Ok(()); // this corresponds to "-Zmiri-genmc" } // FIXME(GenMC): implement remaining parameters. todo!(); diff --git a/src/tools/miri/src/concurrency/genmc/dummy.rs b/src/tools/miri/src/concurrency/genmc/dummy.rs index 7570f8ba3627..79d27c4be159 100644 --- a/src/tools/miri/src/concurrency/genmc/dummy.rs +++ b/src/tools/miri/src/concurrency/genmc/dummy.rs @@ -227,21 +227,14 @@ impl VisitProvenance for GenmcCtx { } impl GenmcConfig { - pub fn parse_arg(_genmc_config: &mut Option, trimmed_arg: &str) { - // FIXME(genmc,macos): Add `target_os = "macos"` once `https://github.com/dtolnay/cxx/issues/1535` is fixed. - if cfg!(all( - feature = "genmc", - any(target_os = "linux", target_os = "macos"), - target_pointer_width = "64", - target_endian = "little" - )) { - unimplemented!( - "GenMC is disabled, cannot handle argument: \"-Zmiri-genmc{trimmed_arg}\"" - ); + pub fn parse_arg( + _genmc_config: &mut Option, + trimmed_arg: &str, + ) -> Result<(), String> { + if cfg!(feature = "genmc") { + Err(format!("GenMC is disabled in this build of Miri")) } else { - unimplemented!( - "GenMC mode is not supported on this platform, cannot handle argument: \"-Zmiri-genmc{trimmed_arg}\"" - ); + Err(format!("GenMC is not supported on this target")) } } diff --git a/src/tools/miri/src/concurrency/thread.rs b/src/tools/miri/src/concurrency/thread.rs index abfee0ee8746..878afdf25173 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -677,6 +677,8 @@ trait EvalContextPrivExt<'tcx>: MiriInterpCxExt<'tcx> { fn run_on_stack_empty(&mut self) -> InterpResult<'tcx, Poll<()>> { let this = self.eval_context_mut(); // Inform GenMC that a thread has finished all user code. GenMC needs to know this for scheduling. + // FIXME(GenMC): Thread-local destructors *are* user code, so this is odd. Also now that we + // support pre-main constructors, it can get called there as well. if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() { let thread_id = this.active_thread(); genmc_ctx.handle_thread_stack_empty(thread_id); diff --git a/src/tools/miri/tests/genmc/pass/test_cxx_build.stderr b/src/tools/miri/tests/genmc/pass/test_cxx_build.stderr index 3773dbeff3b4..4b7aa824bd12 100644 --- a/src/tools/miri/tests/genmc/pass/test_cxx_build.stderr +++ b/src/tools/miri/tests/genmc/pass/test_cxx_build.stderr @@ -1,5 +1,4 @@ -warning: Borrow tracking has been disabled, it is not (yet) supported in GenMC mode. - +warning: borrow tracking has been disabled, it is not (yet) supported in GenMC mode. C++: GenMC handle created! Miri: GenMC handle creation successful! C++: GenMC handle destroyed! From d12ecde365efcf6ee4eb74fb6cfdd8314ab9fec4 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 27 Jul 2025 17:00:31 +0200 Subject: [PATCH 196/809] constify with_exposed_provenance --- library/core/src/ptr/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index dbe3999b4a43..1a2a5182567b 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -974,9 +974,10 @@ pub const fn dangling_mut() -> *mut T { #[must_use] #[inline(always)] #[stable(feature = "exposed_provenance", since = "1.84.0")] +#[rustc_const_unstable(feature = "const_exposed_provenance", issue = "144538")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[allow(fuzzy_provenance_casts)] // this *is* the explicit provenance API one should use instead -pub fn with_exposed_provenance(addr: usize) -> *const T { +pub const fn with_exposed_provenance(addr: usize) -> *const T { addr as *const T } @@ -1014,9 +1015,10 @@ pub fn with_exposed_provenance(addr: usize) -> *const T { #[must_use] #[inline(always)] #[stable(feature = "exposed_provenance", since = "1.84.0")] +#[rustc_const_unstable(feature = "const_exposed_provenance", issue = "144538")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[allow(fuzzy_provenance_casts)] // this *is* the explicit provenance API one should use instead -pub fn with_exposed_provenance_mut(addr: usize) -> *mut T { +pub const fn with_exposed_provenance_mut(addr: usize) -> *mut T { addr as *mut T } From 72927f6eb74550e24f0fdeecd5f21201fd970d12 Mon Sep 17 00:00:00 2001 From: FractalFir Date: Sun, 27 Jul 2025 20:55:45 +0200 Subject: [PATCH 197/809] Ensure correct aligement of rustc_hir::Lifetime on platforms with lower default alignments. --- compiler/rustc_hir/src/hir.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index e83f6a1df720..36bada15db1e 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -148,6 +148,11 @@ impl From for LifetimeSyntax { /// `LifetimeSource::OutlivesBound` or `LifetimeSource::PreciseCapturing` /// — there's no way to "elide" these lifetimes. #[derive(Debug, Copy, Clone, HashStable_Generic)] +// Raise the aligement to at least 4 bytes - this is relied on in other parts of the compiler(for pointer tagging): +// https://github.com/rust-lang/rust/blob/ce5fdd7d42aba9a2925692e11af2bd39cf37798a/compiler/rustc_data_structures/src/tagged_ptr.rs#L163 +// Removing this `repr(4)` will cause the compiler to not build on platforms like `m68k` Linux, where the aligement of u32 and usize is only 2. +// Since `repr(align)` may only raise aligement, this has no effect on platforms where the aligement is already sufficient. +#[repr(align(4))] pub struct Lifetime { #[stable_hasher(ignore)] pub hir_id: HirId, From 47bfa846f37cf053471656b572a35d2bfca16715 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 27 Jul 2025 13:21:06 -0700 Subject: [PATCH 198/809] Allow more MIR SROA --- compiler/rustc_mir_transform/src/sroa.rs | 36 +++++-------------- ...y.run2-{closure#0}.Inline.panic-abort.diff | 36 +++++++++---------- ....run2-{closure#0}.Inline.panic-unwind.diff | 36 +++++++++---------- 3 files changed, 40 insertions(+), 68 deletions(-) diff --git a/compiler/rustc_mir_transform/src/sroa.rs b/compiler/rustc_mir_transform/src/sroa.rs index 7c6ccc89c4f3..80c4b58a5744 100644 --- a/compiler/rustc_mir_transform/src/sroa.rs +++ b/compiler/rustc_mir_transform/src/sroa.rs @@ -1,4 +1,4 @@ -use rustc_abi::{FIRST_VARIANT, FieldIdx}; +use rustc_abi::FieldIdx; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_hir::LangItem; use rustc_index::IndexVec; @@ -32,7 +32,7 @@ impl<'tcx> crate::MirPass<'tcx> for ScalarReplacementOfAggregates { let typing_env = body.typing_env(tcx); loop { debug!(?excluded); - let escaping = escaping_locals(tcx, typing_env, &excluded, body); + let escaping = escaping_locals(tcx, &excluded, body); debug!(?escaping); let replacements = compute_flattening(tcx, typing_env, body, escaping); debug!(?replacements); @@ -64,7 +64,6 @@ impl<'tcx> crate::MirPass<'tcx> for ScalarReplacementOfAggregates { /// client code. fn escaping_locals<'tcx>( tcx: TyCtxt<'tcx>, - typing_env: ty::TypingEnv<'tcx>, excluded: &DenseBitSet, body: &Body<'tcx>, ) -> DenseBitSet { @@ -72,31 +71,12 @@ fn escaping_locals<'tcx>( if ty.is_union() || ty.is_enum() { return true; } - if let ty::Adt(def, _args) = ty.kind() { - if def.repr().simd() { - // Exclude #[repr(simd)] types so that they are not de-optimized into an array - return true; - } - if tcx.is_lang_item(def.did(), LangItem::DynMetadata) { - // codegen wants to see the `DynMetadata`, - // not the inner reference-to-opaque-type. - return true; - } - // We already excluded unions and enums, so this ADT must have one variant - let variant = def.variant(FIRST_VARIANT); - if variant.fields.len() > 1 { - // If this has more than one field, it cannot be a wrapper that only provides a - // niche, so we do not want to automatically exclude it. - return false; - } - let Ok(layout) = tcx.layout_of(typing_env.as_query_input(ty)) else { - // We can't get the layout - return true; - }; - if layout.layout.largest_niche().is_some() { - // This type has a niche - return true; - } + if let ty::Adt(def, _args) = ty.kind() + && tcx.is_lang_item(def.did(), LangItem::DynMetadata) + { + // codegen wants to see the `DynMetadata`, + // not the inner reference-to-opaque-type. + return true; } // Default for non-ADTs false diff --git a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff index 169a6768448f..22e6ea722dda 100644 --- a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff +++ b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff @@ -64,9 +64,8 @@ + let mut _45: &mut std::future::Ready<()>; + let mut _46: &mut std::pin::Pin<&mut std::future::Ready<()>>; + scope 14 (inlined > as DerefMut>::deref_mut) { -+ let mut _47: std::pin::Pin<&mut std::future::Ready<()>>; + scope 15 (inlined Pin::<&mut std::future::Ready<()>>::as_mut) { -+ let mut _48: &mut &mut std::future::Ready<()>; ++ let mut _47: &mut &mut std::future::Ready<()>; + scope 16 (inlined Pin::<&mut std::future::Ready<()>>::new_unchecked) { + } + scope 18 (inlined <&mut std::future::Ready<()> as DerefMut>::deref_mut) { @@ -76,15 +75,15 @@ + } + } + scope 19 (inlined Option::<()>::take) { -+ let mut _49: std::option::Option<()>; ++ let mut _48: std::option::Option<()>; + scope 20 (inlined std::mem::replace::>) { + scope 21 { + } + } + } + scope 22 (inlined #[track_caller] Option::<()>::expect) { -+ let mut _50: isize; -+ let mut _51: !; ++ let mut _49: isize; ++ let mut _50: !; + scope 23 { + } + } @@ -229,28 +228,25 @@ + StorageDead(_24); + StorageLive(_45); + StorageLive(_46); -+ StorageLive(_51); ++ StorageLive(_50); + StorageLive(_42); + StorageLive(_43); + StorageLive(_44); + _46 = &mut _19; + StorageLive(_47); -+ StorageLive(_48); -+ _48 = &mut (_19.0: &mut std::future::Ready<()>); ++ _47 = &mut (_19.0: &mut std::future::Ready<()>); + _45 = copy (_19.0: &mut std::future::Ready<()>); -+ StorageDead(_48); -+ _47 = Pin::<&mut std::future::Ready<()>> { pointer: copy _45 }; + StorageDead(_47); + _44 = &mut ((*_45).0: std::option::Option<()>); -+ StorageLive(_49); -+ _49 = Option::<()>::None; ++ StorageLive(_48); ++ _48 = Option::<()>::None; + _43 = copy ((*_45).0: std::option::Option<()>); -+ ((*_45).0: std::option::Option<()>) = copy _49; -+ StorageDead(_49); ++ ((*_45).0: std::option::Option<()>) = copy _48; ++ StorageDead(_48); + StorageDead(_44); -+ StorageLive(_50); -+ _50 = discriminant(_43); -+ switchInt(move _50) -> [0: bb11, 1: bb12, otherwise: bb5]; ++ StorageLive(_49); ++ _49 = discriminant(_43); ++ switchInt(move _49) -> [0: bb11, 1: bb12, otherwise: bb5]; } + + bb5: { @@ -313,16 +309,16 @@ + } + + bb11: { -+ _51 = option::expect_failed(const "`Ready` polled after completion") -> unwind unreachable; ++ _50 = option::expect_failed(const "`Ready` polled after completion") -> unwind unreachable; + } + + bb12: { + _42 = move ((_43 as Some).0: ()); -+ StorageDead(_50); ++ StorageDead(_49); + StorageDead(_43); + _18 = Poll::<()>::Ready(move _42); + StorageDead(_42); -+ StorageDead(_51); ++ StorageDead(_50); + StorageDead(_46); + StorageDead(_45); + StorageDead(_22); diff --git a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff index 14ba3311d2dc..8b027e988b8e 100644 --- a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff @@ -66,9 +66,8 @@ + let mut _47: &mut std::future::Ready<()>; + let mut _48: &mut std::pin::Pin<&mut std::future::Ready<()>>; + scope 14 (inlined > as DerefMut>::deref_mut) { -+ let mut _49: std::pin::Pin<&mut std::future::Ready<()>>; + scope 15 (inlined Pin::<&mut std::future::Ready<()>>::as_mut) { -+ let mut _50: &mut &mut std::future::Ready<()>; ++ let mut _49: &mut &mut std::future::Ready<()>; + scope 16 (inlined Pin::<&mut std::future::Ready<()>>::new_unchecked) { + } + scope 18 (inlined <&mut std::future::Ready<()> as DerefMut>::deref_mut) { @@ -78,15 +77,15 @@ + } + } + scope 19 (inlined Option::<()>::take) { -+ let mut _51: std::option::Option<()>; ++ let mut _50: std::option::Option<()>; + scope 20 (inlined std::mem::replace::>) { + scope 21 { + } + } + } + scope 22 (inlined #[track_caller] Option::<()>::expect) { -+ let mut _52: isize; -+ let mut _53: !; ++ let mut _51: isize; ++ let mut _52: !; + scope 23 { + } + } @@ -246,28 +245,25 @@ + StorageDead(_24); + StorageLive(_47); + StorageLive(_48); -+ StorageLive(_53); ++ StorageLive(_52); + StorageLive(_44); + StorageLive(_45); + StorageLive(_46); + _48 = &mut _19; + StorageLive(_49); -+ StorageLive(_50); -+ _50 = &mut (_19.0: &mut std::future::Ready<()>); ++ _49 = &mut (_19.0: &mut std::future::Ready<()>); + _47 = copy (_19.0: &mut std::future::Ready<()>); -+ StorageDead(_50); -+ _49 = Pin::<&mut std::future::Ready<()>> { pointer: copy _47 }; + StorageDead(_49); + _46 = &mut ((*_47).0: std::option::Option<()>); -+ StorageLive(_51); -+ _51 = Option::<()>::None; ++ StorageLive(_50); ++ _50 = Option::<()>::None; + _45 = copy ((*_47).0: std::option::Option<()>); -+ ((*_47).0: std::option::Option<()>) = copy _51; -+ StorageDead(_51); ++ ((*_47).0: std::option::Option<()>) = copy _50; ++ StorageDead(_50); + StorageDead(_46); -+ StorageLive(_52); -+ _52 = discriminant(_45); -+ switchInt(move _52) -> [0: bb16, 1: bb17, otherwise: bb7]; ++ StorageLive(_51); ++ _51 = discriminant(_45); ++ switchInt(move _51) -> [0: bb16, 1: bb17, otherwise: bb7]; } - bb6 (cleanup): { @@ -354,16 +350,16 @@ + } + + bb16: { -+ _53 = option::expect_failed(const "`Ready` polled after completion") -> bb11; ++ _52 = option::expect_failed(const "`Ready` polled after completion") -> bb11; + } + + bb17: { + _44 = move ((_45 as Some).0: ()); -+ StorageDead(_52); ++ StorageDead(_51); + StorageDead(_45); + _18 = Poll::<()>::Ready(move _44); + StorageDead(_44); -+ StorageDead(_53); ++ StorageDead(_52); + StorageDead(_48); + StorageDead(_47); + StorageDead(_22); From a20692c2d06683a9467a17dbbd58703ff72916c1 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 27 Jul 2025 23:22:35 +0200 Subject: [PATCH 199/809] centralize clockid_t interpretation --- src/tools/miri/src/concurrency/thread.rs | 2 +- src/tools/miri/src/shims/time.rs | 104 +++++++++--------- src/tools/miri/src/shims/unix/freebsd/sync.rs | 26 ++--- src/tools/miri/src/shims/unix/sync.rs | 65 ++++------- 4 files changed, 81 insertions(+), 116 deletions(-) diff --git a/src/tools/miri/src/concurrency/thread.rs b/src/tools/miri/src/concurrency/thread.rs index 878afdf25173..fe1ef86ccd31 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -375,7 +375,7 @@ impl Timeout { } /// The clock to use for the timeout you are asking for. -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, PartialEq)] pub enum TimeoutClock { Monotonic, RealTime, diff --git a/src/tools/miri/src/shims/time.rs b/src/tools/miri/src/shims/time.rs index eb21abc2a455..b5b35797fec2 100644 --- a/src/tools/miri/src/shims/time.rs +++ b/src/tools/miri/src/shims/time.rs @@ -17,73 +17,71 @@ pub fn system_time_to_duration<'tcx>(time: &SystemTime) -> InterpResult<'tcx, Du impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { + fn parse_clockid(&self, clk_id: Scalar) -> Option { + // This clock support is deliberately minimal because a lot of clock types have fiddly + // properties (is it possible for Miri to be suspended independently of the host?). If you + // have a use for another clock type, please open an issue. + let this = self.eval_context_ref(); + + // Portable names that exist everywhere. + if clk_id == this.eval_libc("CLOCK_REALTIME") { + return Some(TimeoutClock::RealTime); + } else if clk_id == this.eval_libc("CLOCK_MONOTONIC") { + return Some(TimeoutClock::Monotonic); + } + + // Some further platform-specific names we support. + match this.tcx.sess.target.os.as_ref() { + "linux" | "freebsd" | "android" => { + // Linux further distinguishes regular and "coarse" clocks, but the "coarse" version + // is just specified to be "faster and less precise", so we treat it like normal + // clocks. + if clk_id == this.eval_libc("CLOCK_REALTIME_COARSE") { + return Some(TimeoutClock::RealTime); + } else if clk_id == this.eval_libc("CLOCK_MONOTONIC_COARSE") { + return Some(TimeoutClock::Monotonic); + } + } + "macos" => { + // `CLOCK_UPTIME_RAW` supposed to not increment while the system is asleep... but + // that's not really something a program running inside Miri can tell, anyway. + // We need to support it because std uses it. + if clk_id == this.eval_libc("CLOCK_UPTIME_RAW") { + return Some(TimeoutClock::Monotonic); + } + } + _ => {} + } + + None + } + fn clock_gettime( &mut self, clk_id_op: &OpTy<'tcx>, tp_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - // This clock support is deliberately minimal because a lot of clock types have fiddly - // properties (is it possible for Miri to be suspended independently of the host?). If you - // have a use for another clock type, please open an issue. - let this = self.eval_context_mut(); this.assert_target_os_is_unix("clock_gettime"); - let clockid_t_size = this.libc_ty_layout("clockid_t").size; - let clk_id = this.read_scalar(clk_id_op)?.to_int(clockid_t_size)?; + let clk_id = this.read_scalar(clk_id_op)?; let tp = this.deref_pointer_as(tp_op, this.libc_ty_layout("timespec"))?; - let absolute_clocks; - let mut relative_clocks; - - match this.tcx.sess.target.os.as_ref() { - "linux" | "freebsd" | "android" => { - // Linux, Android, and FreeBSD have two main kinds of clocks. REALTIME clocks return the actual time since the - // Unix epoch, including effects which may cause time to move backwards such as NTP. - // Linux further distinguishes regular and "coarse" clocks, but the "coarse" version - // is just specified to be "faster and less precise", so we implement both the same way. - absolute_clocks = vec![ - this.eval_libc("CLOCK_REALTIME").to_int(clockid_t_size)?, - this.eval_libc("CLOCK_REALTIME_COARSE").to_int(clockid_t_size)?, - ]; - // The second kind is MONOTONIC clocks for which 0 is an arbitrary time point, but they are - // never allowed to go backwards. We don't need to do any additional monotonicity - // enforcement because std::time::Instant already guarantees that it is monotonic. - relative_clocks = vec![ - this.eval_libc("CLOCK_MONOTONIC").to_int(clockid_t_size)?, - this.eval_libc("CLOCK_MONOTONIC_COARSE").to_int(clockid_t_size)?, - ]; + let duration = match this.parse_clockid(clk_id) { + Some(TimeoutClock::RealTime) => { + this.check_no_isolation("`clock_gettime` with `REALTIME` clocks")?; + system_time_to_duration(&SystemTime::now())? } - "macos" => { - absolute_clocks = vec![this.eval_libc("CLOCK_REALTIME").to_int(clockid_t_size)?]; - relative_clocks = vec![this.eval_libc("CLOCK_MONOTONIC").to_int(clockid_t_size)?]; - // `CLOCK_UPTIME_RAW` supposed to not increment while the system is asleep... but - // that's not really something a program running inside Miri can tell, anyway. - // We need to support it because std uses it. - relative_clocks.push(this.eval_libc("CLOCK_UPTIME_RAW").to_int(clockid_t_size)?); + Some(TimeoutClock::Monotonic) => + this.machine + .monotonic_clock + .now() + .duration_since(this.machine.monotonic_clock.epoch()), + None => { + return this.set_last_error_and_return(LibcError("EINVAL"), dest); } - "solaris" | "illumos" => { - // The REALTIME clock returns the actual time since the Unix epoch. - absolute_clocks = vec![this.eval_libc("CLOCK_REALTIME").to_int(clockid_t_size)?]; - // MONOTONIC, in the other hand, is the high resolution, non-adjustable - // clock from an arbitrary time in the past. - // Note that the man page mentions HIGHRES but it is just - // an alias of MONOTONIC and the libc crate does not expose it anyway. - // https://docs.oracle.com/cd/E23824_01/html/821-1465/clock-gettime-3c.html - relative_clocks = vec![this.eval_libc("CLOCK_MONOTONIC").to_int(clockid_t_size)?]; - } - target => throw_unsup_format!("`clock_gettime` is not supported on target OS {target}"), - } - - let duration = if absolute_clocks.contains(&clk_id) { - this.check_no_isolation("`clock_gettime` with `REALTIME` clocks")?; - system_time_to_duration(&SystemTime::now())? - } else if relative_clocks.contains(&clk_id) { - this.machine.monotonic_clock.now().duration_since(this.machine.monotonic_clock.epoch()) - } else { - return this.set_last_error_and_return(LibcError("EINVAL"), dest); }; let tv_sec = duration.as_secs(); diff --git a/src/tools/miri/src/shims/unix/freebsd/sync.rs b/src/tools/miri/src/shims/unix/freebsd/sync.rs index f4e7d9e58f9f..13d30e05573a 100644 --- a/src/tools/miri/src/shims/unix/freebsd/sync.rs +++ b/src/tools/miri/src/shims/unix/freebsd/sync.rs @@ -228,26 +228,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let abs_time_flag = flags == abs_time; let clock_id_place = this.project_field(ut, FieldIdx::from_u32(2))?; - let clock_id = this.read_scalar(&clock_id_place)?.to_i32()?; - let timeout_clock = this.translate_umtx_time_clock_id(clock_id)?; + let clock_id = this.read_scalar(&clock_id_place)?; + let Some(timeout_clock) = this.parse_clockid(clock_id) else { + throw_unsup_format!("unsupported clock") + }; + if timeout_clock == TimeoutClock::RealTime { + this.check_no_isolation("`_umtx_op` with `CLOCK_REALTIME`")?; + } interp_ok(Some(UmtxTime { timeout: duration, abs_time: abs_time_flag, timeout_clock })) } - - /// Translate raw FreeBSD clockid to a Miri TimeoutClock. - /// FIXME: share this code with the pthread and clock_gettime shims. - fn translate_umtx_time_clock_id(&mut self, raw_id: i32) -> InterpResult<'tcx, TimeoutClock> { - let this = self.eval_context_mut(); - - let timeout = if raw_id == this.eval_libc_i32("CLOCK_REALTIME") { - // RealTime clock can't be used in isolation mode. - this.check_no_isolation("`_umtx_op` with `CLOCK_REALTIME` timeout")?; - TimeoutClock::RealTime - } else if raw_id == this.eval_libc_i32("CLOCK_MONOTONIC") { - TimeoutClock::Monotonic - } else { - throw_unsup_format!("unsupported clock id {raw_id}"); - }; - interp_ok(timeout) - } } diff --git a/src/tools/miri/src/shims/unix/sync.rs b/src/tools/miri/src/shims/unix/sync.rs index e20e3b79c3be..5ad4fd501a60 100644 --- a/src/tools/miri/src/shims/unix/sync.rs +++ b/src/tools/miri/src/shims/unix/sync.rs @@ -297,14 +297,13 @@ fn condattr_clock_offset<'tcx>(ecx: &MiriInterpCx<'tcx>) -> InterpResult<'tcx, u fn condattr_get_clock_id<'tcx>( ecx: &MiriInterpCx<'tcx>, attr_ptr: &OpTy<'tcx>, -) -> InterpResult<'tcx, i32> { +) -> InterpResult<'tcx, Scalar> { ecx.deref_pointer_and_read( attr_ptr, condattr_clock_offset(ecx)?, ecx.libc_ty_layout("pthread_condattr_t"), ecx.machine.layouts.i32, - )? - .to_i32() + ) } fn condattr_set_clock_id<'tcx>( @@ -321,20 +320,6 @@ fn condattr_set_clock_id<'tcx>( ) } -/// Translates the clock from what is stored in pthread_condattr_t to our enum. -fn condattr_translate_clock_id<'tcx>( - ecx: &MiriInterpCx<'tcx>, - raw_id: i32, -) -> InterpResult<'tcx, ClockId> { - interp_ok(if raw_id == ecx.eval_libc_i32("CLOCK_REALTIME") { - ClockId::Realtime - } else if raw_id == ecx.eval_libc_i32("CLOCK_MONOTONIC") { - ClockId::Monotonic - } else { - throw_unsup_format!("unsupported clock id: {raw_id}"); - }) -} - // # pthread_cond_t // We store some data directly inside the type, ignoring the platform layout: // - init: u32 @@ -363,22 +348,16 @@ fn cond_init_offset<'tcx>(ecx: &MiriInterpCx<'tcx>) -> InterpResult<'tcx, Size> interp_ok(offset) } -#[derive(Debug, Clone, Copy)] -enum ClockId { - Realtime, - Monotonic, -} - #[derive(Debug, Clone)] struct PthreadCondvar { condvar_ref: CondvarRef, - clock: ClockId, + clock: TimeoutClock, } fn cond_create<'tcx>( ecx: &mut MiriInterpCx<'tcx>, cond_ptr: &OpTy<'tcx>, - clock: ClockId, + clock: TimeoutClock, ) -> InterpResult<'tcx, PthreadCondvar> { let cond = ecx.deref_pointer_as(cond_ptr, ecx.libc_ty_layout("pthread_cond_t"))?; let data = PthreadCondvar { condvar_ref: CondvarRef::new(), clock }; @@ -407,7 +386,10 @@ where throw_unsup_format!("unsupported static initializer used for `pthread_cond_t`"); } // This used the static initializer. The clock there is always CLOCK_REALTIME. - interp_ok(PthreadCondvar { condvar_ref: CondvarRef::new(), clock: ClockId::Realtime }) + interp_ok(PthreadCondvar { + condvar_ref: CondvarRef::new(), + clock: TimeoutClock::RealTime, + }) }, ) } @@ -742,11 +724,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ) -> InterpResult<'tcx, Scalar> { let this = self.eval_context_mut(); - let clock_id = this.read_scalar(clock_id_op)?.to_i32()?; - if clock_id == this.eval_libc_i32("CLOCK_REALTIME") - || clock_id == this.eval_libc_i32("CLOCK_MONOTONIC") - { - condattr_set_clock_id(this, attr_op, clock_id)?; + let clock_id = this.read_scalar(clock_id_op)?; + if this.parse_clockid(clock_id).is_some() { + condattr_set_clock_id(this, attr_op, clock_id.to_i32()?)?; } else { let einval = this.eval_libc_i32("EINVAL"); return interp_ok(Scalar::from_i32(einval)); @@ -764,7 +744,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let clock_id = condattr_get_clock_id(this, attr_op)?; this.write_scalar( - Scalar::from_i32(clock_id), + clock_id, &this.deref_pointer_as(clk_id_op, this.libc_ty_layout("clockid_t"))?, )?; @@ -799,13 +779,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let attr = this.read_pointer(attr_op)?; // Default clock if `attr` is null, and on macOS where there is no clock attribute. let clock_id = if this.ptr_is_null(attr)? || this.tcx.sess.target.os == "macos" { - this.eval_libc_i32("CLOCK_REALTIME") + this.eval_libc("CLOCK_REALTIME") } else { condattr_get_clock_id(this, attr_op)? }; - let clock_id = condattr_translate_clock_id(this, clock_id)?; + let Some(clock) = this.parse_clockid(clock_id) else { + // This is UB since this situation cannot arise when using pthread_condattr_setclock. + throw_ub_format!("pthread_cond_init: invalid attributes (unsupported clock)") + }; - cond_create(this, cond_op, clock_id)?; + cond_create(this, cond_op, clock)?; interp_ok(()) } @@ -870,18 +853,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return interp_ok(()); } }; - let timeout_clock = match data.clock { - ClockId::Realtime => { - this.check_no_isolation("`pthread_cond_timedwait` with `CLOCK_REALTIME`")?; - TimeoutClock::RealTime - } - ClockId::Monotonic => TimeoutClock::Monotonic, - }; + if data.clock == TimeoutClock::RealTime { + this.check_no_isolation("`pthread_cond_timedwait` with `CLOCK_REALTIME`")?; + } this.condvar_wait( data.condvar_ref, mutex_ref, - Some((timeout_clock, TimeoutAnchor::Absolute, duration)), + Some((data.clock, TimeoutAnchor::Absolute, duration)), Scalar::from_i32(0), this.eval_libc("ETIMEDOUT"), // retval_timeout dest.clone(), From 9c683d3487d8966dad182bc7ad2524bf0bb6d797 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Sun, 27 Jul 2025 23:27:40 +0200 Subject: [PATCH 200/809] 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 201/809] 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 c0fe2858156bc4ef1256fcd839f426c3c10992fc Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 27 Jul 2025 22:11:55 +0000 Subject: [PATCH 202/809] Parallelize check_private_in_public. --- compiler/rustc_privacy/src/lib.rs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 1a062c63a6fe..ce1c937121e2 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1594,7 +1594,7 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> { self.effective_visibilities.effective_vis(def_id).copied() } - fn check_item(&mut self, id: ItemId) { + fn check_item(&self, id: ItemId) { let tcx = self.tcx; let def_id = id.owner_id.def_id; let item_visibility = tcx.local_visibility(def_id); @@ -1722,7 +1722,7 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> { } } - fn check_foreign_item(&mut self, id: ForeignItemId) { + fn check_foreign_item(&self, id: ForeignItemId) { let tcx = self.tcx; let def_id = id.owner_id.def_id; let item_visibility = tcx.local_visibility(def_id); @@ -1857,13 +1857,9 @@ fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities { fn check_private_in_public(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { let effective_visibilities = tcx.effective_visibilities(()); // Check for private types in public interfaces. - let mut checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities }; + let checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities }; let crate_items = tcx.hir_module_items(module_def_id); - for id in crate_items.free_items() { - checker.check_item(id); - } - for id in crate_items.foreign_items() { - checker.check_foreign_item(id); - } + let _ = crate_items.par_items(|id| Ok(checker.check_item(id))); + let _ = crate_items.par_foreign_items(|id| Ok(checker.check_foreign_item(id))); } From 1b01decc1ca851e014b6951bdd7f2ac2f897adc9 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 27 Jul 2025 22:15:40 +0000 Subject: [PATCH 203/809] Do not fetch spans if not required. --- compiler/rustc_privacy/src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index ce1c937121e2..87d4d180e178 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1423,8 +1423,6 @@ impl SearchInterfaceForPrivateItemsVisitor<'_> { }; let vis = self.tcx.local_visibility(local_def_id); - let span = self.tcx.def_span(self.item_def_id.to_def_id()); - let vis_span = self.tcx.def_span(def_id); if self.in_assoc_ty && !vis.is_at_least(self.required_visibility, self.tcx) { let vis_descr = match vis { ty::Visibility::Public => "public", @@ -1441,6 +1439,8 @@ impl SearchInterfaceForPrivateItemsVisitor<'_> { } }; + let span = self.tcx.def_span(self.item_def_id.to_def_id()); + let vis_span = self.tcx.def_span(def_id); self.tcx.dcx().emit_err(InPublicInterface { span, vis_descr, @@ -1463,6 +1463,8 @@ impl SearchInterfaceForPrivateItemsVisitor<'_> { } else { lint::builtin::PRIVATE_BOUNDS }; + let span = self.tcx.def_span(self.item_def_id.to_def_id()); + let vis_span = self.tcx.def_span(def_id); self.tcx.emit_node_span_lint( lint, self.tcx.local_def_id_to_hir_id(self.item_def_id), From 6bf3cbe39e09f4d9187a0b1f6a7bd45101f7aad8 Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Mon, 28 Jul 2025 00:01:28 +0300 Subject: [PATCH 204/809] 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 7db72f82cce7be6e905651fea58881fc66f13a9b Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 28 Jul 2025 01:00:48 +0000 Subject: [PATCH 205/809] Complete span lowering. --- compiler/rustc_ast_lowering/src/block.rs | 2 +- compiler/rustc_ast_lowering/src/expr.rs | 37 ++++++++++++++++------- compiler/rustc_ast_lowering/src/format.rs | 2 ++ compiler/rustc_ast_lowering/src/item.rs | 5 +-- compiler/rustc_ast_lowering/src/lib.rs | 15 +++++++-- 5 files changed, 45 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/block.rs b/compiler/rustc_ast_lowering/src/block.rs index c3222b79e55c..2cc07694afbc 100644 --- a/compiler/rustc_ast_lowering/src/block.rs +++ b/compiler/rustc_ast_lowering/src/block.rs @@ -95,7 +95,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_local(&mut self, l: &Local) -> &'hir hir::LetStmt<'hir> { // Let statements are allowed to have impl trait in bindings. - let super_ = l.super_; + let super_ = l.super_.map(|span| self.lower_span(span)); let ty = l.ty.as_ref().map(|t| { self.lower_ty(t, self.impl_trait_in_bindings_ctxt(ImplTraitPosition::Variable)) }); diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 15e736261d58..657792c93971 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -282,9 +282,11 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::Field(el, ident) => { hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(*ident)) } - ExprKind::Index(el, er, brackets_span) => { - hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er), *brackets_span) - } + ExprKind::Index(el, er, brackets_span) => hir::ExprKind::Index( + self.lower_expr(el), + self.lower_expr(er), + self.lower_span(*brackets_span), + ), ExprKind::Range(e1, e2, lims) => { self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), *lims) } @@ -334,7 +336,9 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::Struct(se) => { let rest = match &se.rest { StructRest::Base(e) => hir::StructTailExpr::Base(self.lower_expr(e)), - StructRest::Rest(sp) => hir::StructTailExpr::DefaultFields(*sp), + StructRest::Rest(sp) => { + hir::StructTailExpr::DefaultFields(self.lower_span(*sp)) + } StructRest::None => hir::StructTailExpr::None, }; hir::ExprKind::Struct( @@ -678,6 +682,14 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::Arm { hir_id, pat, guard, body, span } } + fn lower_capture_clause(&mut self, capture_clause: CaptureBy) -> CaptureBy { + match capture_clause { + CaptureBy::Ref => CaptureBy::Ref, + CaptureBy::Use { use_kw } => CaptureBy::Use { use_kw: self.lower_span(use_kw) }, + CaptureBy::Value { move_kw } => CaptureBy::Value { move_kw: self.lower_span(move_kw) }, + } + } + /// Lower/desugar a coroutine construct. /// /// In particular, this creates the correct async resume argument and `_task_context`. @@ -769,7 +781,7 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::ExprKind::Closure(self.arena.alloc(hir::Closure { def_id: closure_def_id, binder: hir::ClosureBinder::Default, - capture_clause, + capture_clause: self.lower_capture_clause(capture_clause), bound_generic_params: &[], fn_decl, body, @@ -1035,7 +1047,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn lower_expr_use(&mut self, use_kw_span: Span, expr: &Expr) -> hir::ExprKind<'hir> { - hir::ExprKind::Use(self.lower_expr(expr), use_kw_span) + hir::ExprKind::Use(self.lower_expr(expr), self.lower_span(use_kw_span)) } fn lower_expr_closure( @@ -1083,7 +1095,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let c = self.arena.alloc(hir::Closure { def_id: closure_def_id, binder: binder_clause, - capture_clause, + capture_clause: self.lower_capture_clause(capture_clause), bound_generic_params, fn_decl, body: body_id, @@ -1197,7 +1209,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let c = self.arena.alloc(hir::Closure { def_id: closure_def_id, binder: binder_clause, - capture_clause, + capture_clause: self.lower_capture_clause(capture_clause), bound_generic_params, fn_decl, body, @@ -2101,7 +2113,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn expr_uint(&mut self, sp: Span, ty: ast::UintTy, value: u128) -> hir::Expr<'hir> { let lit = hir::Lit { - span: sp, + span: self.lower_span(sp), node: ast::LitKind::Int(value.into(), ast::LitIntType::Unsigned(ty)), }; self.expr(sp, hir::ExprKind::Lit(lit)) @@ -2120,7 +2132,10 @@ impl<'hir> LoweringContext<'_, 'hir> { } pub(super) fn expr_str(&mut self, sp: Span, value: Symbol) -> hir::Expr<'hir> { - let lit = hir::Lit { span: sp, node: ast::LitKind::Str(value, ast::StrStyle::Cooked) }; + let lit = hir::Lit { + span: self.lower_span(sp), + node: ast::LitKind::Str(value, ast::StrStyle::Cooked), + }; self.expr(sp, hir::ExprKind::Lit(lit)) } @@ -2206,7 +2221,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.arena.alloc(hir::Path { span: self.lower_span(span), res, - segments: arena_vec![self; hir::PathSegment::new(ident, hir_id, res)], + segments: arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)], }), )); diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index 5b1dcab87b92..ec9d26eb33f4 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -402,6 +402,8 @@ fn expand_format_args<'hir>( fmt: &FormatArgs, allow_const: bool, ) -> hir::ExprKind<'hir> { + let macsp = ctx.lower_span(macsp); + let mut incomplete_lit = String::new(); let lit_pieces = ctx.arena.alloc_from_iter(fmt.template.iter().enumerate().filter_map(|(i, piece)| { diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index ddf01b69e7f6..1899dcda3619 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -627,6 +627,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } else { // For non-empty lists we can just drop all the data, the prefix is already // present in HIR as a part of nested imports. + let span = self.lower_span(span); self.arena.alloc(hir::UsePath { res: PerNS::default(), segments: &[], span }) }; hir::ItemKind::Use(path, hir::UseKind::ListStem) @@ -1567,7 +1568,7 @@ impl<'hir> LoweringContext<'_, 'hir> { attrs: &[hir::Attribute], ) -> hir::FnHeader { let asyncness = if let Some(CoroutineKind::Async { span, .. }) = h.coroutine_kind { - hir::IsAsync::Async(span) + hir::IsAsync::Async(self.lower_span(span)) } else { hir::IsAsync::NotAsync }; @@ -1804,7 +1805,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let res = Res::Def(DefKind::TyParam, def_id); let ident = self.lower_ident(ident); let ty_path = self.arena.alloc(hir::Path { - span: param_span, + span: self.lower_span(param_span), res, segments: self .arena diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 9aef189a29d4..189c82b614c2 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -2368,7 +2368,17 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &mut self, modifiers: TraitBoundModifiers, ) -> hir::TraitBoundModifiers { - hir::TraitBoundModifiers { constness: modifiers.constness, polarity: modifiers.polarity } + let constness = match modifiers.constness { + BoundConstness::Never => BoundConstness::Never, + BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)), + BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)), + }; + let polarity = match modifiers.polarity { + BoundPolarity::Positive => BoundPolarity::Positive, + BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)), + BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)), + }; + hir::TraitBoundModifiers { constness, polarity } } // Helper methods for building HIR. @@ -2414,6 +2424,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { init: Option<&'hir hir::Expr<'hir>>, ) -> hir::Stmt<'hir> { let hir_id = self.next_id(); + let span = self.lower_span(span); let local = hir::LetStmt { super_: Some(span), hir_id, @@ -2421,7 +2432,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { pat, els: None, source: hir::LocalSource::Normal, - span: self.lower_span(span), + span, ty: None, }; self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local))) From 43725ed819c57b86b32a66c40572246b1f5b8952 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sat, 26 Jul 2025 06:21:22 +0500 Subject: [PATCH 206/809] use let chains in ast, borrowck, codegen, const_eval --- compiler/rustc_ast_lowering/src/index.rs | 8 +- .../rustc_ast_passes/src/ast_validation.rs | 20 +- compiler/rustc_ast_passes/src/feature_gate.rs | 15 +- compiler/rustc_ast_pretty/src/pprust/state.rs | 8 +- .../src/diagnostics/conflict_errors.rs | 335 +++++++++--------- .../src/diagnostics/explain_borrow.rs | 37 +- .../rustc_borrowck/src/diagnostics/mod.rs | 64 ++-- .../src/diagnostics/move_errors.rs | 57 ++- .../src/diagnostics/region_name.rs | 10 +- .../rustc_borrowck/src/region_infer/mod.rs | 68 ++-- compiler/rustc_borrowck/src/type_check/mod.rs | 26 +- compiler/rustc_codegen_llvm/src/back/lto.rs | 8 +- compiler/rustc_codegen_llvm/src/builder.rs | 8 +- compiler/rustc_codegen_ssa/src/back/link.rs | 12 +- .../rustc_codegen_ssa/src/codegen_attrs.rs | 20 +- .../src/check_consts/check.rs | 8 +- .../rustc_const_eval/src/check_consts/ops.rs | 27 +- .../src/check_consts/resolver.rs | 16 +- .../src/interpret/eval_context.rs | 8 +- .../src/interpret/validity.rs | 8 +- compiler/rustc_errors/src/styled_buffer.rs | 11 +- compiler/rustc_hir_analysis/src/collect.rs | 11 +- .../src/hir_ty_lowering/bounds.rs | 20 +- .../rustc_hir_analysis/src/hir_wf_check.rs | 17 +- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 8 +- .../src/fn_ctxt/suggestions.rs | 46 +-- 26 files changed, 422 insertions(+), 454 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index 1ef64f5a3526..5b63206d7d62 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -164,11 +164,11 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_item(&mut self, i: &'hir Item<'hir>) { debug_assert_eq!(i.owner_id, self.owner); self.with_parent(i.hir_id(), |this| { - if let ItemKind::Struct(_, _, struct_def) = &i.kind { + if let ItemKind::Struct(_, _, struct_def) = &i.kind // If this is a tuple or unit-like struct, register the constructor. - if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { - this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def)); - } + && let Some(ctor_hir_id) = struct_def.ctor_hir_id() + { + this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def)); } intravisit::walk_item(this, i); }); diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index a08dae111530..895a457ec1d5 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -640,16 +640,16 @@ impl<'a> AstValidator<'a> { return; } - if let Some(header) = fk.header() { - if let Const::Yes(const_span) = header.constness { - let mut spans = variadic_spans.clone(); - spans.push(const_span); - self.dcx().emit_err(errors::ConstAndCVariadic { - spans, - const_span, - variadic_spans: variadic_spans.clone(), - }); - } + if let Some(header) = fk.header() + && let Const::Yes(const_span) = header.constness + { + let mut spans = variadic_spans.clone(); + spans.push(const_span); + self.dcx().emit_err(errors::ConstAndCVariadic { + spans, + const_span, + variadic_spans: variadic_spans.clone(), + }); } match (fk.ctxt(), fk.header()) { diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 8114733f4067..662357ce8841 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -630,16 +630,11 @@ fn check_incompatible_features(sess: &Session, features: &Features) { .iter() .filter(|(f1, f2)| features.enabled(*f1) && features.enabled(*f2)) { - if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1) { - if let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2) - { - let spans = vec![f1_span, f2_span]; - sess.dcx().emit_err(errors::IncompatibleFeatures { - spans, - f1: f1_name, - f2: f2_name, - }); - } + if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1) + && let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2) + { + let spans = vec![f1_span, f2_span]; + sess.dcx().emit_err(errors::IncompatibleFeatures { spans, f1: f1_name, f2: f2_name }); } } } diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index def0cb74d295..f0cf0c1487f7 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -572,10 +572,10 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere } fn maybe_print_trailing_comment(&mut self, span: rustc_span::Span, next_pos: Option) { - if let Some(cmnts) = self.comments_mut() { - if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) { - self.print_comment(cmnt); - } + if let Some(cmnts) = self.comments_mut() + && let Some(cmnt) = cmnts.trailing_comment(span, next_pos) + { + self.print_comment(cmnt); } } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 040a0607db56..17ae671b138b 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -2481,13 +2481,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // Check that the parent of the closure is a method call, // with receiver matching with local's type (modulo refs) - if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id) { - if let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind { - let recv_ty = typeck_results.expr_ty(recv); + if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id) + && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind + { + let recv_ty = typeck_results.expr_ty(recv); - if recv_ty.peel_refs() != local_ty { - return; - } + if recv_ty.peel_refs() != local_ty { + return; } } @@ -2753,16 +2753,16 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // With the place of a union and a field access into it, we traverse the second // borrowed place and look for an access to a different field of the same union. for (place_base, elem) in second_borrowed_place.iter_projections().rev() { - if let ProjectionElem::Field(field, _) = elem { - if let Some(union_ty) = union_ty(place_base) { - if field != target_field && place_base == target_base { - return Some(( - self.describe_any_place(place_base), - self.describe_any_place(first_borrowed_place.as_ref()), - self.describe_any_place(second_borrowed_place.as_ref()), - union_ty.to_string(), - )); - } + if let ProjectionElem::Field(field, _) = elem + && let Some(union_ty) = union_ty(place_base) + { + if field != target_field && place_base == target_base { + return Some(( + self.describe_any_place(place_base), + self.describe_any_place(first_borrowed_place.as_ref()), + self.describe_any_place(second_borrowed_place.as_ref()), + union_ty.to_string(), + )); } } } @@ -2949,16 +2949,15 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { from_closure: false, .. } = explanation - { - if let Err(diag) = self.try_report_cannot_return_reference_to_local( + && let Err(diag) = self.try_report_cannot_return_reference_to_local( borrow, borrow_span, span, category, opt_place_desc.as_ref(), - ) { - return diag; - } + ) + { + return diag; } let name = format!("`{name}`"); @@ -3720,30 +3719,30 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let loan_span = loan_spans.args_or_use(); let descr_place = self.describe_any_place(place.as_ref()); - if let BorrowKind::Fake(_) = loan.kind { - if let Some(section) = self.classify_immutable_section(loan.assigned_place) { - let mut err = self.cannot_mutate_in_immutable_section( - span, - loan_span, - &descr_place, - section, - "assign", - ); + if let BorrowKind::Fake(_) = loan.kind + && let Some(section) = self.classify_immutable_section(loan.assigned_place) + { + let mut err = self.cannot_mutate_in_immutable_section( + span, + loan_span, + &descr_place, + section, + "assign", + ); - loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| { - use crate::session_diagnostics::CaptureVarCause::*; - match kind { - hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span }, - hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => { - BorrowUseInClosure { var_span } - } + loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + match kind { + hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span }, + hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => { + BorrowUseInClosure { var_span } } - }); + } + }); - self.buffer_error(err); + self.buffer_error(err); - return; - } + return; } let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place); @@ -3996,119 +3995,116 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}", target, stmt ); - if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind { - if let Some(assigned_to) = place.as_local() { - debug!( - "annotate_argument_and_return_for_borrow: assigned_to={:?} \ + if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind + && let Some(assigned_to) = place.as_local() + { + debug!( + "annotate_argument_and_return_for_borrow: assigned_to={:?} \ rvalue={:?}", - assigned_to, rvalue - ); - // Check if our `target` was captured by a closure. - if let Rvalue::Aggregate( - box AggregateKind::Closure(def_id, args), - operands, - ) = rvalue - { - let def_id = def_id.expect_local(); - for operand in operands { - let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = - operand - else { - continue; - }; - debug!( - "annotate_argument_and_return_for_borrow: assigned_from={:?}", - assigned_from - ); + assigned_to, rvalue + ); + // Check if our `target` was captured by a closure. + if let Rvalue::Aggregate(box AggregateKind::Closure(def_id, args), operands) = + rvalue + { + let def_id = def_id.expect_local(); + for operand in operands { + let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = + operand + else { + continue; + }; + debug!( + "annotate_argument_and_return_for_borrow: assigned_from={:?}", + assigned_from + ); - // Find the local from the operand. - let Some(assigned_from_local) = - assigned_from.local_or_deref_local() - else { - continue; - }; + // Find the local from the operand. + let Some(assigned_from_local) = assigned_from.local_or_deref_local() + else { + continue; + }; - if assigned_from_local != target { - continue; - } - - // If a closure captured our `target` and then assigned - // into a place then we should annotate the closure in - // case it ends up being assigned into the return place. - annotated_closure = - self.annotate_fn_sig(def_id, args.as_closure().sig()); - debug!( - "annotate_argument_and_return_for_borrow: \ - annotated_closure={:?} assigned_from_local={:?} \ - assigned_to={:?}", - annotated_closure, assigned_from_local, assigned_to - ); - - if assigned_to == mir::RETURN_PLACE { - // If it was assigned directly into the return place, then - // return now. - return annotated_closure; - } else { - // Otherwise, update the target. - target = assigned_to; - } + if assigned_from_local != target { + continue; } - // If none of our closure's operands matched, then skip to the next - // statement. - continue; + // If a closure captured our `target` and then assigned + // into a place then we should annotate the closure in + // case it ends up being assigned into the return place. + annotated_closure = + self.annotate_fn_sig(def_id, args.as_closure().sig()); + debug!( + "annotate_argument_and_return_for_borrow: \ + annotated_closure={:?} assigned_from_local={:?} \ + assigned_to={:?}", + annotated_closure, assigned_from_local, assigned_to + ); + + if assigned_to == mir::RETURN_PLACE { + // If it was assigned directly into the return place, then + // return now. + return annotated_closure; + } else { + // Otherwise, update the target. + target = assigned_to; + } } - // Otherwise, look at other types of assignment. - let assigned_from = match rvalue { - Rvalue::Ref(_, _, assigned_from) => assigned_from, - Rvalue::Use(operand) => match operand { - Operand::Copy(assigned_from) | Operand::Move(assigned_from) => { - assigned_from - } - _ => continue, - }, - _ => continue, - }; - debug!( - "annotate_argument_and_return_for_borrow: \ - assigned_from={:?}", - assigned_from, - ); - - // Find the local from the rvalue. - let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { - continue; - }; - debug!( - "annotate_argument_and_return_for_borrow: \ - assigned_from_local={:?}", - assigned_from_local, - ); - - // Check if our local matches the target - if so, we've assigned our - // borrow to a new place. - if assigned_from_local != target { - continue; - } - - // If we assigned our `target` into a new place, then we should - // check if it was the return place. - debug!( - "annotate_argument_and_return_for_borrow: \ - assigned_from_local={:?} assigned_to={:?}", - assigned_from_local, assigned_to - ); - if assigned_to == mir::RETURN_PLACE { - // If it was then return the annotated closure if there was one, - // else, annotate this function. - return annotated_closure.or_else(fallback); - } - - // If we didn't assign into the return place, then we just update - // the target. - target = assigned_to; + // If none of our closure's operands matched, then skip to the next + // statement. + continue; } + + // Otherwise, look at other types of assignment. + let assigned_from = match rvalue { + Rvalue::Ref(_, _, assigned_from) => assigned_from, + Rvalue::Use(operand) => match operand { + Operand::Copy(assigned_from) | Operand::Move(assigned_from) => { + assigned_from + } + _ => continue, + }, + _ => continue, + }; + debug!( + "annotate_argument_and_return_for_borrow: \ + assigned_from={:?}", + assigned_from, + ); + + // Find the local from the rvalue. + let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { + continue; + }; + debug!( + "annotate_argument_and_return_for_borrow: \ + assigned_from_local={:?}", + assigned_from_local, + ); + + // Check if our local matches the target - if so, we've assigned our + // borrow to a new place. + if assigned_from_local != target { + continue; + } + + // If we assigned our `target` into a new place, then we should + // check if it was the return place. + debug!( + "annotate_argument_and_return_for_borrow: \ + assigned_from_local={:?} assigned_to={:?}", + assigned_from_local, assigned_to + ); + if assigned_to == mir::RETURN_PLACE { + // If it was then return the annotated closure if there was one, + // else, annotate this function. + return annotated_closure.or_else(fallback); + } + + // If we didn't assign into the return place, then we just update + // the target. + target = assigned_to; } } @@ -4120,32 +4116,31 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { ); if let TerminatorKind::Call { destination, target: Some(_), args, .. } = &terminator.kind + && let Some(assigned_to) = destination.as_local() { - if let Some(assigned_to) = destination.as_local() { + debug!( + "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}", + assigned_to, args + ); + for operand in args { + let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = + &operand.node + else { + continue; + }; debug!( - "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}", - assigned_to, args + "annotate_argument_and_return_for_borrow: assigned_from={:?}", + assigned_from, ); - for operand in args { - let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = - &operand.node - else { - continue; - }; + + if let Some(assigned_from_local) = assigned_from.local_or_deref_local() { debug!( - "annotate_argument_and_return_for_borrow: assigned_from={:?}", - assigned_from, + "annotate_argument_and_return_for_borrow: assigned_from_local={:?}", + assigned_from_local, ); - if let Some(assigned_from_local) = assigned_from.local_or_deref_local() { - debug!( - "annotate_argument_and_return_for_borrow: assigned_from_local={:?}", - assigned_from_local, - ); - - if assigned_to == mir::RETURN_PLACE && assigned_from_local == target { - return annotated_closure.or_else(fallback); - } + if assigned_to == mir::RETURN_PLACE && assigned_from_local == target { + return annotated_closure.or_else(fallback); } } } @@ -4244,10 +4239,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // as the HIR doesn't have full types for closure arguments. let return_ty = sig.output().skip_binder(); let mut return_span = fn_decl.output.span(); - if let hir::FnRetTy::Return(ty) = &fn_decl.output { - if let hir::TyKind::Ref(lifetime, _) = ty.kind { - return_span = lifetime.ident.span; - } + if let hir::FnRetTy::Return(ty) = &fn_decl.output + && let hir::TyKind::Ref(lifetime, _) = ty.kind + { + return_span = lifetime.ident.span; } Some(AnnotatedBorrowFnSignature::NamedFunction { diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index f9e52239d6f6..a10da08ddf34 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -917,30 +917,29 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { if let TerminatorKind::Call { destination, target: Some(block), args, .. } = &terminator.kind + && let Some(dest) = destination.as_local() { - if let Some(dest) = destination.as_local() { - debug!( - "was_captured_by_trait_object: target={:?} dest={:?} args={:?}", - target, dest, args - ); - // Check if one of the arguments to this function is the target place. - let found_target = args.iter().any(|arg| { - if let Operand::Move(place) = arg.node { - if let Some(potential) = place.as_local() { - potential == target - } else { - false - } + debug!( + "was_captured_by_trait_object: target={:?} dest={:?} args={:?}", + target, dest, args + ); + // Check if one of the arguments to this function is the target place. + let found_target = args.iter().any(|arg| { + if let Operand::Move(place) = arg.node { + if let Some(potential) = place.as_local() { + potential == target } else { false } - }); - - // If it is, follow this to the next block and update the target. - if found_target { - target = dest; - queue.push(block.start_location()); + } else { + false } + }); + + // If it is, follow this to the next block and update the target. + if found_target { + target = dest; + queue.push(block.start_location()); } } } diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 9ad91d605a77..ed4cd52ed9c8 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -266,48 +266,44 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { args, .. } = &terminator.kind + && let ty::FnDef(id, _) = *const_.ty().kind() { - if let ty::FnDef(id, _) = *const_.ty().kind() { - debug!("add_moved_or_invoked_closure_note: id={:?}", id); - if self.infcx.tcx.is_lang_item(self.infcx.tcx.parent(id), LangItem::FnOnce) { - let closure = match args.first() { - Some(Spanned { - node: Operand::Copy(place) | Operand::Move(place), .. - }) if target == place.local_or_deref_local() => { - place.local_or_deref_local().unwrap() - } - _ => return false, - }; + debug!("add_moved_or_invoked_closure_note: id={:?}", id); + if self.infcx.tcx.is_lang_item(self.infcx.tcx.parent(id), LangItem::FnOnce) { + let closure = match args.first() { + Some(Spanned { node: Operand::Copy(place) | Operand::Move(place), .. }) + if target == place.local_or_deref_local() => + { + place.local_or_deref_local().unwrap() + } + _ => return false, + }; - debug!("add_moved_or_invoked_closure_note: closure={:?}", closure); - if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() { - let did = did.expect_local(); - if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { - diag.subdiagnostic(OnClosureNote::InvokedTwice { - place_name: &ty::place_to_string_for_capture( - self.infcx.tcx, - hir_place, - ), - span: *span, - }); - return true; - } + debug!("add_moved_or_invoked_closure_note: closure={:?}", closure); + if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() { + let did = did.expect_local(); + if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { + diag.subdiagnostic(OnClosureNote::InvokedTwice { + place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), + span: *span, + }); + return true; } } } } // Check if we are just moving a closure after it has been invoked. - if let Some(target) = target { - if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() { - let did = did.expect_local(); - if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { - diag.subdiagnostic(OnClosureNote::MovedTwice { - place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), - span: *span, - }); - return true; - } + if let Some(target) = target + && let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() + { + let did = did.expect_local(); + if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { + diag.subdiagnostic(OnClosureNote::MovedTwice { + place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), + span: *span, + }); + return true; } } false diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index a5661e44af8a..1067f1e40ef6 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -126,36 +126,35 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { .statements .get(location.statement_index) .map(|stmt| &stmt.kind) + && let Some(local) = place.as_local() { - if let Some(local) = place.as_local() { - let local_decl = &self.body.local_decls[local]; - // opt_match_place is the - // match_span is the span of the expression being matched on - // match *x.y { ... } match_place is Some(*x.y) - // ^^^^ match_span is the span of *x.y - // - // opt_match_place is None for let [mut] x = ... statements, - // whether or not the right-hand side is a place expression - if let LocalInfo::User(BindingForm::Var(VarBindingForm { - opt_match_place: Some((opt_match_place, match_span)), - binding_mode: _, - opt_ty_info: _, - pat_span: _, - })) = *local_decl.local_info() - { - let stmt_source_info = self.body.source_info(location); - self.append_binding_error( - grouped_errors, - kind, - original_path, - *move_from, - local, - opt_match_place, - match_span, - stmt_source_info.span, - ); - return; - } + let local_decl = &self.body.local_decls[local]; + // opt_match_place is the + // match_span is the span of the expression being matched on + // match *x.y { ... } match_place is Some(*x.y) + // ^^^^ match_span is the span of *x.y + // + // opt_match_place is None for let [mut] x = ... statements, + // whether or not the right-hand side is a place expression + if let LocalInfo::User(BindingForm::Var(VarBindingForm { + opt_match_place: Some((opt_match_place, match_span)), + binding_mode: _, + opt_ty_info: _, + pat_span: _, + })) = *local_decl.local_info() + { + let stmt_source_info = self.body.source_info(location); + self.append_binding_error( + grouped_errors, + kind, + original_path, + *move_from, + local, + opt_match_place, + match_span, + stmt_source_info.span, + ); + return; } } diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index edd14d155f66..517f9e88cd9b 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -528,15 +528,15 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { // match_adt_and_segment in this case. Res::Def(DefKind::TyAlias, _) => (), _ => { - if let Some(last_segment) = path.segments.last() { - if let Some(highlight) = self.match_adt_and_segment( + if let Some(last_segment) = path.segments.last() + && let Some(highlight) = self.match_adt_and_segment( args, needle_fr, last_segment, search_stack, - ) { - return Some(highlight); - } + ) + { + return Some(highlight); } } } diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index 5f1b655c6b60..68f1637e07ee 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -822,10 +822,10 @@ impl<'tcx> RegionInferenceContext<'tcx> { continue; } - if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements { - if self.try_promote_type_test(infcx, type_test, propagated_outlives_requirements) { - continue; - } + if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements + && self.try_promote_type_test(infcx, type_test, propagated_outlives_requirements) + { + continue; } // Type-test failed. Report the error. @@ -1479,40 +1479,36 @@ impl<'tcx> RegionInferenceContext<'tcx> { shorter_fr: RegionVid, propagated_outlives_requirements: &mut Option<&mut Vec>>, ) -> RegionRelationCheckResult { - if let Some(propagated_outlives_requirements) = propagated_outlives_requirements { + if let Some(propagated_outlives_requirements) = propagated_outlives_requirements // Shrink `longer_fr` until we find a non-local region (if we do). // We'll call it `fr-` -- it's ever so slightly smaller than // `longer_fr`. - if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr) - { - debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus); + && let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr) + { + debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus); - let blame_span_category = self.find_outlives_blame_span( - longer_fr, - NllRegionVariableOrigin::FreeRegion, - shorter_fr, - ); + let blame_span_category = self.find_outlives_blame_span( + longer_fr, + NllRegionVariableOrigin::FreeRegion, + shorter_fr, + ); - // Grow `shorter_fr` until we find some non-local regions. (We - // always will.) We'll call them `shorter_fr+` -- they're ever - // so slightly larger than `shorter_fr`. - let shorter_fr_plus = - self.universal_region_relations.non_local_upper_bounds(shorter_fr); - debug!( - "try_propagate_universal_region_error: shorter_fr_plus={:?}", - shorter_fr_plus - ); - for fr in shorter_fr_plus { - // Push the constraint `fr-: shorter_fr+` - propagated_outlives_requirements.push(ClosureOutlivesRequirement { - subject: ClosureOutlivesSubject::Region(fr_minus), - outlived_free_region: fr, - blame_span: blame_span_category.1.span, - category: blame_span_category.0, - }); - } - return RegionRelationCheckResult::Propagated; + // Grow `shorter_fr` until we find some non-local regions. (We + // always will.) We'll call them `shorter_fr+` -- they're ever + // so slightly larger than `shorter_fr`. + let shorter_fr_plus = + self.universal_region_relations.non_local_upper_bounds(shorter_fr); + debug!("try_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus); + for fr in shorter_fr_plus { + // Push the constraint `fr-: shorter_fr+` + propagated_outlives_requirements.push(ClosureOutlivesRequirement { + subject: ClosureOutlivesSubject::Region(fr_minus), + outlived_free_region: fr, + blame_span: blame_span_category.1.span, + category: blame_span_category.0, + }); } + return RegionRelationCheckResult::Propagated; } RegionRelationCheckResult::Error @@ -2085,11 +2081,11 @@ impl<'tcx> RegionInferenceContext<'tcx> { let locations = self.scc_values.locations_outlived_by(scc); for location in locations { let bb = &body[location.block]; - if let Some(terminator) = &bb.terminator { + if let Some(terminator) = &bb.terminator // terminator of a loop should be TerminatorKind::FalseUnwind - if let TerminatorKind::FalseUnwind { .. } = terminator.kind { - return Some(location); - } + && let TerminatorKind::FalseUnwind { .. } = terminator.kind + { + return Some(location); } } None diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index d500088c259a..f363ef0a5a98 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -669,24 +669,24 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ); } - if let Some(annotation_index) = self.rvalue_user_ty(rv) { - if let Err(terr) = self.relate_type_and_user_type( + if let Some(annotation_index) = self.rvalue_user_ty(rv) + && let Err(terr) = self.relate_type_and_user_type( rv_ty, ty::Invariant, &UserTypeProjection { base: annotation_index, projs: vec![] }, location.to_locations(), ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg), - ) { - let annotation = &self.user_type_annotations[annotation_index]; - span_mirbug!( - self, - stmt, - "bad user type on rvalue ({:?} = {:?}): {:?}", - annotation, - rv_ty, - terr - ); - } + ) + { + let annotation = &self.user_type_annotations[annotation_index]; + span_mirbug!( + self, + stmt, + "bad user type on rvalue ({:?} = {:?}): {:?}", + annotation, + rv_ty, + terr + ); } if !self.unsized_feature_enabled() { diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index 767835c34f02..657513991acd 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -505,10 +505,10 @@ fn thin_lto( // Save the current ThinLTO import information for the next compilation // session, overwriting the previous serialized data (if any). - if let Some(path) = key_map_path { - if let Err(err) = curr_key_map.save_to_file(&path) { - return Err(write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err })); - } + if let Some(path) = key_map_path + && let Err(err) = curr_key_map.save_to_file(&path) + { + return Err(write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err })); } Ok((opt_jobs, copy_jobs)) diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 0ade9edb0d2e..f712b3b83faa 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -687,10 +687,10 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { bx.nonnull_metadata(load); } - if let Some(pointee) = layout.pointee_info_at(bx, offset) { - if let Some(_) = pointee.safe { - bx.align_metadata(load, pointee.align); - } + if let Some(pointee) = layout.pointee_info_at(bx, offset) + && let Some(_) = pointee.safe + { + bx.align_metadata(load, pointee.align); } } abi::Primitive::Float(_) => {} diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 5ce301c0eb98..162fbf3d6e24 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -3369,12 +3369,12 @@ fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box, did: LocalDefId) -> CodegenFnAttrs { ) .with_note("Rustc requires this item to have a specific mangled name.") .with_span_label(tcx.def_span(did), "should be the internal language item"); - if let Some(lang_item) = lang_item { - if let Some(link_name) = lang_item.link_name() { - err = err - .with_note("If you are trying to prevent mangling to ease debugging, many") - .with_note(format!( - "debuggers support a command such as `rbreak {link_name}` to" - )) - .with_note(format!( - "match `.*{link_name}.*` instead of `break {link_name}` on a specific name" - )) - } + if let Some(lang_item) = lang_item + && let Some(link_name) = lang_item.link_name() + { + err = err + .with_note("If you are trying to prevent mangling to ease debugging, many") + .with_note(format!("debuggers support a command such as `rbreak {link_name}` to")) + .with_note(format!( + "match `.*{link_name}.*` instead of `break {link_name}` on a specific name" + )) } err.emit(); } diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 0eb6f28bdb37..69637cadcc99 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -714,10 +714,10 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) { self.super_operand(op, location); - if let Operand::Constant(c) = op { - if let Some(def_id) = c.check_static_ptr(self.tcx) { - self.check_static(def_id, self.span); - } + if let Operand::Constant(c) = op + && let Some(def_id) = c.check_static_ptr(self.tcx) + { + self.check_static(def_id, self.span); } } diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index b2e0577cc824..982e640fa92a 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -295,21 +295,18 @@ fn build_error_for_const_call<'tcx>( } let deref = "*".repeat(num_refs); - if let Ok(call_str) = ccx.tcx.sess.source_map().span_to_snippet(span) { - if let Some(eq_idx) = call_str.find("==") { - if let Some(rhs_idx) = - call_str[(eq_idx + 2)..].find(|c: char| !c.is_whitespace()) - { - let rhs_pos = - span.lo() + BytePos::from_usize(eq_idx + 2 + rhs_idx); - let rhs_span = span.with_lo(rhs_pos).with_hi(rhs_pos); - sugg = Some(errors::ConsiderDereferencing { - deref, - span: span.shrink_to_lo(), - rhs_span, - }); - } - } + if let Ok(call_str) = ccx.tcx.sess.source_map().span_to_snippet(span) + && let Some(eq_idx) = call_str.find("==") + && let Some(rhs_idx) = + call_str[(eq_idx + 2)..].find(|c: char| !c.is_whitespace()) + { + let rhs_pos = span.lo() + BytePos::from_usize(eq_idx + 2 + rhs_idx); + let rhs_span = span.with_lo(rhs_pos).with_hi(rhs_pos); + sugg = Some(errors::ConsiderDereferencing { + deref, + span: span.shrink_to_lo(), + rhs_span, + }); } } _ => {} diff --git a/compiler/rustc_const_eval/src/check_consts/resolver.rs b/compiler/rustc_const_eval/src/check_consts/resolver.rs index 9f7fcc509a58..d98e5027e4d6 100644 --- a/compiler/rustc_const_eval/src/check_consts/resolver.rs +++ b/compiler/rustc_const_eval/src/check_consts/resolver.rs @@ -137,14 +137,14 @@ where // If a local with no projections is moved from (e.g. `x` in `y = x`), record that // it no longer needs to be dropped. - if let mir::Operand::Move(place) = operand { - if let Some(local) = place.as_local() { - // For backward compatibility with the MaybeMutBorrowedLocals used in an earlier - // implementation we retain qualif if a local had been borrowed before. This might - // not be strictly necessary since the local is no longer initialized. - if !self.state.borrow.contains(local) { - self.state.qualif.remove(local); - } + if let mir::Operand::Move(place) = operand + && let Some(local) = place.as_local() + { + // For backward compatibility with the MaybeMutBorrowedLocals used in an earlier + // implementation we retain qualif if a local had been borrowed before. This might + // not be strictly necessary since the local is no longer initialized. + if !self.state.borrow.contains(local) { + self.state.qualif.remove(local); } } } diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 0c888694e49b..0a8591ca140d 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -442,10 +442,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // # First compute the dynamic alignment // Packed type alignment needs to be capped. - if let ty::Adt(def, _) = layout.ty.kind() { - if let Some(packed) = def.repr().pack { - unsized_align = unsized_align.min(packed); - } + if let ty::Adt(def, _) = layout.ty.kind() + && let Some(packed) = def.repr().pack + { + unsized_align = unsized_align.min(packed); } // Choose max of two known alignments (combined value must diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 693b37829600..ed48f53c3105 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -320,10 +320,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { // for a coroutine). let var_hir_id = captured_place.get_root_variable(); let node = self.ecx.tcx.hir_node(var_hir_id); - if let hir::Node::Pat(pat) = node { - if let hir::PatKind::Binding(_, _, ident, _) = pat.kind { - name = Some(ident.name); - } + if let hir::Node::Pat(pat) = node + && let hir::PatKind::Binding(_, _, ident, _) = pat.kind + { + name = Some(ident.name); } } } diff --git a/compiler/rustc_errors/src/styled_buffer.rs b/compiler/rustc_errors/src/styled_buffer.rs index 790efd0286e9..095502e80aa5 100644 --- a/compiler/rustc_errors/src/styled_buffer.rs +++ b/compiler/rustc_errors/src/styled_buffer.rs @@ -153,12 +153,11 @@ impl StyledBuffer { /// 1. That line and column exist in `StyledBuffer` /// 2. `overwrite` is `true` or existing style is `Style::NoStyle` or `Style::Quotation` fn set_style(&mut self, line: usize, col: usize, style: Style, overwrite: bool) { - if let Some(ref mut line) = self.lines.get_mut(line) { - if let Some(StyledChar { style: s, .. }) = line.get_mut(col) { - if overwrite || matches!(s, Style::NoStyle | Style::Quotation) { - *s = style; - } - } + if let Some(ref mut line) = self.lines.get_mut(line) + && let Some(StyledChar { style: s, .. }) = line.get_mut(col) + && (overwrite || matches!(s, Style::NoStyle | Style::Quotation)) + { + *s = style; } } } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 0728b24eb142..afe79bed851c 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -530,13 +530,12 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { .iter() .enumerate() .map(|(i, a)| { - if let hir::TyKind::Infer(()) = a.kind { - if let Some(suggested_ty) = + if let hir::TyKind::Infer(()) = a.kind + && let Some(suggested_ty) = self.lowerer().suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i)) - { - infer_replacements.push((a.span, suggested_ty.to_string())); - return Ty::new_error_with_message(tcx, a.span, suggested_ty.to_string()); - } + { + infer_replacements.push((a.span, suggested_ty.to_string())); + return Ty::new_error_with_message(tcx, a.span, suggested_ty.to_string()); } self.lowerer().lower_ty(a) 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..7760642d8fb0 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -617,18 +617,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { }); // Provide the resolved type of the associated constant to `type_of(AnonConst)`. - if let Some(const_arg) = constraint.ct() { - if let hir::ConstArgKind::Anon(anon_const) = const_arg.kind { - let ty = alias_term - .map_bound(|alias| tcx.type_of(alias.def_id).instantiate(tcx, alias.args)); - let ty = check_assoc_const_binding_type( - self, - constraint.ident, - ty, - constraint.hir_id, - ); - tcx.feed_anon_const_type(anon_const.def_id, ty::EarlyBinder::bind(ty)); - } + if let Some(const_arg) = constraint.ct() + && let hir::ConstArgKind::Anon(anon_const) = const_arg.kind + { + let ty = alias_term + .map_bound(|alias| tcx.type_of(alias.def_id).instantiate(tcx, alias.args)); + let ty = + check_assoc_const_binding_type(self, constraint.ident, ty, constraint.hir_id); + tcx.feed_anon_const_type(anon_const.def_id, ty::EarlyBinder::bind(ty)); } alias_term diff --git a/compiler/rustc_hir_analysis/src/hir_wf_check.rs b/compiler/rustc_hir_analysis/src/hir_wf_check.rs index bf539dfab42a..3fddaee8cef4 100644 --- a/compiler/rustc_hir_analysis/src/hir_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/hir_wf_check.rs @@ -103,16 +103,15 @@ pub(super) fn diagnostic_hir_wf_check<'tcx>( // over less-specific types (e.g. `Option>`) if self.depth >= self.cause_depth { self.cause = Some(error.obligation.cause); - if let hir::TyKind::TraitObject(..) = ty.kind { - if let DefKind::AssocTy | DefKind::AssocConst | DefKind::AssocFn = + if let hir::TyKind::TraitObject(..) = ty.kind + && let DefKind::AssocTy | DefKind::AssocConst | DefKind::AssocFn = self.tcx.def_kind(self.def_id) - { - self.cause = Some(ObligationCause::new( - ty.span, - self.def_id, - ObligationCauseCode::DynCompatible(ty.span), - )); - } + { + self.cause = Some(ObligationCause::new( + ty.span, + self.def_id, + ObligationCauseCode::DynCompatible(ty.span), + )); } self.cause_depth = self.depth } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index eb8d671c939c..719989d57930 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -2136,10 +2136,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) }; - if let hir::ExprKind::If(_, _, Some(el)) = expr.kind { - if let Some(rslt) = check_in_progress(el) { - return rslt; - } + if let hir::ExprKind::If(_, _, Some(el)) = expr.kind + && let Some(rslt) = check_in_progress(el) + { + return rslt; } if let hir::ExprKind::Match(_, arms, _) = expr.kind { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index d18f4e03d2fa..ede02fbf9bd3 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -615,31 +615,31 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool { - if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) { - if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) { - // Report upto four upvars being captured to reduce the amount error messages - // reported back to the user. - let spans_and_labels = upvars - .iter() - .take(4) - .map(|(var_hir_id, upvar)| { - let var_name = self.tcx.hir_name(*var_hir_id).to_string(); - let msg = format!("`{var_name}` captured here"); - (upvar.span, msg) - }) - .collect::>(); + if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) + && let Some(upvars) = self.tcx.upvars_mentioned(*def_id) + { + // Report upto four upvars being captured to reduce the amount error messages + // reported back to the user. + let spans_and_labels = upvars + .iter() + .take(4) + .map(|(var_hir_id, upvar)| { + let var_name = self.tcx.hir_name(*var_hir_id).to_string(); + let msg = format!("`{var_name}` captured here"); + (upvar.span, msg) + }) + .collect::>(); - let mut multi_span: MultiSpan = - spans_and_labels.iter().map(|(sp, _)| *sp).collect::>().into(); - for (sp, label) in spans_and_labels { - multi_span.push_span_label(sp, label); - } - err.span_note( - multi_span, - "closures can only be coerced to `fn` types if they do not capture any variables" - ); - return true; + let mut multi_span: MultiSpan = + spans_and_labels.iter().map(|(sp, _)| *sp).collect::>().into(); + for (sp, label) in spans_and_labels { + multi_span.push_span_label(sp, label); } + err.span_note( + multi_span, + "closures can only be coerced to `fn` types if they do not capture any variables", + ); + return true; } false } From bae38bad7803be7fdf1878188da9650f82548016 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sat, 26 Jul 2025 06:21:54 +0500 Subject: [PATCH 207/809] use let chains in hir, lint, mir --- .../src/fn_ctxt/suggestions.rs | 12 +- .../rustc_hir_typeck/src/method/confirm.rs | 10 +- .../rustc_hir_typeck/src/typeck_root_ctxt.rs | 9 +- compiler/rustc_hir_typeck/src/writeback.rs | 12 +- compiler/rustc_lint/src/builtin.rs | 48 ++++---- compiler/rustc_lint/src/internal.rs | 31 +++-- compiler/rustc_lint/src/map_unit_fn.rs | 110 +++++++++--------- compiler/rustc_lint/src/non_fmt_panic.rs | 60 +++++----- compiler/rustc_lint/src/nonstandard_style.rs | 18 +-- compiler/rustc_lint/src/unused.rs | 53 ++++----- compiler/rustc_metadata/src/locator.rs | 9 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 8 +- compiler/rustc_middle/src/middle/region.rs | 31 +++-- compiler/rustc_middle/src/ty/adt.rs | 8 +- compiler/rustc_middle/src/ty/layout.rs | 8 +- compiler/rustc_middle/src/ty/print/pretty.rs | 8 +- compiler/rustc_mir_build/src/thir/cx/block.rs | 38 +++--- compiler/rustc_mir_build/src/thir/cx/expr.rs | 18 +-- .../src/thir/pattern/check_match.rs | 12 +- .../src/drop_flag_effects.rs | 5 +- .../src/impls/initialized.rs | 13 +-- compiler/rustc_mir_dataflow/src/rustc_peek.rs | 48 ++++---- .../rustc_mir_dataflow/src/value_analysis.rs | 8 +- .../rustc_mir_transform/src/coroutine/drop.rs | 8 +- 24 files changed, 278 insertions(+), 307 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index ede02fbf9bd3..33ae4f6c45cf 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -3008,13 +3008,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Returns whether the given expression is an `else if`. fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool { - if let hir::ExprKind::If(..) = expr.kind { - if let Node::Expr(hir::Expr { - kind: hir::ExprKind::If(_, _, Some(else_expr)), .. - }) = self.tcx.parent_hir_node(expr.hir_id) - { - return else_expr.hir_id == expr.hir_id; - } + if let hir::ExprKind::If(..) = expr.kind + && let Node::Expr(hir::Expr { kind: hir::ExprKind::If(_, _, Some(else_expr)), .. }) = + self.tcx.parent_hir_node(expr.hir_id) + { + return else_expr.hir_id == expr.hir_id; } false } diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 4c343bb7c229..8d9f7eaf1774 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -669,17 +669,17 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn check_for_illegal_method_calls(&self, pick: &probe::Pick<'_>) { // Disallow calls to the method `drop` defined in the `Drop` trait. - if let Some(trait_def_id) = pick.item.trait_container(self.tcx) { - if let Err(e) = callee::check_legal_trait_for_method_call( + if let Some(trait_def_id) = pick.item.trait_container(self.tcx) + && let Err(e) = callee::check_legal_trait_for_method_call( self.tcx, self.span, Some(self.self_expr.span), self.call_expr.span, trait_def_id, self.body_id.to_def_id(), - ) { - self.set_tainted_by_errors(e); - } + ) + { + self.set_tainted_by_errors(e); } } diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index 9f4ab8ca5d41..6a985fc91e7d 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -165,13 +165,12 @@ impl<'tcx> TypeckRootCtxt<'tcx> { if let ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) = obligation.predicate.kind().skip_binder() - { // If the projection predicate (Foo::Bar == X) has X as a non-TyVid, // we need to make it into one. - if let Some(vid) = predicate.term.as_type().and_then(|ty| ty.ty_vid()) { - debug!("infer_var_info: {:?}.output = true", vid); - infer_var_info.entry(vid).or_default().output = true; - } + && let Some(vid) = predicate.term.as_type().and_then(|ty| ty.ty_vid()) + { + debug!("infer_var_info: {:?}.output = true", vid); + infer_var_info.entry(vid).or_default().output = true; } } } diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index b2497cb0de16..093de950d636 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -227,21 +227,19 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { self.typeck_results.type_dependent_defs_mut().remove(e.hir_id); self.typeck_results.node_args_mut().remove(e.hir_id); - if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id) { + if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id) // Discard the need for a mutable borrow - // Extra adjustment made when indexing causes a drop // of size information - we need to get rid of it // Since this is "after" the other adjustment to be // discarded, we do an extra `pop()` - if let Some(Adjustment { + && let Some(Adjustment { kind: Adjust::Pointer(PointerCoercion::Unsize), .. }) = a.pop() - { - // So the borrow discard actually happens here - a.pop(); - } + { + // So the borrow discard actually happens here + a.pop(); } } } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index eb4c3703dbd6..c48fb286dc0f 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2446,16 +2446,16 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { /// Determine if this expression is a "dangerous initialization". fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option { - if let hir::ExprKind::Call(path_expr, args) = expr.kind { + if let hir::ExprKind::Call(path_expr, args) = expr.kind // Find calls to `mem::{uninitialized,zeroed}` methods. - if let hir::ExprKind::Path(ref qpath) = path_expr.kind { - let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; - match cx.tcx.get_diagnostic_name(def_id) { - Some(sym::mem_zeroed) => return Some(InitKind::Zeroed), - Some(sym::mem_uninitialized) => return Some(InitKind::Uninit), - Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed), - _ => {} - } + && let hir::ExprKind::Path(ref qpath) = path_expr.kind + { + let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; + match cx.tcx.get_diagnostic_name(def_id) { + Some(sym::mem_zeroed) => return Some(InitKind::Zeroed), + Some(sym::mem_uninitialized) => return Some(InitKind::Uninit), + Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed), + _ => {} } } else if let hir::ExprKind::MethodCall(_, receiver, ..) = expr.kind { // Find problematic calls to `MaybeUninit::assume_init`. @@ -2463,14 +2463,14 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) { // This is a call to *some* method named `assume_init`. // See if the `self` parameter is one of the dangerous constructors. - if let hir::ExprKind::Call(path_expr, _) = receiver.kind { - if let hir::ExprKind::Path(ref qpath) = path_expr.kind { - let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; - match cx.tcx.get_diagnostic_name(def_id) { - Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed), - Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit), - _ => {} - } + if let hir::ExprKind::Call(path_expr, _) = receiver.kind + && let hir::ExprKind::Path(ref qpath) = path_expr.kind + { + let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; + match cx.tcx.get_diagnostic_name(def_id) { + Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed), + Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit), + _ => {} } } } @@ -2724,13 +2724,13 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { } // check for call to `core::ptr::null` or `core::ptr::null_mut` hir::ExprKind::Call(path, _) => { - if let hir::ExprKind::Path(ref qpath) = path.kind { - if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() { - return matches!( - cx.tcx.get_diagnostic_name(def_id), - Some(sym::ptr_null | sym::ptr_null_mut) - ); - } + if let hir::ExprKind::Path(ref qpath) = path.kind + && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() + { + return matches!( + cx.tcx.get_diagnostic_name(def_id), + Some(sym::ptr_null | sym::ptr_null_mut) + ); } } _ => {} diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index d8fc46aa9ab5..7dafcc199a32 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -411,22 +411,21 @@ declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]); impl EarlyLintPass for LintPassImpl { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { - if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind { - if let Some(last) = lint_pass.path.segments.last() { - if last.ident.name == sym::LintPass { - let expn_data = lint_pass.path.span.ctxt().outer_expn_data(); - let call_site = expn_data.call_site; - if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass) - && call_site.ctxt().outer_expn_data().kind - != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass) - { - cx.emit_span_lint( - LINT_PASS_IMPL_WITHOUT_MACRO, - lint_pass.path.span, - LintPassByHand, - ); - } - } + if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind + && let Some(last) = lint_pass.path.segments.last() + && last.ident.name == sym::LintPass + { + let expn_data = lint_pass.path.span.ctxt().outer_expn_data(); + let call_site = expn_data.call_site; + if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass) + && call_site.ctxt().outer_expn_data().kind + != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass) + { + cx.emit_span_lint( + LINT_PASS_IMPL_WITHOUT_MACRO, + lint_pass.path.span, + LintPassByHand, + ); } } } diff --git a/compiler/rustc_lint/src/map_unit_fn.rs b/compiler/rustc_lint/src/map_unit_fn.rs index af509cb786db..a8803158889f 100644 --- a/compiler/rustc_lint/src/map_unit_fn.rs +++ b/compiler/rustc_lint/src/map_unit_fn.rs @@ -43,56 +43,50 @@ impl<'tcx> LateLintPass<'tcx> for MapUnitFn { return; } - if let StmtKind::Semi(expr) = stmt.kind { - if let ExprKind::MethodCall(path, receiver, args, span) = expr.kind { - if path.ident.name.as_str() == "map" { - if receiver.span.from_expansion() - || args.iter().any(|e| e.span.from_expansion()) - || !is_impl_slice(cx, receiver) - || !is_diagnostic_name(cx, expr.hir_id, "IteratorMap") - { - return; + if let StmtKind::Semi(expr) = stmt.kind + && let ExprKind::MethodCall(path, receiver, args, span) = expr.kind + { + if path.ident.name.as_str() == "map" { + if receiver.span.from_expansion() + || args.iter().any(|e| e.span.from_expansion()) + || !is_impl_slice(cx, receiver) + || !is_diagnostic_name(cx, expr.hir_id, "IteratorMap") + { + return; + } + let arg_ty = cx.typeck_results().expr_ty(&args[0]); + let default_span = args[0].span; + if let ty::FnDef(id, _) = arg_ty.kind() { + let fn_ty = cx.tcx.fn_sig(id).skip_binder(); + let ret_ty = fn_ty.output().skip_binder(); + if is_unit_type(ret_ty) { + cx.emit_span_lint( + MAP_UNIT_FN, + span, + MappingToUnit { + function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span), + argument_label: args[0].span, + map_label: span, + suggestion: path.ident.span, + replace: "for_each".to_string(), + }, + ) } - let arg_ty = cx.typeck_results().expr_ty(&args[0]); - let default_span = args[0].span; - if let ty::FnDef(id, _) = arg_ty.kind() { - let fn_ty = cx.tcx.fn_sig(id).skip_binder(); - let ret_ty = fn_ty.output().skip_binder(); - if is_unit_type(ret_ty) { - cx.emit_span_lint( - MAP_UNIT_FN, - span, - MappingToUnit { - function_label: cx - .tcx - .span_of_impl(*id) - .unwrap_or(default_span), - argument_label: args[0].span, - map_label: span, - suggestion: path.ident.span, - replace: "for_each".to_string(), - }, - ) - } - } else if let ty::Closure(id, subs) = arg_ty.kind() { - let cl_ty = subs.as_closure().sig(); - let ret_ty = cl_ty.output().skip_binder(); - if is_unit_type(ret_ty) { - cx.emit_span_lint( - MAP_UNIT_FN, - span, - MappingToUnit { - function_label: cx - .tcx - .span_of_impl(*id) - .unwrap_or(default_span), - argument_label: args[0].span, - map_label: span, - suggestion: path.ident.span, - replace: "for_each".to_string(), - }, - ) - } + } else if let ty::Closure(id, subs) = arg_ty.kind() { + let cl_ty = subs.as_closure().sig(); + let ret_ty = cl_ty.output().skip_binder(); + if is_unit_type(ret_ty) { + cx.emit_span_lint( + MAP_UNIT_FN, + span, + MappingToUnit { + function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span), + argument_label: args[0].span, + map_label: span, + suggestion: path.ident.span, + replace: "for_each".to_string(), + }, + ) } } } @@ -101,10 +95,10 @@ impl<'tcx> LateLintPass<'tcx> for MapUnitFn { } fn is_impl_slice(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { - if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) { - if let Some(impl_id) = cx.tcx.impl_of_method(method_id) { - return cx.tcx.type_of(impl_id).skip_binder().is_slice(); - } + 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) + { + return cx.tcx.type_of(impl_id).skip_binder().is_slice(); } false } @@ -114,11 +108,11 @@ fn is_unit_type(ty: Ty<'_>) -> bool { } fn is_diagnostic_name(cx: &LateContext<'_>, id: HirId, name: &str) -> bool { - if let Some(def_id) = cx.typeck_results().type_dependent_def_id(id) { - if let Some(item) = cx.tcx.get_diagnostic_name(def_id) { - if item.as_str() == name { - return true; - } + if let Some(def_id) = cx.typeck_results().type_dependent_def_id(id) + && let Some(item) = cx.tcx.get_diagnostic_name(def_id) + { + if item.as_str() == name { + return true; } } false diff --git a/compiler/rustc_lint/src/non_fmt_panic.rs b/compiler/rustc_lint/src/non_fmt_panic.rs index 16c061008085..2eabeeaa88f9 100644 --- a/compiler/rustc_lint/src/non_fmt_panic.rs +++ b/compiler/rustc_lint/src/non_fmt_panic.rs @@ -48,38 +48,38 @@ declare_lint_pass!(NonPanicFmt => [NON_FMT_PANICS]); impl<'tcx> LateLintPass<'tcx> for NonPanicFmt { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { - if let hir::ExprKind::Call(f, [arg]) = &expr.kind { - if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() { - let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id); + if let hir::ExprKind::Call(f, [arg]) = &expr.kind + && let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() + { + let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id); - if cx.tcx.is_lang_item(def_id, LangItem::BeginPanic) - || cx.tcx.is_lang_item(def_id, LangItem::Panic) - || f_diagnostic_name == Some(sym::panic_str_2015) + if cx.tcx.is_lang_item(def_id, LangItem::BeginPanic) + || cx.tcx.is_lang_item(def_id, LangItem::Panic) + || f_diagnostic_name == Some(sym::panic_str_2015) + { + if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id { + if matches!( + cx.tcx.get_diagnostic_name(id), + Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro) + ) { + check_panic(cx, f, arg); + } + } + } else if f_diagnostic_name == Some(sym::unreachable_display) { + if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id + && cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id) { - if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id { - if matches!( - cx.tcx.get_diagnostic_name(id), - Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro) - ) { - check_panic(cx, f, arg); - } - } - } else if f_diagnostic_name == Some(sym::unreachable_display) { - if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id { - if cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id) { - check_panic( - cx, - f, - // This is safe because we checked above that the callee is indeed - // unreachable_display - match &arg.kind { - // Get the borrowed arg not the borrow - hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg, - _ => bug!("call to unreachable_display without borrow"), - }, - ); - } - } + check_panic( + cx, + f, + // This is safe because we checked above that the callee is indeed + // unreachable_display + match &arg.kind { + // Get the borrowed arg not the borrow + hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg, + _ => bug!("call to unreachable_display without borrow"), + }, + ); } } } diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index db89396d1dc2..76e374deef6a 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -623,15 +623,15 @@ impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals { .. }) = p.kind { - if let Res::Def(DefKind::Const, _) = path.res { - if let [segment] = path.segments { - NonUpperCaseGlobals::check_upper_case( - cx, - "constant in pattern", - None, - &segment.ident, - ); - } + if let Res::Def(DefKind::Const, _) = path.res + && let [segment] = path.segments + { + NonUpperCaseGlobals::check_upper_case( + cx, + "constant in pattern", + None, + &segment.ident, + ); } } } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index a9eb1739f7f1..13dd6cb16618 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -562,20 +562,19 @@ declare_lint_pass!(PathStatements => [PATH_STATEMENTS]); impl<'tcx> LateLintPass<'tcx> for PathStatements { fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) { - if let hir::StmtKind::Semi(expr) = s.kind { - if let hir::ExprKind::Path(_) = expr.kind { - let ty = cx.typeck_results().expr_ty(expr); - if ty.needs_drop(cx.tcx, cx.typing_env()) { - let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) - { - PathStatementDropSub::Suggestion { span: s.span, snippet } - } else { - PathStatementDropSub::Help { span: s.span } - }; - cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub }) + if let hir::StmtKind::Semi(expr) = s.kind + && let hir::ExprKind::Path(_) = expr.kind + { + let ty = cx.typeck_results().expr_ty(expr); + if ty.needs_drop(cx.tcx, cx.typing_env()) { + let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) { + PathStatementDropSub::Suggestion { span: s.span, snippet } } else { - cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect); - } + PathStatementDropSub::Help { span: s.span } + }; + cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub }) + } else { + cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect); } } } @@ -1509,21 +1508,19 @@ impl UnusedDelimLint for UnusedBraces { // let _: A<{produces_literal!()}>; // ``` // FIXME(const_generics): handle paths when #67075 is fixed. - if let [stmt] = inner.stmts.as_slice() { - if let ast::StmtKind::Expr(ref expr) = stmt.kind { - if !Self::is_expr_delims_necessary(expr, ctx, followed_by_block) - && (ctx != UnusedDelimsCtx::AnonConst - || (matches!(expr.kind, ast::ExprKind::Lit(_)) - && !expr.span.from_expansion())) - && ctx != UnusedDelimsCtx::ClosureBody - && !cx.sess().source_map().is_multiline(value.span) - && value.attrs.is_empty() - && !value.span.from_expansion() - && !inner.span.from_expansion() - { - self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw) - } - } + if let [stmt] = inner.stmts.as_slice() + && let ast::StmtKind::Expr(ref expr) = stmt.kind + && !Self::is_expr_delims_necessary(expr, ctx, followed_by_block) + && (ctx != UnusedDelimsCtx::AnonConst + || (matches!(expr.kind, ast::ExprKind::Lit(_)) + && !expr.span.from_expansion())) + && ctx != UnusedDelimsCtx::ClosureBody + && !cx.sess().source_map().is_multiline(value.span) + && value.attrs.is_empty() + && !value.span.from_expansion() + && !inner.span.from_expansion() + { + self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw) } } ast::ExprKind::Let(_, ref expr, _, _) => { diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index c30cfd1fcf71..9fef22f9558d 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -370,12 +370,11 @@ impl<'a> CrateLocator<'a> { return self.find_commandline_library(crate_rejections); } let mut seen_paths = FxHashSet::default(); - if let Some(extra_filename) = self.extra_filename { - if let library @ Some(_) = + if let Some(extra_filename) = self.extra_filename + && let library @ Some(_) = self.find_library_crate(crate_rejections, extra_filename, &mut seen_paths)? - { - return Ok(library); - } + { + return Ok(library); } self.find_library_crate(crate_rejections, "", &mut seen_paths) } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 5cd98038fc6d..8a8ce2a789a6 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -2141,10 +2141,10 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { .push((id.owner_id.def_id.local_def_index, simplified_self_ty)); let trait_def = tcx.trait_def(trait_ref.def_id); - if let Ok(mut an) = trait_def.ancestors(tcx, def_id) { - if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) { - self.tables.impl_parent.set_some(def_id.index, parent.into()); - } + if let Ok(mut an) = trait_def.ancestors(tcx, def_id) + && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) + { + self.tables.impl_parent.set_some(def_id.index, parent.into()); } // if this is an impl of `CoerceUnsized`, create its diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index 0f5b63f5c1d2..800c1af660a4 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -175,23 +175,22 @@ impl Scope { return DUMMY_SP; }; let span = tcx.hir_span(hir_id); - if let ScopeData::Remainder(first_statement_index) = self.data { - if let Node::Block(blk) = tcx.hir_node(hir_id) { - // Want span for scope starting after the - // indexed statement and ending at end of - // `blk`; reuse span of `blk` and shift `lo` - // forward to end of indexed statement. - // - // (This is the special case alluded to in the - // doc-comment for this method) + if let ScopeData::Remainder(first_statement_index) = self.data + // Want span for scope starting after the + // indexed statement and ending at end of + // `blk`; reuse span of `blk` and shift `lo` + // forward to end of indexed statement. + // + // (This is the special case alluded to in the + // doc-comment for this method) + && let Node::Block(blk) = tcx.hir_node(hir_id) + { + let stmt_span = blk.stmts[first_statement_index.index()].span; - let stmt_span = blk.stmts[first_statement_index.index()].span; - - // To avoid issues with macro-generated spans, the span - // of the statement must be nested in that of the block. - if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { - return span.with_lo(stmt_span.lo()); - } + // To avoid issues with macro-generated spans, the span + // of the statement must be nested in that of the block. + if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { + return span.with_lo(stmt_span.lo()); } } span diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 275458fc85f8..3bf80d37e656 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -566,10 +566,10 @@ impl<'tcx> AdtDef<'tcx> { let mut prev_discr = None::>; self.variants().iter_enumerated().map(move |(i, v)| { let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx)); - if let VariantDiscr::Explicit(expr_did) = v.discr { - if let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) { - discr = new_discr; - } + if let VariantDiscr::Explicit(expr_did) = v.discr + && let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) + { + discr = new_discr; } prev_discr = Some(discr); diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 809717513c79..a5123576fc64 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -1055,11 +1055,11 @@ where _ => Some(this), }; - if let Some(variant) = data_variant { + if let Some(variant) = data_variant // We're not interested in any unions. - if let FieldsShape::Union(_) = variant.fields { - data_variant = None; - } + && let FieldsShape::Union(_) = variant.fields + { + data_variant = None; } let mut result = None; diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 9ee64df0ad06..d1cc75699d2b 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -225,10 +225,10 @@ impl<'tcx> RegionHighlightMode<'tcx> { region: Option>, number: Option, ) { - if let Some(k) = region { - if let Some(n) = number { - self.highlighting_region(k, n); - } + if let Some(k) = region + && let Some(n) = number + { + self.highlighting_region(k, n); } } diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index e858b629ab14..57ddb8eddb8e 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -76,28 +76,24 @@ impl<'tcx> ThirBuildCx<'tcx> { let mut pattern = self.pattern_from_hir(local.pat); debug!(?pattern); - if let Some(ty) = &local.ty { - if let Some(&user_ty) = + if let Some(ty) = &local.ty + && let Some(&user_ty) = self.typeck_results.user_provided_types().get(ty.hir_id) - { - debug!("mirror_stmts: user_ty={:?}", user_ty); - let annotation = CanonicalUserTypeAnnotation { - user_ty: Box::new(user_ty), - span: ty.span, - inferred_ty: self.typeck_results.node_type(ty.hir_id), - }; - pattern = Box::new(Pat { - ty: pattern.ty, - span: pattern.span, - kind: PatKind::AscribeUserType { - ascription: Ascription { - annotation, - variance: ty::Covariant, - }, - subpattern: pattern, - }, - }); - } + { + debug!("mirror_stmts: user_ty={:?}", user_ty); + let annotation = CanonicalUserTypeAnnotation { + user_ty: Box::new(user_ty), + span: ty.span, + inferred_ty: self.typeck_results.node_type(ty.hir_id), + }; + pattern = Box::new(Pat { + ty: pattern.ty, + span: pattern.span, + kind: PatKind::AscribeUserType { + ascription: Ascription { annotation, variance: ty::Covariant }, + subpattern: pattern, + }, + }); } let span = match local.init { diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index b694409f327b..33bf4e3e29fb 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -105,11 +105,11 @@ impl<'tcx> ThirBuildCx<'tcx> { // // ^ error message points at this expression. // } let mut adjust_span = |expr: &mut Expr<'tcx>| { - if let ExprKind::Block { block } = expr.kind { - if let Some(last_expr) = self.thir[block].expr { - span = self.thir[last_expr].span; - expr.span = span; - } + if let ExprKind::Block { block } = expr.kind + && let Some(last_expr) = self.thir[block].expr + { + span = self.thir[last_expr].span; + expr.span = span; } }; @@ -956,10 +956,10 @@ impl<'tcx> ThirBuildCx<'tcx> { }; fn local(expr: &rustc_hir::Expr<'_>) -> Option { - if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind { - if let Res::Local(hir_id) = path.res { - return Some(hir_id); - } + if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind + && let Res::Local(hir_id) = path.res + { + return Some(hir_id); } None diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 7f47754f6bcd..ae67bb5075e8 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -1155,14 +1155,12 @@ fn find_fallback_pattern_typo<'tcx>( } hir::Node::Block(hir::Block { stmts, .. }) => { for stmt in *stmts { - if let hir::StmtKind::Let(let_stmt) = stmt.kind { - if let hir::PatKind::Binding(_, _, binding_name, _) = + if let hir::StmtKind::Let(let_stmt) = stmt.kind + && let hir::PatKind::Binding(_, _, binding_name, _) = let_stmt.pat.kind - { - if name == binding_name.name { - lint.pattern_let_binding = Some(binding_name.span); - } - } + && name == binding_name.name + { + lint.pattern_let_binding = Some(binding_name.span); } } } diff --git a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs index c9c7fddae5a8..1402a1a8b913 100644 --- a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs +++ b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs @@ -124,10 +124,9 @@ pub fn drop_flag_effects_for_location<'tcx, F>( // Drop does not count as a move but we should still consider the variable uninitialized. if let Some(Terminator { kind: TerminatorKind::Drop { place, .. }, .. }) = body.stmt_at(loc).right() + && let LookupResult::Exact(mpi) = move_data.rev_lookup.find(place.as_ref()) { - if let LookupResult::Exact(mpi) = move_data.rev_lookup.find(place.as_ref()) { - on_all_children_bits(move_data, mpi, |mpi| callback(mpi, DropFlagState::Absent)) - } + on_all_children_bits(move_data, mpi, |mpi| callback(mpi, DropFlagState::Absent)) } debug!("drop_flag_effects: assignment for location({:?})", loc); diff --git a/compiler/rustc_mir_dataflow/src/impls/initialized.rs b/compiler/rustc_mir_dataflow/src/impls/initialized.rs index 085757f0fb6e..117525eb7778 100644 --- a/compiler/rustc_mir_dataflow/src/impls/initialized.rs +++ b/compiler/rustc_mir_dataflow/src/impls/initialized.rs @@ -637,16 +637,13 @@ impl<'tcx> Analysis<'tcx> for EverInitializedPlaces<'_, 'tcx> { debug!("initializes move_indexes {:?}", init_loc_map[location]); state.gen_all(init_loc_map[location].iter().copied()); - if let mir::StatementKind::StorageDead(local) = stmt.kind { + if let mir::StatementKind::StorageDead(local) = stmt.kind // End inits for StorageDead, so that an immutable variable can // be reinitialized on the next iteration of the loop. - if let Some(move_path_index) = rev_lookup.find_local(local) { - debug!( - "clears the ever initialized status of {:?}", - init_path_map[move_path_index] - ); - state.kill_all(init_path_map[move_path_index].iter().copied()); - } + && let Some(move_path_index) = rev_lookup.find_local(local) + { + debug!("clears the ever initialized status of {:?}", init_path_map[move_path_index]); + state.kill_all(init_path_map[move_path_index].iter().copied()); } } diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index 303fc767b9a3..1682f3328574 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -135,12 +135,11 @@ fn value_assigned_to_local<'a, 'tcx>( stmt: &'a mir::Statement<'tcx>, local: Local, ) -> Option<&'a mir::Rvalue<'tcx>> { - if let mir::StatementKind::Assign(box (place, rvalue)) = &stmt.kind { - if let Some(l) = place.as_local() { - if local == l { - return Some(&*rvalue); - } - } + if let mir::StatementKind::Assign(box (place, rvalue)) = &stmt.kind + && let Some(l) = place.as_local() + && local == l + { + return Some(&*rvalue); } None @@ -178,31 +177,30 @@ impl PeekCall { let span = terminator.source_info.span; if let mir::TerminatorKind::Call { func: Operand::Constant(func), args, .. } = &terminator.kind + && let ty::FnDef(def_id, fn_args) = *func.const_.ty().kind() { - if let ty::FnDef(def_id, fn_args) = *func.const_.ty().kind() { - if tcx.intrinsic(def_id)?.name != sym::rustc_peek { - return None; - } + if tcx.intrinsic(def_id)?.name != sym::rustc_peek { + return None; + } - assert_eq!(fn_args.len(), 1); - let kind = PeekCallKind::from_arg_ty(fn_args.type_at(0)); - let arg = match &args[0].node { - Operand::Copy(place) | Operand::Move(place) => { - if let Some(local) = place.as_local() { - local - } else { - tcx.dcx().emit_err(PeekMustBeNotTemporary { span }); - return None; - } - } - _ => { + assert_eq!(fn_args.len(), 1); + let kind = PeekCallKind::from_arg_ty(fn_args.type_at(0)); + let arg = match &args[0].node { + Operand::Copy(place) | Operand::Move(place) => { + if let Some(local) = place.as_local() { + local + } else { tcx.dcx().emit_err(PeekMustBeNotTemporary { span }); return None; } - }; + } + _ => { + tcx.dcx().emit_err(PeekMustBeNotTemporary { span }); + return None; + } + }; - return Some(PeekCall { arg, kind, span }); - } + return Some(PeekCall { arg, kind, span }); } None diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 83fd8ccba60e..005e79731307 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -215,10 +215,10 @@ impl State { // If both places are tracked, we copy the value to the target. // If the target is tracked, but the source is not, we do nothing, as invalidation has // already been performed. - if let Some(target_value) = map.places[target].value_index { - if let Some(source_value) = map.places[source].value_index { - values.insert(target_value, values.get(source_value).clone()); - } + if let Some(target_value) = map.places[target].value_index + && let Some(source_value) = map.places[source].value_index + { + values.insert(target_value, values.get(source_value).clone()); } for target_child in map.children(target) { // Try to find corresponding child and recurse. Reasoning is similar as above. diff --git a/compiler/rustc_mir_transform/src/coroutine/drop.rs b/compiler/rustc_mir_transform/src/coroutine/drop.rs index 406575c4f43f..1a314e029f4a 100644 --- a/compiler/rustc_mir_transform/src/coroutine/drop.rs +++ b/compiler/rustc_mir_transform/src/coroutine/drop.rs @@ -23,10 +23,10 @@ impl<'tcx> MutVisitor<'tcx> for FixReturnPendingVisitor<'tcx> { } // Converting `_0 = Poll::::Pending` to `_0 = Poll::<()>::Pending` - if let Rvalue::Aggregate(kind, _) = rvalue { - if let AggregateKind::Adt(_, _, ref mut args, _, _) = **kind { - *args = self.tcx.mk_args(&[self.tcx.types.unit.into()]); - } + if let Rvalue::Aggregate(kind, _) = rvalue + && let AggregateKind::Adt(_, _, ref mut args, _, _) = **kind + { + *args = self.tcx.mk_args(&[self.tcx.types.unit.into()]); } } } From b8eb046e6ee3294969bf8faf31da226b0ea29d18 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sat, 26 Jul 2025 06:22:20 +0500 Subject: [PATCH 208/809] use let chains in mir, resolve, target --- .../rustc_mir_transform/src/promote_consts.rs | 19 +- .../src/remove_noop_landing_pads.rs | 15 +- compiler/rustc_mir_transform/src/validate.rs | 17 +- .../rustc_monomorphize/src/partitioning.rs | 9 +- compiler/rustc_parse/src/parser/item.rs | 50 +++-- compiler/rustc_passes/src/reachable.rs | 8 +- compiler/rustc_passes/src/stability.rs | 16 +- compiler/rustc_passes/src/upvars.rs | 26 +-- compiler/rustc_privacy/src/lib.rs | 11 +- .../rustc_query_system/src/dep_graph/graph.rs | 12 +- compiler/rustc_query_system/src/query/job.rs | 8 +- .../rustc_resolve/src/late/diagnostics.rs | 204 +++++++++--------- compiler/rustc_resolve/src/macros.rs | 61 +++--- compiler/rustc_session/src/parse.rs | 8 +- compiler/rustc_session/src/session.rs | 10 +- compiler/rustc_span/src/source_map.rs | 8 +- .../rustc_target/src/callconv/loongarch.rs | 19 +- compiler/rustc_target/src/callconv/mips64.rs | 30 ++- compiler/rustc_target/src/callconv/mod.rs | 22 +- compiler/rustc_target/src/callconv/riscv.rs | 18 +- .../trait_impl_difference.rs | 5 +- .../src/error_reporting/infer/suggest.rs | 163 +++++++------- .../traits/on_unimplemented.rs | 18 +- .../src/error_reporting/traits/suggestions.rs | 36 ++-- .../src/traits/coherence.rs | 15 +- .../src/traits/select/mod.rs | 37 ++-- compiler/rustc_ty_utils/src/abi.rs | 10 +- compiler/rustc_ty_utils/src/ty.rs | 8 +- 28 files changed, 415 insertions(+), 448 deletions(-) diff --git a/compiler/rustc_mir_transform/src/promote_consts.rs b/compiler/rustc_mir_transform/src/promote_consts.rs index 4e8f30e077b0..462ddfa3dd3c 100644 --- a/compiler/rustc_mir_transform/src/promote_consts.rs +++ b/compiler/rustc_mir_transform/src/promote_consts.rs @@ -997,12 +997,11 @@ fn promote_candidates<'tcx>( for candidate in candidates.into_iter().rev() { let Location { block, statement_index } = candidate.location; if let StatementKind::Assign(box (place, _)) = &body[block].statements[statement_index].kind + && let Some(local) = place.as_local() { - if let Some(local) = place.as_local() { - if temps[local] == TempState::PromotedOut { - // Already promoted. - continue; - } + if temps[local] == TempState::PromotedOut { + // Already promoted. + continue; } } @@ -1066,11 +1065,11 @@ fn promote_candidates<'tcx>( _ => true, }); let terminator = block.terminator_mut(); - if let TerminatorKind::Drop { place, target, .. } = &terminator.kind { - if let Some(index) = place.as_local() { - if promoted(index) { - terminator.kind = TerminatorKind::Goto { target: *target }; - } + if let TerminatorKind::Drop { place, target, .. } = &terminator.kind + && let Some(index) = place.as_local() + { + if promoted(index) { + terminator.kind = TerminatorKind::Goto { target: *target }; } } } diff --git a/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs b/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs index 797056ad52d4..5b6d7ffb5110 100644 --- a/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs +++ b/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs @@ -48,14 +48,13 @@ impl<'tcx> crate::MirPass<'tcx> for RemoveNoopLandingPads { let postorder: Vec<_> = traversal::postorder(body).map(|(bb, _)| bb).collect(); for bb in postorder { debug!(" processing {:?}", bb); - if let Some(unwind) = body[bb].terminator_mut().unwind_mut() { - if let UnwindAction::Cleanup(unwind_bb) = *unwind { - if nop_landing_pads.contains(unwind_bb) { - debug!(" removing noop landing pad"); - landing_pads_removed += 1; - *unwind = UnwindAction::Continue; - } - } + if let Some(unwind) = body[bb].terminator_mut().unwind_mut() + && let UnwindAction::Cleanup(unwind_bb) = *unwind + && nop_landing_pads.contains(unwind_bb) + { + debug!(" removing noop landing pad"); + landing_pads_removed += 1; + *unwind = UnwindAction::Continue; } body[bb].terminator_mut().successors_mut(|target| { diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index 5860072d541f..98d12bf0a38b 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -80,15 +80,14 @@ impl<'tcx> crate::MirPass<'tcx> for Validator { cfg_checker.fail(location, msg); } - if let MirPhase::Runtime(_) = body.phase { - if let ty::InstanceKind::Item(_) = body.source.instance { - if body.has_free_regions() { - cfg_checker.fail( - Location::START, - format!("Free regions in optimized {} MIR", body.phase.name()), - ); - } - } + if let MirPhase::Runtime(_) = body.phase + && let ty::InstanceKind::Item(_) = body.source.instance + && body.has_free_regions() + { + cfg_checker.fail( + Location::START, + format!("Free regions in optimized {} MIR", body.phase.name()), + ); } } diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index ca8228de57e8..f3e7d582781d 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -1178,12 +1178,11 @@ fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> MonoItemPartitio let autodiff_items = tcx.arena.alloc_from_iter(autodiff_items); // Output monomorphization stats per def_id - if let SwitchWithOptPath::Enabled(ref path) = tcx.sess.opts.unstable_opts.dump_mono_stats { - if let Err(err) = + if let SwitchWithOptPath::Enabled(ref path) = tcx.sess.opts.unstable_opts.dump_mono_stats + && let Err(err) = dump_mono_items_stats(tcx, codegen_units, path, tcx.crate_name(LOCAL_CRATE)) - { - tcx.dcx().emit_fatal(CouldntDumpMonoStats { error: err.to_string() }); - } + { + tcx.dcx().emit_fatal(CouldntDumpMonoStats { error: err.to_string() }); } if tcx.sess.opts.unstable_opts.print_mono_items { diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index b767b0fcf994..65d84b3e3d9d 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -1973,21 +1973,21 @@ impl<'a> Parser<'a> { format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)); // Try to recover extra trailing angle brackets - if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind { - if let Some(last_segment) = segments.last() { - let guar = self.check_trailing_angle_brackets( - last_segment, - &[exp!(Comma), exp!(CloseBrace)], - ); - if let Some(_guar) = guar { - // Handle a case like `Vec>,` where we can continue parsing fields - // after the comma - let _ = self.eat(exp!(Comma)); + if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind + && let Some(last_segment) = segments.last() + { + let guar = self.check_trailing_angle_brackets( + last_segment, + &[exp!(Comma), exp!(CloseBrace)], + ); + if let Some(_guar) = guar { + // Handle a case like `Vec>,` where we can continue parsing fields + // after the comma + let _ = self.eat(exp!(Comma)); - // `check_trailing_angle_brackets` already emitted a nicer error, as - // proven by the presence of `_guar`. We can continue parsing. - return Ok(a_var); - } + // `check_trailing_angle_brackets` already emitted a nicer error, as + // proven by the presence of `_guar`. We can continue parsing. + return Ok(a_var); } } @@ -3034,18 +3034,16 @@ impl<'a> Parser<'a> { if let Ok(t) = &ty { // Check for trailing angle brackets - if let TyKind::Path(_, Path { segments, .. }) = &t.kind { - if let Some(segment) = segments.last() { - if let Some(guar) = - this.check_trailing_angle_brackets(segment, &[exp!(CloseParen)]) - { - return Ok(( - dummy_arg(segment.ident, guar), - Trailing::No, - UsePreAttrPos::No, - )); - } - } + if let TyKind::Path(_, Path { segments, .. }) = &t.kind + && let Some(segment) = segments.last() + && let Some(guar) = + this.check_trailing_angle_brackets(segment, &[exp!(CloseParen)]) + { + return Ok(( + dummy_arg(segment.ident, guar), + Trailing::No, + UsePreAttrPos::No, + )); } if this.token != token::Comma && this.token != token::CloseParen { diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index b49e8118fe37..2f78c22c7483 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -104,10 +104,10 @@ impl<'tcx> Visitor<'tcx> for ReachableContext<'tcx> { fn visit_inline_asm(&mut self, asm: &'tcx hir::InlineAsm<'tcx>, id: hir::HirId) { for (op, _) in asm.operands { - if let hir::InlineAsmOperand::SymStatic { def_id, .. } = op { - if let Some(def_id) = def_id.as_local() { - self.reachable_symbols.insert(def_id); - } + if let hir::InlineAsmOperand::SymStatic { def_id, .. } = op + && let Some(def_id) = def_id.as_local() + { + self.reachable_symbols.insert(def_id); } } intravisit::walk_inline_asm(self, asm, id); diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 40999d622dc0..9ed7293873f5 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -929,10 +929,10 @@ struct CheckTraitImplStable<'tcx> { impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> { fn visit_path(&mut self, path: &hir::Path<'tcx>, _id: hir::HirId) { - if let Some(def_id) = path.res.opt_def_id() { - if let Some(stab) = self.tcx.lookup_stability(def_id) { - self.fully_stable &= stab.level.is_stable(); - } + if let Some(def_id) = path.res.opt_def_id() + && let Some(stab) = self.tcx.lookup_stability(def_id) + { + self.fully_stable &= stab.level.is_stable(); } intravisit::walk_path(self, path) } @@ -1055,10 +1055,10 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { // implications from this crate. remaining_implications.remove(&feature); - if let FeatureStability::Unstable { old_name: Some(alias) } = stability { - if let Some(span) = remaining_lib_features.swap_remove(&alias) { - tcx.dcx().emit_err(errors::RenamedFeature { span, feature, alias }); - } + if let FeatureStability::Unstable { old_name: Some(alias) } = stability + && let Some(span) = remaining_lib_features.swap_remove(&alias) + { + tcx.dcx().emit_err(errors::RenamedFeature { span, feature, alias }); } if remaining_lib_features.is_empty() && remaining_implications.is_empty() { diff --git a/compiler/rustc_passes/src/upvars.rs b/compiler/rustc_passes/src/upvars.rs index fae88fbba360..88f202919bb5 100644 --- a/compiler/rustc_passes/src/upvars.rs +++ b/compiler/rustc_passes/src/upvars.rs @@ -75,19 +75,19 @@ impl<'tcx> Visitor<'tcx> for CaptureCollector<'_, 'tcx> { } fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { - if let hir::ExprKind::Closure(closure) = expr.kind { - if let Some(upvars) = self.tcx.upvars_mentioned(closure.def_id) { - // Every capture of a closure expression is a local in scope, - // that is moved/copied/borrowed into the closure value, and - // for this analysis they are like any other access to a local. - // - // E.g. in `|b| |c| (a, b, c)`, the upvars of the inner closure - // are `a` and `b`, and while `a` is not directly used in the - // outer closure, it needs to be an upvar there too, so that - // the inner closure can take it (from the outer closure's env). - for (&var_id, upvar) in upvars { - self.visit_local_use(var_id, upvar.span); - } + if let hir::ExprKind::Closure(closure) = expr.kind + && let Some(upvars) = self.tcx.upvars_mentioned(closure.def_id) + { + // Every capture of a closure expression is a local in scope, + // that is moved/copied/borrowed into the closure value, and + // for this analysis they are like any other access to a local. + // + // E.g. in `|b| |c| (a, b, c)`, the upvars of the inner closure + // are `a` and `b`, and while `a` is not directly used in the + // outer closure, it needs to be an upvar there too, so that + // the inner closure can take it (from the outer closure's env). + for (&var_id, upvar) in upvars { + self.visit_local_use(var_id, upvar.span); } } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 6fd2b7fc12f0..b4fa11a8eb37 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -204,12 +204,10 @@ where // Something like `fn() {my_method}` type of the method // `impl Pub { pub fn my_method() {} }` is considered a private type, // so we need to visit the self type additionally. - if let Some(assoc_item) = tcx.opt_associated_item(def_id) { - if let Some(impl_def_id) = assoc_item.impl_container(tcx) { - try_visit!( - tcx.type_of(impl_def_id).instantiate_identity().visit_with(self) - ); - } + if let Some(assoc_item) = tcx.opt_associated_item(def_id) + && let Some(impl_def_id) = assoc_item.impl_container(tcx) + { + try_visit!(tcx.type_of(impl_def_id).instantiate_identity().visit_with(self)); } } ty::Alias(kind @ (ty::Inherent | ty::Free | ty::Projection), data) => { @@ -734,6 +732,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { if let Some(ctor_def_id) = variant.data.ctor_def_id() { self.update(ctor_def_id, variant_ev, Level::Reachable); } + for field in variant.data.fields() { self.update(field.def_id, variant_ev, Level::Reachable); self.reach(field.def_id, variant_ev).ty(); diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 04fc32a9b500..7e258aaa54f7 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -498,12 +498,12 @@ impl DepGraph { #[cfg(debug_assertions)] { - if let Some(target) = task_deps.node { - if let Some(ref forbidden_edge) = data.current.forbidden_edge { - let src = forbidden_edge.index_to_node.lock()[&dep_node_index]; - if forbidden_edge.test(&src, &target) { - panic!("forbidden edge {:?} -> {:?} created", src, target) - } + if let Some(target) = task_deps.node + && let Some(ref forbidden_edge) = data.current.forbidden_edge + { + let src = forbidden_edge.index_to_node.lock()[&dep_node_index]; + if forbidden_edge.test(&src, &target) { + panic!("forbidden edge {:?} -> {:?} created", src, target) } } } diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 7e61f5026da4..fd1ea997ebe5 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -289,10 +289,10 @@ where F: FnMut(Span, QueryJobId) -> Option>, { // Visit the parent query which is a non-resumable waiter since it's on the same stack - if let Some(parent) = query.parent(query_map) { - if let Some(cycle) = visit(query.span(query_map), parent) { - return Some(cycle); - } + if let Some(parent) = query.parent(query_map) + && let Some(cycle) = visit(query.span(query_map), parent) + { + return Some(cycle); } // Visit the explicit waiters which use condvars and are resumable diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 69095942f524..1f78b65d07dd 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -818,10 +818,10 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { // If the first argument in call is `self` suggest calling a method. if let Some((call_span, args_span)) = self.call_has_self_arg(source) { let mut args_snippet = String::new(); - if let Some(args_span) = args_span { - if let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span) { - args_snippet = snippet; - } + if let Some(args_span) = args_span + && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span) + { + args_snippet = snippet; } err.span_suggestion( @@ -955,59 +955,57 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)), false, ) = (source, res, is_macro) - { - if let Some(bounds @ [first_bound, .., last_bound]) = + && let Some(bounds @ [first_bound, .., last_bound]) = self.diag_metadata.current_trait_object - { - fallback = true; - let spans: Vec = bounds - .iter() - .map(|bound| bound.span()) - .filter(|&sp| sp != base_error.span) - .collect(); + { + fallback = true; + let spans: Vec = bounds + .iter() + .map(|bound| bound.span()) + .filter(|&sp| sp != base_error.span) + .collect(); - let start_span = first_bound.span(); - // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><) - let end_span = last_bound.span(); - // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar) - let last_bound_span = spans.last().cloned().unwrap(); - let mut multi_span: MultiSpan = spans.clone().into(); - for sp in spans { - let msg = if sp == last_bound_span { - format!( - "...because of {these} bound{s}", - these = pluralize!("this", bounds.len() - 1), - s = pluralize!(bounds.len() - 1), - ) - } else { - String::new() - }; - multi_span.push_span_label(sp, msg); - } - multi_span.push_span_label(base_error.span, "expected this type to be a trait..."); - err.span_help( - multi_span, - "`+` is used to constrain a \"trait object\" type with lifetimes or \ + let start_span = first_bound.span(); + // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><) + let end_span = last_bound.span(); + // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar) + let last_bound_span = spans.last().cloned().unwrap(); + let mut multi_span: MultiSpan = spans.clone().into(); + for sp in spans { + let msg = if sp == last_bound_span { + format!( + "...because of {these} bound{s}", + these = pluralize!("this", bounds.len() - 1), + s = pluralize!(bounds.len() - 1), + ) + } else { + String::new() + }; + multi_span.push_span_label(sp, msg); + } + multi_span.push_span_label(base_error.span, "expected this type to be a trait..."); + err.span_help( + multi_span, + "`+` is used to constrain a \"trait object\" type with lifetimes or \ auto-traits; structs and enums can't be bound in that way", - ); - if bounds.iter().all(|bound| match bound { - ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true, - ast::GenericBound::Trait(tr) => tr.span == base_error.span, - }) { - let mut sugg = vec![]; - if base_error.span != start_span { - sugg.push((start_span.until(base_error.span), String::new())); - } - if base_error.span != end_span { - sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new())); - } - - err.multipart_suggestion( - "if you meant to use a type and not a trait here, remove the bounds", - sugg, - Applicability::MaybeIncorrect, - ); + ); + if bounds.iter().all(|bound| match bound { + ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true, + ast::GenericBound::Trait(tr) => tr.span == base_error.span, + }) { + let mut sugg = vec![]; + if base_error.span != start_span { + sugg.push((start_span.until(base_error.span), String::new())); } + if base_error.span != end_span { + sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new())); + } + + err.multipart_suggestion( + "if you meant to use a type and not a trait here, remove the bounds", + sugg, + Applicability::MaybeIncorrect, + ); } } @@ -1151,13 +1149,13 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { } err.code(E0411); err.span_label(span, "`Self` is only available in impls, traits, and type definitions"); - if let Some(item) = self.diag_metadata.current_item { - if let Some(ident) = item.kind.ident() { - err.span_label( - ident.span, - format!("`Self` not allowed in {} {}", item.kind.article(), item.kind.descr()), - ); - } + if let Some(item) = self.diag_metadata.current_item + && let Some(ident) = item.kind.ident() + { + err.span_label( + ident.span, + format!("`Self` not allowed in {} {}", item.kind.article(), item.kind.descr()), + ); } true } @@ -1932,11 +1930,11 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { }; let (ctor_def, ctor_vis, fields) = if let Some(struct_ctor) = struct_ctor { - if let PathSource::Expr(Some(parent)) = source { - if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind { - bad_struct_syntax_suggestion(self, err, def_id); - return true; - } + if let PathSource::Expr(Some(parent)) = source + && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind + { + bad_struct_syntax_suggestion(self, err, def_id); + return true; } struct_ctor } else { @@ -2344,19 +2342,13 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) { if let Some(node_id) = self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id) + && let Some(resolution) = self.r.partial_res_map.get(&node_id) + && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res() + && let Some(fields) = self.r.field_idents(did) + && let Some(field) = fields.iter().find(|id| ident.name == id.name) { // Look for a field with the same name in the current self_type. - if let Some(resolution) = self.r.partial_res_map.get(&node_id) { - if let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = - resolution.full_res() - { - if let Some(fields) = self.r.field_idents(did) { - if let Some(field) = fields.iter().find(|id| ident.name == id.name) { - return Some(AssocSuggestion::Field(field.span)); - } - } - } - } + return Some(AssocSuggestion::Field(field.span)); } } @@ -2391,44 +2383,44 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { } // Look for associated items in the current trait. - if let Some((module, _)) = self.current_trait_ref { - if let Ok(binding) = self.r.maybe_resolve_ident_in_module( + if let Some((module, _)) = self.current_trait_ref + && let Ok(binding) = self.r.maybe_resolve_ident_in_module( ModuleOrUniformRoot::Module(module), ident, ns, &self.parent_scope, None, - ) { - let res = binding.res(); - if filter_fn(res) { - match res { - Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => { - let has_self = match def_id.as_local() { - Some(def_id) => self - .r - .delegation_fn_sigs - .get(&def_id) - .is_some_and(|sig| sig.has_self), - None => { - self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| { - matches!(ident, Some(Ident { name: kw::SelfLower, .. })) - }) - } - }; - if has_self { - return Some(AssocSuggestion::MethodWithSelf { called }); - } else { - return Some(AssocSuggestion::AssocFn { called }); + ) + { + let res = binding.res(); + if filter_fn(res) { + match res { + Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => { + let has_self = match def_id.as_local() { + Some(def_id) => self + .r + .delegation_fn_sigs + .get(&def_id) + .is_some_and(|sig| sig.has_self), + None => { + self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| { + matches!(ident, Some(Ident { name: kw::SelfLower, .. })) + }) } + }; + if has_self { + return Some(AssocSuggestion::MethodWithSelf { called }); + } else { + return Some(AssocSuggestion::AssocFn { called }); } - Res::Def(DefKind::AssocConst, _) => { - return Some(AssocSuggestion::AssocConst); - } - Res::Def(DefKind::AssocTy, _) => { - return Some(AssocSuggestion::AssocType); - } - _ => {} } + Res::Def(DefKind::AssocConst, _) => { + return Some(AssocSuggestion::AssocConst); + } + Res::Def(DefKind::AssocTy, _) => { + return Some(AssocSuggestion::AssocType); + } + _ => {} } } } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index f0225daa09db..1a7a8afe22dd 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -1023,40 +1023,39 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { node_id: NodeId, ) { let span = path.span; - if let Some(stability) = &ext.stability { - if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. } = + if let Some(stability) = &ext.stability + && let StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. } = stability.level - { - let feature = stability.feature; + { + let feature = stability.feature; - let is_allowed = - |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature); - let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature)); - if !is_allowed(feature) && !allowed_by_implication { - let lint_buffer = &mut self.lint_buffer; - let soft_handler = |lint, span, msg: String| { - lint_buffer.buffer_lint( - lint, - node_id, - span, - BuiltinLintDiag::UnstableFeature( - // FIXME make this translatable - msg.into(), - ), - ) - }; - stability::report_unstable( - self.tcx.sess, - feature, - reason.to_opt_reason(), - issue, - None, - is_soft, + let is_allowed = + |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature); + let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature)); + if !is_allowed(feature) && !allowed_by_implication { + let lint_buffer = &mut self.lint_buffer; + let soft_handler = |lint, span, msg: String| { + lint_buffer.buffer_lint( + lint, + node_id, span, - soft_handler, - stability::UnstableKind::Regular, - ); - } + BuiltinLintDiag::UnstableFeature( + // FIXME make this translatable + msg.into(), + ), + ) + }; + stability::report_unstable( + self.tcx.sess, + feature, + reason.to_opt_reason(), + issue, + None, + is_soft, + span, + soft_handler, + stability::UnstableKind::Regular, + ); } } if let Some(depr) = &ext.deprecation { diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 9097b27b86c4..426480f0dbab 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -107,10 +107,10 @@ pub fn feature_err_issue( let span = span.into(); // Cancel an earlier warning for this same error, if it exists. - if let Some(span) = span.primary_span() { - if let Some(err) = sess.dcx().steal_non_err(span, StashKey::EarlySyntaxWarning) { - err.cancel() - } + if let Some(span) = span.primary_span() + && let Some(err) = sess.dcx().steal_non_err(span, StashKey::EarlySyntaxWarning) + { + err.cancel() } let mut err = sess.dcx().create_err(FeatureGateError { span, explain: explain.into() }); diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 85bd8340c3cc..da00ccf0f71d 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1362,11 +1362,11 @@ fn validate_commandline_args_with_session_available(sess: &Session) { sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() }); } - if let Some(flavor) = sess.opts.cg.linker_flavor { - if let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor) { - let flavor = flavor.desc(); - sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list }); - } + if let Some(flavor) = sess.opts.cg.linker_flavor + && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor) + { + let flavor = flavor.desc(); + sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list }); } if sess.opts.unstable_opts.function_return != FunctionReturn::default() { diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 8a3644163caf..d93151497986 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -826,10 +826,10 @@ impl SourceMap { /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char` /// `c`. pub fn span_through_char(&self, sp: Span, c: char) -> Span { - if let Ok(snippet) = self.span_to_snippet(sp) { - if let Some(offset) = snippet.find(c) { - return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32)); - } + if let Ok(snippet) = self.span_to_snippet(sp) + && let Some(offset) = snippet.find(c) + { + return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32)); } sp } diff --git a/compiler/rustc_target/src/callconv/loongarch.rs b/compiler/rustc_target/src/callconv/loongarch.rs index 27b41cc09ed0..d567ad401bb1 100644 --- a/compiler/rustc_target/src/callconv/loongarch.rs +++ b/compiler/rustc_target/src/callconv/loongarch.rs @@ -314,16 +314,15 @@ fn classify_arg<'a, Ty, C>( } fn extend_integer_width(arg: &mut ArgAbi<'_, Ty>, xlen: u64) { - if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr { - if let Primitive::Int(i, _) = scalar.primitive() { - // 32-bit integers are always sign-extended - if i.size().bits() == 32 && xlen > 32 { - if let PassMode::Direct(ref mut attrs) = arg.mode { - attrs.ext(ArgExtension::Sext); - return; - } - } - } + if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr + && let Primitive::Int(i, _) = scalar.primitive() + && i.size().bits() == 32 + && xlen > 32 + && let PassMode::Direct(ref mut attrs) = arg.mode + { + // 32-bit integers are always sign-extended + attrs.ext(ArgExtension::Sext); + return; } arg.extend_integer_width_to(xlen); diff --git a/compiler/rustc_target/src/callconv/mips64.rs b/compiler/rustc_target/src/callconv/mips64.rs index 77c0cf06fc16..0209838bec18 100644 --- a/compiler/rustc_target/src/callconv/mips64.rs +++ b/compiler/rustc_target/src/callconv/mips64.rs @@ -6,15 +6,14 @@ use crate::callconv::{ArgAbi, ArgExtension, CastTarget, FnAbi, PassMode, Uniform fn extend_integer_width_mips(arg: &mut ArgAbi<'_, Ty>, bits: u64) { // Always sign extend u32 values on 64-bit mips - if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr { - if let Primitive::Int(i, signed) = scalar.primitive() { - if !signed && i.size().bits() == 32 { - if let PassMode::Direct(ref mut attrs) = arg.mode { - attrs.ext(ArgExtension::Sext); - return; - } - } - } + if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr + && let Primitive::Int(i, signed) = scalar.primitive() + && !signed + && i.size().bits() == 32 + && let PassMode::Direct(ref mut attrs) = arg.mode + { + attrs.ext(ArgExtension::Sext); + return; } arg.extend_integer_width_to(bits); @@ -58,13 +57,12 @@ where ret.cast_to(reg); return; } - } else if ret.layout.fields.count() == 2 { - if let Some(reg0) = float_reg(cx, ret, 0) { - if let Some(reg1) = float_reg(cx, ret, 1) { - ret.cast_to(CastTarget::pair(reg0, reg1)); - return; - } - } + } else if ret.layout.fields.count() == 2 + && let Some(reg0) = float_reg(cx, ret, 0) + && let Some(reg1) = float_reg(cx, ret, 1) + { + ret.cast_to(CastTarget::pair(reg0, reg1)); + return; } } diff --git a/compiler/rustc_target/src/callconv/mod.rs b/compiler/rustc_target/src/callconv/mod.rs index ab3271220eb4..63e56744aec9 100644 --- a/compiler/rustc_target/src/callconv/mod.rs +++ b/compiler/rustc_target/src/callconv/mod.rs @@ -495,18 +495,16 @@ impl<'a, Ty> ArgAbi<'a, Ty> { pub fn extend_integer_width_to(&mut self, bits: u64) { // Only integers have signedness - if let BackendRepr::Scalar(scalar) = self.layout.backend_repr { - if let Primitive::Int(i, signed) = scalar.primitive() { - if i.size().bits() < bits { - if let PassMode::Direct(ref mut attrs) = self.mode { - if signed { - attrs.ext(ArgExtension::Sext) - } else { - attrs.ext(ArgExtension::Zext) - }; - } - } - } + if let BackendRepr::Scalar(scalar) = self.layout.backend_repr + && let Primitive::Int(i, signed) = scalar.primitive() + && i.size().bits() < bits + && let PassMode::Direct(ref mut attrs) = self.mode + { + if signed { + attrs.ext(ArgExtension::Sext) + } else { + attrs.ext(ArgExtension::Zext) + }; } } diff --git a/compiler/rustc_target/src/callconv/riscv.rs b/compiler/rustc_target/src/callconv/riscv.rs index a06f54d60e7b..161e2c1645f9 100644 --- a/compiler/rustc_target/src/callconv/riscv.rs +++ b/compiler/rustc_target/src/callconv/riscv.rs @@ -393,16 +393,14 @@ fn classify_arg<'a, Ty, C>( } fn extend_integer_width(arg: &mut ArgAbi<'_, Ty>, xlen: u64) { - if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr { - if let Primitive::Int(i, _) = scalar.primitive() { - // 32-bit integers are always sign-extended - if i.size().bits() == 32 && xlen > 32 { - if let PassMode::Direct(ref mut attrs) = arg.mode { - attrs.ext(ArgExtension::Sext); - return; - } - } - } + if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr + && let Primitive::Int(i, _) = scalar.primitive() + && i.size().bits() == 32 + && xlen > 32 + && let PassMode::Direct(ref mut attrs) = arg.mode + { + attrs.ext(ArgExtension::Sext); + return; } arg.extend_integer_width_to(xlen); diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs index 772a7f013323..2a3268d3339e 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs @@ -104,10 +104,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { ty::AssocKind::Fn { .. } => { if let Some(hir_id) = assoc_item.def_id.as_local().map(|id| self.tcx().local_def_id_to_hir_id(id)) + && let Some(decl) = self.tcx().hir_fn_decl_by_hir_id(hir_id) { - if let Some(decl) = self.tcx().hir_fn_decl_by_hir_id(hir_id) { - visitor.visit_fn_decl(decl); - } + visitor.visit_fn_decl(decl); } } _ => {} diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs index c0daf08ce079..44baa213b284 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs @@ -91,51 +91,51 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { ) { // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with // some modifications due to that being in typeck and this being in infer. - if let ObligationCauseCode::Pattern { .. } = cause.code() { - if let ty::Adt(expected_adt, args) = exp_found.expected.kind() { - let compatible_variants: Vec<_> = expected_adt - .variants() - .iter() - .filter(|variant| { - variant.fields.len() == 1 && variant.ctor_kind() == Some(CtorKind::Fn) - }) - .filter_map(|variant| { - let sole_field = &variant.single_field(); - let sole_field_ty = sole_field.ty(self.tcx, args); - if self.same_type_modulo_infer(sole_field_ty, exp_found.found) { - let variant_path = - with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id)); - // FIXME #56861: DRYer prelude filtering - if let Some(path) = variant_path.strip_prefix("std::prelude::") { - if let Some((_, path)) = path.split_once("::") { - return Some(path.to_string()); - } - } - Some(variant_path) - } else { - None + if let ObligationCauseCode::Pattern { .. } = cause.code() + && let ty::Adt(expected_adt, args) = exp_found.expected.kind() + { + let compatible_variants: Vec<_> = expected_adt + .variants() + .iter() + .filter(|variant| { + variant.fields.len() == 1 && variant.ctor_kind() == Some(CtorKind::Fn) + }) + .filter_map(|variant| { + let sole_field = &variant.single_field(); + let sole_field_ty = sole_field.ty(self.tcx, args); + if self.same_type_modulo_infer(sole_field_ty, exp_found.found) { + let variant_path = + with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id)); + // FIXME #56861: DRYer prelude filtering + if let Some(path) = variant_path.strip_prefix("std::prelude::") + && let Some((_, path)) = path.split_once("::") + { + return Some(path.to_string()); } - }) - .collect(); - match &compatible_variants[..] { - [] => {} - [variant] => { - let sugg = SuggestTuplePatternOne { - variant: variant.to_owned(), - span_low: cause.span.shrink_to_lo(), - span_high: cause.span.shrink_to_hi(), - }; - diag.subdiagnostic(sugg); - } - _ => { - // More than one matching variant. - let sugg = SuggestTuplePatternMany { - path: self.tcx.def_path_str(expected_adt.did()), - cause_span: cause.span, - compatible_variants, - }; - diag.subdiagnostic(sugg); + Some(variant_path) + } else { + None } + }) + .collect(); + match &compatible_variants[..] { + [] => {} + [variant] => { + let sugg = SuggestTuplePatternOne { + variant: variant.to_owned(), + span_low: cause.span.shrink_to_lo(), + span_high: cause.span.shrink_to_hi(), + }; + diag.subdiagnostic(sugg); + } + _ => { + // More than one matching variant. + let sugg = SuggestTuplePatternMany { + path: self.tcx.def_path_str(expected_adt.did()), + cause_span: cause.span, + compatible_variants, + }; + diag.subdiagnostic(sugg); } } } @@ -288,19 +288,17 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { .filter(|field| field.vis.is_accessible_from(field.did, self.tcx)) .map(|field| (field.name, field.ty(self.tcx, expected_args))) .find(|(_, ty)| self.same_type_modulo_infer(*ty, exp_found.found)) + && let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() + && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { - if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() { - if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { - let suggestion = if expected_def.is_struct() { - SuggestAccessingField::Safe { span, snippet, name, ty } - } else if expected_def.is_union() { - SuggestAccessingField::Unsafe { span, snippet, name, ty } - } else { - return; - }; - diag.subdiagnostic(suggestion); - } - } + let suggestion = if expected_def.is_struct() { + SuggestAccessingField::Safe { span, snippet, name, ty } + } else if expected_def.is_union() { + SuggestAccessingField::Unsafe { span, snippet, name, ty } + } else { + return; + }; + diag.subdiagnostic(suggestion); } } } @@ -540,38 +538,35 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { ) -> Option { if let (ty::Adt(exp_def, exp_args), ty::Ref(_, found_ty, _)) = (expected.kind(), found.kind()) + && let ty::Adt(found_def, found_args) = *found_ty.kind() { - if let ty::Adt(found_def, found_args) = *found_ty.kind() { - if exp_def == &found_def { - let have_as_ref = &[ - (sym::Option, SuggestAsRefKind::Option), - (sym::Result, SuggestAsRefKind::Result), - ]; - if let Some(msg) = have_as_ref.iter().find_map(|(name, msg)| { - self.tcx.is_diagnostic_item(*name, exp_def.did()).then_some(msg) - }) { - let mut show_suggestion = true; - for (exp_ty, found_ty) in - std::iter::zip(exp_args.types(), found_args.types()) - { - match *exp_ty.kind() { - ty::Ref(_, exp_ty, _) => { - match (exp_ty.kind(), found_ty.kind()) { - (_, ty::Param(_)) - | (_, ty::Infer(_)) - | (ty::Param(_), _) - | (ty::Infer(_), _) => {} - _ if self.same_type_modulo_infer(exp_ty, found_ty) => {} - _ => show_suggestion = false, - }; - } - ty::Param(_) | ty::Infer(_) => {} - _ => show_suggestion = false, + if exp_def == &found_def { + let have_as_ref = &[ + (sym::Option, SuggestAsRefKind::Option), + (sym::Result, SuggestAsRefKind::Result), + ]; + if let Some(msg) = have_as_ref.iter().find_map(|(name, msg)| { + self.tcx.is_diagnostic_item(*name, exp_def.did()).then_some(msg) + }) { + let mut show_suggestion = true; + for (exp_ty, found_ty) in std::iter::zip(exp_args.types(), found_args.types()) { + match *exp_ty.kind() { + ty::Ref(_, exp_ty, _) => { + match (exp_ty.kind(), found_ty.kind()) { + (_, ty::Param(_)) + | (_, ty::Infer(_)) + | (ty::Param(_), _) + | (ty::Infer(_), _) => {} + _ if self.same_type_modulo_infer(exp_ty, found_ty) => {} + _ => show_suggestion = false, + }; } + ty::Param(_) | ty::Infer(_) => {} + _ => show_suggestion = false, } - if show_suggestion { - return Some(*msg); - } + } + if show_suggestion { + return Some(*msg); } } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index 2344bc79f213..5765dfd891d4 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -381,15 +381,15 @@ impl IgnoredDiagnosticOption { old: Option, option_name: &'static str, ) { - if let (Some(new_item), Some(old_item)) = (new, old) { - if let Some(item_def_id) = item_def_id.as_local() { - tcx.emit_node_span_lint( - MALFORMED_DIAGNOSTIC_ATTRIBUTES, - tcx.local_def_id_to_hir_id(item_def_id), - new_item, - IgnoredDiagnosticOption { span: new_item, prev_span: old_item, option_name }, - ); - } + if let (Some(new_item), Some(old_item)) = (new, old) + && let Some(item_def_id) = item_def_id.as_local() + { + tcx.emit_node_span_lint( + MALFORMED_DIAGNOSTIC_ATTRIBUTES, + tcx.local_def_id_to_hir_id(item_def_id), + new_item, + IgnoredDiagnosticOption { span: new_item, prev_span: old_item, option_name }, + ); } } } 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 bf7d4257b626..c52487363664 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -2213,26 +2213,26 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { span: Span, trait_ref: DefId, ) { - if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) { - if let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind { - err.note(format!( - "{}s cannot be accessed directly on a `trait`, they can only be \ + if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) + && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind + { + err.note(format!( + "{}s cannot be accessed directly on a `trait`, they can only be \ accessed through a specific `impl`", - self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id) - )); + self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id) + )); - if !assoc_item.is_impl_trait_in_trait() { - err.span_suggestion_verbose( - span, - "use the fully qualified path to an implementation", - format!( - "::{}", - self.tcx.def_path_str(trait_ref), - assoc_item.name() - ), - Applicability::HasPlaceholders, - ); - } + if !assoc_item.is_impl_trait_in_trait() { + err.span_suggestion_verbose( + span, + "use the fully qualified path to an implementation", + format!( + "::{}", + self.tcx.def_path_str(trait_ref), + assoc_item.name() + ), + Applicability::HasPlaceholders, + ); } } } diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index f50f01a285b5..07e78da37b3b 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -695,15 +695,14 @@ impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> { source: CandidateSource::Impl(def_id), result: Ok(_), } = cand.kind() + && let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id) { - if let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id) { - let message = infcx - .tcx - .get_attr(def_id, sym::rustc_reservation_impl) - .and_then(|a| a.value_str()); - if let Some(message) = message { - self.causes.insert(IntercrateAmbiguityCause::ReservationImpl { message }); - } + let message = infcx + .tcx + .get_attr(def_id, sym::rustc_reservation_impl) + .and_then(|a| a.value_str()); + if let Some(message) = message { + self.causes.insert(IntercrateAmbiguityCause::ReservationImpl { message }); } } } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index f90316f520b3..d7c3543cb3fd 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -781,16 +781,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { self, &project_obligation, ) - { - if let Some(cached_res) = self + && let Some(cached_res) = self .infcx .inner .borrow_mut() .projection_cache() .is_complete(key) - { - break 'compute_res Ok(cached_res); - } + { + break 'compute_res Ok(cached_res); } // Need to explicitly set the depth of nested goals here as @@ -1436,24 +1434,23 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { let tcx = self.tcx(); // Treat reservation impls as ambiguity. - if let ImplCandidate(def_id) = candidate { - if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) { - if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes { - let message = tcx - .get_attr(def_id, sym::rustc_reservation_impl) - .and_then(|a| a.value_str()); - if let Some(message) = message { - debug!( - "filter_reservation_impls: \ + if let ImplCandidate(def_id) = candidate + && let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) + { + if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes { + let message = + tcx.get_attr(def_id, sym::rustc_reservation_impl).and_then(|a| a.value_str()); + if let Some(message) = message { + debug!( + "filter_reservation_impls: \ reservation impl ambiguity on {:?}", - def_id - ); - intercrate_ambiguity_clauses - .insert(IntercrateAmbiguityCause::ReservationImpl { message }); - } + def_id + ); + intercrate_ambiguity_clauses + .insert(IntercrateAmbiguityCause::ReservationImpl { message }); } - return Ok(None); } + return Ok(None); } Ok(Some(candidate)) } diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index f0ff50318abc..af2e000e3402 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -642,11 +642,11 @@ fn fn_abi_adjust_for_abi<'tcx>( // The `deduced_param_attrs` list could be empty if this is a type of function // we can't deduce any parameters for, so make sure the argument index is in // bounds. - if let Some(deduced_param_attrs) = deduced_param_attrs.get(arg_idx) { - if deduced_param_attrs.read_only { - attrs.regular.insert(ArgAttribute::ReadOnly); - debug!("added deduced read-only attribute"); - } + if let Some(deduced_param_attrs) = deduced_param_attrs.get(arg_idx) + && deduced_param_attrs.read_only + { + attrs.regular.insert(ArgAttribute::ReadOnly); + debug!("added deduced read-only attribute"); } } } diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index f8d793464a93..8e09a4a8996d 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -106,10 +106,10 @@ fn adt_sizedness_constraint<'tcx>( tcx: TyCtxt<'tcx>, (def_id, sizedness): (DefId, SizedTraitKind), ) -> Option>> { - if let Some(def_id) = def_id.as_local() { - if let ty::Representability::Infinite(_) = tcx.representability(def_id) { - return None; - } + if let Some(def_id) = def_id.as_local() + && let ty::Representability::Infinite(_) = tcx.representability(def_id) + { + return None; } let def = tcx.adt_def(def_id); From 8d82365a64d86bcc43c50a55718bc0935d102440 Mon Sep 17 00:00:00 2001 From: The rustc-josh-sync Cronjob Bot Date: Mon, 28 Jul 2025 04:18:33 +0000 Subject: [PATCH 209/809] Prepare for merging from rust-lang/rust This updates the rust-version file to 2b5e239c6b86cde974b0ef0f8e23754fb08ff3c5. --- 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 ce9f984e637b..b631041b6bfa 100644 --- a/src/doc/rustc-dev-guide/rust-version +++ b/src/doc/rustc-dev-guide/rust-version @@ -1 +1 @@ -efd420c770bb179537c01063e98cb6990c439654 +2b5e239c6b86cde974b0ef0f8e23754fb08ff3c5 From 173926da2bd94bde24740a4b9e6b1bac1bfcb910 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Tue, 1 Jul 2025 09:33:35 -0700 Subject: [PATCH 210/809] Remove `[T]::array_chunks(_mut)` --- ...sroot_tests-128bit-atomic-operations.patch | 2 +- library/alloc/src/lib.rs | 1 - library/alloc/src/slice.rs | 4 - library/alloc/src/string.rs | 24 +- library/core/src/slice/iter.rs | 249 ------------------ library/core/src/slice/mod.rs | 76 ------ library/core/src/str/iter.rs | 2 +- library/coretests/tests/lib.rs | 1 - library/coretests/tests/slice.rs | 184 ------------- library/std/src/lib.rs | 1 - library/std/src/sys/random/sgx.rs | 14 +- library/std/src/sys/random/uefi.rs | 5 +- 12 files changed, 23 insertions(+), 540 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/patches/0027-sysroot_tests-128bit-atomic-operations.patch b/compiler/rustc_codegen_cranelift/patches/0027-sysroot_tests-128bit-atomic-operations.patch index f6e6bbc2387c..f3d1d5c43ea1 100644 --- a/compiler/rustc_codegen_cranelift/patches/0027-sysroot_tests-128bit-atomic-operations.patch +++ b/compiler/rustc_codegen_cranelift/patches/0027-sysroot_tests-128bit-atomic-operations.patch @@ -19,7 +19,7 @@ index 1e336bf..35e6f54 100644 -#![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] #![cfg_attr(test, feature(cfg_select))] #![feature(alloc_layout_extra)] - #![feature(array_chunks)] + #![feature(array_ptr_get)] diff --git a/coretests/tests/atomic.rs b/coretests/tests/atomic.rs index b735957..ea728b6 100644 --- a/coretests/tests/atomic.rs diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 6b6e4df4cba7..c091e496c509 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -94,7 +94,6 @@ // tidy-alphabetical-start #![feature(alloc_layout_extra)] #![feature(allocator_api)] -#![feature(array_chunks)] #![feature(array_into_iter_constructors)] #![feature(array_windows)] #![feature(ascii_char)] diff --git a/library/alloc/src/slice.rs b/library/alloc/src/slice.rs index b4da56578c89..ce9f967cc387 100644 --- a/library/alloc/src/slice.rs +++ b/library/alloc/src/slice.rs @@ -16,10 +16,6 @@ use core::cmp::Ordering::{self, Less}; use core::mem::MaybeUninit; #[cfg(not(no_global_oom_handling))] use core::ptr; -#[unstable(feature = "array_chunks", issue = "74985")] -pub use core::slice::ArrayChunks; -#[unstable(feature = "array_chunks", issue = "74985")] -pub use core::slice::ArrayChunksMut; #[unstable(feature = "array_windows", issue = "75027")] pub use core::slice::ArrayWindows; #[stable(feature = "inherent_ascii_escape", since = "1.60.0")] diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index a189c00a6b61..d58240f3051e 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -787,12 +787,12 @@ impl String { #[cfg(not(no_global_oom_handling))] #[unstable(feature = "str_from_utf16_endian", issue = "116258")] pub fn from_utf16le(v: &[u8]) -> Result { - if v.len() % 2 != 0 { + let (chunks, []) = v.as_chunks::<2>() else { return Err(FromUtf16Error(())); - } + }; match (cfg!(target_endian = "little"), unsafe { v.align_to::() }) { (true, ([], v, [])) => Self::from_utf16(v), - _ => char::decode_utf16(v.array_chunks::<2>().copied().map(u16::from_le_bytes)) + _ => char::decode_utf16(chunks.iter().copied().map(u16::from_le_bytes)) .collect::>() .map_err(|_| FromUtf16Error(())), } @@ -830,11 +830,11 @@ impl String { (true, ([], v, [])) => Self::from_utf16_lossy(v), (true, ([], v, [_remainder])) => Self::from_utf16_lossy(v) + "\u{FFFD}", _ => { - let mut iter = v.array_chunks::<2>(); - let string = char::decode_utf16(iter.by_ref().copied().map(u16::from_le_bytes)) + let (chunks, remainder) = v.as_chunks::<2>(); + let string = char::decode_utf16(chunks.iter().copied().map(u16::from_le_bytes)) .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)) .collect(); - if iter.remainder().is_empty() { string } else { string + "\u{FFFD}" } + if remainder.is_empty() { string } else { string + "\u{FFFD}" } } } } @@ -862,12 +862,12 @@ impl String { #[cfg(not(no_global_oom_handling))] #[unstable(feature = "str_from_utf16_endian", issue = "116258")] pub fn from_utf16be(v: &[u8]) -> Result { - if v.len() % 2 != 0 { + let (chunks, []) = v.as_chunks::<2>() else { return Err(FromUtf16Error(())); - } + }; match (cfg!(target_endian = "big"), unsafe { v.align_to::() }) { (true, ([], v, [])) => Self::from_utf16(v), - _ => char::decode_utf16(v.array_chunks::<2>().copied().map(u16::from_be_bytes)) + _ => char::decode_utf16(chunks.iter().copied().map(u16::from_be_bytes)) .collect::>() .map_err(|_| FromUtf16Error(())), } @@ -905,11 +905,11 @@ impl String { (true, ([], v, [])) => Self::from_utf16_lossy(v), (true, ([], v, [_remainder])) => Self::from_utf16_lossy(v) + "\u{FFFD}", _ => { - let mut iter = v.array_chunks::<2>(); - let string = char::decode_utf16(iter.by_ref().copied().map(u16::from_be_bytes)) + let (chunks, remainder) = v.as_chunks::<2>(); + let string = char::decode_utf16(chunks.iter().copied().map(u16::from_be_bytes)) .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)) .collect(); - if iter.remainder().is_empty() { string } else { string + "\u{FFFD}" } + if remainder.is_empty() { string } else { string + "\u{FFFD}" } } } } diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 33132dcc7148..ae910e052520 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -2301,255 +2301,6 @@ impl ExactSizeIterator for ArrayWindows<'_, T, N> { } } -/// An iterator over a slice in (non-overlapping) chunks (`N` elements at a -/// time), starting at the beginning of the slice. -/// -/// When the slice len is not evenly divided by the chunk size, the last -/// up to `N-1` elements will be omitted but can be retrieved from -/// the [`remainder`] function from the iterator. -/// -/// This struct is created by the [`array_chunks`] method on [slices]. -/// -/// # Example -/// -/// ``` -/// #![feature(array_chunks)] -/// -/// let slice = ['l', 'o', 'r', 'e', 'm']; -/// let mut iter = slice.array_chunks::<2>(); -/// assert_eq!(iter.next(), Some(&['l', 'o'])); -/// assert_eq!(iter.next(), Some(&['r', 'e'])); -/// assert_eq!(iter.next(), None); -/// ``` -/// -/// [`array_chunks`]: slice::array_chunks -/// [`remainder`]: ArrayChunks::remainder -/// [slices]: slice -#[derive(Debug)] -#[unstable(feature = "array_chunks", issue = "74985")] -#[must_use = "iterators are lazy and do nothing unless consumed"] -pub struct ArrayChunks<'a, T: 'a, const N: usize> { - iter: Iter<'a, [T; N]>, - rem: &'a [T], -} - -impl<'a, T, const N: usize> ArrayChunks<'a, T, N> { - #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")] - #[inline] - pub(super) const fn new(slice: &'a [T]) -> Self { - let (array_slice, rem) = slice.as_chunks(); - Self { iter: array_slice.iter(), rem } - } - - /// Returns the remainder of the original slice that is not going to be - /// returned by the iterator. The returned slice has at most `N-1` - /// elements. - #[must_use] - #[unstable(feature = "array_chunks", issue = "74985")] - pub fn remainder(&self) -> &'a [T] { - self.rem - } -} - -// FIXME(#26925) Remove in favor of `#[derive(Clone)]` -#[unstable(feature = "array_chunks", issue = "74985")] -impl Clone for ArrayChunks<'_, T, N> { - fn clone(&self) -> Self { - ArrayChunks { iter: self.iter.clone(), rem: self.rem } - } -} - -#[unstable(feature = "array_chunks", issue = "74985")] -impl<'a, T, const N: usize> Iterator for ArrayChunks<'a, T, N> { - type Item = &'a [T; N]; - - #[inline] - fn next(&mut self) -> Option<&'a [T; N]> { - self.iter.next() - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } - - #[inline] - fn count(self) -> usize { - self.iter.count() - } - - #[inline] - fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n) - } - - #[inline] - fn last(self) -> Option { - self.iter.last() - } - - unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a [T; N] { - // SAFETY: The safety guarantees of `__iterator_get_unchecked` are - // transferred to the caller. - unsafe { self.iter.__iterator_get_unchecked(i) } - } -} - -#[unstable(feature = "array_chunks", issue = "74985")] -impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunks<'a, T, N> { - #[inline] - fn next_back(&mut self) -> Option<&'a [T; N]> { - self.iter.next_back() - } - - #[inline] - fn nth_back(&mut self, n: usize) -> Option { - self.iter.nth_back(n) - } -} - -#[unstable(feature = "array_chunks", issue = "74985")] -impl ExactSizeIterator for ArrayChunks<'_, T, N> { - fn is_empty(&self) -> bool { - self.iter.is_empty() - } -} - -#[unstable(feature = "trusted_len", issue = "37572")] -unsafe impl TrustedLen for ArrayChunks<'_, T, N> {} - -#[unstable(feature = "array_chunks", issue = "74985")] -impl FusedIterator for ArrayChunks<'_, T, N> {} - -#[doc(hidden)] -#[unstable(feature = "array_chunks", issue = "74985")] -unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunks<'a, T, N> {} - -#[doc(hidden)] -#[unstable(feature = "array_chunks", issue = "74985")] -unsafe impl<'a, T, const N: usize> TrustedRandomAccessNoCoerce for ArrayChunks<'a, T, N> { - const MAY_HAVE_SIDE_EFFECT: bool = false; -} - -/// An iterator over a slice in (non-overlapping) mutable chunks (`N` elements -/// at a time), starting at the beginning of the slice. -/// -/// When the slice len is not evenly divided by the chunk size, the last -/// up to `N-1` elements will be omitted but can be retrieved from -/// the [`into_remainder`] function from the iterator. -/// -/// This struct is created by the [`array_chunks_mut`] method on [slices]. -/// -/// # Example -/// -/// ``` -/// #![feature(array_chunks)] -/// -/// let mut slice = ['l', 'o', 'r', 'e', 'm']; -/// let iter = slice.array_chunks_mut::<2>(); -/// ``` -/// -/// [`array_chunks_mut`]: slice::array_chunks_mut -/// [`into_remainder`]: ../../std/slice/struct.ArrayChunksMut.html#method.into_remainder -/// [slices]: slice -#[derive(Debug)] -#[unstable(feature = "array_chunks", issue = "74985")] -#[must_use = "iterators are lazy and do nothing unless consumed"] -pub struct ArrayChunksMut<'a, T: 'a, const N: usize> { - iter: IterMut<'a, [T; N]>, - rem: &'a mut [T], -} - -impl<'a, T, const N: usize> ArrayChunksMut<'a, T, N> { - #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")] - #[inline] - pub(super) const fn new(slice: &'a mut [T]) -> Self { - let (array_slice, rem) = slice.as_chunks_mut(); - Self { iter: array_slice.iter_mut(), rem } - } - - /// Returns the remainder of the original slice that is not going to be - /// returned by the iterator. The returned slice has at most `N-1` - /// elements. - #[must_use = "`self` will be dropped if the result is not used"] - #[unstable(feature = "array_chunks", issue = "74985")] - pub fn into_remainder(self) -> &'a mut [T] { - self.rem - } -} - -#[unstable(feature = "array_chunks", issue = "74985")] -impl<'a, T, const N: usize> Iterator for ArrayChunksMut<'a, T, N> { - type Item = &'a mut [T; N]; - - #[inline] - fn next(&mut self) -> Option<&'a mut [T; N]> { - self.iter.next() - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } - - #[inline] - fn count(self) -> usize { - self.iter.count() - } - - #[inline] - fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n) - } - - #[inline] - fn last(self) -> Option { - self.iter.last() - } - - unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> &'a mut [T; N] { - // SAFETY: The safety guarantees of `__iterator_get_unchecked` are transferred to - // the caller. - unsafe { self.iter.__iterator_get_unchecked(i) } - } -} - -#[unstable(feature = "array_chunks", issue = "74985")] -impl<'a, T, const N: usize> DoubleEndedIterator for ArrayChunksMut<'a, T, N> { - #[inline] - fn next_back(&mut self) -> Option<&'a mut [T; N]> { - self.iter.next_back() - } - - #[inline] - fn nth_back(&mut self, n: usize) -> Option { - self.iter.nth_back(n) - } -} - -#[unstable(feature = "array_chunks", issue = "74985")] -impl ExactSizeIterator for ArrayChunksMut<'_, T, N> { - fn is_empty(&self) -> bool { - self.iter.is_empty() - } -} - -#[unstable(feature = "trusted_len", issue = "37572")] -unsafe impl TrustedLen for ArrayChunksMut<'_, T, N> {} - -#[unstable(feature = "array_chunks", issue = "74985")] -impl FusedIterator for ArrayChunksMut<'_, T, N> {} - -#[doc(hidden)] -#[unstable(feature = "array_chunks", issue = "74985")] -unsafe impl<'a, T, const N: usize> TrustedRandomAccess for ArrayChunksMut<'a, T, N> {} - -#[doc(hidden)] -#[unstable(feature = "array_chunks", issue = "74985")] -unsafe impl<'a, T, const N: usize> TrustedRandomAccessNoCoerce for ArrayChunksMut<'a, T, N> { - const MAY_HAVE_SIDE_EFFECT: bool = false; -} - /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a /// time), starting at the end of the slice. /// diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 6fe5affc48be..1f34a7931d24 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -52,8 +52,6 @@ pub use index::SliceIndex; pub use index::{range, try_range}; #[unstable(feature = "array_windows", issue = "75027")] pub use iter::ArrayWindows; -#[unstable(feature = "array_chunks", issue = "74985")] -pub use iter::{ArrayChunks, ArrayChunksMut}; #[stable(feature = "slice_group_by", since = "1.77.0")] pub use iter::{ChunkBy, ChunkByMut}; #[stable(feature = "rust1", since = "1.0.0")] @@ -1448,42 +1446,6 @@ impl [T] { (remainder, array_slice) } - /// Returns an iterator over `N` elements of the slice at a time, starting at the - /// beginning of the slice. - /// - /// The chunks are array references and do not overlap. If `N` does not divide the - /// length of the slice, then the last up to `N-1` elements will be omitted and can be - /// retrieved from the `remainder` function of the iterator. - /// - /// This method is the const generic equivalent of [`chunks_exact`]. - /// - /// # Panics - /// - /// Panics if `N` is zero. This check will most probably get changed to a compile time - /// error before this method gets stabilized. - /// - /// # Examples - /// - /// ``` - /// #![feature(array_chunks)] - /// let slice = ['l', 'o', 'r', 'e', 'm']; - /// let mut iter = slice.array_chunks(); - /// assert_eq!(iter.next().unwrap(), &['l', 'o']); - /// assert_eq!(iter.next().unwrap(), &['r', 'e']); - /// assert!(iter.next().is_none()); - /// assert_eq!(iter.remainder(), &['m']); - /// ``` - /// - /// [`chunks_exact`]: slice::chunks_exact - #[unstable(feature = "array_chunks", issue = "74985")] - #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")] - #[inline] - #[track_caller] - pub const fn array_chunks(&self) -> ArrayChunks<'_, T, N> { - assert!(N != 0, "chunk size must be non-zero"); - ArrayChunks::new(self) - } - /// Splits the slice into a slice of `N`-element arrays, /// assuming that there's no remainder. /// @@ -1646,44 +1608,6 @@ impl [T] { (remainder, array_slice) } - /// Returns an iterator over `N` elements of the slice at a time, starting at the - /// beginning of the slice. - /// - /// The chunks are mutable array references and do not overlap. If `N` does not divide - /// the length of the slice, then the last up to `N-1` elements will be omitted and - /// can be retrieved from the `into_remainder` function of the iterator. - /// - /// This method is the const generic equivalent of [`chunks_exact_mut`]. - /// - /// # Panics - /// - /// Panics if `N` is zero. This check will most probably get changed to a compile time - /// error before this method gets stabilized. - /// - /// # Examples - /// - /// ``` - /// #![feature(array_chunks)] - /// let v = &mut [0, 0, 0, 0, 0]; - /// let mut count = 1; - /// - /// for chunk in v.array_chunks_mut() { - /// *chunk = [count; 2]; - /// count += 1; - /// } - /// assert_eq!(v, &[1, 1, 2, 2, 0]); - /// ``` - /// - /// [`chunks_exact_mut`]: slice::chunks_exact_mut - #[unstable(feature = "array_chunks", issue = "74985")] - #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")] - #[inline] - #[track_caller] - pub const fn array_chunks_mut(&mut self) -> ArrayChunksMut<'_, T, N> { - assert!(N != 0, "chunk size must be non-zero"); - ArrayChunksMut::new(self) - } - /// Returns an iterator over overlapping windows of `N` elements of a slice, /// starting at the beginning of the slice. /// diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index bcf886484add..d2985d8a1866 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -52,7 +52,7 @@ impl<'a> Iterator for Chars<'a> { const CHUNK_SIZE: usize = 32; if remainder >= CHUNK_SIZE { - let mut chunks = self.iter.as_slice().array_chunks::(); + let mut chunks = self.iter.as_slice().as_chunks::().0.iter(); let mut bytes_skipped: usize = 0; while remainder > CHUNK_SIZE diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index c5bfd1574e29..57a89365fa98 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -2,7 +2,6 @@ #![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] #![cfg_attr(test, feature(cfg_select))] #![feature(alloc_layout_extra)] -#![feature(array_chunks)] #![feature(array_ptr_get)] #![feature(array_try_from_fn)] #![feature(array_windows)] diff --git a/library/coretests/tests/slice.rs b/library/coretests/tests/slice.rs index d17e681480c7..992f24cb18f2 100644 --- a/library/coretests/tests/slice.rs +++ b/library/coretests/tests/slice.rs @@ -611,190 +611,6 @@ fn test_chunks_exact_mut_zip() { assert_eq!(v1, [13, 14, 19, 20, 4]); } -#[test] -fn test_array_chunks_infer() { - let v: &[i32] = &[0, 1, 2, 3, 4, -4]; - let c = v.array_chunks(); - for &[a, b, c] in c { - assert_eq!(a + b + c, 3); - } - - let v2: &[i32] = &[0, 1, 2, 3, 4, 5, 6]; - let total = v2.array_chunks().map(|&[a, b]| a * b).sum::(); - assert_eq!(total, 2 * 3 + 4 * 5); -} - -#[test] -fn test_array_chunks_count() { - let v: &[i32] = &[0, 1, 2, 3, 4, 5]; - let c = v.array_chunks::<3>(); - assert_eq!(c.count(), 2); - - let v2: &[i32] = &[0, 1, 2, 3, 4]; - let c2 = v2.array_chunks::<2>(); - assert_eq!(c2.count(), 2); - - let v3: &[i32] = &[]; - let c3 = v3.array_chunks::<2>(); - assert_eq!(c3.count(), 0); -} - -#[test] -fn test_array_chunks_nth() { - let v: &[i32] = &[0, 1, 2, 3, 4, 5]; - let mut c = v.array_chunks::<2>(); - assert_eq!(c.nth(1).unwrap(), &[2, 3]); - assert_eq!(c.next().unwrap(), &[4, 5]); - - let v2: &[i32] = &[0, 1, 2, 3, 4, 5, 6]; - let mut c2 = v2.array_chunks::<3>(); - assert_eq!(c2.nth(1).unwrap(), &[3, 4, 5]); - assert_eq!(c2.next(), None); -} - -#[test] -fn test_array_chunks_nth_back() { - let v: &[i32] = &[0, 1, 2, 3, 4, 5]; - let mut c = v.array_chunks::<2>(); - assert_eq!(c.nth_back(1).unwrap(), &[2, 3]); - assert_eq!(c.next().unwrap(), &[0, 1]); - assert_eq!(c.next(), None); - - let v2: &[i32] = &[0, 1, 2, 3, 4]; - let mut c2 = v2.array_chunks::<3>(); - assert_eq!(c2.nth_back(0).unwrap(), &[0, 1, 2]); - assert_eq!(c2.next(), None); - assert_eq!(c2.next_back(), None); - - let v3: &[i32] = &[0, 1, 2, 3, 4]; - let mut c3 = v3.array_chunks::<10>(); - assert_eq!(c3.nth_back(0), None); -} - -#[test] -fn test_array_chunks_last() { - let v: &[i32] = &[0, 1, 2, 3, 4, 5]; - let c = v.array_chunks::<2>(); - assert_eq!(c.last().unwrap(), &[4, 5]); - - let v2: &[i32] = &[0, 1, 2, 3, 4]; - let c2 = v2.array_chunks::<2>(); - assert_eq!(c2.last().unwrap(), &[2, 3]); -} - -#[test] -fn test_array_chunks_remainder() { - let v: &[i32] = &[0, 1, 2, 3, 4]; - let c = v.array_chunks::<2>(); - assert_eq!(c.remainder(), &[4]); -} - -#[test] -fn test_array_chunks_zip() { - let v1: &[i32] = &[0, 1, 2, 3, 4]; - let v2: &[i32] = &[6, 7, 8, 9, 10]; - - let res = v1 - .array_chunks::<2>() - .zip(v2.array_chunks::<2>()) - .map(|(a, b)| a.iter().sum::() + b.iter().sum::()) - .collect::>(); - assert_eq!(res, vec![14, 22]); -} - -#[test] -fn test_array_chunks_mut_infer() { - let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5, 6]; - for a in v.array_chunks_mut() { - let sum = a.iter().sum::(); - *a = [sum; 3]; - } - assert_eq!(v, &[3, 3, 3, 12, 12, 12, 6]); - - let v2: &mut [i32] = &mut [0, 1, 2, 3, 4, 5, 6]; - v2.array_chunks_mut().for_each(|[a, b]| core::mem::swap(a, b)); - assert_eq!(v2, &[1, 0, 3, 2, 5, 4, 6]); -} - -#[test] -fn test_array_chunks_mut_count() { - let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5]; - let c = v.array_chunks_mut::<3>(); - assert_eq!(c.count(), 2); - - let v2: &mut [i32] = &mut [0, 1, 2, 3, 4]; - let c2 = v2.array_chunks_mut::<2>(); - assert_eq!(c2.count(), 2); - - let v3: &mut [i32] = &mut []; - let c3 = v3.array_chunks_mut::<2>(); - assert_eq!(c3.count(), 0); -} - -#[test] -fn test_array_chunks_mut_nth() { - let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5]; - let mut c = v.array_chunks_mut::<2>(); - assert_eq!(c.nth(1).unwrap(), &[2, 3]); - assert_eq!(c.next().unwrap(), &[4, 5]); - - let v2: &mut [i32] = &mut [0, 1, 2, 3, 4, 5, 6]; - let mut c2 = v2.array_chunks_mut::<3>(); - assert_eq!(c2.nth(1).unwrap(), &[3, 4, 5]); - assert_eq!(c2.next(), None); -} - -#[test] -fn test_array_chunks_mut_nth_back() { - let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5]; - let mut c = v.array_chunks_mut::<2>(); - assert_eq!(c.nth_back(1).unwrap(), &[2, 3]); - assert_eq!(c.next().unwrap(), &[0, 1]); - assert_eq!(c.next(), None); - - let v2: &mut [i32] = &mut [0, 1, 2, 3, 4]; - let mut c2 = v2.array_chunks_mut::<3>(); - assert_eq!(c2.nth_back(0).unwrap(), &[0, 1, 2]); - assert_eq!(c2.next(), None); - assert_eq!(c2.next_back(), None); - - let v3: &mut [i32] = &mut [0, 1, 2, 3, 4]; - let mut c3 = v3.array_chunks_mut::<10>(); - assert_eq!(c3.nth_back(0), None); -} - -#[test] -fn test_array_chunks_mut_last() { - let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5]; - let c = v.array_chunks_mut::<2>(); - assert_eq!(c.last().unwrap(), &[4, 5]); - - let v2: &mut [i32] = &mut [0, 1, 2, 3, 4]; - let c2 = v2.array_chunks_mut::<2>(); - assert_eq!(c2.last().unwrap(), &[2, 3]); -} - -#[test] -fn test_array_chunks_mut_remainder() { - let v: &mut [i32] = &mut [0, 1, 2, 3, 4]; - let c = v.array_chunks_mut::<2>(); - assert_eq!(c.into_remainder(), &[4]); -} - -#[test] -fn test_array_chunks_mut_zip() { - let v1: &mut [i32] = &mut [0, 1, 2, 3, 4]; - let v2: &[i32] = &[6, 7, 8, 9, 10]; - - for (a, b) in v1.array_chunks_mut::<2>().zip(v2.array_chunks::<2>()) { - let sum = b.iter().sum::(); - for v in a { - *v += sum; - } - } - assert_eq!(v1, [13, 14, 19, 20, 4]); -} - #[test] fn test_array_windows_infer() { let v: &[i32] = &[0, 1, 0, 1]; diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 323742a75b05..433e013b40fd 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -324,7 +324,6 @@ // // Library features (core): // tidy-alphabetical-start -#![feature(array_chunks)] #![feature(bstr)] #![feature(bstr_internals)] #![feature(char_internals)] diff --git a/library/std/src/sys/random/sgx.rs b/library/std/src/sys/random/sgx.rs index c3647a8df220..462b19003fad 100644 --- a/library/std/src/sys/random/sgx.rs +++ b/library/std/src/sys/random/sgx.rs @@ -46,22 +46,22 @@ fn rdrand16() -> u16 { } pub fn fill_bytes(bytes: &mut [u8]) { - let mut chunks = bytes.array_chunks_mut(); - for chunk in &mut chunks { + let (chunks, remainder) = bytes.as_chunks_mut(); + for chunk in chunks { *chunk = rdrand64().to_ne_bytes(); } - let mut chunks = chunks.into_remainder().array_chunks_mut(); - for chunk in &mut chunks { + let (chunks, remainder) = remainder.as_chunks_mut(); + for chunk in chunks { *chunk = rdrand32().to_ne_bytes(); } - let mut chunks = chunks.into_remainder().array_chunks_mut(); - for chunk in &mut chunks { + let (chunks, remainder) = remainder.as_chunks_mut(); + for chunk in chunks { *chunk = rdrand16().to_ne_bytes(); } - if let [byte] = chunks.into_remainder() { + if let [byte] = remainder { *byte = rdrand16() as u8; } } diff --git a/library/std/src/sys/random/uefi.rs b/library/std/src/sys/random/uefi.rs index 5f001f0f532a..4a71d32fffeb 100644 --- a/library/std/src/sys/random/uefi.rs +++ b/library/std/src/sys/random/uefi.rs @@ -138,12 +138,11 @@ mod rdrand { } unsafe fn rdrand_exact(dest: &mut [u8]) -> Option<()> { - let mut chunks = dest.array_chunks_mut(); - for chunk in &mut chunks { + let (chunks, tail) = dest.as_chunks_mut(); + for chunk in chunks { *chunk = unsafe { rdrand() }?.to_ne_bytes(); } - let tail = chunks.into_remainder(); let n = tail.len(); if n > 0 { let src = unsafe { rdrand() }?.to_ne_bytes(); From fbd553e8e579887210e7a8e71f41f631d3054e67 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 28 Jul 2025 08:38:15 +0200 Subject: [PATCH 211/809] prepare for sync --- 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 634ce1fa0628..2178caf63968 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -b56aaec52bc0fa35591a872fb4aac81f606e265c +733dab558992d902d6d17576de1da768094e2cf3 From dea3e131d53eccd46703a304d942778b5c6edef6 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 28 Jul 2025 08:42:04 +0200 Subject: [PATCH 212/809] revert accidental change --- src/tools/miri/src/diagnostics.rs | 2 +- .../fail/function_pointers/abi_mismatch_return_type.stderr | 2 ++ src/tools/miri/tests/fail/shims/return_type_mismatch.stderr | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/tools/miri/src/diagnostics.rs b/src/tools/miri/src/diagnostics.rs index 8fdf8d643eae..9ecbd31c5b9f 100644 --- a/src/tools/miri/src/diagnostics.rs +++ b/src/tools/miri/src/diagnostics.rs @@ -382,7 +382,7 @@ pub fn report_error<'tcx>( helps.push(note_span!(span, "{:?} was deallocated here:", alloc_id)); } } - AbiMismatchArgument { .. } => { + AbiMismatchArgument { .. } | AbiMismatchReturn { .. } => { helps.push(note!("this means these two types are not *guaranteed* to be ABI-compatible across all targets")); helps.push(note!("if you think this code should be accepted anyway, please report an issue with Miri")); } diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr index 07e6561b53e7..28c676ad4823 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr @@ -6,6 +6,8 @@ LL | g() | = 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 + = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at tests/fail/function_pointers/abi_mismatch_return_type.rs:LL:CC diff --git a/src/tools/miri/tests/fail/shims/return_type_mismatch.stderr b/src/tools/miri/tests/fail/shims/return_type_mismatch.stderr index 080ee16a2eb5..18ff3067fa03 100644 --- a/src/tools/miri/tests/fail/shims/return_type_mismatch.stderr +++ b/src/tools/miri/tests/fail/shims/return_type_mismatch.stderr @@ -6,6 +6,8 @@ LL | close(fd); | = 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 + = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at tests/fail/shims/return_type_mismatch.rs:LL:CC From 66445e7975a5f11324e61e2ebbfdbdfa2015be02 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Mon, 28 Jul 2025 08:57:48 +0200 Subject: [PATCH 213/809] fix pauses --- src/doc/rustc-dev-guide/src/tests/ui.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/tests/ui.md b/src/doc/rustc-dev-guide/src/tests/ui.md index b1feef9ed0cc..8f872b3aa4b9 100644 --- a/src/doc/rustc-dev-guide/src/tests/ui.md +++ b/src/doc/rustc-dev-guide/src/tests/ui.md @@ -320,8 +320,8 @@ be preferred over //@ error-pattern, //@ error-pattern is imprecise and non-exha ### `error-pattern` -The `error-pattern` [directive](directives.md) can be used for runtime messages, which don't -have a specific span, or in exceptional cases, for compile time messages. +The `error-pattern` [directive](directives.md) can be used for runtime messages which don't +have a specific span, or, in exceptional cases, for compile time messages. Let's think about this test: From b707493721a06acaba2cb0e0c59f6855f799293f Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Mon, 28 Jul 2025 09:09:41 +0200 Subject: [PATCH 214/809] reword to avoid using a term used in a confusing manner, "error annotations" --- src/doc/rustc-dev-guide/src/tests/ui.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/doc/rustc-dev-guide/src/tests/ui.md b/src/doc/rustc-dev-guide/src/tests/ui.md index 8f872b3aa4b9..782f78d76148 100644 --- a/src/doc/rustc-dev-guide/src/tests/ui.md +++ b/src/doc/rustc-dev-guide/src/tests/ui.md @@ -309,8 +309,9 @@ fn main((ؼ Use `//~?` to match an error without line information. `//~?` is precise and will not match errors if their line information is available. -For tests wishing to match against compiler diagnostics, error annotations should -be preferred over //@ error-pattern, //@ error-pattern is imprecise and non-exhaustive. +It should be preferred over `//@ error-pattern` +for tests wishing to match against compiler diagnostics, +due to `//@ error-pattern` being imprecise and non-exhaustive. ```rust,ignore //@ compile-flags: --print yyyy From 3e6f950d66008a7a15f38d10d5b19707c06602c7 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Thu, 17 Jul 2025 06:09:15 +0200 Subject: [PATCH 215/809] 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 ecb046a63e94301463b8a5291d7ef9776c06aadc Mon Sep 17 00:00:00 2001 From: Patrick-6 Date: Mon, 28 Jul 2025 10:50:02 +0200 Subject: [PATCH 216/809] Reduce required cc crate version. --- src/tools/miri/Cargo.lock | 4 ++-- src/tools/miri/genmc-sys/Cargo.toml | 2 +- src/tools/miri/genmc-sys/build.rs | 4 +++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/tools/miri/Cargo.lock b/src/tools/miri/Cargo.lock index ece51f2ba74a..b46f0f834209 100644 --- a/src/tools/miri/Cargo.lock +++ b/src/tools/miri/Cargo.lock @@ -166,9 +166,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.30" +version = "1.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deec109607ca693028562ed836a5f1c4b8bd77755c4e132fc5ce11b0b6211ae7" +checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" dependencies = [ "jobserver", "libc", diff --git a/src/tools/miri/genmc-sys/Cargo.toml b/src/tools/miri/genmc-sys/Cargo.toml index 95aef75afc4f..737ab9073bfb 100644 --- a/src/tools/miri/genmc-sys/Cargo.toml +++ b/src/tools/miri/genmc-sys/Cargo.toml @@ -11,7 +11,7 @@ edition = "2024" cxx = { version = "1.0.160", features = ["c++20"] } [build-dependencies] -cc = "1.2.30" +cc = "1.2.16" cmake = "0.1.54" git2 = { version = "0.20.2", default-features = false, features = ["https"] } cxx-build = { version = "1.0.160", features = ["parallel"] } diff --git a/src/tools/miri/genmc-sys/build.rs b/src/tools/miri/genmc-sys/build.rs index f20e0e8d525f..479a3bd7186b 100644 --- a/src/tools/miri/genmc-sys/build.rs +++ b/src/tools/miri/genmc-sys/build.rs @@ -215,8 +215,10 @@ fn compile_cpp_dependencies(genmc_path: &Path) { if enable_genmc_debug { bridge.define("ENABLE_GENMC_DEBUG", None); } + for definition in definitions { + bridge.flag(definition); + } bridge - .flags(definitions) .opt_level(2) .debug(true) // Same settings that GenMC uses (default for cmake `RelWithDebInfo`) .warnings(false) // NOTE: enabling this produces a lot of warnings. From f29f073f43f7cd2732a040bf2369d02c84239dc0 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Sun, 13 Jul 2025 12:38:21 +0200 Subject: [PATCH 217/809] add support for ./x check src/tools/linkchecker --- src/bootstrap/src/core/build_steps/check.rs | 6 ++++++ src/bootstrap/src/core/builder/mod.rs | 1 + 2 files changed, 7 insertions(+) diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index cfe090b22dc3..b4232409ba83 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -556,3 +556,9 @@ tool_check_step!(Compiletest { allow_features: COMPILETEST_ALLOW_FEATURES, default: false, }); + +tool_check_step!(Linkchecker { + path: "src/tools/linkchecker", + mode: |_builder| Mode::ToolBootstrap, + default: false +}); diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 923c3a9a9350..020622d1c121 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -1033,6 +1033,7 @@ impl<'a> Builder<'a> { check::Compiletest, check::FeaturesStatusDump, check::CoverageDump, + check::Linkchecker, // This has special staging logic, it may run on stage 1 while others run on stage 0. // It takes quite some time to build stage 1, so put this at the end. // From c745614e03bd820a0b6fd4f0962f21c66464c1fb Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Sun, 13 Jul 2025 12:40:32 +0200 Subject: [PATCH 218/809] bump linkchecker to edition 2024 --- src/tools/linkchecker/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/linkchecker/Cargo.toml b/src/tools/linkchecker/Cargo.toml index 7123d43eb564..fb5bff3fe63f 100644 --- a/src/tools/linkchecker/Cargo.toml +++ b/src/tools/linkchecker/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "linkchecker" version = "0.1.0" -edition = "2021" +edition = "2024" [[bin]] name = "linkchecker" From 984926eb3a0b96a6fed8d721b93ccd8efeb8510e Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Tue, 1 Jul 2025 10:57:52 +0200 Subject: [PATCH 219/809] add an argument parser to linkchecker --- src/tools/linkchecker/main.rs | 51 +++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/src/tools/linkchecker/main.rs b/src/tools/linkchecker/main.rs index 84cba3f8c447..4b45692e8490 100644 --- a/src/tools/linkchecker/main.rs +++ b/src/tools/linkchecker/main.rs @@ -18,11 +18,11 @@ use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; +use std::fs; use std::io::ErrorKind; use std::path::{Component, Path, PathBuf}; use std::rc::Rc; use std::time::Instant; -use std::{env, fs}; use html5ever::tendril::ByteTendril; use html5ever::tokenizer::{ @@ -110,10 +110,20 @@ macro_rules! t { }; } +struct Cli { + docs: PathBuf, +} + fn main() { - let docs = env::args_os().nth(1).expect("doc path should be first argument"); - let docs = env::current_dir().unwrap().join(docs); - let mut checker = Checker { root: docs.clone(), cache: HashMap::new() }; + let cli = match parse_cli() { + Ok(cli) => cli, + Err(err) => { + eprintln!("error: {err}"); + usage_and_exit(1); + } + }; + + let mut checker = Checker { root: cli.docs.clone(), cache: HashMap::new() }; let mut report = Report { errors: 0, start: Instant::now(), @@ -125,7 +135,7 @@ fn main() { intra_doc_exceptions: 0, has_broken_urls: false, }; - checker.walk(&docs, &mut report); + checker.walk(&cli.docs, &mut report); report.report(); if report.errors != 0 { println!("found some broken links"); @@ -133,6 +143,37 @@ fn main() { } } +fn parse_cli() -> Result { + fn to_canonical_path(arg: &str) -> Result { + PathBuf::from(arg).canonicalize().map_err(|e| format!("could not canonicalize {arg}: {e}")) + } + + let mut verbatim = false; + let mut docs = None; + + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + if !verbatim && arg == "--" { + verbatim = true; + } else if !verbatim && (arg == "-h" || arg == "--help") { + usage_and_exit(0) + } else if !verbatim && arg.starts_with('-') { + return Err(format!("unknown flag: {arg}")); + } else if docs.is_none() { + docs = Some(arg); + } else { + return Err("too many positional arguments".into()); + } + } + + Ok(Cli { docs: to_canonical_path(&docs.ok_or("missing first positional argument")?)? }) +} + +fn usage_and_exit(code: i32) -> ! { + eprintln!("usage: linkchecker "); + std::process::exit(code) +} + struct Checker { root: PathBuf, cache: Cache, From 2b11851452364e07a3b0456a7a24424d944297fa Mon Sep 17 00:00:00 2001 From: Boxy Date: Mon, 28 Jul 2025 09:59:57 +0100 Subject: [PATCH 220/809] Raw Pointers are Constant PatKinds too --- compiler/rustc_middle/src/thir.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 730c1147684b..3dd6d2c89286 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -838,6 +838,8 @@ pub enum PatKind<'tcx> { /// * integer, bool, char or float (represented as a valtree), which will be handled by /// exhaustiveness to cover exactly its own value, similar to `&str`, but these values are /// much simpler. + /// * raw pointers derived from integers, other raw pointers will have already resulted in an + // error. /// * `String`, if `string_deref_patterns` is enabled. Constant { value: mir::Const<'tcx>, From 6693b3908f36374cd998e43445760f2b1552973d Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Tue, 1 Jul 2025 12:16:35 +0200 Subject: [PATCH 221/809] add --link-targets-dir flag to linkchecker --- src/tools/linkchecker/main.rs | 77 +++++++++++++++++++++++------------ 1 file changed, 52 insertions(+), 25 deletions(-) diff --git a/src/tools/linkchecker/main.rs b/src/tools/linkchecker/main.rs index 4b45692e8490..1dc45728c90c 100644 --- a/src/tools/linkchecker/main.rs +++ b/src/tools/linkchecker/main.rs @@ -17,9 +17,10 @@ //! should catch the majority of "broken link" cases. use std::cell::{Cell, RefCell}; +use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::fs; -use std::io::ErrorKind; +use std::iter::once; use std::path::{Component, Path, PathBuf}; use std::rc::Rc; use std::time::Instant; @@ -112,6 +113,7 @@ macro_rules! t { struct Cli { docs: PathBuf, + link_targets_dirs: Vec, } fn main() { @@ -123,7 +125,11 @@ fn main() { } }; - let mut checker = Checker { root: cli.docs.clone(), cache: HashMap::new() }; + let mut checker = Checker { + root: cli.docs.clone(), + link_targets_dirs: cli.link_targets_dirs, + cache: HashMap::new(), + }; let mut report = Report { errors: 0, start: Instant::now(), @@ -144,12 +150,13 @@ fn main() { } fn parse_cli() -> Result { - fn to_canonical_path(arg: &str) -> Result { - PathBuf::from(arg).canonicalize().map_err(|e| format!("could not canonicalize {arg}: {e}")) + fn to_absolute_path(arg: &str) -> Result { + std::path::absolute(arg).map_err(|e| format!("could not convert to absolute {arg}: {e}")) } let mut verbatim = false; let mut docs = None; + let mut link_targets_dirs = Vec::new(); let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -157,6 +164,12 @@ fn parse_cli() -> Result { verbatim = true; } else if !verbatim && (arg == "-h" || arg == "--help") { usage_and_exit(0) + } else if !verbatim && arg == "--link-targets-dir" { + link_targets_dirs.push(to_absolute_path( + &args.next().ok_or("missing value for --link-targets-dir")?, + )?); + } else if !verbatim && let Some(value) = arg.strip_prefix("--link-targets-dir=") { + link_targets_dirs.push(to_absolute_path(value)?); } else if !verbatim && arg.starts_with('-') { return Err(format!("unknown flag: {arg}")); } else if docs.is_none() { @@ -166,16 +179,20 @@ fn parse_cli() -> Result { } } - Ok(Cli { docs: to_canonical_path(&docs.ok_or("missing first positional argument")?)? }) + Ok(Cli { + docs: to_absolute_path(&docs.ok_or("missing first positional argument")?)?, + link_targets_dirs, + }) } fn usage_and_exit(code: i32) -> ! { - eprintln!("usage: linkchecker "); + eprintln!("usage: linkchecker PATH [--link-targets-dir=PATH ...]"); std::process::exit(code) } struct Checker { root: PathBuf, + link_targets_dirs: Vec, cache: Cache, } @@ -461,37 +478,34 @@ impl Checker { /// Load a file from disk, or from the cache if available. fn load_file(&mut self, file: &Path, report: &mut Report) -> (String, &FileEntry) { - // https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499- - #[cfg(windows)] - const ERROR_INVALID_NAME: i32 = 123; - let pretty_path = file.strip_prefix(&self.root).unwrap_or(file).to_str().unwrap().to_string(); - let entry = - self.cache.entry(pretty_path.clone()).or_insert_with(|| match fs::metadata(file) { + for base in once(&self.root).chain(self.link_targets_dirs.iter()) { + let entry = self.cache.entry(pretty_path.clone()); + if let Entry::Occupied(e) = &entry + && !matches!(e.get(), FileEntry::Missing) + { + break; + } + + let file = base.join(&pretty_path); + entry.insert_entry(match fs::metadata(&file) { Ok(metadata) if metadata.is_dir() => FileEntry::Dir, Ok(_) => { if file.extension().and_then(|s| s.to_str()) != Some("html") { FileEntry::OtherFile } else { report.html_files += 1; - load_html_file(file, report) + load_html_file(&file, report) } } - Err(e) if e.kind() == ErrorKind::NotFound => FileEntry::Missing, - Err(e) => { - // If a broken intra-doc link contains `::`, on windows, it will cause `ERROR_INVALID_NAME` rather than `NotFound`. - // Explicitly check for that so that the broken link can be allowed in `LINKCHECK_EXCEPTIONS`. - #[cfg(windows)] - if e.raw_os_error() == Some(ERROR_INVALID_NAME) - && file.as_os_str().to_str().map_or(false, |s| s.contains("::")) - { - return FileEntry::Missing; - } - panic!("unexpected read error for {}: {}", file.display(), e); - } + Err(e) if is_not_found_error(&file, &e) => FileEntry::Missing, + Err(e) => panic!("unexpected read error for {}: {}", file.display(), e), }); + } + + let entry = self.cache.get(&pretty_path).unwrap(); (pretty_path, entry) } } @@ -670,3 +684,16 @@ fn parse_ids(ids: &mut HashSet, file: &str, source: &str, report: &mut R ids.insert(encoded); } } + +fn is_not_found_error(path: &Path, error: &std::io::Error) -> bool { + // https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499- + const WINDOWS_ERROR_INVALID_NAME: i32 = 123; + + error.kind() == std::io::ErrorKind::NotFound + // If a broken intra-doc link contains `::`, on windows, it will cause `ERROR_INVALID_NAME` + // rather than `NotFound`. Explicitly check for that so that the broken link can be allowed + // in `LINKCHECK_EXCEPTIONS`. + || (cfg!(windows) + && error.raw_os_error() == Some(WINDOWS_ERROR_INVALID_NAME) + && path.as_os_str().to_str().map_or(false, |s| s.contains("::"))) +} From c340233769438df7299624b2d0de791995245518 Mon Sep 17 00:00:00 2001 From: xonx <119700621+xonx4l@users.noreply.github.com> Date: Mon, 28 Jul 2025 15:05:36 +0530 Subject: [PATCH 222/809] fixed typo chunks->as_chunks --- library/core/src/slice/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 6fe5affc48be..536d6e1e7c30 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -1232,7 +1232,7 @@ impl [T] { /// /// [`chunks`]: slice::chunks /// [`rchunks_exact`]: slice::rchunks_exact - /// [`as_chunks`]: slice::chunks + /// [`as_chunks`]: slice::as_chunks #[stable(feature = "chunks_exact", since = "1.31.0")] #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")] #[inline] From 65589ad33f544003e49cabeb0b76f6b1f0d3ce30 Mon Sep 17 00:00:00 2001 From: Tshepang Mbambo Date: Mon, 28 Jul 2025 11:45:21 +0200 Subject: [PATCH 223/809] 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 68f08c5dd9f5bee706a221df13660cc9b3a71c93 Mon Sep 17 00:00:00 2001 From: Yosh Date: Mon, 21 Jul 2025 03:04:17 +0200 Subject: [PATCH 224/809] Add `core::mem::DropGuard` Fix CI for drop_guard fix CI fix all tidy lints fix tidy link add first batch of feedback from review Add second batch of feedback from review add third batch of feedback from review fix failing test Update library/core/src/mem/drop_guard.rs Co-authored-by: Ruby Lazuli fix doctests Implement changes from T-Libs-API review And start tracking based on the tracking issue. fix tidy lint --- library/core/src/mem/drop_guard.rs | 155 +++++++++++++++++++++++++++++ library/core/src/mem/mod.rs | 4 + library/coretests/tests/lib.rs | 1 + library/coretests/tests/mem.rs | 46 +++++++++ library/std/src/lib.rs | 1 + 5 files changed, 207 insertions(+) create mode 100644 library/core/src/mem/drop_guard.rs diff --git a/library/core/src/mem/drop_guard.rs b/library/core/src/mem/drop_guard.rs new file mode 100644 index 000000000000..47ccb69acc80 --- /dev/null +++ b/library/core/src/mem/drop_guard.rs @@ -0,0 +1,155 @@ +use crate::fmt::{self, Debug}; +use crate::mem::ManuallyDrop; +use crate::ops::{Deref, DerefMut}; + +/// Wrap a value and run a closure when dropped. +/// +/// This is useful for quickly creating desructors inline. +/// +/// # Examples +/// +/// ```rust +/// # #![allow(unused)] +/// #![feature(drop_guard)] +/// +/// use std::mem::DropGuard; +/// +/// { +/// // Create a new guard around a string that will +/// // print its value when dropped. +/// let s = String::from("Chashu likes tuna"); +/// let mut s = DropGuard::new(s, |s| println!("{s}")); +/// +/// // Modify the string contained in the guard. +/// s.push_str("!!!"); +/// +/// // The guard will be dropped here, printing: +/// // "Chashu likes tuna!!!" +/// } +/// ``` +#[unstable(feature = "drop_guard", issue = "144426")] +#[doc(alias = "ScopeGuard")] +#[doc(alias = "defer")] +pub struct DropGuard +where + F: FnOnce(T), +{ + inner: ManuallyDrop, + f: ManuallyDrop, +} + +impl DropGuard +where + F: FnOnce(T), +{ + /// Create a new instance of `DropGuard`. + /// + /// # Example + /// + /// ```rust + /// # #![allow(unused)] + /// #![feature(drop_guard)] + /// + /// use std::mem::DropGuard; + /// + /// let value = String::from("Chashu likes tuna"); + /// let guard = DropGuard::new(value, |s| println!("{s}")); + /// ``` + #[unstable(feature = "drop_guard", issue = "144426")] + #[must_use] + pub const fn new(inner: T, f: F) -> Self { + Self { inner: ManuallyDrop::new(inner), f: ManuallyDrop::new(f) } + } + + /// Consumes the `DropGuard`, returning the wrapped value. + /// + /// This will not execute the closure. This is implemented as an associated + /// function to prevent any potential conflicts with any other methods called + /// `into_inner` from the `Deref` and `DerefMut` impls. + /// + /// It is typically preferred to call this function instead of `mem::forget` + /// because it will return the stored value and drop variables captured + /// by the closure instead of leaking their owned resources. + /// + /// # Example + /// + /// ```rust + /// # #![allow(unused)] + /// #![feature(drop_guard)] + /// + /// use std::mem::DropGuard; + /// + /// let value = String::from("Nori likes chicken"); + /// let guard = DropGuard::new(value, |s| println!("{s}")); + /// assert_eq!(DropGuard::into_inner(guard), "Nori likes chicken"); + /// ``` + #[unstable(feature = "drop_guard", issue = "144426")] + #[inline] + pub fn into_inner(guard: Self) -> T { + // First we ensure that dropping the guard will not trigger + // its destructor + let mut guard = ManuallyDrop::new(guard); + + // Next we manually read the stored value from the guard. + // + // SAFETY: this is safe because we've taken ownership of the guard. + let value = unsafe { ManuallyDrop::take(&mut guard.inner) }; + + // Finally we drop the stored closure. We do this *after* having read + // the value, so that even if the closure's `drop` function panics, + // unwinding still tries to drop the value. + // + // SAFETY: this is safe because we've taken ownership of the guard. + unsafe { ManuallyDrop::drop(&mut guard.f) }; + value + } +} + +#[unstable(feature = "drop_guard", issue = "144426")] +impl Deref for DropGuard +where + F: FnOnce(T), +{ + type Target = T; + + fn deref(&self) -> &T { + &*self.inner + } +} + +#[unstable(feature = "drop_guard", issue = "144426")] +impl DerefMut for DropGuard +where + F: FnOnce(T), +{ + fn deref_mut(&mut self) -> &mut T { + &mut *self.inner + } +} + +#[unstable(feature = "drop_guard", issue = "144426")] +impl Drop for DropGuard +where + F: FnOnce(T), +{ + fn drop(&mut self) { + // SAFETY: `DropGuard` is in the process of being dropped. + let inner = unsafe { ManuallyDrop::take(&mut self.inner) }; + + // SAFETY: `DropGuard` is in the process of being dropped. + let f = unsafe { ManuallyDrop::take(&mut self.f) }; + + f(inner); + } +} + +#[unstable(feature = "drop_guard", issue = "144426")] +impl Debug for DropGuard +where + T: Debug, + F: FnOnce(T), +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index 2198d098c4be..fcb9f25ede2f 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -21,6 +21,10 @@ mod transmutability; #[unstable(feature = "transmutability", issue = "99571")] pub use transmutability::{Assume, TransmuteFrom}; +mod drop_guard; +#[unstable(feature = "drop_guard", issue = "144426")] +pub use drop_guard::DropGuard; + // This one has to be a re-export (rather than wrapping the underlying intrinsic) so that we can do // the special magic "types have equal size" check at the call site. #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 4cfac9ecc2ab..c8f516f0a955 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -30,6 +30,7 @@ #![feature(core_private_diy_float)] #![feature(cstr_display)] #![feature(dec2flt)] +#![feature(drop_guard)] #![feature(duration_constants)] #![feature(duration_constructors)] #![feature(duration_constructors_lite)] diff --git a/library/coretests/tests/mem.rs b/library/coretests/tests/mem.rs index 9c15be4a8c4b..e896c61ef488 100644 --- a/library/coretests/tests/mem.rs +++ b/library/coretests/tests/mem.rs @@ -1,5 +1,6 @@ use core::mem::*; use core::{array, ptr}; +use std::cell::Cell; #[cfg(panic = "unwind")] use std::rc::Rc; @@ -795,3 +796,48 @@ fn const_maybe_uninit_zeroed() { assert_eq!(unsafe { (*UNINIT.0.cast::<[[u8; SIZE]; 1]>())[0] }, [0u8; SIZE]); } + +#[test] +fn drop_guards_only_dropped_by_closure_when_run() { + let value_drops = Cell::new(0); + let value = DropGuard::new((), |()| value_drops.set(1 + value_drops.get())); + let closure_drops = Cell::new(0); + let guard = DropGuard::new(value, |_| closure_drops.set(1 + closure_drops.get())); + assert_eq!(value_drops.get(), 0); + assert_eq!(closure_drops.get(), 0); + drop(guard); + assert_eq!(value_drops.get(), 1); + assert_eq!(closure_drops.get(), 1); +} + +#[test] +fn drop_guard_into_inner() { + let dropped = Cell::new(false); + let value = DropGuard::new(42, |_| dropped.set(true)); + let guard = DropGuard::new(value, |_| dropped.set(true)); + let inner = DropGuard::into_inner(guard); + assert_eq!(dropped.get(), false); + assert_eq!(*inner, 42); +} + +#[test] +#[cfg(panic = "unwind")] +fn drop_guard_always_drops_value_if_closure_drop_unwinds() { + // Create a value with a destructor, which we will validate ran successfully. + let mut value_was_dropped = false; + let value_with_tracked_destruction = DropGuard::new((), |_| value_was_dropped = true); + + // Create a closure that will begin unwinding when dropped. + let drop_bomb = DropGuard::new((), |_| panic!()); + let closure_that_panics_on_drop = move |_| { + let _drop_bomb = drop_bomb; + }; + + // This will run the closure, which will panic when dropped. This should + // run the destructor of the value we passed, which we validate. + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let guard = DropGuard::new(value_with_tracked_destruction, closure_that_panics_on_drop); + DropGuard::into_inner(guard); + })); + assert!(value_was_dropped); +} diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 323742a75b05..1b1e85cfc2fe 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -331,6 +331,7 @@ #![feature(clone_to_uninit)] #![feature(core_intrinsics)] #![feature(core_io_borrowed_buf)] +#![feature(drop_guard)] #![feature(duration_constants)] #![feature(error_generic_member_access)] #![feature(error_iter)] From 45b0c8d03e627d55f814a4cd03b90c5068664ac8 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Thu, 24 Jul 2025 08:07:56 +0000 Subject: [PATCH 225/809] Add regression test --- tests/ui/enum-discriminant/wrapping_niche.rs | 24 ++ .../enum-discriminant/wrapping_niche.stderr | 229 ++++++++++++++++++ 2 files changed, 253 insertions(+) create mode 100644 tests/ui/enum-discriminant/wrapping_niche.rs create mode 100644 tests/ui/enum-discriminant/wrapping_niche.stderr diff --git a/tests/ui/enum-discriminant/wrapping_niche.rs b/tests/ui/enum-discriminant/wrapping_niche.rs new file mode 100644 index 000000000000..8097414be687 --- /dev/null +++ b/tests/ui/enum-discriminant/wrapping_niche.rs @@ -0,0 +1,24 @@ +//! Test that we produce the same niche range no +//! matter of signendess if the discriminants are the same. + +#![feature(rustc_attrs)] + +#[repr(u16)] +#[rustc_layout(debug)] +enum UnsignedAroundZero { + //~^ ERROR: layout_of + A = 65535, + B = 0, + C = 1, +} + +#[repr(i16)] +#[rustc_layout(debug)] +enum SignedAroundZero { + //~^ ERROR: layout_of + A = -1, + B = 0, + C = 1, +} + +fn main() {} diff --git a/tests/ui/enum-discriminant/wrapping_niche.stderr b/tests/ui/enum-discriminant/wrapping_niche.stderr new file mode 100644 index 000000000000..76cafa43e905 --- /dev/null +++ b/tests/ui/enum-discriminant/wrapping_niche.stderr @@ -0,0 +1,229 @@ +error: layout_of(UnsignedAroundZero) = Layout { + size: Size(2 bytes), + align: AbiAlign { + abi: Align(2 bytes), + }, + backend_repr: Scalar( + Initialized { + value: Int( + I16, + false, + ), + valid_range: 0..=65535, + }, + ), + fields: Arbitrary { + offsets: [ + Size(0 bytes), + ], + memory_index: [ + 0, + ], + }, + largest_niche: None, + uninhabited: false, + variants: Multiple { + tag: Initialized { + value: Int( + I16, + false, + ), + valid_range: 0..=65535, + }, + tag_encoding: Direct, + tag_field: 0, + variants: [ + Layout { + size: Size(2 bytes), + align: AbiAlign { + abi: Align(2 bytes), + }, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + memory_index: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), + randomization_seed: 9885373149222004003, + }, + Layout { + size: Size(2 bytes), + align: AbiAlign { + abi: Align(2 bytes), + }, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + memory_index: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 1, + }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), + randomization_seed: 9885373149222004003, + }, + Layout { + size: Size(2 bytes), + align: AbiAlign { + abi: Align(2 bytes), + }, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + memory_index: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 2, + }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), + randomization_seed: 9885373149222004003, + }, + ], + }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), + randomization_seed: 2648004449468912780, + } + --> $DIR/wrapping_niche.rs:8:1 + | +LL | enum UnsignedAroundZero { + | ^^^^^^^^^^^^^^^^^^^^^^^ + +error: layout_of(SignedAroundZero) = Layout { + size: Size(2 bytes), + align: AbiAlign { + abi: Align(2 bytes), + }, + backend_repr: Scalar( + Initialized { + value: Int( + I16, + true, + ), + valid_range: (..=1) | (65535..), + }, + ), + fields: Arbitrary { + offsets: [ + Size(0 bytes), + ], + memory_index: [ + 0, + ], + }, + largest_niche: Some( + Niche { + offset: Size(0 bytes), + value: Int( + I16, + true, + ), + valid_range: (..=1) | (65535..), + }, + ), + uninhabited: false, + variants: Multiple { + tag: Initialized { + value: Int( + I16, + true, + ), + valid_range: (..=1) | (65535..), + }, + tag_encoding: Direct, + tag_field: 0, + variants: [ + Layout { + size: Size(2 bytes), + align: AbiAlign { + abi: Align(2 bytes), + }, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + memory_index: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 0, + }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), + randomization_seed: 2684536712112553499, + }, + Layout { + size: Size(2 bytes), + align: AbiAlign { + abi: Align(2 bytes), + }, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + memory_index: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 1, + }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), + randomization_seed: 2684536712112553499, + }, + Layout { + size: Size(2 bytes), + align: AbiAlign { + abi: Align(2 bytes), + }, + backend_repr: Memory { + sized: true, + }, + fields: Arbitrary { + offsets: [], + memory_index: [], + }, + largest_niche: None, + uninhabited: false, + variants: Single { + index: 2, + }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), + randomization_seed: 2684536712112553499, + }, + ], + }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), + randomization_seed: 10738146848450213996, + } + --> $DIR/wrapping_niche.rs:17:1 + | +LL | enum SignedAroundZero { + | ^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + From 91bccd6ba8861fd91bcf0f682f50f78fdb38a450 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Thu, 24 Jul 2025 14:06:58 +0200 Subject: [PATCH 226/809] 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 227/809] 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 228/809] 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 e008fe0c1865e6f307c1e4e6260612837051cb8b Mon Sep 17 00:00:00 2001 From: Kornel Date: Sat, 19 Jul 2025 22:49:06 +0100 Subject: [PATCH 229/809] Avoid redundant lookup in CrateLoader::existing_match --- compiler/rustc_metadata/src/creader.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 438eff330548..6d3dab267ac3 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -511,7 +511,7 @@ impl CStore { // We're also sure to compare *paths*, not actual byte slices. The // `source` stores paths which are normalized which may be different // from the strings on the command line. - let source = self.get_crate_data(cnum).cdata.source(); + let source = data.source(); if let Some(entry) = externs.get(name.as_str()) { // Only use `--extern crate_name=path` here, not `--extern crate_name`. if let Some(mut files) = entry.files() { From 671e083391df7d7ea3b70c8030be578d17b5743b Mon Sep 17 00:00:00 2001 From: Kornel Date: Thu, 3 Jul 2025 13:41:54 +0100 Subject: [PATCH 230/809] Clarify update_extern_crate --- compiler/rustc_metadata/src/rmeta/decoder.rs | 8 +++++-- .../src/rmeta/decoder/cstore_impl.rs | 24 ++++++++++++++++--- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index e6aedc61338b..00c97a2f738e 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -1937,9 +1937,13 @@ impl CrateMetadata { self.root.decode_target_modifiers(&self.blob).collect() } - pub(crate) fn update_extern_crate(&mut self, new_extern_crate: ExternCrate) -> bool { + /// Keep `new_extern_crate` if it looks better in diagnostics + pub(crate) fn update_extern_crate_diagnostics( + &mut self, + new_extern_crate: ExternCrate, + ) -> bool { let update = - Some(new_extern_crate.rank()) > self.extern_crate.as_ref().map(ExternCrate::rank); + self.extern_crate.as_ref().is_none_or(|old| old.rank() < new_extern_crate.rank()); if update { self.extern_crate = Some(new_extern_crate); } diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 57a672c45f7b..989741c004a1 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -627,14 +627,32 @@ impl CStore { } } - pub(crate) fn update_extern_crate(&mut self, cnum: CrateNum, extern_crate: ExternCrate) { + /// Track how an extern crate has been loaded. Called after resolving an import in the local crate. + pub(crate) fn update_extern_crate( + &mut self, + cnum: CrateNum, + extern_crate: ExternCrate, + ) { + debug_assert_eq!( + extern_crate.dependency_of, LOCAL_CRATE, + "this function should not be called on transitive dependencies" + ); + self.update_transitive_extern_crate_diagnostics(cnum, extern_crate); + } + + /// `CrateMetadata` uses `ExternCrate` only for diagnostics + fn update_transitive_extern_crate_diagnostics( + &mut self, + cnum: CrateNum, + extern_crate: ExternCrate, + ) { let cmeta = self.get_crate_data_mut(cnum); - if cmeta.update_extern_crate(extern_crate) { + if cmeta.update_extern_crate_diagnostics(extern_crate) { // Propagate the extern crate info to dependencies if it was updated. let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate }; let dependencies = mem::take(&mut cmeta.dependencies); for &dep_cnum in &dependencies { - self.update_extern_crate(dep_cnum, extern_crate); + self.update_transitive_extern_crate_diagnostics(dep_cnum, extern_crate); } self.get_crate_data_mut(cnum).dependencies = dependencies; } From 8a0f97604777cbdb0ea027e6ca741cc0b13e64c9 Mon Sep 17 00:00:00 2001 From: Kornel Date: Tue, 15 Jul 2025 10:48:17 +0100 Subject: [PATCH 231/809] Save names of used extern crates Tracks association between `self.sess.opts.externs` (aliases in `--extern alias=rlib`) and resolved `CrateNum` Intended to allow Rustdoc match the aliases in `--extern-html-root-url` Force-injected extern crates aren't included, since they're meant for the linker only --- compiler/rustc_metadata/src/creader.rs | 15 +++++++++++++++ .../src/rmeta/decoder/cstore_impl.rs | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 6d3dab267ac3..127a773e5e80 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -12,6 +12,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::owned_slice::OwnedSlice; use rustc_data_structures::svh::Svh; use rustc_data_structures::sync::{self, FreezeReadGuard, FreezeWriteGuard}; +use rustc_data_structures::unord::UnordMap; use rustc_expand::base::SyntaxExtension; use rustc_fs_util::try_canonicalize; use rustc_hir as hir; @@ -69,6 +70,9 @@ pub struct CStore { /// This crate has a `#[alloc_error_handler]` item. has_alloc_error_handler: bool, + /// Names that were used to load the crates via `extern crate` or paths. + resolved_externs: UnordMap, + /// Unused externs of the crate unused_externs: Vec, @@ -249,6 +253,14 @@ impl CStore { self.metas[cnum] = Some(Box::new(data)); } + /// Save the name used to resolve the extern crate in the local crate + /// + /// The name isn't always the crate's own name, because `sess.opts.externs` can assign it another name. + /// It's also not always the same as the `DefId`'s symbol due to renames `extern crate resolved_name as defid_name`. + pub(crate) fn set_resolved_extern_crate_name(&mut self, name: Symbol, extern_crate: CrateNum) { + self.resolved_externs.insert(name, extern_crate); + } + pub(crate) fn iter_crate_data(&self) -> impl Iterator { self.metas .iter_enumerated() @@ -475,6 +487,7 @@ impl CStore { alloc_error_handler_kind: None, has_global_allocator: false, has_alloc_error_handler: false, + resolved_externs: UnordMap::default(), unused_externs: Vec::new(), used_extern_options: Default::default(), } @@ -1308,6 +1321,7 @@ impl CStore { let path_len = definitions.def_path(def_id).data.len(); self.update_extern_crate( cnum, + name, ExternCrate { src: ExternCrateSource::Extern(def_id.to_def_id()), span: item.span, @@ -1332,6 +1346,7 @@ impl CStore { self.update_extern_crate( cnum, + name, ExternCrate { src: ExternCrateSource::Path, span, diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 989741c004a1..9415e420eed5 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -628,15 +628,20 @@ impl CStore { } /// Track how an extern crate has been loaded. Called after resolving an import in the local crate. + /// + /// * the `name` is for [`Self::set_resolved_extern_crate_name`] saving `--extern name=` + /// * `extern_crate` is for diagnostics pub(crate) fn update_extern_crate( &mut self, cnum: CrateNum, + name: Symbol, extern_crate: ExternCrate, ) { debug_assert_eq!( extern_crate.dependency_of, LOCAL_CRATE, "this function should not be called on transitive dependencies" ); + self.set_resolved_extern_crate_name(name, cnum); self.update_transitive_extern_crate_diagnostics(cnum, extern_crate); } From 0813cc9dcf755bb04ef396bfa94218b56bb08c4a Mon Sep 17 00:00:00 2001 From: Kornel Date: Sat, 5 Jul 2025 02:00:57 +0100 Subject: [PATCH 232/809] Test renamed crates in rustdoc --- tests/rustdoc/extern/extern-html-alias.rs | 9 +++++++++ tests/rustdoc/extern/extern-html-fallback.rs | 14 ++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 tests/rustdoc/extern/extern-html-alias.rs create mode 100644 tests/rustdoc/extern/extern-html-fallback.rs diff --git a/tests/rustdoc/extern/extern-html-alias.rs b/tests/rustdoc/extern/extern-html-alias.rs new file mode 100644 index 000000000000..3ff782d3963c --- /dev/null +++ b/tests/rustdoc/extern/extern-html-alias.rs @@ -0,0 +1,9 @@ +//@ compile-flags:-Z unstable-options --extern-html-root-url externs_name=https://renamed.example.com --extern-html-root-url empty=https://bad.invalid +//@ aux-crate:externs_name=empty.rs +//@ edition: 2018 + +extern crate externs_name as renamed; + +//@ has extern_html_alias/index.html +//@ has - '//a/@href' 'https://renamed.example.com/empty/index.html' +pub use renamed as yet_different_name; diff --git a/tests/rustdoc/extern/extern-html-fallback.rs b/tests/rustdoc/extern/extern-html-fallback.rs new file mode 100644 index 000000000000..ddac9bf713c6 --- /dev/null +++ b/tests/rustdoc/extern/extern-html-fallback.rs @@ -0,0 +1,14 @@ +//@ compile-flags:-Z unstable-options --extern-html-root-url yet_another_name=https://bad.invalid --extern-html-root-url renamed_privately=https://bad.invalid --extern-html-root-url renamed_locally=https://bad.invalid --extern-html-root-url empty=https://localhost +//@ aux-crate:externs_name=empty.rs +//@ edition: 2018 + +mod m { + pub extern crate externs_name as renamed_privately; +} + +// renaming within the crate's source code is not supposed to affect CLI flags +extern crate externs_name as renamed_locally; + +//@ has extern_html_fallback/index.html +//@ has - '//a/@href' 'https://localhost/empty/index.html' +pub use crate::renamed_locally as yet_another_name; From 276c4238a7ee0fa472c951f357642778d60a3bdb Mon Sep 17 00:00:00 2001 From: Kornel Date: Thu, 3 Jul 2025 15:13:19 +0100 Subject: [PATCH 233/809] Support multiple crate versions in --extern-html-root-url --- compiler/rustc_metadata/src/creader.rs | 8 +++++++ src/doc/rustdoc/src/unstable-features.md | 6 +++++ src/librustdoc/formats/cache.rs | 30 ++++++++++++++++++------ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 127a773e5e80..6bfb3769f247 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -261,6 +261,14 @@ impl CStore { self.resolved_externs.insert(name, extern_crate); } + /// Crate resolved and loaded via the given extern name + /// (corresponds to names in `sess.opts.externs`) + /// + /// May be `None` if the crate wasn't used + pub fn resolved_extern_crate(&self, externs_name: Symbol) -> Option { + self.resolved_externs.get(&externs_name).copied() + } + pub(crate) fn iter_crate_data(&self) -> impl Iterator { self.metas .iter_enumerated() diff --git a/src/doc/rustdoc/src/unstable-features.md b/src/doc/rustdoc/src/unstable-features.md index 27910ad0ab79..7bd2970eee70 100644 --- a/src/doc/rustdoc/src/unstable-features.md +++ b/src/doc/rustdoc/src/unstable-features.md @@ -395,6 +395,12 @@ flags to control that behavior. When the `--extern-html-root-url` flag is given one of your dependencies, rustdoc use that URL for those docs. Keep in mind that if those docs exist in the output directory, those local docs will still override this flag. +The names in this flag are first matched against the names given in the `--extern name=` flags, +which allows selecting between multiple crates with the same name (e.g. multiple versions of +the same crate). For transitive dependencies that haven't been loaded via an `--extern` flag, matching +falls backs to using crate names only, without ability to distinguish between multiple crates with +the same name. + ## `-Z force-unstable-if-unmarked` Using this flag looks like this: diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index 5191120ebdb0..e28cc3a542e5 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -4,6 +4,7 @@ use rustc_ast::join_path_syms; use rustc_attr_data_structures::StabilityLevel; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet}; +use rustc_metadata::creader::CStore; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::Symbol; use tracing::debug; @@ -158,18 +159,33 @@ impl Cache { assert!(cx.external_traits.is_empty()); cx.cache.traits = mem::take(&mut krate.external_traits); + let render_options = &cx.render_options; + let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence; + let dst = &render_options.output; + + // Make `--extern-html-root-url` support the same names as `--extern` whenever possible + let cstore = CStore::from_tcx(tcx); + for (name, extern_url) in &render_options.extern_html_root_urls { + if let Some(crate_num) = cstore.resolved_extern_crate(Symbol::intern(name)) { + let e = ExternalCrate { crate_num }; + let location = e.location(Some(extern_url), extern_url_takes_precedence, dst, tcx); + cx.cache.extern_locations.insert(e.crate_num, location); + } + } + // Cache where all our extern crates are located - // FIXME: this part is specific to HTML so it'd be nice to remove it from the common code + // This is also used in the JSON output. for &crate_num in tcx.crates(()) { let e = ExternalCrate { crate_num }; let name = e.name(tcx); - let render_options = &cx.render_options; - let extern_url = render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u); - let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence; - let dst = &render_options.output; - let location = e.location(extern_url, extern_url_takes_precedence, dst, tcx); - cx.cache.extern_locations.insert(e.crate_num, location); + cx.cache.extern_locations.entry(e.crate_num).or_insert_with(|| { + // falls back to matching by crates' own names, because + // transitive dependencies and injected crates may be loaded without `--extern` + let extern_url = + render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u); + e.location(extern_url, extern_url_takes_precedence, dst, tcx) + }); cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module)); } From 71920e265caf363ba3408adc2744c0441ef58472 Mon Sep 17 00:00:00 2001 From: usamoi Date: Mon, 28 Jul 2025 20:41:14 +0800 Subject: [PATCH 234/809] fix `Atomic*::as_ptr` wording --- library/core/src/sync/atomic.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 57bea505433d..70c02ead3584 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -1245,8 +1245,8 @@ impl AtomicBool { /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the /// atomic types work with interior mutability. All modifications of an atomic change the value /// through a shared reference, and can do so safely as long as they use atomic operations. Any - /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same - /// restriction in [Memory model for atomic accesses]. + /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the + /// requirements of the [memory model]. /// /// # Examples /// @@ -1265,7 +1265,7 @@ impl AtomicBool { /// # } /// ``` /// - /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses + /// [memory model]: self#memory-model-for-atomic-accesses #[inline] #[stable(feature = "atomic_as_ptr", since = "1.70.0")] #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] @@ -2489,8 +2489,8 @@ impl AtomicPtr { /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the /// atomic types work with interior mutability. All modifications of an atomic change the value /// through a shared reference, and can do so safely as long as they use atomic operations. Any - /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same - /// restriction in [Memory model for atomic accesses]. + /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the + /// requirements of the [memory model]. /// /// # Examples /// @@ -2510,7 +2510,7 @@ impl AtomicPtr { /// } /// ``` /// - /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses + /// [memory model]: self#memory-model-for-atomic-accesses #[inline] #[stable(feature = "atomic_as_ptr", since = "1.70.0")] #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] @@ -3623,8 +3623,8 @@ macro_rules! atomic_int { /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the /// atomic types work with interior mutability. All modifications of an atomic change the value /// through a shared reference, and can do so safely as long as they use atomic operations. Any - /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same - /// restriction in [Memory model for atomic accesses]. + /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the + /// requirements of the [memory model]. /// /// # Examples /// @@ -3645,7 +3645,7 @@ macro_rules! atomic_int { /// # } /// ``` /// - /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses + /// [memory model]: self#memory-model-for-atomic-accesses #[inline] #[stable(feature = "atomic_as_ptr", since = "1.70.0")] #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] From f63f212a043dbc60fc28a4bf845662863d532fd7 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Mon, 28 Jul 2025 18:53:24 +0530 Subject: [PATCH 235/809] use dry_run and verbose directly from exec_ctx --- src/bootstrap/src/core/download.rs | 57 ++++++++++++++---------------- 1 file changed, 27 insertions(+), 30 deletions(-) diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index 745acb04275a..2011e3067c47 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -38,7 +38,7 @@ impl Config { } pub(crate) fn remove(&self, f: &Path) { - remove(self.dry_run(), f); + remove(&self.exec_ctx, f); } /// Create a temporary directory in `out` and return its path. @@ -74,13 +74,13 @@ impl Config { } fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) { - unpack(self.verbose > 0, tarball, dst, pattern); + unpack(&self.exec_ctx, tarball, dst, pattern); } /// Returns whether the SHA256 checksum of `path` matches `expected`. #[cfg(test)] pub(crate) fn verify(&self, path: &Path, expected: &str) -> bool { - verify(self.verbose > 0, self.dry_run(), path, expected) + verify(&self.exec_ctx, path, expected) } } @@ -414,12 +414,10 @@ pub(crate) struct DownloadContext<'a> { out: &'a Path, patch_binaries_for_nix: Option, exec_ctx: &'a ExecutionContext, - verbose: bool, stage0_metadata: &'a build_helper::stage0_parser::Stage0, llvm_assertions: bool, bootstrap_cache_path: &'a Option, is_running_on_ci: bool, - dry_run: bool, } impl<'a> AsRef> for DownloadContext<'a> { @@ -435,12 +433,10 @@ impl<'a> From<&'a Config> for DownloadContext<'a> { out: &value.out, patch_binaries_for_nix: value.patch_binaries_for_nix, exec_ctx: &value.exec_ctx, - verbose: value.verbose > 0, stage0_metadata: &value.stage0_metadata, llvm_assertions: value.llvm_assertions, bootstrap_cache_path: &value.bootstrap_cache_path, is_running_on_ci: value.is_running_on_ci, - dry_run: value.dry_run(), } } } @@ -508,7 +504,7 @@ pub(crate) fn maybe_download_rustfmt<'a>( let dwn_ctx = dwn_ctx.as_ref(); - if dwn_ctx.dry_run { + if dwn_ctx.exec_ctx.dry_run() { return Some(PathBuf::new()); } @@ -563,9 +559,9 @@ pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef(dwn_ctx: impl AsRef>) { let dwn_ctx = dwn_ctx.as_ref(); - if dwn_ctx.verbose { + dwn_ctx.exec_ctx.verbose(|| { println!("downloading stage0 beta artifacts"); - } + }); let date = dwn_ctx.stage0_metadata.compiler.date.clone(); let version = dwn_ctx.stage0_metadata.compiler.version.clone(); @@ -634,8 +630,8 @@ fn download_toolchain<'a>( } } -pub(crate) fn remove(dry_run: bool, f: &Path) { - if dry_run { +pub(crate) fn remove(exec_ctx: &ExecutionContext, f: &Path) { + if exec_ctx.dry_run() { return; } fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}")); @@ -757,7 +753,7 @@ fn download_component<'a>( ) { let dwn_ctx = dwn_ctx.as_ref(); - if dwn_ctx.dry_run { + if dwn_ctx.exec_ctx.dry_run() { return; } @@ -802,22 +798,22 @@ fn download_component<'a>( ); let sha256 = dwn_ctx.stage0_metadata.checksums_sha256.get(&url).expect(&error); if tarball.exists() { - if verify(dwn_ctx.verbose, dwn_ctx.dry_run, &tarball, sha256) { - unpack(dwn_ctx.verbose, &tarball, &bin_root, prefix); + if verify(dwn_ctx.exec_ctx, &tarball, sha256) { + unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix); return; } else { - if dwn_ctx.verbose { + dwn_ctx.exec_ctx.verbose(|| { println!( "ignoring cached file {} due to failed verification", tarball.display() ) - } - remove(dwn_ctx.dry_run, &tarball); + }); + remove(dwn_ctx.exec_ctx, &tarball); } } Some(sha256) } else if tarball.exists() { - unpack(dwn_ctx.verbose, &tarball, &bin_root, prefix); + unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix); return; } else { None @@ -836,22 +832,22 @@ download-rustc = false } download_file(dwn_ctx, &format!("{base_url}/{url}"), &tarball, help_on_error); if let Some(sha256) = checksum - && !verify(dwn_ctx.verbose, dwn_ctx.dry_run, &tarball, sha256) + && !verify(dwn_ctx.exec_ctx, &tarball, sha256) { panic!("failed to verify {}", tarball.display()); } - unpack(dwn_ctx.verbose, &tarball, &bin_root, prefix); + unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix); } -pub(crate) fn verify(verbose: bool, dry_run: bool, path: &Path, expected: &str) -> bool { +pub(crate) fn verify(exec_ctx: &ExecutionContext, path: &Path, expected: &str) -> bool { use sha2::Digest; - if verbose { + exec_ctx.verbose(|| { println!("verifying {}", path.display()); - } + }); - if dry_run { + if exec_ctx.dry_run() { return false; } @@ -885,7 +881,7 @@ pub(crate) fn verify(verbose: bool, dry_run: bool, path: &Path, expected: &str) verified } -fn unpack(verbose: bool, tarball: &Path, dst: &Path, pattern: &str) { +fn unpack(exec_ctx: &ExecutionContext, tarball: &Path, dst: &Path, pattern: &str) { eprintln!("extracting {} to {}", tarball.display(), dst.display()); if !dst.exists() { t!(fs::create_dir_all(dst)); @@ -927,9 +923,10 @@ fn unpack(verbose: bool, tarball: &Path, dst: &Path, pattern: &str) { } short_path = short_path.strip_prefix(pattern).unwrap_or(short_path); let dst_path = dst.join(short_path); - if verbose { + + exec_ctx.verbose(|| { println!("extracting {} to {}", original_path.display(), dst.display()); - } + }); if !t!(member.unpack_in(dst)) { panic!("path traversal attack ??"); @@ -957,9 +954,9 @@ fn download_file<'a>( ) { let dwn_ctx = dwn_ctx.as_ref(); - if dwn_ctx.verbose { + dwn_ctx.exec_ctx.verbose(|| { println!("download {url}"); - } + }); // Use a temporary file in case we crash while downloading, to avoid a corrupt download in cache/. let tempfile = tempdir(dwn_ctx.out).join(dest_path.file_name().unwrap()); // While bootstrap itself only supports http and https downloads, downstream forks might From d87b4f2c77add3404f7469ea72f1d7c51e2a29dc Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Fri, 25 Jul 2025 23:07:13 +0900 Subject: [PATCH 236/809] fix: Reject upvar scrutinees for `loop_match` --- compiler/rustc_mir_build/src/thir/cx/expr.rs | 21 +++-- tests/ui/loop-match/upvar-scrutinee.rs | 81 ++++++++++++++++++++ tests/ui/loop-match/upvar-scrutinee.stderr | 18 +++++ 3 files changed, 113 insertions(+), 7 deletions(-) create mode 100644 tests/ui/loop-match/upvar-scrutinee.rs create mode 100644 tests/ui/loop-match/upvar-scrutinee.stderr diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 33bf4e3e29fb..16df58cd76df 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -955,9 +955,13 @@ impl<'tcx> ThirBuildCx<'tcx> { dcx.emit_fatal(LoopMatchBadRhs { span: block_body_expr.span }) }; - fn local(expr: &rustc_hir::Expr<'_>) -> Option { + fn local( + cx: &mut ThirBuildCx<'_>, + expr: &rustc_hir::Expr<'_>, + ) -> Option { if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind && let Res::Local(hir_id) = path.res + && !cx.is_upvar(hir_id) { return Some(hir_id); } @@ -965,11 +969,11 @@ impl<'tcx> ThirBuildCx<'tcx> { None } - let Some(scrutinee_hir_id) = local(scrutinee) else { + let Some(scrutinee_hir_id) = local(self, scrutinee) else { dcx.emit_fatal(LoopMatchInvalidMatch { span: scrutinee.span }) }; - if local(state) != Some(scrutinee_hir_id) { + if local(self, state) != Some(scrutinee_hir_id) { dcx.emit_fatal(LoopMatchInvalidUpdate { scrutinee: scrutinee.span, lhs: state.span, @@ -1260,10 +1264,7 @@ impl<'tcx> ThirBuildCx<'tcx> { fn convert_var(&mut self, var_hir_id: hir::HirId) -> ExprKind<'tcx> { // We want upvars here not captures. // Captures will be handled in MIR. - let is_upvar = self - .tcx - .upvars_mentioned(self.body_owner) - .is_some_and(|upvars| upvars.contains_key(&var_hir_id)); + let is_upvar = self.is_upvar(var_hir_id); debug!( "convert_var({:?}): is_upvar={}, body_owner={:?}", @@ -1443,6 +1444,12 @@ impl<'tcx> ThirBuildCx<'tcx> { } } + fn is_upvar(&mut self, var_hir_id: hir::HirId) -> bool { + self.tcx + .upvars_mentioned(self.body_owner) + .is_some_and(|upvars| upvars.contains_key(&var_hir_id)) + } + /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExpr. fn field_refs(&mut self, fields: &'tcx [hir::ExprField<'tcx>]) -> Box<[FieldExpr]> { fields diff --git a/tests/ui/loop-match/upvar-scrutinee.rs b/tests/ui/loop-match/upvar-scrutinee.rs new file mode 100644 index 000000000000..a93e3a0e59ab --- /dev/null +++ b/tests/ui/loop-match/upvar-scrutinee.rs @@ -0,0 +1,81 @@ +#![allow(incomplete_features)] +#![feature(loop_match)] + +#[derive(Clone, Copy)] +enum State { + A, + B, +} + +fn main() { + let mut state = State::A; + + #[loop_match] + loop { + state = 'blk: { + match state { + State::A => { + #[const_continue] + break 'blk State::B; + } + State::B => { + return; + } + } + } + } + + || { + #[loop_match] + loop { + state = 'blk: { + match state { + //~^ ERROR invalid match on `#[loop_match]` state + State::A => { + #[const_continue] + break 'blk State::B; + } + State::B => { + return; + } + } + } + } + }; + + || { + let mut state = state; + #[loop_match] + loop { + state = 'blk: { + match state { + State::A => { + #[const_continue] + break 'blk State::B; + } + State::B => { + return; + } + } + } + } + }; + + move || { + #[loop_match] + loop { + state = 'blk: { + match state { + //~^ ERROR invalid match on `#[loop_match]` state + State::A => { + #[const_continue] + break 'blk State::B; + } + State::B => { + return; + } + } + } + } + }; +} diff --git a/tests/ui/loop-match/upvar-scrutinee.stderr b/tests/ui/loop-match/upvar-scrutinee.stderr new file mode 100644 index 000000000000..b7a0a90193d7 --- /dev/null +++ b/tests/ui/loop-match/upvar-scrutinee.stderr @@ -0,0 +1,18 @@ +error: invalid match on `#[loop_match]` state + --> $DIR/upvar-scrutinee.rs:32:23 + | +LL | match state { + | ^^^^^ + | + = note: a local variable must be the scrutinee within a `#[loop_match]` + +error: invalid match on `#[loop_match]` state + --> $DIR/upvar-scrutinee.rs:68:23 + | +LL | match state { + | ^^^^^ + | + = note: a local variable must be the scrutinee within a `#[loop_match]` + +error: aborting due to 2 previous errors + From 18a13b15fe1ebac207eb9efe789dfa717b4c4a97 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 28 Jul 2025 15:20:27 +0200 Subject: [PATCH 237/809] 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 238/809] 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 d409694c74d8e9606d9668e5ee78ce6ac364e4f7 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 28 Jul 2025 15:51:41 +0200 Subject: [PATCH 239/809] lookup_link_section: support arrays of function pointers --- src/tools/miri/src/helpers.rs | 17 +++++++++++++++-- src/tools/miri/tests/pass/shims/ctor.rs | 15 +++++++-------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index 0c96ddf00db4..ab7e35710d34 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -1087,8 +1087,21 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "failed to evaluate static in required link_section: {def_id:?}\n{err:?}" ) }); - let val = this.read_immediate(&const_val)?; - array.push(val); + match const_val.layout.ty.kind() { + ty::FnPtr(..) => { + array.push(this.read_immediate(&const_val)?); + } + ty::Array(elem_ty, _) if matches!(elem_ty.kind(), ty::FnPtr(..)) => { + let mut elems = this.project_array_fields(&const_val)?; + while let Some((_idx, elem)) = elems.next(this)? { + array.push(this.read_immediate(&elem)?); + } + } + _ => + throw_unsup_format!( + "only function pointers and arrays of function pointers are supported in well-known linker sections" + ), + } } interp_ok(()) })?; diff --git a/src/tools/miri/tests/pass/shims/ctor.rs b/src/tools/miri/tests/pass/shims/ctor.rs index b997d2386b82..a0fcdb1081e6 100644 --- a/src/tools/miri/tests/pass/shims/ctor.rs +++ b/src/tools/miri/tests/pass/shims/ctor.rs @@ -2,13 +2,13 @@ use std::sync::atomic::{AtomicUsize, Ordering}; static COUNT: AtomicUsize = AtomicUsize::new(0); -unsafe extern "C" fn ctor() { - COUNT.fetch_add(1, Ordering::Relaxed); +unsafe extern "C" fn ctor() { + COUNT.fetch_add(N, Ordering::Relaxed); } #[rustfmt::skip] macro_rules! ctor { - ($ident:ident = $ctor:ident) => { + ($ident:ident: $ty:ty = $ctor:expr) => { #[cfg_attr( all(any( target_os = "linux", @@ -33,14 +33,13 @@ macro_rules! ctor { link_section = "__DATA,__mod_init_func" )] #[used] - static $ident: unsafe extern "C" fn() = $ctor; + static $ident: $ty = $ctor; }; } -ctor! { CTOR1 = ctor } -ctor! { CTOR2 = ctor } -ctor! { CTOR3 = ctor } +ctor! { CTOR1: unsafe extern "C" fn() = ctor::<1> } +ctor! { CTOR2: [unsafe extern "C" fn(); 2] = [ctor::<2>, ctor::<3>] } fn main() { - assert_eq!(COUNT.load(Ordering::Relaxed), 3, "ctors did not run"); + assert_eq!(COUNT.load(Ordering::Relaxed), 6, "ctors did not run"); } From db42d5b36c804be21efd9c537a5a6771ec1c8201 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Mon, 28 Jul 2025 19:23:04 +0530 Subject: [PATCH 240/809] remove config wrappers of download_toolchain and maybe_download_fmt and during config parsing directly invoke cdownload methods --- src/bootstrap/src/core/config/config.rs | 18 +++++++++++++----- src/bootstrap/src/core/download.rs | 12 ------------ 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 6e04f1154243..90001f9ae318 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -45,7 +45,9 @@ use crate::core::config::{ DebuginfoLevel, DryRun, GccCiMode, LlvmLibunwind, Merge, ReplaceOpt, RustcLto, SplitDebuginfo, StringOrBool, set, threads_from_config, }; -use crate::core::download::is_download_ci_available; +use crate::core::download::{ + DownloadContext, download_beta_toolchain, is_download_ci_available, maybe_download_rustfmt, +}; use crate::utils::channel; use crate::utils::exec::{ExecutionContext, command}; use crate::utils::helpers::{exe, get_host_target}; @@ -801,7 +803,8 @@ impl Config { } rustc } else { - config.download_beta_toolchain(); + let dwn_ctx = DownloadContext::from(&config); + download_beta_toolchain(dwn_ctx); config .out .join(config.host_target) @@ -827,7 +830,8 @@ impl Config { } cargo } else { - config.download_beta_toolchain(); + let dwn_ctx = DownloadContext::from(&config); + download_beta_toolchain(dwn_ctx); config.initial_sysroot.join("bin").join(exe("cargo", config.host_target)) }; @@ -994,8 +998,12 @@ impl Config { config.apply_dist_config(toml.dist); - config.initial_rustfmt = - if let Some(r) = rustfmt { Some(r) } else { config.maybe_download_rustfmt() }; + config.initial_rustfmt = if let Some(r) = rustfmt { + Some(r) + } else { + let dwn_ctx = DownloadContext::from(&config); + maybe_download_rustfmt(dwn_ctx) + }; if matches!(config.lld_mode, LldMode::SelfContained) && !config.lld_enabled diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index 2011e3067c47..7ec6c62a07d0 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -128,13 +128,6 @@ impl Config { cargo_clippy } - /// NOTE: rustfmt is a completely different toolchain than the bootstrap compiler, so it can't - /// reuse target directories or artifacts - pub(crate) fn maybe_download_rustfmt(&self) -> Option { - let dwn_ctx: DownloadContext<'_> = self.into(); - maybe_download_rustfmt(dwn_ctx) - } - pub(crate) fn ci_rust_std_contents(&self) -> Vec { self.ci_component_contents(".rust-std-contents") } @@ -172,11 +165,6 @@ impl Config { ); } - pub(crate) fn download_beta_toolchain(&self) { - let dwn_ctx: DownloadContext<'_> = self.into(); - download_beta_toolchain(dwn_ctx); - } - fn download_toolchain( &self, version: &str, From c56f49dc34f43568122f057d72f3472b3fcd4d8e Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Mon, 28 Jul 2025 17:24:28 +0300 Subject: [PATCH 241/809] expand: Micro-optimize prelude injection Use `splice` to avoid shifting the other items twice. Put `extern crate std;` first so it's already resolved when we resolve `::std::prelude::rust_20XX`. --- compiler/rustc_builtin_macros/src/standard_library_imports.rs | 4 +--- tests/pretty/asm.pp | 4 ++-- tests/pretty/cast-lt.pp | 4 ++-- tests/pretty/dollar-crate.pp | 4 ++-- tests/pretty/expanded-and-path-remap-80832.pp | 4 ++-- tests/pretty/format-args-str-escape.pp | 4 ++-- tests/pretty/hir-delegation.pp | 4 ++-- tests/pretty/hir-fn-params.pp | 4 ++-- tests/pretty/hir-fn-variadic.pp | 4 ++-- tests/pretty/hir-if-else.pp | 4 ++-- tests/pretty/hir-lifetimes.pp | 4 ++-- tests/pretty/hir-pretty-attr.pp | 4 ++-- tests/pretty/hir-pretty-loop.pp | 4 ++-- tests/pretty/hir-struct-expr.pp | 4 ++-- tests/pretty/if-else.pp | 4 ++-- tests/pretty/issue-12590-c.pp | 4 ++-- tests/pretty/issue-4264.pp | 4 ++-- tests/pretty/issue-85089.pp | 4 ++-- tests/pretty/never-pattern.pp | 4 ++-- tests/pretty/pin-ergonomics-hir.pp | 4 ++-- tests/pretty/postfix-match/precedence.pp | 4 ++-- tests/pretty/shebang-at-top.pp | 4 ++-- tests/pretty/tests-are-sorted.pp | 4 ++-- tests/ui/asm/unpretty-expanded.stdout | 4 ++-- .../return-type-notation/unpretty-parenthesized.stdout | 4 ++-- tests/ui/codemap_tests/unicode.expanded.stdout | 4 ++-- tests/ui/const-generics/defaults/pretty-printing-ast.stdout | 4 ++-- tests/ui/deriving/built-in-proc-macro-scope.stdout | 4 ++-- tests/ui/deriving/deriving-all-codegen.stdout | 4 ++-- tests/ui/deriving/deriving-coerce-pointee-expanded.stdout | 4 ++-- tests/ui/deriving/proc-macro-attribute-mixing.stdout | 4 ++-- .../no_ice_for_partial_compiler_runs.stdout | 4 ++-- tests/ui/macros/genercs-in-path-with-prettry-hir.stdout | 4 ++-- .../non-consuming-methods-have-optimized-codegen.stdout | 4 ++-- tests/ui/match/issue-82392.stdout | 4 ++-- tests/ui/proc-macro/meta-macro-hygiene.stdout | 4 ++-- tests/ui/proc-macro/nonterminal-token-hygiene.stdout | 4 ++-- tests/ui/proc-macro/quote/debug.stdout | 4 ++-- tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout | 4 ++-- tests/ui/type-alias-impl-trait/issue-60662.stdout | 4 ++-- tests/ui/unpretty/bad-literal.stdout | 4 ++-- tests/ui/unpretty/debug-fmt-hir.stdout | 4 ++-- tests/ui/unpretty/deprecated-attr.stdout | 4 ++-- tests/ui/unpretty/diagnostic-attr.stdout | 4 ++-- tests/ui/unpretty/exhaustive-asm.expanded.stdout | 4 ++-- tests/ui/unpretty/exhaustive-asm.hir.stdout | 4 ++-- tests/ui/unpretty/exhaustive.expanded.stdout | 4 ++-- tests/ui/unpretty/exhaustive.hir.stdout | 4 ++-- tests/ui/unpretty/flattened-format-args.stdout | 4 ++-- tests/ui/unpretty/interpolation-expanded.stdout | 4 ++-- tests/ui/unpretty/let-else-hir.stdout | 4 ++-- tests/ui/unpretty/self-hir.stdout | 4 ++-- tests/ui/unpretty/unpretty-expr-fn-arg.stdout | 4 ++-- 53 files changed, 105 insertions(+), 107 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/standard_library_imports.rs b/compiler/rustc_builtin_macros/src/standard_library_imports.rs index 682e7c9b17ae..2068b5ca54dd 100644 --- a/compiler/rustc_builtin_macros/src/standard_library_imports.rs +++ b/compiler/rustc_builtin_macros/src/standard_library_imports.rs @@ -47,8 +47,6 @@ pub fn inject( ast::ItemKind::ExternCrate(None, Ident::new(name, ident_span)), ); - krate.items.insert(0, item); - let root = (edition == Edition2015).then_some(kw::PathRoot); let import_path = root @@ -75,6 +73,6 @@ pub fn inject( }), ); - krate.items.insert(0, use_item); + krate.items.splice(0..0, [item, use_item]); krate.items.len() - orig_num_items } diff --git a/tests/pretty/asm.pp b/tests/pretty/asm.pp index e6c9545f51ee..dca28f99a37d 100644 --- a/tests/pretty/asm.pp +++ b/tests/pretty/asm.pp @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-mode:expanded //@ pp-exact:asm.pp //@ only-x86_64 diff --git a/tests/pretty/cast-lt.pp b/tests/pretty/cast-lt.pp index f6155c9d827b..e82636edca7e 100644 --- a/tests/pretty/cast-lt.pp +++ b/tests/pretty/cast-lt.pp @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:expanded //@ pp-exact:cast-lt.pp diff --git a/tests/pretty/dollar-crate.pp b/tests/pretty/dollar-crate.pp index 561a9500aaaa..31a55ec2bdaa 100644 --- a/tests/pretty/dollar-crate.pp +++ b/tests/pretty/dollar-crate.pp @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:expanded //@ pp-exact:dollar-crate.pp diff --git a/tests/pretty/expanded-and-path-remap-80832.pp b/tests/pretty/expanded-and-path-remap-80832.pp index 5b3922bb3294..6206498e4a2b 100644 --- a/tests/pretty/expanded-and-path-remap-80832.pp +++ b/tests/pretty/expanded-and-path-remap-80832.pp @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; // Test for issue 80832 // //@ pretty-mode:expanded diff --git a/tests/pretty/format-args-str-escape.pp b/tests/pretty/format-args-str-escape.pp index 277b608475cf..d0bd7cf0c72a 100644 --- a/tests/pretty/format-args-str-escape.pp +++ b/tests/pretty/format-args-str-escape.pp @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:expanded //@ pp-exact:format-args-str-escape.pp diff --git a/tests/pretty/hir-delegation.pp b/tests/pretty/hir-delegation.pp index c0d724cccb51..f8ad02f2fccc 100644 --- a/tests/pretty/hir-delegation.pp +++ b/tests/pretty/hir-delegation.pp @@ -4,10 +4,10 @@ #![allow(incomplete_features)] #![feature(fn_delegation)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; fn b(e: C) { } diff --git a/tests/pretty/hir-fn-params.pp b/tests/pretty/hir-fn-params.pp index cfb33cc93eba..fb4ea0304e5a 100644 --- a/tests/pretty/hir-fn-params.pp +++ b/tests/pretty/hir-fn-params.pp @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:hir //@ pp-exact:hir-fn-params.pp diff --git a/tests/pretty/hir-fn-variadic.pp b/tests/pretty/hir-fn-variadic.pp index 99919e7fc6b2..c0f5b7069a2d 100644 --- a/tests/pretty/hir-fn-variadic.pp +++ b/tests/pretty/hir-fn-variadic.pp @@ -3,10 +3,10 @@ //@ pp-exact:hir-fn-variadic.pp #![feature(c_variadic)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; extern "C" { unsafe fn foo(x: i32, va1: ...); diff --git a/tests/pretty/hir-if-else.pp b/tests/pretty/hir-if-else.pp index 4bccde663eb5..af5d31b07cb1 100644 --- a/tests/pretty/hir-if-else.pp +++ b/tests/pretty/hir-if-else.pp @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:hir //@ pp-exact:hir-if-else.pp diff --git a/tests/pretty/hir-lifetimes.pp b/tests/pretty/hir-lifetimes.pp index 1bb2f17cdfb4..00c052d3f798 100644 --- a/tests/pretty/hir-lifetimes.pp +++ b/tests/pretty/hir-lifetimes.pp @@ -5,10 +5,10 @@ // This tests the pretty-printing of lifetimes in lots of ways. #![allow(unused)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; struct Foo<'a> { x: &'a u32, diff --git a/tests/pretty/hir-pretty-attr.pp b/tests/pretty/hir-pretty-attr.pp index c780f8e3639f..01bfe2c09547 100644 --- a/tests/pretty/hir-pretty-attr.pp +++ b/tests/pretty/hir-pretty-attr.pp @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:hir //@ pp-exact:hir-pretty-attr.pp diff --git a/tests/pretty/hir-pretty-loop.pp b/tests/pretty/hir-pretty-loop.pp index c07120273c90..a0830c5188ad 100644 --- a/tests/pretty/hir-pretty-loop.pp +++ b/tests/pretty/hir-pretty-loop.pp @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:hir //@ pp-exact:hir-pretty-loop.pp diff --git a/tests/pretty/hir-struct-expr.pp b/tests/pretty/hir-struct-expr.pp index 177eb5e8631f..bb222dc2e5f1 100644 --- a/tests/pretty/hir-struct-expr.pp +++ b/tests/pretty/hir-struct-expr.pp @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:hir //@ pp-exact:hir-struct-expr.pp diff --git a/tests/pretty/if-else.pp b/tests/pretty/if-else.pp index d4ff02c54415..f29b693e571e 100644 --- a/tests/pretty/if-else.pp +++ b/tests/pretty/if-else.pp @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:expanded //@ pp-exact:if-else.pp diff --git a/tests/pretty/issue-12590-c.pp b/tests/pretty/issue-12590-c.pp index 691738a89ed8..0df095b0ee55 100644 --- a/tests/pretty/issue-12590-c.pp +++ b/tests/pretty/issue-12590-c.pp @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:expanded //@ pp-exact:issue-12590-c.pp diff --git a/tests/pretty/issue-4264.pp b/tests/pretty/issue-4264.pp index f4b641335d1d..1344923f4c47 100644 --- a/tests/pretty/issue-4264.pp +++ b/tests/pretty/issue-4264.pp @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-compare-only //@ pretty-mode:hir,typed //@ pp-exact:issue-4264.pp diff --git a/tests/pretty/issue-85089.pp b/tests/pretty/issue-85089.pp index 31c0f90bf27e..28a85bdf4ad8 100644 --- a/tests/pretty/issue-85089.pp +++ b/tests/pretty/issue-85089.pp @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; // Test to print lifetimes on HIR pretty-printing. //@ pretty-compare-only diff --git a/tests/pretty/never-pattern.pp b/tests/pretty/never-pattern.pp index 923ad9b82c7a..1ce332ea5064 100644 --- a/tests/pretty/never-pattern.pp +++ b/tests/pretty/never-pattern.pp @@ -7,10 +7,10 @@ #![allow(incomplete_features)] #![feature(never_patterns)] #![feature(never_type)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; fn f(x: Result) { _ = match x { Ok(x) => x, Err(!) , }; } diff --git a/tests/pretty/pin-ergonomics-hir.pp b/tests/pretty/pin-ergonomics-hir.pp index 58a1c62f712c..beca5988017d 100644 --- a/tests/pretty/pin-ergonomics-hir.pp +++ b/tests/pretty/pin-ergonomics-hir.pp @@ -4,10 +4,10 @@ #![feature(pin_ergonomics)] #![allow(dead_code, incomplete_features)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; use std::pin::Pin; diff --git a/tests/pretty/postfix-match/precedence.pp b/tests/pretty/postfix-match/precedence.pp index 2052b445a2b3..b6ff45daea12 100644 --- a/tests/pretty/postfix-match/precedence.pp +++ b/tests/pretty/postfix-match/precedence.pp @@ -1,10 +1,10 @@ #![feature(prelude_import)] #![no_std] #![feature(postfix_match)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; use std::ops::Add; diff --git a/tests/pretty/shebang-at-top.pp b/tests/pretty/shebang-at-top.pp index a27972526364..197def4a154b 100644 --- a/tests/pretty/shebang-at-top.pp +++ b/tests/pretty/shebang-at-top.pp @@ -1,10 +1,10 @@ #!/usr/bin/env rust #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ pretty-mode:expanded //@ pp-exact:shebang-at-top.pp //@ pretty-compare-only diff --git a/tests/pretty/tests-are-sorted.pp b/tests/pretty/tests-are-sorted.pp index d6a2c0ff9796..9e1566b2eff3 100644 --- a/tests/pretty/tests-are-sorted.pp +++ b/tests/pretty/tests-are-sorted.pp @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: --crate-type=lib --test --remap-path-prefix={{src-base}}/=/the/src/ --remap-path-prefix={{src-base}}\=/the/src/ //@ pretty-compare-only //@ pretty-mode:expanded diff --git a/tests/ui/asm/unpretty-expanded.stdout b/tests/ui/asm/unpretty-expanded.stdout index 7ba1702dfed8..7678f6bc3450 100644 --- a/tests/ui/asm/unpretty-expanded.stdout +++ b/tests/ui/asm/unpretty-expanded.stdout @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ needs-asm-support //@ check-pass //@ compile-flags: -Zunpretty=expanded diff --git a/tests/ui/associated-type-bounds/return-type-notation/unpretty-parenthesized.stdout b/tests/ui/associated-type-bounds/return-type-notation/unpretty-parenthesized.stdout index 87667553837f..7499df5be5da 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/unpretty-parenthesized.stdout +++ b/tests/ui/associated-type-bounds/return-type-notation/unpretty-parenthesized.stdout @@ -1,8 +1,8 @@ #![feature(prelude_import)] -#[prelude_import] -use std::prelude::rust_2021::*; #[macro_use] extern crate std; +#[prelude_import] +use std::prelude::rust_2021::*; //@ edition: 2021 //@ compile-flags: -Zunpretty=expanded //@ check-pass diff --git a/tests/ui/codemap_tests/unicode.expanded.stdout b/tests/ui/codemap_tests/unicode.expanded.stdout index c88035de0449..af375108b478 100644 --- a/tests/ui/codemap_tests/unicode.expanded.stdout +++ b/tests/ui/codemap_tests/unicode.expanded.stdout @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ revisions: normal expanded //@[expanded] check-pass //@[expanded]compile-flags: -Zunpretty=expanded diff --git a/tests/ui/const-generics/defaults/pretty-printing-ast.stdout b/tests/ui/const-generics/defaults/pretty-printing-ast.stdout index b6cb7fa09c88..030fcec9cf2a 100644 --- a/tests/ui/const-generics/defaults/pretty-printing-ast.stdout +++ b/tests/ui/const-generics/defaults/pretty-printing-ast.stdout @@ -6,10 +6,10 @@ //@ edition: 2015 #![crate_type = "lib"] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; trait Foo {} diff --git a/tests/ui/deriving/built-in-proc-macro-scope.stdout b/tests/ui/deriving/built-in-proc-macro-scope.stdout index 2697618ab003..4fbce5edb819 100644 --- a/tests/ui/deriving/built-in-proc-macro-scope.stdout +++ b/tests/ui/deriving/built-in-proc-macro-scope.stdout @@ -6,10 +6,10 @@ //@ edition:2015 #![feature(derive_coerce_pointee)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; #[macro_use] extern crate another_proc_macro; diff --git a/tests/ui/deriving/deriving-all-codegen.stdout b/tests/ui/deriving/deriving-all-codegen.stdout index fa8f249373d3..0e4bfa30257d 100644 --- a/tests/ui/deriving/deriving-all-codegen.stdout +++ b/tests/ui/deriving/deriving-all-codegen.stdout @@ -17,10 +17,10 @@ #![crate_type = "lib"] #![allow(dead_code)] #![allow(deprecated)] -#[prelude_import] -use std::prelude::rust_2021::*; #[macro_use] extern crate std; +#[prelude_import] +use std::prelude::rust_2021::*; // Empty struct. struct Empty; diff --git a/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout b/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout index 84f8e9a3195a..89300a5c6d0c 100644 --- a/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout +++ b/tests/ui/deriving/deriving-coerce-pointee-expanded.stdout @@ -4,10 +4,10 @@ //@ compile-flags: -Zunpretty=expanded //@ edition: 2015 #![feature(derive_coerce_pointee)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; use std::marker::CoercePointee; pub trait MyTrait {} diff --git a/tests/ui/deriving/proc-macro-attribute-mixing.stdout b/tests/ui/deriving/proc-macro-attribute-mixing.stdout index faa9c0218a33..b81110682d68 100644 --- a/tests/ui/deriving/proc-macro-attribute-mixing.stdout +++ b/tests/ui/deriving/proc-macro-attribute-mixing.stdout @@ -12,10 +12,10 @@ //@ edition: 2015 #![feature(derive_coerce_pointee)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; #[macro_use] extern crate another_proc_macro; diff --git a/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.stdout b/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.stdout index d63abea92302..80abac44ca84 100644 --- a/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.stdout +++ b/tests/ui/lint/rfc-2383-lint-reason/no_ice_for_partial_compiler_runs.stdout @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; // This ensures that ICEs like rust#94953 don't happen //@ check-pass //@ compile-flags: -Z unpretty=expanded diff --git a/tests/ui/macros/genercs-in-path-with-prettry-hir.stdout b/tests/ui/macros/genercs-in-path-with-prettry-hir.stdout index 6b0300132b5f..ba93384644d5 100644 --- a/tests/ui/macros/genercs-in-path-with-prettry-hir.stdout +++ b/tests/ui/macros/genercs-in-path-with-prettry-hir.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: -Zunpretty=hir //@ edition: 2015 diff --git a/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout b/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout index 33193c78334c..e29655faabe5 100644 --- a/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout +++ b/tests/ui/macros/rfc-2011-nicer-assert-messages/non-consuming-methods-have-optimized-codegen.stdout @@ -5,10 +5,10 @@ //@ edition: 2015 #![feature(core_intrinsics, generic_assert)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; fn arbitrary_consuming_method_for_demonstration_purposes() { let elem = 1i32; diff --git a/tests/ui/match/issue-82392.stdout b/tests/ui/match/issue-82392.stdout index 3efc964e053b..d7eef0497392 100644 --- a/tests/ui/match/issue-82392.stdout +++ b/tests/ui/match/issue-82392.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; // https://github.com/rust-lang/rust/issues/82329 //@ compile-flags: -Zunpretty=hir,typed //@ check-pass diff --git a/tests/ui/proc-macro/meta-macro-hygiene.stdout b/tests/ui/proc-macro/meta-macro-hygiene.stdout index 91d16eca1b0a..452598c372c1 100644 --- a/tests/ui/proc-macro/meta-macro-hygiene.stdout +++ b/tests/ui/proc-macro/meta-macro-hygiene.stdout @@ -16,10 +16,10 @@ Respanned: TokenStream [Ident { ident: "$crate", span: $DIR/auxiliary/make-macro // in the stdout #![no_std /* 0#0 */] -#[prelude_import /* 0#1 */] -use core /* 0#1 */::prelude /* 0#1 */::rust_2018 /* 0#1 */::*; #[macro_use /* 0#1 */] extern crate core /* 0#1 */; +#[prelude_import /* 0#1 */] +use core /* 0#1 */::prelude /* 0#1 */::rust_2018 /* 0#1 */::*; // Don't load unnecessary hygiene information from std extern crate std /* 0#0 */; diff --git a/tests/ui/proc-macro/nonterminal-token-hygiene.stdout b/tests/ui/proc-macro/nonterminal-token-hygiene.stdout index 63741326e341..e10a5199f179 100644 --- a/tests/ui/proc-macro/nonterminal-token-hygiene.stdout +++ b/tests/ui/proc-macro/nonterminal-token-hygiene.stdout @@ -36,10 +36,10 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ #![feature /* 0#0 */(decl_macro)] #![no_std /* 0#0 */] -#[prelude_import /* 0#1 */] -use ::core /* 0#1 */::prelude /* 0#1 */::rust_2015 /* 0#1 */::*; #[macro_use /* 0#1 */] extern crate core /* 0#2 */; +#[prelude_import /* 0#1 */] +use ::core /* 0#1 */::prelude /* 0#1 */::rust_2015 /* 0#1 */::*; // Don't load unnecessary hygiene information from std extern crate std /* 0#0 */; diff --git a/tests/ui/proc-macro/quote/debug.stdout b/tests/ui/proc-macro/quote/debug.stdout index 3acb472d9c0f..77c52f02a33c 100644 --- a/tests/ui/proc-macro/quote/debug.stdout +++ b/tests/ui/proc-macro/quote/debug.stdout @@ -12,10 +12,10 @@ #![feature(proc_macro_quote)] #![crate_type = "proc-macro"] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; extern crate proc_macro; diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout b/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout index e2e45ae94ea6..66ba726fb9a4 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/ast-pretty-check.stdout @@ -1,9 +1,9 @@ #![feature(prelude_import)] #![no_std] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ check-pass //@ compile-flags: -Z unpretty=expanded //@ edition: 2015 diff --git a/tests/ui/type-alias-impl-trait/issue-60662.stdout b/tests/ui/type-alias-impl-trait/issue-60662.stdout index 52152a73affe..7ad29c88bcfe 100644 --- a/tests/ui/type-alias-impl-trait/issue-60662.stdout +++ b/tests/ui/type-alias-impl-trait/issue-60662.stdout @@ -3,10 +3,10 @@ //@ edition: 2015 #![feature(type_alias_impl_trait)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; trait Animal { } diff --git a/tests/ui/unpretty/bad-literal.stdout b/tests/ui/unpretty/bad-literal.stdout index ba8467359cd6..1f697aff27c9 100644 --- a/tests/ui/unpretty/bad-literal.stdout +++ b/tests/ui/unpretty/bad-literal.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: -Zunpretty=hir //@ check-fail //@ edition: 2015 diff --git a/tests/ui/unpretty/debug-fmt-hir.stdout b/tests/ui/unpretty/debug-fmt-hir.stdout index 1d224c9e91ff..9c79421e32ab 100644 --- a/tests/ui/unpretty/debug-fmt-hir.stdout +++ b/tests/ui/unpretty/debug-fmt-hir.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: -Zunpretty=hir //@ check-pass //@ edition: 2015 diff --git a/tests/ui/unpretty/deprecated-attr.stdout b/tests/ui/unpretty/deprecated-attr.stdout index 0abeef6f61e0..26cc74c11604 100644 --- a/tests/ui/unpretty/deprecated-attr.stdout +++ b/tests/ui/unpretty/deprecated-attr.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: -Zunpretty=hir //@ check-pass //@ edition: 2015 diff --git a/tests/ui/unpretty/diagnostic-attr.stdout b/tests/ui/unpretty/diagnostic-attr.stdout index a1325c61ca73..4822cf4700b9 100644 --- a/tests/ui/unpretty/diagnostic-attr.stdout +++ b/tests/ui/unpretty/diagnostic-attr.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: -Zunpretty=hir //@ check-pass //@ edition: 2015 diff --git a/tests/ui/unpretty/exhaustive-asm.expanded.stdout b/tests/ui/unpretty/exhaustive-asm.expanded.stdout index 92829b0ab15b..9a58e4c2877b 100644 --- a/tests/ui/unpretty/exhaustive-asm.expanded.stdout +++ b/tests/ui/unpretty/exhaustive-asm.expanded.stdout @@ -1,8 +1,8 @@ #![feature(prelude_import)] -#[prelude_import] -use std::prelude::rust_2024::*; #[macro_use] extern crate std; +#[prelude_import] +use std::prelude::rust_2024::*; //@ revisions: expanded hir //@[expanded]compile-flags: -Zunpretty=expanded //@[expanded]check-pass diff --git a/tests/ui/unpretty/exhaustive-asm.hir.stdout b/tests/ui/unpretty/exhaustive-asm.hir.stdout index bbd846a88454..b33b38c2caba 100644 --- a/tests/ui/unpretty/exhaustive-asm.hir.stdout +++ b/tests/ui/unpretty/exhaustive-asm.hir.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use std::prelude::rust_2024::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use std::prelude::rust_2024::*; //@ revisions: expanded hir //@[expanded]compile-flags: -Zunpretty=expanded //@[expanded]check-pass diff --git a/tests/ui/unpretty/exhaustive.expanded.stdout b/tests/ui/unpretty/exhaustive.expanded.stdout index 53ca3c8e3915..6b08f3e1cd76 100644 --- a/tests/ui/unpretty/exhaustive.expanded.stdout +++ b/tests/ui/unpretty/exhaustive.expanded.stdout @@ -29,10 +29,10 @@ #![feature(try_blocks)] #![feature(yeet_expr)] #![allow(incomplete_features)] -#[prelude_import] -use std::prelude::rust_2024::*; #[macro_use] extern crate std; +#[prelude_import] +use std::prelude::rust_2024::*; #[prelude_import] use self::prelude::*; diff --git a/tests/ui/unpretty/exhaustive.hir.stdout b/tests/ui/unpretty/exhaustive.hir.stdout index 77807728c9d3..9cfa65f58012 100644 --- a/tests/ui/unpretty/exhaustive.hir.stdout +++ b/tests/ui/unpretty/exhaustive.hir.stdout @@ -28,10 +28,10 @@ #![feature(try_blocks)] #![feature(yeet_expr)] #![allow(incomplete_features)] -#[prelude_import] -use std::prelude::rust_2024::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use std::prelude::rust_2024::*; #[prelude_import] use self::prelude::*; diff --git a/tests/ui/unpretty/flattened-format-args.stdout b/tests/ui/unpretty/flattened-format-args.stdout index 3cd027346655..0792dc10e946 100644 --- a/tests/ui/unpretty/flattened-format-args.stdout +++ b/tests/ui/unpretty/flattened-format-args.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: -Zunpretty=hir -Zflatten-format-args=yes //@ check-pass //@ edition: 2015 diff --git a/tests/ui/unpretty/interpolation-expanded.stdout b/tests/ui/unpretty/interpolation-expanded.stdout index d46b46b67f41..7284a89e7a9b 100644 --- a/tests/ui/unpretty/interpolation-expanded.stdout +++ b/tests/ui/unpretty/interpolation-expanded.stdout @@ -10,10 +10,10 @@ // synthesizing parentheses indiscriminately; only where necessary. #![feature(if_let_guard)] -#[prelude_import] -use std::prelude::rust_2024::*; #[macro_use] extern crate std; +#[prelude_import] +use std::prelude::rust_2024::*; macro_rules! expr { ($expr:expr) => { $expr }; } diff --git a/tests/ui/unpretty/let-else-hir.stdout b/tests/ui/unpretty/let-else-hir.stdout index a83790d8bee5..14270a572027 100644 --- a/tests/ui/unpretty/let-else-hir.stdout +++ b/tests/ui/unpretty/let-else-hir.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: -Zunpretty=hir //@ check-pass //@ edition: 2015 diff --git a/tests/ui/unpretty/self-hir.stdout b/tests/ui/unpretty/self-hir.stdout index 1eafc3c8b46b..b190565dcc47 100644 --- a/tests/ui/unpretty/self-hir.stdout +++ b/tests/ui/unpretty/self-hir.stdout @@ -1,7 +1,7 @@ -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; //@ compile-flags: -Zunpretty=hir //@ check-pass //@ edition: 2015 diff --git a/tests/ui/unpretty/unpretty-expr-fn-arg.stdout b/tests/ui/unpretty/unpretty-expr-fn-arg.stdout index e9fd2222a8d2..c04909a73613 100644 --- a/tests/ui/unpretty/unpretty-expr-fn-arg.stdout +++ b/tests/ui/unpretty/unpretty-expr-fn-arg.stdout @@ -8,10 +8,10 @@ //@ compile-flags: -Zunpretty=hir,typed //@ edition: 2015 #![allow(dead_code)] -#[prelude_import] -use ::std::prelude::rust_2015::*; #[attr = MacroUse {arguments: UseAll}] extern crate std; +#[prelude_import] +use ::std::prelude::rust_2015::*; fn main() ({ } as ()) From 96aca2b442f42684f2deeaf2be560e9548864363 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 16:40:38 -0500 Subject: [PATCH 242/809] Remove TraitAlias from trait_of_item This is dead code. --- compiler/rustc_middle/src/ty/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 4c95f0748d32..2e1be6e322f8 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1994,7 +1994,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn trait_of_item(self, def_id: DefId) -> Option { if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) { let parent = self.parent(def_id); - if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) { + if let DefKind::Trait = self.def_kind(parent) { return Some(parent); } } From 0d7abc8df083296c29e0fb816c1c4b10e4cf6577 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 18:34:17 -0500 Subject: [PATCH 243/809] Introduce assoc_parent --- compiler/rustc_hir/src/def.rs | 4 ++++ compiler/rustc_middle/src/ty/mod.rs | 21 +++++++-------------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index ca57c4f31641..3fee9af01b36 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -295,6 +295,10 @@ impl DefKind { } } + pub fn is_assoc(self) -> bool { + matches!(self, DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy) + } + /// This is a "module" in name resolution sense. #[inline] pub fn is_module_like(self) -> bool { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2e1be6e322f8..556065577700 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1988,29 +1988,22 @@ impl<'tcx> TyCtxt<'tcx> { self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id) } + /// If the given `DefId` is an associated item, returns the `DefId` of the parent trait or impl. + pub fn assoc_parent(self, def_id: DefId) -> Option { + self.def_kind(def_id).is_assoc().then(|| self.parent(def_id)) + } + /// If the given `DefId` describes an item belonging to a trait, /// returns the `DefId` of the trait that the trait item belongs to; /// otherwise, returns `None`. pub fn trait_of_item(self, def_id: DefId) -> Option { - if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) { - let parent = self.parent(def_id); - if let DefKind::Trait = self.def_kind(parent) { - return Some(parent); - } - } - None + self.assoc_parent(def_id).filter(|id| self.def_kind(id) == DefKind::Trait) } /// If the given `DefId` describes a method belonging to an impl, returns the /// `DefId` of the impl that the method belongs to; otherwise, returns `None`. pub fn impl_of_method(self, def_id: DefId) -> Option { - if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) { - let parent = self.parent(def_id); - if let DefKind::Impl { .. } = self.def_kind(parent) { - return Some(parent); - } - } - None + self.assoc_parent(def_id).filter(|id| matches!(self.def_kind(id), DefKind::Impl { .. })) } pub fn is_exportable(self, def_id: DefId) -> bool { From 172af038a733020ec487d57a593ddb27ce16c325 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 19:05:31 -0500 Subject: [PATCH 244/809] Rename trait_of_item -> trait_of_assoc --- .../rustc_borrowck/src/diagnostics/conflict_errors.rs | 2 +- compiler/rustc_borrowck/src/diagnostics/mod.rs | 2 +- compiler/rustc_const_eval/src/check_consts/check.rs | 2 +- compiler/rustc_const_eval/src/check_consts/qualifs.rs | 2 +- compiler/rustc_const_eval/src/interpret/call.rs | 2 +- .../src/errors/wrong_number_of_generic_args.rs | 2 +- compiler/rustc_hir_typeck/src/fallback.rs | 2 +- compiler/rustc_lint/src/noop_method_call.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 4 ++-- compiler/rustc_mir_transform/src/check_call_recursion.rs | 2 +- compiler/rustc_mir_transform/src/shim.rs | 2 +- compiler/rustc_monomorphize/src/partitioning.rs | 2 +- compiler/rustc_passes/src/dead.rs | 2 +- .../src/cfi/typeid/itanium_cxx_abi/transform.rs | 6 +++--- .../src/error_reporting/infer/need_type_info.rs | 2 +- .../src/error_reporting/traits/ambiguity.rs | 2 +- .../src/error_reporting/traits/suggestions.rs | 2 +- compiler/rustc_trait_selection/src/traits/mod.rs | 2 +- compiler/rustc_trait_selection/src/traits/project.rs | 2 +- compiler/rustc_ty_utils/src/instance.rs | 2 +- src/tools/clippy/clippy_lints/src/dereference.rs | 2 +- .../clippy/clippy_lints/src/loops/needless_range_loop.rs | 2 +- .../clippy/clippy_lints/src/methods/clone_on_copy.rs | 2 +- .../clippy_lints/src/methods/iter_overeager_cloned.rs | 4 ++-- .../clippy/clippy_lints/src/methods/manual_str_repeat.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/map_clone.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/open_options.rs | 2 +- src/tools/clippy/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/clippy_lints/src/methods/useless_asref.rs | 2 +- src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs | 2 +- src/tools/clippy/clippy_lints/src/ranges.rs | 2 +- .../clippy/clippy_lints/src/unconditional_recursion.rs | 8 ++++---- src/tools/clippy/clippy_lints/src/unused_io_amount.rs | 2 +- src/tools/clippy/clippy_utils/src/lib.rs | 4 ++-- src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs | 2 +- 37 files changed, 47 insertions(+), 47 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index bfe806e8901f..be8b3f0bc1e3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -2384,7 +2384,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { if let Some(body_expr) = finder.body_expr && let Some(loop_span) = finder.loop_span && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id) - && let Some(trait_did) = tcx.trait_of_item(def_id) + && let Some(trait_did) = tcx.trait_of_assoc(def_id) && tcx.is_diagnostic_item(sym::Iterator, trait_did) { if let Some(loop_bind) = finder.loop_bind { diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index ed4cd52ed9c8..56fdaf1c724a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -938,7 +938,7 @@ impl<'tcx> BorrowedContentSource<'tcx> { fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option { match *func.kind() { ty::FnDef(def_id, args) => { - let trait_id = tcx.trait_of_item(def_id)?; + let trait_id = tcx.trait_of_assoc(def_id)?; if tcx.is_lang_item(trait_id, LangItem::Deref) || tcx.is_lang_item(trait_id, LangItem::DerefMut) diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 69637cadcc99..44e5d1d5ee7e 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -784,7 +784,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { self.revalidate_conditional_constness(callee, fn_args, *fn_span); // Attempting to call a trait method? - if let Some(trait_did) = tcx.trait_of_item(callee) { + if let Some(trait_did) = tcx.trait_of_assoc(callee) { // We can't determine the actual callee here, so we have to do different checks // than usual. diff --git a/compiler/rustc_const_eval/src/check_consts/qualifs.rs b/compiler/rustc_const_eval/src/check_consts/qualifs.rs index 166491b47a1f..faf41f1658b7 100644 --- a/compiler/rustc_const_eval/src/check_consts/qualifs.rs +++ b/compiler/rustc_const_eval/src/check_consts/qualifs.rs @@ -369,7 +369,7 @@ where assert!(promoted.is_none() || Q::ALLOW_PROMOTED); // Don't peek inside trait associated constants. - if promoted.is_none() && cx.tcx.trait_of_item(def).is_none() { + if promoted.is_none() && cx.tcx.trait_of_assoc(def).is_none() { let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def); if !Q::in_qualifs(&qualifs) { diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index bda00ea2fb88..5b3adba02659 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -725,7 +725,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ) { let tcx = *self.tcx; - let trait_def_id = tcx.trait_of_item(def_id).unwrap(); + let trait_def_id = tcx.trait_of_assoc(def_id).unwrap(); let virtual_trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, virtual_instance.args); let existential_trait_ref = ty::ExistentialTraitRef::erase_self_ty(tcx, virtual_trait_ref); let concrete_trait_ref = existential_trait_ref.with_self_ty(tcx, dyn_ty); diff --git a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs index 2d60c9561a98..835f8e8cdaee 100644 --- a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs @@ -759,7 +759,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { &self, err: &mut Diag<'_, impl EmissionGuarantee>, ) { - let trait_ = match self.tcx.trait_of_item(self.def_id) { + let trait_ = match self.tcx.trait_of_assoc(self.def_id) { Some(def_id) => def_id, None => return, }; diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 759b5d9550c0..9406697dfed6 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -694,7 +694,7 @@ impl<'tcx> Visitor<'tcx> for AnnotateUnitFallbackVisitor<'_, 'tcx> { // i.e. changing `Default::default()` to `<() as Default>::default()`. if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind && let Res::Def(DefKind::AssocFn, def_id) = path.res - && self.fcx.tcx.trait_of_item(def_id).is_some() + && self.fcx.tcx.trait_of_assoc(def_id).is_some() && let Some(args) = self.fcx.typeck_results.borrow().node_args_opt(expr.hir_id) && let self_ty = args.type_at(0) && let Some(vid) = self.fcx.root_vid(self_ty) diff --git a/compiler/rustc_lint/src/noop_method_call.rs b/compiler/rustc_lint/src/noop_method_call.rs index b7835e6c36ab..24682c4562a0 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -84,7 +84,7 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { return; }; - let Some(trait_id) = cx.tcx.trait_of_item(did) else { return }; + let Some(trait_id) = cx.tcx.trait_of_assoc(did) else { return }; let Some(trait_) = cx.tcx.get_diagnostic_name(trait_id) else { return }; diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 556065577700..2e4bad290d7d 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1996,7 +1996,7 @@ impl<'tcx> TyCtxt<'tcx> { /// If the given `DefId` describes an item belonging to a trait, /// returns the `DefId` of the trait that the trait item belongs to; /// otherwise, returns `None`. - pub fn trait_of_item(self, def_id: DefId) -> Option { + pub fn trait_of_assoc(self, def_id: DefId) -> Option { self.assoc_parent(def_id).filter(|id| self.def_kind(id) == DefKind::Trait) } @@ -2174,7 +2174,7 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn is_const_default_method(self, def_id: DefId) -> bool { - matches!(self.trait_of_item(def_id), Some(trait_id) if self.is_const_trait(trait_id)) + matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id)) } pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool { diff --git a/compiler/rustc_mir_transform/src/check_call_recursion.rs b/compiler/rustc_mir_transform/src/check_call_recursion.rs index cace4cd6bba5..dccfcc52b463 100644 --- a/compiler/rustc_mir_transform/src/check_call_recursion.rs +++ b/compiler/rustc_mir_transform/src/check_call_recursion.rs @@ -21,7 +21,7 @@ impl<'tcx> MirLint<'tcx> for CheckCallRecursion { if let DefKind::Fn | DefKind::AssocFn = tcx.def_kind(def_id) { // If this is trait/impl method, extract the trait's args. - let trait_args = match tcx.trait_of_item(def_id.to_def_id()) { + let trait_args = match tcx.trait_of_assoc(def_id.to_def_id()) { Some(trait_def_id) => { let trait_args_count = tcx.generics_of(trait_def_id).count(); &GenericArgs::identity_for_item(tcx, def_id)[..trait_args_count] diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 6c65b072bec0..c687036f544d 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -75,7 +75,7 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceKind<'tcx>) -> Body< build_call_shim(tcx, instance, Some(adjustment), CallKind::Direct(def_id)) } ty::InstanceKind::FnPtrShim(def_id, ty) => { - let trait_ = tcx.trait_of_item(def_id).unwrap(); + let trait_ = tcx.trait_of_assoc(def_id).unwrap(); // Supports `Fn` or `async Fn` traits. let adjustment = match tcx .fn_trait_kind_from_def_id(trait_) diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index f3e7d582781d..9f5807070a7b 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -650,7 +650,7 @@ fn characteristic_def_id_of_mono_item<'tcx>( // its self-type. If the self-type does not provide a characteristic // DefId, we use the location of the impl after all. - if tcx.trait_of_item(def_id).is_some() { + if tcx.trait_of_assoc(def_id).is_some() { let self_ty = instance.args.type_at(0); // This is a default implementation of a trait method. return characteristic_def_id_of_type(self_ty).or(Some(def_id)); diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index d987041fe0e0..ae379d53ad12 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -429,7 +429,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { Node::TraitItem(trait_item) => { // mark the trait live let trait_item_id = trait_item.owner_id.to_def_id(); - if let Some(trait_id) = self.tcx.trait_of_item(trait_item_id) { + if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) { self.check_def_id(trait_id); } intravisit::walk_trait_item(self, trait_item); diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index c69991f3fb20..6d42d954b2bd 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -339,7 +339,7 @@ pub(crate) fn transform_instance<'tcx>( } else if let ty::InstanceKind::Virtual(def_id, _) = instance.def { // Transform self into a trait object of the trait that defines the method for virtual // functions to match the type erasure done below. - let upcast_ty = match tcx.trait_of_item(def_id) { + let upcast_ty = match tcx.trait_of_assoc(def_id) { Some(trait_id) => trait_object_ty( tcx, ty::Binder::dummy(ty::TraitRef::from_method(tcx, trait_id, instance.args)), @@ -364,7 +364,7 @@ pub(crate) fn transform_instance<'tcx>( }; instance.args = tcx.mk_args_trait(self_ty, instance.args.into_iter().skip(1)); } else if let ty::InstanceKind::VTableShim(def_id) = instance.def - && let Some(trait_id) = tcx.trait_of_item(def_id) + && let Some(trait_id) = tcx.trait_of_assoc(def_id) { // Adjust the type ids of VTableShims to the type id expected in the call sites for the // entry in the vtable (i.e., by using the signature of the closure passed as an argument @@ -480,7 +480,7 @@ fn implemented_method<'tcx>( // Provided method in a `trait` block trait_method = trait_method_bound; method_id = instance.def_id(); - trait_id = tcx.trait_of_item(method_id)?; + trait_id = tcx.trait_of_assoc(method_id)?; trait_ref = ty::EarlyBinder::bind(TraitRef::from_method(tcx, trait_id, instance.args)); trait_id } else { 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 1db05ced8d2f..022d549a9df8 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 @@ -1303,7 +1303,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> { && let Some(args) = self.node_args_opt(expr.hir_id) && args.iter().any(|arg| self.generic_arg_contains_target(arg)) && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) - && self.tecx.tcx.trait_of_item(def_id).is_some() + && self.tecx.tcx.trait_of_assoc(def_id).is_some() && !has_impl_trait(def_id) // FIXME(fn_delegation): In delegation item argument spans are equal to last path // segment. This leads to ICE's when emitting `multipart_suggestion`. diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs index 98f67257fd13..cdf1402252aa 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs @@ -360,7 +360,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }, ] = path.segments && data.trait_ref.def_id == *trait_id - && self.tcx.trait_of_item(*item_id) == Some(*trait_id) + && self.tcx.trait_of_assoc(*item_id) == Some(*trait_id) && let None = self.tainted_by_errors() { let assoc_item = self.tcx.associated_item(item_id); 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 c52487363664..c182fd99b17b 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -987,7 +987,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { else { return false; }; - if self.tcx.trait_of_item(did) != Some(clone_trait) { + if self.tcx.trait_of_assoc(did) != Some(clone_trait) { return false; } Some(ident.span) diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 91c41544f78f..9b5e59ce0fdb 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -759,7 +759,7 @@ fn instantiate_and_check_impossible_predicates<'tcx>( // Specifically check trait fulfillment to avoid an error when trying to resolve // associated items. - if let Some(trait_def_id) = tcx.trait_of_item(key.0) { + if let Some(trait_def_id) = tcx.trait_of_assoc(key.0) { let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1); predicates.push(trait_ref.upcast(tcx)); } diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 28b5b7cf391e..581191b2036d 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1507,7 +1507,7 @@ fn confirm_builtin_candidate<'cx, 'tcx>( let tcx = selcx.tcx(); let self_ty = obligation.predicate.self_ty(); let item_def_id = obligation.predicate.def_id; - let trait_def_id = tcx.trait_of_item(item_def_id).unwrap(); + let trait_def_id = tcx.trait_of_assoc(item_def_id).unwrap(); let args = tcx.mk_args(&[self_ty.into()]); let (term, obligations) = if tcx.is_lang_item(trait_def_id, LangItem::DiscriminantKind) { let discriminant_def_id = diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 166e8f193429..e6c3568620b5 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -21,7 +21,7 @@ fn resolve_instance_raw<'tcx>( ) -> Result>, ErrorGuaranteed> { let PseudoCanonicalInput { typing_env, value: (def_id, args) } = key; - let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) { + let result = if let Some(trait_def_id) = tcx.trait_of_assoc(def_id) { debug!(" => associated item, attempting to find impl in typing_env {:#?}", typing_env); resolve_associated_item( tcx, diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 5099df3fa023..995a1209595e 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index 972b0b110e0e..7bb684d65bb4 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs index 2ecf3eb89798..0a456d1057ad 100644 --- a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs b/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs index f5fe4316eb0d..f851ebe91f37 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs b/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs index 8167e4f96053..a811dd1cee18 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/map_clone.rs b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs index 333a33f7527d..d016ace28bd4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/open_options.rs b/src/tools/clippy/clippy_lints/src/methods/open_options.rs index 9b5f138295c3..87e6cf021023 100644 --- a/src/tools/clippy/clippy_lints/src/methods/open_options.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs b/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs index 6f78d6c61281..51dd4ac313a6 100644 --- a/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs index ce81282ddfeb..0ec2d8b4fc31 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index 769526d131bf..a86428808216 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs b/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs index d30c12e0c483..d9cf8273fada 100644 --- a/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs b/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs index 9b2cfd91b853..22ec4fe60fb0 100644 --- a/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/ranges.rs b/src/tools/clippy/clippy_lints/src/ranges.rs index 9281678b3d83..03d00ba849f3 100644 --- a/src/tools/clippy/clippy_lints/src/ranges.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs index d321c48f6aff..dcddff557d1c 100644 --- a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/unused_io_amount.rs b/src/tools/clippy/clippy_lints/src/unused_io_amount.rs index 12cc10938993..bed5c0fc0150 100644 --- a/src/tools/clippy/clippy_lints/src/unused_io_amount.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index ce5af4d2f482..211af4d5b089 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index b3356450d387..11c17a77b154 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/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 b0740198ae5fe909d814a6fb4eb25c300cfb311a Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 19:05:31 -0500 Subject: [PATCH 245/809] 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 b43164cef643957f9e1cd20dffdbb736f3f3c298 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 19:09:05 -0500 Subject: [PATCH 246/809] Rename impl_of_method -> impl_of_assoc --- .../rustc_borrowck/src/diagnostics/mutability_errors.rs | 6 +++--- compiler/rustc_borrowck/src/type_check/mod.rs | 2 +- compiler/rustc_codegen_llvm/src/debuginfo/mod.rs | 2 +- compiler/rustc_codegen_ssa/src/back/symbol_export.rs | 2 +- compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs | 2 +- compiler/rustc_lint/src/map_unit_fn.rs | 2 +- compiler/rustc_lint/src/pass_by_value.rs | 2 +- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_middle/src/middle/privacy.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 2 +- compiler/rustc_mir_transform/src/check_call_recursion.rs | 2 +- compiler/rustc_mir_transform/src/check_packed_ref.rs | 2 +- compiler/rustc_mir_transform/src/coverage/query.rs | 2 +- compiler/rustc_monomorphize/src/partitioning.rs | 2 +- compiler/rustc_passes/src/dead.rs | 2 +- .../src/cfi/typeid/itanium_cxx_abi/transform.rs | 2 +- src/tools/clippy/clippy_lints/src/assigning_clones.rs | 2 +- .../clippy/clippy_lints/src/casts/cast_ptr_alignment.rs | 2 +- .../src/casts/confusing_method_to_numeric_cast.rs | 2 +- .../clippy/clippy_lints/src/implicit_saturating_sub.rs | 4 ++-- .../clippy/clippy_lints/src/methods/bytes_count_to_len.rs | 2 +- .../methods/case_sensitive_file_extension_comparisons.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/get_first.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/map_clone.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs | 2 +- src/tools/clippy/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/clippy_lints/src/methods/suspicious_splitn.rs | 2 +- .../clippy/clippy_lints/src/methods/unnecessary_sort_by.rs | 2 +- .../clippy/clippy_lints/src/methods/unnecessary_to_owned.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/useless_asref.rs | 2 +- .../clippy/clippy_lints/src/methods/vec_resize_to_zero.rs | 2 +- src/tools/clippy/clippy_lints/src/operators/op_ref.rs | 2 +- .../clippy/clippy_lints/src/return_self_not_must_use.rs | 2 +- src/tools/clippy/clippy_lints/src/unused_io_amount.rs | 2 +- src/tools/clippy/clippy_utils/src/eager_or_lazy.rs | 2 +- src/tools/clippy/clippy_utils/src/lib.rs | 4 ++-- 41 files changed, 45 insertions(+), 45 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index a06540f83250..5d9416b59fce 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -682,7 +682,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } let my_def = self.body.source.def_id(); let Some(td) = - self.infcx.tcx.impl_of_method(my_def).and_then(|x| self.infcx.tcx.trait_id_of_impl(x)) + self.infcx.tcx.impl_of_assoc(my_def).and_then(|x| self.infcx.tcx.trait_id_of_impl(x)) else { return (false, false, None); }; @@ -880,7 +880,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let opt_suggestions = tcx .typeck(path_segment.hir_id.owner.def_id) .type_dependent_def_id(expr.hir_id) - .and_then(|def_id| tcx.impl_of_method(def_id)) + .and_then(|def_id| tcx.impl_of_assoc(def_id)) .map(|def_id| tcx.associated_items(def_id)) .map(|assoc_items| { assoc_items @@ -1056,7 +1056,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { .tcx .typeck(path_segment.hir_id.owner.def_id) .type_dependent_def_id(cur_expr.hir_id) - .and_then(|def_id| self.infcx.tcx.impl_of_method(def_id)) + .and_then(|def_id| self.infcx.tcx.impl_of_assoc(def_id)) .map(|def_id| self.infcx.tcx.associated_items(def_id)) .map(|assoc_items| { assoc_items.filter_by_name_unhygienic(sym::iter_mut).peekable() diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index f363ef0a5a98..f5fedbf95c1c 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -1761,7 +1761,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ); assert!(!matches!( - tcx.impl_of_method(def_id).map(|imp| tcx.def_kind(imp)), + tcx.impl_of_assoc(def_id).map(|imp| tcx.def_kind(imp)), Some(DefKind::Impl { of_trait: true }) )); self.prove_predicates( diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 5ca2505cec43..6cbf2dbf7d3f 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -533,7 +533,7 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { // First, let's see if this is a method within an inherent impl. Because // if yes, we want to make the result subroutine DIE a child of the // subroutine's self-type. - if let Some(impl_def_id) = cx.tcx.impl_of_method(instance.def_id()) { + if let Some(impl_def_id) = cx.tcx.impl_of_assoc(instance.def_id()) { // If the method does *not* belong to a trait, proceed if cx.tcx.trait_id_of_impl(impl_def_id).is_none() { let impl_self_ty = cx.tcx.instantiate_and_normalize_erasing_regions( diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index 2f5eca2d6b23..297bdec2bc21 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -86,7 +86,7 @@ fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap {} - DefKind::AssocFn if tcx.impl_of_method(def_id.to_def_id()).is_some() => {} + DefKind::AssocFn if tcx.impl_of_assoc(def_id.to_def_id()).is_some() => {} _ => return None, }; 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 287a5532f016..f73442fdebd4 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -755,7 +755,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let limit = if candidates.len() == 5 { 5 } else { 4 }; for (index, &item) in candidates.iter().take(limit).enumerate() { - let impl_ = tcx.impl_of_method(item).unwrap(); + let impl_ = tcx.impl_of_assoc(item).unwrap(); let note_span = if item.is_local() { Some(tcx.def_span(item)) diff --git a/compiler/rustc_lint/src/map_unit_fn.rs b/compiler/rustc_lint/src/map_unit_fn.rs index a8803158889f..34210137bde1 100644 --- a/compiler/rustc_lint/src/map_unit_fn.rs +++ b/compiler/rustc_lint/src/map_unit_fn.rs @@ -96,7 +96,7 @@ impl<'tcx> LateLintPass<'tcx> for MapUnitFn { fn is_impl_slice(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { 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) { return cx.tcx.type_of(impl_id).skip_binder().is_slice(); } diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index d3b3b55dd4c4..a3cf3d568b1c 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -24,7 +24,7 @@ impl<'tcx> LateLintPass<'tcx> for PassByValue { fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx, AmbigArg>) { match &ty.kind { TyKind::Ref(_, hir::MutTy { ty: inner_ty, mutbl: hir::Mutability::Not }) => { - if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner.to_def_id()) { + if let Some(impl_did) = cx.tcx.impl_of_assoc(ty.hir_id.owner.to_def_id()) { if cx.tcx.impl_trait_ref(impl_did).is_some() { return; } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index fc9d795cb231..b0afc333ebe2 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1904,7 +1904,7 @@ impl InvalidAtomicOrdering { if let ExprKind::MethodCall(method_path, _, args, _) = &expr.kind && recognized_names.contains(&method_path.ident.name) && let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(impl_did) = cx.tcx.impl_of_method(m_def_id) + && let Some(impl_did) = cx.tcx.impl_of_assoc(m_def_id) && let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().ty_adt_def() // skip extension traits, only lint functions from the standard library && cx.tcx.trait_id_of_impl(impl_did).is_none() diff --git a/compiler/rustc_middle/src/middle/privacy.rs b/compiler/rustc_middle/src/middle/privacy.rs index 03549091d62d..785ddd1ee298 100644 --- a/compiler/rustc_middle/src/middle/privacy.rs +++ b/compiler/rustc_middle/src/middle/privacy.rs @@ -182,7 +182,7 @@ impl EffectiveVisibilities { // don't check this condition for them. let is_impl = matches!(tcx.def_kind(def_id), DefKind::Impl { .. }); let is_associated_item_in_trait_impl = tcx - .impl_of_method(def_id.to_def_id()) + .impl_of_assoc(def_id.to_def_id()) .and_then(|impl_id| tcx.trait_id_of_impl(impl_id)) .is_some(); if !is_impl && !is_associated_item_in_trait_impl { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2e4bad290d7d..1119e60be85b 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2002,7 +2002,7 @@ impl<'tcx> TyCtxt<'tcx> { /// If the given `DefId` describes a method belonging to an impl, returns the /// `DefId` of the impl that the method belongs to; otherwise, returns `None`. - pub fn impl_of_method(self, def_id: DefId) -> Option { + pub fn impl_of_assoc(self, def_id: DefId) -> Option { self.assoc_parent(def_id).filter(|id| matches!(self.def_kind(id), DefKind::Impl { .. })) } diff --git a/compiler/rustc_mir_transform/src/check_call_recursion.rs b/compiler/rustc_mir_transform/src/check_call_recursion.rs index dccfcc52b463..6d61ac2dd803 100644 --- a/compiler/rustc_mir_transform/src/check_call_recursion.rs +++ b/compiler/rustc_mir_transform/src/check_call_recursion.rs @@ -44,7 +44,7 @@ impl<'tcx> MirLint<'tcx> for CheckDropRecursion { // First check if `body` is an `fn drop()` of `Drop` if let DefKind::AssocFn = tcx.def_kind(def_id) && let Some(trait_ref) = - tcx.impl_of_method(def_id.to_def_id()).and_then(|def_id| tcx.impl_trait_ref(def_id)) + tcx.impl_of_assoc(def_id.to_def_id()).and_then(|def_id| tcx.impl_trait_ref(def_id)) && tcx.is_lang_item(trait_ref.instantiate_identity().def_id, LangItem::Drop) // avoid erroneous `Drop` impls from causing ICEs below && let sig = tcx.fn_sig(def_id).instantiate_identity() diff --git a/compiler/rustc_mir_transform/src/check_packed_ref.rs b/compiler/rustc_mir_transform/src/check_packed_ref.rs index e9b85ba6e9db..dcb812c78993 100644 --- a/compiler/rustc_mir_transform/src/check_packed_ref.rs +++ b/compiler/rustc_mir_transform/src/check_packed_ref.rs @@ -40,7 +40,7 @@ impl<'tcx> Visitor<'tcx> for PackedRefChecker<'_, 'tcx> { if context.is_borrow() && util::is_disaligned(self.tcx, self.body, self.typing_env, *place) { let def_id = self.body.source.instance.def_id(); - if let Some(impl_def_id) = self.tcx.impl_of_method(def_id) + if let Some(impl_def_id) = self.tcx.impl_of_assoc(def_id) && self.tcx.is_builtin_derived(impl_def_id) { // If we ever reach here it means that the generated derive diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 986c001de5e8..551f720c869e 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -35,7 +35,7 @@ fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { // Don't instrument functions with `#[automatically_derived]` on their // enclosing impl block, on the assumption that most users won't care about // coverage for derived impls. - if let Some(impl_of) = tcx.impl_of_method(def_id.to_def_id()) + if let Some(impl_of) = tcx.impl_of_assoc(def_id.to_def_id()) && tcx.is_automatically_derived(impl_of) { trace!("InstrumentCoverage skipped for {def_id:?} (automatically derived)"); diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index 9f5807070a7b..cee15e0f6969 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -656,7 +656,7 @@ fn characteristic_def_id_of_mono_item<'tcx>( return characteristic_def_id_of_type(self_ty).or(Some(def_id)); } - if let Some(impl_def_id) = tcx.impl_of_method(def_id) { + if let Some(impl_def_id) = tcx.impl_of_assoc(def_id) { if tcx.sess.opts.incremental.is_some() && tcx .trait_id_of_impl(impl_def_id) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index ae379d53ad12..a90d1af87ca1 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -368,7 +368,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { /// will be ignored for the purposes of dead code analysis (see PR #85200 /// for discussion). fn should_ignore_item(&mut self, def_id: DefId) -> bool { - if let Some(impl_of) = self.tcx.impl_of_method(def_id) { + if let Some(impl_of) = self.tcx.impl_of_assoc(def_id) { if !self.tcx.is_automatically_derived(impl_of) { return false; } diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index 6d42d954b2bd..52717d73b8ae 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -466,7 +466,7 @@ fn implemented_method<'tcx>( let method_id; let trait_id; let trait_method; - let ancestor = if let Some(impl_id) = tcx.impl_of_method(instance.def_id()) { + let ancestor = if let Some(impl_id) = tcx.impl_of_assoc(instance.def_id()) { // Implementation in an `impl` block trait_ref = tcx.impl_trait_ref(impl_id)?; let impl_method = tcx.associated_item(instance.def_id()); diff --git a/src/tools/clippy/clippy_lints/src/assigning_clones.rs b/src/tools/clippy/clippy_lints/src/assigning_clones.rs index 8b8b42bbf722..52287be34c78 100644 --- a/src/tools/clippy/clippy_lints/src/assigning_clones.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs b/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs index e4dafde0f9df..a1543cabd2f9 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs b/src/tools/clippy/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs index 849de22cfbaa..73347e7141eb 100644 --- a/src/tools/clippy/clippy_lints/src/casts/confusing_method_to_numeric_cast.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs index c743501da253..c634c12e1877 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs b/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs index a9f6a41c2357..b8cc5ddd845c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs b/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs index 292fa08b5984..6f9702f6c6c3 100644 --- a/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/get_first.rs b/src/tools/clippy/clippy_lints/src/methods/get_first.rs index f4465e654c2e..2e1d71ce284d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/get_first.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs b/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs index 9724463f0c08..efa8cee58df7 100644 --- a/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs b/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs index c286c5faaed3..077957fa44dc 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/map_clone.rs b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs index d016ace28bd4..748be9bfcc62 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs b/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs index 5d0d4dae35fa..41beda9c5cb4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs index 320523aceb67..4235af882b0c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/open_options.rs b/src/tools/clippy/clippy_lints/src/methods/open_options.rs index 87e6cf021023..37a8e25bef96 100644 --- a/src/tools/clippy/clippy_lints/src/methods/open_options.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs b/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs index 38d9c5f16778..32752ef7435f 100644 --- a/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/stable_sort_primitive.rs b/src/tools/clippy/clippy_lints/src/methods/stable_sort_primitive.rs index aef14435d8af..17d1a6abde0a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/stable_sort_primitive.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/suspicious_splitn.rs b/src/tools/clippy/clippy_lints/src/methods/suspicious_splitn.rs index f8b6d4349fbe..9876681ddbb3 100644 --- a/src/tools/clippy/clippy_lints/src/methods/suspicious_splitn.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs index dbff08bc51c9..1de9f6ab4970 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index a86428808216..54f45263275c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs b/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs index d9cf8273fada..38fad239f679 100644 --- a/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs b/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs index 5ea4ada128a2..bfb481f4fc09 100644 --- a/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/operators/op_ref.rs b/src/tools/clippy/clippy_lints/src/operators/op_ref.rs index 21e1ab0f4f27..0a1f2625f4cf 100644 --- a/src/tools/clippy/clippy_lints/src/operators/op_ref.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs index 25929b853af8..3497216d1c56 100644 --- a/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs +++ b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs @@ -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/src/tools/clippy/clippy_lints/src/unused_io_amount.rs b/src/tools/clippy/clippy_lints/src/unused_io_amount.rs index bed5c0fc0150..f3cd3f1bb286 100644 --- a/src/tools/clippy/clippy_lints/src/unused_io_amount.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs index 9d38672efada..eb3f442ac754 100644 --- a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 211af4d5b089..67e09e772a77 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/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 86ff11e729e780f533030208f1c0ab25e52e6f47 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 19:09:05 -0500 Subject: [PATCH 247/809] 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 cdcfdd1a1b3f267a98c693fc03b4411934b60674 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 19:01:22 -0500 Subject: [PATCH 248/809] Tweak docs --- compiler/rustc_middle/src/ty/mod.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 1119e60be85b..bb70c61cd141 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1993,15 +1993,14 @@ impl<'tcx> TyCtxt<'tcx> { self.def_kind(def_id).is_assoc().then(|| self.parent(def_id)) } - /// If the given `DefId` describes an item belonging to a trait, - /// returns the `DefId` of the trait that the trait item belongs to; - /// otherwise, returns `None`. + /// If the given `DefId` is an associated item of a trait, + /// returns the `DefId` of the trait; otherwise, returns `None`. pub fn trait_of_assoc(self, def_id: DefId) -> Option { self.assoc_parent(def_id).filter(|id| self.def_kind(id) == DefKind::Trait) } - /// If the given `DefId` describes a method belonging to an impl, returns the - /// `DefId` of the impl that the method belongs to; otherwise, returns `None`. + /// If the given `DefId` is an associated item of an impl, + /// returns the `DefId` of the impl; otherwise returns `None`. pub fn impl_of_assoc(self, def_id: DefId) -> Option { self.assoc_parent(def_id).filter(|id| matches!(self.def_kind(id), DefKind::Impl { .. })) } From 4f1044a5a6c7b9ea1c9a46f61a4a20c8e8761fec Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 28 Jul 2025 17:09:20 +0200 Subject: [PATCH 249/809] 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 250/809] 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 73751a04910d08052bf6b825f8829cacba86c648 Mon Sep 17 00:00:00 2001 From: joboet Date: Sat, 26 Jul 2025 14:29:00 +0200 Subject: [PATCH 251/809] thread name in stack overflow message --- library/std/src/sys/pal/hermit/thread.rs | 6 ++++- library/std/src/sys/pal/itron/thread.rs | 6 ++++- library/std/src/sys/pal/sgx/thread.rs | 6 ++++- library/std/src/sys/pal/teeos/thread.rs | 6 ++++- library/std/src/sys/pal/uefi/thread.rs | 6 ++++- .../std/src/sys/pal/unix/stack_overflow.rs | 23 ++++++++++-------- library/std/src/sys/pal/unix/thread.rs | 24 +++++++++++++------ library/std/src/sys/pal/unsupported/thread.rs | 6 ++++- library/std/src/sys/pal/wasi/thread.rs | 4 ++-- .../std/src/sys/pal/wasm/atomics/thread.rs | 6 ++++- library/std/src/sys/pal/windows/thread.rs | 6 ++++- library/std/src/sys/pal/xous/thread.rs | 6 ++++- library/std/src/thread/mod.rs | 2 +- tests/ui/runtime/out-of-stack.rs | 12 +++++++--- 14 files changed, 87 insertions(+), 32 deletions(-) diff --git a/library/std/src/sys/pal/hermit/thread.rs b/library/std/src/sys/pal/hermit/thread.rs index 9bc5a16b8002..95fe4f902d33 100644 --- a/library/std/src/sys/pal/hermit/thread.rs +++ b/library/std/src/sys/pal/hermit/thread.rs @@ -58,7 +58,11 @@ impl Thread { } } - pub unsafe fn new(stack: usize, p: Box) -> io::Result { + pub unsafe fn new( + stack: usize, + _name: Option<&str>, + p: Box, + ) -> io::Result { unsafe { Thread::new_with_coreid(stack, p, -1 /* = no specific core */) } diff --git a/library/std/src/sys/pal/itron/thread.rs b/library/std/src/sys/pal/itron/thread.rs index 813e1cbcd58f..0d28051fcc46 100644 --- a/library/std/src/sys/pal/itron/thread.rs +++ b/library/std/src/sys/pal/itron/thread.rs @@ -86,7 +86,11 @@ impl Thread { /// # Safety /// /// See `thread::Builder::spawn_unchecked` for safety requirements. - pub unsafe fn new(stack: usize, p: Box) -> io::Result { + pub unsafe fn new( + stack: usize, + _name: Option<&str>, + p: Box, + ) -> io::Result { let inner = Box::new(ThreadInner { start: UnsafeCell::new(ManuallyDrop::new(p)), lifecycle: AtomicUsize::new(LIFECYCLE_INIT), diff --git a/library/std/src/sys/pal/sgx/thread.rs b/library/std/src/sys/pal/sgx/thread.rs index 85f6dcd96b4a..a236c3627060 100644 --- a/library/std/src/sys/pal/sgx/thread.rs +++ b/library/std/src/sys/pal/sgx/thread.rs @@ -96,7 +96,11 @@ pub mod wait_notify { impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(_stack: usize, p: Box) -> io::Result { + pub unsafe fn new( + _stack: usize, + _name: Option<&str>, + p: Box, + ) -> io::Result { let mut queue_lock = task_queue::lock(); unsafe { usercalls::launch_thread()? }; let (task, handle) = task_queue::Task::new(p); diff --git a/library/std/src/sys/pal/teeos/thread.rs b/library/std/src/sys/pal/teeos/thread.rs index b9cdc7a2a58b..a91d95626e70 100644 --- a/library/std/src/sys/pal/teeos/thread.rs +++ b/library/std/src/sys/pal/teeos/thread.rs @@ -22,7 +22,11 @@ unsafe extern "C" { impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(stack: usize, p: Box) -> io::Result { + pub unsafe fn new( + stack: usize, + _name: Option<&str>, + p: Box, + ) -> io::Result { let p = Box::into_raw(Box::new(p)); let mut native: libc::pthread_t = unsafe { mem::zeroed() }; let mut attr: libc::pthread_attr_t = unsafe { mem::zeroed() }; diff --git a/library/std/src/sys/pal/uefi/thread.rs b/library/std/src/sys/pal/uefi/thread.rs index e4776ec42fbb..75c364362b2d 100644 --- a/library/std/src/sys/pal/uefi/thread.rs +++ b/library/std/src/sys/pal/uefi/thread.rs @@ -11,7 +11,11 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 64 * 1024; impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(_stack: usize, _p: Box) -> io::Result { + pub unsafe fn new( + _stack: usize, + _name: Option<&str>, + _p: Box, + ) -> io::Result { unsupported() } diff --git a/library/std/src/sys/pal/unix/stack_overflow.rs b/library/std/src/sys/pal/unix/stack_overflow.rs index a3be2cdf738f..d89100e69196 100644 --- a/library/std/src/sys/pal/unix/stack_overflow.rs +++ b/library/std/src/sys/pal/unix/stack_overflow.rs @@ -8,8 +8,8 @@ pub struct Handler { } impl Handler { - pub unsafe fn new() -> Handler { - make_handler(false) + pub unsafe fn new(thread_name: Option>) -> Handler { + make_handler(false, thread_name) } fn null() -> Handler { @@ -72,7 +72,6 @@ mod imp { use crate::sync::OnceLock; use crate::sync::atomic::{Atomic, AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use crate::sys::pal::unix::os; - use crate::thread::with_current_name; use crate::{io, mem, panic, ptr}; // Signal handler for the SIGSEGV and SIGBUS handlers. We've got guard pages @@ -158,13 +157,12 @@ mod imp { if !NEED_ALTSTACK.load(Ordering::Relaxed) { // haven't set up our sigaltstack yet NEED_ALTSTACK.store(true, Ordering::Release); - let handler = unsafe { make_handler(true) }; + let handler = unsafe { make_handler(true, None) }; MAIN_ALTSTACK.store(handler.data, Ordering::Relaxed); mem::forget(handler); if let Some(guard_page_range) = guard_page_range.take() { - let thread_name = with_current_name(|name| name.map(Box::from)); - set_current_info(guard_page_range, thread_name); + set_current_info(guard_page_range, Some(Box::from("main"))); } } @@ -230,14 +228,13 @@ mod imp { /// # Safety /// Mutates the alternate signal stack #[forbid(unsafe_op_in_unsafe_fn)] - pub unsafe fn make_handler(main_thread: bool) -> Handler { + pub unsafe fn make_handler(main_thread: bool, thread_name: Option>) -> Handler { if !NEED_ALTSTACK.load(Ordering::Acquire) { return Handler::null(); } if !main_thread { if let Some(guard_page_range) = unsafe { current_guard() } { - let thread_name = with_current_name(|name| name.map(Box::from)); set_current_info(guard_page_range, thread_name); } } @@ -634,7 +631,10 @@ mod imp { pub unsafe fn cleanup() {} - pub unsafe fn make_handler(_main_thread: bool) -> super::Handler { + pub unsafe fn make_handler( + _main_thread: bool, + _thread_name: Option>, + ) -> super::Handler { super::Handler::null() } @@ -717,7 +717,10 @@ mod imp { pub unsafe fn cleanup() {} - pub unsafe fn make_handler(main_thread: bool) -> super::Handler { + pub unsafe fn make_handler( + main_thread: bool, + _thread_name: Option>, + ) -> super::Handler { if !main_thread { reserve_stack(); } diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index e4f5520d8a33..7f6440152d4b 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -22,6 +22,11 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024; #[cfg(any(target_os = "espidf", target_os = "nuttx"))] pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 indicates that the stack size configured in the ESP-IDF/NuttX menuconfig system should be used +struct ThreadData { + name: Option>, + f: Box, +} + pub struct Thread { id: libc::pthread_t, } @@ -34,8 +39,12 @@ unsafe impl Sync for Thread {} impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces - pub unsafe fn new(stack: usize, p: Box) -> io::Result { - let p = Box::into_raw(Box::new(p)); + pub unsafe fn new( + stack: usize, + name: Option<&str>, + f: Box, + ) -> io::Result { + let data = Box::into_raw(Box::new(ThreadData { name: name.map(Box::from), f })); let mut native: libc::pthread_t = mem::zeroed(); let mut attr: mem::MaybeUninit = mem::MaybeUninit::uninit(); assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); @@ -73,7 +82,7 @@ impl Thread { }; } - let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, p as *mut _); + let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, data as *mut _); // Note: if the thread creation fails and this assert fails, then p will // be leaked. However, an alternative design could cause double-free // which is clearly worse. @@ -82,19 +91,20 @@ impl Thread { return if ret != 0 { // The thread failed to start and as a result p was not consumed. Therefore, it is // safe to reconstruct the box so that it gets deallocated. - drop(Box::from_raw(p)); + drop(Box::from_raw(data)); Err(io::Error::from_raw_os_error(ret)) } else { Ok(Thread { id: native }) }; - extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void { + extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void { unsafe { + let data = Box::from_raw(data as *mut ThreadData); // Next, set up our stack overflow handler which may get triggered if we run // out of stack. - let _handler = stack_overflow::Handler::new(); + let _handler = stack_overflow::Handler::new(data.name); // Finally, let's run some code. - Box::from_raw(main as *mut Box)(); + (data.f)(); } ptr::null_mut() } diff --git a/library/std/src/sys/pal/unsupported/thread.rs b/library/std/src/sys/pal/unsupported/thread.rs index 8a3119fa292d..5a1e3fde9860 100644 --- a/library/std/src/sys/pal/unsupported/thread.rs +++ b/library/std/src/sys/pal/unsupported/thread.rs @@ -10,7 +10,11 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 64 * 1024; impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(_stack: usize, _p: Box) -> io::Result { + pub unsafe fn new( + _stack: usize, + _name: Option<&str>, + _p: Box, + ) -> io::Result { unsupported() } diff --git a/library/std/src/sys/pal/wasi/thread.rs b/library/std/src/sys/pal/wasi/thread.rs index 5f21a553673a..a46c74630c97 100644 --- a/library/std/src/sys/pal/wasi/thread.rs +++ b/library/std/src/sys/pal/wasi/thread.rs @@ -73,7 +73,7 @@ impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements cfg_if::cfg_if! { if #[cfg(target_feature = "atomics")] { - pub unsafe fn new(stack: usize, p: Box) -> io::Result { + pub unsafe fn new(stack: usize, _name: Option<&str>, p: Box) -> io::Result { let p = Box::into_raw(Box::new(p)); let mut native: libc::pthread_t = unsafe { mem::zeroed() }; let mut attr: libc::pthread_attr_t = unsafe { mem::zeroed() }; @@ -120,7 +120,7 @@ impl Thread { } } } else { - pub unsafe fn new(_stack: usize, _p: Box) -> io::Result { + pub unsafe fn new(_stack: usize, _name: Option<&str>, _p: Box) -> io::Result { crate::sys::unsupported() } } diff --git a/library/std/src/sys/pal/wasm/atomics/thread.rs b/library/std/src/sys/pal/wasm/atomics/thread.rs index 44ce3eab109f..ebfabaafc794 100644 --- a/library/std/src/sys/pal/wasm/atomics/thread.rs +++ b/library/std/src/sys/pal/wasm/atomics/thread.rs @@ -10,7 +10,11 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024; impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(_stack: usize, _p: Box) -> io::Result { + pub unsafe fn new( + _stack: usize, + _name: Option<&str>, + _p: Box, + ) -> io::Result { unsupported() } diff --git a/library/std/src/sys/pal/windows/thread.rs b/library/std/src/sys/pal/windows/thread.rs index 147851717553..b45f76fb546f 100644 --- a/library/std/src/sys/pal/windows/thread.rs +++ b/library/std/src/sys/pal/windows/thread.rs @@ -20,7 +20,11 @@ pub struct Thread { impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces - pub unsafe fn new(stack: usize, p: Box) -> io::Result { + pub unsafe fn new( + stack: usize, + _name: Option<&str>, + p: Box, + ) -> io::Result { let p = Box::into_raw(Box::new(p)); // CreateThread rounds up values for the stack size to the nearest page size (at least 4kb). diff --git a/library/std/src/sys/pal/xous/thread.rs b/library/std/src/sys/pal/xous/thread.rs index 1b344e984dc3..f2404a62abf9 100644 --- a/library/std/src/sys/pal/xous/thread.rs +++ b/library/std/src/sys/pal/xous/thread.rs @@ -20,7 +20,11 @@ pub const GUARD_PAGE_SIZE: usize = 4096; impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(stack: usize, p: Box) -> io::Result { + pub unsafe fn new( + stack: usize, + _name: Option<&str>, + p: Box, + ) -> io::Result { let p = Box::into_raw(Box::new(p)); let mut stack_size = crate::cmp::max(stack, MIN_STACK_SIZE); diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 6075173db47f..62ecacccd2ea 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -595,7 +595,7 @@ impl Builder { // Similarly, the `sys` implementation must guarantee that no references to the closure // exist after the thread has terminated, which is signaled by `Thread::join` // returning. - native: unsafe { imp::Thread::new(stack_size, main)? }, + native: unsafe { imp::Thread::new(stack_size, my_thread.name(), main)? }, thread: my_thread, packet: my_packet, }) diff --git a/tests/ui/runtime/out-of-stack.rs b/tests/ui/runtime/out-of-stack.rs index 6be34afb5603..913d3637c8f2 100644 --- a/tests/ui/runtime/out-of-stack.rs +++ b/tests/ui/runtime/out-of-stack.rs @@ -19,7 +19,7 @@ extern crate libc; use std::env; use std::hint::black_box; use std::process::Command; -use std::thread; +use std::thread::Builder; fn silent_recurse() { let buf = [0u8; 1000]; @@ -56,9 +56,9 @@ fn main() { } else if args.len() > 1 && args[1] == "loud" { loud_recurse(); } else if args.len() > 1 && args[1] == "silent-thread" { - thread::spawn(silent_recurse).join(); + Builder::new().name("ferris".to_string()).spawn(silent_recurse).unwrap().join(); } else if args.len() > 1 && args[1] == "loud-thread" { - thread::spawn(loud_recurse).join(); + Builder::new().name("ferris".to_string()).spawn(loud_recurse).unwrap().join(); } else { let mut modes = vec![ "silent-thread", @@ -82,6 +82,12 @@ fn main() { let error = String::from_utf8_lossy(&silent.stderr); assert!(error.contains("has overflowed its stack"), "missing overflow message: {}", error); + + if mode.contains("thread") { + assert!(error.contains("ferris"), "missing thread name: {}", error); + } else { + assert!(error.contains("main"), "missing thread name: {}", error); + } } } } From 2db97b2f7d877e5db2c892b42ed4deb8d829af14 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 28 Jul 2025 16:09:47 +0000 Subject: [PATCH 252/809] Account for .yield in illegal postfix operator message --- compiler/rustc_parse/src/parser/expr.rs | 6 +++++- tests/ui/coroutine/postfix-yield-after-cast.rs | 10 ++++++++++ tests/ui/coroutine/postfix-yield-after-cast.stderr | 13 +++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/ui/coroutine/postfix-yield-after-cast.rs create mode 100644 tests/ui/coroutine/postfix-yield-after-cast.stderr diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 3d89530f9143..54d8a7910258 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -785,9 +785,13 @@ impl<'a> Parser<'a> { ExprKind::Call(_, _) => "a function call", ExprKind::Await(_, _) => "`.await`", ExprKind::Use(_, _) => "`.use`", + ExprKind::Yield(YieldKind::Postfix(_)) => "`.yield`", ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match", ExprKind::Err(_) => return Ok(with_postfix), - _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"), + _ => unreachable!( + "did not expect {:?} as an illegal postfix operator following cast", + with_postfix.kind + ), } ); let mut err = self.dcx().struct_span_err(span, msg); diff --git a/tests/ui/coroutine/postfix-yield-after-cast.rs b/tests/ui/coroutine/postfix-yield-after-cast.rs new file mode 100644 index 000000000000..472efb9f5138 --- /dev/null +++ b/tests/ui/coroutine/postfix-yield-after-cast.rs @@ -0,0 +1,10 @@ +// Regression test for . + +#![feature(yield_expr, coroutines)] + +fn main() { + #[coroutine] || { + 0 as u8.yield + //~^ ERROR cast cannot be followed by `.yield` + }; +} diff --git a/tests/ui/coroutine/postfix-yield-after-cast.stderr b/tests/ui/coroutine/postfix-yield-after-cast.stderr new file mode 100644 index 000000000000..a4de064fdf87 --- /dev/null +++ b/tests/ui/coroutine/postfix-yield-after-cast.stderr @@ -0,0 +1,13 @@ +error: cast cannot be followed by `.yield` + --> $DIR/postfix-yield-after-cast.rs:7:9 + | +LL | 0 as u8.yield + | ^^^^^^^ + | +help: try surrounding the expression in parentheses + | +LL | (0 as u8).yield + | + + + +error: aborting due to 1 previous error + From c5b4606d2a2070f1e7d79622d6be83138b54de31 Mon Sep 17 00:00:00 2001 From: apiraino Date: Mon, 28 Jul 2025 15:16:00 +0200 Subject: [PATCH 253/809] Enable t-compiler backport nomination --- triagebot.toml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/triagebot.toml b/triagebot.toml index 894f56df7419..e1b4983adf7b 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -50,6 +50,21 @@ remove_labels = ["S-waiting-on-author"] # Those labels are added when PR author requests a review from an assignee add_labels = ["S-waiting-on-review"] +# [backport.*] sections autonominate pull requests for a backport +# see: https://forge.rust-lang.org/triagebot/backport.html + +[backport.t-compiler-beta-backport] +# The pull request MUST have one of these labels +required-pr-labels = ["T-compiler"] +# The regression MUST have this label +required-issue-label = "regression-from-stable-to-beta" +# if the above conditions matches, the PR will receive these labels +add-labels = ["beta-nominated"] + +[backport.t-compiler-stable-backport] +required-pr-labels = ["T-compiler"] +required-issue-label = "regression-from-stable-to-stable" +add-labels = ["stable-nominated"] # ------------------------------------------------------------------------------ # Ping groups From c071101da73c417612155eb44e4cf4b9b3ee7499 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Mon, 28 Jul 2025 22:23:56 +0530 Subject: [PATCH 254/809] make sure to populate DownloadState dependencies before its initialization in config parsing --- src/bootstrap/src/core/config/config.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 90001f9ae318..9644ade00b34 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -797,6 +797,11 @@ impl Config { ); } + 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 { if !flags_skip_stage0_validation { config.check_stage0_version(&rustc, "rustc"); @@ -867,7 +872,6 @@ impl Config { config.reuse = reuse.map(PathBuf::from); config.submodules = submodules; config.android_ndk = android_ndk; - config.bootstrap_cache_path = bootstrap_cache_path; 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); @@ -886,7 +890,6 @@ impl Config { 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.patch_binaries_for_nix = patch_binaries_for_nix; config.verbose = cmp::max(config.verbose, flags_verbose as usize); @@ -895,9 +898,6 @@ impl Config { config.apply_install_config(toml.install); - config.llvm_assertions = - toml.llvm.as_ref().is_some_and(|llvm| llvm.assertions.unwrap_or(false)); - let file_content = t!(fs::read_to_string(config.src.join("src/ci/channel"))); let ci_channel = file_content.trim_end(); From 5185a665a977dd6b57c76ffaaa8becd57e569c6f Mon Sep 17 00:00:00 2001 From: binarycat Date: Fri, 25 Jul 2025 14:02:01 -0500 Subject: [PATCH 255/809] tidy: increase performance of auto extra checks feature MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jakub Beránek --- src/tools/tidy/src/extra_checks/mod.rs | 30 ++++++++------ src/tools/tidy/src/lib.rs | 55 ++++++++++++++++++-------- 2 files changed, 55 insertions(+), 30 deletions(-) diff --git a/src/tools/tidy/src/extra_checks/mod.rs b/src/tools/tidy/src/extra_checks/mod.rs index 8121eb057db5..f90f716cd950 100644 --- a/src/tools/tidy/src/extra_checks/mod.rs +++ b/src/tools/tidy/src/extra_checks/mod.rs @@ -86,7 +86,7 @@ fn check_impl( std::env::var("TIDY_PRINT_DIFF").is_ok_and(|v| v.eq_ignore_ascii_case("true") || v == "1"); // Split comma-separated args up - let lint_args = match extra_checks { + let mut lint_args = match extra_checks { Some(s) => s .strip_prefix("--extra-checks=") .unwrap() @@ -99,11 +99,7 @@ fn check_impl( }) .filter_map(|(res, src)| match res { Ok(arg) => { - if arg.is_inactive_auto(ci_info) { - None - } else { - Some(arg) - } + Some(arg) } Err(err) => { // only warn because before bad extra checks would be silently ignored. @@ -114,6 +110,11 @@ fn check_impl( .collect(), None => vec![], }; + if lint_args.iter().any(|ck| ck.auto) { + crate::files_modified_batch_filter(ci_info, &mut lint_args, |ck, path| { + ck.is_non_auto_or_matches(path) + }); + } macro_rules! extra_check { ($lang:ident, $kind:ident) => { @@ -721,10 +722,10 @@ impl ExtraCheckArg { self.lang == lang && self.kind.map(|k| k == kind).unwrap_or(true) } - /// Returns `true` if this is an auto arg and the relevant files are not modified. - fn is_inactive_auto(&self, ci_info: &CiInfo) -> bool { + /// Returns `false` if this is an auto arg and the passed filename does not trigger the auto rule + fn is_non_auto_or_matches(&self, filepath: &str) -> bool { if !self.auto { - return false; + return true; } let ext = match self.lang { ExtraCheckLang::Py => ".py", @@ -732,12 +733,15 @@ impl ExtraCheckArg { ExtraCheckLang::Shell => ".sh", ExtraCheckLang::Js => ".js", ExtraCheckLang::Spellcheck => { - return !crate::files_modified(ci_info, |s| { - SPELLCHECK_DIRS.iter().any(|dir| Path::new(s).starts_with(dir)) - }); + for dir in SPELLCHECK_DIRS { + if Path::new(filepath).starts_with(dir) { + return true; + } + } + return false; } }; - !crate::files_modified(ci_info, |s| s.ends_with(ext)) + filepath.ends_with(ext) } fn has_supported_kind(&self) -> bool { diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index 4f9fb308a866..4ea9d051ddb5 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -125,40 +125,61 @@ pub fn git_diff>(base_commit: &str, extra_arg: S) -> Option bool) -> bool { +/// Similar to `files_modified`, but only involves a single call to `git`. +/// +/// removes all elements from `items` that do not cause any match when `pred` is called with the list of modifed files. +/// +/// if in CI, no elements will be removed. +pub fn files_modified_batch_filter( + ci_info: &CiInfo, + items: &mut Vec, + pred: impl Fn(&T, &str) -> bool, +) { if CiEnv::is_ci() { // assume everything is modified on CI because we really don't want false positives there. - return true; + return; } let Some(base_commit) = &ci_info.base_commit else { eprintln!("No base commit, assuming all files are modified"); - return true; + return; }; match crate::git_diff(base_commit, "--name-status") { Some(output) => { - let modified_files = output.lines().filter_map(|ln| { - let (status, name) = ln - .trim_end() - .split_once('\t') - .expect("bad format from `git diff --name-status`"); - if status == "M" { Some(name) } else { None } - }); - for modified_file in modified_files { - if pred(modified_file) { - return true; + let modified_files: Vec<_> = output + .lines() + .filter_map(|ln| { + let (status, name) = ln + .trim_end() + .split_once('\t') + .expect("bad format from `git diff --name-status`"); + if status == "M" { Some(name) } else { None } + }) + .collect(); + items.retain(|item| { + for modified_file in &modified_files { + if pred(item, modified_file) { + // at least one predicate matches, keep this item. + return true; + } } - } - false + // no predicates matched, remove this item. + false + }); } None => { eprintln!("warning: failed to run `git diff` to check for changes"); eprintln!("warning: assuming all files are modified"); - true } } } +/// Returns true if any modified file matches the predicate, if we are in CI, or if unable to list modified files. +pub fn files_modified(ci_info: &CiInfo, pred: impl Fn(&str) -> bool) -> bool { + let mut v = vec![()]; + files_modified_batch_filter(ci_info, &mut v, |_, p| pred(p)); + !v.is_empty() +} + pub mod alphabetical; pub mod bins; pub mod debug_artifacts; From 4096582662d38ca5d1692e0213ddf5574a40e0d6 Mon Sep 17 00:00:00 2001 From: binarycat Date: Mon, 28 Jul 2025 13:12:51 -0500 Subject: [PATCH 256/809] bootstrap: enable tidy auto extra checks on tools profile --- bootstrap.example.toml | 3 +++ src/bootstrap/defaults/bootstrap.tools.toml | 2 ++ 2 files changed, 5 insertions(+) diff --git a/bootstrap.example.toml b/bootstrap.example.toml index 73e93ccbe420..ef49113b70f4 100644 --- a/bootstrap.example.toml +++ b/bootstrap.example.toml @@ -475,6 +475,9 @@ # Note that if any value is manually given to bootstrap such as # `./x test tidy --extra-checks=js`, this value is ignored. # Use `--extra-checks=''` to temporarily disable all extra checks. +# +# Automatically enabled in the "tools" profile. +# Set to the empty string to force disable (recommeded for hdd systems). #build.tidy-extra-checks = "" # Indicates whether ccache is used when building certain artifacts (e.g. LLVM). diff --git a/src/bootstrap/defaults/bootstrap.tools.toml b/src/bootstrap/defaults/bootstrap.tools.toml index 57c2706f60a5..5abe636bd968 100644 --- a/src/bootstrap/defaults/bootstrap.tools.toml +++ b/src/bootstrap/defaults/bootstrap.tools.toml @@ -14,6 +14,8 @@ test-stage = 2 doc-stage = 2 # Contributors working on tools will probably expect compiler docs to be generated, so they can figure out how to use the API. compiler-docs = true +# Contributors working on tools are the most likely to change non-rust programs. +tidy-extra-checks = "auto:js,auto:py,auto:cpp,auto:spellcheck" [llvm] # Will download LLVM from CI if available on your platform. From 327ee15959949c808da2498f7337a5fa5e415c08 Mon Sep 17 00:00:00 2001 From: Noratrieb <48135649+Noratrieb@users.noreply.github.com> Date: Mon, 28 Jul 2025 20:47:01 +0200 Subject: [PATCH 257/809] Ensure external paths passed via flags end up in rustdoc depinfo rustdoc has many flags to pass external HTML/Markdown/CSS files that end up in the build. These need to be recorded in depinfo so that Cargo will rebuild the crate if they change. --- src/librustdoc/config.rs | 20 +++++++++++------- src/librustdoc/externalfiles.rs | 23 ++++++++++++++------- src/librustdoc/lib.rs | 8 ++++++- src/librustdoc/scrape_examples.rs | 2 ++ tests/run-make/rustdoc-dep-info/after.md | 1 + tests/run-make/rustdoc-dep-info/before.html | 0 tests/run-make/rustdoc-dep-info/extend.css | 0 tests/run-make/rustdoc-dep-info/rmake.rs | 15 +++++++++++++- tests/run-make/rustdoc-dep-info/theme.css | 1 + 9 files changed, 53 insertions(+), 17 deletions(-) create mode 100644 tests/run-make/rustdoc-dep-info/after.md create mode 100644 tests/run-make/rustdoc-dep-info/before.html create mode 100644 tests/run-make/rustdoc-dep-info/extend.css create mode 100644 tests/run-make/rustdoc-dep-info/theme.css diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 986390dbaa08..dfa6bf175d94 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -377,7 +377,7 @@ impl Options { early_dcx: &mut EarlyDiagCtxt, matches: &getopts::Matches, args: Vec, - ) -> Option<(InputMode, Options, RenderOptions)> { + ) -> Option<(InputMode, Options, RenderOptions, Vec)> { // Check for unstable options. nightly_options::check_nightly_options(early_dcx, matches, &opts()); @@ -640,10 +640,13 @@ impl Options { let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s)); - if let Some(ref p) = extension_css - && !p.is_file() - { - dcx.fatal("option --extend-css argument must be a file"); + let mut loaded_paths = Vec::new(); + + if let Some(ref p) = extension_css { + loaded_paths.push(p.clone()); + if !p.is_file() { + dcx.fatal("option --extend-css argument must be a file"); + } } let mut themes = Vec::new(); @@ -687,6 +690,7 @@ impl Options { )) .emit(); } + loaded_paths.push(theme_file.clone()); themes.push(StylePath { path: theme_file }); } } @@ -705,6 +709,7 @@ impl Options { &mut id_map, edition, &None, + &mut loaded_paths, ) else { dcx.fatal("`ExternalHtml::load` failed"); }; @@ -796,7 +801,8 @@ impl Options { let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx); let with_examples = matches.opt_strs("with-examples"); - let call_locations = crate::scrape_examples::load_call_locations(with_examples, dcx); + let call_locations = + crate::scrape_examples::load_call_locations(with_examples, dcx, &mut loaded_paths); let doctest_build_args = matches.opt_strs("doctest-build-arg"); let unstable_features = @@ -881,7 +887,7 @@ impl Options { parts_out_dir, disable_minification, }; - Some((input, options, render_options)) + Some((input, options, render_options, loaded_paths)) } } diff --git a/src/librustdoc/externalfiles.rs b/src/librustdoc/externalfiles.rs index ea2aa963eddf..42ade5b90048 100644 --- a/src/librustdoc/externalfiles.rs +++ b/src/librustdoc/externalfiles.rs @@ -1,4 +1,4 @@ -use std::path::Path; +use std::path::{Path, PathBuf}; use std::{fs, str}; use rustc_errors::DiagCtxtHandle; @@ -32,12 +32,13 @@ impl ExternalHtml { id_map: &mut IdMap, edition: Edition, playground: &Option, + loaded_paths: &mut Vec, ) -> Option { let codes = ErrorCodes::from(nightly_build); - let ih = load_external_files(in_header, dcx)?; + let ih = load_external_files(in_header, dcx, loaded_paths)?; let bc = { - let mut bc = load_external_files(before_content, dcx)?; - let m_bc = load_external_files(md_before_content, dcx)?; + let mut bc = load_external_files(before_content, dcx, loaded_paths)?; + let m_bc = load_external_files(md_before_content, dcx, loaded_paths)?; Markdown { content: &m_bc, links: &[], @@ -52,8 +53,8 @@ impl ExternalHtml { bc }; let ac = { - let mut ac = load_external_files(after_content, dcx)?; - let m_ac = load_external_files(md_after_content, dcx)?; + let mut ac = load_external_files(after_content, dcx, loaded_paths)?; + let m_ac = load_external_files(md_after_content, dcx, loaded_paths)?; Markdown { content: &m_ac, links: &[], @@ -79,8 +80,10 @@ pub(crate) enum LoadStringError { pub(crate) fn load_string>( file_path: P, dcx: DiagCtxtHandle<'_>, + loaded_paths: &mut Vec, ) -> Result { let file_path = file_path.as_ref(); + loaded_paths.push(file_path.to_owned()); let contents = match fs::read(file_path) { Ok(bytes) => bytes, Err(e) => { @@ -101,10 +104,14 @@ pub(crate) fn load_string>( } } -fn load_external_files(names: &[String], dcx: DiagCtxtHandle<'_>) -> Option { +fn load_external_files( + names: &[String], + dcx: DiagCtxtHandle<'_>, + loaded_paths: &mut Vec, +) -> Option { let mut out = String::new(); for name in names { - let Ok(s) = load_string(name, dcx) else { return None }; + let Ok(s) = load_string(name, dcx, loaded_paths) else { return None }; out.push_str(&s); out.push('\n'); } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index a3cdc4f687f2..7431ff8e1ade 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -799,7 +799,7 @@ fn main_args(early_dcx: &mut EarlyDiagCtxt, at_args: &[String]) { // Note that we discard any distinction between different non-zero exit // codes from `from_matches` here. - let (input, options, render_options) = + let (input, options, render_options, loaded_paths) = match config::Options::from_matches(early_dcx, &matches, args) { Some(opts) => opts, None => return, @@ -870,6 +870,12 @@ fn main_args(early_dcx: &mut EarlyDiagCtxt, at_args: &[String]) { interface::run_compiler(config, |compiler| { let sess = &compiler.sess; + // Register the loaded external files in the source map so they show up in depinfo. + // We can't load them via the source map because it gets created after we process the options. + for external_path in &loaded_paths { + let _ = sess.source_map().load_file(external_path); + } + if sess.opts.describe_lints { rustc_driver::describe_lints(sess, registered_lints); return; diff --git a/src/librustdoc/scrape_examples.rs b/src/librustdoc/scrape_examples.rs index fceacb69fb55..4d29c74e1eb5 100644 --- a/src/librustdoc/scrape_examples.rs +++ b/src/librustdoc/scrape_examples.rs @@ -333,9 +333,11 @@ pub(crate) fn run( pub(crate) fn load_call_locations( with_examples: Vec, dcx: DiagCtxtHandle<'_>, + loaded_paths: &mut Vec, ) -> AllCallLocations { let mut all_calls: AllCallLocations = FxIndexMap::default(); for path in with_examples { + loaded_paths.push(path.clone().into()); let bytes = match fs::read(&path) { Ok(bytes) => bytes, Err(e) => dcx.fatal(format!("failed to load examples: {e}")), diff --git a/tests/run-make/rustdoc-dep-info/after.md b/tests/run-make/rustdoc-dep-info/after.md new file mode 100644 index 000000000000..10d4b4c41164 --- /dev/null +++ b/tests/run-make/rustdoc-dep-info/after.md @@ -0,0 +1 @@ +meow! :3 diff --git a/tests/run-make/rustdoc-dep-info/before.html b/tests/run-make/rustdoc-dep-info/before.html new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/run-make/rustdoc-dep-info/extend.css b/tests/run-make/rustdoc-dep-info/extend.css new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/run-make/rustdoc-dep-info/rmake.rs b/tests/run-make/rustdoc-dep-info/rmake.rs index db7a00a5ce21..625f81fd428e 100644 --- a/tests/run-make/rustdoc-dep-info/rmake.rs +++ b/tests/run-make/rustdoc-dep-info/rmake.rs @@ -9,13 +9,26 @@ use run_make_support::{path, rfs, rustdoc}; fn main() { // We're only emitting dep info, so we shouldn't be running static analysis to // figure out that this program is erroneous. - rustdoc().input("lib.rs").arg("-Zunstable-options").emit("dep-info").run(); + // Ensure that all kinds of input reading flags end up in dep-info. + rustdoc() + .input("lib.rs") + .arg("-Zunstable-options") + .arg("--html-before-content=before.html") + .arg("--markdown-after-content=after.md") + .arg("--extend-css=extend.css") + .arg("--theme=theme.css") + .emit("dep-info") + .run(); let content = rfs::read_to_string("foo.d"); assert_contains(&content, "lib.rs:"); assert_contains(&content, "foo.rs:"); assert_contains(&content, "bar.rs:"); assert_contains(&content, "doc.md:"); + assert_contains(&content, "after.md:"); + assert_contains(&content, "before.html:"); + assert_contains(&content, "extend.css:"); + assert_contains(&content, "theme.css:"); // Now we check that we can provide a file name to the `dep-info` argument. rustdoc().input("lib.rs").arg("-Zunstable-options").emit("dep-info=bla.d").run(); diff --git a/tests/run-make/rustdoc-dep-info/theme.css b/tests/run-make/rustdoc-dep-info/theme.css new file mode 100644 index 000000000000..459daffa9a19 --- /dev/null +++ b/tests/run-make/rustdoc-dep-info/theme.css @@ -0,0 +1 @@ +/* This is not a valid theme but that doesn't really matter */ From 081b5654789f60d7303e05a26f86c80d0594f531 Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 28 Jul 2025 19:50:53 +0100 Subject: [PATCH 258/809] 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 aa9767290e46c9c73fa1fd3abb52277b4d07cfae Mon Sep 17 00:00:00 2001 From: Scott Schafer Date: Fri, 30 May 2025 16:03:32 -0600 Subject: [PATCH 259/809] feat: Right align line numbers --- compiler/rustc_errors/src/emitter.rs | 50 +++++++++++-------- compiler/rustc_parse/src/parser/tests.rs | 48 +++++++++--------- .../foo.stderr | 12 ++--- .../doctest/standalone-warning-2024.stderr | 2 +- .../ui-testing-optout.stderr | 2 +- tests/ui/modules/issue-107649.stderr | 4 +- 6 files changed, 64 insertions(+), 54 deletions(-) diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 95400ac2ca3b..46a4a1868247 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -713,8 +713,7 @@ impl HumanEmitter { Style::LineNumber, ); } - buffer.puts(line_offset, 0, &self.maybe_anonymized(line_index), Style::LineNumber); - + self.draw_line_num(buffer, line_index, line_offset, width_offset - 3); self.draw_col_separator_no_space(buffer, line_offset, width_offset - 2); left } @@ -2128,11 +2127,11 @@ impl HumanEmitter { // Account for a suggestion to completely remove a line(s) with whitespace (#94192). let line_end = sm.lookup_char_pos(parts[0].span.hi()).line; for line in line_start..=line_end { - buffer.puts( + self.draw_line_num( + &mut buffer, + line, row_num - 1 + line - line_start, - 0, - &self.maybe_anonymized(line), - Style::LineNumber, + max_line_num_len, ); buffer.puts( row_num - 1 + line - line_start, @@ -2612,12 +2611,7 @@ impl HumanEmitter { // For more info: https://github.com/rust-lang/rust/issues/92741 let lines_to_remove = file_lines.lines.iter().take(file_lines.lines.len() - 1); for (index, line_to_remove) in lines_to_remove.enumerate() { - buffer.puts( - *row_num - 1, - 0, - &self.maybe_anonymized(line_num + index), - Style::LineNumber, - ); + self.draw_line_num(buffer, line_num + index, *row_num - 1, max_line_num_len); buffer.puts(*row_num - 1, max_line_num_len + 1, "- ", Style::Removal); let line = normalize_whitespace( &file_lines.file.get_line(line_to_remove.line_index).unwrap(), @@ -2634,11 +2628,11 @@ impl HumanEmitter { let last_line_index = file_lines.lines[file_lines.lines.len() - 1].line_index; let last_line = &file_lines.file.get_line(last_line_index).unwrap(); if last_line != line_to_add { - buffer.puts( + self.draw_line_num( + buffer, + line_num + file_lines.lines.len() - 1, *row_num - 1, - 0, - &self.maybe_anonymized(line_num + file_lines.lines.len() - 1), - Style::LineNumber, + max_line_num_len, ); buffer.puts(*row_num - 1, max_line_num_len + 1, "- ", Style::Removal); buffer.puts( @@ -2661,7 +2655,7 @@ impl HumanEmitter { // 2 - .await // | // *row_num -= 1; - buffer.puts(*row_num, 0, &self.maybe_anonymized(line_num), Style::LineNumber); + self.draw_line_num(buffer, line_num, *row_num, max_line_num_len); buffer.puts(*row_num, max_line_num_len + 1, "+ ", Style::Addition); buffer.append(*row_num, &normalize_whitespace(line_to_add), Style::NoStyle); } else { @@ -2671,7 +2665,7 @@ impl HumanEmitter { *row_num -= 2; } } else if is_multiline { - buffer.puts(*row_num, 0, &self.maybe_anonymized(line_num), Style::LineNumber); + self.draw_line_num(buffer, line_num, *row_num, max_line_num_len); match &highlight_parts { [SubstitutionHighlight { start: 0, end }] if *end == line_to_add.len() => { buffer.puts(*row_num, max_line_num_len + 1, "+ ", Style::Addition); @@ -2702,11 +2696,11 @@ impl HumanEmitter { Style::NoStyle, ); } else if let DisplaySuggestion::Add = show_code_change { - buffer.puts(*row_num, 0, &self.maybe_anonymized(line_num), Style::LineNumber); + self.draw_line_num(buffer, line_num, *row_num, max_line_num_len); buffer.puts(*row_num, max_line_num_len + 1, "+ ", Style::Addition); buffer.append(*row_num, &normalize_whitespace(line_to_add), Style::NoStyle); } else { - buffer.puts(*row_num, 0, &self.maybe_anonymized(line_num), Style::LineNumber); + self.draw_line_num(buffer, line_num, *row_num, max_line_num_len); self.draw_col_separator(buffer, *row_num, max_line_num_len + 1); buffer.append(*row_num, &normalize_whitespace(line_to_add), Style::NoStyle); } @@ -3016,6 +3010,22 @@ impl HumanEmitter { OutputTheme::Unicode => "…", } } + + fn draw_line_num( + &self, + buffer: &mut StyledBuffer, + line_num: usize, + line_offset: usize, + max_line_num_len: usize, + ) { + let line_num = self.maybe_anonymized(line_num); + buffer.puts( + line_offset, + max_line_num_len.saturating_sub(str_width(&line_num)), + &line_num, + Style::LineNumber, + ); + } } #[derive(Debug, Clone, Copy)] diff --git a/compiler/rustc_parse/src/parser/tests.rs b/compiler/rustc_parse/src/parser/tests.rs index 15679d23bc56..43a1d779a75d 100644 --- a/compiler/rustc_parse/src/parser/tests.rs +++ b/compiler/rustc_parse/src/parser/tests.rs @@ -2114,15 +2114,15 @@ fn foo() { error: foo --> test.rs:3:6 | -3 | X0 Y0 Z0 + 3 | X0 Y0 Z0 | _______^ -4 | | X1 Y1 Z1 + 4 | | X1 Y1 Z1 | | ____^____- | ||____| | | `X` is a good letter -5 | | 1 -6 | | 2 -7 | | 3 + 5 | | 1 + 6 | | 2 + 7 | | 3 ... | 15 | | X2 Y2 Z2 16 | | X3 Y3 Z3 @@ -2133,15 +2133,15 @@ error: foo error: foo ╭▸ test.rs:3:6 │ -3 │ X0 Y0 Z0 + 3 │ X0 Y0 Z0 │ ┏━━━━━━━┛ -4 │ ┃ X1 Y1 Z1 + 4 │ ┃ X1 Y1 Z1 │ ┃┌────╿────┘ │ ┗│━━━━┥ │ │ `X` is a good letter -5 │ │ 1 -6 │ │ 2 -7 │ │ 3 + 5 │ │ 1 + 6 │ │ 2 + 7 │ │ 3 ‡ │ 15 │ │ X2 Y2 Z2 16 │ │ X3 Y3 Z3 @@ -2189,15 +2189,15 @@ fn foo() { error: foo --> test.rs:3:6 | -3 | X0 Y0 Z0 + 3 | X0 Y0 Z0 | _______^ -4 | | 1 -5 | | 2 -6 | | 3 -7 | | X1 Y1 Z1 + 4 | | 1 + 5 | | 2 + 6 | | 3 + 7 | | X1 Y1 Z1 | | _________- -8 | || 4 -9 | || 5 + 8 | || 4 + 9 | || 5 10 | || 6 11 | || X2 Y2 Z2 | ||__________- `Z` is a good letter too @@ -2211,15 +2211,15 @@ error: foo error: foo ╭▸ test.rs:3:6 │ -3 │ X0 Y0 Z0 + 3 │ X0 Y0 Z0 │ ┏━━━━━━━┛ -4 │ ┃ 1 -5 │ ┃ 2 -6 │ ┃ 3 -7 │ ┃ X1 Y1 Z1 + 4 │ ┃ 1 + 5 │ ┃ 2 + 6 │ ┃ 3 + 7 │ ┃ X1 Y1 Z1 │ ┃┌─────────┘ -8 │ ┃│ 4 -9 │ ┃│ 5 + 8 │ ┃│ 4 + 9 │ ┃│ 5 10 │ ┃│ 6 11 │ ┃│ X2 Y2 Z2 │ ┃└──────────┘ `Z` is a good letter too diff --git a/tests/run-make/crate-loading-crate-depends-on-itself/foo.stderr b/tests/run-make/crate-loading-crate-depends-on-itself/foo.stderr index 7f131153540b..9433a0ba00e8 100644 --- a/tests/run-make/crate-loading-crate-depends-on-itself/foo.stderr +++ b/tests/run-make/crate-loading-crate-depends-on-itself/foo.stderr @@ -7,19 +7,19 @@ error[E0277]: the trait bound `foo::Struct: Trait` is not satisfied note: there are multiple different versions of crate `foo` in the dependency graph --> foo-current.rs:7:1 | -4 | extern crate foo; + 4 | extern crate foo; | ----------------- one version of crate `foo` used here, as a direct dependency of the current crate -5 | -6 | pub struct Struct; + 5 | + 6 | pub struct Struct; | ----------------- this type implements the required trait -7 | pub trait Trait {} + 7 | pub trait Trait {} | ^^^^^^^^^^^^^^^ this is the required trait | ::: foo-prev.rs:X:Y | -4 | pub struct Struct; + 4 | pub struct Struct; | ----------------- this type doesn't implement the required trait -5 | pub trait Trait {} + 5 | pub trait Trait {} | --------------- this is the found trait = note: two types coming from two different versions of the same crate are different types even if they look the same = help: you can use `cargo tree` to explore your dependency tree diff --git a/tests/rustdoc-ui/doctest/standalone-warning-2024.stderr b/tests/rustdoc-ui/doctest/standalone-warning-2024.stderr index bfc1e9194045..ce65557c2c4a 100644 --- a/tests/rustdoc-ui/doctest/standalone-warning-2024.stderr +++ b/tests/rustdoc-ui/doctest/standalone-warning-2024.stderr @@ -15,7 +15,7 @@ error: unknown attribute `standalone` note: the lint level is defined here --> $DIR/standalone-warning-2024.rs:9:9 | -9 | #![deny(warnings)] + 9 | #![deny(warnings)] | ^^^^^^^^ = note: `#[deny(rustdoc::invalid_codeblock_attributes)]` implied by `#[deny(warnings)]` diff --git a/tests/ui/compiletest-self-test/ui-testing-optout.stderr b/tests/ui/compiletest-self-test/ui-testing-optout.stderr index 652c472c0bcf..f1d03eab14a9 100644 --- a/tests/ui/compiletest-self-test/ui-testing-optout.stderr +++ b/tests/ui/compiletest-self-test/ui-testing-optout.stderr @@ -16,7 +16,7 @@ error[E0412]: cannot find type `D` in this scope error[E0412]: cannot find type `F` in this scope --> $DIR/ui-testing-optout.rs:92:10 | -4 | type A = B; + 4 | type A = B; | ----------- similarly named type alias `A` defined here ... 92 | type E = F; diff --git a/tests/ui/modules/issue-107649.stderr b/tests/ui/modules/issue-107649.stderr index 802ac669a10e..49d7cb4e0aad 100644 --- a/tests/ui/modules/issue-107649.stderr +++ b/tests/ui/modules/issue-107649.stderr @@ -9,8 +9,8 @@ error[E0277]: `Dummy` doesn't implement `Debug` help: consider annotating `Dummy` with `#[derive(Debug)]` --> $DIR/auxiliary/dummy_lib.rs:2:1 | -2 + #[derive(Debug)] -3 | pub struct Dummy; + 2 + #[derive(Debug)] + 3 | pub struct Dummy; | error: aborting due to 1 previous error From be9d3bcfed2df9926f620af84bde1d687a9f6962 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 4 Jul 2025 19:13:24 +0000 Subject: [PATCH 260/809] Make resolve_fn_signature responsible for its own rib. --- compiler/rustc_resolve/src/late.rs | 129 ++++++++++++----------------- 1 file changed, 54 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index ed9622a0d81c..261d099abdc0 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -910,22 +910,15 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc span, |this| { this.visit_generic_params(&fn_ptr.generic_params, false); - this.with_lifetime_rib( - LifetimeRibKind::AnonymousCreateParameter { - binder: ty.id, - report_in_path: false, - }, - |this| { - this.resolve_fn_signature( - ty.id, - false, - // We don't need to deal with patterns in parameters, because - // they are not possible for foreign or bodiless functions. - fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)), - &fn_ptr.decl.output, - ) - }, - ); + this.resolve_fn_signature( + ty.id, + false, + // We don't need to deal with patterns in parameters, because + // they are not possible for foreign or bodiless functions. + fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)), + &fn_ptr.decl.output, + false, + ) }, ) } @@ -1042,19 +1035,12 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc self.visit_fn_header(&sig.header); self.visit_ident(ident); self.visit_generics(generics); - self.with_lifetime_rib( - LifetimeRibKind::AnonymousCreateParameter { - binder: fn_id, - report_in_path: false, - }, - |this| { - this.resolve_fn_signature( - fn_id, - sig.decl.has_self(), - sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)), - &sig.decl.output, - ); - }, + self.resolve_fn_signature( + fn_id, + sig.decl.has_self(), + sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)), + &sig.decl.output, + false, ); return; } @@ -1080,22 +1066,15 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc .coroutine_kind .map(|coroutine_kind| coroutine_kind.return_id()); - this.with_lifetime_rib( - LifetimeRibKind::AnonymousCreateParameter { - binder: fn_id, - report_in_path: coro_node_id.is_some(), - }, - |this| { - this.resolve_fn_signature( - fn_id, - declaration.has_self(), - declaration - .inputs - .iter() - .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)), - &declaration.output, - ); - }, + this.resolve_fn_signature( + fn_id, + declaration.has_self(), + declaration + .inputs + .iter() + .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)), + &declaration.output, + coro_node_id.is_some(), ); if let Some(contract) = contract { @@ -1307,19 +1286,12 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc kind: LifetimeBinderKind::PolyTrait, .. } => { - self.with_lifetime_rib( - LifetimeRibKind::AnonymousCreateParameter { - binder, - report_in_path: false, - }, - |this| { - this.resolve_fn_signature( - binder, - false, - p_args.inputs.iter().map(|ty| (None, &**ty)), - &p_args.output, - ) - }, + self.resolve_fn_signature( + binder, + false, + p_args.inputs.iter().map(|ty| (None, &**ty)), + &p_args.output, + false, ); break; } @@ -2236,25 +2208,32 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { has_self: bool, inputs: impl Iterator, &'ast Ty)> + Clone, output_ty: &'ast FnRetTy, + report_elided_lifetimes_in_path: bool, ) { - // Add each argument to the rib. - let elision_lifetime = self.resolve_fn_params(has_self, inputs); - debug!(?elision_lifetime); - - let outer_failures = take(&mut self.diag_metadata.current_elision_failures); - let output_rib = if let Ok(res) = elision_lifetime.as_ref() { - self.r.lifetime_elision_allowed.insert(fn_id); - LifetimeRibKind::Elided(*res) - } else { - LifetimeRibKind::ElisionFailure + let rib = LifetimeRibKind::AnonymousCreateParameter { + binder: fn_id, + report_in_path: report_elided_lifetimes_in_path, }; - self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty)); - let elision_failures = - replace(&mut self.diag_metadata.current_elision_failures, outer_failures); - if !elision_failures.is_empty() { - let Err(failure_info) = elision_lifetime else { bug!() }; - self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info)); - } + self.with_lifetime_rib(rib, |this| { + // Add each argument to the rib. + let elision_lifetime = this.resolve_fn_params(has_self, inputs); + debug!(?elision_lifetime); + + let outer_failures = take(&mut this.diag_metadata.current_elision_failures); + let output_rib = if let Ok(res) = elision_lifetime.as_ref() { + this.r.lifetime_elision_allowed.insert(fn_id); + LifetimeRibKind::Elided(*res) + } else { + LifetimeRibKind::ElisionFailure + }; + this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty)); + let elision_failures = + replace(&mut this.diag_metadata.current_elision_failures, outer_failures); + if !elision_failures.is_empty() { + let Err(failure_info) = elision_lifetime else { bug!() }; + this.report_missing_lifetime_specifiers(elision_failures, Some(failure_info)); + } + }); } /// Resolve inside function parameters and parameter types. From 0e53d8533bf0bb8d6bc59bb000fe7cc7a361902e Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 16 Jun 2025 15:25:31 +0000 Subject: [PATCH 261/809] 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 7ca4d1f6a155e802b31cfc1f0971f3916aa8e02d Mon Sep 17 00:00:00 2001 From: Zalathar Date: Tue, 29 Jul 2025 10:29:32 +1000 Subject: [PATCH 262/809] coverage: Regression test for "function name is empty" bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bug was triggered by a particular usage of the `?` try operator in a proc-macro expansion. Thanks to lqd for the minimization. Co-authored-by: Rémy Rakic --- .../coverage/auxiliary/try_in_macro_helper.rs | 31 +++++++++++++ tests/coverage/try-in-macro.attr.cov-map | 20 +++++++++ tests/coverage/try-in-macro.attr.coverage | 44 +++++++++++++++++++ tests/coverage/try-in-macro.bang.cov-map | 20 +++++++++ tests/coverage/try-in-macro.bang.coverage | 44 +++++++++++++++++++ tests/coverage/try-in-macro.derive.cov-map | 20 +++++++++ tests/coverage/try-in-macro.derive.coverage | 44 +++++++++++++++++++ tests/coverage/try-in-macro.rs | 43 ++++++++++++++++++ 8 files changed, 266 insertions(+) create mode 100644 tests/coverage/auxiliary/try_in_macro_helper.rs create mode 100644 tests/coverage/try-in-macro.attr.cov-map create mode 100644 tests/coverage/try-in-macro.attr.coverage create mode 100644 tests/coverage/try-in-macro.bang.cov-map create mode 100644 tests/coverage/try-in-macro.bang.coverage create mode 100644 tests/coverage/try-in-macro.derive.cov-map create mode 100644 tests/coverage/try-in-macro.derive.coverage create mode 100644 tests/coverage/try-in-macro.rs diff --git a/tests/coverage/auxiliary/try_in_macro_helper.rs b/tests/coverage/auxiliary/try_in_macro_helper.rs new file mode 100644 index 000000000000..27d2af15b055 --- /dev/null +++ b/tests/coverage/auxiliary/try_in_macro_helper.rs @@ -0,0 +1,31 @@ +//@ edition: 2024 +// (The proc-macro crate doesn't need to be instrumented.) +//@ compile-flags: -Cinstrument-coverage=off + +use proc_macro::TokenStream; + +/// Minimized form of `#[derive(arbitrary::Arbitrary)]` that still triggers +/// the original bug. +const CODE: &str = " + impl Arbitrary for MyEnum { + fn try_size_hint() -> Option { + Some(0)?; + None + } + } +"; + +#[proc_macro_attribute] +pub fn attr(_attr: TokenStream, _item: TokenStream) -> TokenStream { + CODE.parse().unwrap() +} + +#[proc_macro] +pub fn bang(_item: TokenStream) -> TokenStream { + CODE.parse().unwrap() +} + +#[proc_macro_derive(Arbitrary)] +pub fn derive_arbitrary(_item: TokenStream) -> TokenStream { + CODE.parse().unwrap() +} diff --git a/tests/coverage/try-in-macro.attr.cov-map b/tests/coverage/try-in-macro.attr.cov-map new file mode 100644 index 000000000000..7111e89637ce --- /dev/null +++ b/tests/coverage/try-in-macro.attr.cov-map @@ -0,0 +1,20 @@ +Function name: ::try_size_hint +Raw bytes (9): 0x[01, 01, 00, 01, 00, 1e, 2a, 00, 2b] +Number of files: 1 +- file 0 => $DIR/try-in-macro.rs +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 30, 42) to (start + 0, 43) +Highest counter ID seen: (none) + +Function name: try_in_macro::main +Raw bytes (19): 0x[01, 01, 00, 03, 01, 29, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] +Number of files: 1 +- file 0 => $DIR/try-in-macro.rs +Number of expressions: 0 +Number of file 0 mappings: 3 +- Code(Counter(0)) at (prev + 41, 1) to (start + 0, 10) +- Code(Counter(0)) at (prev + 1, 5) to (start + 0, 26) +- Code(Counter(0)) at (prev + 1, 1) to (start + 0, 2) +Highest counter ID seen: c0 + diff --git a/tests/coverage/try-in-macro.attr.coverage b/tests/coverage/try-in-macro.attr.coverage new file mode 100644 index 000000000000..457a161f3c79 --- /dev/null +++ b/tests/coverage/try-in-macro.attr.coverage @@ -0,0 +1,44 @@ + LL| |//! Regression test for . + LL| |//! + LL| |//! The changes in exposed a + LL| |//! latent bug that would sometimes cause the compiler to emit a covfun record + LL| |//! for a function, but not emit a corresponding PGO symbol name entry, because + LL| |//! the function did not have any physical coverage counters. The `llvm-cov` + LL| |//! tool would then fail to resolve the covfun record's function name hash, + LL| |//! and exit with the cryptic error: + LL| |//! + LL| |//! ```text + LL| |//! malformed instrumentation profile data: function name is empty + LL| |//! ``` + LL| |//! + LL| |//! The bug was then triggered in the wild by the macro-expansion of + LL| |//! `#[derive(arbitrary::Arbitrary)]`. + LL| |//! + LL| |//! This test uses a minimized form of the `Arbitrary` derive macro that was + LL| |//! found to still trigger the original bug. The bug could also be triggered + LL| |//! by a bang proc-macro or an attribute proc-macro. + LL| | + LL| |//@ edition: 2024 + LL| |//@ revisions: attr bang derive + LL| |//@ proc-macro: try_in_macro_helper.rs + LL| | + LL| |trait Arbitrary { + LL| | fn try_size_hint() -> Option; + LL| |} + LL| | + LL| |// Expand via an attribute proc-macro. + LL| |#[cfg_attr(attr, try_in_macro_helper::attr)] + LL| |const _: () = (); + LL| | + LL| |// Expand via a regular bang-style proc-macro. + LL| |#[cfg(bang)] + LL| |try_in_macro_helper::bang!(); + LL| | + LL| |// Expand via a derive proc-macro. + LL| |#[cfg_attr(derive, derive(try_in_macro_helper::Arbitrary))] + LL| |enum MyEnum {} + LL| | + LL| 1|fn main() { + LL| 1| MyEnum::try_size_hint(); + LL| 1|} + diff --git a/tests/coverage/try-in-macro.bang.cov-map b/tests/coverage/try-in-macro.bang.cov-map new file mode 100644 index 000000000000..80bd91a993c0 --- /dev/null +++ b/tests/coverage/try-in-macro.bang.cov-map @@ -0,0 +1,20 @@ +Function name: ::try_size_hint +Raw bytes (9): 0x[01, 01, 00, 01, 00, 23, 1c, 00, 1d] +Number of files: 1 +- file 0 => $DIR/try-in-macro.rs +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 35, 28) to (start + 0, 29) +Highest counter ID seen: (none) + +Function name: try_in_macro::main +Raw bytes (19): 0x[01, 01, 00, 03, 01, 29, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] +Number of files: 1 +- file 0 => $DIR/try-in-macro.rs +Number of expressions: 0 +Number of file 0 mappings: 3 +- Code(Counter(0)) at (prev + 41, 1) to (start + 0, 10) +- Code(Counter(0)) at (prev + 1, 5) to (start + 0, 26) +- Code(Counter(0)) at (prev + 1, 1) to (start + 0, 2) +Highest counter ID seen: c0 + diff --git a/tests/coverage/try-in-macro.bang.coverage b/tests/coverage/try-in-macro.bang.coverage new file mode 100644 index 000000000000..457a161f3c79 --- /dev/null +++ b/tests/coverage/try-in-macro.bang.coverage @@ -0,0 +1,44 @@ + LL| |//! Regression test for . + LL| |//! + LL| |//! The changes in exposed a + LL| |//! latent bug that would sometimes cause the compiler to emit a covfun record + LL| |//! for a function, but not emit a corresponding PGO symbol name entry, because + LL| |//! the function did not have any physical coverage counters. The `llvm-cov` + LL| |//! tool would then fail to resolve the covfun record's function name hash, + LL| |//! and exit with the cryptic error: + LL| |//! + LL| |//! ```text + LL| |//! malformed instrumentation profile data: function name is empty + LL| |//! ``` + LL| |//! + LL| |//! The bug was then triggered in the wild by the macro-expansion of + LL| |//! `#[derive(arbitrary::Arbitrary)]`. + LL| |//! + LL| |//! This test uses a minimized form of the `Arbitrary` derive macro that was + LL| |//! found to still trigger the original bug. The bug could also be triggered + LL| |//! by a bang proc-macro or an attribute proc-macro. + LL| | + LL| |//@ edition: 2024 + LL| |//@ revisions: attr bang derive + LL| |//@ proc-macro: try_in_macro_helper.rs + LL| | + LL| |trait Arbitrary { + LL| | fn try_size_hint() -> Option; + LL| |} + LL| | + LL| |// Expand via an attribute proc-macro. + LL| |#[cfg_attr(attr, try_in_macro_helper::attr)] + LL| |const _: () = (); + LL| | + LL| |// Expand via a regular bang-style proc-macro. + LL| |#[cfg(bang)] + LL| |try_in_macro_helper::bang!(); + LL| | + LL| |// Expand via a derive proc-macro. + LL| |#[cfg_attr(derive, derive(try_in_macro_helper::Arbitrary))] + LL| |enum MyEnum {} + LL| | + LL| 1|fn main() { + LL| 1| MyEnum::try_size_hint(); + LL| 1|} + diff --git a/tests/coverage/try-in-macro.derive.cov-map b/tests/coverage/try-in-macro.derive.cov-map new file mode 100644 index 000000000000..6646b6693bae --- /dev/null +++ b/tests/coverage/try-in-macro.derive.cov-map @@ -0,0 +1,20 @@ +Function name: ::try_size_hint +Raw bytes (9): 0x[01, 01, 00, 01, 00, 26, 38, 00, 39] +Number of files: 1 +- file 0 => $DIR/try-in-macro.rs +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 38, 56) to (start + 0, 57) +Highest counter ID seen: (none) + +Function name: try_in_macro::main +Raw bytes (19): 0x[01, 01, 00, 03, 01, 29, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] +Number of files: 1 +- file 0 => $DIR/try-in-macro.rs +Number of expressions: 0 +Number of file 0 mappings: 3 +- Code(Counter(0)) at (prev + 41, 1) to (start + 0, 10) +- Code(Counter(0)) at (prev + 1, 5) to (start + 0, 26) +- Code(Counter(0)) at (prev + 1, 1) to (start + 0, 2) +Highest counter ID seen: c0 + diff --git a/tests/coverage/try-in-macro.derive.coverage b/tests/coverage/try-in-macro.derive.coverage new file mode 100644 index 000000000000..457a161f3c79 --- /dev/null +++ b/tests/coverage/try-in-macro.derive.coverage @@ -0,0 +1,44 @@ + LL| |//! Regression test for . + LL| |//! + LL| |//! The changes in exposed a + LL| |//! latent bug that would sometimes cause the compiler to emit a covfun record + LL| |//! for a function, but not emit a corresponding PGO symbol name entry, because + LL| |//! the function did not have any physical coverage counters. The `llvm-cov` + LL| |//! tool would then fail to resolve the covfun record's function name hash, + LL| |//! and exit with the cryptic error: + LL| |//! + LL| |//! ```text + LL| |//! malformed instrumentation profile data: function name is empty + LL| |//! ``` + LL| |//! + LL| |//! The bug was then triggered in the wild by the macro-expansion of + LL| |//! `#[derive(arbitrary::Arbitrary)]`. + LL| |//! + LL| |//! This test uses a minimized form of the `Arbitrary` derive macro that was + LL| |//! found to still trigger the original bug. The bug could also be triggered + LL| |//! by a bang proc-macro or an attribute proc-macro. + LL| | + LL| |//@ edition: 2024 + LL| |//@ revisions: attr bang derive + LL| |//@ proc-macro: try_in_macro_helper.rs + LL| | + LL| |trait Arbitrary { + LL| | fn try_size_hint() -> Option; + LL| |} + LL| | + LL| |// Expand via an attribute proc-macro. + LL| |#[cfg_attr(attr, try_in_macro_helper::attr)] + LL| |const _: () = (); + LL| | + LL| |// Expand via a regular bang-style proc-macro. + LL| |#[cfg(bang)] + LL| |try_in_macro_helper::bang!(); + LL| | + LL| |// Expand via a derive proc-macro. + LL| |#[cfg_attr(derive, derive(try_in_macro_helper::Arbitrary))] + LL| |enum MyEnum {} + LL| | + LL| 1|fn main() { + LL| 1| MyEnum::try_size_hint(); + LL| 1|} + diff --git a/tests/coverage/try-in-macro.rs b/tests/coverage/try-in-macro.rs new file mode 100644 index 000000000000..ab9d66754180 --- /dev/null +++ b/tests/coverage/try-in-macro.rs @@ -0,0 +1,43 @@ +//! Regression test for . +//! +//! The changes in exposed a +//! latent bug that would sometimes cause the compiler to emit a covfun record +//! for a function, but not emit a corresponding PGO symbol name entry, because +//! the function did not have any physical coverage counters. The `llvm-cov` +//! tool would then fail to resolve the covfun record's function name hash, +//! and exit with the cryptic error: +//! +//! ```text +//! malformed instrumentation profile data: function name is empty +//! ``` +//! +//! The bug was then triggered in the wild by the macro-expansion of +//! `#[derive(arbitrary::Arbitrary)]`. +//! +//! This test uses a minimized form of the `Arbitrary` derive macro that was +//! found to still trigger the original bug. The bug could also be triggered +//! by a bang proc-macro or an attribute proc-macro. + +//@ edition: 2024 +//@ revisions: attr bang derive +//@ proc-macro: try_in_macro_helper.rs + +trait Arbitrary { + fn try_size_hint() -> Option; +} + +// Expand via an attribute proc-macro. +#[cfg_attr(attr, try_in_macro_helper::attr)] +const _: () = (); + +// Expand via a regular bang-style proc-macro. +#[cfg(bang)] +try_in_macro_helper::bang!(); + +// Expand via a derive proc-macro. +#[cfg_attr(derive, derive(try_in_macro_helper::Arbitrary))] +enum MyEnum {} + +fn main() { + MyEnum::try_size_hint(); +} From dc33eb6c424a1325e53644517f78c3461591211d Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 29 Jul 2025 08:10:55 +0200 Subject: [PATCH 263/809] update lockfile and bless tidy --- Cargo.lock | 139 +++++++++++++++++++++ src/bootstrap/src/utils/proc_macro_deps.rs | 5 + 2 files changed, 144 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 6be3bced5e16..4be66fe25d3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -466,6 +466,8 @@ version = "1.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" dependencies = [ + "jobserver", + "libc", "shlex", ] @@ -655,6 +657,26 @@ dependencies = [ "serde", ] +[[package]] +name = "cmake" +version = "0.1.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" +dependencies = [ + "cc", +] + +[[package]] +name = "codespan-reporting" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81" +dependencies = [ + "serde", + "termcolor", + "unicode-width 0.2.1", +] + [[package]] name = "collect-license-metadata" version = "0.1.0" @@ -913,6 +935,68 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "cxx" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3523cc02ad831111491dd64b27ad999f1ae189986728e477604e61b81f828df" +dependencies = [ + "cc", + "cxxbridge-cmd", + "cxxbridge-flags", + "cxxbridge-macro", + "foldhash", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "212b754247a6f07b10fa626628c157593f0abf640a3dd04cce2760eca970f909" +dependencies = [ + "cc", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "scratch", + "syn 2.0.104", +] + +[[package]] +name = "cxxbridge-cmd" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a20413ec2e742520ba6837c9324b55ffac24ead47491a6e29f933c5b135a" +dependencies = [ + "clap", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a258b6069020b4e5da6415df94a50ee4f586a6c38b037a180e940a43d06a070d" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8dec184b52be5008d6eaf7e62fc1802caf1ad1227d11b3b7df2c409c7ffc3f4" +dependencies = [ + "indexmap", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.104", +] + [[package]] name = "darling" version = "0.20.11" @@ -1373,6 +1457,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "genmc-sys" +version = "0.1.0" +dependencies = [ + "cc", + "cmake", + "cxx", + "cxx-build", + "git2", +] + [[package]] name = "getopts" version = "0.2.23" @@ -1427,6 +1522,21 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "git2" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2deb07a133b1520dc1a5690e9bd08950108873d7ed5de38dcc74d3b5ebffa110" +dependencies = [ + "bitflags", + "libc", + "libgit2-sys", + "log", + "openssl-probe", + "openssl-sys", + "url", +] + [[package]] name = "glob" version = "0.3.2" @@ -2060,6 +2170,19 @@ dependencies = [ "cc", ] +[[package]] +name = "libgit2-sys" +version = "0.18.2+1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c42fe03df2bd3c53a3a9c7317ad91d80c81cd1fb0caec8d7cc4cd2bfa10c222" +dependencies = [ + "cc", + "libc", + "libz-sys", + "openssl-sys", + "pkg-config", +] + [[package]] name = "libloading" version = "0.8.8" @@ -2099,6 +2222,15 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "link-cplusplus" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6f6da007f968f9def0d65a05b187e2960183de70c160204ecfccf0ee330212" +dependencies = [ + "cc", +] + [[package]] name = "linkchecker" version = "0.1.0" @@ -2308,6 +2440,7 @@ dependencies = [ "chrono-tz", "colored 3.0.0", "directories", + "genmc-sys", "getrandom 0.3.3", "ipc-channel", "libc", @@ -4877,6 +5010,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scratch" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f6280af86e5f559536da57a45ebc84948833b3bee313a7dd25232e09c878a52" + [[package]] name = "self_cell" version = "1.2.0" diff --git a/src/bootstrap/src/utils/proc_macro_deps.rs b/src/bootstrap/src/utils/proc_macro_deps.rs index 21c7fc89d7df..777c8601aa1d 100644 --- a/src/bootstrap/src/utils/proc_macro_deps.rs +++ b/src/bootstrap/src/utils/proc_macro_deps.rs @@ -3,6 +3,7 @@ /// See pub static CRATES: &[&str] = &[ // tidy-alphabetical-start + "allocator-api2", "annotate-snippets", "anstyle", "askama_parser", @@ -16,13 +17,17 @@ pub static CRATES: &[&str] = &[ "darling_core", "derive_builder_core", "digest", + "equivalent", "fluent-bundle", "fluent-langneg", "fluent-syntax", "fnv", + "foldhash", "generic-array", + "hashbrown", "heck", "ident_case", + "indexmap", "intl-memoizer", "intl_pluralrules", "libc", From 950a3b34ea25631749708029594f892df4399c7d Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Mon, 28 Jul 2025 01:12:05 -0700 Subject: [PATCH 264/809] Add a mir-opt pre-codegen test for dropping a `Box<[impl Copy]>` --- ...ace.PreCodegen.after.32bit.panic-abort.mir | 111 ++++++++++++++++++ ...ce.PreCodegen.after.32bit.panic-unwind.mir | 111 ++++++++++++++++++ ...ace.PreCodegen.after.64bit.panic-abort.mir | 111 ++++++++++++++++++ ...ce.PreCodegen.after.64bit.panic-unwind.mir | 111 ++++++++++++++++++ tests/mir-opt/pre-codegen/drop_boxed_slice.rs | 19 +++ 5 files changed, 463 insertions(+) create mode 100644 tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir create mode 100644 tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir create mode 100644 tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir create mode 100644 tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir create mode 100644 tests/mir-opt/pre-codegen/drop_boxed_slice.rs 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 new file mode 100644 index 000000000000..587e69154ea1 --- /dev/null +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-abort.mir @@ -0,0 +1,111 @@ +// MIR for `generic_in_place` after PreCodegen + +fn generic_in_place(_1: *mut Box<[T]>) -> () { + debug ptr => _1; + let mut _0: (); + scope 1 (inlined drop_in_place::> - shim(Some(Box<[T]>))) { + scope 2 (inlined as Drop>::drop) { + let _2: std::ptr::NonNull<[T]>; + let mut _3: *mut [T]; + let mut _4: *const [T]; + let _12: (); + scope 3 { + let _8: std::ptr::alignment::AlignmentEnum; + scope 4 { + scope 12 (inlined Layout::size) { + } + scope 13 (inlined Unique::<[T]>::cast::) { + scope 14 (inlined NonNull::<[T]>::cast::) { + scope 15 (inlined NonNull::<[T]>::as_ptr) { + } + } + } + scope 16 (inlined as From>>::from) { + scope 17 (inlined Unique::::as_non_null_ptr) { + } + } + scope 18 (inlined ::deallocate) { + let mut _9: *mut u8; + scope 19 (inlined Layout::size) { + } + scope 20 (inlined NonNull::::as_ptr) { + } + scope 21 (inlined std::alloc::dealloc) { + let mut _11: usize; + scope 22 (inlined Layout::size) { + } + scope 23 (inlined Layout::align) { + scope 24 (inlined std::ptr::Alignment::as_usize) { + let mut _10: u32; + } + } + } + } + } + scope 5 (inlined Unique::<[T]>::as_ptr) { + scope 6 (inlined NonNull::<[T]>::as_ptr) { + } + } + scope 7 (inlined Layout::for_value_raw::<[T]>) { + let mut _5: usize; + let mut _6: usize; + scope 8 { + scope 11 (inlined #[track_caller] Layout::from_size_align_unchecked) { + let mut _7: std::ptr::Alignment; + } + } + scope 9 (inlined size_of_val_raw::<[T]>) { + } + scope 10 (inlined align_of_val_raw::<[T]>) { + } + } + } + } + } + + bb0: { + StorageLive(_2); + _2 = copy (((*_1).0: std::ptr::Unique<[T]>).0: std::ptr::NonNull<[T]>); + StorageLive(_4); + _3 = copy _2 as *mut [T] (Transmute); + _4 = copy _2 as *const [T] (Transmute); + StorageLive(_6); + _5 = std::intrinsics::size_of_val::<[T]>(copy _4) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _6 = std::intrinsics::align_of_val::<[T]>(move _4) -> [return: bb2, unwind unreachable]; + } + + bb2: { + StorageLive(_7); + _7 = copy _6 as std::ptr::Alignment (Transmute); + _8 = move (_7.0: std::ptr::alignment::AlignmentEnum); + StorageDead(_7); + StorageDead(_6); + StorageDead(_4); + switchInt(copy _5) -> [0: bb5, otherwise: bb3]; + } + + bb3: { + 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: bb4, unwind unreachable]; + } + + bb4: { + StorageDead(_11); + StorageDead(_9); + goto -> bb5; + } + + bb5: { + StorageDead(_2); + return; + } +} 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 new file mode 100644 index 000000000000..587e69154ea1 --- /dev/null +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.32bit.panic-unwind.mir @@ -0,0 +1,111 @@ +// MIR for `generic_in_place` after PreCodegen + +fn generic_in_place(_1: *mut Box<[T]>) -> () { + debug ptr => _1; + let mut _0: (); + scope 1 (inlined drop_in_place::> - shim(Some(Box<[T]>))) { + scope 2 (inlined as Drop>::drop) { + let _2: std::ptr::NonNull<[T]>; + let mut _3: *mut [T]; + let mut _4: *const [T]; + let _12: (); + scope 3 { + let _8: std::ptr::alignment::AlignmentEnum; + scope 4 { + scope 12 (inlined Layout::size) { + } + scope 13 (inlined Unique::<[T]>::cast::) { + scope 14 (inlined NonNull::<[T]>::cast::) { + scope 15 (inlined NonNull::<[T]>::as_ptr) { + } + } + } + scope 16 (inlined as From>>::from) { + scope 17 (inlined Unique::::as_non_null_ptr) { + } + } + scope 18 (inlined ::deallocate) { + let mut _9: *mut u8; + scope 19 (inlined Layout::size) { + } + scope 20 (inlined NonNull::::as_ptr) { + } + scope 21 (inlined std::alloc::dealloc) { + let mut _11: usize; + scope 22 (inlined Layout::size) { + } + scope 23 (inlined Layout::align) { + scope 24 (inlined std::ptr::Alignment::as_usize) { + let mut _10: u32; + } + } + } + } + } + scope 5 (inlined Unique::<[T]>::as_ptr) { + scope 6 (inlined NonNull::<[T]>::as_ptr) { + } + } + scope 7 (inlined Layout::for_value_raw::<[T]>) { + let mut _5: usize; + let mut _6: usize; + scope 8 { + scope 11 (inlined #[track_caller] Layout::from_size_align_unchecked) { + let mut _7: std::ptr::Alignment; + } + } + scope 9 (inlined size_of_val_raw::<[T]>) { + } + scope 10 (inlined align_of_val_raw::<[T]>) { + } + } + } + } + } + + bb0: { + StorageLive(_2); + _2 = copy (((*_1).0: std::ptr::Unique<[T]>).0: std::ptr::NonNull<[T]>); + StorageLive(_4); + _3 = copy _2 as *mut [T] (Transmute); + _4 = copy _2 as *const [T] (Transmute); + StorageLive(_6); + _5 = std::intrinsics::size_of_val::<[T]>(copy _4) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _6 = std::intrinsics::align_of_val::<[T]>(move _4) -> [return: bb2, unwind unreachable]; + } + + bb2: { + StorageLive(_7); + _7 = copy _6 as std::ptr::Alignment (Transmute); + _8 = move (_7.0: std::ptr::alignment::AlignmentEnum); + StorageDead(_7); + StorageDead(_6); + StorageDead(_4); + switchInt(copy _5) -> [0: bb5, otherwise: bb3]; + } + + bb3: { + 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: bb4, unwind unreachable]; + } + + bb4: { + StorageDead(_11); + StorageDead(_9); + goto -> bb5; + } + + bb5: { + StorageDead(_2); + return; + } +} 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 new file mode 100644 index 000000000000..e88f6b394fa7 --- /dev/null +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-abort.mir @@ -0,0 +1,111 @@ +// MIR for `generic_in_place` after PreCodegen + +fn generic_in_place(_1: *mut Box<[T]>) -> () { + debug ptr => _1; + let mut _0: (); + scope 1 (inlined drop_in_place::> - shim(Some(Box<[T]>))) { + scope 2 (inlined as Drop>::drop) { + let _2: std::ptr::NonNull<[T]>; + let mut _3: *mut [T]; + let mut _4: *const [T]; + let _12: (); + scope 3 { + let _8: std::ptr::alignment::AlignmentEnum; + scope 4 { + scope 12 (inlined Layout::size) { + } + scope 13 (inlined Unique::<[T]>::cast::) { + scope 14 (inlined NonNull::<[T]>::cast::) { + scope 15 (inlined NonNull::<[T]>::as_ptr) { + } + } + } + scope 16 (inlined as From>>::from) { + scope 17 (inlined Unique::::as_non_null_ptr) { + } + } + scope 18 (inlined ::deallocate) { + let mut _9: *mut u8; + scope 19 (inlined Layout::size) { + } + scope 20 (inlined NonNull::::as_ptr) { + } + scope 21 (inlined std::alloc::dealloc) { + let mut _11: usize; + scope 22 (inlined Layout::size) { + } + scope 23 (inlined Layout::align) { + scope 24 (inlined std::ptr::Alignment::as_usize) { + let mut _10: u64; + } + } + } + } + } + scope 5 (inlined Unique::<[T]>::as_ptr) { + scope 6 (inlined NonNull::<[T]>::as_ptr) { + } + } + scope 7 (inlined Layout::for_value_raw::<[T]>) { + let mut _5: usize; + let mut _6: usize; + scope 8 { + scope 11 (inlined #[track_caller] Layout::from_size_align_unchecked) { + let mut _7: std::ptr::Alignment; + } + } + scope 9 (inlined size_of_val_raw::<[T]>) { + } + scope 10 (inlined align_of_val_raw::<[T]>) { + } + } + } + } + } + + bb0: { + StorageLive(_2); + _2 = copy (((*_1).0: std::ptr::Unique<[T]>).0: std::ptr::NonNull<[T]>); + StorageLive(_4); + _3 = copy _2 as *mut [T] (Transmute); + _4 = copy _2 as *const [T] (Transmute); + StorageLive(_6); + _5 = std::intrinsics::size_of_val::<[T]>(copy _4) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _6 = std::intrinsics::align_of_val::<[T]>(move _4) -> [return: bb2, unwind unreachable]; + } + + bb2: { + StorageLive(_7); + _7 = copy _6 as std::ptr::Alignment (Transmute); + _8 = move (_7.0: std::ptr::alignment::AlignmentEnum); + StorageDead(_7); + StorageDead(_6); + StorageDead(_4); + switchInt(copy _5) -> [0: bb5, otherwise: bb3]; + } + + bb3: { + 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: bb4, unwind unreachable]; + } + + bb4: { + StorageDead(_11); + StorageDead(_9); + goto -> bb5; + } + + bb5: { + StorageDead(_2); + return; + } +} 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 new file mode 100644 index 000000000000..e88f6b394fa7 --- /dev/null +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.generic_in_place.PreCodegen.after.64bit.panic-unwind.mir @@ -0,0 +1,111 @@ +// MIR for `generic_in_place` after PreCodegen + +fn generic_in_place(_1: *mut Box<[T]>) -> () { + debug ptr => _1; + let mut _0: (); + scope 1 (inlined drop_in_place::> - shim(Some(Box<[T]>))) { + scope 2 (inlined as Drop>::drop) { + let _2: std::ptr::NonNull<[T]>; + let mut _3: *mut [T]; + let mut _4: *const [T]; + let _12: (); + scope 3 { + let _8: std::ptr::alignment::AlignmentEnum; + scope 4 { + scope 12 (inlined Layout::size) { + } + scope 13 (inlined Unique::<[T]>::cast::) { + scope 14 (inlined NonNull::<[T]>::cast::) { + scope 15 (inlined NonNull::<[T]>::as_ptr) { + } + } + } + scope 16 (inlined as From>>::from) { + scope 17 (inlined Unique::::as_non_null_ptr) { + } + } + scope 18 (inlined ::deallocate) { + let mut _9: *mut u8; + scope 19 (inlined Layout::size) { + } + scope 20 (inlined NonNull::::as_ptr) { + } + scope 21 (inlined std::alloc::dealloc) { + let mut _11: usize; + scope 22 (inlined Layout::size) { + } + scope 23 (inlined Layout::align) { + scope 24 (inlined std::ptr::Alignment::as_usize) { + let mut _10: u64; + } + } + } + } + } + scope 5 (inlined Unique::<[T]>::as_ptr) { + scope 6 (inlined NonNull::<[T]>::as_ptr) { + } + } + scope 7 (inlined Layout::for_value_raw::<[T]>) { + let mut _5: usize; + let mut _6: usize; + scope 8 { + scope 11 (inlined #[track_caller] Layout::from_size_align_unchecked) { + let mut _7: std::ptr::Alignment; + } + } + scope 9 (inlined size_of_val_raw::<[T]>) { + } + scope 10 (inlined align_of_val_raw::<[T]>) { + } + } + } + } + } + + bb0: { + StorageLive(_2); + _2 = copy (((*_1).0: std::ptr::Unique<[T]>).0: std::ptr::NonNull<[T]>); + StorageLive(_4); + _3 = copy _2 as *mut [T] (Transmute); + _4 = copy _2 as *const [T] (Transmute); + StorageLive(_6); + _5 = std::intrinsics::size_of_val::<[T]>(copy _4) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _6 = std::intrinsics::align_of_val::<[T]>(move _4) -> [return: bb2, unwind unreachable]; + } + + bb2: { + StorageLive(_7); + _7 = copy _6 as std::ptr::Alignment (Transmute); + _8 = move (_7.0: std::ptr::alignment::AlignmentEnum); + StorageDead(_7); + StorageDead(_6); + StorageDead(_4); + switchInt(copy _5) -> [0: bb5, otherwise: bb3]; + } + + bb3: { + 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: bb4, unwind unreachable]; + } + + bb4: { + StorageDead(_11); + StorageDead(_9); + goto -> bb5; + } + + bb5: { + StorageDead(_2); + return; + } +} diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.rs b/tests/mir-opt/pre-codegen/drop_boxed_slice.rs new file mode 100644 index 000000000000..e625a440d200 --- /dev/null +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.rs @@ -0,0 +1,19 @@ +//@ compile-flags: -O -Zmir-opt-level=2 +// EMIT_MIR_FOR_EACH_PANIC_STRATEGY +// EMIT_MIR_FOR_EACH_BIT_WIDTH + +#![crate_type = "lib"] + +// EMIT_MIR drop_boxed_slice.generic_in_place.PreCodegen.after.mir +pub unsafe fn generic_in_place(ptr: *mut Box<[T]>) { + // CHECK-LABEL: fn generic_in_place(_1: *mut Box<[T]>) + // CHECK: (inlined as Drop>::drop) + // CHECK: [[SIZE:_.+]] = std::intrinsics::size_of_val::<[T]> + // CHECK: [[ALIGN:_.+]] = std::intrinsics::align_of_val::<[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]]) -> + std::ptr::drop_in_place(ptr) +} From 185b0745180e6f6f3a4c9c7a41ec8725749cf5bd Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 27 Jul 2025 23:23:22 -0700 Subject: [PATCH 265/809] Add a MIR test for `align_of_val` on a slice --- ..._slice.InstSimplify-after-simplifycfg.diff | 20 +++++++++++++++++++ tests/mir-opt/instsimplify/align_of_slice.rs | 13 ++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 tests/mir-opt/instsimplify/align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff create mode 100644 tests/mir-opt/instsimplify/align_of_slice.rs diff --git a/tests/mir-opt/instsimplify/align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff b/tests/mir-opt/instsimplify/align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff new file mode 100644 index 000000000000..21ba2e250560 --- /dev/null +++ b/tests/mir-opt/instsimplify/align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff @@ -0,0 +1,20 @@ +- // MIR for `of_val_slice` before InstSimplify-after-simplifycfg ++ // MIR for `of_val_slice` after InstSimplify-after-simplifycfg + + fn of_val_slice(_1: &[T]) -> usize { + debug slice => _1; + let mut _0: usize; + let mut _2: *const [T]; + + bb0: { + StorageLive(_2); + _2 = &raw const (*_1); + _0 = std::intrinsics::align_of_val::<[T]>(move _2) -> [return: bb1, unwind unreachable]; + } + + bb1: { + StorageDead(_2); + return; + } + } + diff --git a/tests/mir-opt/instsimplify/align_of_slice.rs b/tests/mir-opt/instsimplify/align_of_slice.rs new file mode 100644 index 000000000000..900a05c2a8b3 --- /dev/null +++ b/tests/mir-opt/instsimplify/align_of_slice.rs @@ -0,0 +1,13 @@ +//@ test-mir-pass: InstSimplify-after-simplifycfg +//@ needs-unwind + +#![crate_type = "lib"] +#![feature(core_intrinsics)] + +// EMIT_MIR align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff +pub fn of_val_slice(slice: &[T]) -> usize { + // CHECK-LABEL: fn of_val_slice(_1: &[T]) + // CHECK: _2 = &raw const (*_1); + // CHECK: _0 = std::intrinsics::align_of_val::<[T]>(move _2) + unsafe { core::intrinsics::align_of_val(slice) } +} From 8ef9233339c09d80e12b31c523082b94d9e09b44 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 27 Jul 2025 23:39:06 -0700 Subject: [PATCH 266/809] =?UTF-8?q?Simplify=20`align=5Fof=5Fval::<[T]>(?= =?UTF-8?q?=E2=80=A6)`=20=E2=86=92=20`align=5Fof::()`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rustc_mir_transform/src/instsimplify.rs | 31 +++++++++++++++++++ ..._slice.InstSimplify-after-simplifycfg.diff | 4 ++- tests/mir-opt/instsimplify/align_of_slice.rs | 3 +- ...ace.PreCodegen.after.32bit.panic-abort.mir | 25 +++++++-------- ...ce.PreCodegen.after.32bit.panic-unwind.mir | 25 +++++++-------- ...ace.PreCodegen.after.64bit.panic-abort.mir | 25 +++++++-------- ...ce.PreCodegen.after.64bit.panic-unwind.mir | 25 +++++++-------- tests/mir-opt/pre-codegen/drop_boxed_slice.rs | 2 +- 8 files changed, 80 insertions(+), 60 deletions(-) diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index dbcaed209538..c83bd25c6636 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -55,6 +55,7 @@ impl<'tcx> crate::MirPass<'tcx> for InstSimplify { let terminator = block.terminator.as_mut().unwrap(); ctx.simplify_primitive_clone(terminator, &mut block.statements); + ctx.simplify_align_of_slice_val(terminator, &mut block.statements); ctx.simplify_intrinsic_assert(terminator); ctx.simplify_nounwind_call(terminator); simplify_duplicate_switch_targets(terminator); @@ -252,6 +253,36 @@ impl<'tcx> InstSimplifyContext<'_, 'tcx> { terminator.kind = TerminatorKind::Goto { target: *destination_block }; } + // Convert `align_of_val::<[T]>(ptr)` to `align_of::()`, since the + // alignment of a slice doesn't actually depend on metadata at all + // and the element type is always `Sized`. + // + // This is here so it can run after inlining, where it's more useful. + // (LowerIntrinsics is done in cleanup, before the optimization passes.) + fn simplify_align_of_slice_val( + &self, + terminator: &mut Terminator<'tcx>, + statements: &mut Vec>, + ) { + if let TerminatorKind::Call { + func, args, destination, target: Some(destination_block), .. + } = &terminator.kind + && args.len() == 1 + && let Some((fn_def_id, generics)) = func.const_fn_def() + && self.tcx.is_intrinsic(fn_def_id, sym::align_of_val) + && let ty::Slice(elem_ty) = *generics.type_at(0).kind() + { + statements.push(Statement::new( + terminator.source_info, + StatementKind::Assign(Box::new(( + *destination, + Rvalue::NullaryOp(NullOp::AlignOf, elem_ty), + ))), + )); + terminator.kind = TerminatorKind::Goto { target: *destination_block }; + } + } + fn simplify_nounwind_call(&self, terminator: &mut Terminator<'tcx>) { let TerminatorKind::Call { ref func, ref mut unwind, .. } = terminator.kind else { return; diff --git a/tests/mir-opt/instsimplify/align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff b/tests/mir-opt/instsimplify/align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff index 21ba2e250560..042e19bf2aa1 100644 --- a/tests/mir-opt/instsimplify/align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff +++ b/tests/mir-opt/instsimplify/align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff @@ -9,7 +9,9 @@ bb0: { StorageLive(_2); _2 = &raw const (*_1); - _0 = std::intrinsics::align_of_val::<[T]>(move _2) -> [return: bb1, unwind unreachable]; +- _0 = std::intrinsics::align_of_val::<[T]>(move _2) -> [return: bb1, unwind unreachable]; ++ _0 = AlignOf(T); ++ goto -> bb1; } bb1: { diff --git a/tests/mir-opt/instsimplify/align_of_slice.rs b/tests/mir-opt/instsimplify/align_of_slice.rs index 900a05c2a8b3..0af05cb6b0b0 100644 --- a/tests/mir-opt/instsimplify/align_of_slice.rs +++ b/tests/mir-opt/instsimplify/align_of_slice.rs @@ -7,7 +7,6 @@ // EMIT_MIR align_of_slice.of_val_slice.InstSimplify-after-simplifycfg.diff pub fn of_val_slice(slice: &[T]) -> usize { // CHECK-LABEL: fn of_val_slice(_1: &[T]) - // CHECK: _2 = &raw const (*_1); - // CHECK: _0 = std::intrinsics::align_of_val::<[T]>(move _2) + // CHECK: _0 = AlignOf(T); unsafe { core::intrinsics::align_of_val(slice) } } 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 587e69154ea1..2777bba893bb 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 @@ -70,24 +70,21 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { _3 = copy _2 as *mut [T] (Transmute); _4 = copy _2 as *const [T] (Transmute); StorageLive(_6); - _5 = std::intrinsics::size_of_val::<[T]>(copy _4) -> [return: bb1, unwind unreachable]; + _5 = std::intrinsics::size_of_val::<[T]>(move _4) -> [return: bb1, unwind unreachable]; } bb1: { - _6 = std::intrinsics::align_of_val::<[T]>(move _4) -> [return: bb2, unwind unreachable]; - } - - bb2: { + _6 = AlignOf(T); StorageLive(_7); _7 = copy _6 as std::ptr::Alignment (Transmute); _8 = move (_7.0: std::ptr::alignment::AlignmentEnum); StorageDead(_7); StorageDead(_6); StorageDead(_4); - switchInt(copy _5) -> [0: bb5, otherwise: bb3]; + switchInt(copy _5) -> [0: bb4, otherwise: bb2]; } - bb3: { + bb2: { StorageLive(_9); _9 = copy _3 as *mut u8 (PtrToPtr); StorageLive(_11); @@ -95,16 +92,16 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { _10 = discriminant(_8); _11 = move _10 as usize (IntToInt); StorageDead(_10); - _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb4, unwind unreachable]; + _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb3, unwind unreachable]; + } + + bb3: { + StorageDead(_11); + StorageDead(_9); + goto -> bb4; } bb4: { - StorageDead(_11); - StorageDead(_9); - goto -> bb5; - } - - bb5: { StorageDead(_2); return; } 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 587e69154ea1..2777bba893bb 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 @@ -70,24 +70,21 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { _3 = copy _2 as *mut [T] (Transmute); _4 = copy _2 as *const [T] (Transmute); StorageLive(_6); - _5 = std::intrinsics::size_of_val::<[T]>(copy _4) -> [return: bb1, unwind unreachable]; + _5 = std::intrinsics::size_of_val::<[T]>(move _4) -> [return: bb1, unwind unreachable]; } bb1: { - _6 = std::intrinsics::align_of_val::<[T]>(move _4) -> [return: bb2, unwind unreachable]; - } - - bb2: { + _6 = AlignOf(T); StorageLive(_7); _7 = copy _6 as std::ptr::Alignment (Transmute); _8 = move (_7.0: std::ptr::alignment::AlignmentEnum); StorageDead(_7); StorageDead(_6); StorageDead(_4); - switchInt(copy _5) -> [0: bb5, otherwise: bb3]; + switchInt(copy _5) -> [0: bb4, otherwise: bb2]; } - bb3: { + bb2: { StorageLive(_9); _9 = copy _3 as *mut u8 (PtrToPtr); StorageLive(_11); @@ -95,16 +92,16 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { _10 = discriminant(_8); _11 = move _10 as usize (IntToInt); StorageDead(_10); - _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb4, unwind unreachable]; + _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb3, unwind unreachable]; + } + + bb3: { + StorageDead(_11); + StorageDead(_9); + goto -> bb4; } bb4: { - StorageDead(_11); - StorageDead(_9); - goto -> bb5; - } - - bb5: { StorageDead(_2); return; } 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 e88f6b394fa7..2be0a478c852 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 @@ -70,24 +70,21 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { _3 = copy _2 as *mut [T] (Transmute); _4 = copy _2 as *const [T] (Transmute); StorageLive(_6); - _5 = std::intrinsics::size_of_val::<[T]>(copy _4) -> [return: bb1, unwind unreachable]; + _5 = std::intrinsics::size_of_val::<[T]>(move _4) -> [return: bb1, unwind unreachable]; } bb1: { - _6 = std::intrinsics::align_of_val::<[T]>(move _4) -> [return: bb2, unwind unreachable]; - } - - bb2: { + _6 = AlignOf(T); StorageLive(_7); _7 = copy _6 as std::ptr::Alignment (Transmute); _8 = move (_7.0: std::ptr::alignment::AlignmentEnum); StorageDead(_7); StorageDead(_6); StorageDead(_4); - switchInt(copy _5) -> [0: bb5, otherwise: bb3]; + switchInt(copy _5) -> [0: bb4, otherwise: bb2]; } - bb3: { + bb2: { StorageLive(_9); _9 = copy _3 as *mut u8 (PtrToPtr); StorageLive(_11); @@ -95,16 +92,16 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { _10 = discriminant(_8); _11 = move _10 as usize (IntToInt); StorageDead(_10); - _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb4, unwind unreachable]; + _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb3, unwind unreachable]; + } + + bb3: { + StorageDead(_11); + StorageDead(_9); + goto -> bb4; } bb4: { - StorageDead(_11); - StorageDead(_9); - goto -> bb5; - } - - bb5: { StorageDead(_2); return; } 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 e88f6b394fa7..2be0a478c852 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 @@ -70,24 +70,21 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { _3 = copy _2 as *mut [T] (Transmute); _4 = copy _2 as *const [T] (Transmute); StorageLive(_6); - _5 = std::intrinsics::size_of_val::<[T]>(copy _4) -> [return: bb1, unwind unreachable]; + _5 = std::intrinsics::size_of_val::<[T]>(move _4) -> [return: bb1, unwind unreachable]; } bb1: { - _6 = std::intrinsics::align_of_val::<[T]>(move _4) -> [return: bb2, unwind unreachable]; - } - - bb2: { + _6 = AlignOf(T); StorageLive(_7); _7 = copy _6 as std::ptr::Alignment (Transmute); _8 = move (_7.0: std::ptr::alignment::AlignmentEnum); StorageDead(_7); StorageDead(_6); StorageDead(_4); - switchInt(copy _5) -> [0: bb5, otherwise: bb3]; + switchInt(copy _5) -> [0: bb4, otherwise: bb2]; } - bb3: { + bb2: { StorageLive(_9); _9 = copy _3 as *mut u8 (PtrToPtr); StorageLive(_11); @@ -95,16 +92,16 @@ fn generic_in_place(_1: *mut Box<[T]>) -> () { _10 = discriminant(_8); _11 = move _10 as usize (IntToInt); StorageDead(_10); - _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb4, unwind unreachable]; + _12 = alloc::alloc::__rust_dealloc(move _9, move _5, move _11) -> [return: bb3, unwind unreachable]; + } + + bb3: { + StorageDead(_11); + StorageDead(_9); + goto -> bb4; } bb4: { - StorageDead(_11); - StorageDead(_9); - goto -> bb5; - } - - bb5: { StorageDead(_2); return; } diff --git a/tests/mir-opt/pre-codegen/drop_boxed_slice.rs b/tests/mir-opt/pre-codegen/drop_boxed_slice.rs index e625a440d200..11fb7afef0fb 100644 --- a/tests/mir-opt/pre-codegen/drop_boxed_slice.rs +++ b/tests/mir-opt/pre-codegen/drop_boxed_slice.rs @@ -9,7 +9,7 @@ pub unsafe fn generic_in_place(ptr: *mut Box<[T]>) { // CHECK-LABEL: fn generic_in_place(_1: *mut Box<[T]>) // CHECK: (inlined as Drop>::drop) // CHECK: [[SIZE:_.+]] = std::intrinsics::size_of_val::<[T]> - // CHECK: [[ALIGN:_.+]] = std::intrinsics::align_of_val::<[T]> + // CHECK: [[ALIGN:_.+]] = AlignOf(T); // CHECK: [[B:_.+]] = copy [[ALIGN]] as std::ptr::Alignment (Transmute); // CHECK: [[C:_.+]] = move ([[B]].0: std::ptr::alignment::AlignmentEnum); // CHECK: [[D:_.+]] = discriminant([[C]]); From 81176b1a6c3a40b2db42821f209cf834befad77e Mon Sep 17 00:00:00 2001 From: xizheyin Date: Tue, 22 Jul 2025 00:20:52 +0800 Subject: [PATCH 267/809] Create two methods to fix `find_oldest_ancestor_in_same_ctxt` Signed-off-by: xizheyin --- .../src/diagnostics/explain_borrow.rs | 2 +- .../src/fn_ctxt/suggestions.rs | 12 ++- compiler/rustc_lint/src/unused.rs | 4 +- compiler/rustc_span/src/lib.rs | 84 +++++++++++-------- 4 files changed, 59 insertions(+), 43 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index a10da08ddf34..fdca6b565409 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -341,7 +341,7 @@ impl<'tcx> BorrowExplanation<'tcx> { } } } else if let LocalInfo::BlockTailTemp(info) = local_decl.local_info() { - let sp = info.span.find_oldest_ancestor_in_same_ctxt(); + let sp = info.span.find_ancestor_not_from_macro().unwrap_or(info.span); if info.tail_result_is_ignored { // #85581: If the first mutable borrow's scope contains // the second borrow, this suggestion isn't helpful. diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 33ae4f6c45cf..2345cdab208e 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1302,7 +1302,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => ".clone()".to_string(), }; - let span = expr.span.find_oldest_ancestor_in_same_ctxt().shrink_to_hi(); + let span = expr.span.find_ancestor_not_from_macro().unwrap_or(expr.span).shrink_to_hi(); diag.span_suggestion_verbose( span, @@ -1395,7 +1395,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .macro_backtrace() .any(|x| matches!(x.kind, ExpnKind::Macro(MacroKind::Attr | MacroKind::Derive, ..))) { - let span = expr.span.find_oldest_ancestor_in_same_ctxt(); + let span = expr + .span + .find_ancestor_not_from_extern_macro(&self.tcx.sess.source_map()) + .unwrap_or(expr.span); let mut sugg = if self.precedence(expr) >= ExprPrecedence::Unambiguous { vec![(span.shrink_to_hi(), ".into()".to_owned())] @@ -2062,7 +2065,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => sugg.to_string(), }; - let span = expr.span.find_oldest_ancestor_in_same_ctxt(); + let span = expr + .span + .find_ancestor_not_from_extern_macro(&self.tcx.sess.source_map()) + .unwrap_or(expr.span); err.span_suggestion_verbose(span.shrink_to_hi(), msg, sugg, Applicability::HasPlaceholders); true } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 11df071f0686..00e40b515a32 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -185,7 +185,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { let mut op_warned = false; if let Some(must_use_op) = must_use_op { - let span = expr.span.find_oldest_ancestor_in_same_ctxt(); + let span = expr.span.find_ancestor_not_from_macro().unwrap_or(expr.span); cx.emit_span_lint( UNUSED_MUST_USE, expr.span, @@ -511,7 +511,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { ); } MustUsePath::Def(span, def_id, reason) => { - let span = span.find_oldest_ancestor_in_same_ctxt(); + let span = span.find_ancestor_not_from_macro().unwrap_or(*span); cx.emit_span_lint( UNUSED_MUST_USE, span, diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index dbc67da37b53..3f72ccd9f89d 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -716,12 +716,17 @@ impl Span { (!ctxt.is_root()).then(|| ctxt.outer_expn_data().call_site) } - /// Walk down the expansion ancestors to find a span that's contained within `outer`. + /// Find the first ancestor span that's contained within `outer`. /// - /// The span returned by this method may have a different [`SyntaxContext`] as `outer`. + /// This method traverses the macro expansion ancestors until it finds the first span + /// that's contained within `outer`. + /// + /// The span returned by this method may have a different [`SyntaxContext`] than `outer`. /// If you need to extend the span, use [`find_ancestor_inside_same_ctxt`] instead, /// because joining spans with different syntax contexts can create unexpected results. /// + /// This is used to find the span of the macro call when a parent expr span, i.e. `outer`, is known. + /// /// [`find_ancestor_inside_same_ctxt`]: Self::find_ancestor_inside_same_ctxt pub fn find_ancestor_inside(mut self, outer: Span) -> Option { while !outer.contains(self) { @@ -730,8 +735,10 @@ impl Span { Some(self) } - /// Walk down the expansion ancestors to find a span with the same [`SyntaxContext`] as - /// `other`. + /// Find the first ancestor span with the same [`SyntaxContext`] as `other`. + /// + /// This method traverses the macro expansion ancestors until it finds a span + /// that has the same [`SyntaxContext`] as `other`. /// /// Like [`find_ancestor_inside_same_ctxt`], but specifically for when spans might not /// overlap. Take care when using this, and prefer [`find_ancestor_inside`] or @@ -747,9 +754,12 @@ impl Span { Some(self) } - /// Walk down the expansion ancestors to find a span that's contained within `outer` and + /// Find the first ancestor span that's contained within `outer` and /// has the same [`SyntaxContext`] as `outer`. /// + /// This method traverses the macro expansion ancestors until it finds a span + /// that is both contained within `outer` and has the same [`SyntaxContext`] as `outer`. + /// /// This method is the combination of [`find_ancestor_inside`] and /// [`find_ancestor_in_same_ctxt`] and should be preferred when extending the returned span. /// If you do not need to modify the span, use [`find_ancestor_inside`] instead. @@ -763,43 +773,43 @@ impl Span { Some(self) } - /// Recursively walk down the expansion ancestors to find the oldest ancestor span with the same - /// [`SyntaxContext`] the initial span. + /// Find the first ancestor span that does not come from an external macro. /// - /// This method is suitable for peeling through *local* macro expansions to find the "innermost" - /// span that is still local and shares the same [`SyntaxContext`]. For example, given + /// This method traverses the macro expansion ancestors until it finds a span + /// that is either from user-written code or from a local macro (defined in the current crate). /// - /// ```ignore (illustrative example, contains type error) - /// macro_rules! outer { - /// ($x: expr) => { - /// inner!($x) - /// } - /// } + /// External macros are those defined in dependencies or the standard library. + /// This method is useful for reporting errors in user-controllable code and avoiding + /// diagnostics inside external macros. /// - /// macro_rules! inner { - /// ($x: expr) => { - /// format!("error: {}", $x) - /// //~^ ERROR mismatched types - /// } - /// } + /// # See also /// - /// fn bar(x: &str) -> Result<(), Box> { - /// Err(outer!(x)) - /// } - /// ``` - /// - /// if provided the initial span of `outer!(x)` inside `bar`, this method will recurse - /// the parent callsites until we reach `format!("error: {}", $x)`, at which point it is the - /// oldest ancestor span that is both still local and shares the same [`SyntaxContext`] as the - /// initial span. - pub fn find_oldest_ancestor_in_same_ctxt(self) -> Span { - let mut cur = self; - while cur.eq_ctxt(self) - && let Some(parent_callsite) = cur.parent_callsite() - { - cur = parent_callsite; + /// - [`Self::find_ancestor_not_from_macro`] + /// - [`Self::in_external_macro`] + pub fn find_ancestor_not_from_extern_macro(mut self, sm: &SourceMap) -> Option { + while self.in_external_macro(sm) { + self = self.parent_callsite()?; } - cur + Some(self) + } + + /// Find the first ancestor span that does not come from any macro expansion. + /// + /// This method traverses the macro expansion ancestors until it finds a span + /// that originates from user-written code rather than any macro-generated code. + /// + /// This method is useful for reporting errors at the exact location users wrote code + /// and providing suggestions at directly editable locations. + /// + /// # See also + /// + /// - [`Self::find_ancestor_not_from_extern_macro`] + /// - [`Span::from_expansion`] + pub fn find_ancestor_not_from_macro(mut self) -> Option { + while self.from_expansion() { + self = self.parent_callsite()?; + } + Some(self) } /// Edition of the crate from which this span came. From e532080507056b242ecbcbb8e79bc95f041998d6 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 29 Jul 2025 09:22:24 +0200 Subject: [PATCH 268/809] cc dependencies: clarify comment --- compiler/rustc_codegen_ssa/Cargo.toml | 4 ++-- compiler/rustc_llvm/Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_codegen_ssa/Cargo.toml b/compiler/rustc_codegen_ssa/Cargo.toml index cfae1b3ec98e..94501da69a76 100644 --- a/compiler/rustc_codegen_ssa/Cargo.toml +++ b/compiler/rustc_codegen_ssa/Cargo.toml @@ -8,8 +8,8 @@ edition = "2024" ar_archive_writer = "0.4.2" bitflags = "2.4.1" bstr = "1.11.3" -# Pinned so `cargo update` bumps don't cause breakage. Please also update the -# `cc` in `rustc_llvm` if you update the `cc` here. +# `cc` updates often break things, so we pin it here. Cargo enforces "max 1 semver-compat version +# per crate", so if you change this, you need to also change it in `rustc_llvm`. cc = "=1.2.16" itertools = "0.12" pathdiff = "0.2.0" diff --git a/compiler/rustc_llvm/Cargo.toml b/compiler/rustc_llvm/Cargo.toml index 39de4783238b..85a2a9c09f08 100644 --- a/compiler/rustc_llvm/Cargo.toml +++ b/compiler/rustc_llvm/Cargo.toml @@ -10,8 +10,8 @@ libc = "0.2.73" [build-dependencies] # tidy-alphabetical-start -# Pinned so `cargo update` bumps don't cause breakage. Please also update the -# pinned `cc` in `rustc_codegen_ssa` if you update `cc` here. +# `cc` updates often break things, so we pin it here. Cargo enforces "max 1 semver-compat version +# per crate", so if you change this, you need to also change it in `rustc_codegen_ssa`. cc = "=1.2.16" # tidy-alphabetical-end From b8302ce6053e97899002324ef1eefcbaf41984fc Mon Sep 17 00:00:00 2001 From: Jacob Adam Date: Tue, 29 Jul 2025 09:03:57 +0200 Subject: [PATCH 269/809] Add a regression test for an ICE with the `generic_const_exprs` feature attribute. It ensures that using the `generic_const_exprs` feature in a library crate without enabling it in a dependent crate does not lead to an ICE. --- ...bute-missing-in-dependent-crate-ice-aux.rs | 9 +++++++++ ...ttribute-missing-in-dependent-crate-ice.rs | 19 +++++++++++++++++++ ...bute-missing-in-dependent-crate-ice.stderr | 14 ++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 tests/ui/const-generics/generic_const_exprs/auxiliary/feature-attribute-missing-in-dependent-crate-ice-aux.rs create mode 100644 tests/ui/const-generics/generic_const_exprs/feature-attribute-missing-in-dependent-crate-ice.rs create mode 100644 tests/ui/const-generics/generic_const_exprs/feature-attribute-missing-in-dependent-crate-ice.stderr diff --git a/tests/ui/const-generics/generic_const_exprs/auxiliary/feature-attribute-missing-in-dependent-crate-ice-aux.rs b/tests/ui/const-generics/generic_const_exprs/auxiliary/feature-attribute-missing-in-dependent-crate-ice-aux.rs new file mode 100644 index 000000000000..3902454c14cd --- /dev/null +++ b/tests/ui/const-generics/generic_const_exprs/auxiliary/feature-attribute-missing-in-dependent-crate-ice-aux.rs @@ -0,0 +1,9 @@ +#![feature(generic_const_exprs)] + +pub struct Error(()); + +pub trait FromSlice: Sized { + const SIZE: usize = std::mem::size_of::(); + + fn validate_slice(bytes: &[[u8; Self::SIZE]]) -> Result<(), Error>; +} diff --git a/tests/ui/const-generics/generic_const_exprs/feature-attribute-missing-in-dependent-crate-ice.rs b/tests/ui/const-generics/generic_const_exprs/feature-attribute-missing-in-dependent-crate-ice.rs new file mode 100644 index 000000000000..b9537014767e --- /dev/null +++ b/tests/ui/const-generics/generic_const_exprs/feature-attribute-missing-in-dependent-crate-ice.rs @@ -0,0 +1,19 @@ +//! Regression test to ensure that using the `generic_const_exprs` feature in a library crate +//! without enabling it in a dependent crate does not lead to an ICE. +//! +//! Issue: + +//@ aux-build:feature-attribute-missing-in-dependent-crate-ice-aux.rs + +extern crate feature_attribute_missing_in_dependent_crate_ice_aux as aux; + +struct Wrapper(i64); + +impl aux::FromSlice for Wrapper { + fn validate_slice(_: &[[u8; Self::SIZE]]) -> Result<(), aux::Error> { + //~^ ERROR generic `Self` types are currently not permitted in anonymous constants + Ok(()) + } +} + +fn main() {} diff --git a/tests/ui/const-generics/generic_const_exprs/feature-attribute-missing-in-dependent-crate-ice.stderr b/tests/ui/const-generics/generic_const_exprs/feature-attribute-missing-in-dependent-crate-ice.stderr new file mode 100644 index 000000000000..5c3306651426 --- /dev/null +++ b/tests/ui/const-generics/generic_const_exprs/feature-attribute-missing-in-dependent-crate-ice.stderr @@ -0,0 +1,14 @@ +error: generic `Self` types are currently not permitted in anonymous constants + --> $DIR/feature-attribute-missing-in-dependent-crate-ice.rs:13:33 + | +LL | fn validate_slice(_: &[[u8; Self::SIZE]]) -> Result<(), aux::Error> { + | ^^^^ + | +note: not a concrete type + --> $DIR/feature-attribute-missing-in-dependent-crate-ice.rs:12:41 + | +LL | impl aux::FromSlice for Wrapper { + | ^^^^^^^^^^ + +error: aborting due to 1 previous error + 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 270/809] 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 271/809] 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 272/809] 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 273/809] 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 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 274/809] 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 ec4dc1c5f87e3de735cefb21ac51522568b1b391 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Wed, 23 Jul 2025 13:34:04 +0200 Subject: [PATCH 275/809] clean up existing poison files --- library/std/src/sync/poison.rs | 6 +++--- library/std/src/sync/poison/condvar.rs | 2 +- library/std/src/sync/poison/mutex.rs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/library/std/src/sync/poison.rs b/library/std/src/sync/poison.rs index 0c05f152ef84..b901a5701a48 100644 --- a/library/std/src/sync/poison.rs +++ b/library/std/src/sync/poison.rs @@ -13,7 +13,9 @@ //! depend on the primitive. See [#Overview] below. //! //! For the alternative implementations that do not employ poisoning, -//! see `std::sync::nonpoisoning`. +//! see [`std::sync::nonpoison`]. +//! +//! [`std::sync::nonpoison`]: crate::sync::nonpoison //! //! # Overview //! @@ -56,8 +58,6 @@ //! while it is locked exclusively (write mode). If a panic occurs in any reader, //! then the lock will not be poisoned. -// FIXME(sync_nonpoison) add links to sync::nonpoison to the doc comment above. - #[stable(feature = "rust1", since = "1.0.0")] pub use self::condvar::{Condvar, WaitTimeoutResult}; #[unstable(feature = "mapped_lock_guards", issue = "117108")] diff --git a/library/std/src/sync/poison/condvar.rs b/library/std/src/sync/poison/condvar.rs index 7f0f3f652bcb..0e9d4233c657 100644 --- a/library/std/src/sync/poison/condvar.rs +++ b/library/std/src/sync/poison/condvar.rs @@ -13,7 +13,7 @@ use crate::time::{Duration, Instant}; #[stable(feature = "wait_timeout", since = "1.5.0")] pub struct WaitTimeoutResult(bool); -// FIXME(sync_nonpoison): `WaitTimeoutResult` is actually poisoning-agnostic, it seems. +// FIXME(nonpoison_condvar): `WaitTimeoutResult` is actually poisoning-agnostic, it seems. // Should we take advantage of this fact? impl WaitTimeoutResult { /// Returns `true` if the wait was known to have timed out. diff --git a/library/std/src/sync/poison/mutex.rs b/library/std/src/sync/poison/mutex.rs index 30325be685c3..64744f18c746 100644 --- a/library/std/src/sync/poison/mutex.rs +++ b/library/std/src/sync/poison/mutex.rs @@ -650,7 +650,7 @@ impl fmt::Debug for Mutex { d.field("data", &&**err.get_ref()); } Err(TryLockError::WouldBlock) => { - d.field("data", &format_args!("")); + d.field("data", &""); } } d.field("poisoned", &self.poison.get()); From 3bdc228c103d72a61d9639d6fd0dd5c1566ec37f Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Wed, 23 Jul 2025 13:47:49 +0200 Subject: [PATCH 276/809] add `nonpoison::mutex` implementation Adds the equivalent `nonpoison` types to the `poison::mutex` module. These types and implementations are gated under the `nonpoison_mutex` feature gate. Also blesses the ui tests that now have a name conflicts (because these types no longer have unique names). The full path distinguishes the different types. Co-authored-by: Aandreba Co-authored-by: Trevor Gross --- library/std/src/sync/mod.rs | 2 + library/std/src/sync/nonpoison.rs | 37 ++ library/std/src/sync/nonpoison/mutex.rs | 611 ++++++++++++++++++ .../issue-64130-non-send-future-diags.stderr | 4 +- tests/ui/async-await/issue-71137.stderr | 4 +- tests/ui/async-await/issues/issue-67893.rs | 2 +- .../ui/async-await/issues/issue-67893.stderr | 6 +- tests/ui/lint/must_not_suspend/mutex.rs | 2 +- tests/ui/lint/must_not_suspend/mutex.stderr | 2 +- .../private-field-access-in-mutex-54062.rs | 2 +- ...private-field-access-in-mutex-54062.stderr | 2 +- tests/ui/suggestions/inner_type.fixed | 2 +- tests/ui/suggestions/inner_type.rs | 2 +- tests/ui/suggestions/inner_type.stderr | 4 +- tests/ui/sync/mutexguard-sync.stderr | 2 +- .../const-traits/span-bug-issue-121418.stderr | 6 +- .../ui/typeck/assign-non-lval-derefmut.fixed | 4 +- tests/ui/typeck/assign-non-lval-derefmut.rs | 4 +- .../ui/typeck/assign-non-lval-derefmut.stderr | 14 +- tests/ui/typeck/deref-multi.stderr | 2 +- 20 files changed, 682 insertions(+), 32 deletions(-) create mode 100644 library/std/src/sync/nonpoison.rs create mode 100644 library/std/src/sync/nonpoison/mutex.rs diff --git a/library/std/src/sync/mod.rs b/library/std/src/sync/mod.rs index e67b4f6f22f5..6ef3bf25cf67 100644 --- a/library/std/src/sync/mod.rs +++ b/library/std/src/sync/mod.rs @@ -225,6 +225,8 @@ pub use self::poison::{MappedMutexGuard, MappedRwLockReadGuard, MappedRwLockWrit pub mod mpmc; pub mod mpsc; +#[unstable(feature = "sync_nonpoison", issue = "134645")] +pub mod nonpoison; #[unstable(feature = "sync_poison_mod", issue = "134646")] pub mod poison; diff --git a/library/std/src/sync/nonpoison.rs b/library/std/src/sync/nonpoison.rs new file mode 100644 index 000000000000..2bbf226dc2cd --- /dev/null +++ b/library/std/src/sync/nonpoison.rs @@ -0,0 +1,37 @@ +//! Non-poisoning synchronous locks. +//! +//! The difference from the locks in the [`poison`] module is that the locks in this module will not +//! become poisoned when a thread panics while holding a guard. +//! +//! [`poison`]: super::poison + +use crate::fmt; + +/// A type alias for the result of a nonblocking locking method. +#[unstable(feature = "sync_nonpoison", issue = "134645")] +pub type TryLockResult = Result; + +/// A lock could not be acquired at this time because the operation would otherwise block. +#[unstable(feature = "sync_nonpoison", issue = "134645")] +pub struct WouldBlock; + +#[unstable(feature = "sync_nonpoison", issue = "134645")] +impl fmt::Debug for WouldBlock { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + "WouldBlock".fmt(f) + } +} + +#[unstable(feature = "sync_nonpoison", issue = "134645")] +impl fmt::Display for WouldBlock { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + "try_lock failed because the operation would block".fmt(f) + } +} + +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +pub use self::mutex::MappedMutexGuard; +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +pub use self::mutex::{Mutex, MutexGuard}; + +mod mutex; diff --git a/library/std/src/sync/nonpoison/mutex.rs b/library/std/src/sync/nonpoison/mutex.rs new file mode 100644 index 000000000000..b6861c78f001 --- /dev/null +++ b/library/std/src/sync/nonpoison/mutex.rs @@ -0,0 +1,611 @@ +use crate::cell::UnsafeCell; +use crate::fmt; +use crate::marker::PhantomData; +use crate::mem::{self, ManuallyDrop}; +use crate::ops::{Deref, DerefMut}; +use crate::ptr::NonNull; +use crate::sync::nonpoison::{TryLockResult, WouldBlock}; +use crate::sys::sync as sys; + +/// A mutual exclusion primitive useful for protecting shared data that does not keep track of +/// lock poisoning. +/// +/// For more information about mutexes, check out the documentation for the poisoning variant of +/// this lock at [`poison::Mutex`]. +/// +/// [`poison::Mutex`]: crate::sync::poison::Mutex +/// +/// # Examples +/// +/// Note that this `Mutex` does **not** propagate threads that panic while holding the lock via +/// poisoning. If you need this functionality, see [`poison::Mutex`]. +/// +/// ``` +/// #![feature(nonpoison_mutex)] +/// +/// use std::thread; +/// use std::sync::{Arc, nonpoison::Mutex}; +/// +/// let mutex = Arc::new(Mutex::new(0u32)); +/// let mut handles = Vec::new(); +/// +/// for n in 0..10 { +/// let m = Arc::clone(&mutex); +/// let handle = thread::spawn(move || { +/// let mut guard = m.lock(); +/// *guard += 1; +/// panic!("panic from thread {n} {guard}") +/// }); +/// handles.push(handle); +/// } +/// +/// for h in handles { +/// let _ = h.join(); +/// } +/// +/// println!("Finished, locked {} times", mutex.lock()); +/// ``` +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +#[cfg_attr(not(test), rustc_diagnostic_item = "NonPoisonMutex")] +pub struct Mutex { + inner: sys::Mutex, + data: UnsafeCell, +} + +/// `T` must be `Send` for a [`Mutex`] to be `Send` because it is possible to acquire +/// the owned `T` from the `Mutex` via [`into_inner`]. +/// +/// [`into_inner`]: Mutex::into_inner +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +unsafe impl Send for Mutex {} + +/// `T` must be `Send` for [`Mutex`] to be `Sync`. +/// This ensures that the protected data can be accessed safely from multiple threads +/// without causing data races or other unsafe behavior. +/// +/// [`Mutex`] provides mutable access to `T` to one thread at a time. However, it's essential +/// for `T` to be `Send` because it's not safe for non-`Send` structures to be accessed in +/// this manner. For instance, consider [`Rc`], a non-atomic reference counted smart pointer, +/// which is not `Send`. With `Rc`, we can have multiple copies pointing to the same heap +/// allocation with a non-atomic reference count. If we were to use `Mutex>`, it would +/// only protect one instance of `Rc` from shared access, leaving other copies vulnerable +/// to potential data races. +/// +/// Also note that it is not necessary for `T` to be `Sync` as `&T` is only made available +/// to one thread at a time if `T` is not `Sync`. +/// +/// [`Rc`]: crate::rc::Rc +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +unsafe impl Sync for Mutex {} + +/// An RAII implementation of a "scoped lock" of a mutex. When this structure is +/// dropped (falls out of scope), the lock will be unlocked. +/// +/// The data protected by the mutex can be accessed through this guard via its +/// [`Deref`] and [`DerefMut`] implementations. +/// +/// This structure is created by the [`lock`] and [`try_lock`] methods on +/// [`Mutex`]. +/// +/// [`lock`]: Mutex::lock +/// [`try_lock`]: Mutex::try_lock +#[must_use = "if unused the Mutex will immediately unlock"] +#[must_not_suspend = "holding a MutexGuard across suspend \ + points can cause deadlocks, delays, \ + and cause Futures to not implement `Send`"] +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +#[clippy::has_significant_drop] +#[cfg_attr(not(test), rustc_diagnostic_item = "NonPoisonMutexGuard")] +pub struct MutexGuard<'a, T: ?Sized + 'a> { + lock: &'a Mutex, +} + +/// A [`MutexGuard`] is not `Send` to maximize platform portablity. +/// +/// On platforms that use POSIX threads (commonly referred to as pthreads) there is a requirement to +/// release mutex locks on the same thread they were acquired. +/// For this reason, [`MutexGuard`] must not implement `Send` to prevent it being dropped from +/// another thread. +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl !Send for MutexGuard<'_, T> {} + +/// `T` must be `Sync` for a [`MutexGuard`] to be `Sync` +/// because it is possible to get a `&T` from `&MutexGuard` (via `Deref`). +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +unsafe impl Sync for MutexGuard<'_, T> {} + +// FIXME(nonpoison_condvar): Use this link instead: [`Condvar`]: crate::sync::nonpoison::Condvar +/// An RAII mutex guard returned by `MutexGuard::map`, which can point to a +/// subfield of the protected data. When this structure is dropped (falls out +/// of scope), the lock will be unlocked. +/// +/// The main difference between `MappedMutexGuard` and [`MutexGuard`] is that the +/// former cannot be used with [`Condvar`], since that could introduce soundness issues if the +/// locked object is modified by another thread while the `Mutex` is unlocked. +/// +/// The data protected by the mutex can be accessed through this guard via its +/// [`Deref`] and [`DerefMut`] implementations. +/// +/// This structure is created by the [`map`] and [`filter_map`] methods on +/// [`MutexGuard`]. +/// +/// [`map`]: MutexGuard::map +/// [`filter_map`]: MutexGuard::filter_map +/// [`Condvar`]: crate::sync::Condvar +#[must_use = "if unused the Mutex will immediately unlock"] +#[must_not_suspend = "holding a MappedMutexGuard across suspend \ + points can cause deadlocks, delays, \ + and cause Futures to not implement `Send`"] +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +// #[unstable(feature = "nonpoison_mutex", issue = "134645")] +#[clippy::has_significant_drop] +pub struct MappedMutexGuard<'a, T: ?Sized + 'a> { + // NB: we use a pointer instead of `&'a mut T` to avoid `noalias` violations, because a + // `MappedMutexGuard` argument doesn't hold uniqueness for its whole scope, only until it drops. + // `NonNull` is covariant over `T`, so we add a `PhantomData<&'a mut T>` field + // below for the correct variance over `T` (invariance). + data: NonNull, + inner: &'a sys::Mutex, + _variance: PhantomData<&'a mut T>, +} + +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +// #[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl !Send for MappedMutexGuard<'_, T> {} +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +// #[unstable(feature = "nonpoison_mutex", issue = "134645")] +unsafe impl Sync for MappedMutexGuard<'_, T> {} + +impl Mutex { + /// Creates a new mutex in an unlocked state ready for use. + /// + /// # Examples + /// + /// ``` + /// #![feature(nonpoison_mutex)] + /// + /// use std::sync::nonpoison::Mutex; + /// + /// let mutex = Mutex::new(0); + /// ``` + #[unstable(feature = "nonpoison_mutex", issue = "134645")] + #[inline] + pub const fn new(t: T) -> Mutex { + Mutex { inner: sys::Mutex::new(), data: UnsafeCell::new(t) } + } + + /// Returns the contained value by cloning it. + /// + /// # Examples + /// + /// ``` + /// #![feature(nonpoison_mutex)] + /// #![feature(lock_value_accessors)] + /// + /// use std::sync::nonpoison::Mutex; + /// + /// let mut mutex = Mutex::new(7); + /// + /// assert_eq!(mutex.get_cloned(), 7); + /// ``` + #[unstable(feature = "lock_value_accessors", issue = "133407")] + // #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn get_cloned(&self) -> T + where + T: Clone, + { + self.lock().clone() + } + + /// Sets the contained value. + /// + /// # Examples + /// + /// ``` + /// #![feature(nonpoison_mutex)] + /// #![feature(lock_value_accessors)] + /// + /// use std::sync::nonpoison::Mutex; + /// + /// let mut mutex = Mutex::new(7); + /// + /// assert_eq!(mutex.get_cloned(), 7); + /// mutex.set(11); + /// assert_eq!(mutex.get_cloned(), 11); + /// ``` + #[unstable(feature = "lock_value_accessors", issue = "133407")] + // #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn set(&self, value: T) { + if mem::needs_drop::() { + // If the contained value has a non-trivial destructor, we + // call that destructor after the lock has been released. + drop(self.replace(value)) + } else { + *self.lock() = value; + } + } + + /// Replaces the contained value with `value`, and returns the old contained value. + /// + /// # Examples + /// + /// ``` + /// #![feature(nonpoison_mutex)] + /// #![feature(lock_value_accessors)] + /// + /// use std::sync::nonpoison::Mutex; + /// + /// let mut mutex = Mutex::new(7); + /// + /// assert_eq!(mutex.replace(11), 7); + /// assert_eq!(mutex.get_cloned(), 11); + /// ``` + #[unstable(feature = "lock_value_accessors", issue = "133407")] + // #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn replace(&self, value: T) -> T { + let mut guard = self.lock(); + mem::replace(&mut *guard, value) + } +} + +impl Mutex { + /// Acquires a mutex, blocking the current thread until it is able to do so. + /// + /// This function will block the local thread until it is available to acquire + /// the mutex. Upon returning, the thread is the only thread with the lock + /// held. An RAII guard is returned to allow scoped unlock of the lock. When + /// the guard goes out of scope, the mutex will be unlocked. + /// + /// The exact behavior on locking a mutex in the thread which already holds + /// the lock is left unspecified. However, this function will not return on + /// the second call (it might panic or deadlock, for example). + /// + /// # Panics + /// + /// This function might panic when called if the lock is already held by + /// the current thread. + /// + /// # Examples + /// + /// ``` + /// #![feature(nonpoison_mutex)] + /// + /// use std::sync::{Arc, nonpoison::Mutex}; + /// use std::thread; + /// + /// let mutex = Arc::new(Mutex::new(0)); + /// let c_mutex = Arc::clone(&mutex); + /// + /// thread::spawn(move || { + /// *c_mutex.lock() = 10; + /// }).join().expect("thread::spawn failed"); + /// assert_eq!(*mutex.lock(), 10); + /// ``` + #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn lock(&self) -> MutexGuard<'_, T> { + unsafe { + self.inner.lock(); + MutexGuard::new(self) + } + } + + /// Attempts to acquire this lock. + /// + /// This function does not block. If the lock could not be acquired at this time, then + /// [`WouldBlock`] is returned. Otherwise, an RAII guard is returned. + /// + /// The lock will be unlocked when the guard is dropped. + /// + /// # Errors + /// + /// If the mutex could not be acquired because it is already locked, then this call will return + /// the [`WouldBlock`] error. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Mutex}; + /// use std::thread; + /// + /// let mutex = Arc::new(Mutex::new(0)); + /// let c_mutex = Arc::clone(&mutex); + /// + /// thread::spawn(move || { + /// let mut lock = c_mutex.try_lock(); + /// if let Ok(ref mut mutex) = lock { + /// **mutex = 10; + /// } else { + /// println!("try_lock failed"); + /// } + /// }).join().expect("thread::spawn failed"); + /// assert_eq!(*mutex.lock().unwrap(), 10); + /// ``` + #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn try_lock(&self) -> TryLockResult> { + unsafe { if self.inner.try_lock() { Ok(MutexGuard::new(self)) } else { Err(WouldBlock) } } + } + + /// Consumes this mutex, returning the underlying data. + /// + /// # Examples + /// + /// ``` + /// #![feature(nonpoison_mutex)] + /// + /// use std::sync::nonpoison::Mutex; + /// + /// let mutex = Mutex::new(0); + /// assert_eq!(mutex.into_inner(), 0); + /// ``` + #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn into_inner(self) -> T + where + T: Sized, + { + self.data.into_inner() + } + + /// Returns a mutable reference to the underlying data. + /// + /// Since this call borrows the `Mutex` mutably, no actual locking needs to + /// take place -- the mutable borrow statically guarantees no locks exist. + /// + /// # Examples + /// + /// ``` + /// #![feature(nonpoison_mutex)] + /// + /// use std::sync::nonpoison::Mutex; + /// + /// let mut mutex = Mutex::new(0); + /// *mutex.get_mut() = 10; + /// assert_eq!(*mutex.lock(), 10); + /// ``` + #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn get_mut(&mut self) -> &mut T { + self.data.get_mut() + } + + /// Returns a raw pointer to the underlying data. + /// + /// The returned pointer is always non-null and properly aligned, but it is + /// the user's responsibility to ensure that any reads and writes through it + /// are properly synchronized to avoid data races, and that it is not read + /// or written through after the mutex is dropped. + #[unstable(feature = "mutex_data_ptr", issue = "140368")] + // #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn data_ptr(&self) -> *mut T { + self.data.get() + } +} + +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl From for Mutex { + /// Creates a new mutex in an unlocked state ready for use. + /// This is equivalent to [`Mutex::new`]. + fn from(t: T) -> Self { + Mutex::new(t) + } +} + +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl Default for Mutex { + /// Creates a `Mutex`, with the `Default` value for T. + fn default() -> Mutex { + Mutex::new(Default::default()) + } +} + +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl fmt::Debug for Mutex { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut d = f.debug_struct("Mutex"); + match self.try_lock() { + Ok(guard) => { + d.field("data", &&*guard); + } + Err(WouldBlock) => { + d.field("data", &""); + } + } + d.finish_non_exhaustive() + } +} + +impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> { + unsafe fn new(lock: &'mutex Mutex) -> MutexGuard<'mutex, T> { + return MutexGuard { lock }; + } +} + +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl Deref for MutexGuard<'_, T> { + type Target = T; + + fn deref(&self) -> &T { + unsafe { &*self.lock.data.get() } + } +} + +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl DerefMut for MutexGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.lock.data.get() } + } +} + +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl Drop for MutexGuard<'_, T> { + #[inline] + fn drop(&mut self) { + unsafe { + self.lock.inner.unlock(); + } + } +} + +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl fmt::Debug for MutexGuard<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[unstable(feature = "nonpoison_mutex", issue = "134645")] +impl fmt::Display for MutexGuard<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + +impl<'a, T: ?Sized> MutexGuard<'a, T> { + /// Makes a [`MappedMutexGuard`] for a component of the borrowed data, e.g. + /// an enum variant. + /// + /// The `Mutex` is already locked, so this cannot fail. + /// + /// This is an associated function that needs to be used as + /// `MutexGuard::map(...)`. A method would interfere with methods of the + /// same name on the contents of the `MutexGuard` used through `Deref`. + #[unstable(feature = "mapped_lock_guards", issue = "117108")] + // #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn map(orig: Self, f: F) -> MappedMutexGuard<'a, U> + where + F: FnOnce(&mut T) -> &mut U, + U: ?Sized, + { + // SAFETY: the conditions of `MutexGuard::new` were satisfied when the original guard + // was created, and have been upheld throughout `map` and/or `filter_map`. + // The signature of the closure guarantees that it will not "leak" the lifetime of the reference + // passed to it. If the closure panics, the guard will be dropped. + let data = NonNull::from(f(unsafe { &mut *orig.lock.data.get() })); + let orig = ManuallyDrop::new(orig); + MappedMutexGuard { data, inner: &orig.lock.inner, _variance: PhantomData } + } + + /// Makes a [`MappedMutexGuard`] for a component of the borrowed data. The + /// original guard is returned as an `Err(...)` if the closure returns + /// `None`. + /// + /// The `Mutex` is already locked, so this cannot fail. + /// + /// This is an associated function that needs to be used as + /// `MutexGuard::filter_map(...)`. A method would interfere with methods of the + /// same name on the contents of the `MutexGuard` used through `Deref`. + #[unstable(feature = "mapped_lock_guards", issue = "117108")] + // #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn filter_map(orig: Self, f: F) -> Result, Self> + where + F: FnOnce(&mut T) -> Option<&mut U>, + U: ?Sized, + { + // SAFETY: the conditions of `MutexGuard::new` were satisfied when the original guard + // was created, and have been upheld throughout `map` and/or `filter_map`. + // The signature of the closure guarantees that it will not "leak" the lifetime of the reference + // passed to it. If the closure panics, the guard will be dropped. + match f(unsafe { &mut *orig.lock.data.get() }) { + Some(data) => { + let data = NonNull::from(data); + let orig = ManuallyDrop::new(orig); + Ok(MappedMutexGuard { data, inner: &orig.lock.inner, _variance: PhantomData }) + } + None => Err(orig), + } + } +} + +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +impl Deref for MappedMutexGuard<'_, T> { + type Target = T; + + fn deref(&self) -> &T { + unsafe { self.data.as_ref() } + } +} + +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +impl DerefMut for MappedMutexGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { self.data.as_mut() } + } +} + +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +impl Drop for MappedMutexGuard<'_, T> { + #[inline] + fn drop(&mut self) { + unsafe { + self.inner.unlock(); + } + } +} + +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +impl fmt::Debug for MappedMutexGuard<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[unstable(feature = "mapped_lock_guards", issue = "117108")] +impl fmt::Display for MappedMutexGuard<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + +impl<'a, T: ?Sized> MappedMutexGuard<'a, T> { + /// Makes a [`MappedMutexGuard`] for a component of the borrowed data, e.g. + /// an enum variant. + /// + /// The `Mutex` is already locked, so this cannot fail. + /// + /// This is an associated function that needs to be used as + /// `MappedMutexGuard::map(...)`. A method would interfere with methods of the + /// same name on the contents of the `MutexGuard` used through `Deref`. + #[unstable(feature = "mapped_lock_guards", issue = "117108")] + // #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn map(mut orig: Self, f: F) -> MappedMutexGuard<'a, U> + where + F: FnOnce(&mut T) -> &mut U, + U: ?Sized, + { + // SAFETY: the conditions of `MutexGuard::new` were satisfied when the original guard + // was created, and have been upheld throughout `map` and/or `filter_map`. + // The signature of the closure guarantees that it will not "leak" the lifetime of the reference + // passed to it. If the closure panics, the guard will be dropped. + let data = NonNull::from(f(unsafe { orig.data.as_mut() })); + let orig = ManuallyDrop::new(orig); + MappedMutexGuard { data, inner: orig.inner, _variance: PhantomData } + } + + /// Makes a [`MappedMutexGuard`] for a component of the borrowed data. The + /// original guard is returned as an `Err(...)` if the closure returns + /// `None`. + /// + /// The `Mutex` is already locked, so this cannot fail. + /// + /// This is an associated function that needs to be used as + /// `MappedMutexGuard::filter_map(...)`. A method would interfere with methods of the + /// same name on the contents of the `MutexGuard` used through `Deref`. + #[unstable(feature = "mapped_lock_guards", issue = "117108")] + // #[unstable(feature = "nonpoison_mutex", issue = "134645")] + pub fn filter_map(mut orig: Self, f: F) -> Result, Self> + where + F: FnOnce(&mut T) -> Option<&mut U>, + U: ?Sized, + { + // SAFETY: the conditions of `MutexGuard::new` were satisfied when the original guard + // was created, and have been upheld throughout `map` and/or `filter_map`. + // The signature of the closure guarantees that it will not "leak" the lifetime of the reference + // passed to it. If the closure panics, the guard will be dropped. + match f(unsafe { orig.data.as_mut() }) { + Some(data) => { + let data = NonNull::from(data); + let orig = ManuallyDrop::new(orig); + Ok(MappedMutexGuard { data, inner: orig.inner, _variance: PhantomData }) + } + None => Err(orig), + } + } +} diff --git a/tests/ui/async-await/issue-64130-non-send-future-diags.stderr b/tests/ui/async-await/issue-64130-non-send-future-diags.stderr index d28807e223be..beaf8e9c96d8 100644 --- a/tests/ui/async-await/issue-64130-non-send-future-diags.stderr +++ b/tests/ui/async-await/issue-64130-non-send-future-diags.stderr @@ -4,12 +4,12 @@ error: future cannot be sent between threads safely LL | is_send(foo()); | ^^^^^ future returned by `foo` is not `Send` | - = help: within `impl Future`, the trait `Send` is not implemented for `MutexGuard<'_, u32>` + = help: within `impl Future`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, u32>` note: future is not `Send` as this value is used across an await --> $DIR/issue-64130-non-send-future-diags.rs:17:11 | LL | let g = x.lock().unwrap(); - | - has type `MutexGuard<'_, u32>` which is not `Send` + | - has type `std::sync::MutexGuard<'_, u32>` which is not `Send` LL | baz().await; | ^^^^^ await occurs here, with `g` maybe used later note: required by a bound in `is_send` diff --git a/tests/ui/async-await/issue-71137.stderr b/tests/ui/async-await/issue-71137.stderr index 8739c22a3104..d567e3f2063d 100644 --- a/tests/ui/async-await/issue-71137.stderr +++ b/tests/ui/async-await/issue-71137.stderr @@ -4,12 +4,12 @@ error: future cannot be sent between threads safely LL | fake_spawn(wrong_mutex()); | ^^^^^^^^^^^^^ future returned by `wrong_mutex` is not `Send` | - = help: within `impl Future`, the trait `Send` is not implemented for `MutexGuard<'_, i32>` + = help: within `impl Future`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, i32>` note: future is not `Send` as this value is used across an await --> $DIR/issue-71137.rs:14:26 | LL | let mut guard = m.lock().unwrap(); - | --------- has type `MutexGuard<'_, i32>` which is not `Send` + | --------- has type `std::sync::MutexGuard<'_, i32>` which is not `Send` LL | (async { "right"; }).await; | ^^^^^ await occurs here, with `mut guard` maybe used later note: required by a bound in `fake_spawn` diff --git a/tests/ui/async-await/issues/issue-67893.rs b/tests/ui/async-await/issues/issue-67893.rs index 73cce38c94a0..2020abe7a5a9 100644 --- a/tests/ui/async-await/issues/issue-67893.rs +++ b/tests/ui/async-await/issues/issue-67893.rs @@ -7,5 +7,5 @@ fn g(_: impl Send) {} fn main() { g(issue_67893::run()) - //~^ ERROR `MutexGuard<'_, ()>` cannot be sent between threads safely + //~^ ERROR `std::sync::MutexGuard<'_, ()>` cannot be sent between threads safely } diff --git a/tests/ui/async-await/issues/issue-67893.stderr b/tests/ui/async-await/issues/issue-67893.stderr index c01237255b89..34f28dd53c7b 100644 --- a/tests/ui/async-await/issues/issue-67893.stderr +++ b/tests/ui/async-await/issues/issue-67893.stderr @@ -1,8 +1,8 @@ -error[E0277]: `MutexGuard<'_, ()>` cannot be sent between threads safely +error[E0277]: `std::sync::MutexGuard<'_, ()>` cannot be sent between threads safely --> $DIR/issue-67893.rs:9:7 | LL | g(issue_67893::run()) - | - ^^^^^^^^^^^^^^^^^^ `MutexGuard<'_, ()>` cannot be sent between threads safely + | - ^^^^^^^^^^^^^^^^^^ `std::sync::MutexGuard<'_, ()>` cannot be sent between threads safely | | | required by a bound introduced by this call | @@ -11,7 +11,7 @@ LL | g(issue_67893::run()) LL | pub async fn run() { | ------------------ within this `impl Future` | - = help: within `impl Future`, the trait `Send` is not implemented for `MutexGuard<'_, ()>` + = help: within `impl Future`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, ()>` note: required because it's used within this `async` fn body --> $DIR/auxiliary/issue_67893.rs:9:20 | diff --git a/tests/ui/lint/must_not_suspend/mutex.rs b/tests/ui/lint/must_not_suspend/mutex.rs index d14f7130b4cf..8dd4cc176151 100644 --- a/tests/ui/lint/must_not_suspend/mutex.rs +++ b/tests/ui/lint/must_not_suspend/mutex.rs @@ -5,7 +5,7 @@ async fn other() {} pub async fn uhoh(m: std::sync::Mutex<()>) { - let _guard = m.lock().unwrap(); //~ ERROR `MutexGuard` held across + let _guard = m.lock().unwrap(); //~ ERROR `std::sync::MutexGuard` held across other().await; } diff --git a/tests/ui/lint/must_not_suspend/mutex.stderr b/tests/ui/lint/must_not_suspend/mutex.stderr index ca53a753150e..0db1f2575b19 100644 --- a/tests/ui/lint/must_not_suspend/mutex.stderr +++ b/tests/ui/lint/must_not_suspend/mutex.stderr @@ -1,4 +1,4 @@ -error: `MutexGuard` held across a suspend point, but should not be +error: `std::sync::MutexGuard` held across a suspend point, but should not be --> $DIR/mutex.rs:8:9 | LL | let _guard = m.lock().unwrap(); diff --git a/tests/ui/privacy/private-field-access-in-mutex-54062.rs b/tests/ui/privacy/private-field-access-in-mutex-54062.rs index f145f9c3e529..c957e0bc7e86 100644 --- a/tests/ui/privacy/private-field-access-in-mutex-54062.rs +++ b/tests/ui/privacy/private-field-access-in-mutex-54062.rs @@ -8,7 +8,7 @@ fn main() {} fn testing(test: Test) { let _ = test.comps.inner.try_lock(); - //~^ ERROR: field `inner` of struct `Mutex` is private + //~^ ERROR: field `inner` of struct `std::sync::Mutex` is private } // https://github.com/rust-lang/rust/issues/54062 diff --git a/tests/ui/privacy/private-field-access-in-mutex-54062.stderr b/tests/ui/privacy/private-field-access-in-mutex-54062.stderr index 142441075974..f7f846406485 100644 --- a/tests/ui/privacy/private-field-access-in-mutex-54062.stderr +++ b/tests/ui/privacy/private-field-access-in-mutex-54062.stderr @@ -1,4 +1,4 @@ -error[E0616]: field `inner` of struct `Mutex` is private +error[E0616]: field `inner` of struct `std::sync::Mutex` is private --> $DIR/private-field-access-in-mutex-54062.rs:10:24 | LL | let _ = test.comps.inner.try_lock(); diff --git a/tests/ui/suggestions/inner_type.fixed b/tests/ui/suggestions/inner_type.fixed index 3dc939d6b5c4..175a2a02acdf 100644 --- a/tests/ui/suggestions/inner_type.fixed +++ b/tests/ui/suggestions/inner_type.fixed @@ -25,7 +25,7 @@ fn main() { let another_item = std::sync::Mutex::new(Struct { p: 42_u32 }); another_item.lock().unwrap().method(); - //~^ ERROR no method named `method` found for struct `Mutex` in the current scope [E0599] + //~^ ERROR no method named `method` found for struct `std::sync::Mutex` in the current scope [E0599] //~| HELP use `.lock().unwrap()` to borrow the `Struct`, blocking the current thread until it can be acquired let another_item = std::sync::RwLock::new(Struct { p: 42_u32 }); diff --git a/tests/ui/suggestions/inner_type.rs b/tests/ui/suggestions/inner_type.rs index 81a05c253119..ab021414f56c 100644 --- a/tests/ui/suggestions/inner_type.rs +++ b/tests/ui/suggestions/inner_type.rs @@ -25,7 +25,7 @@ fn main() { let another_item = std::sync::Mutex::new(Struct { p: 42_u32 }); another_item.method(); - //~^ ERROR no method named `method` found for struct `Mutex` in the current scope [E0599] + //~^ ERROR no method named `method` found for struct `std::sync::Mutex` in the current scope [E0599] //~| HELP use `.lock().unwrap()` to borrow the `Struct`, blocking the current thread until it can be acquired let another_item = std::sync::RwLock::new(Struct { p: 42_u32 }); diff --git a/tests/ui/suggestions/inner_type.stderr b/tests/ui/suggestions/inner_type.stderr index 5ac3d04f1041..67ebb5789b70 100644 --- a/tests/ui/suggestions/inner_type.stderr +++ b/tests/ui/suggestions/inner_type.stderr @@ -30,11 +30,11 @@ help: use `.borrow_mut()` to mutably borrow the `Struct`, panicking if any LL | other_item.borrow_mut().some_mutable_method(); | +++++++++++++ -error[E0599]: no method named `method` found for struct `Mutex` in the current scope +error[E0599]: no method named `method` found for struct `std::sync::Mutex` in the current scope --> $DIR/inner_type.rs:27:18 | LL | another_item.method(); - | ^^^^^^ method not found in `Mutex>` + | ^^^^^^ method not found in `std::sync::Mutex>` | note: the method `method` exists on the type `Struct` --> $DIR/inner_type.rs:9:5 diff --git a/tests/ui/sync/mutexguard-sync.stderr b/tests/ui/sync/mutexguard-sync.stderr index 1501a793d5e8..ab9983c1f2c1 100644 --- a/tests/ui/sync/mutexguard-sync.stderr +++ b/tests/ui/sync/mutexguard-sync.stderr @@ -8,7 +8,7 @@ LL | test_sync(guard); | = help: the trait `Sync` is not implemented for `Cell` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead - = note: required for `MutexGuard<'_, Cell>` to implement `Sync` + = note: required for `std::sync::MutexGuard<'_, Cell>` to implement `Sync` note: required by a bound in `test_sync` --> $DIR/mutexguard-sync.rs:5:17 | diff --git a/tests/ui/traits/const-traits/span-bug-issue-121418.stderr b/tests/ui/traits/const-traits/span-bug-issue-121418.stderr index 92cfecd05404..f31129d9cb7c 100644 --- a/tests/ui/traits/const-traits/span-bug-issue-121418.stderr +++ b/tests/ui/traits/const-traits/span-bug-issue-121418.stderr @@ -14,8 +14,8 @@ error[E0277]: the size for values of type `(dyn T + 'static)` cannot be known at LL | pub const fn new() -> std::sync::Mutex {} | ^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: within `Mutex<(dyn T + 'static)>`, the trait `Sized` is not implemented for `(dyn T + 'static)` -note: required because it appears within the type `Mutex<(dyn T + 'static)>` + = help: within `std::sync::Mutex<(dyn T + 'static)>`, the trait `Sized` is not implemented for `(dyn T + 'static)` +note: required because it appears within the type `std::sync::Mutex<(dyn T + 'static)>` --> $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL = note: the return type of a function must have a statically known size @@ -27,7 +27,7 @@ LL | pub const fn new() -> std::sync::Mutex {} | | | implicitly returns `()` as its body has no tail or `return` expression | - = note: expected struct `Mutex<(dyn T + 'static)>` + = note: expected struct `std::sync::Mutex<(dyn T + 'static)>` found unit type `()` error: aborting due to 3 previous errors diff --git a/tests/ui/typeck/assign-non-lval-derefmut.fixed b/tests/ui/typeck/assign-non-lval-derefmut.fixed index 6ecec574f2ec..e6f97a9e86c6 100644 --- a/tests/ui/typeck/assign-non-lval-derefmut.fixed +++ b/tests/ui/typeck/assign-non-lval-derefmut.fixed @@ -5,11 +5,11 @@ fn main() { *x.lock().unwrap() = 2; //~^ ERROR invalid left-hand side of assignment *x.lock().unwrap() += 1; - //~^ ERROR binary assignment operation `+=` cannot be applied to type `MutexGuard<'_, usize>` + //~^ ERROR binary assignment operation `+=` cannot be applied to type `std::sync::MutexGuard<'_, usize>` let mut y = x.lock().unwrap(); *y = 2; //~^ ERROR mismatched types *y += 1; - //~^ ERROR binary assignment operation `+=` cannot be applied to type `MutexGuard<'_, usize>` + //~^ ERROR binary assignment operation `+=` cannot be applied to type `std::sync::MutexGuard<'_, usize>` } diff --git a/tests/ui/typeck/assign-non-lval-derefmut.rs b/tests/ui/typeck/assign-non-lval-derefmut.rs index ac1be913e2a9..a53a52c7e4dd 100644 --- a/tests/ui/typeck/assign-non-lval-derefmut.rs +++ b/tests/ui/typeck/assign-non-lval-derefmut.rs @@ -5,11 +5,11 @@ fn main() { x.lock().unwrap() = 2; //~^ ERROR invalid left-hand side of assignment x.lock().unwrap() += 1; - //~^ ERROR binary assignment operation `+=` cannot be applied to type `MutexGuard<'_, usize>` + //~^ ERROR binary assignment operation `+=` cannot be applied to type `std::sync::MutexGuard<'_, usize>` let mut y = x.lock().unwrap(); y = 2; //~^ ERROR mismatched types y += 1; - //~^ ERROR binary assignment operation `+=` cannot be applied to type `MutexGuard<'_, usize>` + //~^ ERROR binary assignment operation `+=` cannot be applied to type `std::sync::MutexGuard<'_, usize>` } diff --git a/tests/ui/typeck/assign-non-lval-derefmut.stderr b/tests/ui/typeck/assign-non-lval-derefmut.stderr index 16fb1e9c5c3a..f57b5abe2eed 100644 --- a/tests/ui/typeck/assign-non-lval-derefmut.stderr +++ b/tests/ui/typeck/assign-non-lval-derefmut.stderr @@ -11,15 +11,15 @@ help: consider dereferencing here to assign to the mutably borrowed value LL | *x.lock().unwrap() = 2; | + -error[E0368]: binary assignment operation `+=` cannot be applied to type `MutexGuard<'_, usize>` +error[E0368]: binary assignment operation `+=` cannot be applied to type `std::sync::MutexGuard<'_, usize>` --> $DIR/assign-non-lval-derefmut.rs:7:5 | LL | x.lock().unwrap() += 1; | -----------------^^^^^ | | - | cannot use `+=` on type `MutexGuard<'_, usize>` + | cannot use `+=` on type `std::sync::MutexGuard<'_, usize>` | -note: the foreign item type `MutexGuard<'_, usize>` doesn't implement `AddAssign<{integer}>` +note: the foreign item type `std::sync::MutexGuard<'_, usize>` doesn't implement `AddAssign<{integer}>` --> $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL | = note: not implement `AddAssign<{integer}>` @@ -36,22 +36,22 @@ LL | let mut y = x.lock().unwrap(); LL | y = 2; | ^ expected `MutexGuard<'_, usize>`, found integer | - = note: expected struct `MutexGuard<'_, usize>` + = note: expected struct `std::sync::MutexGuard<'_, usize>` found type `{integer}` help: consider dereferencing here to assign to the mutably borrowed value | LL | *y = 2; | + -error[E0368]: binary assignment operation `+=` cannot be applied to type `MutexGuard<'_, usize>` +error[E0368]: binary assignment operation `+=` cannot be applied to type `std::sync::MutexGuard<'_, usize>` --> $DIR/assign-non-lval-derefmut.rs:13:5 | LL | y += 1; | -^^^^^ | | - | cannot use `+=` on type `MutexGuard<'_, usize>` + | cannot use `+=` on type `std::sync::MutexGuard<'_, usize>` | -note: the foreign item type `MutexGuard<'_, usize>` doesn't implement `AddAssign<{integer}>` +note: the foreign item type `std::sync::MutexGuard<'_, usize>` doesn't implement `AddAssign<{integer}>` --> $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL | = note: not implement `AddAssign<{integer}>` diff --git a/tests/ui/typeck/deref-multi.stderr b/tests/ui/typeck/deref-multi.stderr index 02513853c486..c4fa49e43ef2 100644 --- a/tests/ui/typeck/deref-multi.stderr +++ b/tests/ui/typeck/deref-multi.stderr @@ -63,7 +63,7 @@ LL | x.lock().unwrap() | ^^^^^^^^^^^^^^^^^ expected `i32`, found `MutexGuard<'_, &i32>` | = note: expected type `i32` - found struct `MutexGuard<'_, &i32>` + found struct `std::sync::MutexGuard<'_, &i32>` help: consider dereferencing the type | LL | **x.lock().unwrap() From f34fb05923ab4c8bff48bf5d52ca08c5b8e2233a Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Wed, 23 Jul 2025 14:04:32 +0200 Subject: [PATCH 277/809] reorder mutex tests This commit simply helps discern the actual changes needed to test both poison and nonpoison locks. --- library/std/tests/sync/mutex.rs | 312 +++++++++++++++++--------------- 1 file changed, 163 insertions(+), 149 deletions(-) diff --git a/library/std/tests/sync/mutex.rs b/library/std/tests/sync/mutex.rs index ac82914d6de4..6f06d3385d1a 100644 --- a/library/std/tests/sync/mutex.rs +++ b/library/std/tests/sync/mutex.rs @@ -6,28 +6,9 @@ use std::sync::mpsc::channel; use std::sync::{Arc, Condvar, MappedMutexGuard, Mutex, MutexGuard, TryLockError}; use std::{hint, mem, thread}; -struct Packet(Arc<(Mutex, Condvar)>); - -#[derive(Eq, PartialEq, Debug)] -struct NonCopy(i32); - -#[derive(Eq, PartialEq, Debug)] -struct NonCopyNeedsDrop(i32); - -impl Drop for NonCopyNeedsDrop { - fn drop(&mut self) { - hint::black_box(()); - } -} - -#[test] -fn test_needs_drop() { - assert!(!mem::needs_drop::()); - assert!(mem::needs_drop::()); -} - -#[derive(Clone, Eq, PartialEq, Debug)] -struct Cloneable(i32); +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Nonpoison & Poison Tests +//////////////////////////////////////////////////////////////////////////////////////////////////// #[test] fn smoke() { @@ -78,19 +59,22 @@ fn try_lock() { *m.try_lock().unwrap() = (); } -fn new_poisoned_mutex(value: T) -> Mutex { - let mutex = Mutex::new(value); +#[derive(Eq, PartialEq, Debug)] +struct NonCopy(i32); - let catch_unwind_result = panic::catch_unwind(AssertUnwindSafe(|| { - let _guard = mutex.lock().unwrap(); +#[derive(Eq, PartialEq, Debug)] +struct NonCopyNeedsDrop(i32); - panic!("test panic to poison mutex"); - })); +impl Drop for NonCopyNeedsDrop { + fn drop(&mut self) { + hint::black_box(()); + } +} - assert!(catch_unwind_result.is_err()); - assert!(mutex.is_poisoned()); - - mutex +#[test] +fn test_needs_drop() { + assert!(!mem::needs_drop::()); + assert!(mem::needs_drop::()); } #[test] @@ -117,35 +101,6 @@ fn test_into_inner_drop() { assert_eq!(num_drops.load(Ordering::SeqCst), 1); } -#[test] -#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] -fn test_into_inner_poison() { - let m = new_poisoned_mutex(NonCopy(10)); - - match m.into_inner() { - Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), - Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {x:?}"), - } -} - -#[test] -fn test_get_cloned() { - let m = Mutex::new(Cloneable(10)); - - assert_eq!(m.get_cloned().unwrap(), Cloneable(10)); -} - -#[test] -#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] -fn test_get_cloned_poison() { - let m = new_poisoned_mutex(Cloneable(10)); - - match m.get_cloned() { - Err(e) => assert_eq!(e.into_inner(), ()), - Ok(x) => panic!("get of poisoned Mutex is Ok: {x:?}"), - } -} - #[test] fn test_get_mut() { let mut m = Mutex::new(NonCopy(10)); @@ -154,14 +109,13 @@ fn test_get_mut() { } #[test] -#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] -fn test_get_mut_poison() { - let mut m = new_poisoned_mutex(NonCopy(10)); +fn test_get_cloned() { + #[derive(Clone, Eq, PartialEq, Debug)] + struct Cloneable(i32); - match m.get_mut() { - Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), - Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {x:?}"), - } + let m = Mutex::new(Cloneable(10)); + + assert_eq!(m.get_cloned().unwrap(), Cloneable(10)); } #[test] @@ -181,6 +135,145 @@ fn test_set() { inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); } +#[test] +fn test_replace() { + fn inner(mut init: impl FnMut() -> T, mut value: impl FnMut() -> T) + where + T: Debug + Eq, + { + let m = Mutex::new(init()); + + assert_eq!(*m.lock().unwrap(), init()); + assert_eq!(m.replace(value()).unwrap(), init()); + assert_eq!(*m.lock().unwrap(), value()); + } + + inner(|| NonCopy(10), || NonCopy(20)); + inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); +} + +#[test] +fn test_mutex_arc_condvar() { + struct Packet(Arc<(Mutex, Condvar)>); + + let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); + let packet2 = Packet(packet.0.clone()); + let (tx, rx) = channel(); + let _t = thread::spawn(move || { + // wait until parent gets in + rx.recv().unwrap(); + let &(ref lock, ref cvar) = &*packet2.0; + let mut lock = lock.lock().unwrap(); + *lock = true; + cvar.notify_one(); + }); + + let &(ref lock, ref cvar) = &*packet.0; + let mut lock = lock.lock().unwrap(); + tx.send(()).unwrap(); + assert!(!*lock); + while !*lock { + lock = cvar.wait(lock).unwrap(); + } +} + +#[test] +fn test_mutex_arc_nested() { + // Tests nested mutexes and access + // to underlying data. + let arc = Arc::new(Mutex::new(1)); + let arc2 = Arc::new(Mutex::new(arc)); + let (tx, rx) = channel(); + let _t = thread::spawn(move || { + let lock = arc2.lock().unwrap(); + let lock2 = lock.lock().unwrap(); + assert_eq!(*lock2, 1); + tx.send(()).unwrap(); + }); + rx.recv().unwrap(); +} + +#[test] +fn test_mutex_unsized() { + let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); + { + let b = &mut *mutex.lock().unwrap(); + b[0] = 4; + b[2] = 5; + } + let comp: &[i32] = &[4, 2, 5]; + assert_eq!(&*mutex.lock().unwrap(), comp); +} + +#[test] +fn test_mapping_mapped_guard() { + let arr = [0; 4]; + let mut lock = Mutex::new(arr); + let guard = lock.lock().unwrap(); + let guard = MutexGuard::map(guard, |arr| &mut arr[..2]); + let mut guard = MappedMutexGuard::map(guard, |slice| &mut slice[1..]); + assert_eq!(guard.len(), 1); + guard[0] = 42; + drop(guard); + assert_eq!(*lock.get_mut().unwrap(), [0, 42, 0, 0]); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Poison Tests +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/// Creates a mutex that is immediately poisoned. +fn new_poisoned_mutex(value: T) -> Mutex { + let mutex = Mutex::new(value); + + let catch_unwind_result = panic::catch_unwind(AssertUnwindSafe(|| { + let _guard = mutex.lock().unwrap(); + + panic!("test panic to poison mutex"); + })); + + assert!(catch_unwind_result.is_err()); + assert!(mutex.is_poisoned()); + + mutex +} + +#[test] +#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] +fn test_into_inner_poison() { + let m = new_poisoned_mutex(NonCopy(10)); + + match m.into_inner() { + Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), + Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {x:?}"), + } +} + +#[test] +#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] +fn test_get_cloned_poison() { + #[derive(Clone, Eq, PartialEq, Debug)] + struct Cloneable(i32); + + let m = new_poisoned_mutex(Cloneable(10)); + + match m.get_cloned() { + Err(e) => assert_eq!(e.into_inner(), ()), + Ok(x) => panic!("get of poisoned Mutex is Ok: {x:?}"), + } +} + +#[test] +#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] +fn test_get_mut_poison() { + let mut m = new_poisoned_mutex(NonCopy(10)); + + match m.get_mut() { + Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), + Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {x:?}"), + } +} + #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn test_set_poison() { @@ -203,23 +296,6 @@ fn test_set_poison() { inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); } -#[test] -fn test_replace() { - fn inner(mut init: impl FnMut() -> T, mut value: impl FnMut() -> T) - where - T: Debug + Eq, - { - let m = Mutex::new(init()); - - assert_eq!(*m.lock().unwrap(), init()); - assert_eq!(m.replace(value()).unwrap(), init()); - assert_eq!(*m.lock().unwrap(), value()); - } - - inner(|| NonCopy(10), || NonCopy(20)); - inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); -} - #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn test_replace_poison() { @@ -242,32 +318,11 @@ fn test_replace_poison() { inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); } -#[test] -fn test_mutex_arc_condvar() { - let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); - let packet2 = Packet(packet.0.clone()); - let (tx, rx) = channel(); - let _t = thread::spawn(move || { - // wait until parent gets in - rx.recv().unwrap(); - let &(ref lock, ref cvar) = &*packet2.0; - let mut lock = lock.lock().unwrap(); - *lock = true; - cvar.notify_one(); - }); - - let &(ref lock, ref cvar) = &*packet.0; - let mut lock = lock.lock().unwrap(); - tx.send(()).unwrap(); - assert!(!*lock); - while !*lock { - lock = cvar.wait(lock).unwrap(); - } -} - #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn test_arc_condvar_poison() { + struct Packet(Arc<(Mutex, Condvar)>); + let packet = Packet(Arc::new((Mutex::new(1), Condvar::new()))); let packet2 = Packet(packet.0.clone()); let (tx, rx) = channel(); @@ -326,22 +381,6 @@ fn test_mutex_arc_poison_mapped() { assert!(arc.is_poisoned()); } -#[test] -fn test_mutex_arc_nested() { - // Tests nested mutexes and access - // to underlying data. - let arc = Arc::new(Mutex::new(1)); - let arc2 = Arc::new(Mutex::new(arc)); - let (tx, rx) = channel(); - let _t = thread::spawn(move || { - let lock = arc2.lock().unwrap(); - let lock2 = lock.lock().unwrap(); - assert_eq!(*lock2, 1); - tx.send(()).unwrap(); - }); - rx.recv().unwrap(); -} - #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn test_mutex_arc_access_in_unwind() { @@ -364,31 +403,6 @@ fn test_mutex_arc_access_in_unwind() { assert_eq!(*lock, 2); } -#[test] -fn test_mutex_unsized() { - let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); - { - let b = &mut *mutex.lock().unwrap(); - b[0] = 4; - b[2] = 5; - } - let comp: &[i32] = &[4, 2, 5]; - assert_eq!(&*mutex.lock().unwrap(), comp); -} - -#[test] -fn test_mapping_mapped_guard() { - let arr = [0; 4]; - let mut lock = Mutex::new(arr); - let guard = lock.lock().unwrap(); - let guard = MutexGuard::map(guard, |arr| &mut arr[..2]); - let mut guard = MappedMutexGuard::map(guard, |slice| &mut slice[1..]); - assert_eq!(guard.len(), 1); - guard[0] = 42; - drop(guard); - assert_eq!(*lock.get_mut().unwrap(), [0, 42, 0, 0]); -} - #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn panic_while_mapping_unlocked_poison() { From 3eb722e655670cc204aee5e3b4f0a9b9f29a8cd0 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Wed, 23 Jul 2025 14:09:27 +0200 Subject: [PATCH 278/809] add nonpoison and poison mutex tests Adds tests for the `nonpoison::Mutex` variant by using a macro to duplicate the existing `poison` tests. Note that all of the tests here are adapted from the existing `poison` tests. --- library/std/tests/sync/lib.rs | 55 +++++ library/std/tests/sync/mutex.rs | 351 +++++++++++++++++++------------- 2 files changed, 260 insertions(+), 146 deletions(-) diff --git a/library/std/tests/sync/lib.rs b/library/std/tests/sync/lib.rs index 51190f0894fb..94f1fe96b6a2 100644 --- a/library/std/tests/sync/lib.rs +++ b/library/std/tests/sync/lib.rs @@ -6,7 +6,10 @@ #![feature(reentrant_lock)] #![feature(rwlock_downgrade)] #![feature(std_internals)] +#![feature(sync_nonpoison)] +#![feature(nonpoison_mutex)] #![allow(internal_features)] +#![feature(macro_metavar_expr_concat)] // For concatenating identifiers in macros. mod barrier; mod condvar; @@ -29,3 +32,55 @@ mod rwlock; #[path = "../common/mod.rs"] mod common; + +#[track_caller] +fn result_unwrap(x: Result) -> T { + x.unwrap() +} + +/// A macro that generates two test cases for both the poison and nonpoison locks. +/// +/// To write a test that tests both `poison` and `nonpoison` locks, import any of the types +/// under both `poison` and `nonpoison` using the module name `locks` instead. For example, write +/// `use locks::Mutex;` instead of `use std::sync::poiosn::Mutex`. This will import the correct type +/// for each test variant. +/// +/// Write a test as normal in the `test_body`, but instead of calling `unwrap` on `poison` methods +/// that return a `LockResult` or similar, call the function `maybe_unwrap(...)` on the result. +/// +/// For example, call `maybe_unwrap(mutex.lock())` instead of `mutex.lock().unwrap()` or +/// `maybe_unwrap(rwlock.read())` instead of `rwlock.read().unwrap()`. +/// +/// For the `poison` types, `maybe_unwrap` will simply unwrap the `Result` (usually this is a form +/// of `LockResult`, but it could also be other kinds of results). For the `nonpoison` types, it is +/// a no-op (the identity function). +/// +/// The test names will be prefiex with `poison_` or `nonpoison_`. +macro_rules! nonpoison_and_poison_unwrap_test { + ( + name: $name:ident, + test_body: {$($test_body:tt)*} + ) => { + // Creates the nonpoison test. + #[test] + fn ${concat(nonpoison_, $name)}() { + #[allow(unused_imports)] + use ::std::convert::identity as maybe_unwrap; + use ::std::sync::nonpoison as locks; + + $($test_body)* + } + + // Creates the poison test with the suffix `_unwrap_poisoned`. + #[test] + fn ${concat(poison_, $name)}() { + #[allow(unused_imports)] + use super::result_unwrap as maybe_unwrap; + use ::std::sync::poison as locks; + + $($test_body)* + } + } +} + +use nonpoison_and_poison_unwrap_test; diff --git a/library/std/tests/sync/mutex.rs b/library/std/tests/sync/mutex.rs index 6f06d3385d1a..60f5d4f45bf2 100644 --- a/library/std/tests/sync/mutex.rs +++ b/library/std/tests/sync/mutex.rs @@ -9,55 +9,68 @@ use std::{hint, mem, thread}; //////////////////////////////////////////////////////////////////////////////////////////////////// // Nonpoison & Poison Tests //////////////////////////////////////////////////////////////////////////////////////////////////// +use super::nonpoison_and_poison_unwrap_test; -#[test] -fn smoke() { - let m = Mutex::new(()); - drop(m.lock().unwrap()); - drop(m.lock().unwrap()); -} +nonpoison_and_poison_unwrap_test!( + name: smoke, + test_body: { + use locks::Mutex; -#[test] -fn lots_and_lots() { - const J: u32 = 1000; - const K: u32 = 3; + let m = Mutex::new(()); + drop(maybe_unwrap(m.lock())); + drop(maybe_unwrap(m.lock())); + } +); - let m = Arc::new(Mutex::new(0)); +nonpoison_and_poison_unwrap_test!( + name: lots_and_lots, + test_body: { + use locks::Mutex; - fn inc(m: &Mutex) { - for _ in 0..J { - *m.lock().unwrap() += 1; + const J: u32 = 1000; + const K: u32 = 3; + + let m = Arc::new(Mutex::new(0)); + + fn inc(m: &Mutex) { + for _ in 0..J { + *maybe_unwrap(m.lock()) += 1; + } } - } - let (tx, rx) = channel(); - for _ in 0..K { - let tx2 = tx.clone(); - let m2 = m.clone(); - thread::spawn(move || { - inc(&m2); - tx2.send(()).unwrap(); - }); - let tx2 = tx.clone(); - let m2 = m.clone(); - thread::spawn(move || { - inc(&m2); - tx2.send(()).unwrap(); - }); - } + let (tx, rx) = channel(); + for _ in 0..K { + let tx2 = tx.clone(); + let m2 = m.clone(); + thread::spawn(move || { + inc(&m2); + tx2.send(()).unwrap(); + }); + let tx2 = tx.clone(); + let m2 = m.clone(); + thread::spawn(move || { + inc(&m2); + tx2.send(()).unwrap(); + }); + } - drop(tx); - for _ in 0..2 * K { - rx.recv().unwrap(); + drop(tx); + for _ in 0..2 * K { + rx.recv().unwrap(); + } + assert_eq!(*maybe_unwrap(m.lock()), J * K * 2); } - assert_eq!(*m.lock().unwrap(), J * K * 2); -} +); -#[test] -fn try_lock() { - let m = Mutex::new(()); - *m.try_lock().unwrap() = (); -} +nonpoison_and_poison_unwrap_test!( + name: try_lock, + test_body: { + use locks::Mutex; + + let m = Mutex::new(()); + *m.try_lock().unwrap() = (); + } +); #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); @@ -77,146 +90,192 @@ fn test_needs_drop() { assert!(mem::needs_drop::()); } -#[test] -fn test_into_inner() { - let m = Mutex::new(NonCopy(10)); - assert_eq!(m.into_inner().unwrap(), NonCopy(10)); -} +nonpoison_and_poison_unwrap_test!( + name: test_into_inner, + test_body: { + use locks::Mutex; -#[test] -fn test_into_inner_drop() { - struct Foo(Arc); - impl Drop for Foo { - fn drop(&mut self) { - self.0.fetch_add(1, Ordering::SeqCst); + let m = Mutex::new(NonCopy(10)); + assert_eq!(maybe_unwrap(m.into_inner()), NonCopy(10)); + } +); + +nonpoison_and_poison_unwrap_test!( + name: test_into_inner_drop, + test_body: { + use locks::Mutex; + + struct Foo(Arc); + impl Drop for Foo { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } } - } - let num_drops = Arc::new(AtomicUsize::new(0)); - let m = Mutex::new(Foo(num_drops.clone())); - assert_eq!(num_drops.load(Ordering::SeqCst), 0); - { - let _inner = m.into_inner().unwrap(); + let num_drops = Arc::new(AtomicUsize::new(0)); + let m = Mutex::new(Foo(num_drops.clone())); assert_eq!(num_drops.load(Ordering::SeqCst), 0); + { + let _inner = maybe_unwrap(m.into_inner()); + assert_eq!(num_drops.load(Ordering::SeqCst), 0); + } + assert_eq!(num_drops.load(Ordering::SeqCst), 1); } - assert_eq!(num_drops.load(Ordering::SeqCst), 1); -} +); -#[test] -fn test_get_mut() { - let mut m = Mutex::new(NonCopy(10)); - *m.get_mut().unwrap() = NonCopy(20); - assert_eq!(m.into_inner().unwrap(), NonCopy(20)); -} +nonpoison_and_poison_unwrap_test!( + name: test_get_mut, + test_body: { + use locks::Mutex; -#[test] -fn test_get_cloned() { - #[derive(Clone, Eq, PartialEq, Debug)] - struct Cloneable(i32); - - let m = Mutex::new(Cloneable(10)); - - assert_eq!(m.get_cloned().unwrap(), Cloneable(10)); -} - -#[test] -fn test_set() { - fn inner(mut init: impl FnMut() -> T, mut value: impl FnMut() -> T) - where - T: Debug + Eq, - { - let m = Mutex::new(init()); - - assert_eq!(*m.lock().unwrap(), init()); - m.set(value()).unwrap(); - assert_eq!(*m.lock().unwrap(), value()); + let mut m = Mutex::new(NonCopy(10)); + *maybe_unwrap(m.get_mut()) = NonCopy(20); + assert_eq!(maybe_unwrap(m.into_inner()), NonCopy(20)); } +); - inner(|| NonCopy(10), || NonCopy(20)); - inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); -} +nonpoison_and_poison_unwrap_test!( + name: test_get_cloned, + test_body: { + use locks::Mutex; -#[test] -fn test_replace() { - fn inner(mut init: impl FnMut() -> T, mut value: impl FnMut() -> T) - where - T: Debug + Eq, - { - let m = Mutex::new(init()); + #[derive(Clone, Eq, PartialEq, Debug)] + struct Cloneable(i32); - assert_eq!(*m.lock().unwrap(), init()); - assert_eq!(m.replace(value()).unwrap(), init()); - assert_eq!(*m.lock().unwrap(), value()); + let m = Mutex::new(Cloneable(10)); + + assert_eq!(maybe_unwrap(m.get_cloned()), Cloneable(10)); } +); - inner(|| NonCopy(10), || NonCopy(20)); - inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); -} +nonpoison_and_poison_unwrap_test!( + name: test_set, + test_body: { + use locks::Mutex; + fn inner(mut init: impl FnMut() -> T, mut value: impl FnMut() -> T) + where + T: Debug + Eq, + { + let m = Mutex::new(init()); + + assert_eq!(*maybe_unwrap(m.lock()), init()); + maybe_unwrap(m.set(value())); + assert_eq!(*maybe_unwrap(m.lock()), value()); + } + + inner(|| NonCopy(10), || NonCopy(20)); + inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); + } +); + +// Ensure that old values that are replaced by `set` are correctly dropped. +nonpoison_and_poison_unwrap_test!( + name: test_replace, + test_body: { + use locks::Mutex; + + fn inner(mut init: impl FnMut() -> T, mut value: impl FnMut() -> T) + where + T: Debug + Eq, + { + let m = Mutex::new(init()); + + assert_eq!(*maybe_unwrap(m.lock()), init()); + assert_eq!(maybe_unwrap(m.replace(value())), init()); + assert_eq!(*maybe_unwrap(m.lock()), value()); + } + + inner(|| NonCopy(10), || NonCopy(20)); + inner(|| NonCopyNeedsDrop(10), || NonCopyNeedsDrop(20)); + } +); + +// FIXME(nonpoison_condvar): Move this to the `condvar.rs` test file once `nonpoison::condvar` gets +// implemented. #[test] fn test_mutex_arc_condvar() { struct Packet(Arc<(Mutex, Condvar)>); let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); let packet2 = Packet(packet.0.clone()); + let (tx, rx) = channel(); + let _t = thread::spawn(move || { - // wait until parent gets in + // Wait until our parent has taken the lock. rx.recv().unwrap(); let &(ref lock, ref cvar) = &*packet2.0; - let mut lock = lock.lock().unwrap(); - *lock = true; + + // Set the data to `true` and wake up our parent. + let mut guard = lock.lock().unwrap(); + *guard = true; cvar.notify_one(); }); let &(ref lock, ref cvar) = &*packet.0; - let mut lock = lock.lock().unwrap(); + let mut guard = lock.lock().unwrap(); + // Wake up our child. tx.send(()).unwrap(); - assert!(!*lock); - while !*lock { - lock = cvar.wait(lock).unwrap(); + + // Wait until our child has set the data to `true`. + assert!(!*guard); + while !*guard { + guard = cvar.wait(guard).unwrap(); } } -#[test] -fn test_mutex_arc_nested() { - // Tests nested mutexes and access - // to underlying data. - let arc = Arc::new(Mutex::new(1)); - let arc2 = Arc::new(Mutex::new(arc)); - let (tx, rx) = channel(); - let _t = thread::spawn(move || { - let lock = arc2.lock().unwrap(); - let lock2 = lock.lock().unwrap(); - assert_eq!(*lock2, 1); - tx.send(()).unwrap(); - }); - rx.recv().unwrap(); -} +nonpoison_and_poison_unwrap_test!( + name: test_mutex_arc_nested, + test_body: { + use locks::Mutex; -#[test] -fn test_mutex_unsized() { - let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); - { - let b = &mut *mutex.lock().unwrap(); - b[0] = 4; - b[2] = 5; + // Tests nested mutexes and access + // to underlying data. + let arc = Arc::new(Mutex::new(1)); + let arc2 = Arc::new(Mutex::new(arc)); + let (tx, rx) = channel(); + let _t = thread::spawn(move || { + let lock = maybe_unwrap(arc2.lock()); + let lock2 = maybe_unwrap(lock.lock()); + assert_eq!(*lock2, 1); + tx.send(()).unwrap(); + }); + rx.recv().unwrap(); } - let comp: &[i32] = &[4, 2, 5]; - assert_eq!(&*mutex.lock().unwrap(), comp); -} +); -#[test] -fn test_mapping_mapped_guard() { - let arr = [0; 4]; - let mut lock = Mutex::new(arr); - let guard = lock.lock().unwrap(); - let guard = MutexGuard::map(guard, |arr| &mut arr[..2]); - let mut guard = MappedMutexGuard::map(guard, |slice| &mut slice[1..]); - assert_eq!(guard.len(), 1); - guard[0] = 42; - drop(guard); - assert_eq!(*lock.get_mut().unwrap(), [0, 42, 0, 0]); -} +nonpoison_and_poison_unwrap_test!( + name: test_mutex_unsized, + test_body: { + use locks::Mutex; + + let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); + { + let b = &mut *maybe_unwrap(mutex.lock()); + b[0] = 4; + b[2] = 5; + } + let comp: &[i32] = &[4, 2, 5]; + assert_eq!(&*maybe_unwrap(mutex.lock()), comp); + } +); + +nonpoison_and_poison_unwrap_test!( + name: test_mapping_mapped_guard, + test_body: { + use locks::{Mutex, MutexGuard, MappedMutexGuard}; + + let arr = [0; 4]; + let lock = Mutex::new(arr); + let guard = maybe_unwrap(lock.lock()); + let guard = MutexGuard::map(guard, |arr| &mut arr[..2]); + let mut guard = MappedMutexGuard::map(guard, |slice| &mut slice[1..]); + assert_eq!(guard.len(), 1); + guard[0] = 42; + drop(guard); + assert_eq!(*maybe_unwrap(lock.lock()), [0, 42, 0, 0]); + } +); //////////////////////////////////////////////////////////////////////////////////////////////////// // Poison Tests From d073d297b65f8cc0c8b75249b74c7df5a3dc18bc Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Tue, 29 Jul 2025 10:44:36 +0200 Subject: [PATCH 279/809] add extra drop, panic, and unwind tests --- library/std/tests/sync/mutex.rs | 102 +++++++++++++++++++++++++------- 1 file changed, 80 insertions(+), 22 deletions(-) diff --git a/library/std/tests/sync/mutex.rs b/library/std/tests/sync/mutex.rs index 60f5d4f45bf2..90cefc0d5946 100644 --- a/library/std/tests/sync/mutex.rs +++ b/library/std/tests/sync/mutex.rs @@ -111,6 +111,7 @@ nonpoison_and_poison_unwrap_test!( self.0.fetch_add(1, Ordering::SeqCst); } } + let num_drops = Arc::new(AtomicUsize::new(0)); let m = Mutex::new(Foo(num_drops.clone())); assert_eq!(num_drops.load(Ordering::SeqCst), 0); @@ -169,6 +170,28 @@ nonpoison_and_poison_unwrap_test!( ); // Ensure that old values that are replaced by `set` are correctly dropped. +nonpoison_and_poison_unwrap_test!( + name: test_set_drop, + test_body: { + use locks::Mutex; + + struct Foo(Arc); + impl Drop for Foo { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + + let num_drops = Arc::new(AtomicUsize::new(0)); + let m = Mutex::new(Foo(num_drops.clone())); + assert_eq!(num_drops.load(Ordering::SeqCst), 0); + + let different = Foo(Arc::new(AtomicUsize::new(42))); + maybe_unwrap(m.set(different)); + assert_eq!(num_drops.load(Ordering::SeqCst), 1); + } +); + nonpoison_and_poison_unwrap_test!( name: test_replace, test_body: { @@ -277,6 +300,63 @@ nonpoison_and_poison_unwrap_test!( } ); +#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] +nonpoison_and_poison_unwrap_test!( + name: test_panics, + test_body: { + use locks::Mutex; + + let mutex = Mutex::new(42); + + let catch_unwind_result1 = panic::catch_unwind(AssertUnwindSafe(|| { + let _guard1 = maybe_unwrap(mutex.lock()); + + panic!("test panic with mutex once"); + })); + assert!(catch_unwind_result1.is_err()); + + let catch_unwind_result2 = panic::catch_unwind(AssertUnwindSafe(|| { + let _guard2 = maybe_unwrap(mutex.lock()); + + panic!("test panic with mutex twice"); + })); + assert!(catch_unwind_result2.is_err()); + + let catch_unwind_result3 = panic::catch_unwind(AssertUnwindSafe(|| { + let _guard3 = maybe_unwrap(mutex.lock()); + + panic!("test panic with mutex thrice"); + })); + assert!(catch_unwind_result3.is_err()); + } +); + +#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] +nonpoison_and_poison_unwrap_test!( + name: test_mutex_arc_access_in_unwind, + test_body: { + use locks::Mutex; + + let arc = Arc::new(Mutex::new(1)); + let arc2 = arc.clone(); + let _ = thread::spawn(move || -> () { + struct Unwinder { + i: Arc>, + } + impl Drop for Unwinder { + fn drop(&mut self) { + *maybe_unwrap(self.i.lock()) += 1; + } + } + let _u = Unwinder { i: arc2 }; + panic!(); + }) + .join(); + let lock = maybe_unwrap(arc.lock()); + assert_eq!(*lock, 2); + } +); + //////////////////////////////////////////////////////////////////////////////////////////////////// // Poison Tests //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -440,28 +520,6 @@ fn test_mutex_arc_poison_mapped() { assert!(arc.is_poisoned()); } -#[test] -#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] -fn test_mutex_arc_access_in_unwind() { - let arc = Arc::new(Mutex::new(1)); - let arc2 = arc.clone(); - let _ = thread::spawn(move || -> () { - struct Unwinder { - i: Arc>, - } - impl Drop for Unwinder { - fn drop(&mut self) { - *self.i.lock().unwrap() += 1; - } - } - let _u = Unwinder { i: arc2 }; - panic!(); - }) - .join(); - let lock = arc.lock().unwrap(); - assert_eq!(*lock, 2); -} - #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn panic_while_mapping_unlocked_poison() { From 64a27c2e370e1f9e50fb231fc7d6a4debcebe985 Mon Sep 17 00:00:00 2001 From: lcnr Date: Tue, 29 Jul 2025 09:46:41 +0000 Subject: [PATCH 280/809] resuse eagerly resolved goal from previous iteration --- .../src/solve/eval_ctxt/canonical.rs | 9 ++---- .../src/solve/eval_ctxt/mod.rs | 31 +++++++++++++++---- .../rustc_next_trait_solver/src/solve/mod.rs | 4 +++ .../src/solve/fulfill.rs | 6 +++- 4 files changed, 37 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs index de1330ca82a4..74c5b49ea92f 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs @@ -53,17 +53,14 @@ where { /// Canonicalizes the goal remembering the original values /// for each bound variable. + /// + /// This expects `goal` and `opaque_types` to be eager resolved. pub(super) fn canonicalize_goal( &self, is_hir_typeck_root_goal: bool, goal: Goal, + opaque_types: Vec<(ty::OpaqueTypeKey, I::Ty)>, ) -> (Vec, CanonicalInput) { - // We only care about one entry per `OpaqueTypeKey` here, - // so we only canonicalize the lookup table and ignore - // duplicate entries. - let opaque_types = self.delegate.clone_opaque_types_lookup_table(); - let (goal, opaque_types) = eager_resolve_vars(self.delegate, (goal, opaque_types)); - let mut orig_values = Default::default(); let canonical = Canonicalizer::canonicalize_input( self.delegate, diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index 053ccf285cf0..8671cc7c3d30 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -20,6 +20,7 @@ use super::has_only_region_constraints; use crate::coherence; use crate::delegate::SolverDelegate; use crate::placeholder::BoundVarReplacer; +use crate::resolve::eager_resolve_vars; use crate::solve::inspect::{self, ProofTreeBuilder}; use crate::solve::search_graph::SearchGraph; use crate::solve::ty::may_use_unstable_feature; @@ -440,6 +441,7 @@ where return Ok(( NestedNormalizationGoals::empty(), GoalEvaluation { + goal, certainty: Certainty::Maybe(stalled_on.stalled_cause), has_changed: HasChanged::No, stalled_on: Some(stalled_on), @@ -447,10 +449,16 @@ where )); } + // We only care about one entry per `OpaqueTypeKey` here, + // so we only canonicalize the lookup table and ignore + // duplicate entries. + let opaque_types = self.delegate.clone_opaque_types_lookup_table(); + let (goal, opaque_types) = eager_resolve_vars(self.delegate, (goal, opaque_types)); + let is_hir_typeck_root_goal = matches!(goal_evaluation_kind, GoalEvaluationKind::Root) && self.delegate.in_hir_typeck(); - - let (orig_values, canonical_goal) = self.canonicalize_goal(is_hir_typeck_root_goal, goal); + let (orig_values, canonical_goal) = + self.canonicalize_goal(is_hir_typeck_root_goal, goal, opaque_types); let mut goal_evaluation = self.inspect.new_goal_evaluation(goal, &orig_values, goal_evaluation_kind); let canonical_result = self.search_graph.evaluate_goal( @@ -528,7 +536,10 @@ where }, }; - Ok((normalization_nested_goals, GoalEvaluation { certainty, has_changed, stalled_on })) + Ok(( + normalization_nested_goals, + GoalEvaluation { goal, certainty, has_changed, stalled_on }, + )) } pub(super) fn compute_goal(&mut self, goal: Goal) -> QueryResult { @@ -664,7 +675,7 @@ where let ( NestedNormalizationGoals(nested_goals), - GoalEvaluation { certainty, stalled_on, has_changed: _ }, + GoalEvaluation { goal, certainty, stalled_on, has_changed: _ }, ) = self.evaluate_goal_raw( GoalEvaluationKind::Nested, source, @@ -702,7 +713,15 @@ where // FIXME: Do we need to eagerly resolve here? Or should we check // if the cache key has any changed vars? let with_resolved_vars = self.resolve_vars_if_possible(goal); - if pred.alias != goal.predicate.as_normalizes_to().unwrap().skip_binder().alias { + if pred.alias + != with_resolved_vars + .predicate + .as_normalizes_to() + .unwrap() + .no_bound_vars() + .unwrap() + .alias + { unchanged_certainty = None; } @@ -714,7 +733,7 @@ where } } } else { - let GoalEvaluation { certainty, has_changed, stalled_on } = + let GoalEvaluation { goal, certainty, has_changed, stalled_on } = self.evaluate_goal(GoalEvaluationKind::Nested, source, goal, stalled_on)?; if has_changed == HasChanged::Yes { unchanged_certainty = None; diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index f39426c7689d..9d52dee3c659 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -386,6 +386,10 @@ fn response_no_constraints_raw( /// The result of evaluating a goal. pub struct GoalEvaluation { + /// The goal we've evaluated. This is the input goal, but potentially with its + /// inference variables resolved. This never applies any inference constraints + /// from evaluating the goal. + pub goal: Goal, pub certainty: Certainty, pub has_changed: HasChanged, /// If the [`Certainty`] was `Maybe`, then keep track of whether the goal has changed diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 3ce0f0255124..70452947a8b5 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -207,7 +207,7 @@ where let result = delegate.evaluate_root_goal(goal, obligation.cause.span, stalled_on); self.inspect_evaluated_obligation(infcx, &obligation, &result); - let GoalEvaluation { certainty, has_changed, stalled_on } = match result { + let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result { Ok(result) => result, Err(NoSolution) => { errors.push(E::from_solver_error( @@ -218,6 +218,10 @@ where } }; + // We've resolved the goal in `evaluate_root_goal`, avoid redoing this work + // in the next iteration. This does not resolve the inference variables + // constrained by evaluating the goal. + obligation.predicate = goal.predicate; if has_changed == HasChanged::Yes { // We increment the recursion depth here to track the number of times // this goal has resulted in inference progress. This doesn't precisely From 27610341768951b2d46071683bcb87ea7c690e98 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 28 Jul 2025 12:05:17 +1000 Subject: [PATCH 281/809] coverage: Test how `#[automatically_derived]` affects instrumentation --- tests/coverage/auto-derived.auto.cov-map | 47 +++++++++++++++++ tests/coverage/auto-derived.auto.coverage | 54 ++++++++++++++++++++ tests/coverage/auto-derived.base.cov-map | 61 +++++++++++++++++++++++ tests/coverage/auto-derived.base.coverage | 54 ++++++++++++++++++++ tests/coverage/auto-derived.on.cov-map | 47 +++++++++++++++++ tests/coverage/auto-derived.on.coverage | 54 ++++++++++++++++++++ tests/coverage/auto-derived.rs | 53 ++++++++++++++++++++ 7 files changed, 370 insertions(+) create mode 100644 tests/coverage/auto-derived.auto.cov-map create mode 100644 tests/coverage/auto-derived.auto.coverage create mode 100644 tests/coverage/auto-derived.base.cov-map create mode 100644 tests/coverage/auto-derived.base.coverage create mode 100644 tests/coverage/auto-derived.on.cov-map create mode 100644 tests/coverage/auto-derived.on.coverage create mode 100644 tests/coverage/auto-derived.rs diff --git a/tests/coverage/auto-derived.auto.cov-map b/tests/coverage/auto-derived.auto.cov-map new file mode 100644 index 000000000000..a0aa1206de42 --- /dev/null +++ b/tests/coverage/auto-derived.auto.cov-map @@ -0,0 +1,47 @@ +Function name: ::my_assoc_fn::inner_fn +Raw bytes (24): 0x[01, 01, 00, 04, 01, 1a, 09, 00, 16, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1e, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 26, 9) to (start + 0, 22) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 30) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: ::my_assoc_fn::inner_fn_on +Raw bytes (24): 0x[01, 01, 00, 04, 01, 1f, 09, 00, 19, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 23, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 31, 9) to (start + 0, 25) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 35) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: ::my_assoc_fn::{closure#0} +Raw bytes (24): 0x[01, 01, 00, 04, 01, 23, 1a, 00, 1b, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1d, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 35, 26) to (start + 0, 27) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 29) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: auto_derived::main +Raw bytes (19): 0x[01, 01, 00, 03, 01, 33, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 3 +- Code(Counter(0)) at (prev + 51, 1) to (start + 0, 10) +- Code(Counter(0)) at (prev + 1, 5) to (start + 0, 26) +- Code(Counter(0)) at (prev + 1, 1) to (start + 0, 2) +Highest counter ID seen: c0 + diff --git a/tests/coverage/auto-derived.auto.coverage b/tests/coverage/auto-derived.auto.coverage new file mode 100644 index 000000000000..960bd11ec3a1 --- /dev/null +++ b/tests/coverage/auto-derived.auto.coverage @@ -0,0 +1,54 @@ + LL| |#![feature(coverage_attribute)] + LL| |//@ edition: 2024 + LL| |//@ revisions: base auto on + LL| | + LL| |// Tests for how `#[automatically_derived]` affects coverage instrumentation. + LL| |// + LL| |// The actual behaviour is an implementation detail, so this test mostly exists + LL| |// to show when that behaviour has been accidentally or deliberately changed. + LL| |// + LL| |// Revision guide: + LL| |// - base: Test baseline instrumentation behaviour without `#[automatically_derived]` + LL| |// - auto: Test how `#[automatically_derived]` affects instrumentation + LL| |// - on: Test interaction between auto-derived and `#[coverage(on)]` + LL| | + LL| |struct MyStruct; + LL| | + LL| |trait MyTrait { + LL| | fn my_assoc_fn(); + LL| |} + LL| | + LL| |#[cfg_attr(auto, automatically_derived)] + LL| |#[cfg_attr(on, automatically_derived)] + LL| |#[cfg_attr(on, coverage(on))] + LL| |impl MyTrait for MyStruct { + LL| | fn my_assoc_fn() { + LL| 1| fn inner_fn() { + LL| 1| say("in inner fn"); + LL| 1| } + LL| | + LL| | #[coverage(on)] + LL| 1| fn inner_fn_on() { + LL| 1| say("in inner fn (on)"); + LL| 1| } + LL| | + LL| 1| let closure = || { + LL| 1| say("in closure"); + LL| 1| }; + LL| | + LL| | closure(); + LL| | inner_fn(); + LL| | inner_fn_on(); + LL| | } + LL| |} + LL| | + LL| |#[coverage(off)] + LL| |#[inline(never)] + LL| |fn say(s: &str) { + LL| | println!("{s}"); + LL| |} + LL| | + LL| 1|fn main() { + LL| 1| MyStruct::my_assoc_fn(); + LL| 1|} + diff --git a/tests/coverage/auto-derived.base.cov-map b/tests/coverage/auto-derived.base.cov-map new file mode 100644 index 000000000000..2dcd616300d9 --- /dev/null +++ b/tests/coverage/auto-derived.base.cov-map @@ -0,0 +1,61 @@ +Function name: ::my_assoc_fn +Raw bytes (34): 0x[01, 01, 00, 06, 01, 19, 05, 00, 15, 01, 0a, 0d, 00, 14, 01, 04, 09, 00, 12, 01, 01, 09, 00, 11, 01, 01, 09, 00, 14, 01, 01, 05, 00, 06] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 6 +- Code(Counter(0)) at (prev + 25, 5) to (start + 0, 21) +- Code(Counter(0)) at (prev + 10, 13) to (start + 0, 20) +- Code(Counter(0)) at (prev + 4, 9) to (start + 0, 18) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 17) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 20) +- Code(Counter(0)) at (prev + 1, 5) to (start + 0, 6) +Highest counter ID seen: c0 + +Function name: ::my_assoc_fn::inner_fn +Raw bytes (24): 0x[01, 01, 00, 04, 01, 1a, 09, 00, 16, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1e, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 26, 9) to (start + 0, 22) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 30) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: ::my_assoc_fn::inner_fn_on +Raw bytes (24): 0x[01, 01, 00, 04, 01, 1f, 09, 00, 19, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 23, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 31, 9) to (start + 0, 25) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 35) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: ::my_assoc_fn::{closure#0} +Raw bytes (24): 0x[01, 01, 00, 04, 01, 23, 1a, 00, 1b, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1d, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 35, 26) to (start + 0, 27) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 29) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: auto_derived::main +Raw bytes (19): 0x[01, 01, 00, 03, 01, 33, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 3 +- Code(Counter(0)) at (prev + 51, 1) to (start + 0, 10) +- Code(Counter(0)) at (prev + 1, 5) to (start + 0, 26) +- Code(Counter(0)) at (prev + 1, 1) to (start + 0, 2) +Highest counter ID seen: c0 + diff --git a/tests/coverage/auto-derived.base.coverage b/tests/coverage/auto-derived.base.coverage new file mode 100644 index 000000000000..6ab6aa5c4dfc --- /dev/null +++ b/tests/coverage/auto-derived.base.coverage @@ -0,0 +1,54 @@ + LL| |#![feature(coverage_attribute)] + LL| |//@ edition: 2024 + LL| |//@ revisions: base auto on + LL| | + LL| |// Tests for how `#[automatically_derived]` affects coverage instrumentation. + LL| |// + LL| |// The actual behaviour is an implementation detail, so this test mostly exists + LL| |// to show when that behaviour has been accidentally or deliberately changed. + LL| |// + LL| |// Revision guide: + LL| |// - base: Test baseline instrumentation behaviour without `#[automatically_derived]` + LL| |// - auto: Test how `#[automatically_derived]` affects instrumentation + LL| |// - on: Test interaction between auto-derived and `#[coverage(on)]` + LL| | + LL| |struct MyStruct; + LL| | + LL| |trait MyTrait { + LL| | fn my_assoc_fn(); + LL| |} + LL| | + LL| |#[cfg_attr(auto, automatically_derived)] + LL| |#[cfg_attr(on, automatically_derived)] + LL| |#[cfg_attr(on, coverage(on))] + LL| |impl MyTrait for MyStruct { + LL| 1| fn my_assoc_fn() { + LL| 1| fn inner_fn() { + LL| 1| say("in inner fn"); + LL| 1| } + LL| | + LL| | #[coverage(on)] + LL| 1| fn inner_fn_on() { + LL| 1| say("in inner fn (on)"); + LL| 1| } + LL| | + LL| 1| let closure = || { + LL| 1| say("in closure"); + LL| 1| }; + LL| | + LL| 1| closure(); + LL| 1| inner_fn(); + LL| 1| inner_fn_on(); + LL| 1| } + LL| |} + LL| | + LL| |#[coverage(off)] + LL| |#[inline(never)] + LL| |fn say(s: &str) { + LL| | println!("{s}"); + LL| |} + LL| | + LL| 1|fn main() { + LL| 1| MyStruct::my_assoc_fn(); + LL| 1|} + diff --git a/tests/coverage/auto-derived.on.cov-map b/tests/coverage/auto-derived.on.cov-map new file mode 100644 index 000000000000..a0aa1206de42 --- /dev/null +++ b/tests/coverage/auto-derived.on.cov-map @@ -0,0 +1,47 @@ +Function name: ::my_assoc_fn::inner_fn +Raw bytes (24): 0x[01, 01, 00, 04, 01, 1a, 09, 00, 16, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1e, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 26, 9) to (start + 0, 22) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 30) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: ::my_assoc_fn::inner_fn_on +Raw bytes (24): 0x[01, 01, 00, 04, 01, 1f, 09, 00, 19, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 23, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 31, 9) to (start + 0, 25) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 35) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: ::my_assoc_fn::{closure#0} +Raw bytes (24): 0x[01, 01, 00, 04, 01, 23, 1a, 00, 1b, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1d, 01, 01, 09, 00, 0a] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 4 +- Code(Counter(0)) at (prev + 35, 26) to (start + 0, 27) +- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) +- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 29) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) +Highest counter ID seen: c0 + +Function name: auto_derived::main +Raw bytes (19): 0x[01, 01, 00, 03, 01, 33, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 3 +- Code(Counter(0)) at (prev + 51, 1) to (start + 0, 10) +- Code(Counter(0)) at (prev + 1, 5) to (start + 0, 26) +- Code(Counter(0)) at (prev + 1, 1) to (start + 0, 2) +Highest counter ID seen: c0 + diff --git a/tests/coverage/auto-derived.on.coverage b/tests/coverage/auto-derived.on.coverage new file mode 100644 index 000000000000..960bd11ec3a1 --- /dev/null +++ b/tests/coverage/auto-derived.on.coverage @@ -0,0 +1,54 @@ + LL| |#![feature(coverage_attribute)] + LL| |//@ edition: 2024 + LL| |//@ revisions: base auto on + LL| | + LL| |// Tests for how `#[automatically_derived]` affects coverage instrumentation. + LL| |// + LL| |// The actual behaviour is an implementation detail, so this test mostly exists + LL| |// to show when that behaviour has been accidentally or deliberately changed. + LL| |// + LL| |// Revision guide: + LL| |// - base: Test baseline instrumentation behaviour without `#[automatically_derived]` + LL| |// - auto: Test how `#[automatically_derived]` affects instrumentation + LL| |// - on: Test interaction between auto-derived and `#[coverage(on)]` + LL| | + LL| |struct MyStruct; + LL| | + LL| |trait MyTrait { + LL| | fn my_assoc_fn(); + LL| |} + LL| | + LL| |#[cfg_attr(auto, automatically_derived)] + LL| |#[cfg_attr(on, automatically_derived)] + LL| |#[cfg_attr(on, coverage(on))] + LL| |impl MyTrait for MyStruct { + LL| | fn my_assoc_fn() { + LL| 1| fn inner_fn() { + LL| 1| say("in inner fn"); + LL| 1| } + LL| | + LL| | #[coverage(on)] + LL| 1| fn inner_fn_on() { + LL| 1| say("in inner fn (on)"); + LL| 1| } + LL| | + LL| 1| let closure = || { + LL| 1| say("in closure"); + LL| 1| }; + LL| | + LL| | closure(); + LL| | inner_fn(); + LL| | inner_fn_on(); + LL| | } + LL| |} + LL| | + LL| |#[coverage(off)] + LL| |#[inline(never)] + LL| |fn say(s: &str) { + LL| | println!("{s}"); + LL| |} + LL| | + LL| 1|fn main() { + LL| 1| MyStruct::my_assoc_fn(); + LL| 1|} + diff --git a/tests/coverage/auto-derived.rs b/tests/coverage/auto-derived.rs new file mode 100644 index 000000000000..cbf8279918a2 --- /dev/null +++ b/tests/coverage/auto-derived.rs @@ -0,0 +1,53 @@ +#![feature(coverage_attribute)] +//@ edition: 2024 +//@ revisions: base auto on + +// Tests for how `#[automatically_derived]` affects coverage instrumentation. +// +// The actual behaviour is an implementation detail, so this test mostly exists +// to show when that behaviour has been accidentally or deliberately changed. +// +// Revision guide: +// - base: Test baseline instrumentation behaviour without `#[automatically_derived]` +// - auto: Test how `#[automatically_derived]` affects instrumentation +// - on: Test interaction between auto-derived and `#[coverage(on)]` + +struct MyStruct; + +trait MyTrait { + fn my_assoc_fn(); +} + +#[cfg_attr(auto, automatically_derived)] +#[cfg_attr(on, automatically_derived)] +#[cfg_attr(on, coverage(on))] +impl MyTrait for MyStruct { + fn my_assoc_fn() { + fn inner_fn() { + say("in inner fn"); + } + + #[coverage(on)] + fn inner_fn_on() { + say("in inner fn (on)"); + } + + let closure = || { + say("in closure"); + }; + + closure(); + inner_fn(); + inner_fn_on(); + } +} + +#[coverage(off)] +#[inline(never)] +fn say(s: &str) { + println!("{s}"); +} + +fn main() { + MyStruct::my_assoc_fn(); +} From b4d0c91635e87be830282cb86d23882b6b6f9dad Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 28 Jul 2025 12:29:40 +1000 Subject: [PATCH 282/809] coverage: Rename `CoverageStatus` to `CoverageAttrKind` This patch also prepares the affected code in `coverage_attr_on` for some subsequent changes. --- .../src/attributes.rs | 20 ++++--------- .../src/attributes/codegen_attrs.rs | 10 +++---- .../rustc_mir_transform/src/coverage/query.rs | 29 ++++++++++--------- 3 files changed, 27 insertions(+), 32 deletions(-) diff --git a/compiler/rustc_attr_data_structures/src/attributes.rs b/compiler/rustc_attr_data_structures/src/attributes.rs index 610c93a253ce..55019cd57a71 100644 --- a/compiler/rustc_attr_data_structures/src/attributes.rs +++ b/compiler/rustc_attr_data_structures/src/attributes.rs @@ -110,18 +110,10 @@ pub enum DeprecatedSince { Err, } -#[derive( - Copy, - Debug, - Eq, - PartialEq, - Encodable, - Decodable, - Clone, - HashStable_Generic, - PrintAttribute -)] -pub enum CoverageStatus { +/// Successfully-parsed value of a `#[coverage(..)]` attribute. +#[derive(Copy, Debug, Eq, PartialEq, Encodable, Decodable, Clone)] +#[derive(HashStable_Generic, PrintAttribute)] +pub enum CoverageAttrKind { On, Off, } @@ -304,8 +296,8 @@ pub enum AttributeKind { /// Represents `#[const_trait]`. ConstTrait(Span), - /// Represents `#[coverage]`. - Coverage(Span, CoverageStatus), + /// Represents `#[coverage(..)]`. + Coverage(Span, CoverageAttrKind), ///Represents `#[rustc_deny_explicit_impl]`. DenyExplicitImpl(Span), diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index bb28121c2c5d..afa9abed0bb5 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::{AttributeKind, CoverageStatus, OptimizeAttr, UsedBy}; +use rustc_attr_data_structures::{AttributeKind, CoverageAttrKind, OptimizeAttr, UsedBy}; use rustc_feature::{AttributeTemplate, template}; use rustc_session::parse::feature_err; use rustc_span::{Span, Symbol, sym}; @@ -78,16 +78,16 @@ impl SingleAttributeParser for CoverageParser { return None; }; - let status = match arg.path().word_sym() { - Some(sym::off) => CoverageStatus::Off, - Some(sym::on) => CoverageStatus::On, + let kind = match arg.path().word_sym() { + Some(sym::off) => CoverageAttrKind::Off, + Some(sym::on) => CoverageAttrKind::On, None | Some(_) => { fail_incorrect_argument(arg.span()); return None; } }; - Some(AttributeKind::Coverage(cx.attr_span, status)) + Some(AttributeKind::Coverage(cx.attr_span, kind)) } } diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 551f720c869e..02e433e53c92 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::{AttributeKind, CoverageStatus, find_attr}; +use rustc_attr_data_structures::{AttributeKind, CoverageAttrKind, find_attr}; use rustc_index::bit_set::DenseBitSet; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir::coverage::{BasicCoverageBlock, CoverageIdsInfo, CoverageKind, MappingKind}; @@ -57,20 +57,23 @@ fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { /// Query implementation for `coverage_attr_on`. fn coverage_attr_on(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { - // Check for annotations directly on this def. - if let Some(coverage_status) = - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Coverage(_, status) => status) + // Check for a `#[coverage(..)]` attribute on this def. + if let Some(kind) = + find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Coverage(_sp, kind) => kind) { - *coverage_status == CoverageStatus::On - } else { - match tcx.opt_local_parent(def_id) { - // Check the parent def (and so on recursively) until we find an - // enclosing attribute or reach the crate root. - Some(parent) => tcx.coverage_attr_on(parent), - // We reached the crate root without seeing a coverage attribute, so - // allow coverage instrumentation by default. - None => true, + match kind { + CoverageAttrKind::On => return true, + CoverageAttrKind::Off => return false, } + }; + + // Check the parent def (and so on recursively) until we find an + // enclosing attribute or reach the crate root. + match tcx.opt_local_parent(def_id) { + Some(parent) => tcx.coverage_attr_on(parent), + // We reached the crate root without seeing a coverage attribute, so + // allow coverage instrumentation by default. + None => true, } } From 682f744f89e1c014e91b2fd7058c75f2056ac870 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 28 Jul 2025 12:25:05 +1000 Subject: [PATCH 283/809] coverage: Treat `#[automatically_derived]` as `#[coverage(off)]` --- .../rustc_mir_transform/src/coverage/query.rs | 19 +++++++-------- tests/coverage/auto-derived.auto.cov-map | 24 ------------------- tests/coverage/auto-derived.auto.coverage | 12 +++++----- tests/coverage/auto-derived.on.cov-map | 14 +++++++++++ tests/coverage/auto-derived.on.coverage | 10 ++++---- 5 files changed, 34 insertions(+), 45 deletions(-) diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 02e433e53c92..73795e47d2e9 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -32,16 +32,6 @@ fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { return false; } - // Don't instrument functions with `#[automatically_derived]` on their - // enclosing impl block, on the assumption that most users won't care about - // coverage for derived impls. - if let Some(impl_of) = tcx.impl_of_assoc(def_id.to_def_id()) - && tcx.is_automatically_derived(impl_of) - { - trace!("InstrumentCoverage skipped for {def_id:?} (automatically derived)"); - return false; - } - if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED) { trace!("InstrumentCoverage skipped for {def_id:?} (`#[naked]`)"); return false; @@ -67,6 +57,15 @@ fn coverage_attr_on(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { } }; + // Treat `#[automatically_derived]` as an implied `#[coverage(off)]`, on + // the assumption that most users won't want coverage for derived impls. + // + // This affects not just the associated items of an impl block, but also + // any closures and other nested functions within those associated items. + if tcx.is_automatically_derived(def_id.to_def_id()) { + return false; + } + // Check the parent def (and so on recursively) until we find an // enclosing attribute or reach the crate root. match tcx.opt_local_parent(def_id) { diff --git a/tests/coverage/auto-derived.auto.cov-map b/tests/coverage/auto-derived.auto.cov-map index a0aa1206de42..e3d411d895aa 100644 --- a/tests/coverage/auto-derived.auto.cov-map +++ b/tests/coverage/auto-derived.auto.cov-map @@ -1,15 +1,3 @@ -Function name: ::my_assoc_fn::inner_fn -Raw bytes (24): 0x[01, 01, 00, 04, 01, 1a, 09, 00, 16, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1e, 01, 01, 09, 00, 0a] -Number of files: 1 -- file 0 => $DIR/auto-derived.rs -Number of expressions: 0 -Number of file 0 mappings: 4 -- Code(Counter(0)) at (prev + 26, 9) to (start + 0, 22) -- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) -- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 30) -- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) -Highest counter ID seen: c0 - Function name: ::my_assoc_fn::inner_fn_on Raw bytes (24): 0x[01, 01, 00, 04, 01, 1f, 09, 00, 19, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 23, 01, 01, 09, 00, 0a] Number of files: 1 @@ -22,18 +10,6 @@ Number of file 0 mappings: 4 - Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) Highest counter ID seen: c0 -Function name: ::my_assoc_fn::{closure#0} -Raw bytes (24): 0x[01, 01, 00, 04, 01, 23, 1a, 00, 1b, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1d, 01, 01, 09, 00, 0a] -Number of files: 1 -- file 0 => $DIR/auto-derived.rs -Number of expressions: 0 -Number of file 0 mappings: 4 -- Code(Counter(0)) at (prev + 35, 26) to (start + 0, 27) -- Code(Counter(0)) at (prev + 1, 13) to (start + 0, 16) -- Code(Counter(0)) at (prev + 0, 17) to (start + 0, 29) -- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 10) -Highest counter ID seen: c0 - Function name: auto_derived::main Raw bytes (19): 0x[01, 01, 00, 03, 01, 33, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] Number of files: 1 diff --git a/tests/coverage/auto-derived.auto.coverage b/tests/coverage/auto-derived.auto.coverage index 960bd11ec3a1..242abbf80318 100644 --- a/tests/coverage/auto-derived.auto.coverage +++ b/tests/coverage/auto-derived.auto.coverage @@ -23,18 +23,18 @@ LL| |#[cfg_attr(on, coverage(on))] LL| |impl MyTrait for MyStruct { LL| | fn my_assoc_fn() { - LL| 1| fn inner_fn() { - LL| 1| say("in inner fn"); - LL| 1| } + LL| | fn inner_fn() { + LL| | say("in inner fn"); + LL| | } LL| | LL| | #[coverage(on)] LL| 1| fn inner_fn_on() { LL| 1| say("in inner fn (on)"); LL| 1| } LL| | - LL| 1| let closure = || { - LL| 1| say("in closure"); - LL| 1| }; + LL| | let closure = || { + LL| | say("in closure"); + LL| | }; LL| | LL| | closure(); LL| | inner_fn(); diff --git a/tests/coverage/auto-derived.on.cov-map b/tests/coverage/auto-derived.on.cov-map index a0aa1206de42..2dcd616300d9 100644 --- a/tests/coverage/auto-derived.on.cov-map +++ b/tests/coverage/auto-derived.on.cov-map @@ -1,3 +1,17 @@ +Function name: ::my_assoc_fn +Raw bytes (34): 0x[01, 01, 00, 06, 01, 19, 05, 00, 15, 01, 0a, 0d, 00, 14, 01, 04, 09, 00, 12, 01, 01, 09, 00, 11, 01, 01, 09, 00, 14, 01, 01, 05, 00, 06] +Number of files: 1 +- file 0 => $DIR/auto-derived.rs +Number of expressions: 0 +Number of file 0 mappings: 6 +- Code(Counter(0)) at (prev + 25, 5) to (start + 0, 21) +- Code(Counter(0)) at (prev + 10, 13) to (start + 0, 20) +- Code(Counter(0)) at (prev + 4, 9) to (start + 0, 18) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 17) +- Code(Counter(0)) at (prev + 1, 9) to (start + 0, 20) +- Code(Counter(0)) at (prev + 1, 5) to (start + 0, 6) +Highest counter ID seen: c0 + Function name: ::my_assoc_fn::inner_fn Raw bytes (24): 0x[01, 01, 00, 04, 01, 1a, 09, 00, 16, 01, 01, 0d, 00, 10, 01, 00, 11, 00, 1e, 01, 01, 09, 00, 0a] Number of files: 1 diff --git a/tests/coverage/auto-derived.on.coverage b/tests/coverage/auto-derived.on.coverage index 960bd11ec3a1..6ab6aa5c4dfc 100644 --- a/tests/coverage/auto-derived.on.coverage +++ b/tests/coverage/auto-derived.on.coverage @@ -22,7 +22,7 @@ LL| |#[cfg_attr(on, automatically_derived)] LL| |#[cfg_attr(on, coverage(on))] LL| |impl MyTrait for MyStruct { - LL| | fn my_assoc_fn() { + LL| 1| fn my_assoc_fn() { LL| 1| fn inner_fn() { LL| 1| say("in inner fn"); LL| 1| } @@ -36,10 +36,10 @@ LL| 1| say("in closure"); LL| 1| }; LL| | - LL| | closure(); - LL| | inner_fn(); - LL| | inner_fn_on(); - LL| | } + LL| 1| closure(); + LL| 1| inner_fn(); + LL| 1| inner_fn_on(); + LL| 1| } LL| |} LL| | LL| |#[coverage(off)] From 56d9ed74452c8e19c532e98294d5d01925822e94 Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Tue, 22 Jul 2025 14:18:46 +0200 Subject: [PATCH 284/809] Fix nvptx-safe-naming.rs test on LLVM 21 This is now printed on the same line. Use NEXT/SAME depending on the LLVM version. --- tests/assembly-llvm/nvptx-safe-naming.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/assembly-llvm/nvptx-safe-naming.rs b/tests/assembly-llvm/nvptx-safe-naming.rs index d7b46aadd9cc..6a6659a4e304 100644 --- a/tests/assembly-llvm/nvptx-safe-naming.rs +++ b/tests/assembly-llvm/nvptx-safe-naming.rs @@ -1,6 +1,9 @@ //@ assembly-output: ptx-linker //@ compile-flags: --crate-type cdylib -Z unstable-options -Clinker-flavor=llbc //@ only-nvptx64 +//@ revisions: LLVM20 LLVM21 +//@ [LLVM21] min-llvm-version: 21 +//@ [LLVM20] max-llvm-major-version: 20 #![feature(abi_ptx)] #![no_std] @@ -15,7 +18,8 @@ extern crate breakpoint_panic_handler; #[no_mangle] pub unsafe extern "ptx-kernel" fn top_kernel(a: *const u32, b: *mut u32) { // CHECK: call.uni (retval0), - // CHECK-NEXT: [[IMPL_FN]] + // LLVM20-NEXT: [[IMPL_FN]] + // LLVM21-SAME: [[IMPL_FN]] *b = deep::private::MyStruct::new(*a).square(); } From d50b4f10f18b2f84be72692e39dd5de7e8dde949 Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Tue, 29 Jul 2025 12:05:36 +0200 Subject: [PATCH 285/809] Adjust enum-discriminant-eq.rs for LLVM 21 The two xors get folded into the select. --- tests/codegen-llvm/enum/enum-discriminant-eq.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tests/codegen-llvm/enum/enum-discriminant-eq.rs b/tests/codegen-llvm/enum/enum-discriminant-eq.rs index 0494c5f551b3..d599685c2e51 100644 --- a/tests/codegen-llvm/enum/enum-discriminant-eq.rs +++ b/tests/codegen-llvm/enum/enum-discriminant-eq.rs @@ -1,6 +1,9 @@ //@ compile-flags: -Copt-level=3 -Zmerge-functions=disabled //@ min-llvm-version: 20 //@ only-64bit +//@ revisions: LLVM20 LLVM21 +//@ [LLVM21] min-llvm-version: 21 +//@ [LLVM20] max-llvm-major-version: 20 // The `derive(PartialEq)` on enums with field-less variants compares discriminants, // so make sure we emit that in some reasonable way. @@ -137,17 +140,20 @@ pub fn mid_nz32_eq_discr(a: Mid>, b: Mid>) -> bool { pub fn mid_ac_eq_discr(a: Mid, b: Mid) -> bool { // CHECK-LABEL: @mid_ac_eq_discr( - // CHECK: %[[A_REL_DISCR:.+]] = xor i8 %a, -128 + // LLVM20: %[[A_REL_DISCR:.+]] = xor i8 %a, -128 // CHECK: %[[A_IS_NICHE:.+]] = icmp slt i8 %a, 0 // CHECK: %[[A_NOT_HOLE:.+]] = icmp ne i8 %a, -127 // CHECK: tail call void @llvm.assume(i1 %[[A_NOT_HOLE]]) - // CHECK: %[[A_DISCR:.+]] = select i1 %[[A_IS_NICHE]], i8 %[[A_REL_DISCR]], i8 1 + // LLVM20: %[[A_DISCR:.+]] = select i1 %[[A_IS_NICHE]], i8 %[[A_REL_DISCR]], i8 1 - // CHECK: %[[B_REL_DISCR:.+]] = xor i8 %b, -128 + // LLVM20: %[[B_REL_DISCR:.+]] = xor i8 %b, -128 // CHECK: %[[B_IS_NICHE:.+]] = icmp slt i8 %b, 0 // CHECK: %[[B_NOT_HOLE:.+]] = icmp ne i8 %b, -127 // CHECK: tail call void @llvm.assume(i1 %[[B_NOT_HOLE]]) - // CHECK: %[[B_DISCR:.+]] = select i1 %[[B_IS_NICHE]], i8 %[[B_REL_DISCR]], i8 1 + // LLVM20: %[[B_DISCR:.+]] = select i1 %[[B_IS_NICHE]], i8 %[[B_REL_DISCR]], i8 1 + + // LLVM21: %[[A_DISCR:.+]] = select i1 %[[A_IS_NICHE]], i8 %a, i8 -127 + // LLVM21: %[[B_DISCR:.+]] = select i1 %[[B_IS_NICHE]], i8 %b, i8 -127 // CHECK: %[[R:.+]] = icmp eq i8 %[[A_DISCR]], %[[B_DISCR]] // CHECK: ret i1 %[[R]] From 652b9eb98b3dc5be8b2b65954e252e9e272c3447 Mon Sep 17 00:00:00 2001 From: FractalFir Date: Tue, 29 Jul 2025 12:42:48 +0200 Subject: [PATCH 286/809] Add support for the m68k architecture in 'object_architecture' --- compiler/rustc_target/src/spec/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index c64cd9a51b7d..033590e01a67 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -3598,6 +3598,7 @@ impl Target { ), "x86" => (Architecture::I386, None), "s390x" => (Architecture::S390x, None), + "m68k" => (Architecture::M68k, None), "mips" | "mips32r6" => (Architecture::Mips, None), "mips64" | "mips64r6" => ( // While there are currently no builtin targets From de02a32cf1203a9c9efb97a66dac44b7c646bb24 Mon Sep 17 00:00:00 2001 From: Lucas Werkmeister Date: Tue, 29 Jul 2025 13:24:41 +0200 Subject: [PATCH 287/809] Fix typo in `DropGuard` doc --- library/core/src/mem/drop_guard.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/mem/drop_guard.rs b/library/core/src/mem/drop_guard.rs index 47ccb69acc80..fecc94b815e9 100644 --- a/library/core/src/mem/drop_guard.rs +++ b/library/core/src/mem/drop_guard.rs @@ -4,7 +4,7 @@ use crate::ops::{Deref, DerefMut}; /// Wrap a value and run a closure when dropped. /// -/// This is useful for quickly creating desructors inline. +/// This is useful for quickly creating destructors inline. /// /// # Examples /// From ccf660f855eec84f976ed07190d9e8a8b93e2c1f Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Tue, 29 Jul 2025 14:07:27 +0200 Subject: [PATCH 288/809] Relax check lines in x86-return-float.rs On LLVM 21 additional %esp adjustments are generated. Don't use NEXT to allow these. --- tests/assembly-llvm/x86-return-float.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/assembly-llvm/x86-return-float.rs b/tests/assembly-llvm/x86-return-float.rs index 165c11d22801..4db93f68485a 100644 --- a/tests/assembly-llvm/x86-return-float.rs +++ b/tests/assembly-llvm/x86-return-float.rs @@ -334,9 +334,9 @@ pub fn return_f128(x: f128) -> f128 { // linux-NEXT: .cfi_offset // CHECK-NEXT: movl %esp, %ebp // linux-NEXT: .cfi_def_cfa_register - // linux-NEXT: movaps 8(%ebp), %xmm0 - // win-NEXT: movups 8(%ebp), %xmm0 - // CHECK-NEXT: popl %ebp + // linux: movaps 8(%ebp), %xmm0 + // win: movups 8(%ebp), %xmm0 + // CHECK: popl %ebp // linux-NEXT: .cfi_def_cfa // CHECK-NEXT: retl x From 1ceacf55a0e207c08bbedfea422c0842a4983e3d Mon Sep 17 00:00:00 2001 From: WANG Rui Date: Tue, 24 Jun 2025 20:19:10 +0800 Subject: [PATCH 289/809] LoongArch64 LSX fast-path for `str.contains(&str)` Benchmark results with LLVM 21 on LA664: ``` OLD: test bench_is_contained_in ... bench: 43.63 ns/iter (+/- 0.04) NEW: test bench_is_contained_in ... bench: 12.81 ns/iter (+/- 0.01) ``` --- library/core/src/str/pattern.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index bcbbb11c83b2..e116b1383832 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -996,7 +996,10 @@ impl<'b> Pattern for &'b str { return haystack.as_bytes().contains(&self.as_bytes()[0]); } - #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + #[cfg(any( + all(target_arch = "x86_64", target_feature = "sse2"), + all(target_arch = "loongarch64", target_feature = "lsx") + ))] if self.len() <= 32 { if let Some(result) = simd_contains(self, haystack) { return result; @@ -1770,11 +1773,18 @@ impl TwoWayStrategy for RejectAndMatch { /// If we ever ship std with for x86-64-v3 or adapt this for other platforms then wider vectors /// should be evaluated. /// +/// Similarly, on LoongArch the 128-bit LSX vector extension is the baseline, +/// so we also use `u8x16` there. Wider vector widths may be considered +/// for future LoongArch extensions (e.g., LASX). +/// /// For haystacks smaller than vector-size + needle length it falls back to /// a naive O(n*m) search so this implementation should not be called on larger needles. /// /// [0]: http://0x80.pl/articles/simd-strfind.html#sse-avx2 -#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] +#[cfg(any( + all(target_arch = "x86_64", target_feature = "sse2"), + all(target_arch = "loongarch64", target_feature = "lsx") +))] #[inline] fn simd_contains(needle: &str, haystack: &str) -> Option { let needle = needle.as_bytes(); @@ -1906,7 +1916,10 @@ fn simd_contains(needle: &str, haystack: &str) -> Option { /// # Safety /// /// Both slices must have the same length. -#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] // only called on x86 +#[cfg(any( + all(target_arch = "x86_64", target_feature = "sse2"), + all(target_arch = "loongarch64", target_feature = "lsx") +))] #[inline] unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool { debug_assert_eq!(x.len(), y.len()); From c39b4479ce6f33604000b9ffdc91d2e8e115cb41 Mon Sep 17 00:00:00 2001 From: LorrensP-2158466 Date: Mon, 28 Jul 2025 21:21:59 +0200 Subject: [PATCH 290/809] "Cachify" `ExternPreludeEntry.binding` through a `Cell`. --- compiler/rustc_resolve/src/build_reduced_graph.rs | 11 +++++------ compiler/rustc_resolve/src/lib.rs | 12 ++++++------ 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index b15b478a6be9..7912345ec56a 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -984,18 +984,17 @@ 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: None, introduced_by_item: true }); + 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 = Some(imported_binding) + entry.binding.set(Some(imported_binding)); } else if ident.name != kw::Underscore { self.r.dcx().span_delayed_bug( item.span, diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 8115b87dcae0..88dfb50b47dd 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1009,13 +1009,13 @@ impl<'ra> NameBindingData<'ra> { #[derive(Default, Clone)] struct ExternPreludeEntry<'ra> { - binding: Option>, + binding: Cell>>, introduced_by_item: bool, } impl ExternPreludeEntry<'_> { fn is_import(&self) -> bool { - self.binding.is_some_and(|binding| binding.is_import()) + self.binding.get().is_some_and(|binding| binding.is_import()) } } @@ -2006,7 +2006,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { // but not introduce it, as used if they are accessed from lexical scope. if used == Used::Scope { if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) { - if !entry.introduced_by_item && entry.binding == Some(used_binding) { + if !entry.introduced_by_item && entry.binding.get() == Some(used_binding) { return; } } @@ -2170,7 +2170,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { 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 { + Some(if let Some(binding) = entry.binding.get() { if finalize { if !entry.is_import() { self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span); @@ -2195,8 +2195,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { }) }); - if let Some(entry) = self.extern_prelude.get_mut(&norm_ident) { - entry.binding = binding; + if let Some(entry) = self.extern_prelude.get(&norm_ident) { + entry.binding.set(binding); } binding From 75bdbf25e39f073b35eadedcf575affac7762a86 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Thu, 24 Jul 2025 10:19:20 +0000 Subject: [PATCH 291/809] Pick the largest niche even if the largest niche is wrapped around --- compiler/rustc_abi/src/layout.rs | 82 +++++++++++++------ compiler/rustc_abi/src/lib.rs | 13 +++ compiler/rustc_middle/src/ty/layout.rs | 4 +- .../enum-discriminant/wrapping_niche.stderr | 15 +++- .../enums/niche_optimization.rs | 12 +-- 5 files changed, 91 insertions(+), 35 deletions(-) diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 716bb716cdb5..90c63bc9db3c 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeSet; use std::fmt::{self, Write}; use std::ops::{Bound, Deref}; use std::{cmp, iter}; @@ -5,7 +6,7 @@ use std::{cmp, iter}; use rustc_hashes::Hash64; use rustc_index::Idx; use rustc_index::bit_set::BitMatrix; -use tracing::debug; +use tracing::{debug, trace}; use crate::{ AbiAlign, Align, BackendRepr, FieldsShape, HasDataLayout, IndexSlice, IndexVec, Integer, @@ -766,30 +767,63 @@ impl LayoutCalculator { let niche_filling_layout = calculate_niche_filling_layout(); - let (mut min, mut max) = (i128::MAX, i128::MIN); let discr_type = repr.discr_type(); - let bits = Integer::from_attr(dl, discr_type).size().bits(); - for (i, mut val) in discriminants { - if !repr.c() && variants[i].iter().any(|f| f.is_uninhabited()) { - continue; - } - if discr_type.is_signed() { - // sign extend the raw representation to be an i128 - val = (val << (128 - bits)) >> (128 - bits); - } - if val < min { - min = val; - } - if val > max { - max = val; - } - } - // We might have no inhabited variants, so pretend there's at least one. - if (min, max) == (i128::MAX, i128::MIN) { - min = 0; - max = 0; - } - assert!(min <= max, "discriminant range is {min}...{max}"); + let discr_int = Integer::from_attr(dl, discr_type); + let bits = discr_int.size().bits(); + // Because we can only represent one range of valid values, we'll look for the + // largest range of invalid values and pick everything else as the range of valid + // values. + + // First we need to sort the possible discriminant values so that we can look for the largest gap: + let valid_discriminants: BTreeSet = discriminants + .filter(|&(i, _)| repr.c() || variants[i].iter().all(|f| !f.is_uninhabited())) + .map(|(_, val)| { + if discr_type.is_signed() { + // sign extend the raw representation to be an i128 + (val << (128 - bits)) >> (128 - bits) + } else { + val + } + }) + .collect(); + trace!(?valid_discriminants); + let discriminants = valid_discriminants.iter().copied(); + //let next_discriminants = discriminants.clone().cycle().skip(1); + let next_discriminants = + discriminants.clone().chain(valid_discriminants.first().copied()).skip(1); + // Iterate over pairs of each discriminant together with the next one. + // Since they were sorted, we can now compute the niche sizes and pick the largest. + let discriminants = discriminants.zip(next_discriminants); + let largest_niche = discriminants.max_by_key(|&(start, end)| { + trace!(?start, ?end); + // If this is a wraparound range, the niche size is `MAX - abs(diff)`, as the diff between + // the two end points is actually the size of the valid discriminants. + let dist = if start > end { + // Overflow can happen for 128 bit discriminants if `end` is negative. + // But in that case casting to `u128` still gets us the right value, + // as the distance must be positive if the lhs of the subtraction is larger than the rhs. + let dist = start.wrapping_sub(end); + if discr_type.is_signed() { + discr_int.signed_max().wrapping_sub(dist) as u128 + } else { + discr_int.size().unsigned_int_max() - dist as u128 + } + } else { + // Overflow can happen for 128 bit discriminants if `start` is negative. + // But in that case casting to `u128` still gets us the right value, + // as the distance must be positive if the lhs of the subtraction is larger than the rhs. + end.wrapping_sub(start) as u128 + }; + trace!(?dist); + dist + }); + trace!(?largest_niche); + + // `max` is the last valid discriminant before the largest niche + // `min` is the first valid discriminant after the largest niche + let (max, min) = largest_niche + // We might have no inhabited variants, so pretend there's at least one. + .unwrap_or((0, 0)); let (min_ity, signed) = discr_range_of_repr(min, max); //Integer::repr_discr(tcx, ty, &repr, min, max); let mut align = dl.aggregate_align; diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 8e346706877d..14e256b8045d 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1205,6 +1205,19 @@ impl Integer { } } + /// Returns the smallest signed value that can be represented by this Integer. + #[inline] + pub fn signed_min(self) -> i128 { + use Integer::*; + match self { + I8 => i8::MIN as i128, + I16 => i16::MIN as i128, + I32 => i32::MIN as i128, + I64 => i64::MIN as i128, + I128 => i128::MIN, + } + } + /// Finds the smallest Integer type which can represent the signed value. #[inline] pub fn fit_signed(x: i128) -> Integer { diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index a5123576fc64..aed94f9aa04d 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -107,8 +107,8 @@ impl abi::Integer { abi::Integer::I8 }; - // If there are no negative values, we can use the unsigned fit. - if min >= 0 { + // Pick the smallest fit. + if unsigned_fit <= signed_fit { (cmp::max(unsigned_fit, at_least), false) } else { (cmp::max(signed_fit, at_least), true) diff --git a/tests/ui/enum-discriminant/wrapping_niche.stderr b/tests/ui/enum-discriminant/wrapping_niche.stderr index 76cafa43e905..e3e1755e14dd 100644 --- a/tests/ui/enum-discriminant/wrapping_niche.stderr +++ b/tests/ui/enum-discriminant/wrapping_niche.stderr @@ -9,7 +9,7 @@ error: layout_of(UnsignedAroundZero) = Layout { I16, false, ), - valid_range: 0..=65535, + valid_range: (..=1) | (65535..), }, ), fields: Arbitrary { @@ -20,7 +20,16 @@ error: layout_of(UnsignedAroundZero) = Layout { 0, ], }, - largest_niche: None, + largest_niche: Some( + Niche { + offset: Size(0 bytes), + value: Int( + I16, + false, + ), + valid_range: (..=1) | (65535..), + }, + ), uninhabited: false, variants: Multiple { tag: Initialized { @@ -28,7 +37,7 @@ error: layout_of(UnsignedAroundZero) = Layout { I16, false, ), - valid_range: 0..=65535, + valid_range: (..=1) | (65535..), }, tag_encoding: Direct, tag_field: 0, diff --git a/tests/ui/transmutability/enums/niche_optimization.rs b/tests/ui/transmutability/enums/niche_optimization.rs index 2436be500279..316a857662a2 100644 --- a/tests/ui/transmutability/enums/niche_optimization.rs +++ b/tests/ui/transmutability/enums/niche_optimization.rs @@ -75,8 +75,8 @@ fn one_niche() { assert::is_transmutable::(); assert::is_transmutable::(); + assert::is_transmutable::(); assert::is_transmutable::(); - assert::is_transmutable::(); } fn one_niche_alt() { @@ -97,9 +97,9 @@ fn one_niche_alt() { }; assert::is_transmutable::(); - assert::is_transmutable::(); + assert::is_transmutable::(); + assert::is_transmutable::(); assert::is_transmutable::(); - assert::is_transmutable::(); } fn two_niche() { @@ -121,9 +121,9 @@ fn two_niche() { assert::is_transmutable::(); assert::is_transmutable::(); + assert::is_transmutable::(); + assert::is_transmutable::(); assert::is_transmutable::(); - assert::is_transmutable::(); - assert::is_transmutable::(); } fn no_niche() { @@ -142,7 +142,7 @@ fn no_niche() { } const _: () = { - assert!(std::mem::size_of::() == 2); + assert!(std::mem::size_of::() == 1); }; #[repr(C)] From 219bad49461f5c9fc318732a73a05af5d198fed2 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 29 Jul 2025 08:43:10 +0000 Subject: [PATCH 292/809] Reuse `sign_extend` helper --- compiler/rustc_abi/src/layout.rs | 4 ++-- compiler/rustc_middle/src/ty/util.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 90c63bc9db3c..c2405553756b 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -769,7 +769,6 @@ impl LayoutCalculator { let discr_type = repr.discr_type(); let discr_int = Integer::from_attr(dl, discr_type); - let bits = discr_int.size().bits(); // Because we can only represent one range of valid values, we'll look for the // largest range of invalid values and pick everything else as the range of valid // values. @@ -780,7 +779,8 @@ impl LayoutCalculator { .map(|(_, val)| { if discr_type.is_signed() { // sign extend the raw representation to be an i128 - (val << (128 - bits)) >> (128 - bits) + // FIXME: do this at the discriminant iterator creation sites + discr_int.size().sign_extend(val as u128) } else { val } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 174892c6f4d2..a7d07adf78f0 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -32,7 +32,7 @@ use crate::ty::{ #[derive(Copy, Clone, Debug)] pub struct Discr<'tcx> { - /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`). + /// Bit representation of the discriminant (e.g., `-1i8` is `0xFF_u128`). pub val: u128, pub ty: Ty<'tcx>, } From 0b807fc1afafb52a97f596c3ba3d926aabe6a1ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 16:18:52 +0200 Subject: [PATCH 293/809] Update rustc-perf submodule --- src/tools/rustc-perf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rustc-perf b/src/tools/rustc-perf index 6a70166b92a1..dde879cf1087 160000 --- a/src/tools/rustc-perf +++ b/src/tools/rustc-perf @@ -1 +1 @@ -Subproject commit 6a70166b92a1b1560cb3cf056427b011b2a1f2bf +Subproject commit dde879cf1087cb34a32287bd8ccc4d545bb9fee5 From d1a877aac268c6bd6cb66f8c7bc5152a080439a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 16:36:48 +0200 Subject: [PATCH 294/809] Improve tidy error on dependency license exceptions --- src/tools/tidy/src/deps.rs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 8e2a796106f4..b9ad8b1404fc 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -599,7 +599,7 @@ pub fn check(root: &Path, cargo: &Path, bless: bool, bad: &mut bool) { .other_options(vec!["--locked".to_owned()]); let metadata = t!(cmd.exec()); - check_license_exceptions(&metadata, exceptions, bad); + check_license_exceptions(&metadata, workspace, exceptions, bad); if let Some((crates, permitted_deps)) = permitted_deps { check_permitted_dependencies(&metadata, workspace, permitted_deps, crates, bad); } @@ -730,14 +730,19 @@ fn check_runtime_license_exceptions(metadata: &Metadata, bad: &mut bool) { /// Check that all licenses of tool dependencies are in the valid list in `LICENSES`. /// /// Packages listed in `exceptions` are allowed for tools. -fn check_license_exceptions(metadata: &Metadata, exceptions: &[(&str, &str)], bad: &mut bool) { +fn check_license_exceptions( + metadata: &Metadata, + workspace: &str, + exceptions: &[(&str, &str)], + bad: &mut bool, +) { // Validate the EXCEPTIONS list hasn't changed. for (name, license) in exceptions { // Check that the package actually exists. if !metadata.packages.iter().any(|p| *p.name == *name) { tidy_error!( bad, - "could not find exception package `{}`\n\ + "could not find exception package `{}` in workspace `{workspace}`\n\ Remove from EXCEPTIONS list if it is no longer used.", name ); @@ -753,13 +758,15 @@ fn check_license_exceptions(metadata: &Metadata, exceptions: &[(&str, &str)], ba } tidy_error!( bad, - "dependency exception `{}` does not declare a license expression", + "dependency exception `{}` in workspace `{workspace}` does not declare a license expression", pkg.id ); } Some(pkg_license) => { if pkg_license.as_str() != *license { - println!("dependency exception `{name}` license has changed"); + println!( + "dependency exception `{name}` license in workspace `{workspace}` has changed" + ); println!(" previously `{license}` now `{pkg_license}`"); println!(" update EXCEPTIONS for the new license"); *bad = true; @@ -783,12 +790,21 @@ fn check_license_exceptions(metadata: &Metadata, exceptions: &[(&str, &str)], ba let license = match &pkg.license { Some(license) => license, None => { - tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id); + tidy_error!( + bad, + "dependency `{}` in workspace `{workspace}` does not define a license expression", + pkg.id + ); continue; } }; if !LICENSES.contains(&license.as_str()) { - tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id); + tidy_error!( + bad, + "invalid license `{}` for package `{}` in workspace `{workspace}`", + license, + pkg.id + ); } } } From ab4024eb31bf341cb92e1acb1db78e6cab6c434a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 16:41:10 +0200 Subject: [PATCH 295/809] Update license exceptions for rustc-perf --- src/tools/tidy/src/deps.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index b9ad8b1404fc..1ff0349cc1eb 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -167,7 +167,7 @@ const EXCEPTIONS_RUSTC_PERF: ExceptionList = &[ ("brotli-decompressor", "BSD-3-Clause/MIT"), ("encoding_rs", "(Apache-2.0 OR MIT) AND BSD-3-Clause"), ("inferno", "CDDL-1.0"), - ("ring", NON_STANDARD_LICENSE), // see EXCEPTIONS_NON_STANDARD_LICENSE_DEPS for more. + ("option-ext", "MPL-2.0"), ("ryu", "Apache-2.0 OR BSL-1.0"), ("snap", "BSD-3-Clause"), ("subtle", "BSD-3-Clause"), From b60026ab4277a8b37aa0a812baf977b3766520aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Tue, 29 Jul 2025 16:41:44 +0200 Subject: [PATCH 296/809] Remove no longer needed handling of nonstandard licenses --- src/tools/tidy/src/deps.rs | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 1ff0349cc1eb..858b058cb7d0 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -226,20 +226,6 @@ const EXCEPTIONS_UEFI_QEMU_TEST: ExceptionList = &[ ("r-efi", "MIT OR Apache-2.0 OR LGPL-2.1-or-later"), // LGPL is not acceptable, but we use it under MIT OR Apache-2.0 ]; -/// Placeholder for non-standard license file. -const NON_STANDARD_LICENSE: &str = "NON_STANDARD_LICENSE"; - -/// These dependencies have non-standard licenses but are genenrally permitted. -const EXCEPTIONS_NON_STANDARD_LICENSE_DEPS: &[&str] = &[ - // `ring` is included because it is an optional dependency of `hyper`, - // which is a training data in rustc-perf for optimized build. - // The license of it is generally `ISC AND MIT AND OpenSSL`, - // though the `package.license` field is not set. - // - // See https://github.com/briansmith/ring/issues/902 - "ring", -]; - const PERMITTED_DEPS_LOCATION: &str = concat!(file!(), ":", line!()); /// Crates rustc is allowed to depend on. Avoid adding to the list if possible. @@ -751,11 +737,6 @@ fn check_license_exceptions( for pkg in metadata.packages.iter().filter(|p| *p.name == *name) { match &pkg.license { None => { - if *license == NON_STANDARD_LICENSE - && EXCEPTIONS_NON_STANDARD_LICENSE_DEPS.contains(&pkg.name.as_str()) - { - continue; - } tidy_error!( bad, "dependency exception `{}` in workspace `{workspace}` does not declare a license expression", From 77fc593a6a372d6d8adc3f1b96416f93c3d1aa8d Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 28 Jul 2025 07:22:56 -0700 Subject: [PATCH 297/809] Update wasi-sdk to 27.0 in CI This updates the wasi-sdk used in CI to build release binaries and run CI with. No major motivation beyond keeping things up-to-date and following the development of wasi-sdk. --- src/ci/docker/host-x86_64/dist-various-2/Dockerfile | 4 ++-- src/ci/docker/host-x86_64/test-various/Dockerfile | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ci/docker/host-x86_64/dist-various-2/Dockerfile b/src/ci/docker/host-x86_64/dist-various-2/Dockerfile index e1d83d360872..0855ea222a36 100644 --- a/src/ci/docker/host-x86_64/dist-various-2/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-various-2/Dockerfile @@ -81,9 +81,9 @@ RUN /tmp/build-fuchsia-toolchain.sh COPY host-x86_64/dist-various-2/build-x86_64-fortanix-unknown-sgx-toolchain.sh /tmp/ RUN /tmp/build-x86_64-fortanix-unknown-sgx-toolchain.sh -RUN curl -L https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-25/wasi-sdk-25.0-x86_64-linux.tar.gz | \ +RUN curl -L https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-27/wasi-sdk-27.0-x86_64-linux.tar.gz | \ tar -xz -ENV WASI_SDK_PATH=/tmp/wasi-sdk-25.0-x86_64-linux +ENV WASI_SDK_PATH=/tmp/wasi-sdk-27.0-x86_64-linux COPY scripts/freebsd-toolchain.sh /tmp/ RUN /tmp/freebsd-toolchain.sh i686 diff --git a/src/ci/docker/host-x86_64/test-various/Dockerfile b/src/ci/docker/host-x86_64/test-various/Dockerfile index 662a26400ce9..82a820c859dc 100644 --- a/src/ci/docker/host-x86_64/test-various/Dockerfile +++ b/src/ci/docker/host-x86_64/test-various/Dockerfile @@ -40,9 +40,9 @@ WORKDIR / COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh -RUN curl -L https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-25/wasi-sdk-25.0-x86_64-linux.tar.gz | \ +RUN curl -L https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-27/wasi-sdk-27.0-x86_64-linux.tar.gz | \ tar -xz -ENV WASI_SDK_PATH=/wasi-sdk-25.0-x86_64-linux +ENV WASI_SDK_PATH=/wasi-sdk-27.0-x86_64-linux ENV RUST_CONFIGURE_ARGS \ --musl-root-x86_64=/usr/local/x86_64-linux-musl \ From 307fd41123bd9ce4ff9e4e9767f3f7771d91d789 Mon Sep 17 00:00:00 2001 From: Martin Nordholts Date: Wed, 16 Jul 2025 19:42:23 +0200 Subject: [PATCH 298/809] tests: Test line number in debuginfo for diverging function calls --- .../diverging-function-call-debuginfo.rs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 tests/codegen-llvm/diverging-function-call-debuginfo.rs diff --git a/tests/codegen-llvm/diverging-function-call-debuginfo.rs b/tests/codegen-llvm/diverging-function-call-debuginfo.rs new file mode 100644 index 000000000000..1a80fe1643de --- /dev/null +++ b/tests/codegen-llvm/diverging-function-call-debuginfo.rs @@ -0,0 +1,38 @@ +/// Make sure that line debuginfo is correct for diverging calls under certain +/// conditions. In particular we want to ensure that the line number is never +/// 0, but we check the absence of 0 by looking for the expected exact line +/// numbers. Regression test for . + +//@ compile-flags: -g -Clto -Copt-level=0 +//@ no-prefer-dynamic + +// First find the scope of both diverge() calls, namely this main() function. +// CHECK-DAG: [[MAIN_SCOPE:![0-9]+]] = distinct !DISubprogram(name: "main", linkageName: {{.*}}diverging_function_call_debuginfo{{.*}}main{{.*}} +fn main() { + if True == False { + // unreachable + // Then find the DILocation with the correct line number for this call ... + // CHECK-DAG: [[UNREACHABLE_CALL_DBG:![0-9]+]] = !DILocation(line: [[@LINE+1]], {{.*}}scope: [[MAIN_SCOPE]] + diverge(); + } + + // ... and this call. + // CHECK-DAG: [[LAST_CALL_DBG:![0-9]+]] = !DILocation(line: [[@LINE+1]], {{.*}}scope: [[MAIN_SCOPE]] + diverge(); +} + +#[derive(PartialEq)] +pub enum MyBool { + True, + False, +} + +use MyBool::*; + +fn diverge() -> ! { + panic!(); +} + +// Finally make sure both DILocations belong to each the respective diverge() call. +// CHECK-DAG: call void {{.*}}diverging_function_call_debuginfo{{.*}}diverge{{.*}} !dbg [[LAST_CALL_DBG]] +// CHECK-DAG: call void {{.*}}diverging_function_call_debuginfo{{.*}}diverge{{.*}} !dbg [[UNREACHABLE_CALL_DBG]] From cffde732ceecd1bcb333d34fe7a9c9caa4d9a9fa Mon Sep 17 00:00:00 2001 From: Daniel Paoliello Date: Wed, 16 Jul 2025 16:16:24 -0700 Subject: [PATCH 299/809] Verify llvm-needs-components are not empty and match the --target value --- .../rustc-dev-guide/src/tests/directives.md | 13 +- src/tools/compiletest/src/directives.rs | 184 ++++++++++++++---- .../compiletest/src/directives/auxiliary.rs | 41 +++- src/tools/compiletest/src/runtest/debugger.rs | 8 +- src/tools/tidy/src/style.rs | 7 +- src/tools/tidy/src/target_specific_tests.rs | 61 +++++- tests/codegen-llvm/abi-efiapi.rs | 10 +- tests/codegen-llvm/cast-target-abi.rs | 2 +- tests/codegen-llvm/cf-protection.rs | 2 +- tests/codegen-llvm/codemodels.rs | 2 +- tests/codegen-llvm/ehcontguard_disabled.rs | 2 - .../codegen-llvm/naked-fn/naked-functions.rs | 2 +- .../address-sanitizer-globals-tracking.rs | 6 +- ...it-kcfi-operand-bundle-attr-no-sanitize.rs | 2 +- ...rand-bundle-itanium-cxx-abi-generalized.rs | 2 +- ...-itanium-cxx-abi-normalized-generalized.rs | 2 +- ...erand-bundle-itanium-cxx-abi-normalized.rs | 2 +- ...mit-kcfi-operand-bundle-itanium-cxx-abi.rs | 2 +- .../kcfi/emit-kcfi-operand-bundle.rs | 2 +- .../kcfi/emit-type-metadata-trait-objects.rs | 2 +- .../sanitizer/memory-track-origins.rs | 2 +- tests/codegen-llvm/ub-checks.rs | 2 +- tests/debuginfo/unsized.rs | 1 - tests/ui/errors/remap-path-prefix-sysroot.rs | 2 +- tests/ui/errors/wrong-target-spec.rs | 1 + tests/ui/linkage-attr/unstable-flavor.rs | 4 +- tests/ui/target_modifiers/defaults_check.rs | 2 +- .../target_modifiers/incompatible_fixedx18.rs | 2 +- .../target_modifiers/incompatible_regparm.rs | 2 +- tests/ui/target_modifiers/no_value_bool.rs | 2 +- 30 files changed, 277 insertions(+), 97 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..89e4d3e9b58e 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -293,8 +293,6 @@ See [Pretty-printer](compiletest.md#pretty-printer-tests). - `no-auto-check-cfg` — disable auto check-cfg (only for `--check-cfg` tests) - [`revisions`](compiletest.md#revisions) — compile multiple times -- [`unused-revision-names`](compiletest.md#ignoring-unused-revision-names) - - suppress tidy checks for mentioning unknown revision names -[`forbid-output`](compiletest.md#incremental-tests) — incremental cfail rejects output pattern - [`should-ice`](compiletest.md#incremental-tests) — incremental cfail should @@ -315,6 +313,17 @@ test suites that use those tools: - `llvm-cov-flags` adds extra flags when running LLVM's `llvm-cov` tool. - Used by [coverage tests](compiletest.md#coverage-tests) in `coverage-run` mode. +### Tidy specific directives + +The following directives control how the [tidy script](../conventions.md#formatting) +verifies tests. + +- `ignore-tidy-target-specific-tests` disables checking that the appropriate + LLVM component is required (via a `needs-llvm-components` directive) when a + test is compiled for a specific target (via the `--target` flag in a + `compile-flag` directive). +- [`unused-revision-names`](compiletest.md#ignoring-unused-revision-names) - + suppress tidy checks for mentioning unknown revision names. ## Substitutions diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index a1f76a075562..69ff846330ed 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -59,9 +59,9 @@ impl EarlyProps { &mut poisoned, testfile, rdr, - &mut |DirectiveLine { raw_directive: ln, .. }| { - parse_and_update_aux(config, ln, &mut props.aux); - config.parse_and_update_revisions(testfile, ln, &mut props.revisions); + &mut |DirectiveLine { line_number, raw_directive: ln, .. }| { + parse_and_update_aux(config, ln, testfile, line_number, &mut props.aux); + config.parse_and_update_revisions(testfile, line_number, ln, &mut props.revisions); }, ); @@ -351,7 +351,7 @@ impl TestProps { &mut poisoned, testfile, file, - &mut |directive @ DirectiveLine { raw_directive: ln, .. }| { + &mut |directive @ DirectiveLine { line_number, raw_directive: ln, .. }| { if !directive.applies_to_test_revision(test_revision) { return; } @@ -361,17 +361,28 @@ impl TestProps { config.push_name_value_directive( ln, ERROR_PATTERN, + testfile, + line_number, &mut self.error_patterns, |r| r, ); config.push_name_value_directive( ln, REGEX_ERROR_PATTERN, + testfile, + line_number, &mut self.regex_error_patterns, |r| r, ); - config.push_name_value_directive(ln, DOC_FLAGS, &mut self.doc_flags, |r| r); + config.push_name_value_directive( + ln, + DOC_FLAGS, + testfile, + line_number, + &mut self.doc_flags, + |r| r, + ); fn split_flags(flags: &str) -> Vec { // Individual flags can be single-quoted to preserve spaces; see @@ -386,7 +397,9 @@ impl TestProps { .collect::>() } - if let Some(flags) = config.parse_name_value_directive(ln, COMPILE_FLAGS) { + if let Some(flags) = + config.parse_name_value_directive(ln, COMPILE_FLAGS, testfile, line_number) + { let flags = split_flags(&flags); for flag in &flags { if flag == "--edition" || flag.starts_with("--edition=") { @@ -395,25 +408,40 @@ impl TestProps { } self.compile_flags.extend(flags); } - if config.parse_name_value_directive(ln, INCORRECT_COMPILER_FLAGS).is_some() { + if config + .parse_name_value_directive( + ln, + INCORRECT_COMPILER_FLAGS, + testfile, + line_number, + ) + .is_some() + { panic!("`compiler-flags` directive should be spelled `compile-flags`"); } - if let Some(edition) = config.parse_edition(ln) { + if let Some(edition) = config.parse_edition(ln, testfile, line_number) { // The edition is added at the start, since flags from //@compile-flags must // be passed to rustc last. self.compile_flags.insert(0, format!("--edition={}", edition.trim())); has_edition = true; } - config.parse_and_update_revisions(testfile, ln, &mut self.revisions); + config.parse_and_update_revisions( + testfile, + line_number, + ln, + &mut self.revisions, + ); - if let Some(flags) = config.parse_name_value_directive(ln, RUN_FLAGS) { + if let Some(flags) = + config.parse_name_value_directive(ln, RUN_FLAGS, testfile, line_number) + { self.run_flags.extend(split_flags(&flags)); } if self.pp_exact.is_none() { - self.pp_exact = config.parse_pp_exact(ln, testfile); + self.pp_exact = config.parse_pp_exact(ln, testfile, line_number); } config.set_name_directive(ln, SHOULD_ICE, &mut self.should_ice); @@ -435,7 +463,9 @@ impl TestProps { ); config.set_name_directive(ln, NO_PREFER_DYNAMIC, &mut self.no_prefer_dynamic); - if let Some(m) = config.parse_name_value_directive(ln, PRETTY_MODE) { + if let Some(m) = + config.parse_name_value_directive(ln, PRETTY_MODE, testfile, line_number) + { self.pretty_mode = m; } @@ -446,35 +476,45 @@ impl TestProps { ); // Call a helper method to deal with aux-related directives. - parse_and_update_aux(config, ln, &mut self.aux); + parse_and_update_aux(config, ln, testfile, line_number, &mut self.aux); config.push_name_value_directive( ln, EXEC_ENV, + testfile, + line_number, &mut self.exec_env, Config::parse_env, ); config.push_name_value_directive( ln, UNSET_EXEC_ENV, + testfile, + line_number, &mut self.unset_exec_env, |r| r.trim().to_owned(), ); config.push_name_value_directive( ln, RUSTC_ENV, + testfile, + line_number, &mut self.rustc_env, Config::parse_env, ); config.push_name_value_directive( ln, UNSET_RUSTC_ENV, + testfile, + line_number, &mut self.unset_rustc_env, |r| r.trim().to_owned(), ); config.push_name_value_directive( ln, FORBID_OUTPUT, + testfile, + line_number, &mut self.forbid_output, |r| r, ); @@ -510,7 +550,7 @@ impl TestProps { } if let Some(code) = config - .parse_name_value_directive(ln, FAILURE_STATUS) + .parse_name_value_directive(ln, FAILURE_STATUS, testfile, line_number) .and_then(|code| code.trim().parse::().ok()) { self.failure_status = Some(code); @@ -531,6 +571,8 @@ impl TestProps { config.set_name_value_directive( ln, ASSEMBLY_OUTPUT, + testfile, + line_number, &mut self.assembly_output, |r| r.trim().to_string(), ); @@ -543,7 +585,9 @@ impl TestProps { // Unlike the other `name_value_directive`s this needs to be handled manually, // because it sets a `bool` flag. - if let Some(known_bug) = config.parse_name_value_directive(ln, KNOWN_BUG) { + if let Some(known_bug) = + config.parse_name_value_directive(ln, KNOWN_BUG, testfile, line_number) + { let known_bug = known_bug.trim(); if known_bug == "unknown" || known_bug.split(',').all(|issue_ref| { @@ -571,16 +615,25 @@ impl TestProps { config.set_name_value_directive( ln, TEST_MIR_PASS, + testfile, + line_number, &mut self.mir_unit_test, |s| s.trim().to_string(), ); config.set_name_directive(ln, REMAP_SRC_BASE, &mut self.remap_src_base); - if let Some(flags) = config.parse_name_value_directive(ln, LLVM_COV_FLAGS) { + if let Some(flags) = + config.parse_name_value_directive(ln, LLVM_COV_FLAGS, testfile, line_number) + { self.llvm_cov_flags.extend(split_flags(&flags)); } - if let Some(flags) = config.parse_name_value_directive(ln, FILECHECK_FLAGS) { + if let Some(flags) = config.parse_name_value_directive( + ln, + FILECHECK_FLAGS, + testfile, + line_number, + ) { self.filecheck_flags.extend(split_flags(&flags)); } @@ -588,9 +641,12 @@ impl TestProps { self.update_add_core_stubs(ln, config); - if let Some(err_kind) = - config.parse_name_value_directive(ln, DONT_REQUIRE_ANNOTATIONS) - { + if let Some(err_kind) = config.parse_name_value_directive( + ln, + DONT_REQUIRE_ANNOTATIONS, + testfile, + line_number, + ) { self.dont_require_annotations .insert(ErrorKind::expect_from_user_str(err_kind.trim())); } @@ -1206,6 +1262,7 @@ impl Config { fn parse_and_update_revisions( &self, testfile: &Utf8Path, + line_number: usize, line: &str, existing: &mut Vec, ) { @@ -1219,7 +1276,8 @@ impl Config { const FILECHECK_FORBIDDEN_REVISION_NAMES: [&str; 9] = ["CHECK", "COM", "NEXT", "SAME", "EMPTY", "NOT", "COUNT", "DAG", "LABEL"]; - if let Some(raw) = self.parse_name_value_directive(line, "revisions") { + if let Some(raw) = self.parse_name_value_directive(line, "revisions", testfile, line_number) + { if self.mode == TestMode::RunMake { panic!("`run-make` tests do not support revisions: {}", testfile); } @@ -1264,8 +1322,13 @@ impl Config { (name.to_owned(), value.to_owned()) } - fn parse_pp_exact(&self, line: &str, testfile: &Utf8Path) -> Option { - if let Some(s) = self.parse_name_value_directive(line, "pp-exact") { + fn parse_pp_exact( + &self, + line: &str, + testfile: &Utf8Path, + line_number: usize, + ) -> Option { + if let Some(s) = self.parse_name_value_directive(line, "pp-exact", testfile, line_number) { Some(Utf8PathBuf::from(&s)) } else if self.parse_name_directive(line, "pp-exact") { testfile.file_name().map(Utf8PathBuf::from) @@ -1306,19 +1369,31 @@ impl Config { line.starts_with("no-") && self.parse_name_directive(&line[3..], directive) } - pub fn parse_name_value_directive(&self, line: &str, directive: &str) -> Option { + pub fn parse_name_value_directive( + &self, + line: &str, + directive: &str, + testfile: &Utf8Path, + line_number: usize, + ) -> Option { let colon = directive.len(); if line.starts_with(directive) && line.as_bytes().get(colon) == Some(&b':') { let value = line[(colon + 1)..].to_owned(); debug!("{}: {}", directive, value); - Some(expand_variables(value, self)) + let value = expand_variables(value, self); + if value.is_empty() { + error!("{testfile}:{line_number}: empty value for directive `{directive}`"); + help!("expected syntax is: `{directive}: value`"); + panic!("empty directive value detected"); + } + Some(value) } else { None } } - fn parse_edition(&self, line: &str) -> Option { - self.parse_name_value_directive(line, "edition") + fn parse_edition(&self, line: &str, testfile: &Utf8Path, line_number: usize) -> Option { + self.parse_name_value_directive(line, "edition", testfile, line_number) } fn set_name_directive(&self, line: &str, directive: &str, value: &mut bool) { @@ -1340,11 +1415,14 @@ impl Config { &self, line: &str, directive: &str, + testfile: &Utf8Path, + line_number: usize, value: &mut Option, parse: impl FnOnce(String) -> T, ) { if value.is_none() { - *value = self.parse_name_value_directive(line, directive).map(parse); + *value = + self.parse_name_value_directive(line, directive, testfile, line_number).map(parse); } } @@ -1352,10 +1430,14 @@ impl Config { &self, line: &str, directive: &str, + testfile: &Utf8Path, + line_number: usize, values: &mut Vec, parse: impl FnOnce(String) -> T, ) { - if let Some(value) = self.parse_name_value_directive(line, directive).map(parse) { + if let Some(value) = + self.parse_name_value_directive(line, directive, testfile, line_number).map(parse) + { values.push(value); } } @@ -1672,9 +1754,9 @@ pub(crate) fn make_test_description( decision!(cfg::handle_ignore(config, ln)); decision!(cfg::handle_only(config, ln)); decision!(needs::handle_needs(&cache.needs, config, ln)); - decision!(ignore_llvm(config, path, ln)); - decision!(ignore_backends(config, path, ln)); - decision!(needs_backends(config, path, ln)); + decision!(ignore_llvm(config, path, ln, line_number)); + decision!(ignore_backends(config, path, ln, line_number)); + decision!(needs_backends(config, path, ln, line_number)); decision!(ignore_cdb(config, ln)); decision!(ignore_gdb(config, ln)); decision!(ignore_lldb(config, ln)); @@ -1801,8 +1883,15 @@ fn ignore_lldb(config: &Config, line: &str) -> IgnoreDecision { IgnoreDecision::Continue } -fn ignore_backends(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { - if let Some(backends_to_ignore) = config.parse_name_value_directive(line, "ignore-backends") { +fn ignore_backends( + config: &Config, + path: &Utf8Path, + line: &str, + line_number: usize, +) -> IgnoreDecision { + if let Some(backends_to_ignore) = + config.parse_name_value_directive(line, "ignore-backends", path, line_number) + { for backend in backends_to_ignore.split_whitespace().map(|backend| { match CodegenBackend::try_from(backend) { Ok(backend) => backend, @@ -1821,8 +1910,15 @@ fn ignore_backends(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecisi IgnoreDecision::Continue } -fn needs_backends(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { - if let Some(needed_backends) = config.parse_name_value_directive(line, "needs-backends") { +fn needs_backends( + config: &Config, + path: &Utf8Path, + line: &str, + line_number: usize, +) -> IgnoreDecision { + if let Some(needed_backends) = + config.parse_name_value_directive(line, "needs-backends", path, line_number) + { if !needed_backends .split_whitespace() .map(|backend| match CodegenBackend::try_from(backend) { @@ -1844,9 +1940,9 @@ fn needs_backends(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecisio IgnoreDecision::Continue } -fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { +fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str, line_number: usize) -> IgnoreDecision { if let Some(needed_components) = - config.parse_name_value_directive(line, "needs-llvm-components") + config.parse_name_value_directive(line, "needs-llvm-components", path, line_number) { let components: HashSet<_> = config.llvm_components.split_whitespace().collect(); if let Some(missing_component) = needed_components @@ -1867,7 +1963,9 @@ fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { if let Some(actual_version) = &config.llvm_version { // Note that these `min` versions will check for not just major versions. - if let Some(version_string) = config.parse_name_value_directive(line, "min-llvm-version") { + if let Some(version_string) = + config.parse_name_value_directive(line, "min-llvm-version", path, line_number) + { let min_version = extract_llvm_version(&version_string); // Ignore if actual version is smaller than the minimum required version. if *actual_version < min_version { @@ -1878,7 +1976,7 @@ fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { }; } } else if let Some(version_string) = - config.parse_name_value_directive(line, "max-llvm-major-version") + config.parse_name_value_directive(line, "max-llvm-major-version", path, line_number) { let max_version = extract_llvm_version(&version_string); // Ignore if actual major version is larger than the maximum required major version. @@ -1892,7 +1990,7 @@ fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { }; } } else if let Some(version_string) = - config.parse_name_value_directive(line, "min-system-llvm-version") + config.parse_name_value_directive(line, "min-system-llvm-version", path, line_number) { let min_version = extract_llvm_version(&version_string); // Ignore if using system LLVM and actual version @@ -1905,7 +2003,7 @@ fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { }; } } else if let Some(version_range) = - config.parse_name_value_directive(line, "ignore-llvm-version") + config.parse_name_value_directive(line, "ignore-llvm-version", path, line_number) { // Syntax is: "ignore-llvm-version: [- ]" let (v_min, v_max) = @@ -1931,7 +2029,7 @@ fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { } } } else if let Some(version_string) = - config.parse_name_value_directive(line, "exact-llvm-major-version") + config.parse_name_value_directive(line, "exact-llvm-major-version", path, line_number) { // Syntax is "exact-llvm-major-version: " let version = extract_llvm_version(&version_string); diff --git a/src/tools/compiletest/src/directives/auxiliary.rs b/src/tools/compiletest/src/directives/auxiliary.rs index cdb75f6ffa90..7c1ed2e70062 100644 --- a/src/tools/compiletest/src/directives/auxiliary.rs +++ b/src/tools/compiletest/src/directives/auxiliary.rs @@ -3,6 +3,8 @@ use std::iter; +use camino::Utf8Path; + use super::directives::{AUX_BIN, AUX_BUILD, AUX_CODEGEN_BACKEND, AUX_CRATE, PROC_MACRO}; use crate::common::Config; @@ -41,17 +43,42 @@ impl AuxProps { /// If the given test directive line contains an `aux-*` directive, parse it /// and update [`AuxProps`] accordingly. -pub(super) fn parse_and_update_aux(config: &Config, ln: &str, aux: &mut AuxProps) { +pub(super) fn parse_and_update_aux( + config: &Config, + ln: &str, + testfile: &Utf8Path, + line_number: usize, + aux: &mut AuxProps, +) { if !(ln.starts_with("aux-") || ln.starts_with("proc-macro")) { return; } - config.push_name_value_directive(ln, AUX_BUILD, &mut aux.builds, |r| r.trim().to_string()); - config.push_name_value_directive(ln, AUX_BIN, &mut aux.bins, |r| r.trim().to_string()); - config.push_name_value_directive(ln, AUX_CRATE, &mut aux.crates, parse_aux_crate); - config - .push_name_value_directive(ln, PROC_MACRO, &mut aux.proc_macros, |r| r.trim().to_string()); - if let Some(r) = config.parse_name_value_directive(ln, AUX_CODEGEN_BACKEND) { + config.push_name_value_directive(ln, AUX_BUILD, testfile, line_number, &mut aux.builds, |r| { + r.trim().to_string() + }); + config.push_name_value_directive(ln, AUX_BIN, testfile, line_number, &mut aux.bins, |r| { + r.trim().to_string() + }); + config.push_name_value_directive( + ln, + AUX_CRATE, + testfile, + line_number, + &mut aux.crates, + parse_aux_crate, + ); + config.push_name_value_directive( + ln, + PROC_MACRO, + testfile, + line_number, + &mut aux.proc_macros, + |r| r.trim().to_string(), + ); + if let Some(r) = + config.parse_name_value_directive(ln, AUX_CODEGEN_BACKEND, testfile, line_number) + { aux.codegen_backend = Some(r.trim().to_owned()); } } diff --git a/src/tools/compiletest/src/runtest/debugger.rs b/src/tools/compiletest/src/runtest/debugger.rs index a4103c5b4a9a..ba824124e875 100644 --- a/src/tools/compiletest/src/runtest/debugger.rs +++ b/src/tools/compiletest/src/runtest/debugger.rs @@ -47,10 +47,14 @@ impl DebuggerCommands { continue; }; - if let Some(command) = config.parse_name_value_directive(&line, &command_directive) { + if let Some(command) = + config.parse_name_value_directive(&line, &command_directive, file, line_no) + { commands.push(command); } - if let Some(pattern) = config.parse_name_value_directive(&line, &check_directive) { + if let Some(pattern) = + config.parse_name_value_directive(&line, &check_directive, file, line_no) + { check_lines.push((line_no, pattern)); } } diff --git a/src/tools/tidy/src/style.rs b/src/tools/tidy/src/style.rs index 35ed61eacc73..fca097c091b7 100644 --- a/src/tools/tidy/src/style.rs +++ b/src/tools/tidy/src/style.rs @@ -519,8 +519,11 @@ pub fn check(path: &Path, bad: &mut bool) { .any(|directive| matches!(directive, Directive::Ignore(_))); let has_alphabetical_directive = line.contains("tidy-alphabetical-start") || line.contains("tidy-alphabetical-end"); - let has_recognized_directive = - has_recognized_ignore_directive || has_alphabetical_directive; + let has_other_tidy_ignore_directive = + line.contains("ignore-tidy-target-specific-tests"); + let has_recognized_directive = has_recognized_ignore_directive + || has_alphabetical_directive + || has_other_tidy_ignore_directive; if contains_potential_directive && (!has_recognized_directive) { err("Unrecognized tidy directive") } diff --git a/src/tools/tidy/src/target_specific_tests.rs b/src/tools/tidy/src/target_specific_tests.rs index f4a6783abb67..b2d5f259eb2d 100644 --- a/src/tools/tidy/src/target_specific_tests.rs +++ b/src/tools/tidy/src/target_specific_tests.rs @@ -12,12 +12,16 @@ const COMPILE_FLAGS_HEADER: &str = "compile-flags:"; #[derive(Default, Debug)] struct RevisionInfo<'a> { - target_arch: Option<&'a str>, + target_arch: Option>, llvm_components: Option>, } pub fn check(tests_path: &Path, bad: &mut bool) { crate::walk::walk(tests_path, |path, _is_dir| filter_not_rust(path), &mut |entry, content| { + if content.contains("// ignore-tidy-target-specific-tests") { + return; + } + let file = entry.path().display(); let mut header_map = BTreeMap::new(); iter_header(content, &mut |HeaderLine { revision, directive, .. }| { @@ -34,10 +38,11 @@ pub fn check(tests_path: &Path, bad: &mut bool) { && let Some((_, v)) = compile_flags.split_once("--target") { let v = v.trim_start_matches([' ', '=']); - let v = if v == "{{target}}" { Some((v, v)) } else { v.split_once("-") }; - if let Some((arch, _)) = v { - let info = header_map.entry(revision).or_insert(RevisionInfo::default()); - info.target_arch.replace(arch); + let info = header_map.entry(revision).or_insert(RevisionInfo::default()); + if v.starts_with("{{") { + info.target_arch.replace(None); + } else if let Some((arch, _)) = v.split_once("-") { + info.target_arch.replace(Some(arch)); } else { eprintln!("{file}: seems to have a malformed --target value"); *bad = true; @@ -54,9 +59,11 @@ pub fn check(tests_path: &Path, bad: &mut bool) { let rev = rev.unwrap_or("[unspecified]"); match (target_arch, llvm_components) { (None, None) => {} - (Some(_), None) => { + (Some(target_arch), None) => { + let llvm_component = + target_arch.map_or_else(|| "".to_string(), arch_to_llvm_component); eprintln!( - "{file}: revision {rev} should specify `{LLVM_COMPONENTS_HEADER}` as it has `--target` set" + "{file}: revision {rev} should specify `{LLVM_COMPONENTS_HEADER} {llvm_component}` as it has `--target` set" ); *bad = true; } @@ -66,11 +73,45 @@ pub fn check(tests_path: &Path, bad: &mut bool) { ); *bad = true; } - (Some(_), Some(_)) => { - // FIXME: check specified components against the target architectures we - // gathered. + (Some(target_arch), Some(llvm_components)) => { + if let Some(target_arch) = target_arch { + let llvm_component = arch_to_llvm_component(target_arch); + if !llvm_components.contains(&llvm_component.as_str()) { + eprintln!( + "{file}: revision {rev} should specify `{LLVM_COMPONENTS_HEADER} {llvm_component}` as it has `--target` set" + ); + *bad = true; + } + } } } } }); } + +fn arch_to_llvm_component(arch: &str) -> String { + // NOTE: This is an *approximate* mapping of Rust's `--target` architecture to LLVM component + // names. It is not intended to be an authoritative source, but rather a best-effort that's good + // enough for the purpose of this tidy check. + match arch { + "amdgcn" => "amdgpu".into(), + "aarch64_be" | "arm64_32" | "arm64e" | "arm64ec" => "aarch64".into(), + "i386" | "i586" | "i686" | "x86" | "x86_64" | "x86_64h" => "x86".into(), + "loongarch32" | "loongarch64" => "loongarch".into(), + "nvptx64" => "nvptx".into(), + "s390x" => "systemz".into(), + "sparc64" | "sparcv9" => "sparc".into(), + "wasm32" | "wasm32v1" | "wasm64" => "webassembly".into(), + _ if arch.starts_with("armeb") + || arch.starts_with("armv") + || arch.starts_with("thumbv") => + { + "arm".into() + } + _ if arch.starts_with("bpfe") => "bpf".into(), + _ if arch.starts_with("mips") => "mips".into(), + _ if arch.starts_with("powerpc") => "powerpc".into(), + _ if arch.starts_with("riscv") => "riscv".into(), + _ => arch.to_ascii_lowercase(), + } +} diff --git a/tests/codegen-llvm/abi-efiapi.rs b/tests/codegen-llvm/abi-efiapi.rs index 1736f0daf0fa..4cd645101a8b 100644 --- a/tests/codegen-llvm/abi-efiapi.rs +++ b/tests/codegen-llvm/abi-efiapi.rs @@ -3,15 +3,15 @@ //@ add-core-stubs //@ revisions:x86_64 i686 aarch64 arm riscv //@[x86_64] compile-flags: --target x86_64-unknown-uefi -//@[x86_64] needs-llvm-components: aarch64 arm riscv +//@[x86_64] needs-llvm-components: x86 //@[i686] compile-flags: --target i686-unknown-linux-musl -//@[i686] needs-llvm-components: aarch64 arm riscv +//@[i686] needs-llvm-components: x86 //@[aarch64] compile-flags: --target aarch64-unknown-none -//@[aarch64] needs-llvm-components: aarch64 arm riscv +//@[aarch64] needs-llvm-components: aarch64 //@[arm] compile-flags: --target armv7r-none-eabi -//@[arm] needs-llvm-components: aarch64 arm riscv +//@[arm] needs-llvm-components: arm //@[riscv] compile-flags: --target riscv64gc-unknown-none-elf -//@[riscv] needs-llvm-components: aarch64 arm riscv +//@[riscv] needs-llvm-components: riscv //@ compile-flags: -C no-prepopulate-passes #![crate_type = "lib"] diff --git a/tests/codegen-llvm/cast-target-abi.rs b/tests/codegen-llvm/cast-target-abi.rs index cbd49e2f022a..28d3ad5f61c7 100644 --- a/tests/codegen-llvm/cast-target-abi.rs +++ b/tests/codegen-llvm/cast-target-abi.rs @@ -4,7 +4,7 @@ //@ compile-flags: -Copt-level=3 -Cno-prepopulate-passes -Zlint-llvm-ir //@[aarch64] compile-flags: --target aarch64-unknown-linux-gnu -//@[aarch64] needs-llvm-components: arm +//@[aarch64] needs-llvm-components: aarch64 //@[loongarch64] compile-flags: --target loongarch64-unknown-linux-gnu //@[loongarch64] needs-llvm-components: loongarch //@[powerpc64] compile-flags: --target powerpc64-unknown-linux-gnu diff --git a/tests/codegen-llvm/cf-protection.rs b/tests/codegen-llvm/cf-protection.rs index f1349a5dcb98..9efadb599322 100644 --- a/tests/codegen-llvm/cf-protection.rs +++ b/tests/codegen-llvm/cf-protection.rs @@ -3,7 +3,7 @@ //@ add-core-stubs //@ revisions: undefined none branch return full //@ needs-llvm-components: x86 -//@ [undefined] compile-flags: +// [undefined] no extra compile-flags //@ [none] compile-flags: -Z cf-protection=none //@ [branch] compile-flags: -Z cf-protection=branch //@ [return] compile-flags: -Z cf-protection=return diff --git a/tests/codegen-llvm/codemodels.rs b/tests/codegen-llvm/codemodels.rs index 06d2eade78ae..e82e094aab8a 100644 --- a/tests/codegen-llvm/codemodels.rs +++ b/tests/codegen-llvm/codemodels.rs @@ -1,7 +1,7 @@ //@ only-x86_64 //@ revisions: NOMODEL MODEL-SMALL MODEL-KERNEL MODEL-MEDIUM MODEL-LARGE -//@[NOMODEL] compile-flags: +// [NOMODEL] no compile-flags //@[MODEL-SMALL] compile-flags: -C code-model=small //@[MODEL-KERNEL] compile-flags: -C code-model=kernel //@[MODEL-MEDIUM] compile-flags: -C code-model=medium diff --git a/tests/codegen-llvm/ehcontguard_disabled.rs b/tests/codegen-llvm/ehcontguard_disabled.rs index 9efb2721b3e8..962d14e7eb9b 100644 --- a/tests/codegen-llvm/ehcontguard_disabled.rs +++ b/tests/codegen-llvm/ehcontguard_disabled.rs @@ -1,5 +1,3 @@ -//@ compile-flags: - #![crate_type = "lib"] // A basic test function. diff --git a/tests/codegen-llvm/naked-fn/naked-functions.rs b/tests/codegen-llvm/naked-fn/naked-functions.rs index 344af6eb42fa..8a7ee4b4de56 100644 --- a/tests/codegen-llvm/naked-fn/naked-functions.rs +++ b/tests/codegen-llvm/naked-fn/naked-functions.rs @@ -8,7 +8,7 @@ //@[win_i686] compile-flags: --target i686-pc-windows-gnu //@[win_i686] needs-llvm-components: x86 //@[macos] compile-flags: --target aarch64-apple-darwin -//@[macos] needs-llvm-components: arm +//@[macos] needs-llvm-components: aarch64 //@[thumb] compile-flags: --target thumbv7em-none-eabi //@[thumb] needs-llvm-components: arm diff --git a/tests/codegen-llvm/sanitizer/address-sanitizer-globals-tracking.rs b/tests/codegen-llvm/sanitizer/address-sanitizer-globals-tracking.rs index f319306f93fd..642bf5e75762 100644 --- a/tests/codegen-llvm/sanitizer/address-sanitizer-globals-tracking.rs +++ b/tests/codegen-llvm/sanitizer/address-sanitizer-globals-tracking.rs @@ -19,9 +19,9 @@ //@ only-linux // //@ revisions:ASAN ASAN-FAT-LTO -//@ compile-flags: -Zsanitizer=address -Ctarget-feature=-crt-static -//@[ASAN] compile-flags: -//@[ASAN-FAT-LTO] compile-flags: -Cprefer-dynamic=false -Clto=fat +//@ compile-flags: -Zsanitizer=address -Ctarget-feature=-crt-static +// [ASAN] no extra compile-flags +//@[ASAN-FAT-LTO] compile-flags: -Cprefer-dynamic=false -Clto=fat #![crate_type = "staticlib"] diff --git a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-attr-no-sanitize.rs b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-attr-no-sanitize.rs index 6b40918dd3af..02c31fb8e9b0 100644 --- a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-attr-no-sanitize.rs +++ b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-attr-no-sanitize.rs @@ -5,7 +5,7 @@ //@ [aarch64] compile-flags: --target aarch64-unknown-none //@ [aarch64] needs-llvm-components: aarch64 //@ [x86_64] compile-flags: --target x86_64-unknown-none -//@ [x86_64] needs-llvm-components: +//@ [x86_64] needs-llvm-components: x86 //@ compile-flags: -Cno-prepopulate-passes -Zsanitizer=kcfi -Copt-level=0 #![crate_type = "lib"] diff --git a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-generalized.rs b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-generalized.rs index 942b50deb028..9a60d51713f5 100644 --- a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-generalized.rs +++ b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-generalized.rs @@ -5,7 +5,7 @@ //@ [aarch64] compile-flags: --target aarch64-unknown-none //@ [aarch64] needs-llvm-components: aarch64 //@ [x86_64] compile-flags: --target x86_64-unknown-none -//@ [x86_64] needs-llvm-components: +//@ [x86_64] needs-llvm-components: x86 //@ compile-flags: -Cno-prepopulate-passes -Zsanitizer=kcfi -Zsanitizer-cfi-generalize-pointers #![crate_type = "lib"] diff --git a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-normalized-generalized.rs b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-normalized-generalized.rs index c89d9bdd1217..134f4ff4bfd9 100644 --- a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-normalized-generalized.rs +++ b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-normalized-generalized.rs @@ -5,7 +5,7 @@ //@ [aarch64] compile-flags: --target aarch64-unknown-none //@ [aarch64] needs-llvm-components: aarch64 //@ [x86_64] compile-flags: --target x86_64-unknown-none -//@ [x86_64] needs-llvm-components: +//@ [x86_64] needs-llvm-components: x86 //@ compile-flags: -Cno-prepopulate-passes -Zsanitizer=kcfi -Zsanitizer-cfi-normalize-integers -Zsanitizer-cfi-generalize-pointers #![crate_type = "lib"] diff --git a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-normalized.rs b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-normalized.rs index 220cae1a4fa3..4328b7fa07df 100644 --- a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-normalized.rs +++ b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi-normalized.rs @@ -5,7 +5,7 @@ //@ [aarch64] compile-flags: --target aarch64-unknown-none //@ [aarch64] needs-llvm-components: aarch64 //@ [x86_64] compile-flags: --target x86_64-unknown-none -//@ [x86_64] needs-llvm-components: +//@ [x86_64] needs-llvm-components: x86 //@ compile-flags: -Cno-prepopulate-passes -Zsanitizer=kcfi -Zsanitizer-cfi-normalize-integers #![crate_type = "lib"] diff --git a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi.rs b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi.rs index bb9a00059030..81a9db1b97a5 100644 --- a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi.rs +++ b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle-itanium-cxx-abi.rs @@ -5,7 +5,7 @@ //@ [aarch64] compile-flags: --target aarch64-unknown-none //@ [aarch64] needs-llvm-components: aarch64 //@ [x86_64] compile-flags: --target x86_64-unknown-none -//@ [x86_64] needs-llvm-components: +//@ [x86_64] needs-llvm-components: x86 //@ compile-flags: -Cno-prepopulate-passes -Zsanitizer=kcfi -Copt-level=0 #![crate_type = "lib"] diff --git a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle.rs b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle.rs index 8b844b991429..61056c2a54e7 100644 --- a/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle.rs +++ b/tests/codegen-llvm/sanitizer/kcfi/emit-kcfi-operand-bundle.rs @@ -5,7 +5,7 @@ //@ [aarch64] compile-flags: --target aarch64-unknown-none //@ [aarch64] needs-llvm-components: aarch64 //@ [x86_64] compile-flags: --target x86_64-unknown-none -//@ [x86_64] needs-llvm-components: +//@ [x86_64] needs-llvm-components: x86 //@ compile-flags: -Cno-prepopulate-passes -Zsanitizer=kcfi -Copt-level=0 #![crate_type = "lib"] diff --git a/tests/codegen-llvm/sanitizer/kcfi/emit-type-metadata-trait-objects.rs b/tests/codegen-llvm/sanitizer/kcfi/emit-type-metadata-trait-objects.rs index 15c107bea158..182af162d782 100644 --- a/tests/codegen-llvm/sanitizer/kcfi/emit-type-metadata-trait-objects.rs +++ b/tests/codegen-llvm/sanitizer/kcfi/emit-type-metadata-trait-objects.rs @@ -5,7 +5,7 @@ //@ [aarch64] compile-flags: --target aarch64-unknown-none //@ [aarch64] needs-llvm-components: aarch64 //@ [x86_64] compile-flags: --target x86_64-unknown-none -//@ [x86_64] needs-llvm-components: +//@ [x86_64] needs-llvm-components: x86 //@ compile-flags: -Cno-prepopulate-passes -Zsanitizer=kcfi -Copt-level=0 #![crate_type = "lib"] diff --git a/tests/codegen-llvm/sanitizer/memory-track-origins.rs b/tests/codegen-llvm/sanitizer/memory-track-origins.rs index 318c277e10cb..5eb5b356b051 100644 --- a/tests/codegen-llvm/sanitizer/memory-track-origins.rs +++ b/tests/codegen-llvm/sanitizer/memory-track-origins.rs @@ -5,7 +5,7 @@ //@ revisions:MSAN-0 MSAN-1 MSAN-2 MSAN-1-LTO MSAN-2-LTO // //@ compile-flags: -Zsanitizer=memory -Ctarget-feature=-crt-static -//@[MSAN-0] compile-flags: +// [MSAN-0] no extra compile-flags //@[MSAN-1] compile-flags: -Zsanitizer-memory-track-origins=1 //@[MSAN-2] compile-flags: -Zsanitizer-memory-track-origins //@[MSAN-1-LTO] compile-flags: -Zsanitizer-memory-track-origins=1 -C lto=fat diff --git a/tests/codegen-llvm/ub-checks.rs b/tests/codegen-llvm/ub-checks.rs index 67f5bff08d5b..c40bc9acc52a 100644 --- a/tests/codegen-llvm/ub-checks.rs +++ b/tests/codegen-llvm/ub-checks.rs @@ -6,7 +6,7 @@ // but ub-checks are explicitly disabled. //@ revisions: DEBUG NOCHECKS -//@ [DEBUG] compile-flags: +// [DEBUG] no extra compile-flags //@ [NOCHECKS] compile-flags: -Zub-checks=no //@ compile-flags: -Copt-level=3 -Cdebug-assertions=yes diff --git a/tests/debuginfo/unsized.rs b/tests/debuginfo/unsized.rs index 17c5e463fbac..edd9f5af557d 100644 --- a/tests/debuginfo/unsized.rs +++ b/tests/debuginfo/unsized.rs @@ -37,7 +37,6 @@ // cdb-check: [...] vtable : 0x[...] [Type: unsigned [...]int[...] (*)[4]] // cdb-command:dx _box -// cdb-check: // cdb-check:_box [Type: alloc::boxed::Box >,alloc::alloc::Global>] // cdb-check:[+0x000] pointer : 0x[...] [Type: unsized::Foo > *] // cdb-check:[...] vtable : 0x[...] [Type: unsigned [...]int[...] (*)[4]] diff --git a/tests/ui/errors/remap-path-prefix-sysroot.rs b/tests/ui/errors/remap-path-prefix-sysroot.rs index 5e2e4fab51de..f4a2766ff4c0 100644 --- a/tests/ui/errors/remap-path-prefix-sysroot.rs +++ b/tests/ui/errors/remap-path-prefix-sysroot.rs @@ -2,7 +2,7 @@ //@ compile-flags: -g -Ztranslate-remapped-path-to-local-path=yes //@ [with-remap]compile-flags: --remap-path-prefix={{rust-src-base}}=remapped //@ [with-remap]compile-flags: --remap-path-prefix={{src-base}}=remapped-tests-ui -//@ [without-remap]compile-flags: +// [without-remap] no extra compile-flags // The $SRC_DIR*.rs:LL:COL normalisation doesn't kick in automatically // as the remapped revision will not begin with $SRC_DIR_REAL, diff --git a/tests/ui/errors/wrong-target-spec.rs b/tests/ui/errors/wrong-target-spec.rs index a3a0e05d8266..1a9768881122 100644 --- a/tests/ui/errors/wrong-target-spec.rs +++ b/tests/ui/errors/wrong-target-spec.rs @@ -2,6 +2,7 @@ // checks that such invalid target specs are rejected by the compiler. // See https://github.com/rust-lang/rust/issues/33329 +// ignore-tidy-target-specific-tests //@ needs-llvm-components: x86 //@ compile-flags: --target x86_64_unknown-linux-musl diff --git a/tests/ui/linkage-attr/unstable-flavor.rs b/tests/ui/linkage-attr/unstable-flavor.rs index 6aa9efb58d1f..5412e248f341 100644 --- a/tests/ui/linkage-attr/unstable-flavor.rs +++ b/tests/ui/linkage-attr/unstable-flavor.rs @@ -4,9 +4,9 @@ // //@ revisions: bpf ptx //@ [bpf] compile-flags: --target=bpfel-unknown-none -C linker-flavor=bpf --crate-type=rlib -//@ [bpf] needs-llvm-components: +//@ [bpf] needs-llvm-components: bpf //@ [ptx] compile-flags: --target=nvptx64-nvidia-cuda -C linker-flavor=ptx --crate-type=rlib -//@ [ptx] needs-llvm-components: +//@ [ptx] needs-llvm-components: nvptx #![feature(no_core)] #![no_core] diff --git a/tests/ui/target_modifiers/defaults_check.rs b/tests/ui/target_modifiers/defaults_check.rs index de72acd32bc1..ce1d534fd757 100644 --- a/tests/ui/target_modifiers/defaults_check.rs +++ b/tests/ui/target_modifiers/defaults_check.rs @@ -6,7 +6,7 @@ //@ needs-llvm-components: x86 //@ revisions: ok ok_explicit error -//@[ok] compile-flags: +// [ok] no extra compile-flags //@[ok_explicit] compile-flags: -Zreg-struct-return=false //@[error] compile-flags: -Zreg-struct-return=true //@[ok] check-pass diff --git a/tests/ui/target_modifiers/incompatible_fixedx18.rs b/tests/ui/target_modifiers/incompatible_fixedx18.rs index 6c13984f608e..5ba676406ee3 100644 --- a/tests/ui/target_modifiers/incompatible_fixedx18.rs +++ b/tests/ui/target_modifiers/incompatible_fixedx18.rs @@ -5,7 +5,7 @@ //@ revisions:allow_match allow_mismatch error_generated //@[allow_match] compile-flags: -Zfixed-x18 //@[allow_mismatch] compile-flags: -Cunsafe-allow-abi-mismatch=fixed-x18 -//@[error_generated] compile-flags: +// [error_generated] no extra compile-flags //@[allow_mismatch] check-pass //@[allow_match] check-pass diff --git a/tests/ui/target_modifiers/incompatible_regparm.rs b/tests/ui/target_modifiers/incompatible_regparm.rs index 395c26fc2c02..e76bfc976a19 100644 --- a/tests/ui/target_modifiers/incompatible_regparm.rs +++ b/tests/ui/target_modifiers/incompatible_regparm.rs @@ -5,7 +5,7 @@ //@ revisions:allow_regparm_mismatch allow_no_value error_generated //@[allow_regparm_mismatch] compile-flags: -Cunsafe-allow-abi-mismatch=regparm //@[allow_no_value] compile-flags: -Cunsafe-allow-abi-mismatch -//@[error_generated] compile-flags: +// [error_generated] no extra compile-flags //@[allow_regparm_mismatch] check-pass #![feature(no_core)] diff --git a/tests/ui/target_modifiers/no_value_bool.rs b/tests/ui/target_modifiers/no_value_bool.rs index ceba40afa896..72130f8737c0 100644 --- a/tests/ui/target_modifiers/no_value_bool.rs +++ b/tests/ui/target_modifiers/no_value_bool.rs @@ -8,7 +8,7 @@ //@ revisions: ok ok_explicit error error_explicit //@[ok] compile-flags: -Zreg-struct-return //@[ok_explicit] compile-flags: -Zreg-struct-return=true -//@[error] compile-flags: +// [error] no extra compile-flags //@[error_explicit] compile-flags: -Zreg-struct-return=false //@[ok] check-pass //@[ok_explicit] check-pass From 54a4f867f8144203b802fb2c5ae454e0dcb24c6a Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Tue, 29 Jul 2025 18:56:46 +0000 Subject: [PATCH 300/809] 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 301/809] 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 01891d55443fd602a8361ae8d47f9b5b1e4ec6c6 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Thu, 24 Jul 2025 21:26:50 +0500 Subject: [PATCH 302/809] remove hello world directory --- tests/ui/README.md | 4 ---- tests/ui/{hello_world/main.rs => warnings/hello-world.rs} | 0 2 files changed, 4 deletions(-) rename tests/ui/{hello_world/main.rs => warnings/hello-world.rs} (100%) diff --git a/tests/ui/README.md b/tests/ui/README.md index 86c9ad9c1ce8..66c1bb905a79 100644 --- a/tests/ui/README.md +++ b/tests/ui/README.md @@ -654,10 +654,6 @@ Tests on range patterns where one of the bounds is not a direct value. Tests for the standard library collection [`std::collections::HashMap`](https://doc.rust-lang.org/std/collections/struct.HashMap.html). -## `tests/ui/hello_world/` - -Tests that the basic hello-world program is not somehow broken. - ## `tests/ui/higher-ranked/` Tests for higher-ranked trait bounds. diff --git a/tests/ui/hello_world/main.rs b/tests/ui/warnings/hello-world.rs similarity index 100% rename from tests/ui/hello_world/main.rs rename to tests/ui/warnings/hello-world.rs From 05da623016f7bfed812261f2793b4b589631a6b0 Mon Sep 17 00:00:00 2001 From: Orson Peters Date: Sat, 26 Jul 2025 20:13:07 +0200 Subject: [PATCH 303/809] Fix Ord, Eq and Hash implementation of panic::Location Faster equality compare Add tests Add missing files for tests --- library/core/src/panic/location.rs | 42 +++++++++++++++++- library/coretests/tests/panic/location.rs | 43 ++++++++++++++++++- .../coretests/tests/panic/location/file_a.rs | 15 +++++++ .../coretests/tests/panic/location/file_b.rs | 15 +++++++ .../coretests/tests/panic/location/file_c.rs | 11 +++++ 5 files changed, 123 insertions(+), 3 deletions(-) create mode 100644 library/coretests/tests/panic/location/file_a.rs create mode 100644 library/coretests/tests/panic/location/file_b.rs create mode 100644 library/coretests/tests/panic/location/file_c.rs diff --git a/library/core/src/panic/location.rs b/library/core/src/panic/location.rs index 972270208852..6ef7d5a22a30 100644 --- a/library/core/src/panic/location.rs +++ b/library/core/src/panic/location.rs @@ -1,5 +1,7 @@ +use crate::cmp::Ordering; use crate::ffi::CStr; use crate::fmt; +use crate::hash::{Hash, Hasher}; use crate::marker::PhantomData; use crate::ptr::NonNull; @@ -32,7 +34,7 @@ use crate::ptr::NonNull; /// Files are compared as strings, not `Path`, which could be unexpected. /// See [`Location::file`]'s documentation for more discussion. #[lang = "panic_location"] -#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)] +#[derive(Copy, Clone)] #[stable(feature = "panic_hooks", since = "1.10.0")] pub struct Location<'a> { // A raw pointer is used rather than a reference because the pointer is valid for one more byte @@ -44,6 +46,44 @@ pub struct Location<'a> { _filename: PhantomData<&'a str>, } +#[stable(feature = "panic_hooks", since = "1.10.0")] +impl PartialEq for Location<'_> { + fn eq(&self, other: &Self) -> bool { + // Compare col / line first as they're cheaper to compare and more likely to differ, + // while not impacting the result. + self.col == other.col && self.line == other.line && self.file() == other.file() + } +} + +#[stable(feature = "panic_hooks", since = "1.10.0")] +impl Eq for Location<'_> {} + +#[stable(feature = "panic_hooks", since = "1.10.0")] +impl Ord for Location<'_> { + fn cmp(&self, other: &Self) -> Ordering { + self.file() + .cmp(other.file()) + .then_with(|| self.line.cmp(&other.line)) + .then_with(|| self.col.cmp(&other.col)) + } +} + +#[stable(feature = "panic_hooks", since = "1.10.0")] +impl PartialOrd for Location<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +#[stable(feature = "panic_hooks", since = "1.10.0")] +impl Hash for Location<'_> { + fn hash(&self, state: &mut H) { + self.file().hash(state); + self.line.hash(state); + self.col.hash(state); + } +} + #[stable(feature = "panic_hooks", since = "1.10.0")] impl fmt::Debug for Location<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/library/coretests/tests/panic/location.rs b/library/coretests/tests/panic/location.rs index 5ce0b06e90e1..910001bcc1c5 100644 --- a/library/coretests/tests/panic/location.rs +++ b/library/coretests/tests/panic/location.rs @@ -3,6 +3,23 @@ use core::panic::Location; // Note: Some of the following tests depend on the source location, // so please be careful when editing this file. +mod file_a; +mod file_b; +mod file_c; + +// A small shuffled set of locations for testing, along with their true order. +const LOCATIONS: [(usize, &'static Location<'_>); 9] = [ + (7, file_c::two()), + (0, file_a::one()), + (3, file_b::one()), + (5, file_b::three()), + (8, file_c::three()), + (6, file_c::one()), + (2, file_a::three()), + (4, file_b::two()), + (1, file_a::two()), +]; + #[test] fn location_const_caller() { const _CALLER_REFERENCE: &Location<'static> = Location::caller(); @@ -20,7 +37,7 @@ fn location_const_file() { fn location_const_line() { const CALLER: &Location<'static> = Location::caller(); const LINE: u32 = CALLER.line(); - assert_eq!(LINE, 21); + assert_eq!(LINE, 38); } #[test] @@ -34,6 +51,28 @@ fn location_const_column() { fn location_debug() { let f = format!("{:?}", Location::caller()); assert!(f.contains(&format!("{:?}", file!()))); - assert!(f.contains("35")); + assert!(f.contains("52")); assert!(f.contains("29")); } + +#[test] +fn location_eq() { + for (i, a) in LOCATIONS { + for (j, b) in LOCATIONS { + if i == j { + assert_eq!(a, b); + } else { + assert_ne!(a, b); + } + } + } +} + +#[test] +fn location_ord() { + let mut locations = LOCATIONS.clone(); + locations.sort_by_key(|(_o, l)| **l); + for (correct, (order, _l)) in locations.iter().enumerate() { + assert_eq!(correct, *order); + } +} diff --git a/library/coretests/tests/panic/location/file_a.rs b/library/coretests/tests/panic/location/file_a.rs new file mode 100644 index 000000000000..1ceb225ee9c3 --- /dev/null +++ b/library/coretests/tests/panic/location/file_a.rs @@ -0,0 +1,15 @@ +use core::panic::Location; + +// Used for test super::location_{ord, eq}. Must be in a dedicated file. + +pub const fn one() -> &'static Location<'static> { + Location::caller() +} + +pub const fn two() -> &'static Location<'static> { + Location::caller() +} + +pub const fn three() -> &'static Location<'static> { + Location::caller() +} diff --git a/library/coretests/tests/panic/location/file_b.rs b/library/coretests/tests/panic/location/file_b.rs new file mode 100644 index 000000000000..1ceb225ee9c3 --- /dev/null +++ b/library/coretests/tests/panic/location/file_b.rs @@ -0,0 +1,15 @@ +use core::panic::Location; + +// Used for test super::location_{ord, eq}. Must be in a dedicated file. + +pub const fn one() -> &'static Location<'static> { + Location::caller() +} + +pub const fn two() -> &'static Location<'static> { + Location::caller() +} + +pub const fn three() -> &'static Location<'static> { + Location::caller() +} diff --git a/library/coretests/tests/panic/location/file_c.rs b/library/coretests/tests/panic/location/file_c.rs new file mode 100644 index 000000000000..2ac416c19cf4 --- /dev/null +++ b/library/coretests/tests/panic/location/file_c.rs @@ -0,0 +1,11 @@ +// Used for test super::location_{ord, eq}. Must be in a dedicated file. + +// This is used for testing column ordering of Location, hence this ugly one-liner. +// We must fmt skip the entire containing module or else tidy will still complain. +#[rustfmt::skip] +mod no_fmt { + use core::panic::Location; + pub const fn one() -> &'static Location<'static> { Location::caller() } pub const fn two() -> &'static Location<'static> { Location::caller() } pub const fn three() -> &'static Location<'static> { Location::caller() } +} + +pub use no_fmt::*; From 642bec7617b8ad2cb1d3a036991e130166c4ffaf Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Mon, 28 Jul 2025 18:35:23 +0200 Subject: [PATCH 304/809] 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 305/809] 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 306/809] 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 dee20136411854ec541561844eea6de73fe211fe Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 30 Jul 2025 12:28:16 +1000 Subject: [PATCH 307/809] compiletest: Move directive names back into a separate file This list no longer needs to be included in multiple crates, but having it in its own file makes it easier to find and update when necessary. --- src/tools/compiletest/src/directives.rs | 294 +----------------- .../src/directives/directive_names.rs | 289 +++++++++++++++++ 2 files changed, 293 insertions(+), 290 deletions(-) create mode 100644 src/tools/compiletest/src/directives/directive_names.rs diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index a1f76a075562..646dbdae60fe 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -12,6 +12,9 @@ use tracing::*; use crate::common::{CodegenBackend, Config, Debugger, FailMode, PassMode, RunFailMode, TestMode}; use crate::debuggers::{extract_cdb_version, extract_gdb_version}; use crate::directives::auxiliary::{AuxProps, parse_and_update_aux}; +use crate::directives::directive_names::{ + KNOWN_DIRECTIVE_NAMES, KNOWN_HTMLDOCCK_DIRECTIVE_NAMES, KNOWN_JSONDOCCK_DIRECTIVE_NAMES, +}; use crate::directives::needs::CachedNeedsConditions; use crate::errors::ErrorKind; use crate::executor::{CollectedTestDesc, ShouldPanic}; @@ -20,6 +23,7 @@ use crate::util::static_regex; pub(crate) mod auxiliary; mod cfg; +mod directive_names; mod needs; #[cfg(test)] mod tests; @@ -769,296 +773,6 @@ fn line_directive<'line>( Some(DirectiveLine { line_number, revision, raw_directive }) } -/// This was originally generated by collecting directives from ui tests and then extracting their -/// directive names. This is **not** an exhaustive list of all possible directives. Instead, this is -/// a best-effort approximation for diagnostics. Add new directives to this list when needed. -const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ - // tidy-alphabetical-start - "add-core-stubs", - "assembly-output", - "aux-bin", - "aux-build", - "aux-codegen-backend", - "aux-crate", - "build-aux-docs", - "build-fail", - "build-pass", - "check-fail", - "check-pass", - "check-run-results", - "check-stdout", - "check-test-line-numbers-match", - "compile-flags", - "doc-flags", - "dont-check-compiler-stderr", - "dont-check-compiler-stdout", - "dont-check-failure-status", - "dont-require-annotations", - "edition", - "error-pattern", - "exact-llvm-major-version", - "exec-env", - "failure-status", - "filecheck-flags", - "forbid-output", - "force-host", - "ignore-16bit", - "ignore-32bit", - "ignore-64bit", - "ignore-aarch64", - "ignore-aarch64-pc-windows-msvc", - "ignore-aarch64-unknown-linux-gnu", - "ignore-aix", - "ignore-android", - "ignore-apple", - "ignore-arm", - "ignore-arm-unknown-linux-gnueabi", - "ignore-arm-unknown-linux-gnueabihf", - "ignore-arm-unknown-linux-musleabi", - "ignore-arm-unknown-linux-musleabihf", - "ignore-auxiliary", - "ignore-avr", - "ignore-backends", - "ignore-beta", - "ignore-cdb", - "ignore-compare-mode-next-solver", - "ignore-compare-mode-polonius", - "ignore-coverage-map", - "ignore-coverage-run", - "ignore-cross-compile", - "ignore-eabi", - "ignore-elf", - "ignore-emscripten", - "ignore-endian-big", - "ignore-enzyme", - "ignore-freebsd", - "ignore-fuchsia", - "ignore-gdb", - "ignore-gdb-version", - "ignore-gnu", - "ignore-haiku", - "ignore-horizon", - "ignore-i686-pc-windows-gnu", - "ignore-i686-pc-windows-msvc", - "ignore-illumos", - "ignore-ios", - "ignore-linux", - "ignore-lldb", - "ignore-llvm-version", - "ignore-loongarch32", - "ignore-loongarch64", - "ignore-macabi", - "ignore-macos", - "ignore-msp430", - "ignore-msvc", - "ignore-musl", - "ignore-netbsd", - "ignore-nightly", - "ignore-none", - "ignore-nto", - "ignore-nvptx64", - "ignore-nvptx64-nvidia-cuda", - "ignore-openbsd", - "ignore-pass", - "ignore-powerpc", - "ignore-powerpc64", - "ignore-remote", - "ignore-riscv64", - "ignore-rustc-debug-assertions", - "ignore-rustc_abi-x86-sse2", - "ignore-s390x", - "ignore-sgx", - "ignore-sparc64", - "ignore-spirv", - "ignore-stable", - "ignore-stage1", - "ignore-stage2", - "ignore-std-debug-assertions", - "ignore-test", - "ignore-thumb", - "ignore-thumbv8m.base-none-eabi", - "ignore-thumbv8m.main-none-eabi", - "ignore-tvos", - "ignore-unix", - "ignore-unknown", - "ignore-uwp", - "ignore-visionos", - "ignore-vxworks", - "ignore-wasi", - "ignore-wasm", - "ignore-wasm32", - "ignore-wasm32-bare", - "ignore-wasm64", - "ignore-watchos", - "ignore-windows", - "ignore-windows-gnu", - "ignore-windows-msvc", - "ignore-x32", - "ignore-x86", - "ignore-x86_64", - "ignore-x86_64-apple-darwin", - "ignore-x86_64-pc-windows-gnu", - "ignore-x86_64-unknown-linux-gnu", - "incremental", - "known-bug", - "llvm-cov-flags", - "max-llvm-major-version", - "min-cdb-version", - "min-gdb-version", - "min-lldb-version", - "min-llvm-version", - "min-system-llvm-version", - "needs-asm-support", - "needs-backends", - "needs-crate-type", - "needs-deterministic-layouts", - "needs-dlltool", - "needs-dynamic-linking", - "needs-enzyme", - "needs-force-clang-based-tests", - "needs-git-hash", - "needs-llvm-components", - "needs-llvm-zstd", - "needs-profiler-runtime", - "needs-relocation-model-pic", - "needs-run-enabled", - "needs-rust-lld", - "needs-rustc-debug-assertions", - "needs-sanitizer-address", - "needs-sanitizer-cfi", - "needs-sanitizer-dataflow", - "needs-sanitizer-hwaddress", - "needs-sanitizer-kcfi", - "needs-sanitizer-leak", - "needs-sanitizer-memory", - "needs-sanitizer-memtag", - "needs-sanitizer-safestack", - "needs-sanitizer-shadow-call-stack", - "needs-sanitizer-support", - "needs-sanitizer-thread", - "needs-std-debug-assertions", - "needs-subprocess", - "needs-symlink", - "needs-target-has-atomic", - "needs-target-std", - "needs-threads", - "needs-unwind", - "needs-wasmtime", - "needs-xray", - "no-auto-check-cfg", - "no-prefer-dynamic", - "normalize-stderr", - "normalize-stderr-32bit", - "normalize-stderr-64bit", - "normalize-stdout", - "only-16bit", - "only-32bit", - "only-64bit", - "only-aarch64", - "only-aarch64-apple-darwin", - "only-aarch64-unknown-linux-gnu", - "only-apple", - "only-arm", - "only-avr", - "only-beta", - "only-bpf", - "only-cdb", - "only-dist", - "only-elf", - "only-emscripten", - "only-gnu", - "only-i686-pc-windows-gnu", - "only-i686-pc-windows-msvc", - "only-i686-unknown-linux-gnu", - "only-ios", - "only-linux", - "only-loongarch32", - "only-loongarch64", - "only-loongarch64-unknown-linux-gnu", - "only-macos", - "only-mips", - "only-mips64", - "only-msp430", - "only-msvc", - "only-musl", - "only-nightly", - "only-nvptx64", - "only-powerpc", - "only-riscv64", - "only-rustc_abi-x86-sse2", - "only-s390x", - "only-sparc", - "only-sparc64", - "only-stable", - "only-thumb", - "only-tvos", - "only-uefi", - "only-unix", - "only-visionos", - "only-wasm32", - "only-wasm32-bare", - "only-wasm32-wasip1", - "only-watchos", - "only-windows", - "only-windows-gnu", - "only-windows-msvc", - "only-x86", - "only-x86_64", - "only-x86_64-apple-darwin", - "only-x86_64-fortanix-unknown-sgx", - "only-x86_64-pc-windows-gnu", - "only-x86_64-pc-windows-msvc", - "only-x86_64-unknown-linux-gnu", - "pp-exact", - "pretty-compare-only", - "pretty-mode", - "proc-macro", - "reference", - "regex-error-pattern", - "remap-src-base", - "revisions", - "run-crash", - "run-fail", - "run-fail-or-crash", - "run-flags", - "run-pass", - "run-rustfix", - "rustc-env", - "rustfix-only-machine-applicable", - "should-fail", - "should-ice", - "stderr-per-bitwidth", - "test-mir-pass", - "unique-doc-out-dir", - "unset-exec-env", - "unset-rustc-env", - // Used by the tidy check `unknown_revision`. - "unused-revision-names", - // tidy-alphabetical-end -]; - -const KNOWN_HTMLDOCCK_DIRECTIVE_NAMES: &[&str] = &[ - "count", - "!count", - "files", - "!files", - "has", - "!has", - "has-dir", - "!has-dir", - "hasraw", - "!hasraw", - "matches", - "!matches", - "matchesraw", - "!matchesraw", - "snapshot", - "!snapshot", -]; - -const KNOWN_JSONDOCCK_DIRECTIVE_NAMES: &[&str] = - &["count", "!count", "has", "!has", "is", "!is", "ismany", "!ismany", "set", "!set"]; - /// The (partly) broken-down contents of a line containing a test directive, /// which [`iter_directives`] passes to its callback function. /// diff --git a/src/tools/compiletest/src/directives/directive_names.rs b/src/tools/compiletest/src/directives/directive_names.rs new file mode 100644 index 000000000000..7fc76a42e0ca --- /dev/null +++ b/src/tools/compiletest/src/directives/directive_names.rs @@ -0,0 +1,289 @@ +/// This was originally generated by collecting directives from ui tests and then extracting their +/// directive names. This is **not** an exhaustive list of all possible directives. Instead, this is +/// a best-effort approximation for diagnostics. Add new directives to this list when needed. +pub(crate) const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ + // tidy-alphabetical-start + "add-core-stubs", + "assembly-output", + "aux-bin", + "aux-build", + "aux-codegen-backend", + "aux-crate", + "build-aux-docs", + "build-fail", + "build-pass", + "check-fail", + "check-pass", + "check-run-results", + "check-stdout", + "check-test-line-numbers-match", + "compile-flags", + "doc-flags", + "dont-check-compiler-stderr", + "dont-check-compiler-stdout", + "dont-check-failure-status", + "dont-require-annotations", + "edition", + "error-pattern", + "exact-llvm-major-version", + "exec-env", + "failure-status", + "filecheck-flags", + "forbid-output", + "force-host", + "ignore-16bit", + "ignore-32bit", + "ignore-64bit", + "ignore-aarch64", + "ignore-aarch64-pc-windows-msvc", + "ignore-aarch64-unknown-linux-gnu", + "ignore-aix", + "ignore-android", + "ignore-apple", + "ignore-arm", + "ignore-arm-unknown-linux-gnueabi", + "ignore-arm-unknown-linux-gnueabihf", + "ignore-arm-unknown-linux-musleabi", + "ignore-arm-unknown-linux-musleabihf", + "ignore-auxiliary", + "ignore-avr", + "ignore-backends", + "ignore-beta", + "ignore-cdb", + "ignore-compare-mode-next-solver", + "ignore-compare-mode-polonius", + "ignore-coverage-map", + "ignore-coverage-run", + "ignore-cross-compile", + "ignore-eabi", + "ignore-elf", + "ignore-emscripten", + "ignore-endian-big", + "ignore-enzyme", + "ignore-freebsd", + "ignore-fuchsia", + "ignore-gdb", + "ignore-gdb-version", + "ignore-gnu", + "ignore-haiku", + "ignore-horizon", + "ignore-i686-pc-windows-gnu", + "ignore-i686-pc-windows-msvc", + "ignore-illumos", + "ignore-ios", + "ignore-linux", + "ignore-lldb", + "ignore-llvm-version", + "ignore-loongarch32", + "ignore-loongarch64", + "ignore-macabi", + "ignore-macos", + "ignore-msp430", + "ignore-msvc", + "ignore-musl", + "ignore-netbsd", + "ignore-nightly", + "ignore-none", + "ignore-nto", + "ignore-nvptx64", + "ignore-nvptx64-nvidia-cuda", + "ignore-openbsd", + "ignore-pass", + "ignore-powerpc", + "ignore-powerpc64", + "ignore-remote", + "ignore-riscv64", + "ignore-rustc-debug-assertions", + "ignore-rustc_abi-x86-sse2", + "ignore-s390x", + "ignore-sgx", + "ignore-sparc64", + "ignore-spirv", + "ignore-stable", + "ignore-stage1", + "ignore-stage2", + "ignore-std-debug-assertions", + "ignore-test", + "ignore-thumb", + "ignore-thumbv8m.base-none-eabi", + "ignore-thumbv8m.main-none-eabi", + "ignore-tvos", + "ignore-unix", + "ignore-unknown", + "ignore-uwp", + "ignore-visionos", + "ignore-vxworks", + "ignore-wasi", + "ignore-wasm", + "ignore-wasm32", + "ignore-wasm32-bare", + "ignore-wasm64", + "ignore-watchos", + "ignore-windows", + "ignore-windows-gnu", + "ignore-windows-msvc", + "ignore-x32", + "ignore-x86", + "ignore-x86_64", + "ignore-x86_64-apple-darwin", + "ignore-x86_64-pc-windows-gnu", + "ignore-x86_64-unknown-linux-gnu", + "incremental", + "known-bug", + "llvm-cov-flags", + "max-llvm-major-version", + "min-cdb-version", + "min-gdb-version", + "min-lldb-version", + "min-llvm-version", + "min-system-llvm-version", + "needs-asm-support", + "needs-backends", + "needs-crate-type", + "needs-deterministic-layouts", + "needs-dlltool", + "needs-dynamic-linking", + "needs-enzyme", + "needs-force-clang-based-tests", + "needs-git-hash", + "needs-llvm-components", + "needs-llvm-zstd", + "needs-profiler-runtime", + "needs-relocation-model-pic", + "needs-run-enabled", + "needs-rust-lld", + "needs-rustc-debug-assertions", + "needs-sanitizer-address", + "needs-sanitizer-cfi", + "needs-sanitizer-dataflow", + "needs-sanitizer-hwaddress", + "needs-sanitizer-kcfi", + "needs-sanitizer-leak", + "needs-sanitizer-memory", + "needs-sanitizer-memtag", + "needs-sanitizer-safestack", + "needs-sanitizer-shadow-call-stack", + "needs-sanitizer-support", + "needs-sanitizer-thread", + "needs-std-debug-assertions", + "needs-subprocess", + "needs-symlink", + "needs-target-has-atomic", + "needs-target-std", + "needs-threads", + "needs-unwind", + "needs-wasmtime", + "needs-xray", + "no-auto-check-cfg", + "no-prefer-dynamic", + "normalize-stderr", + "normalize-stderr-32bit", + "normalize-stderr-64bit", + "normalize-stdout", + "only-16bit", + "only-32bit", + "only-64bit", + "only-aarch64", + "only-aarch64-apple-darwin", + "only-aarch64-unknown-linux-gnu", + "only-apple", + "only-arm", + "only-avr", + "only-beta", + "only-bpf", + "only-cdb", + "only-dist", + "only-elf", + "only-emscripten", + "only-gnu", + "only-i686-pc-windows-gnu", + "only-i686-pc-windows-msvc", + "only-i686-unknown-linux-gnu", + "only-ios", + "only-linux", + "only-loongarch32", + "only-loongarch64", + "only-loongarch64-unknown-linux-gnu", + "only-macos", + "only-mips", + "only-mips64", + "only-msp430", + "only-msvc", + "only-musl", + "only-nightly", + "only-nvptx64", + "only-powerpc", + "only-riscv64", + "only-rustc_abi-x86-sse2", + "only-s390x", + "only-sparc", + "only-sparc64", + "only-stable", + "only-thumb", + "only-tvos", + "only-uefi", + "only-unix", + "only-visionos", + "only-wasm32", + "only-wasm32-bare", + "only-wasm32-wasip1", + "only-watchos", + "only-windows", + "only-windows-gnu", + "only-windows-msvc", + "only-x86", + "only-x86_64", + "only-x86_64-apple-darwin", + "only-x86_64-fortanix-unknown-sgx", + "only-x86_64-pc-windows-gnu", + "only-x86_64-pc-windows-msvc", + "only-x86_64-unknown-linux-gnu", + "pp-exact", + "pretty-compare-only", + "pretty-mode", + "proc-macro", + "reference", + "regex-error-pattern", + "remap-src-base", + "revisions", + "run-crash", + "run-fail", + "run-fail-or-crash", + "run-flags", + "run-pass", + "run-rustfix", + "rustc-env", + "rustfix-only-machine-applicable", + "should-fail", + "should-ice", + "stderr-per-bitwidth", + "test-mir-pass", + "unique-doc-out-dir", + "unset-exec-env", + "unset-rustc-env", + // Used by the tidy check `unknown_revision`. + "unused-revision-names", + // tidy-alphabetical-end +]; + +pub(crate) const KNOWN_HTMLDOCCK_DIRECTIVE_NAMES: &[&str] = &[ + "count", + "!count", + "files", + "!files", + "has", + "!has", + "has-dir", + "!has-dir", + "hasraw", + "!hasraw", + "matches", + "!matches", + "matchesraw", + "!matchesraw", + "snapshot", + "!snapshot", +]; + +pub(crate) const KNOWN_JSONDOCCK_DIRECTIVE_NAMES: &[&str] = + &["count", "!count", "has", "!has", "is", "!is", "ismany", "!ismany", "set", "!set"]; From 2e6f4a59226fd82c526df0f61fefc6fea44e7750 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 4 May 2025 14:09:52 +1000 Subject: [PATCH 308/809] coverage: Re-land "Enlarge empty spans during MIR instrumentation" This allows us to assume that coverage spans will only be discarded during codegen in very unusual situations. --- .../src/coverageinfo/mapgen/spans.rs | 28 ++------------ .../rustc_mir_transform/src/coverage/spans.rs | 38 ++++++++++++++++++- tests/coverage/async_closure.cov-map | 21 +++++----- tests/coverage/try-in-macro.attr.cov-map | 9 ----- tests/coverage/try-in-macro.bang.cov-map | 9 ----- tests/coverage/try-in-macro.derive.cov-map | 9 ----- ...ch_match_arms.main.InstrumentCoverage.diff | 2 +- ...ument_coverage.bar.InstrumentCoverage.diff | 2 +- ...ment_coverage.main.InstrumentCoverage.diff | 4 +- ...rage_cleanup.main.CleanupPostBorrowck.diff | 4 +- ...erage_cleanup.main.InstrumentCoverage.diff | 4 +- 11 files changed, 57 insertions(+), 73 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/spans.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/spans.rs index 39a59560c9d3..574463be7ffe 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/spans.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/spans.rs @@ -39,7 +39,10 @@ impl Coords { /// or other expansions), and if it does happen then skipping a span or function is /// better than an ICE or `llvm-cov` failure that the user might have no way to avoid. pub(crate) fn make_coords(source_map: &SourceMap, file: &SourceFile, span: Span) -> Option { - let span = ensure_non_empty_span(source_map, span)?; + if span.is_empty() { + debug_assert!(false, "can't make coords from empty span: {span:?}"); + return None; + } let lo = span.lo(); let hi = span.hi(); @@ -70,29 +73,6 @@ pub(crate) fn make_coords(source_map: &SourceMap, file: &SourceFile, span: Span) }) } -fn ensure_non_empty_span(source_map: &SourceMap, span: Span) -> Option { - if !span.is_empty() { - return Some(span); - } - - // The span is empty, so try to enlarge it to cover an adjacent '{' or '}'. - source_map - .span_to_source(span, |src, start, end| try { - // Adjusting span endpoints by `BytePos(1)` is normally a bug, - // but in this case we have specifically checked that the character - // we're skipping over is one of two specific ASCII characters, so - // adjusting by exactly 1 byte is correct. - if src.as_bytes().get(end).copied() == Some(b'{') { - Some(span.with_hi(span.hi() + BytePos(1))) - } else if start > 0 && src.as_bytes()[start - 1] == b'}' { - Some(span.with_lo(span.lo() - BytePos(1))) - } else { - None - } - }) - .ok()? -} - /// If `llvm-cov` sees a source region that is improperly ordered (end < start), /// it will immediately exit with a fatal error. To prevent that from happening, /// discard regions that are improperly ordered, or might be interpreted in a diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index ec76076020eb..ddeae093df5b 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -1,7 +1,8 @@ use rustc_data_structures::fx::FxHashSet; use rustc_middle::mir; use rustc_middle::ty::TyCtxt; -use rustc_span::{DesugaringKind, ExpnKind, MacroKind, Span}; +use rustc_span::source_map::SourceMap; +use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span}; use tracing::instrument; use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph}; @@ -83,8 +84,18 @@ pub(super) fn extract_refined_covspans<'tcx>( // Discard any span that overlaps with a hole. discard_spans_overlapping_holes(&mut covspans, &holes); - // Perform more refinement steps after holes have been dealt with. + // Discard spans that overlap in unwanted ways. let mut covspans = remove_unwanted_overlapping_spans(covspans); + + // For all empty spans, either enlarge them to be non-empty, or discard them. + let source_map = tcx.sess.source_map(); + covspans.retain_mut(|covspan| { + let Some(span) = ensure_non_empty_span(source_map, covspan.span) else { return false }; + covspan.span = span; + true + }); + + // Merge covspans that can be merged. covspans.dedup_by(|b, a| a.merge_if_eligible(b)); code_mappings.extend(covspans.into_iter().map(|Covspan { span, bcb }| { @@ -230,3 +241,26 @@ fn compare_spans(a: Span, b: Span) -> std::cmp::Ordering { // - Both have the same start and span A extends further right .then_with(|| Ord::cmp(&a.hi(), &b.hi()).reverse()) } + +fn ensure_non_empty_span(source_map: &SourceMap, span: Span) -> Option { + if !span.is_empty() { + return Some(span); + } + + // The span is empty, so try to enlarge it to cover an adjacent '{' or '}'. + source_map + .span_to_source(span, |src, start, end| try { + // Adjusting span endpoints by `BytePos(1)` is normally a bug, + // but in this case we have specifically checked that the character + // we're skipping over is one of two specific ASCII characters, so + // adjusting by exactly 1 byte is correct. + if src.as_bytes().get(end).copied() == Some(b'{') { + Some(span.with_hi(span.hi() + BytePos(1))) + } else if start > 0 && src.as_bytes()[start - 1] == b'}' { + Some(span.with_lo(span.lo() - BytePos(1))) + } else { + None + } + }) + .ok()? +} diff --git a/tests/coverage/async_closure.cov-map b/tests/coverage/async_closure.cov-map index 9f8dc8d6cbba..53128dd7a48b 100644 --- a/tests/coverage/async_closure.cov-map +++ b/tests/coverage/async_closure.cov-map @@ -37,32 +37,29 @@ Number of file 0 mappings: 8 Highest counter ID seen: c0 Function name: async_closure::main::{closure#0} -Raw bytes (14): 0x[01, 01, 00, 02, 01, 0b, 22, 00, 23, 01, 00, 23, 00, 24] +Raw bytes (9): 0x[01, 01, 00, 01, 01, 0b, 22, 00, 24] Number of files: 1 - file 0 => $DIR/async_closure.rs Number of expressions: 0 -Number of file 0 mappings: 2 -- Code(Counter(0)) at (prev + 11, 34) to (start + 0, 35) -- Code(Counter(0)) at (prev + 0, 35) to (start + 0, 36) +Number of file 0 mappings: 1 +- Code(Counter(0)) at (prev + 11, 34) to (start + 0, 36) Highest counter ID seen: c0 Function name: async_closure::main::{closure#0} -Raw bytes (14): 0x[01, 01, 00, 02, 01, 0b, 22, 00, 23, 01, 00, 23, 00, 24] +Raw bytes (9): 0x[01, 01, 00, 01, 01, 0b, 22, 00, 24] Number of files: 1 - file 0 => $DIR/async_closure.rs Number of expressions: 0 -Number of file 0 mappings: 2 -- Code(Counter(0)) at (prev + 11, 34) to (start + 0, 35) -- Code(Counter(0)) at (prev + 0, 35) to (start + 0, 36) +Number of file 0 mappings: 1 +- Code(Counter(0)) at (prev + 11, 34) to (start + 0, 36) Highest counter ID seen: c0 Function name: async_closure::main::{closure#0}::{closure#0}:: -Raw bytes (14): 0x[01, 01, 00, 02, 01, 0b, 22, 00, 23, 01, 00, 23, 00, 24] +Raw bytes (9): 0x[01, 01, 00, 01, 01, 0b, 22, 00, 24] Number of files: 1 - file 0 => $DIR/async_closure.rs Number of expressions: 0 -Number of file 0 mappings: 2 -- Code(Counter(0)) at (prev + 11, 34) to (start + 0, 35) -- Code(Counter(0)) at (prev + 0, 35) to (start + 0, 36) +Number of file 0 mappings: 1 +- Code(Counter(0)) at (prev + 11, 34) to (start + 0, 36) Highest counter ID seen: c0 diff --git a/tests/coverage/try-in-macro.attr.cov-map b/tests/coverage/try-in-macro.attr.cov-map index 7111e89637ce..1b6c97cf145a 100644 --- a/tests/coverage/try-in-macro.attr.cov-map +++ b/tests/coverage/try-in-macro.attr.cov-map @@ -1,12 +1,3 @@ -Function name: ::try_size_hint -Raw bytes (9): 0x[01, 01, 00, 01, 00, 1e, 2a, 00, 2b] -Number of files: 1 -- file 0 => $DIR/try-in-macro.rs -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 30, 42) to (start + 0, 43) -Highest counter ID seen: (none) - Function name: try_in_macro::main Raw bytes (19): 0x[01, 01, 00, 03, 01, 29, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] Number of files: 1 diff --git a/tests/coverage/try-in-macro.bang.cov-map b/tests/coverage/try-in-macro.bang.cov-map index 80bd91a993c0..1b6c97cf145a 100644 --- a/tests/coverage/try-in-macro.bang.cov-map +++ b/tests/coverage/try-in-macro.bang.cov-map @@ -1,12 +1,3 @@ -Function name: ::try_size_hint -Raw bytes (9): 0x[01, 01, 00, 01, 00, 23, 1c, 00, 1d] -Number of files: 1 -- file 0 => $DIR/try-in-macro.rs -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 35, 28) to (start + 0, 29) -Highest counter ID seen: (none) - Function name: try_in_macro::main Raw bytes (19): 0x[01, 01, 00, 03, 01, 29, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] Number of files: 1 diff --git a/tests/coverage/try-in-macro.derive.cov-map b/tests/coverage/try-in-macro.derive.cov-map index 6646b6693bae..1b6c97cf145a 100644 --- a/tests/coverage/try-in-macro.derive.cov-map +++ b/tests/coverage/try-in-macro.derive.cov-map @@ -1,12 +1,3 @@ -Function name: ::try_size_hint -Raw bytes (9): 0x[01, 01, 00, 01, 00, 26, 38, 00, 39] -Number of files: 1 -- file 0 => $DIR/try-in-macro.rs -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 38, 56) to (start + 0, 57) -Highest counter ID seen: (none) - Function name: try_in_macro::main Raw bytes (19): 0x[01, 01, 00, 03, 01, 29, 01, 00, 0a, 01, 01, 05, 00, 1a, 01, 01, 01, 00, 02] Number of files: 1 diff --git a/tests/mir-opt/coverage/branch_match_arms.main.InstrumentCoverage.diff b/tests/mir-opt/coverage/branch_match_arms.main.InstrumentCoverage.diff index d465b8bded22..fa88211383a0 100644 --- a/tests/mir-opt/coverage/branch_match_arms.main.InstrumentCoverage.diff +++ b/tests/mir-opt/coverage/branch_match_arms.main.InstrumentCoverage.diff @@ -40,7 +40,7 @@ + coverage Code { bcb: bcb5 } => $DIR/branch_match_arms.rs:19:17: 19:18 (#0); + coverage Code { bcb: bcb5 } => $DIR/branch_match_arms.rs:19:23: 19:30 (#0); + coverage Code { bcb: bcb5 } => $DIR/branch_match_arms.rs:19:31: 19:32 (#0); -+ coverage Code { bcb: bcb2 } => $DIR/branch_match_arms.rs:21:2: 21:2 (#0); ++ coverage Code { bcb: bcb2 } => $DIR/branch_match_arms.rs:21:1: 21:2 (#0); + bb0: { + Coverage::VirtualCounter(bcb0); diff --git a/tests/mir-opt/coverage/instrument_coverage.bar.InstrumentCoverage.diff b/tests/mir-opt/coverage/instrument_coverage.bar.InstrumentCoverage.diff index cf6d85abd80e..9b6d2b22087b 100644 --- a/tests/mir-opt/coverage/instrument_coverage.bar.InstrumentCoverage.diff +++ b/tests/mir-opt/coverage/instrument_coverage.bar.InstrumentCoverage.diff @@ -6,7 +6,7 @@ + coverage Code { bcb: bcb0 } => $DIR/instrument_coverage.rs:27:1: 27:17 (#0); + coverage Code { bcb: bcb0 } => $DIR/instrument_coverage.rs:28:5: 28:9 (#0); -+ coverage Code { bcb: bcb0 } => $DIR/instrument_coverage.rs:29:2: 29:2 (#0); ++ coverage Code { bcb: bcb0 } => $DIR/instrument_coverage.rs:29:1: 29:2 (#0); + bb0: { + Coverage::VirtualCounter(bcb0); diff --git a/tests/mir-opt/coverage/instrument_coverage.main.InstrumentCoverage.diff b/tests/mir-opt/coverage/instrument_coverage.main.InstrumentCoverage.diff index 980c5e202ffd..b2bb2375aee6 100644 --- a/tests/mir-opt/coverage/instrument_coverage.main.InstrumentCoverage.diff +++ b/tests/mir-opt/coverage/instrument_coverage.main.InstrumentCoverage.diff @@ -10,8 +10,8 @@ + coverage Code { bcb: bcb0 } => $DIR/instrument_coverage.rs:13:1: 13:10 (#0); + coverage Code { bcb: bcb1 } => $DIR/instrument_coverage.rs:15:12: 15:15 (#0); + coverage Code { bcb: bcb2 } => $DIR/instrument_coverage.rs:16:13: 16:18 (#0); -+ coverage Code { bcb: bcb3 } => $DIR/instrument_coverage.rs:17:10: 17:10 (#0); -+ coverage Code { bcb: bcb2 } => $DIR/instrument_coverage.rs:19:2: 19:2 (#0); ++ coverage Code { bcb: bcb3 } => $DIR/instrument_coverage.rs:17:9: 17:10 (#0); ++ coverage Code { bcb: bcb2 } => $DIR/instrument_coverage.rs:19:1: 19:2 (#0); + bb0: { + Coverage::VirtualCounter(bcb0); diff --git a/tests/mir-opt/coverage/instrument_coverage_cleanup.main.CleanupPostBorrowck.diff b/tests/mir-opt/coverage/instrument_coverage_cleanup.main.CleanupPostBorrowck.diff index b707cd41788a..2eb78c08ee80 100644 --- a/tests/mir-opt/coverage/instrument_coverage_cleanup.main.CleanupPostBorrowck.diff +++ b/tests/mir-opt/coverage/instrument_coverage_cleanup.main.CleanupPostBorrowck.diff @@ -10,8 +10,8 @@ coverage Code { bcb: bcb0 } => $DIR/instrument_coverage_cleanup.rs:13:1: 13:10 (#0); coverage Code { bcb: bcb0 } => $DIR/instrument_coverage_cleanup.rs:14:8: 14:36 (#0); coverage Code { bcb: bcb3 } => $DIR/instrument_coverage_cleanup.rs:14:37: 14:39 (#0); - coverage Code { bcb: bcb1 } => $DIR/instrument_coverage_cleanup.rs:14:39: 14:39 (#0); - coverage Code { bcb: bcb2 } => $DIR/instrument_coverage_cleanup.rs:15:2: 15:2 (#0); + coverage Code { bcb: bcb1 } => $DIR/instrument_coverage_cleanup.rs:14:38: 14:39 (#0); + coverage Code { bcb: bcb2 } => $DIR/instrument_coverage_cleanup.rs:15:1: 15:2 (#0); coverage Branch { true_bcb: bcb3, false_bcb: bcb1 } => $DIR/instrument_coverage_cleanup.rs:14:8: 14:36 (#0); bb0: { diff --git a/tests/mir-opt/coverage/instrument_coverage_cleanup.main.InstrumentCoverage.diff b/tests/mir-opt/coverage/instrument_coverage_cleanup.main.InstrumentCoverage.diff index 239b845c2311..0c1bc24b6dc1 100644 --- a/tests/mir-opt/coverage/instrument_coverage_cleanup.main.InstrumentCoverage.diff +++ b/tests/mir-opt/coverage/instrument_coverage_cleanup.main.InstrumentCoverage.diff @@ -10,8 +10,8 @@ + coverage Code { bcb: bcb0 } => $DIR/instrument_coverage_cleanup.rs:13:1: 13:10 (#0); + coverage Code { bcb: bcb0 } => $DIR/instrument_coverage_cleanup.rs:14:8: 14:36 (#0); + coverage Code { bcb: bcb3 } => $DIR/instrument_coverage_cleanup.rs:14:37: 14:39 (#0); -+ coverage Code { bcb: bcb1 } => $DIR/instrument_coverage_cleanup.rs:14:39: 14:39 (#0); -+ coverage Code { bcb: bcb2 } => $DIR/instrument_coverage_cleanup.rs:15:2: 15:2 (#0); ++ coverage Code { bcb: bcb1 } => $DIR/instrument_coverage_cleanup.rs:14:38: 14:39 (#0); ++ coverage Code { bcb: bcb2 } => $DIR/instrument_coverage_cleanup.rs:15:1: 15:2 (#0); + coverage Branch { true_bcb: bcb3, false_bcb: bcb1 } => $DIR/instrument_coverage_cleanup.rs:14:8: 14:36 (#0); + bb0: { From fe08ba0bae44b870fdda45a98ac51f435ddfc044 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Tue, 29 Jul 2025 20:41:34 -0700 Subject: [PATCH 309/809] Re-block SRoA on SIMD types Fixes 144621 --- compiler/rustc_mir_transform/src/sroa.rs | 6 +++- ...roa.foo.ScalarReplacementOfAggregates.diff | 32 +++++++++++++++++++ tests/mir-opt/sroa/simd_sroa.rs | 18 +++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 tests/mir-opt/sroa/simd_sroa.foo.ScalarReplacementOfAggregates.diff create mode 100644 tests/mir-opt/sroa/simd_sroa.rs diff --git a/compiler/rustc_mir_transform/src/sroa.rs b/compiler/rustc_mir_transform/src/sroa.rs index 80c4b58a5744..38769885f368 100644 --- a/compiler/rustc_mir_transform/src/sroa.rs +++ b/compiler/rustc_mir_transform/src/sroa.rs @@ -72,8 +72,12 @@ fn escaping_locals<'tcx>( return true; } if let ty::Adt(def, _args) = ty.kind() - && tcx.is_lang_item(def.did(), LangItem::DynMetadata) + && (def.repr().simd() || tcx.is_lang_item(def.did(), LangItem::DynMetadata)) { + // Exclude #[repr(simd)] types so that they are not de-optimized into an array + // (MCP#838 banned projections into SIMD types, but if the value is unused + // this pass sees "all the uses are of the fields" and expands it.) + // codegen wants to see the `DynMetadata`, // not the inner reference-to-opaque-type. return true; diff --git a/tests/mir-opt/sroa/simd_sroa.foo.ScalarReplacementOfAggregates.diff b/tests/mir-opt/sroa/simd_sroa.foo.ScalarReplacementOfAggregates.diff new file mode 100644 index 000000000000..744032471089 --- /dev/null +++ b/tests/mir-opt/sroa/simd_sroa.foo.ScalarReplacementOfAggregates.diff @@ -0,0 +1,32 @@ +- // MIR for `foo` before ScalarReplacementOfAggregates ++ // MIR for `foo` after ScalarReplacementOfAggregates + + fn foo(_1: &[Simd], _2: Simd) -> () { + debug simds => _1; + debug _unused => _2; + let mut _0: (); + let _3: std::simd::Simd; + let _4: usize; + let mut _5: usize; + let mut _6: bool; + scope 1 { + debug a => _3; + } + + bb0: { + StorageLive(_3); + StorageLive(_4); + _4 = const 0_usize; + _5 = PtrMetadata(copy _1); + _6 = Lt(copy _4, copy _5); + assert(move _6, "index out of bounds: the length is {} but the index is {}", move _5, copy _4) -> [success: bb1, unwind continue]; + } + + bb1: { + _3 = copy (*_1)[_4]; + StorageDead(_4); + StorageDead(_3); + return; + } + } + diff --git a/tests/mir-opt/sroa/simd_sroa.rs b/tests/mir-opt/sroa/simd_sroa.rs new file mode 100644 index 000000000000..1ae84d3f975b --- /dev/null +++ b/tests/mir-opt/sroa/simd_sroa.rs @@ -0,0 +1,18 @@ +//@ needs-unwind +#![feature(portable_simd)] + +// SRoA expands things even if they're unused +// + +use std::simd::Simd; + +// EMIT_MIR simd_sroa.foo.ScalarReplacementOfAggregates.diff +pub(crate) fn foo(simds: &[Simd], _unused: Simd) { + // CHECK-LABEL: fn foo + // CHECK-NOT: [u8; 16] + // CHECK: let [[SIMD:_.+]]: std::simd::Simd; + // CHECK-NOT: [u8; 16] + // CHECK: [[SIMD]] = copy (*_1)[0 of 1]; + // CHECK-NOT: [u8; 16] + let a = simds[0]; +} From 98d08ff014840a15244374178e8b9ed02da3d4ca Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 30 Jul 2025 03:39:16 +0000 Subject: [PATCH 310/809] Make sure to account for the right item universal regions in borrowck --- .../rustc_borrowck/src/universal_regions.rs | 27 ++++++++++++++----- .../liberated-region-from-outer-closure.rs | 12 +++++++++ ...liberated-region-from-outer-closure.stderr | 17 ++++++++++++ .../escape-argument-callee.stderr | 3 +++ .../escape-argument.stderr | 2 ++ ...pagate-approximated-fail-no-postdom.stderr | 2 ++ .../propagate-approximated-ref.stderr | 6 +++++ ...er-to-static-comparing-against-free.stderr | 2 ++ ...oximated-shorter-to-static-no-bound.stderr | 5 ++++ ...mated-shorter-to-static-wrong-bound.stderr | 6 +++++ .../propagate-approximated-val.stderr | 2 ++ .../propagate-despite-same-free-region.stderr | 2 ++ ...ail-to-approximate-longer-no-bounds.stderr | 5 ++++ ...-to-approximate-longer-wrong-bounds.stderr | 6 +++++ .../return-wrong-bound-region.stderr | 2 ++ ...ram-closure-approximate-lower-bound.stderr | 4 +++ 16 files changed, 97 insertions(+), 6 deletions(-) create mode 100644 tests/ui/borrowck/liberated-region-from-outer-closure.rs create mode 100644 tests/ui/borrowck/liberated-region-from-outer-closure.stderr diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index f138f2653203..240c9a5223be 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -969,13 +969,28 @@ fn for_each_late_bound_region_in_item<'tcx>( mir_def_id: LocalDefId, mut f: impl FnMut(ty::Region<'tcx>), ) { - if !tcx.def_kind(mir_def_id).is_fn_like() { - return; - } + let bound_vars = match tcx.def_kind(mir_def_id) { + DefKind::Fn | DefKind::AssocFn => { + tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id)) + } + // We extract the bound vars from the deduced closure signature, since we may have + // only deduced that a param in the closure signature is late-bound from a constraint + // that we discover during typeck. + DefKind::Closure => { + let ty = tcx.type_of(mir_def_id).instantiate_identity(); + match *ty.kind() { + ty::Closure(_, args) => args.as_closure().sig().bound_vars(), + ty::CoroutineClosure(_, args) => { + args.as_coroutine_closure().coroutine_closure_sig().bound_vars() + } + ty::Coroutine(_, _) | ty::Error(_) => return, + _ => unreachable!("unexpected type for closure: {ty}"), + } + } + _ => return, + }; - for (idx, bound_var) in - tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id)).iter().enumerate() - { + for (idx, bound_var) in bound_vars.iter().enumerate() { if let ty::BoundVariableKind::Region(kind) = bound_var { let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind); let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind); diff --git a/tests/ui/borrowck/liberated-region-from-outer-closure.rs b/tests/ui/borrowck/liberated-region-from-outer-closure.rs new file mode 100644 index 000000000000..dcc6370b4a12 --- /dev/null +++ b/tests/ui/borrowck/liberated-region-from-outer-closure.rs @@ -0,0 +1,12 @@ +// Regression test for . + +fn example(x: T) -> impl FnMut(&mut ()) { + move |_: &mut ()| { + move || needs_static_lifetime(x); + //~^ ERROR the parameter type `T` may not live long enough + } +} + +fn needs_static_lifetime(obj: T) {} + +fn main() {} diff --git a/tests/ui/borrowck/liberated-region-from-outer-closure.stderr b/tests/ui/borrowck/liberated-region-from-outer-closure.stderr new file mode 100644 index 000000000000..98b45ac499dc --- /dev/null +++ b/tests/ui/borrowck/liberated-region-from-outer-closure.stderr @@ -0,0 +1,17 @@ +error[E0310]: the parameter type `T` may not live long enough + --> $DIR/liberated-region-from-outer-closure.rs:5:17 + | +LL | move || needs_static_lifetime(x); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | the parameter type `T` must be valid for the static lifetime... + | ...so that the type `T` will meet its required lifetime bounds + | +help: consider adding an explicit lifetime bound + | +LL | fn example(x: T) -> impl FnMut(&mut ()) { + | +++++++++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0310`. diff --git a/tests/ui/nll/closure-requirements/escape-argument-callee.stderr b/tests/ui/nll/closure-requirements/escape-argument-callee.stderr index a445534c8d80..2742162c8211 100644 --- a/tests/ui/nll/closure-requirements/escape-argument-callee.stderr +++ b/tests/ui/nll/closure-requirements/escape-argument-callee.stderr @@ -9,6 +9,9 @@ LL | let mut closure = expect_sig(|p, y| *p = y); for extern "rust-call" fn((&'^0 mut &'^1 i32, &'^2 i32)), (), ] + = note: late-bound region is '?1 + = note: late-bound region is '?2 + = note: late-bound region is '?3 error: lifetime may not live long enough --> $DIR/escape-argument-callee.rs:26:45 diff --git a/tests/ui/nll/closure-requirements/escape-argument.stderr b/tests/ui/nll/closure-requirements/escape-argument.stderr index 7fd1cd8c3e42..22cb0367ad87 100644 --- a/tests/ui/nll/closure-requirements/escape-argument.stderr +++ b/tests/ui/nll/closure-requirements/escape-argument.stderr @@ -9,6 +9,8 @@ LL | let mut closure = expect_sig(|p, y| *p = y); for extern "rust-call" fn((&'^0 mut &'^1 i32, &'^1 i32)), (), ] + = note: late-bound region is '?1 + = note: late-bound region is '?2 note: no external requirements --> $DIR/escape-argument.rs:20:1 diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr index 60087ec992bd..134ce99014d8 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr @@ -9,6 +9,8 @@ LL | |_outlives1, _outlives2, _outlives3, x, y| { for extern "rust-call" fn((std::cell::Cell<&'?1 &'^0 u32>, std::cell::Cell<&'?2 &'^0 u32>, std::cell::Cell<&'^1 &'?3 u32>, std::cell::Cell<&'^0 u32>, std::cell::Cell<&'^1 u32>)), (), ] + = note: late-bound region is '?7 + = note: late-bound region is '?8 = note: late-bound region is '?4 = note: late-bound region is '?5 = note: late-bound region is '?6 diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-ref.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-ref.stderr index 7325a9de8b29..f5527eeb2cdb 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-ref.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-ref.stderr @@ -9,6 +9,12 @@ LL | establish_relationships(&cell_a, &cell_b, |_outlives1, _outlives2, x, y for extern "rust-call" fn((&'^0 std::cell::Cell<&'?1 &'^1 u32>, &'^2 std::cell::Cell<&'^3 &'?2 u32>, &'^4 std::cell::Cell<&'^1 u32>, &'^5 std::cell::Cell<&'^3 u32>)), (), ] + = note: late-bound region is '?5 + = note: late-bound region is '?6 + = note: late-bound region is '?7 + = note: late-bound region is '?8 + = note: late-bound region is '?9 + = note: late-bound region is '?10 = note: late-bound region is '?3 = note: late-bound region is '?4 = note: number of external vids: 5 diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr index 621c1ea083b2..e13653f34234 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr @@ -9,6 +9,7 @@ LL | foo(cell, |cell_a, cell_x| { for extern "rust-call" fn((std::cell::Cell<&'?1 u32>, std::cell::Cell<&'^0 u32>)), (), ] + = note: late-bound region is '?2 error[E0521]: borrowed data escapes outside of closure --> $DIR/propagate-approximated-shorter-to-static-comparing-against-free.rs:22:9 @@ -43,6 +44,7 @@ LL | foo(cell, |cell_a, cell_x| { for extern "rust-call" fn((std::cell::Cell<&'?1 u32>, std::cell::Cell<&'^0 u32>)), (), ] + = note: late-bound region is '?2 = note: number of external vids: 2 = note: where '?1: '?0 diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr index b9365c94a1be..9e9eae985973 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr @@ -9,6 +9,11 @@ LL | establish_relationships(&cell_a, &cell_b, |_outlives, x, y| { for extern "rust-call" fn((&'^0 std::cell::Cell<&'?1 &'^1 u32>, &'^2 std::cell::Cell<&'^1 u32>, &'^3 std::cell::Cell<&'^4 u32>)), (), ] + = note: late-bound region is '?4 + = note: late-bound region is '?5 + = note: late-bound region is '?6 + = note: late-bound region is '?7 + = note: late-bound region is '?8 = note: late-bound region is '?2 = note: late-bound region is '?3 = note: number of external vids: 4 diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr index e5d2867103cf..303fcd4cdfcf 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr @@ -9,6 +9,12 @@ LL | establish_relationships(&cell_a, &cell_b, |_outlives1, _outlives2, x, y for extern "rust-call" fn((&'^0 std::cell::Cell<&'?1 &'^1 u32>, &'^2 std::cell::Cell<&'?2 &'^3 u32>, &'^4 std::cell::Cell<&'^1 u32>, &'^5 std::cell::Cell<&'^3 u32>)), (), ] + = note: late-bound region is '?5 + = note: late-bound region is '?6 + = note: late-bound region is '?7 + = note: late-bound region is '?8 + = note: late-bound region is '?9 + = note: late-bound region is '?10 = note: late-bound region is '?3 = note: late-bound region is '?4 = note: number of external vids: 5 diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-val.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-val.stderr index a14bfb06e831..aa75b4c811c1 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-val.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-val.stderr @@ -9,6 +9,8 @@ LL | establish_relationships(cell_a, cell_b, |outlives1, outlives2, x, y| { for extern "rust-call" fn((std::cell::Cell<&'?1 &'^0 u32>, std::cell::Cell<&'^1 &'?2 u32>, std::cell::Cell<&'^0 u32>, std::cell::Cell<&'^1 u32>)), (), ] + = note: late-bound region is '?5 + = note: late-bound region is '?6 = note: late-bound region is '?3 = note: late-bound region is '?4 = note: number of external vids: 5 diff --git a/tests/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr b/tests/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr index 49c65d77ddde..30ee259d3dce 100644 --- a/tests/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr +++ b/tests/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr @@ -9,6 +9,8 @@ LL | |_outlives1, _outlives2, x, y| { for extern "rust-call" fn((std::cell::Cell<&'?1 &'^0 u32>, std::cell::Cell<&'^1 &'?2 u32>, std::cell::Cell<&'^0 u32>, std::cell::Cell<&'^1 u32>)), (), ] + = note: late-bound region is '?4 + = note: late-bound region is '?5 = note: late-bound region is '?3 = note: number of external vids: 4 = note: where '?1: '?2 diff --git a/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr b/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr index f48ed2823ddb..6b04e346c697 100644 --- a/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr +++ b/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr @@ -9,6 +9,11 @@ LL | establish_relationships(&cell_a, &cell_b, |_outlives, x, y| { for extern "rust-call" fn((&'^0 std::cell::Cell<&'^1 &'?1 u32>, &'^2 std::cell::Cell<&'^3 u32>, &'^4 std::cell::Cell<&'^1 u32>)), (), ] + = note: late-bound region is '?4 + = note: late-bound region is '?5 + = note: late-bound region is '?6 + = note: late-bound region is '?7 + = note: late-bound region is '?8 = note: late-bound region is '?2 = note: late-bound region is '?3 diff --git a/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr b/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr index a090e94593fe..ae2129c65f2c 100644 --- a/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr +++ b/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr @@ -9,6 +9,12 @@ LL | establish_relationships(&cell_a, &cell_b, |_outlives1, _outlives2, x, y for extern "rust-call" fn((&'^0 std::cell::Cell<&'^1 &'?1 u32>, &'^2 std::cell::Cell<&'^3 &'?2 u32>, &'^4 std::cell::Cell<&'^1 u32>, &'^5 std::cell::Cell<&'^3 u32>)), (), ] + = note: late-bound region is '?5 + = note: late-bound region is '?6 + = note: late-bound region is '?7 + = note: late-bound region is '?8 + = note: late-bound region is '?9 + = note: late-bound region is '?10 = note: late-bound region is '?3 = note: late-bound region is '?4 diff --git a/tests/ui/nll/closure-requirements/return-wrong-bound-region.stderr b/tests/ui/nll/closure-requirements/return-wrong-bound-region.stderr index bc5c04a27a3e..1f1cce1e8854 100644 --- a/tests/ui/nll/closure-requirements/return-wrong-bound-region.stderr +++ b/tests/ui/nll/closure-requirements/return-wrong-bound-region.stderr @@ -9,6 +9,8 @@ LL | expect_sig(|a, b| b); // ought to return `a` for extern "rust-call" fn((&'^0 i32, &'^1 i32)) -> &'^0 i32, (), ] + = note: late-bound region is '?1 + = note: late-bound region is '?2 error: lifetime may not live long enough --> $DIR/return-wrong-bound-region.rs:11:23 diff --git a/tests/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr b/tests/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr index e58764354c03..396e149554ce 100644 --- a/tests/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr +++ b/tests/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr @@ -9,6 +9,8 @@ LL | twice(cell, value, |a, b| invoke(a, b)); for extern "rust-call" fn((std::option::Option>, &'^1 T)), (), ] + = note: late-bound region is '?2 + = note: late-bound region is '?3 = note: number of external vids: 2 = note: where T: '?1 @@ -31,6 +33,8 @@ LL | twice(cell, value, |a, b| invoke(a, b)); for extern "rust-call" fn((std::option::Option>, &'^1 T)), (), ] + = note: late-bound region is '?3 + = note: late-bound region is '?4 = note: late-bound region is '?2 = note: number of external vids: 3 = note: where T: '?1 From 43018d3722254cfea4ce553309d8909f8b5aaa2d Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Tue, 22 Jul 2025 13:22:00 +0000 Subject: [PATCH 311/809] Free disk space on Windows 2025 runners --- .github/workflows/ci.yml | 9 +- src/ci/github-actions/jobs.yml | 13 +- src/ci/scripts/free-disk-space-linux.sh | 265 ++++++++++++++++++++ src/ci/scripts/free-disk-space-windows.ps1 | 35 +++ src/ci/scripts/free-disk-space.sh | 268 +-------------------- 5 files changed, 316 insertions(+), 274 deletions(-) create mode 100755 src/ci/scripts/free-disk-space-linux.sh create mode 100644 src/ci/scripts/free-disk-space-windows.ps1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc8ac539a3a0..ac73bcabb977 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -117,7 +117,7 @@ jobs: with: fetch-depth: 2 - # Free up disk space on Linux by removing preinstalled components that + # Free up disk space on Linux and Windows by removing preinstalled components that # we do not need. We do this to enable some of the less resource # intensive jobs to run on free runners, which however also have # less disk space. @@ -125,6 +125,13 @@ jobs: run: src/ci/scripts/free-disk-space.sh if: matrix.free_disk + # If we don't need to free up disk space then just report how much space we have + - name: print disk usage + run: | + echo "disk usage:" + df -h + if: matrix.free_disk == false + # Rust Log Analyzer can't currently detect the PR number of a GitHub # Actions build on its own, so a hint in the log message is needed to # point it in the right direction. diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml index 0a6ebe44b3d7..541272dc9375 100644 --- a/src/ci/github-actions/jobs.yml +++ b/src/ci/github-actions/jobs.yml @@ -31,20 +31,11 @@ runners: <<: *base-job - &job-windows - os: windows-2022 - <<: *base-job - - # NOTE: windows-2025 has less disk space available than windows-2022, - # because the D drive is missing. - - &job-windows-25 os: windows-2025 + free_disk: true <<: *base-job - &job-windows-8c - os: windows-2022-8core-32gb - <<: *base-job - - - &job-windows-25-8c os: windows-2025-8core-32gb <<: *base-job @@ -655,7 +646,7 @@ auto: SCRIPT: python x.py build --set rust.debug=true opt-dist && PGO_HOST=x86_64-pc-windows-msvc ./build/x86_64-pc-windows-msvc/stage0-tools-bin/opt-dist windows-ci -- python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 CODEGEN_BACKENDS: llvm,cranelift - <<: *job-windows-25-8c + <<: *job-windows-8c - name: dist-i686-msvc env: diff --git a/src/ci/scripts/free-disk-space-linux.sh b/src/ci/scripts/free-disk-space-linux.sh new file mode 100755 index 000000000000..32649fe0d9b3 --- /dev/null +++ b/src/ci/scripts/free-disk-space-linux.sh @@ -0,0 +1,265 @@ +#!/bin/bash +set -euo pipefail + +# Free disk space on Linux GitHub action runners +# Script inspired by https://github.com/jlumbroso/free-disk-space + +isX86() { + local arch + arch=$(uname -m) + if [ "$arch" = "x86_64" ]; then + return 0 + else + return 1 + fi +} + +# Check if we're on a GitHub hosted runner. +# In aws codebuild, the variable RUNNER_ENVIRONMENT is "self-hosted". +isGitHubRunner() { + # `:-` means "use the value of RUNNER_ENVIRONMENT if it exists, otherwise use an empty string". + if [[ "${RUNNER_ENVIRONMENT:-}" == "github-hosted" ]]; then + return 0 + else + return 1 + fi +} + +# print a line of the specified character +printSeparationLine() { + for ((i = 0; i < 80; i++)); do + printf "%s" "$1" + done + printf "\n" +} + +# compute available space +# REF: https://unix.stackexchange.com/a/42049/60849 +# REF: https://stackoverflow.com/a/450821/408734 +getAvailableSpace() { + df -a | awk 'NR > 1 {avail+=$4} END {print avail}' +} + +# make Kb human readable (assume the input is Kb) +# REF: https://unix.stackexchange.com/a/44087/60849 +formatByteCount() { + numfmt --to=iec-i --suffix=B --padding=7 "${1}000" +} + +# macro to output saved space +printSavedSpace() { + # Disk space before the operation + local before=${1} + local title=${2:-} + + local after + after=$(getAvailableSpace) + local saved=$((after - before)) + + if [ "$saved" -lt 0 ]; then + echo "::warning::Saved space is negative: $saved. Using '0' as saved space." + saved=0 + fi + + echo "" + printSeparationLine "*" + if [ -n "${title}" ]; then + echo "=> ${title}: Saved $(formatByteCount "$saved")" + else + echo "=> Saved $(formatByteCount "$saved")" + fi + printSeparationLine "*" + echo "" +} + +# macro to print output of df with caption +printDF() { + local caption=${1} + + printSeparationLine "=" + echo "${caption}" + echo "" + echo "$ df -h" + echo "" + df -h + printSeparationLine "=" +} + +removeUnusedFilesAndDirs() { + local to_remove=( + "/usr/share/java" + ) + + if isGitHubRunner; then + to_remove+=( + "/usr/local/aws-sam-cli" + "/usr/local/doc/cmake" + "/usr/local/julia"* + "/usr/local/lib/android" + "/usr/local/share/chromedriver-"* + "/usr/local/share/chromium" + "/usr/local/share/cmake-"* + "/usr/local/share/edge_driver" + "/usr/local/share/emacs" + "/usr/local/share/gecko_driver" + "/usr/local/share/icons" + "/usr/local/share/powershell" + "/usr/local/share/vcpkg" + "/usr/local/share/vim" + "/usr/share/apache-maven-"* + "/usr/share/gradle-"* + "/usr/share/kotlinc" + "/usr/share/miniconda" + "/usr/share/php" + "/usr/share/ri" + "/usr/share/swift" + + # binaries + "/usr/local/bin/azcopy" + "/usr/local/bin/bicep" + "/usr/local/bin/ccmake" + "/usr/local/bin/cmake-"* + "/usr/local/bin/cmake" + "/usr/local/bin/cpack" + "/usr/local/bin/ctest" + "/usr/local/bin/helm" + "/usr/local/bin/kind" + "/usr/local/bin/kustomize" + "/usr/local/bin/minikube" + "/usr/local/bin/packer" + "/usr/local/bin/phpunit" + "/usr/local/bin/pulumi-"* + "/usr/local/bin/pulumi" + "/usr/local/bin/stack" + + # Haskell runtime + "/usr/local/.ghcup" + + # Azure + "/opt/az" + "/usr/share/az_"* + ) + + if [ -n "${AGENT_TOOLSDIRECTORY:-}" ]; then + # Environment variable set by GitHub Actions + to_remove+=( + "${AGENT_TOOLSDIRECTORY}" + ) + else + echo "::warning::AGENT_TOOLSDIRECTORY is not set. Skipping removal." + fi + else + # Remove folders and files present in AWS CodeBuild + to_remove+=( + # binaries + "/usr/local/bin/ecs-cli" + "/usr/local/bin/eksctl" + "/usr/local/bin/kubectl" + + "${HOME}/.gradle" + "${HOME}/.dotnet" + "${HOME}/.goenv" + "${HOME}/.phpenv" + + ) + fi + + for element in "${to_remove[@]}"; do + if [ ! -e "$element" ]; then + # The file or directory doesn't exist. + # Maybe it was removed in a newer version of the runner or it's not present in a + # specific architecture (e.g. ARM). + echo "::warning::Directory or file $element does not exist, skipping." + fi + done + + # Remove all files and directories at once to save time. + sudo rm -rf "${to_remove[@]}" +} + +execAndMeasureSpaceChange() { + local operation=${1} # Function to execute + local title=${2} + + local before + before=$(getAvailableSpace) + $operation + + printSavedSpace "$before" "$title" +} + +# Remove large packages +# REF: https://github.com/apache/flink/blob/master/tools/azure-pipelines/free_disk_space.sh +cleanPackages() { + local packages=( + '^aspnetcore-.*' + '^dotnet-.*' + '^llvm-.*' + '^mongodb-.*' + 'firefox' + 'libgl1-mesa-dri' + 'mono-devel' + 'php.*' + ) + + if isGitHubRunner; then + packages+=( + azure-cli + ) + + if isX86; then + packages+=( + 'google-chrome-stable' + 'google-cloud-cli' + 'google-cloud-sdk' + 'powershell' + ) + fi + else + packages+=( + 'google-chrome-stable' + ) + fi + + sudo apt-get -qq remove -y --fix-missing "${packages[@]}" + + sudo apt-get autoremove -y || echo "::warning::The command [sudo apt-get autoremove -y] failed" + sudo apt-get clean || echo "::warning::The command [sudo apt-get clean] failed failed" +} + +# Remove Docker images. +# Ubuntu 22 runners have docker images already installed. +# They aren't present in ubuntu 24 runners. +cleanDocker() { + echo "=> Removing the following docker images:" + sudo docker image ls + echo "=> Removing docker images..." + sudo docker image prune --all --force || true +} + +# Remove Swap storage +cleanSwap() { + sudo swapoff -a || true + sudo rm -rf /mnt/swapfile || true + free -h +} + +# Display initial disk space stats + +AVAILABLE_INITIAL=$(getAvailableSpace) + +printDF "BEFORE CLEAN-UP:" +echo "" +execAndMeasureSpaceChange cleanPackages "Unused packages" +execAndMeasureSpaceChange cleanDocker "Docker images" +execAndMeasureSpaceChange cleanSwap "Swap storage" +execAndMeasureSpaceChange removeUnusedFilesAndDirs "Unused files and directories" + +# Output saved space statistic +echo "" +printDF "AFTER CLEAN-UP:" + +echo "" +echo "" + +printSavedSpace "$AVAILABLE_INITIAL" "Total saved" diff --git a/src/ci/scripts/free-disk-space-windows.ps1 b/src/ci/scripts/free-disk-space-windows.ps1 new file mode 100644 index 000000000000..8a4677bd2ab4 --- /dev/null +++ b/src/ci/scripts/free-disk-space-windows.ps1 @@ -0,0 +1,35 @@ +# Free disk space on Windows GitHub action runners. + +$ErrorActionPreference = 'Stop' + +Get-Volume | Out-String | Write-Output + +$available = $(Get-Volume C).SizeRemaining + +$dirs = 'C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\Llvm', +'C:\rtools45', 'C:\ghcup', 'C:\Program Files (x86)\Android', +'C:\Program Files\Google\Chrome', 'C:\Program Files (x86)\Microsoft\Edge', +'C:\Program Files\Mozilla Firefox', 'C:\Program Files\MySQL', 'C:\Julia', +'C:\Program Files\MongoDB', 'C:\Program Files\Azure Cosmos DB Emulator', +'C:\Program Files\PostgreSQL', 'C:\Program Files\Unity Hub', +'C:\Strawberry', 'C:\hostedtoolcache\windows\Java_Temurin-Hotspot_jdk' + +foreach ($dir in $dirs) { + Start-ThreadJob -InputObject $dir { + Remove-Item -Recurse -Force -LiteralPath $input + } | Out-Null +} + +foreach ($job in Get-Job) { + Wait-Job $job | Out-Null + if ($job.Error) { + Write-Output "::warning file=$PSCommandPath::$($job.Error)" + } + Remove-Job $job +} + +Get-Volume | Out-String | Write-Output + +$saved = ($(Get-Volume C).SizeRemaining - $available) / 1gb +$savedRounded = [math]::Round($saved, 3) +Write-Output "total space saved: $savedRounded GB" diff --git a/src/ci/scripts/free-disk-space.sh b/src/ci/scripts/free-disk-space.sh index 173f64858b37..062ad801cd8d 100755 --- a/src/ci/scripts/free-disk-space.sh +++ b/src/ci/scripts/free-disk-space.sh @@ -1,266 +1,10 @@ #!/bin/bash set -euo pipefail -# Free disk space on Linux GitHub action runners -# Script inspired by https://github.com/jlumbroso/free-disk-space +script_dir=$(dirname "$0") -isX86() { - local arch - arch=$(uname -m) - if [ "$arch" = "x86_64" ]; then - return 0 - else - return 1 - fi -} - -# Check if we're on a GitHub hosted runner. -# In aws codebuild, the variable RUNNER_ENVIRONMENT is "self-hosted". -isGitHubRunner() { - # `:-` means "use the value of RUNNER_ENVIRONMENT if it exists, otherwise use an empty string". - if [[ "${RUNNER_ENVIRONMENT:-}" == "github-hosted" ]]; then - return 0 - else - return 1 - fi -} - -# print a line of the specified character -printSeparationLine() { - for ((i = 0; i < 80; i++)); do - printf "%s" "$1" - done - printf "\n" -} - -# compute available space -# REF: https://unix.stackexchange.com/a/42049/60849 -# REF: https://stackoverflow.com/a/450821/408734 -getAvailableSpace() { - df -a | awk 'NR > 1 {avail+=$4} END {print avail}' -} - -# make Kb human readable (assume the input is Kb) -# REF: https://unix.stackexchange.com/a/44087/60849 -formatByteCount() { - numfmt --to=iec-i --suffix=B --padding=7 "${1}000" -} - -# macro to output saved space -printSavedSpace() { - # Disk space before the operation - local before=${1} - local title=${2:-} - - local after - after=$(getAvailableSpace) - local saved=$((after - before)) - - if [ "$saved" -lt 0 ]; then - echo "::warning::Saved space is negative: $saved. Using '0' as saved space." - saved=0 - fi - - echo "" - printSeparationLine "*" - if [ -n "${title}" ]; then - echo "=> ${title}: Saved $(formatByteCount "$saved")" - else - echo "=> Saved $(formatByteCount "$saved")" - fi - printSeparationLine "*" - echo "" -} - -# macro to print output of df with caption -printDF() { - local caption=${1} - - printSeparationLine "=" - echo "${caption}" - echo "" - echo "$ df -h" - echo "" - df -h - printSeparationLine "=" -} - -removeUnusedFilesAndDirs() { - local to_remove=( - "/usr/share/java" - ) - - if isGitHubRunner; then - to_remove+=( - "/usr/local/aws-sam-cli" - "/usr/local/doc/cmake" - "/usr/local/julia"* - "/usr/local/lib/android" - "/usr/local/share/chromedriver-"* - "/usr/local/share/chromium" - "/usr/local/share/cmake-"* - "/usr/local/share/edge_driver" - "/usr/local/share/emacs" - "/usr/local/share/gecko_driver" - "/usr/local/share/icons" - "/usr/local/share/powershell" - "/usr/local/share/vcpkg" - "/usr/local/share/vim" - "/usr/share/apache-maven-"* - "/usr/share/gradle-"* - "/usr/share/kotlinc" - "/usr/share/miniconda" - "/usr/share/php" - "/usr/share/ri" - "/usr/share/swift" - - # binaries - "/usr/local/bin/azcopy" - "/usr/local/bin/bicep" - "/usr/local/bin/ccmake" - "/usr/local/bin/cmake-"* - "/usr/local/bin/cmake" - "/usr/local/bin/cpack" - "/usr/local/bin/ctest" - "/usr/local/bin/helm" - "/usr/local/bin/kind" - "/usr/local/bin/kustomize" - "/usr/local/bin/minikube" - "/usr/local/bin/packer" - "/usr/local/bin/phpunit" - "/usr/local/bin/pulumi-"* - "/usr/local/bin/pulumi" - "/usr/local/bin/stack" - - # Haskell runtime - "/usr/local/.ghcup" - - # Azure - "/opt/az" - "/usr/share/az_"* - ) - - if [ -n "${AGENT_TOOLSDIRECTORY:-}" ]; then - # Environment variable set by GitHub Actions - to_remove+=( - "${AGENT_TOOLSDIRECTORY}" - ) - else - echo "::warning::AGENT_TOOLSDIRECTORY is not set. Skipping removal." - fi - else - # Remove folders and files present in AWS CodeBuild - to_remove+=( - # binaries - "/usr/local/bin/ecs-cli" - "/usr/local/bin/eksctl" - "/usr/local/bin/kubectl" - - "${HOME}/.gradle" - "${HOME}/.dotnet" - "${HOME}/.goenv" - "${HOME}/.phpenv" - - ) - fi - - for element in "${to_remove[@]}"; do - if [ ! -e "$element" ]; then - # The file or directory doesn't exist. - # Maybe it was removed in a newer version of the runner or it's not present in a - # specific architecture (e.g. ARM). - echo "::warning::Directory or file $element does not exist, skipping." - fi - done - - # Remove all files and directories at once to save time. - sudo rm -rf "${to_remove[@]}" -} - -execAndMeasureSpaceChange() { - local operation=${1} # Function to execute - local title=${2} - - local before - before=$(getAvailableSpace) - $operation - - printSavedSpace "$before" "$title" -} - -# Remove large packages -# REF: https://github.com/apache/flink/blob/master/tools/azure-pipelines/free_disk_space.sh -cleanPackages() { - local packages=( - '^aspnetcore-.*' - '^dotnet-.*' - '^llvm-.*' - '^mongodb-.*' - 'firefox' - 'libgl1-mesa-dri' - 'mono-devel' - 'php.*' - ) - - if isGitHubRunner; then - packages+=( - azure-cli - ) - - if isX86; then - packages+=( - 'google-chrome-stable' - 'google-cloud-cli' - 'google-cloud-sdk' - 'powershell' - ) - fi - else - packages+=( - 'google-chrome-stable' - ) - fi - - sudo apt-get -qq remove -y --fix-missing "${packages[@]}" - - sudo apt-get autoremove -y || echo "::warning::The command [sudo apt-get autoremove -y] failed" - sudo apt-get clean || echo "::warning::The command [sudo apt-get clean] failed failed" -} - -# Remove Docker images. -# Ubuntu 22 runners have docker images already installed. -# They aren't present in ubuntu 24 runners. -cleanDocker() { - echo "=> Removing the following docker images:" - sudo docker image ls - echo "=> Removing docker images..." - sudo docker image prune --all --force || true -} - -# Remove Swap storage -cleanSwap() { - sudo swapoff -a || true - sudo rm -rf /mnt/swapfile || true - free -h -} - -# Display initial disk space stats - -AVAILABLE_INITIAL=$(getAvailableSpace) - -printDF "BEFORE CLEAN-UP:" -echo "" - -execAndMeasureSpaceChange cleanPackages "Unused packages" -execAndMeasureSpaceChange cleanDocker "Docker images" -execAndMeasureSpaceChange cleanSwap "Swap storage" -execAndMeasureSpaceChange removeUnusedFilesAndDirs "Unused files and directories" - -# Output saved space statistic -echo "" -printDF "AFTER CLEAN-UP:" - -echo "" -echo "" - -printSavedSpace "$AVAILABLE_INITIAL" "Total saved" +if [[ "${RUNNER_OS:-}" == "Windows" ]]; then + pwsh $script_dir/free-disk-space-windows.ps1 +else + $script_dir/free-disk-space-linux.sh +fi From 21af1549988d7194b9daeb6882a5582a980d892e Mon Sep 17 00:00:00 2001 From: David Tenty Date: Wed, 30 Jul 2025 00:39:43 -0400 Subject: [PATCH 312/809] [test][run-make] add needs-llvm-components Add some constraints to run-make tests that require specific target support and will fail without them. --- tests/run-make/link-cfg/rmake.rs | 1 + tests/run-make/mismatching-target-triples/rmake.rs | 1 + tests/run-make/musl-default-linking/rmake.rs | 1 + tests/run-make/rustdoc-target-spec-json-path/rmake.rs | 1 + tests/run-make/target-specs/rmake.rs | 1 + 5 files changed, 5 insertions(+) diff --git a/tests/run-make/link-cfg/rmake.rs b/tests/run-make/link-cfg/rmake.rs index 732de5dbd0b8..18577fb836dd 100644 --- a/tests/run-make/link-cfg/rmake.rs +++ b/tests/run-make/link-cfg/rmake.rs @@ -12,6 +12,7 @@ //@ ignore-cross-compile // Reason: the compiled binary is executed +//@ needs-llvm-components: x86 use run_make_support::{bare_rustc, build_native_dynamic_lib, build_native_static_lib, run, rustc}; diff --git a/tests/run-make/mismatching-target-triples/rmake.rs b/tests/run-make/mismatching-target-triples/rmake.rs index 6f41eac8cdaf..1bbe945e0da5 100644 --- a/tests/run-make/mismatching-target-triples/rmake.rs +++ b/tests/run-make/mismatching-target-triples/rmake.rs @@ -4,6 +4,7 @@ // now replaced by a clearer normal error message. This test checks that this aforementioned // error message is used. // See https://github.com/rust-lang/rust/issues/10814 +//@ needs-llvm-components: x86 use run_make_support::rustc; diff --git a/tests/run-make/musl-default-linking/rmake.rs b/tests/run-make/musl-default-linking/rmake.rs index 017444cfcddc..7bb54e2739c9 100644 --- a/tests/run-make/musl-default-linking/rmake.rs +++ b/tests/run-make/musl-default-linking/rmake.rs @@ -4,6 +4,7 @@ use run_make_support::{rustc, serde_json}; // Per https://github.com/rust-lang/compiler-team/issues/422, // we should be trying to move these targets to dynamically link // musl libc by default. +//@ needs-llvm-components: aarch64 arm mips powerpc riscv systemz x86 static LEGACY_STATIC_LINKING_TARGETS: &[&'static str] = &[ "aarch64-unknown-linux-musl", "arm-unknown-linux-musleabi", diff --git a/tests/run-make/rustdoc-target-spec-json-path/rmake.rs b/tests/run-make/rustdoc-target-spec-json-path/rmake.rs index fe9587f50222..d43aa9b90ac7 100644 --- a/tests/run-make/rustdoc-target-spec-json-path/rmake.rs +++ b/tests/run-make/rustdoc-target-spec-json-path/rmake.rs @@ -1,4 +1,5 @@ // Test that rustdoc will properly canonicalize the target spec json path just like rustc. +//@ needs-llvm-components: x86 use run_make_support::{cwd, rustc, rustdoc}; diff --git a/tests/run-make/target-specs/rmake.rs b/tests/run-make/target-specs/rmake.rs index 9184e5f772f7..398f6bddc91b 100644 --- a/tests/run-make/target-specs/rmake.rs +++ b/tests/run-make/target-specs/rmake.rs @@ -4,6 +4,7 @@ // with the target flag's bundle of new features to check that compilation either succeeds while // using them correctly, or fails with the right error message when using them improperly. // See https://github.com/rust-lang/rust/pull/16156 +//@ needs-llvm-components: x86 use run_make_support::{diff, rfs, rustc}; From e8db4aa4706a4fdfc9a2cbf32a3cbbd11a6d14d1 Mon Sep 17 00:00:00 2001 From: Tom Webber Date: Mon, 14 Jul 2025 20:24:54 +0200 Subject: [PATCH 313/809] 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 314/809] 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 4220587c2232e237a0c39a2c64b0bf046799434a Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Tue, 29 Jul 2025 18:30:48 -0700 Subject: [PATCH 315/809] `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 316/809] 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 317/809] 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 318/809] 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 @@ git history. import json import os +import pprint import re import subprocess as sp import sys @@ -50,15 +51,6 @@ GIT = ["git", "-C", REPO_ROOT] 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 @@ class PrInfo: ], 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 @@ class Context: 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 @@ class Context: 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 319/809] 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 @@ class Context: 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 320/809] 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 re 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 @@ IGNORE_FILES = [ # 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 @@ class Context: """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 321/809] 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 @@ class PrCfg: 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 @@ class Context: 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 322/809] 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 323/809] 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 0cf6eb5f7521d37213576e8b48b574defa1e49f0 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 30 Jul 2025 19:54:16 +0800 Subject: [PATCH 324/809] Introduce proper `build.compiletest-allow-stage0` config option In favor of the adhoc `COMPILETEST_FORCE_STAGE0` env var. --- bootstrap.example.toml | 5 +++++ src/bootstrap/src/core/build_steps/test.rs | 11 +++++------ src/bootstrap/src/core/config/config.rs | 13 +++++++++++++ src/bootstrap/src/core/config/toml/build.rs | 1 + 4 files changed, 24 insertions(+), 6 deletions(-) diff --git a/bootstrap.example.toml b/bootstrap.example.toml index ef49113b70f4..31966af33012 100644 --- a/bootstrap.example.toml +++ b/bootstrap.example.toml @@ -465,6 +465,11 @@ # What custom diff tool to use for displaying compiletest tests. #build.compiletest-diff-tool = +# Whether to allow `compiletest` self-tests and `compiletest`-managed test +# suites to be run against the stage 0 rustc. This is only intended to be used +# when the stage 0 compiler is actually built from in-tree sources. +#build.compiletest-allow-stage0 = false + # Whether to use the precompiled stage0 libtest with compiletest. #build.compiletest-use-stage0-libtest = true diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 0f9268097d7b..3f62f8b20138 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -723,8 +723,8 @@ impl Step for CompiletestTest { let mut cargo = tool::prepare_tool_cargo( builder, compiler, - // compiletest uses libtest internals; make it use the in-tree std to make sure it never breaks - // when std sources change. + // compiletest uses libtest internals; make it use the in-tree std to make sure it never + // breaks when std sources change. Mode::ToolStd, host, Kind::Test, @@ -1612,12 +1612,11 @@ impl Step for Compiletest { return; } - if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() { + if builder.top_stage == 0 && !builder.config.compiletest_allow_stage0 { eprintln!("\ ERROR: `--stage 0` runs compiletest on the stage0 (precompiled) compiler, not your local changes, and will almost always cause tests to fail -HELP: to test the compiler, use `--stage 1` instead -HELP: to test the standard library, use `--stage 0 library/std` instead -NOTE: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `COMPILETEST_FORCE_STAGE0=1`." +HELP: to test the compiler or standard library, omit the stage or explicitly use `--stage 1` instead +NOTE: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `--set build.compiletest-allow-stage0=true`." ); crate::exit!(1); } diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 9644ade00b34..78abdd7f9b8c 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -298,8 +298,16 @@ pub struct Config { /// Command for visual diff display, e.g. `diff-tool --color=always`. pub compiletest_diff_tool: Option, + /// Whether to allow running both `compiletest` self-tests and `compiletest`-managed test suites + /// against the stage 0 (rustc, std). + /// + /// This is only intended to be used when the stage 0 compiler is actually built from in-tree + /// sources. + pub compiletest_allow_stage0: bool, + /// Whether to use the precompiled stage0 libtest with compiletest. pub compiletest_use_stage0_libtest: bool, + /// Default value for `--extra-checks` pub tidy_extra_checks: Option, pub is_running_on_ci: bool, @@ -749,6 +757,7 @@ impl Config { optimized_compiler_builtins, jobs, compiletest_diff_tool, + compiletest_allow_stage0, compiletest_use_stage0_libtest, tidy_extra_checks, ccache, @@ -1020,8 +1029,12 @@ 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; let download_rustc = config.download_rustc_commit.is_some(); diff --git a/src/bootstrap/src/core/config/toml/build.rs b/src/bootstrap/src/core/config/toml/build.rs index 4d29691f38b6..728367b39729 100644 --- a/src/bootstrap/src/core/config/toml/build.rs +++ b/src/bootstrap/src/core/config/toml/build.rs @@ -68,6 +68,7 @@ define_config! { optimized_compiler_builtins: Option = "optimized-compiler-builtins", jobs: Option = "jobs", compiletest_diff_tool: Option = "compiletest-diff-tool", + compiletest_allow_stage0: Option = "compiletest-allow-stage0", compiletest_use_stage0_libtest: Option = "compiletest-use-stage0-libtest", tidy_extra_checks: Option = "tidy-extra-checks", ccache: Option = "ccache", From a7fcc738c98d04ea5b504719555478becbba3dce Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 30 Jul 2025 16:27:33 +0800 Subject: [PATCH 325/809] Update `codegen_{cranelift,gcc}` and `opt-dist` to use `build.compiletest-allow-stage0` --- .../rustc_codegen_cranelift/scripts/setup_rust_fork.sh | 1 + .../rustc_codegen_cranelift/scripts/test_rustc_tests.sh | 2 +- compiler/rustc_codegen_gcc/build_system/src/test.rs | 7 ++++--- src/tools/opt-dist/src/tests.rs | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/scripts/setup_rust_fork.sh b/compiler/rustc_codegen_cranelift/scripts/setup_rust_fork.sh index 532702bb1a46..492f4dc44527 100644 --- a/compiler/rustc_codegen_cranelift/scripts/setup_rust_fork.sh +++ b/compiler/rustc_codegen_cranelift/scripts/setup_rust_fork.sh @@ -33,6 +33,7 @@ rustc = "$(pwd)/../dist/bin/rustc-clif" cargo = "$(rustup which cargo)" full-bootstrap = true local-rebuild = true +compiletest-allow-stage0 = true [rust] download-rustc = false diff --git a/compiler/rustc_codegen_cranelift/scripts/test_rustc_tests.sh b/compiler/rustc_codegen_cranelift/scripts/test_rustc_tests.sh index 7e356b4b462b..52e02c857c7a 100755 --- a/compiler/rustc_codegen_cranelift/scripts/test_rustc_tests.sh +++ b/compiler/rustc_codegen_cranelift/scripts/test_rustc_tests.sh @@ -166,5 +166,5 @@ index 073116933bd..c3e4578204d 100644 EOF echo "[TEST] rustc test suite" -COMPILETEST_FORCE_STAGE0=1 ./x.py test --stage 0 --test-args=--no-capture tests/{codegen-units,run-make,ui,incremental} +./x.py test --stage 0 --test-args=--no-capture tests/{codegen-units,run-make,ui,incremental} popd diff --git a/compiler/rustc_codegen_gcc/build_system/src/test.rs b/compiler/rustc_codegen_gcc/build_system/src/test.rs index bc0fdd40b6e8..2c8271c36a94 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/test.rs +++ b/compiler/rustc_codegen_gcc/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, diff --git a/src/tools/opt-dist/src/tests.rs b/src/tools/opt-dist/src/tests.rs index c9a21fc6fb29..d5121b8c7869 100644 --- a/src/tools/opt-dist/src/tests.rs +++ b/src/tools/opt-dist/src/tests.rs @@ -79,6 +79,7 @@ lld = false rustc = "{rustc}" cargo = "{cargo}" local-rebuild = true +compiletest-allow-stage0=true [target.{host_triple}] llvm-config = "{llvm_config}" @@ -117,7 +118,6 @@ llvm-config = "{llvm_config}" args.extend(["--skip", test_path]); } cmd(&args) - .env("COMPILETEST_FORCE_STAGE0", "1") // Also run dist-only tests .env("COMPILETEST_ENABLE_DIST_TESTS", "1") .run() From 4f8d4ca1908e6179c4094d5843db6a29cb323d4d Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 30 Jul 2025 16:27:33 +0800 Subject: [PATCH 326/809] 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 2033a06d7fb1970794998331dd8747e19caaa6e7 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 30 Jul 2025 19:54:47 +0800 Subject: [PATCH 327/809] Deny `compiletest` self-tests being run against stage 0 rustc unless explicitly allowed Otherwise, `compiletest` would have to know e.g. how to parse two different target spec, if target spec format was changed between beta `rustc` and in-tree `rustc`. --- src/bootstrap/src/core/build_steps/test.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 3f62f8b20138..951ca73fcc49 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -8,6 +8,9 @@ use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::{env, fs, iter}; +#[cfg(feature = "tracing")] +use tracing::instrument; + use crate::core::build_steps::compile::{Std, run_cargo}; use crate::core::build_steps::doc::DocumentationFormat; use crate::core::build_steps::gcc::{Gcc, add_cg_gcc_cargo_flags}; @@ -30,7 +33,7 @@ use crate::utils::helpers::{ 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, DocTests, GitRepo, Mode, PathSet, envify}; +use crate::{CLang, DocTests, GitRepo, Mode, PathSet, debug, envify}; const ADB_TEST_DIR: &str = "/data/local/tmp/work"; @@ -713,9 +716,23 @@ impl Step for CompiletestTest { } /// Runs `cargo test` for compiletest. + #[cfg_attr( + feature = "tracing", + instrument(level = "debug", name = "CompiletestTest::run", skip_all) + )] fn run(self, builder: &Builder<'_>) { let host = self.host; + + if builder.top_stage == 0 && !builder.config.compiletest_allow_stage0 { + eprintln!("\ +ERROR: `--stage 0` runs compiletest self-tests against the stage0 (precompiled) compiler, not the in-tree compiler, and will almost always cause tests to fail +NOTE: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `--set build.compiletest-allow-stage0=true`." + ); + crate::exit!(1); + } + let compiler = builder.compiler(builder.top_stage, host); + debug!(?compiler); // We need `ToolStd` for the locally-built sysroot because // compiletest uses unstable features of the `test` crate. From 2cdd19384ff21a6a4f8377e7ec9aab43b7c9f675 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 30 Jul 2025 16:21:17 +0800 Subject: [PATCH 328/809] Run `compiletest` self-tests against stage 1 rustc And move `./x test compiletest --stage=1` to `pr-check-2`, where testing library artifacts already requires building the stage 1 compiler. --- src/ci/docker/host-x86_64/pr-check-1/Dockerfile | 1 - src/ci/docker/host-x86_64/pr-check-2/Dockerfile | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ci/docker/host-x86_64/pr-check-1/Dockerfile b/src/ci/docker/host-x86_64/pr-check-1/Dockerfile index f7d51fba861e..04ac0f33daf0 100644 --- a/src/ci/docker/host-x86_64/pr-check-1/Dockerfile +++ b/src/ci/docker/host-x86_64/pr-check-1/Dockerfile @@ -43,7 +43,6 @@ ENV SCRIPT \ python3 ../x.py check bootstrap && \ /scripts/check-default-config-profiles.sh && \ python3 ../x.py build src/tools/build-manifest && \ - python3 ../x.py test --stage 0 src/tools/compiletest && \ python3 ../x.py check compiletest --set build.compiletest-use-stage0-libtest=true && \ python3 ../x.py check --target=i686-pc-windows-gnu --host=i686-pc-windows-gnu && \ python3 ../x.py check --set build.optimized-compiler-builtins=false core alloc std --target=aarch64-unknown-linux-gnu,i686-pc-windows-msvc,i686-unknown-linux-gnu,x86_64-apple-darwin,x86_64-pc-windows-gnu,x86_64-pc-windows-msvc && \ diff --git a/src/ci/docker/host-x86_64/pr-check-2/Dockerfile b/src/ci/docker/host-x86_64/pr-check-2/Dockerfile index ce18a181d313..f82e19bcbb47 100644 --- a/src/ci/docker/host-x86_64/pr-check-2/Dockerfile +++ b/src/ci/docker/host-x86_64/pr-check-2/Dockerfile @@ -30,6 +30,7 @@ ENV SCRIPT \ python3 ../x.py check && \ python3 ../x.py clippy ci && \ python3 ../x.py test --stage 1 core alloc std test proc_macro && \ + python3 ../x.py test --stage 1 src/tools/compiletest && \ python3 ../x.py doc --stage 0 bootstrap && \ # Build both public and internal documentation. RUSTDOCFLAGS=\"--document-private-items --document-hidden-items\" python3 ../x.py doc --stage 0 compiler && \ @@ -37,6 +38,6 @@ ENV SCRIPT \ mkdir -p /checkout/obj/staging/doc && \ cp -r build/x86_64-unknown-linux-gnu/doc /checkout/obj/staging && \ RUSTDOCFLAGS=\"--document-private-items --document-hidden-items\" python3 ../x.py doc --stage 1 library/test && \ - # The BOOTSTRAP_TRACING flag is added to verify whether the + # The BOOTSTRAP_TRACING flag is added to verify whether the # bootstrap process compiles successfully with this flag enabled. BOOTSTRAP_TRACING=1 python3 ../x.py --help From e954253d43d361845c248860e4aa521b90bf6443 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 30 Jul 2025 16:24:32 +0800 Subject: [PATCH 329/809] Add change tracker entry --- src/bootstrap/src/utils/change_tracker.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 4b0c48213648..d3331b81587e 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -486,4 +486,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Warning, summary: "Removed `rust.description` and `llvm.ccache` as it was deprecated in #137723 and #136941 long time ago.", }, + ChangeInfo { + change_id: 144675, + severity: ChangeSeverity::Warning, + summary: "Added `build.compiletest-allow-stage0` flag instead of `COMPILETEST_FORCE_STAGE0` env var, and reject running `compiletest` self tests against stage 0 rustc unless explicitly allowed.", + }, ]; From b6cbe33aeb526d6437304f4810762c947bddcd4a Mon Sep 17 00:00:00 2001 From: lcnr Date: Fri, 25 Jul 2025 12:38:54 +0000 Subject: [PATCH 330/809] handle region dependent goals due to infer vars --- compiler/rustc_hir_typeck/src/lib.rs | 17 +++++- compiler/rustc_infer/src/infer/mod.rs | 57 +++++++++++++------ .../src/infer/outlives/obligations.rs | 1 + .../src/infer/snapshot/undo_log.rs | 8 ++- .../src/solve/fulfill.rs | 12 +++- ...iguity-due-to-uniquification-3.next.stderr | 19 +++++++ .../ambiguity-due-to-uniquification-3.rs | 33 +++++++++++ 7 files changed, 128 insertions(+), 19 deletions(-) create mode 100644 tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-3.next.stderr create mode 100644 tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-3.rs diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 9e324286fa17..b395aa8162c3 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -53,7 +53,7 @@ use rustc_hir_analysis::check::{check_abi, check_custom_abi}; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc}; use rustc_middle::query::Providers; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_session::config; use rustc_span::Span; @@ -259,6 +259,21 @@ fn typeck_with_inspect<'tcx>( let typeck_results = fcx.resolve_type_vars_in_body(body); + // Handle potentially region dependent goals, see `InferCtxt::in_hir_typeck`. + if let None = fcx.infcx.tainted_by_errors() { + for obligation in fcx.take_hir_typeck_potentially_region_dependent_goals() { + let obligation = fcx.resolve_vars_if_possible(obligation); + if obligation.has_non_region_infer() { + bug!("unexpected inference variable after writeback: {obligation:?}"); + } + fcx.register_predicate(obligation); + } + fcx.select_obligations_where_possible(|_| {}); + if let None = fcx.infcx.tainted_by_errors() { + fcx.report_ambiguity_errors(); + } + } + fcx.detect_opaque_types_added_during_writeback(); // Consistency check our TypeckResults instance can hold all ItemLocalIds diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 17c587c5e7fd..5bbd8a84b7f0 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -37,10 +37,11 @@ use snapshot::undo_log::InferCtxtUndoLogs; use tracing::{debug, instrument}; use type_variable::TypeVariableOrigin; -use crate::infer::region_constraints::UndoLog; +use crate::infer::snapshot::undo_log::UndoLog; use crate::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey}; use crate::traits::{ - self, ObligationCause, ObligationInspector, PredicateObligations, TraitEngine, + self, ObligationCause, ObligationInspector, PredicateObligation, PredicateObligations, + TraitEngine, }; pub mod at; @@ -156,6 +157,12 @@ pub struct InferCtxtInner<'tcx> { /// which may cause types to no longer be considered well-formed. region_assumptions: Vec>, + /// `-Znext-solver`: Successfully proven goals during HIR typeck which + /// reference inference variables and get reproven after writeback. + /// + /// See the documentation of `InferCtxt::in_hir_typeck` for more details. + hir_typeck_potentially_region_dependent_goals: Vec>, + /// Caches for opaque type inference. opaque_type_storage: OpaqueTypeStorage<'tcx>, } @@ -173,6 +180,7 @@ impl<'tcx> InferCtxtInner<'tcx> { region_constraint_storage: Some(Default::default()), region_obligations: Default::default(), region_assumptions: Default::default(), + hir_typeck_potentially_region_dependent_goals: Default::default(), opaque_type_storage: Default::default(), } } @@ -247,24 +255,25 @@ pub struct InferCtxt<'tcx> { /// the root universe. Most notably, this is used during HIR typeck as region /// solving is left to borrowck instead. pub considering_regions: bool, - /// Whether this inference context is used by HIR typeck. If so, we uniquify regions - /// with `-Znext-solver`. This is necessary as borrowck will start by replacing each - /// occurance of a free region with a unique inference variable so if HIR typeck - /// ends up depending on two regions being equal we'd get unexpected mismatches - /// between HIR typeck and MIR typeck, resulting in an ICE. + /// `-Znext-solver`: Whether this inference context is used by HIR typeck. If so, we + /// need to make sure we don't rely on region identity in the trait solver or when + /// relating types. This is necessary as borrowck starts by replacing each occurrence of a + /// free region with a unique inference variable. If HIR typeck ends up depending on two + /// regions being equal we'd get unexpected mismatches between HIR typeck and MIR typeck, + /// resulting in an ICE. /// /// The trait solver sometimes depends on regions being identical. As a concrete example /// the trait solver ignores other candidates if one candidate exists without any constraints. - /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now, but if we replace - /// each occurance of `'a` with a unique region the goal now equates these regions. + /// The goal `&'a u32: Equals<&'a u32>` has no constraints right now. If we replace each + /// occurrence of `'a` with a unique region the goal now equates these regions. See + /// the tests in trait-system-refactor-initiative#27 for concrete examples. /// - /// See the tests in trait-system-refactor-initiative#27 for concrete examples. - /// - /// FIXME(-Znext-solver): This is insufficient in theory as a goal `T: Trait` - /// may rely on the two occurances of `?x` being identical. If `?x` gets inferred to a - /// type containing regions, this will no longer be the case. We can handle this case - /// by storing goals which hold while still depending on inference vars and then - /// reproving them before writeback. + /// We handle this by *uniquifying* region when canonicalizing root goals during HIR typeck. + /// This is still insufficient as inference variables may *hide* region variables, so e.g. + /// `dyn TwoSuper: Super` may hold but MIR typeck could end up having to prove + /// `dyn TwoSuper<&'0 (), &'1 ()>: Super<&'2 ()>` which is now ambiguous. Because of this we + /// stash all successfully proven goals which reference inference variables and then reprove + /// them after writeback. pub in_hir_typeck: bool, /// If set, this flag causes us to skip the 'leak check' during @@ -1010,6 +1019,22 @@ impl<'tcx> InferCtxt<'tcx> { } } + pub fn push_hir_typeck_potentially_region_dependent_goal( + &self, + goal: PredicateObligation<'tcx>, + ) { + let mut inner = self.inner.borrow_mut(); + inner.undo_log.push(UndoLog::PushHirTypeckPotentiallyRegionDependentGoal); + inner.hir_typeck_potentially_region_dependent_goals.push(goal); + } + + pub fn take_hir_typeck_potentially_region_dependent_goals( + &self, + ) -> Vec> { + assert!(!self.in_snapshot(), "cannot take goals in a snapshot"); + std::mem::take(&mut self.inner.borrow_mut().hir_typeck_potentially_region_dependent_goals) + } + pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { self.resolve_vars_if_possible(t).to_string() } diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index a8520c0e71dd..bb3b51c0ab2c 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -177,6 +177,7 @@ impl<'tcx> InferCtxt<'tcx> { } pub fn take_registered_region_assumptions(&self) -> Vec> { + assert!(!self.in_snapshot(), "cannot take registered region assumptions in a snapshot"); std::mem::take(&mut self.inner.borrow_mut().region_assumptions) } diff --git a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs index 40e4c329446d..fcc0ab3af410 100644 --- a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs +++ b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs @@ -29,6 +29,7 @@ pub(crate) enum UndoLog<'tcx> { ProjectionCache(traits::UndoLog<'tcx>), PushTypeOutlivesConstraint, PushRegionAssumption, + PushHirTypeckPotentiallyRegionDependentGoal, } macro_rules! impl_from { @@ -79,7 +80,12 @@ impl<'tcx> Rollback> for InferCtxtInner<'tcx> { assert_matches!(popped, Some(_), "pushed region constraint but could not pop it"); } UndoLog::PushRegionAssumption => { - self.region_assumptions.pop(); + let popped = self.region_assumptions.pop(); + assert_matches!(popped, Some(_), "pushed region assumption but could not pop it"); + } + UndoLog::PushHirTypeckPotentiallyRegionDependentGoal => { + let popped = self.hir_typeck_potentially_region_dependent_goals.pop(); + assert_matches!(popped, Some(_), "pushed goal but could not pop it"); } } } diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 70452947a8b5..e0b9380eca32 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -197,6 +197,12 @@ where delegate.compute_goal_fast_path(goal, obligation.cause.span) { match certainty { + // This fast path doesn't depend on region identity so it doesn't + // matter if the goal contains inference variables or not, so we + // don't need to call `push_hir_typeck_potentially_region_dependent_goal` + // here. + // + // Only goals proven via the trait solver should be region dependent. Certainty::Yes => {} Certainty::Maybe(_) => { self.obligations.register(obligation, None); @@ -234,7 +240,11 @@ where } match certainty { - Certainty::Yes => {} + Certainty::Yes => { + if infcx.in_hir_typeck && obligation.has_non_region_infer() { + infcx.push_hir_typeck_potentially_region_dependent_goal(obligation); + } + } Certainty::Maybe(_) => self.obligations.register(obligation, stalled_on), } } diff --git a/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-3.next.stderr b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-3.next.stderr new file mode 100644 index 000000000000..e25f892b3657 --- /dev/null +++ b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-3.next.stderr @@ -0,0 +1,19 @@ +error[E0283]: type annotations needed: cannot satisfy `(dyn Object<&(), &()> + 'static): Trait<&()>` + --> $DIR/ambiguity-due-to-uniquification-3.rs:28:17 + | +LL | impls_trait(obj, t); + | ----------- ^^^ + | | + | required by a bound introduced by this call + | + = note: cannot satisfy `(dyn Object<&(), &()> + 'static): Trait<&()>` + = help: the trait `Trait` is implemented for `()` +note: required by a bound in `impls_trait` + --> $DIR/ambiguity-due-to-uniquification-3.rs:24:19 + | +LL | fn impls_trait, U>(_: Inv, _: Inv) {} + | ^^^^^^^^ required by this bound in `impls_trait` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0283`. diff --git a/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-3.rs b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-3.rs new file mode 100644 index 000000000000..6dcd9d5bdf4d --- /dev/null +++ b/tests/ui/traits/next-solver/assembly/ambiguity-due-to-uniquification-3.rs @@ -0,0 +1,33 @@ +//@ revisions: current next +//@[next] compile-flags: -Znext-solver +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[current] check-pass + +// Regression test from trait-system-refactor-initiative#27. +// +// Unlike in the previous two tests, `dyn Object: Trait` relies +// on structural identity of type inference variables. This inference variable +// gets constrained to a type containing a region later on. To prevent this +// from causing an ICE during MIR borrowck, we stash goals which depend on +// inference variables and then reprove them at the end of HIR typeck. + +#![feature(rustc_attrs)] +#![rustc_no_implicit_bounds] +trait Trait {} +impl Trait for () {} + +trait Object: Trait + Trait {} + +#[derive(Clone, Copy)] +struct Inv(*mut T); +fn foo() -> (Inv>, Inv) { todo!() } +fn impls_trait, U>(_: Inv, _: Inv) {} + +fn bar() { + let (obj, t) = foo(); + impls_trait(obj, t); + //[next]~^ ERROR type annotations needed + let _: Inv> = obj; +} + +fn main() {} From df2e54376c4cf9009ba159a50a404e1483f52f67 Mon Sep 17 00:00:00 2001 From: lcnr Date: Wed, 30 Jul 2025 11:57:41 +0200 Subject: [PATCH 331/809] add comment and opaque type fixme --- compiler/rustc_trait_selection/src/solve/fulfill.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index e0b9380eca32..01bdae7435d7 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -241,6 +241,17 @@ where match certainty { Certainty::Yes => { + // Goals may depend on structural identity. Region uniquification at the + // start of MIR borrowck may cause things to no longer be so, potentially + // causing an ICE. + // + // While we uniquify root goals in HIR this does not handle cases where + // regions are hidden inside of a type or const inference variable. + // + // FIXME(-Znext-solver): This does not handle inference variables hidden + // inside of an opaque type, e.g. if there's `Opaque = (?x, ?x)` in the + // storage, we can also rely on structural identity of `?x` even if we + // later uniquify it in MIR borrowck. if infcx.in_hir_typeck && obligation.has_non_region_infer() { infcx.push_hir_typeck_potentially_region_dependent_goal(obligation); } From 2b065e7c0b453cc6de5e89bbab47df3bc4212940 Mon Sep 17 00:00:00 2001 From: lcnr Date: Wed, 30 Jul 2025 14:30:57 +0200 Subject: [PATCH 332/809] extend comment --- compiler/rustc_next_trait_solver/src/solve/mod.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index 9d52dee3c659..aec9594b834b 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -389,6 +389,19 @@ pub struct GoalEvaluation { /// The goal we've evaluated. This is the input goal, but potentially with its /// inference variables resolved. This never applies any inference constraints /// from evaluating the goal. + /// + /// We rely on this to check whether root goals in HIR typeck had an unresolved + /// type inference variable in the input. We must not resolve this after evaluating + /// the goal as even if the inference variable has been resolved by evaluating the + /// goal itself, this goal may still end up failing due to region uniquification + /// later on. + /// + /// This is used as a minor optimization to avoid re-resolving inference variables + /// when reevaluating ambiguous goals. E.g. if we've got a goal `?x: Trait` with `?x` + /// already being constrained to `Vec`, then the first evaluation resolves it to + /// `Vec: Trait`. If this goal is still ambiguous and we later resolve `?y` to `u32`, + /// then reevaluating this goal now only needs to resolve `?y` while it would otherwise + /// have to resolve both `?x` and `?y`, pub goal: Goal, pub certainty: Certainty, pub has_changed: HasChanged, From 9fb99109b66626b51343ba6adee61274b0a67a50 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Wed, 30 Jul 2025 15:45:20 +0200 Subject: [PATCH 333/809] 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 1d589c87bef43ea685927fc97d3c8b8fff725184 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Tue, 29 Jul 2025 23:55:04 +0200 Subject: [PATCH 334/809] clean up codegen fn attrs --- .../rustc_codegen_ssa/src/codegen_attrs.rs | 564 ++++++++++-------- 1 file changed, 308 insertions(+), 256 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index e187331c696c..5c54bce6e035 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -4,12 +4,12 @@ use rustc_abi::{Align, ExternAbi}; use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode}; use rustc_ast::{LitKind, MetaItem, MetaItemInner, attr}; use rustc_attr_data_structures::{ - AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr, UsedBy, find_attr, + AttributeKind, InlineAttr, InstructionSetAttr, UsedBy, find_attr, }; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS; -use rustc_hir::{self as hir, LangItem, lang_items}; +use rustc_hir::{self as hir, Attribute, LangItem, lang_items}; use rustc_middle::middle::codegen_fn_attrs::{ CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, }; @@ -53,77 +53,196 @@ fn linkage_by_name(tcx: TyCtxt<'_>, def_id: LocalDefId, name: &str) -> Linkage { } } -fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { - if cfg!(debug_assertions) { - let def_kind = tcx.def_kind(did); - assert!( - def_kind.has_codegen_attrs(), - "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}", - ); +/// In some cases, attributes are only valid on functions, but it's the `check_attr` +/// pass that checks that they aren't used anywhere else, rather than this module. +/// In these cases, we bail from performing further checks that are only meaningful for +/// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also +/// report a delayed bug, just in case `check_attr` isn't doing its job. +fn try_fn_sig<'tcx>( + tcx: TyCtxt<'tcx>, + did: LocalDefId, + attr_span: Span, +) -> Option>> { + use DefKind::*; + + let def_kind = tcx.def_kind(did); + if let Fn | AssocFn | Variant | Ctor(..) = def_kind { + Some(tcx.fn_sig(did)) + } else { + tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions"); + None + } +} + +// FIXME(jdonszelmann): remove when instruction_set becomes a parsed attr +fn parse_instruction_set_attr(tcx: TyCtxt<'_>, attr: &Attribute) -> Option { + let list = attr.meta_item_list()?; + + match &list[..] { + [MetaItemInner::MetaItem(set)] => { + let segments = set.path.segments.iter().map(|x| x.ident.name).collect::>(); + match segments.as_slice() { + [sym::arm, sym::a32 | sym::t32] if !tcx.sess.target.has_thumb_interworking => { + tcx.dcx().emit_err(errors::UnsupportedInstructionSet { span: attr.span() }); + None + } + [sym::arm, sym::a32] => Some(InstructionSetAttr::ArmA32), + [sym::arm, sym::t32] => Some(InstructionSetAttr::ArmT32), + _ => { + tcx.dcx().emit_err(errors::InvalidInstructionSet { span: attr.span() }); + None + } + } + } + [] => { + tcx.dcx().emit_err(errors::BareInstructionSet { span: attr.span() }); + None + } + _ => { + tcx.dcx().emit_err(errors::MultipleInstructionSet { span: attr.span() }); + None + } + } +} + +// FIXME(jdonszelmann): remove when linkage becomes a parsed attr +fn parse_linkage_attr(tcx: TyCtxt<'_>, did: LocalDefId, attr: &Attribute) -> Option { + let val = attr.value_str()?; + let linkage = linkage_by_name(tcx, did, val.as_str()); + Some(linkage) +} + +// FIXME(jdonszelmann): remove when no_sanitize becomes a parsed attr +fn parse_no_sanitize_attr(tcx: TyCtxt<'_>, attr: &Attribute) -> Option { + let list = attr.meta_item_list()?; + let mut sanitizer_set = SanitizerSet::empty(); + + for item in list.iter() { + match item.name() { + Some(sym::address) => { + sanitizer_set |= SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS + } + Some(sym::cfi) => sanitizer_set |= SanitizerSet::CFI, + Some(sym::kcfi) => sanitizer_set |= SanitizerSet::KCFI, + Some(sym::memory) => sanitizer_set |= SanitizerSet::MEMORY, + Some(sym::memtag) => sanitizer_set |= SanitizerSet::MEMTAG, + Some(sym::shadow_call_stack) => sanitizer_set |= SanitizerSet::SHADOWCALLSTACK, + Some(sym::thread) => sanitizer_set |= SanitizerSet::THREAD, + Some(sym::hwaddress) => sanitizer_set |= SanitizerSet::HWADDRESS, + _ => { + tcx.dcx().emit_err(errors::InvalidNoSanitize { span: item.span() }); + } + } } - let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did)); - let mut codegen_fn_attrs = CodegenFnAttrs::new(); - if tcx.should_inherit_track_caller(did) { - codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER; - } + Some(sanitizer_set) +} + +// FIXME(jdonszelmann): remove when patchable_function_entry becomes a parsed attr +fn parse_patchable_function_entry( + tcx: TyCtxt<'_>, + attr: &Attribute, +) -> Option { + attr.meta_item_list().and_then(|l| { + let mut prefix = None; + let mut entry = None; + for item in l { + let Some(meta_item) = item.meta_item() else { + tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() }); + continue; + }; + + let Some(name_value_lit) = meta_item.name_value_literal() else { + tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() }); + continue; + }; + + let attrib_to_write = match meta_item.name() { + Some(sym::prefix_nops) => &mut prefix, + Some(sym::entry_nops) => &mut entry, + _ => { + tcx.dcx().emit_err(errors::UnexpectedParameterName { + span: item.span(), + prefix_nops: sym::prefix_nops, + entry_nops: sym::entry_nops, + }); + continue; + } + }; + + let rustc_ast::LitKind::Int(val, _) = name_value_lit.kind else { + tcx.dcx().emit_err(errors::InvalidLiteralValue { span: name_value_lit.span }); + continue; + }; + + let Ok(val) = val.get().try_into() else { + tcx.dcx().emit_err(errors::OutOfRangeInteger { span: name_value_lit.span }); + continue; + }; + + *attrib_to_write = Some(val); + } + + if let (None, None) = (prefix, entry) { + tcx.dcx().span_err(attr.span(), "must specify at least one parameter"); + } + + Some(PatchableFunctionEntry::from_prefix_and_entry(prefix.unwrap_or(0), entry.unwrap_or(0))) + }) +} + +/// Spans that are collected when processing built-in attributes, +/// that are useful for emitting diagnostics later. +#[derive(Default)] +struct InterestingAttributeDiagnosticSpans { + link_ordinal: Option, + no_sanitize: Option, + inline: Option, + no_mangle: Option, +} + +/// Process the builtin attrs ([`hir::Attribute`]) on the item. +/// Many of them directly translate to codegen attrs. +fn process_builtin_attrs( + tcx: TyCtxt<'_>, + did: LocalDefId, + attrs: &[Attribute], + codegen_fn_attrs: &mut CodegenFnAttrs, +) -> InterestingAttributeDiagnosticSpans { + let mut interesting_spans = InterestingAttributeDiagnosticSpans::default(); + let rust_target_features = tcx.rust_target_features(LOCAL_CRATE); // If our rustc version supports autodiff/enzyme, then we call our handler // to check for any `#[rustc_autodiff(...)]` attributes. + // FIXME(jdonszelmann): merge with loop below if cfg!(llvm_enzyme) { let ad = autodiff_attrs(tcx, did.into()); codegen_fn_attrs.autodiff_item = ad; } - // When `no_builtins` is applied at the crate level, we should add the - // `no-builtins` attribute to each function to ensure it takes effect in LTO. - let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID); - let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins); - if no_builtins { - codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS; - } - - let rust_target_features = tcx.rust_target_features(LOCAL_CRATE); - - let mut link_ordinal_span = None; - let mut no_sanitize_span = None; - for attr in attrs.iter() { - // In some cases, attribute are only valid on functions, but it's the `check_attr` - // pass that check that they aren't used anywhere else, rather this module. - // In these cases, we bail from performing further checks that are only meaningful for - // functions (such as calling `fn_sig`, which ICEs if given a non-function). We also - // report a delayed bug, just in case `check_attr` isn't doing its job. - let fn_sig = |attr_span| { - use DefKind::*; - - let def_kind = tcx.def_kind(did); - if let Fn | AssocFn | Variant | Ctor(..) = def_kind { - Some(tcx.fn_sig(did)) - } else { - tcx.dcx() - .span_delayed_bug(attr_span, "this attribute can only be applied to functions"); - None - } - }; - if let hir::Attribute::Parsed(p) = attr { match p { AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD, AttributeKind::ExportName { name, .. } => { - codegen_fn_attrs.export_name = Some(*name); + codegen_fn_attrs.export_name = Some(*name) + } + AttributeKind::Inline(inline, span) => { + codegen_fn_attrs.inline = *inline; + interesting_spans.inline = Some(*span); } AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED, AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align), AttributeKind::LinkName { name, .. } => codegen_fn_attrs.link_name = Some(*name), AttributeKind::LinkOrdinal { ordinal, span } => { codegen_fn_attrs.link_ordinal = Some(*ordinal); - link_ordinal_span = Some(*span); + interesting_spans.link_ordinal = Some(*span); } AttributeKind::LinkSection { name, .. } => { codegen_fn_attrs.link_section = Some(*name) } AttributeKind::NoMangle(attr_span) => { + interesting_spans.no_mangle = Some(*attr_span); if tcx.opt_item_name(did.to_def_id()).is_some() { codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE; } else { @@ -137,6 +256,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { }); } } + AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize, AttributeKind::TargetFeature(features, attr_span) => { let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else { tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn"); @@ -184,7 +304,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { let is_closure = tcx.is_closure_like(did.to_def_id()); if !is_closure - && let Some(fn_sig) = fn_sig(*attr_span) + && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span) && fn_sig.skip_binder().abi() != ExternAbi::Rust { tcx.dcx().emit_err(errors::RequiresRustAbi { span: *attr_span }); @@ -232,155 +352,49 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { } sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL, sym::linkage => { - if let Some(val) = attr.value_str() { - let linkage = Some(linkage_by_name(tcx, did, val.as_str())); - if tcx.is_foreign_item(did) { - codegen_fn_attrs.import_linkage = linkage; + let linkage = parse_linkage_attr(tcx, did, attr); - if tcx.is_mutable_static(did.into()) { - let mut diag = tcx.dcx().struct_span_err( - attr.span(), - "extern mutable statics are not allowed with `#[linkage]`", - ); - diag.note( - "marking the extern static mutable would allow changing which \ - symbol the static references rather than make the target of the \ - symbol mutable", - ); - diag.emit(); - } - } else { - codegen_fn_attrs.linkage = linkage; + if tcx.is_foreign_item(did) { + codegen_fn_attrs.import_linkage = linkage; + + if tcx.is_mutable_static(did.into()) { + let mut diag = tcx.dcx().struct_span_err( + attr.span(), + "extern mutable statics are not allowed with `#[linkage]`", + ); + diag.note( + "marking the extern static mutable would allow changing which \ + symbol the static references rather than make the target of the \ + symbol mutable", + ); + diag.emit(); } + } else { + codegen_fn_attrs.linkage = linkage; } } sym::no_sanitize => { - no_sanitize_span = Some(attr.span()); - if let Some(list) = attr.meta_item_list() { - for item in list.iter() { - match item.name() { - Some(sym::address) => { - codegen_fn_attrs.no_sanitize |= - SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS - } - Some(sym::cfi) => codegen_fn_attrs.no_sanitize |= SanitizerSet::CFI, - Some(sym::kcfi) => codegen_fn_attrs.no_sanitize |= SanitizerSet::KCFI, - Some(sym::memory) => { - codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY - } - Some(sym::memtag) => { - codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMTAG - } - Some(sym::shadow_call_stack) => { - codegen_fn_attrs.no_sanitize |= SanitizerSet::SHADOWCALLSTACK - } - Some(sym::thread) => { - codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD - } - Some(sym::hwaddress) => { - codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS - } - _ => { - tcx.dcx().emit_err(errors::InvalidNoSanitize { span: item.span() }); - } - } - } - } + interesting_spans.no_sanitize = Some(attr.span()); + codegen_fn_attrs.no_sanitize |= + parse_no_sanitize_attr(tcx, attr).unwrap_or_default(); } sym::instruction_set => { - codegen_fn_attrs.instruction_set = - attr.meta_item_list().and_then(|l| match &l[..] { - [MetaItemInner::MetaItem(set)] => { - let segments = - set.path.segments.iter().map(|x| x.ident.name).collect::>(); - match segments.as_slice() { - [sym::arm, sym::a32 | sym::t32] - if !tcx.sess.target.has_thumb_interworking => - { - tcx.dcx().emit_err(errors::UnsupportedInstructionSet { - span: attr.span(), - }); - None - } - [sym::arm, sym::a32] => Some(InstructionSetAttr::ArmA32), - [sym::arm, sym::t32] => Some(InstructionSetAttr::ArmT32), - _ => { - tcx.dcx().emit_err(errors::InvalidInstructionSet { - span: attr.span(), - }); - None - } - } - } - [] => { - tcx.dcx().emit_err(errors::BareInstructionSet { span: attr.span() }); - None - } - _ => { - tcx.dcx() - .emit_err(errors::MultipleInstructionSet { span: attr.span() }); - None - } - }) + codegen_fn_attrs.instruction_set = parse_instruction_set_attr(tcx, attr) } sym::patchable_function_entry => { - codegen_fn_attrs.patchable_function_entry = attr.meta_item_list().and_then(|l| { - let mut prefix = None; - let mut entry = None; - for item in l { - let Some(meta_item) = item.meta_item() else { - tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() }); - continue; - }; - - let Some(name_value_lit) = meta_item.name_value_literal() else { - tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() }); - continue; - }; - - let attrib_to_write = match meta_item.name() { - Some(sym::prefix_nops) => &mut prefix, - Some(sym::entry_nops) => &mut entry, - _ => { - tcx.dcx().emit_err(errors::UnexpectedParameterName { - span: item.span(), - prefix_nops: sym::prefix_nops, - entry_nops: sym::entry_nops, - }); - continue; - } - }; - - let rustc_ast::LitKind::Int(val, _) = name_value_lit.kind else { - tcx.dcx().emit_err(errors::InvalidLiteralValue { - span: name_value_lit.span, - }); - continue; - }; - - let Ok(val) = val.get().try_into() else { - tcx.dcx() - .emit_err(errors::OutOfRangeInteger { span: name_value_lit.span }); - continue; - }; - - *attrib_to_write = Some(val); - } - - if let (None, None) = (prefix, entry) { - tcx.dcx().span_err(attr.span(), "must specify at least one parameter"); - } - - Some(PatchableFunctionEntry::from_prefix_and_entry( - prefix.unwrap_or(0), - entry.unwrap_or(0), - )) - }) + codegen_fn_attrs.patchable_function_entry = + parse_patchable_function_entry(tcx, attr); } _ => {} } } + interesting_spans +} + +/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary. +/// Please comment why when adding a new one! +fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) { // Apply the minimum function alignment here. This ensures that a function's alignment is // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate // it happens to be codegen'd (or const-eval'd) in. @@ -390,15 +404,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { // On trait methods, inherit the `#[align]` of the trait's method prototype. codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did)); - let inline_span; - (codegen_fn_attrs.inline, inline_span) = if let Some((inline_attr, span)) = - find_attr!(attrs, AttributeKind::Inline(i, span) => (*i, *span)) - { - (inline_attr, Some(span)) - } else { - (InlineAttr::None, None) - }; - // naked function MUST NOT be inlined! This attribute is required for the rust compiler itself, // but not for the code generation backend because at that point the naked function will just be // a declaration, with a definition provided in global assembly. @@ -406,9 +411,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { codegen_fn_attrs.inline = InlineAttr::Never; } - codegen_fn_attrs.optimize = - find_attr!(attrs, AttributeKind::Optimize(i, _) => *i).unwrap_or(OptimizeAttr::Default); - // #73631: closures inherit `#[target_feature]` annotations // // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`. @@ -431,6 +433,26 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { } } + // When `no_builtins` is applied at the crate level, we should add the + // `no-builtins` attribute to each function to ensure it takes effect in LTO. + let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID); + let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins); + if no_builtins { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS; + } + + // inherit track-caller properly + if tcx.should_inherit_track_caller(did) { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER; + } +} + +fn check_result( + tcx: TyCtxt<'_>, + did: LocalDefId, + interesting_spans: InterestingAttributeDiagnosticSpans, + codegen_fn_attrs: &CodegenFnAttrs, +) { // If a function uses `#[target_feature]` it can't be inlined into general // purpose functions as they wouldn't have the right target features // enabled. For that reason we also forbid `#[inline(always)]` as it can't be @@ -446,14 +468,16 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { // llvm/llvm-project#70563). if !codegen_fn_attrs.target_features.is_empty() && matches!(codegen_fn_attrs.inline, InlineAttr::Always) - && let Some(span) = inline_span + && let Some(span) = interesting_spans.inline { tcx.dcx().span_err(span, "cannot use `#[inline(always)]` with `#[target_feature]`"); } + // warn that inline has no effect when no_sanitize is present if !codegen_fn_attrs.no_sanitize.is_empty() && codegen_fn_attrs.inline.always() - && let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) + && let (Some(no_sanitize_span), Some(inline_span)) = + (interesting_spans.no_sanitize, interesting_spans.inline) { let hir_id = tcx.local_def_id_to_hir_id(did); tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, no_sanitize_span, |lint| { @@ -462,51 +486,16 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { }) } - // Weak lang items have the same semantics as "std internal" symbols in the - // sense that they're preserved through all our LTO passes and only - // strippable by the linker. - // - // Additionally weak lang items have predetermined symbol names. - if let Some((name, _)) = lang_items::extract(attrs) - && let Some(lang_item) = LangItem::from_name(name) + // error when specifying link_name together with link_ordinal + if let Some(_) = codegen_fn_attrs.link_name + && let Some(_) = codegen_fn_attrs.link_ordinal { - if WEAK_LANG_ITEMS.contains(&lang_item) { - codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL; + let msg = "cannot use `#[link_name]` with `#[link_ordinal]`"; + if let Some(span) = interesting_spans.link_ordinal { + tcx.dcx().span_err(span, msg); + } else { + tcx.dcx().err(msg); } - if let Some(link_name) = lang_item.link_name() { - codegen_fn_attrs.export_name = Some(link_name); - codegen_fn_attrs.link_name = Some(link_name); - } - } - check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span); - - if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) - && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) - { - let no_mangle_span = - find_attr!(attrs, AttributeKind::NoMangle(no_mangle_span) => *no_mangle_span) - .unwrap_or_default(); - let lang_item = - lang_items::extract(attrs).map_or(None, |(name, _span)| LangItem::from_name(name)); - let mut err = tcx - .dcx() - .struct_span_err( - no_mangle_span, - "`#[no_mangle]` cannot be used on internal language items", - ) - .with_note("Rustc requires this item to have a specific mangled name.") - .with_span_label(tcx.def_span(did), "should be the internal language item"); - if let Some(lang_item) = lang_item - && let Some(link_name) = lang_item.link_name() - { - err = err - .with_note("If you are trying to prevent mangling to ease debugging, many") - .with_note(format!("debuggers support a command such as `rbreak {link_name}` to")) - .with_note(format!( - "match `.*{link_name}.*` instead of `break {link_name}` on a specific name" - )) - } - err.emit(); } if let Some(features) = check_tied_features( @@ -529,6 +518,84 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { }) .emit(); } +} + +fn handle_lang_items( + tcx: TyCtxt<'_>, + did: LocalDefId, + interesting_spans: &InterestingAttributeDiagnosticSpans, + attrs: &[Attribute], + codegen_fn_attrs: &mut CodegenFnAttrs, +) { + // Weak lang items have the same semantics as "std internal" symbols in the + // sense that they're preserved through all our LTO passes and only + // strippable by the linker. + // + // Additionally weak lang items have predetermined symbol names. + if let Some((name, _)) = lang_items::extract(attrs) + && let Some(lang_item) = LangItem::from_name(name) + { + if WEAK_LANG_ITEMS.contains(&lang_item) { + codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL; + } + if let Some(link_name) = lang_item.link_name() { + codegen_fn_attrs.export_name = Some(link_name); + codegen_fn_attrs.link_name = Some(link_name); + } + } + + // error when using no_mangle on a lang item item + if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) + && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) + { + let lang_item = + lang_items::extract(attrs).map_or(None, |(name, _span)| LangItem::from_name(name)); + let mut err = tcx + .dcx() + .struct_span_err( + interesting_spans.no_mangle.unwrap_or_default(), + "`#[no_mangle]` cannot be used on internal language items", + ) + .with_note("Rustc requires this item to have a specific mangled name.") + .with_span_label(tcx.def_span(did), "should be the internal language item"); + if let Some(lang_item) = lang_item + && let Some(link_name) = lang_item.link_name() + { + err = err + .with_note("If you are trying to prevent mangling to ease debugging, many") + .with_note(format!("debuggers support a command such as `rbreak {link_name}` to")) + .with_note(format!( + "match `.*{link_name}.*` instead of `break {link_name}` on a specific name" + )) + } + err.emit(); + } +} + +/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]). +/// +/// This happens in 4 stages: +/// - apply built-in attributes that directly translate to codegen attributes. +/// - handle lang items. These have special codegen attrs applied to them. +/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item. +/// overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before. +/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs. +fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { + if cfg!(debug_assertions) { + let def_kind = tcx.def_kind(did); + assert!( + def_kind.has_codegen_attrs(), + "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}", + ); + } + + let mut codegen_fn_attrs = CodegenFnAttrs::new(); + let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did)); + + let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs); + handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs); + apply_overrides(tcx, did, &mut codegen_fn_attrs); + check_result(tcx, did, interesting_spans, &codegen_fn_attrs); codegen_fn_attrs } @@ -555,27 +622,12 @@ fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option { tcx.codegen_fn_attrs(opt_trait_item(tcx, def_id)?).alignment } -fn check_link_name_xor_ordinal( - tcx: TyCtxt<'_>, - codegen_fn_attrs: &CodegenFnAttrs, - inline_span: Option, -) { - if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() { - return; - } - let msg = "cannot use `#[link_name]` with `#[link_ordinal]`"; - if let Some(span) = inline_span { - tcx.dcx().span_err(span, msg); - } else { - tcx.dcx().err(msg); - } -} - /// We now check the #\[rustc_autodiff\] attributes which we generated from the #[autodiff(...)] /// macros. There are two forms. The pure one without args to mark primal functions (the functions /// being differentiated). The other form is #[rustc_autodiff(Mode, ActivityList)] on top of the /// placeholder functions. We wrote the rustc_autodiff attributes ourself, so this should never /// panic, unless we introduced a bug when parsing the autodiff macro. +//FIXME(jdonszelmann): put in the main loop. No need to have two..... :/ Let's do that when we make autodiff parsed. fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option { let attrs = tcx.get_attrs(id, sym::rustc_autodiff); From 3fe0e2435665f857c11acbbd91a063f5a3c8d79d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Wed, 30 Jul 2025 16:38:12 +0200 Subject: [PATCH 335/809] only extract lang items once --- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 5c54bce6e035..78edc69b237a 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -527,14 +527,14 @@ fn handle_lang_items( attrs: &[Attribute], codegen_fn_attrs: &mut CodegenFnAttrs, ) { + let lang_item = lang_items::extract(attrs).and_then(|(name, _)| LangItem::from_name(name)); + // Weak lang items have the same semantics as "std internal" symbols in the // sense that they're preserved through all our LTO passes and only // strippable by the linker. // // Additionally weak lang items have predetermined symbol names. - if let Some((name, _)) = lang_items::extract(attrs) - && let Some(lang_item) = LangItem::from_name(name) - { + if let Some(lang_item) = lang_item { if WEAK_LANG_ITEMS.contains(&lang_item) { codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL; } @@ -548,8 +548,6 @@ fn handle_lang_items( if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) { - let lang_item = - lang_items::extract(attrs).map_or(None, |(name, _span)| LangItem::from_name(name)); let mut err = tcx .dcx() .struct_span_err( From 3cbd088ee4e453eeab2d3cfae3e047b7e12bece8 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Wed, 30 Jul 2025 09:56:11 -0500 Subject: [PATCH 336/809] 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 337/809] 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 3ccfa14e48919ce13a7d13be530a2e772e17cd05 Mon Sep 17 00:00:00 2001 From: Balt <59123926+balt-dev@users.noreply.github.com> Date: Mon, 16 Jun 2025 22:44:29 -0500 Subject: [PATCH 338/809] Implement push_mut --- library/alloc/src/collections/linked_list.rs | 54 +++++++- .../alloc/src/collections/vec_deque/mod.rs | 96 ++++++++++++-- library/alloc/src/vec/mod.rs | 122 ++++++++++++++++-- 3 files changed, 243 insertions(+), 29 deletions(-) diff --git a/library/alloc/src/collections/linked_list.rs b/library/alloc/src/collections/linked_list.rs index 70c344e49b76..31dfe73fc799 100644 --- a/library/alloc/src/collections/linked_list.rs +++ b/library/alloc/src/collections/linked_list.rs @@ -825,7 +825,7 @@ impl LinkedList { unsafe { self.tail.as_mut().map(|node| &mut node.as_mut().element) } } - /// Adds an element first in the list. + /// Adds an element to the front of the list. /// /// This operation should compute in *O*(1) time. /// @@ -844,11 +844,34 @@ impl LinkedList { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn push_front(&mut self, elt: T) { + let _ = self.push_front_mut(elt); + } + + /// Adds an element to the front of the list, returning a reference to it. + /// + /// This operation should compute in *O*(1) time. + /// + /// # Examples + /// + /// ``` + /// #![feature(push_mut)] + /// use std::collections::LinkedList; + /// + /// let mut dl = LinkedList::from([1, 2, 3]); + /// + /// let ptr = dl.push_front_mut(2); + /// *ptr += 4; + /// assert_eq!(dl.front().unwrap(), &6); + /// ``` + #[unstable(feature = "push_mut", issue = "135974")] + #[must_use = "if you don't need a reference to the value, use `LinkedList::push_front` instead"] + pub fn push_front_mut(&mut self, elt: T) -> &mut T { let node = Box::new_in(Node::new(elt), &self.alloc); - let node_ptr = NonNull::from(Box::leak(node)); + let mut node_ptr = NonNull::from(Box::leak(node)); // SAFETY: node_ptr is a unique pointer to a node we boxed with self.alloc and leaked unsafe { self.push_front_node(node_ptr); + &mut node_ptr.as_mut().element } } @@ -876,7 +899,7 @@ impl LinkedList { self.pop_front_node().map(Node::into_element) } - /// Appends an element to the back of a list. + /// Adds an element to the back of the list. /// /// This operation should compute in *O*(1) time. /// @@ -893,11 +916,34 @@ impl LinkedList { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_confusables("push", "append")] pub fn push_back(&mut self, elt: T) { + let _ = self.push_back_mut(elt); + } + + /// Adds an element to the back of the list, returning a reference to it. + /// + /// This operation should compute in *O*(1) time. + /// + /// # Examples + /// + /// ``` + /// #![feature(push_mut)] + /// use std::collections::LinkedList; + /// + /// let mut dl = LinkedList::from([1, 2, 3]); + /// + /// let ptr = dl.push_back_mut(2); + /// *ptr += 4; + /// assert_eq!(dl.back().unwrap(), &6); + /// ``` + #[unstable(feature = "push_mut", issue = "135974")] + #[must_use = "if you don't need a reference to the value, use `LinkedList::push_back` instead"] + pub fn push_back_mut(&mut self, elt: T) -> &mut T { let node = Box::new_in(Node::new(elt), &self.alloc); - let node_ptr = NonNull::from(Box::leak(node)); + let mut node_ptr = NonNull::from(Box::leak(node)); // SAFETY: node_ptr is a unique pointer to a node we boxed with self.alloc and leaked unsafe { self.push_back_node(node_ptr); + &mut node_ptr.as_mut().element } } diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 08b1828ff000..2fce5c3e737e 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -182,11 +182,16 @@ impl VecDeque { unsafe { ptr::read(self.ptr().add(off)) } } - /// Writes an element into the buffer, moving it. + /// Writes an element into the buffer, moving it and returning a pointer to it. + /// # Safety + /// + /// May only be called if `off < self.capacity()`. #[inline] - unsafe fn buffer_write(&mut self, off: usize, value: T) { + unsafe fn buffer_write(&mut self, off: usize, value: T) -> &mut T { unsafe { - ptr::write(self.ptr().add(off), value); + let ptr = self.ptr().add(off); + ptr::write(ptr, value); + &mut *ptr } } @@ -1888,16 +1893,34 @@ impl VecDeque { #[stable(feature = "rust1", since = "1.0.0")] #[track_caller] pub fn push_front(&mut self, value: T) { + let _ = self.push_front_mut(value); + } + + /// Prepends an element to the deque, returning a reference to it. + /// + /// # Examples + /// + /// ``` + /// #![feature(push_mut)] + /// use std::collections::VecDeque; + /// + /// let mut d = VecDeque::from([1, 2, 3]); + /// let x = d.push_front_mut(8); + /// *x -= 1; + /// assert_eq!(d.front(), Some(&7)); + /// ``` + #[unstable(feature = "push_mut", issue = "135974")] + #[track_caller] + #[must_use = "if you don't need a reference to the value, use `VecDeque::push_front` instead"] + pub fn push_front_mut(&mut self, value: T) -> &mut T { if self.is_full() { self.grow(); } self.head = self.wrap_sub(self.head, 1); self.len += 1; - - unsafe { - self.buffer_write(self.head, value); - } + // SAFETY: We know that self.head is within range of the deque. + unsafe { self.buffer_write(self.head, value) } } /// Appends an element to the back of the deque. @@ -1916,12 +1939,33 @@ impl VecDeque { #[rustc_confusables("push", "put", "append")] #[track_caller] pub fn push_back(&mut self, value: T) { + let _ = self.push_back_mut(value); + } + + /// Appends an element to the back of the deque, returning a reference to it. + /// + /// # Examples + /// + /// ``` + /// #![feature(push_mut)] + /// use std::collections::VecDeque; + /// + /// let mut d = VecDeque::from([1, 2, 3]); + /// let x = d.push_back_mut(9); + /// *x += 1; + /// assert_eq!(d.back(), Some(&10)); + /// ``` + #[unstable(feature = "push_mut", issue = "135974")] + #[track_caller] + #[must_use = "if you don't need a reference to the value, use `VecDeque::push_back` instead"] + pub fn push_back_mut(&mut self, value: T) -> &mut T { if self.is_full() { self.grow(); } - unsafe { self.buffer_write(self.to_physical_idx(self.len), value) } + let len = self.len; self.len += 1; + unsafe { self.buffer_write(self.to_physical_idx(len), value) } } #[inline] @@ -2007,7 +2051,7 @@ impl VecDeque { /// /// # Panics /// - /// Panics if `index` is strictly greater than deque's length + /// Panics if `index` is strictly greater than the deque's length. /// /// # Examples /// @@ -2029,7 +2073,37 @@ impl VecDeque { #[stable(feature = "deque_extras_15", since = "1.5.0")] #[track_caller] pub fn insert(&mut self, index: usize, value: T) { + let _ = self.insert_mut(index, value); + } + + /// Inserts an element at `index` within the deque, shifting all elements + /// with indices greater than or equal to `index` towards the back, and + /// returning a reference to it. + /// + /// Element at index 0 is the front of the queue. + /// + /// # Panics + /// + /// Panics if `index` is strictly greater than the deque's length. + /// + /// # Examples + /// + /// ``` + /// #![feature(push_mut)] + /// use std::collections::VecDeque; + /// + /// let mut vec_deque = VecDeque::from([1, 2, 3]); + /// + /// let x = vec_deque.insert_mut(1, 5); + /// *x += 7; + /// assert_eq!(vec_deque, &[1, 12, 2, 3]); + /// ``` + #[unstable(feature = "push_mut", issue = "135974")] + #[track_caller] + #[must_use = "if you don't need a reference to the value, use `VecDeque::insert` instead"] + pub fn insert_mut(&mut self, index: usize, value: T) -> &mut T { assert!(index <= self.len(), "index out of bounds"); + if self.is_full() { self.grow(); } @@ -2042,16 +2116,16 @@ impl VecDeque { unsafe { // see `remove()` for explanation why this wrap_copy() call is safe. self.wrap_copy(self.to_physical_idx(index), self.to_physical_idx(index + 1), k); - self.buffer_write(self.to_physical_idx(index), value); self.len += 1; + self.buffer_write(self.to_physical_idx(index), value) } } else { let old_head = self.head; self.head = self.wrap_sub(self.head, 1); unsafe { self.wrap_copy(old_head, self.head, index); - self.buffer_write(self.to_physical_idx(index), value); self.len += 1; + self.buffer_write(self.to_physical_idx(index), value) } } } diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 9856e9c18ec6..ce74615dbccf 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -2046,6 +2046,38 @@ impl Vec { #[stable(feature = "rust1", since = "1.0.0")] #[track_caller] pub fn insert(&mut self, index: usize, element: T) { + let _ = self.insert_mut(index, element); + } + + /// Inserts an element at position `index` within the vector, shifting all + /// elements after it to the right, and returning a reference to the new + /// element. + /// + /// # Panics + /// + /// Panics if `index > len`. + /// + /// # Examples + /// + /// ``` + /// #![feature(push_mut)] + /// let mut vec = vec![1, 3, 5, 9]; + /// let x = vec.insert_mut(3, 6); + /// *x += 1; + /// assert_eq!(vec, [1, 3, 5, 7, 9]); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be + /// shifted to the right. In the worst case, all elements are shifted when + /// the insertion index is 0. + #[cfg(not(no_global_oom_handling))] + #[inline] + #[unstable(feature = "push_mut", issue = "135974")] + #[track_caller] + #[must_use = "if you don't need a reference to the value, use `Vec::insert` instead"] + pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T { #[cold] #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))] #[track_caller] @@ -2067,8 +2099,8 @@ impl Vec { unsafe { // infallible // The spot to put the new value + let p = self.as_mut_ptr().add(index); { - let p = self.as_mut_ptr().add(index); if index < len { // Shift everything over to make space. (Duplicating the // `index`th element into two consecutive places.) @@ -2079,6 +2111,7 @@ impl Vec { ptr::write(p, element); } self.set_len(len + 1); + &mut *p } } @@ -2486,18 +2519,7 @@ impl Vec { #[rustc_confusables("push_back", "put", "append")] #[track_caller] pub fn push(&mut self, value: T) { - // Inform codegen that the length does not change across grow_one(). - let len = self.len; - // This will panic or abort if we would allocate > isize::MAX bytes - // or if the length increment would overflow for zero-sized types. - if len == self.buf.capacity() { - self.buf.grow_one(); - } - unsafe { - let end = self.as_mut_ptr().add(len); - ptr::write(end, value); - self.len = len + 1; - } + let _ = self.push_mut(value); } /// Appends an element if there is sufficient spare capacity, otherwise an error is returned @@ -2538,6 +2560,77 @@ impl Vec { #[inline] #[unstable(feature = "vec_push_within_capacity", issue = "100486")] pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> { + self.push_mut_within_capacity(value).map(|_| ()) + } + + /// Appends an element to the back of a collection, returning a reference to it. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// #![feature(push_mut)] + /// + /// + /// let mut vec = vec![1, 2]; + /// let last = vec.push_mut(3); + /// assert_eq!(*last, 3); + /// assert_eq!(vec, [1, 2, 3]); + /// + /// let last = vec.push_mut(3); + /// *last += 1; + /// assert_eq!(vec, [1, 2, 3, 4]); + /// ``` + /// + /// # Time complexity + /// + /// Takes amortized *O*(1) time. If the vector's length would exceed its + /// capacity after the push, *O*(*capacity*) time is taken to copy the + /// vector's elements to a larger allocation. This expensive operation is + /// offset by the *capacity* *O*(1) insertions it allows. + #[cfg(not(no_global_oom_handling))] + #[inline] + #[unstable(feature = "push_mut", issue = "135974")] + #[track_caller] + #[must_use = "if you don't need a reference to the value, use `Vec::push` instead"] + pub fn push_mut(&mut self, value: T) -> &mut T { + // Inform codegen that the length does not change across grow_one(). + let len = self.len; + // This will panic or abort if we would allocate > isize::MAX bytes + // or if the length increment would overflow for zero-sized types. + if len == self.buf.capacity() { + self.buf.grow_one(); + } + unsafe { + let end = self.as_mut_ptr().add(len); + ptr::write(end, value); + self.len = len + 1; + // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference. + &mut *end + } + } + + /// Appends an element and returns a reference to it if there is sufficient spare capacity, + /// otherwise an error is returned with the element. + /// + /// Unlike [`push_mut`] this method will not reallocate when there's insufficient capacity. + /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity. + /// + /// [`push_mut`]: Vec::push_mut + /// [`reserve`]: Vec::reserve + /// [`try_reserve`]: Vec::try_reserve + /// + /// # Time complexity + /// + /// Takes *O*(1) time. + #[unstable(feature = "push_mut", issue = "135974")] + // #[unstable(feature = "vec_push_within_capacity", issue = "100486")] + #[inline] + #[must_use = "if you don't need a reference to the value, use `Vec::push_within_capacity` instead"] + pub fn push_mut_within_capacity(&mut self, value: T) -> Result<&mut T, T> { if self.len == self.buf.capacity() { return Err(value); } @@ -2545,8 +2638,9 @@ impl Vec { let end = self.as_mut_ptr().add(self.len); ptr::write(end, value); self.len += 1; + // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference. + Ok(&mut *end) } - Ok(()) } /// Removes the last element from a vector and returns it, or [`None`] if it From 2ae048e1df765e0ba4c9638149552ea1eba82834 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 30 Jul 2025 17:48:24 +0000 Subject: [PATCH 339/809] 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 340/809] 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 341/809] 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 342/809] 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 1a515e69490cdc3cee5325c4fc8d18baa502f38a Mon Sep 17 00:00:00 2001 From: Alona Enraght-Moony Date: Wed, 30 Jul 2025 19:12:31 +0000 Subject: [PATCH 343/809] rustdoc-json: Add test for `#[macro_use]` attribute --- tests/rustdoc-json/attrs/macro_export.rs | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 tests/rustdoc-json/attrs/macro_export.rs diff --git a/tests/rustdoc-json/attrs/macro_export.rs b/tests/rustdoc-json/attrs/macro_export.rs new file mode 100644 index 000000000000..1472aabb6ff5 --- /dev/null +++ b/tests/rustdoc-json/attrs/macro_export.rs @@ -0,0 +1,40 @@ +//@ compile-flags: --document-private-items + +//@ set exported_id = "$.index[?(@.name=='exported')].id" +//@ is "$.index[?(@.name=='exported')].attrs" '[{"other": "#[macro_export]"}]' +//@ is "$.index[?(@.name=='exported')].visibility" '"public"' + +#[macro_export] +macro_rules! exported { + () => {}; +} + +//@ set not_exported_id = "$.index[?(@.name=='not_exported')].id" +//@ is "$.index[?(@.name=='not_exported')].attrs" [] +//@ is "$.index[?(@.name=='not_exported')].visibility" '"crate"' +macro_rules! not_exported { + () => {}; +} + +//@ set module_id = "$.index[?(@.name=='module')].id" +pub mod module { + //@ set exported_from_mod_id = "$.index[?(@.name=='exported_from_mod')].id" + //@ is "$.index[?(@.name=='exported_from_mod')].attrs" '[{"other": "#[macro_export]"}]' + //@ is "$.index[?(@.name=='exported_from_mod')].visibility" '"public"' + #[macro_export] + macro_rules! exported_from_mod { + () => {}; + } + + //@ set not_exported_from_mod_id = "$.index[?(@.name=='not_exported_from_mod')].id" + //@ is "$.index[?(@.name=='not_exported_from_mod')].attrs" [] + //@ is "$.index[?(@.name=='not_exported_from_mod')].visibility" '"crate"' + macro_rules! not_exported_from_mod { + () => {}; + } +} +// The non-exported macro's are left in place, but the #[macro_export]'d ones +// are moved to the crate root. + +//@ is "$.index[?(@.name=='module')].inner.module.items[*]" $not_exported_from_mod_id +//@ ismany "$.index[?(@.name=='macro_export')].inner.module.items[*]" $exported_id $not_exported_id $module_id $exported_from_mod_id From a33e084afe698e0a025211abd6dc1c9a4bb22e9d Mon Sep 17 00:00:00 2001 From: Alona Enraght-Moony Date: Wed, 30 Jul 2025 19:57:32 +0000 Subject: [PATCH 344/809] rustdoc-json: Move `#[macro_export]` from `Other` to it's own variant --- src/librustdoc/json/conversions.rs | 8 ++++++-- src/rustdoc-json-types/lib.rs | 7 +++++-- tests/rustdoc-json/attrs/macro_export.rs | 4 ++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 08bc0bb19505..fe69a5abee1a 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -908,8 +908,12 @@ fn maybe_from_hir_attr( hir::Attribute::Parsed(kind) => kind, hir::Attribute::Unparsed(_) => { - // FIXME: We should handle `#[doc(hidden)]`. - return Some(other_attr(tcx, attr)); + return Some(if attr.has_name(sym::macro_export) { + Attribute::MacroExport + // FIXME: We should handle `#[doc(hidden)]`. + } else { + other_attr(tcx, attr) + }); } }; diff --git a/src/rustdoc-json-types/lib.rs b/src/rustdoc-json-types/lib.rs index 6235b0e8576f..40f89009a431 100644 --- a/src/rustdoc-json-types/lib.rs +++ b/src/rustdoc-json-types/lib.rs @@ -37,8 +37,8 @@ pub type FxHashMap = HashMap; // re-export for use in src/librustdoc // will instead cause conflicts. See #94591 for more. (This paragraph and the "Latest feature" line // are deliberately not in a doc comment, because they need not be in public docs.) // -// Latest feature: Structured Attributes -pub const FORMAT_VERSION: u32 = 54; +// Latest feature: Add Attribute::MacroUse +pub const FORMAT_VERSION: u32 = 55; /// The root of the emitted JSON blob. /// @@ -216,6 +216,9 @@ pub enum Attribute { /// `#[must_use]` MustUse { reason: Option }, + /// `#[macro_export]` + MacroExport, + /// `#[export_name = "name"]` ExportName(String), diff --git a/tests/rustdoc-json/attrs/macro_export.rs b/tests/rustdoc-json/attrs/macro_export.rs index 1472aabb6ff5..5d487cf6a56e 100644 --- a/tests/rustdoc-json/attrs/macro_export.rs +++ b/tests/rustdoc-json/attrs/macro_export.rs @@ -1,7 +1,7 @@ //@ compile-flags: --document-private-items //@ set exported_id = "$.index[?(@.name=='exported')].id" -//@ is "$.index[?(@.name=='exported')].attrs" '[{"other": "#[macro_export]"}]' +//@ is "$.index[?(@.name=='exported')].attrs" '["macro_export"]' //@ is "$.index[?(@.name=='exported')].visibility" '"public"' #[macro_export] @@ -19,7 +19,7 @@ macro_rules! not_exported { //@ set module_id = "$.index[?(@.name=='module')].id" pub mod module { //@ set exported_from_mod_id = "$.index[?(@.name=='exported_from_mod')].id" - //@ is "$.index[?(@.name=='exported_from_mod')].attrs" '[{"other": "#[macro_export]"}]' + //@ is "$.index[?(@.name=='exported_from_mod')].attrs" '["macro_export"]' //@ is "$.index[?(@.name=='exported_from_mod')].visibility" '"public"' #[macro_export] macro_rules! exported_from_mod { From 585eac88c8275ec336f730b7b715cc573a755b55 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 30 Jul 2025 20:30:17 +0000 Subject: [PATCH 345/809] stall ConstArgHasType in compute_goal_fast_path --- compiler/rustc_trait_selection/src/solve/delegate.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/compiler/rustc_trait_selection/src/solve/delegate.rs b/compiler/rustc_trait_selection/src/solve/delegate.rs index 7426504e1393..1fa2a690fcbb 100644 --- a/compiler/rustc_trait_selection/src/solve/delegate.rs +++ b/compiler/rustc_trait_selection/src/solve/delegate.rs @@ -135,6 +135,13 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate< None } } + ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _)) => { + if self.shallow_resolve_const(ct).is_ct_infer() { + Some(Certainty::AMBIGUOUS) + } else { + None + } + } ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => { let arg = self.shallow_resolve_term(arg); if arg.is_trivially_wf(self.tcx) { From ee0118f8a1dbfcad06b8c09644553a3fc3e070d4 Mon Sep 17 00:00:00 2001 From: David Tenty Date: Wed, 30 Jul 2025 16:45:17 -0400 Subject: [PATCH 346/809] [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 347/809] 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 348/809] 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 4643d9ad6d09631b663c4f6879103b4d399b1cd8 Mon Sep 17 00:00:00 2001 From: Scott Schafer Date: Tue, 22 Jul 2025 05:14:37 -0600 Subject: [PATCH 349/809] test: Check close window rendering --- tests/ui/error-emitter/auxiliary/close_window.rs | 4 ++++ tests/ui/error-emitter/close_window.ascii.stderr | 14 ++++++++++++++ tests/ui/error-emitter/close_window.rs | 11 +++++++++++ tests/ui/error-emitter/close_window.unicode.stderr | 14 ++++++++++++++ 4 files changed, 43 insertions(+) create mode 100644 tests/ui/error-emitter/auxiliary/close_window.rs create mode 100644 tests/ui/error-emitter/close_window.ascii.stderr create mode 100644 tests/ui/error-emitter/close_window.rs create mode 100644 tests/ui/error-emitter/close_window.unicode.stderr diff --git a/tests/ui/error-emitter/auxiliary/close_window.rs b/tests/ui/error-emitter/auxiliary/close_window.rs new file mode 100644 index 000000000000..e41313b6ab31 --- /dev/null +++ b/tests/ui/error-emitter/auxiliary/close_window.rs @@ -0,0 +1,4 @@ +pub struct S; +impl S { + fn method(&self) {} +} diff --git a/tests/ui/error-emitter/close_window.ascii.stderr b/tests/ui/error-emitter/close_window.ascii.stderr new file mode 100644 index 000000000000..e208b7093933 --- /dev/null +++ b/tests/ui/error-emitter/close_window.ascii.stderr @@ -0,0 +1,14 @@ +error[E0624]: method `method` is private + --> $DIR/close_window.rs:9:7 + | +LL | s.method(); + | ^^^^^^ private method + | + ::: $DIR/auxiliary/close_window.rs:3:5 + | +LL | fn method(&self) {} + | ---------------- private method defined here + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0624`. diff --git a/tests/ui/error-emitter/close_window.rs b/tests/ui/error-emitter/close_window.rs new file mode 100644 index 000000000000..879507c287a7 --- /dev/null +++ b/tests/ui/error-emitter/close_window.rs @@ -0,0 +1,11 @@ +//@ aux-build:close_window.rs +//@ revisions: ascii unicode +//@[unicode] compile-flags: -Zunstable-options --error-format=human-unicode + +extern crate close_window; + +fn main() { + let s = close_window::S; + s.method(); + //[ascii]~^ ERROR method `method` is private +} diff --git a/tests/ui/error-emitter/close_window.unicode.stderr b/tests/ui/error-emitter/close_window.unicode.stderr new file mode 100644 index 000000000000..c24b6939af5a --- /dev/null +++ b/tests/ui/error-emitter/close_window.unicode.stderr @@ -0,0 +1,14 @@ +error[E0624]: method `method` is private + ╭▸ $DIR/close_window.rs:9:7 + │ +LL │ s.method(); + ╰╴ ━━━━━━ private method + │ + ⸬ $DIR/auxiliary/close_window.rs:3:5 + │ +LL │ fn method(&self) {} + ╰╴ ──────────────── private method defined here + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0624`. From 8e786169e8136223f6dfac7be85aff339b4cc893 Mon Sep 17 00:00:00 2001 From: Stypox Date: Wed, 30 Jul 2025 17:33:28 +0200 Subject: [PATCH 350/809] Uniform enter_trace_span! and add documentation The macro was uniformed between rustc_const_eval and miri --- .../rustc_const_eval/src/interpret/stack.rs | 4 +- .../rustc_const_eval/src/interpret/util.rs | 63 ++++++++++++++++++- src/tools/miri/src/helpers.rs | 18 +----- 3 files changed, 65 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/stack.rs b/compiler/rustc_const_eval/src/interpret/stack.rs index 2e99bb4209f2..25d163bba62f 100644 --- a/compiler/rustc_const_eval/src/interpret/stack.rs +++ b/compiler/rustc_const_eval/src/interpret/stack.rs @@ -397,9 +397,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Finish things up. M::after_stack_push(self)?; self.frame_mut().loc = Left(mir::Location::START); - // `tracing_separate_thread` is used to instruct the chrome_tracing [tracing::Layer] in Miri + // `tracing_separate_thread` is used to instruct the tracing_chrome [tracing::Layer] in Miri // to put the "frame" span on a separate trace thread/line than other spans, to make the - // visualization in https://ui.perfetto.dev easier to interpret. It is set to a value of + // visualization in easier to interpret. It is set to a value of // [tracing::field::Empty] so that other tracing layers (e.g. the logger) will ignore it. let span = info_span!("frame", tracing_separate_thread = Empty, "{}", instance); self.frame_mut().tracing_span.enter(span); diff --git a/compiler/rustc_const_eval/src/interpret/util.rs b/compiler/rustc_const_eval/src/interpret/util.rs index 72650d545c3c..341756f837ee 100644 --- a/compiler/rustc_const_eval/src/interpret/util.rs +++ b/compiler/rustc_const_eval/src/interpret/util.rs @@ -53,13 +53,72 @@ pub trait EnteredTraceSpan {} impl EnteredTraceSpan for () {} impl EnteredTraceSpan for tracing::span::EnteredSpan {} -/// Shortand for calling [crate::interpret::Machine::enter_trace_span] on a [tracing::info_span]. +/// Shortand for calling [crate::interpret::Machine::enter_trace_span] on a [tracing::info_span!]. /// This is supposed to be compiled out when [crate::interpret::Machine::enter_trace_span] has the /// default implementation (i.e. when it does not actually enter the span but instead returns `()`). +/// This macro takes a type implementing the [crate::interpret::Machine] trait as its first argument +/// and otherwise accepts the same syntax as [tracing::span!] (see some tips below). /// Note: the result of this macro **must be used** because the span is exited when it's dropped. +/// +/// ### Syntax accepted by this macro +/// +/// The full documentation for the [tracing::span!] syntax can be found at [tracing] under "Using the +/// Macros". A few possibly confusing syntaxes are listed here: +/// ```rust +/// # use rustc_const_eval::enter_trace_span; +/// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>; +/// # let my_display_var = String::new(); +/// # let my_debug_var = String::new(); +/// // logs a span named "hello" with a field named "arg" of value 42 (works only because +/// // 42 implements the tracing::Value trait, otherwise use one of the options below) +/// let _span = enter_trace_span!(M, "hello", arg = 42); +/// // logs a field called "my_display_var" using the Display implementation +/// let _span = enter_trace_span!(M, "hello", %my_display_var); +/// // logs a field called "my_debug_var" using the Debug implementation +/// let _span = enter_trace_span!(M, "hello", ?my_debug_var); +/// ``` +/// +/// ### `NAME::SUBNAME` syntax +/// +/// In addition to the syntax accepted by [tracing::span!], this macro optionally allows passing +/// the span name (i.e. the first macro argument) in the form `NAME::SUBNAME` (without quotes) to +/// indicate that the span has name "NAME" (usually the name of the component) and has an additional +/// more specific name "SUBNAME" (usually the function name). The latter is passed to the [tracing] +/// infrastructure as a span field with the name "NAME". This allows not being distracted by +/// subnames when looking at the trace in , but when deeper introspection +/// is needed within a component, it's still possible to view the subnames directly in the UI by +/// selecting a span, clicking on the "NAME" argument on the right, and clicking on "Visualize +/// argument values". +/// ```rust +/// # use rustc_const_eval::enter_trace_span; +/// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>; +/// // for example, the first will expand to the second +/// let _span = enter_trace_span!(M, borrow_tracker::on_stack_pop, /* ... */); +/// let _span = enter_trace_span!(M, "borrow_tracker", borrow_tracker = "on_stack_pop", /* ... */); +/// ``` +/// +/// ### `tracing_separate_thread` parameter +/// +/// This macro was introduced to obtain better traces of Miri without impacting release performance. +/// Miri saves traces using the the `tracing_chrome` `tracing::Layer` so that they can be visualized +/// in . To instruct `tracing_chrome` to put some spans on a separate trace +/// thread/line than other spans when viewed in , you can pass +/// `tracing_separate_thread = tracing::field::Empty` to the tracing macros. This is useful to +/// separate out spans which just indicate the current step or program frame being processed by the +/// interpreter. You should use a value of [tracing::field::Empty] so that other tracing layers +/// (e.g. the logger) will ignore the `tracing_separate_thread` field. For example: +/// ```rust +/// # use rustc_const_eval::enter_trace_span; +/// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>; +/// let _span = enter_trace_span!(M, step::eval_statement, tracing_separate_thread = tracing::field::Empty); +/// ``` #[macro_export] macro_rules! enter_trace_span { + ($machine:ident, $name:ident :: $subname:ident $($tt:tt)*) => {{ + $crate::enter_trace_span!($machine, stringify!($name), $name = %stringify!($subname) $($tt)*) + }}; + ($machine:ident, $($tt:tt)*) => { - $machine::enter_trace_span(|| tracing::info_span!($($tt)*)) + <$machine as $crate::interpret::Machine>::enter_trace_span(|| tracing::info_span!($($tt)*)) } } diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index ab7e35710d34..c52796d358de 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -1257,25 +1257,11 @@ pub struct MaybeEnteredTraceSpan { /// This is like [rustc_const_eval::enter_trace_span] except that it does not depend on the /// [Machine] trait to check if tracing is enabled, because from the Miri codebase we can directly /// check whether the "tracing" feature is enabled, unlike from the rustc_const_eval codebase. -/// -/// In addition to the syntax accepted by [tracing::span!], this macro optionally allows passing -/// the span name (i.e. the first macro argument) in the form `NAME::SUBNAME` (without quotes) to -/// indicate that the span has name "NAME" (usually the name of the component) and has an additional -/// more specific name "SUBNAME" (usually the function name). The latter is passed to the [tracing] -/// infrastructure as a span field with the name "NAME". This allows not being distracted by -/// subnames when looking at the trace in , but when deeper introspection -/// is needed within a component, it's still possible to view the subnames directly in the UI by -/// selecting a span, clicking on the "NAME" argument on the right, and clicking on "Visualize -/// argument values". -/// ```rust -/// // for example, the first will expand to the second -/// enter_trace_span!(borrow_tracker::on_stack_pop, /* ... */) -/// enter_trace_span!("borrow_tracker", borrow_tracker = "on_stack_pop", /* ... */) -/// ``` +/// Look at [rustc_const_eval::enter_trace_span] for complete documentation, examples and tips. #[macro_export] macro_rules! enter_trace_span { ($name:ident :: $subname:ident $($tt:tt)*) => {{ - enter_trace_span!(stringify!($name), $name = %stringify!($subname) $($tt)*) + $crate::enter_trace_span!(stringify!($name), $name = %stringify!($subname) $($tt)*) }}; ($($tt:tt)*) => { From 3b5fec08f1ad2725ffdbd2172035589314b4a4c8 Mon Sep 17 00:00:00 2001 From: Stypox Date: Wed, 30 Jul 2025 18:14:58 +0200 Subject: [PATCH 351/809] Use new enter_trace_span! syntax for layout_of & friends --- compiler/rustc_const_eval/src/interpret/eval_context.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 0a8591ca140d..c4b705d7124e 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -113,7 +113,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// See [LayoutOf::layout_of] for the original documentation. #[inline(always)] pub fn layout_of(&self, ty: Ty<'tcx>) -> >::LayoutOfResult { - let _span = enter_trace_span!(M, "InterpCx::layout_of", ty = ?ty.kind()); + let _span = enter_trace_span!(M, layouting::layout_of, ty = ?ty.kind()); LayoutOf::layout_of(self, ty) } @@ -126,7 +126,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List>, ) -> >::FnAbiOfResult { - let _span = enter_trace_span!(M, "InterpCx::fn_abi_of_fn_ptr", ?sig, ?extra_args); + let _span = enter_trace_span!(M, layouting::fn_abi_of_fn_ptr, ?sig, ?extra_args); FnAbiOf::fn_abi_of_fn_ptr(self, sig, extra_args) } @@ -139,7 +139,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List>, ) -> >::FnAbiOfResult { - let _span = enter_trace_span!(M, "InterpCx::fn_abi_of_instance", ?instance, ?extra_args); + let _span = enter_trace_span!(M, layouting::fn_abi_of_instance, ?instance, ?extra_args); FnAbiOf::fn_abi_of_instance(self, instance, extra_args) } } From e1f674cfa962fc76adbc4cfe95e9b3434299eede Mon Sep 17 00:00:00 2001 From: Stypox Date: Wed, 30 Jul 2025 18:17:02 +0200 Subject: [PATCH 352/809] Use specific name for "frame" span field Otherwise the field would be named "message" by default --- compiler/rustc_const_eval/src/interpret/stack.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_const_eval/src/interpret/stack.rs b/compiler/rustc_const_eval/src/interpret/stack.rs index 25d163bba62f..73cc87508ef9 100644 --- a/compiler/rustc_const_eval/src/interpret/stack.rs +++ b/compiler/rustc_const_eval/src/interpret/stack.rs @@ -401,7 +401,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // to put the "frame" span on a separate trace thread/line than other spans, to make the // visualization in easier to interpret. It is set to a value of // [tracing::field::Empty] so that other tracing layers (e.g. the logger) will ignore it. - let span = info_span!("frame", tracing_separate_thread = Empty, "{}", instance); + let span = info_span!("frame", tracing_separate_thread = Empty, frame = %instance); self.frame_mut().tracing_span.enter(span); interp_ok(()) From 2bf10de494a4ee9cbd5176e00cca8830d778669a Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 29 Jul 2025 14:32:01 +1000 Subject: [PATCH 353/809] Remove unused `impl_decodable_via_ref!` entries. --- compiler/rustc_middle/src/ty/codec.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 335b889b14dc..95759d1f31a7 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -510,12 +510,9 @@ impl_decodable_via_ref! { &'tcx ty::List>, &'tcx traits::ImplSource<'tcx, ()>, &'tcx mir::Body<'tcx>, - &'tcx mir::ConcreteOpaqueTypes<'tcx>, &'tcx ty::List, &'tcx ty::List>, &'tcx ty::ListWithCachedTypeInfo>, - &'tcx ty::List, - &'tcx ty::List<(VariantIdx, FieldIdx)>, } #[macro_export] From e83c8cb26cd068cb23ca079d2992a08bed240385 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 08:38:52 +1000 Subject: [PATCH 354/809] Move `ResolverOutputs` out of `rustc_middle`. It's not used in `rustc_middle`, and `rustc_resolve` is a better place for it. --- compiler/rustc_interface/src/passes.rs | 4 ++-- compiler/rustc_middle/src/ty/mod.rs | 5 ----- compiler/rustc_resolve/src/lib.rs | 9 +++++++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 057fbe2fc4e0..83ac981429c8 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -29,7 +29,7 @@ use rustc_parse::{ new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal, validate_attr, }; use rustc_passes::{abi_test, input_stats, layout_test}; -use rustc_resolve::Resolver; +use rustc_resolve::{Resolver, ResolverOutputs}; use rustc_session::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType}; use rustc_session::cstore::Untracked; use rustc_session::output::{collect_crate_types, filename_for_input}; @@ -793,7 +793,7 @@ fn resolver_for_lowering_raw<'tcx>( // Make sure we don't mutate the cstore from here on. tcx.untracked().cstore.freeze(); - let ty::ResolverOutputs { + let ResolverOutputs { global_ctxt: untracked_resolutions, ast_lowering: untracked_resolver_for_lowering, } = resolver.into_outputs(); diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index bb70c61cd141..a0a6e3bab247 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -170,11 +170,6 @@ mod visit; // Data types -pub struct ResolverOutputs { - pub global_ctxt: ResolverGlobalCtxt, - pub ast_lowering: ResolverAstLowering, -} - #[derive(Debug, HashStable)] pub struct ResolverGlobalCtxt { pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>, diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 88dfb50b47dd..a70ae4fd57a0 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -64,8 +64,8 @@ use rustc_middle::middle::privacy::EffectiveVisibilities; use rustc_middle::query::Providers; use rustc_middle::span_bug; use rustc_middle::ty::{ - self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverGlobalCtxt, - ResolverOutputs, TyCtxt, TyCtxtFeed, Visibility, + self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverAstLowering, + ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility, }; use rustc_query_system::ich::StableHashingContext; use rustc_session::lint::builtin::PRIVATE_MACRO_USE; @@ -1037,6 +1037,11 @@ impl MacroData { } } +pub struct ResolverOutputs { + pub global_ctxt: ResolverGlobalCtxt, + pub ast_lowering: ResolverAstLowering, +} + /// The main resolver class. /// /// This is the visitor that walks the whole crate. From 790ab947989cd0a2161a4e3b281ada90734dd134 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 08:46:51 +1000 Subject: [PATCH 355/809] Move `ImplHeader` out of `rustc_middle`. It's not used in `rustc_middle`, and `rustc_trait_selection` is a better place for it. --- compiler/rustc_middle/src/ty/mod.rs | 12 --------- .../src/traits/coherence.rs | 25 ++++++++++++++----- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index a0a6e3bab247..6e368948f29c 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -250,18 +250,6 @@ impl MainDefinition { } } -/// The "header" of an impl is everything outside the body: a Self type, a trait -/// ref (in the case of a trait impl), and a set of predicates (from the -/// bounds / where-clauses). -#[derive(Clone, Debug, TypeFoldable, TypeVisitable)] -pub struct ImplHeader<'tcx> { - pub impl_def_id: DefId, - pub impl_args: ty::GenericArgsRef<'tcx>, - pub self_ty: Ty<'tcx>, - pub trait_ref: Option>, - pub predicates: Vec>, -} - #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)] pub struct ImplTraitHeader<'tcx> { pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>, diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 07e78da37b3b..517333d15613 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -12,6 +12,7 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::PredicateObligations; +use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::bug; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal}; @@ -37,8 +38,20 @@ use crate::traits::{ SelectionContext, SkipLeakCheck, util, }; +/// The "header" of an impl is everything outside the body: a Self type, a trait +/// ref (in the case of a trait impl), and a set of predicates (from the +/// bounds / where-clauses). +#[derive(Clone, Debug, TypeFoldable, TypeVisitable)] +pub struct ImplHeader<'tcx> { + pub impl_def_id: DefId, + pub impl_args: ty::GenericArgsRef<'tcx>, + pub self_ty: Ty<'tcx>, + pub trait_ref: Option>, + pub predicates: Vec>, +} + pub struct OverlapResult<'tcx> { - pub impl_header: ty::ImplHeader<'tcx>, + pub impl_header: ImplHeader<'tcx>, pub intercrate_ambiguity_causes: FxIndexSet>, /// `true` if the overlap might've been permitted before the shift @@ -151,11 +164,11 @@ pub fn overlapping_impls( } } -fn fresh_impl_header<'tcx>(infcx: &InferCtxt<'tcx>, impl_def_id: DefId) -> ty::ImplHeader<'tcx> { +fn fresh_impl_header<'tcx>(infcx: &InferCtxt<'tcx>, impl_def_id: DefId) -> ImplHeader<'tcx> { let tcx = infcx.tcx; let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id); - ty::ImplHeader { + ImplHeader { impl_def_id, impl_args, self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args), @@ -173,7 +186,7 @@ fn fresh_impl_header_normalized<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, impl_def_id: DefId, -) -> ty::ImplHeader<'tcx> { +) -> ImplHeader<'tcx> { let header = fresh_impl_header(infcx, impl_def_id); let InferOk { value: mut header, obligations } = @@ -287,8 +300,8 @@ fn overlap<'tcx>( fn equate_impl_headers<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - impl1: &ty::ImplHeader<'tcx>, - impl2: &ty::ImplHeader<'tcx>, + impl1: &ImplHeader<'tcx>, + impl2: &ImplHeader<'tcx>, ) -> Option> { let result = match (impl1.trait_ref, impl2.trait_ref) { From 3a1f2d5cc23a7e6da66edc5fede26a8acac08167 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 08:54:12 +1000 Subject: [PATCH 356/809] Move an `EarlyParamRegion` impl block. Next to all the other `EarlyParamRegion` pieces. --- compiler/rustc_middle/src/ty/mod.rs | 10 +--------- compiler/rustc_middle/src/ty/region.rs | 8 ++++++++ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 6e368948f29c..67828185485f 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -49,7 +49,7 @@ use rustc_serialize::{Decodable, Encodable}; use rustc_session::lint::LintBuffer; pub use rustc_session::lint::RegisteredTools; use rustc_span::hygiene::MacroKind; -use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym}; pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet}; pub use rustc_type_ir::fast_reject::DeepRejectCtxt; #[allow( @@ -453,14 +453,6 @@ impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> { } } -impl EarlyParamRegion { - /// Does this early bound region have a name? Early bound regions normally - /// always have names except when using anonymous lifetimes (`'_`). - pub fn is_named(&self) -> bool { - self.name != kw::UnderscoreLifetime - } -} - /// The crate outlives map is computed during typeck and contains the /// outlives of every item in the local crate. You should not use it /// directly, because to do so will make your pass dependent on the diff --git a/compiler/rustc_middle/src/ty/region.rs b/compiler/rustc_middle/src/ty/region.rs index 5cf960721776..600dfc2ff690 100644 --- a/compiler/rustc_middle/src/ty/region.rs +++ b/compiler/rustc_middle/src/ty/region.rs @@ -324,6 +324,14 @@ pub struct EarlyParamRegion { pub name: Symbol, } +impl EarlyParamRegion { + /// Does this early bound region have a name? Early bound regions normally + /// always have names except when using anonymous lifetimes (`'_`). + pub fn is_named(&self) -> bool { + self.name != kw::UnderscoreLifetime + } +} + impl rustc_type_ir::inherent::ParamLike for EarlyParamRegion { fn index(self) -> u32 { self.index From b44eb11bdfaf98f5c9bf115af43b62634569c69d Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 09:03:55 +1000 Subject: [PATCH 357/809] Move `ParamTerm` out of `rustc_middle`. It's only used in `rustc_hir_typeck`. --- .../src/fn_ctxt/adjust_fulfillment_errors.rs | 25 +++++++++++++++---- compiler/rustc_middle/src/ty/mod.rs | 15 ----------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index 4e4bf8a5562e..ed88e32a2736 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -17,6 +17,21 @@ enum ClauseFlavor { Const, } +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +enum ParamTerm { + Ty(ty::ParamTy), + Const(ty::ParamConst), +} + +impl ParamTerm { + fn index(self) -> usize { + match self { + ParamTerm::Ty(ty) => ty.index as usize, + ParamTerm::Const(ct) => ct.index as usize, + } + } +} + impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(crate) fn adjust_fulfillment_error_for_expr_obligation( &self, @@ -77,17 +92,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => return false, }; - let find_param_matching = |matches: &dyn Fn(ty::ParamTerm) -> bool| { + let find_param_matching = |matches: &dyn Fn(ParamTerm) -> bool| { predicate_args.iter().find_map(|arg| { arg.walk().find_map(|arg| { if let ty::GenericArgKind::Type(ty) = arg.kind() && let ty::Param(param_ty) = *ty.kind() - && matches(ty::ParamTerm::Ty(param_ty)) + && matches(ParamTerm::Ty(param_ty)) { Some(arg) } else if let ty::GenericArgKind::Const(ct) = arg.kind() && let ty::ConstKind::Param(param_ct) = ct.kind() - && matches(ty::ParamTerm::Const(param_ct)) + && matches(ParamTerm::Const(param_ct)) { Some(arg) } else { @@ -106,14 +121,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // from a trait or impl, for example. let mut fallback_param_to_point_at = find_param_matching(&|param_term| { self.tcx.parent(generics.param_at(param_term.index(), self.tcx).def_id) != def_id - && !matches!(param_term, ty::ParamTerm::Ty(ty) if ty.name == kw::SelfUpper) + && !matches!(param_term, ParamTerm::Ty(ty) if ty.name == kw::SelfUpper) }); // Finally, the `Self` parameter is possibly the reason that the predicate // is unsatisfied. This is less likely to be true for methods, because // method probe means that we already kinda check that the predicates due // to the `Self` type are true. let mut self_param_to_point_at = find_param_matching( - &|param_term| matches!(param_term, ty::ParamTerm::Ty(ty) if ty.name == kw::SelfUpper), + &|param_term| matches!(param_term, ParamTerm::Ty(ty) if ty.name == kw::SelfUpper), ); // Finally, for ambiguity-related errors, we actually want to look diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 67828185485f..1e70d63539df 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -673,21 +673,6 @@ impl<'tcx> TermKind<'tcx> { } } -#[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub enum ParamTerm { - Ty(ParamTy), - Const(ParamConst), -} - -impl ParamTerm { - pub fn index(self) -> usize { - match self { - ParamTerm::Ty(ty) => ty.index as usize, - ParamTerm::Const(ct) => ct.index as usize, - } - } -} - #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum TermVid { Ty(ty::TyVid), From 51cd9b564f75b8330893b919b90e293530d1c395 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 31 Jul 2025 02:12:32 +0000 Subject: [PATCH 358/809] Consider operator's span when computing binop expr span --- compiler/rustc_parse/src/parser/expr.rs | 13 ++++++++----- compiler/rustc_parse/src/validate_attr.rs | 2 +- tests/ui/lint/wide_pointer_comparisons.rs | 4 +--- tests/ui/lint/wide_pointer_comparisons.stderr | 18 ++++++++++-------- 4 files changed, 20 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 54d8a7910258..35b987cf50fa 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -263,10 +263,11 @@ impl<'a> Parser<'a> { continue; } + let op_span = op.span; let op = op.node; // Special cases: if op == AssocOp::Cast { - lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?; + lhs = self.parse_assoc_op_cast(lhs, lhs_span, op_span, ExprKind::Cast)?; continue; } else if let AssocOp::Range(limits) = op { // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to @@ -284,7 +285,7 @@ impl<'a> Parser<'a> { this.parse_expr_assoc_with(min_prec, attrs) })?; - let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span); + let span = self.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span); lhs = match op { AssocOp::Binary(ast_op) => { let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs); @@ -429,7 +430,7 @@ impl<'a> Parser<'a> { None }; let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span); - let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span); + let span = self.mk_expr_sp(&lhs, lhs.span, cur_op_span, rhs_span); let range = self.mk_range(Some(lhs), rhs, limits); Ok(self.mk_expr(span, range)) } @@ -654,10 +655,11 @@ impl<'a> Parser<'a> { &mut self, lhs: P, lhs_span: Span, + op_span: Span, expr_kind: fn(P, P) -> ExprKind, ) -> PResult<'a, P> { let mk_expr = |this: &mut Self, lhs: P, rhs: P| { - this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, rhs.span), expr_kind(lhs, rhs)) + this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span), expr_kind(lhs, rhs)) }; // Save the state of the parser before parsing type normally, in case there is a @@ -4005,11 +4007,12 @@ impl<'a> Parser<'a> { /// Create expression span ensuring the span of the parent node /// is larger than the span of lhs and rhs, including the attributes. - fn mk_expr_sp(&self, lhs: &P, lhs_span: Span, rhs_span: Span) -> Span { + fn mk_expr_sp(&self, lhs: &P, lhs_span: Span, op_span: Span, rhs_span: Span) -> Span { lhs.attrs .iter() .find(|a| a.style == AttrStyle::Outer) .map_or(lhs_span, |a| a.span) + .to(op_span) .to(rhs_span) } diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index bc4c605afadb..a7f8d3b9139d 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -106,7 +106,7 @@ pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Met res } else { // Example cases: - // - `#[foo = 1+1]`: results in `ast::ExprKind::BinOp`. + // - `#[foo = 1+1]`: results in `ast::ExprKind::Binary`. // - `#[foo = include_str!("nonexistent-file.rs")]`: // results in `ast::ExprKind::Err`. In that case we delay // the error because an earlier error will have already diff --git a/tests/ui/lint/wide_pointer_comparisons.rs b/tests/ui/lint/wide_pointer_comparisons.rs index 05097cbf1e3d..a5e3f4754b8f 100644 --- a/tests/ui/lint/wide_pointer_comparisons.rs +++ b/tests/ui/lint/wide_pointer_comparisons.rs @@ -146,12 +146,10 @@ fn main() { { macro_rules! cmp { ($a:tt, $b:tt) => { $a == $b } + //~^ WARN ambiguous wide pointer comparison } - // FIXME: This lint uses some custom span combination logic. - // Rewrite it to adapt to the new metavariable span rules. cmp!(a, b); - //~^ WARN ambiguous wide pointer comparison } { diff --git a/tests/ui/lint/wide_pointer_comparisons.stderr b/tests/ui/lint/wide_pointer_comparisons.stderr index 4f5238e8252f..4199ff62e2a3 100644 --- a/tests/ui/lint/wide_pointer_comparisons.stderr +++ b/tests/ui/lint/wide_pointer_comparisons.stderr @@ -720,18 +720,20 @@ LL + std::ptr::eq(*a, *b) | warning: ambiguous wide pointer comparison, the comparison includes metadata which may not be expected - --> $DIR/wide_pointer_comparisons.rs:153:14 + --> $DIR/wide_pointer_comparisons.rs:148:33 | +LL | ($a:tt, $b:tt) => { $a == $b } + | ^^^^^^^^ +... LL | cmp!(a, b); - | ^^^^ + | ---------- in this macro invocation | -help: use `std::ptr::addr_eq` or untyped pointers to only compare their addresses - | -LL | cmp!(std::ptr::addr_eq(a, b)); - | ++++++++++++++++++ + + = help: use explicit `std::ptr::eq` method to compare metadata and addresses + = help: use `std::ptr::addr_eq` or untyped pointers to only compare their addresses + = note: this warning originates in the macro `cmp` (in Nightly builds, run with -Z macro-backtrace for more info) warning: ambiguous wide pointer comparison, the comparison includes metadata which may not be expected - --> $DIR/wide_pointer_comparisons.rs:159:39 + --> $DIR/wide_pointer_comparisons.rs:157:39 | LL | ($a:ident, $b:ident) => { $a == $b } | ^^^^^^^^ @@ -747,7 +749,7 @@ LL + ($a:ident, $b:ident) => { std::ptr::addr_eq($a, $b) } | warning: ambiguous wide pointer comparison, the comparison includes metadata which may not be expected - --> $DIR/wide_pointer_comparisons.rs:169:37 + --> $DIR/wide_pointer_comparisons.rs:167:37 | LL | ($a:expr, $b:expr) => { $a == $b } | ^^^^^^^^ 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 359/809] 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 360/809] 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 0a3eb2f88e13740bacbcba1c61855edf61d7d6c0 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 14:57:46 +1000 Subject: [PATCH 361/809] Remove unused `ParameterizedOverTcx` impls. --- compiler/rustc_middle/src/ty/parameterized.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs index dbacbe21edb7..d9c8fe96c473 100644 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ b/compiler/rustc_middle/src/ty/parameterized.rs @@ -11,10 +11,6 @@ pub trait ParameterizedOverTcx: 'static { type Value<'tcx>; } -impl ParameterizedOverTcx for &'static [T] { - type Value<'tcx> = &'tcx [T::Value<'tcx>]; -} - impl ParameterizedOverTcx for Option { type Value<'tcx> = Option>; } @@ -57,8 +53,6 @@ macro_rules! trivially_parameterized_over_tcx { trivially_parameterized_over_tcx! { usize, - (), - u32, u64, bool, std::string::String, @@ -76,16 +70,13 @@ trivially_parameterized_over_tcx! { ty::DeducedParamAttrs, ty::Destructor, ty::Generics, - ty::ImplPolarity, ty::ImplTraitInTraitData, ty::ReprOptions, ty::TraitDef, - ty::UnusedGenericParams, ty::Visibility, ty::adjustment::CoerceUnsizedInfo, ty::fast_reject::SimplifiedType, ty::IntrinsicDef, - rustc_ast::Attribute, rustc_ast::DelimArgs, rustc_attr_data_structures::StrippedCfgItem, rustc_attr_data_structures::ConstStability, @@ -96,7 +87,6 @@ trivially_parameterized_over_tcx! { rustc_hir::Defaultness, rustc_hir::Safety, rustc_hir::CoroutineKind, - rustc_hir::IsAsync, rustc_hir::LangItem, rustc_hir::def::DefKind, rustc_hir::def::DocLinkResMap, @@ -106,7 +96,6 @@ trivially_parameterized_over_tcx! { rustc_hir::OpaqueTyOrigin, rustc_hir::PreciseCapturingArgKind, rustc_index::bit_set::DenseBitSet, - rustc_index::bit_set::FiniteBitSet, rustc_session::cstore::ForeignModule, rustc_session::cstore::LinkagePreference, rustc_session::cstore::NativeLib, @@ -117,7 +106,6 @@ trivially_parameterized_over_tcx! { rustc_span::SourceFile, rustc_span::Span, rustc_span::Symbol, - rustc_span::def_id::DefPathHash, rustc_span::hygiene::SyntaxContextKey, rustc_span::Ident, rustc_type_ir::Variance, @@ -148,7 +136,6 @@ parameterized_over_tcx! { ty::ConstConditions, ty::TraitRef, ty::Const, - ty::Predicate, ty::Clause, ty::ClauseKind, ty::ImplTraitHeader, From 66fd421208c4ed74f24eaab1f50f70993a8133aa Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 15:04:51 +1000 Subject: [PATCH 362/809] Move `rustc_middle::parameterized` to `rustc_metadata`. It's only used there. --- .../src/rmeta/def_path_hash_map.rs | 5 - compiler/rustc_metadata/src/rmeta/mod.rs | 31 +--- .../rustc_metadata/src/rmeta/parameterized.rs | 166 ++++++++++++++++++ compiler/rustc_middle/src/ty/mod.rs | 2 - compiler/rustc_middle/src/ty/parameterized.rs | 142 --------------- 5 files changed, 170 insertions(+), 176 deletions(-) create mode 100644 compiler/rustc_metadata/src/rmeta/parameterized.rs delete mode 100644 compiler/rustc_middle/src/ty/parameterized.rs diff --git a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs index 19369425f816..f3917b55782b 100644 --- a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs +++ b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs @@ -1,6 +1,5 @@ use rustc_data_structures::owned_slice::OwnedSlice; use rustc_hir::def_path_hash_map::{Config as HashMapConfig, DefPathHashMap}; -use rustc_middle::parameterized_over_tcx; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_span::def_id::{DefIndex, DefPathHash}; @@ -11,10 +10,6 @@ pub(crate) enum DefPathHashMapRef<'tcx> { BorrowedFromTcx(&'tcx DefPathHashMap), } -parameterized_over_tcx! { - DefPathHashMapRef, -} - impl DefPathHashMapRef<'_> { #[inline] pub(crate) fn def_path_hash_to_def_index(&self, def_path_hash: &DefPathHash) -> DefIndex { diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 915c97316880..9de5e12d5bb6 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -6,6 +6,7 @@ use decoder::{DecodeContext, Metadata}; use def_path_hash_map::DefPathHashMapRef; use encoder::EncodeContext; pub use encoder::{EncodedMetadata, encode_metadata, rendered_const}; +pub(crate) use parameterized::ParameterizedOverTcx; use rustc_abi::{FieldIdx, ReprOptions, VariantIdx}; use rustc_attr_data_structures::StrippedCfgItem; use rustc_data_structures::fx::FxHashMap; @@ -26,12 +27,10 @@ use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use rustc_middle::middle::lib_features::FeatureStability; use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault; +use rustc_middle::mir; use rustc_middle::ty::fast_reject::SimplifiedType; -use rustc_middle::ty::{ - self, DeducedParamAttrs, ParameterizedOverTcx, Ty, TyCtxt, UnusedGenericParams, -}; +use rustc_middle::ty::{self, DeducedParamAttrs, Ty, TyCtxt, UnusedGenericParams}; use rustc_middle::util::Providers; -use rustc_middle::{mir, trivially_parameterized_over_tcx}; use rustc_serialize::opaque::FileEncoder; use rustc_session::config::{SymbolManglingVersion, TargetModifier}; use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib}; @@ -47,6 +46,7 @@ use crate::creader::CrateMetadataRef; mod decoder; mod def_path_hash_map; mod encoder; +mod parameterized; mod table; pub(crate) fn rustc_version(cfg_version: &'static str) -> String { @@ -86,10 +86,6 @@ struct LazyValue { _marker: PhantomData T>, } -impl ParameterizedOverTcx for LazyValue { - type Value<'tcx> = LazyValue>; -} - impl LazyValue { fn from_position(position: NonZero) -> LazyValue { LazyValue { position, _marker: PhantomData } @@ -112,10 +108,6 @@ struct LazyArray { _marker: PhantomData T>, } -impl ParameterizedOverTcx for LazyArray { - type Value<'tcx> = LazyArray>; -} - impl Default for LazyArray { fn default() -> LazyArray { LazyArray::from_position_and_num_elems(NonZero::new(1).unwrap(), 0) @@ -143,10 +135,6 @@ struct LazyTable { _marker: PhantomData T>, } -impl ParameterizedOverTcx for LazyTable { - type Value<'tcx> = LazyTable>; -} - impl LazyTable { fn from_position_and_encoded_size( position: NonZero, @@ -594,14 +582,3 @@ pub fn provide(providers: &mut Providers) { encoder::provide(providers); decoder::provide(providers); } - -trivially_parameterized_over_tcx! { - VariantData, - RawDefId, - TraitImpls, - IncoherentImpls, - CrateHeader, - CrateRoot, - CrateDep, - AttrFlags, -} diff --git a/compiler/rustc_metadata/src/rmeta/parameterized.rs b/compiler/rustc_metadata/src/rmeta/parameterized.rs new file mode 100644 index 000000000000..7cd399baa42e --- /dev/null +++ b/compiler/rustc_metadata/src/rmeta/parameterized.rs @@ -0,0 +1,166 @@ +use std::hash::Hash; + +use rustc_data_structures::unord::UnordMap; +use rustc_hir::def_id::DefIndex; +use rustc_index::{Idx, IndexVec}; +use rustc_middle::ty::{Binder, EarlyBinder}; +use rustc_span::Symbol; + +use crate::rmeta::{LazyArray, LazyTable, LazyValue}; + +pub(crate) trait ParameterizedOverTcx: 'static { + type Value<'tcx>; +} + +impl ParameterizedOverTcx for Option { + type Value<'tcx> = Option>; +} + +impl ParameterizedOverTcx for (A, B) { + type Value<'tcx> = (A::Value<'tcx>, B::Value<'tcx>); +} + +impl ParameterizedOverTcx for Vec { + type Value<'tcx> = Vec>; +} + +impl ParameterizedOverTcx for IndexVec { + type Value<'tcx> = IndexVec>; +} + +impl ParameterizedOverTcx for UnordMap { + type Value<'tcx> = UnordMap>; +} + +impl ParameterizedOverTcx for Binder<'static, T> { + type Value<'tcx> = Binder<'tcx, T::Value<'tcx>>; +} + +impl ParameterizedOverTcx for EarlyBinder<'static, T> { + type Value<'tcx> = EarlyBinder<'tcx, T::Value<'tcx>>; +} + +impl ParameterizedOverTcx for LazyValue { + type Value<'tcx> = LazyValue>; +} + +impl ParameterizedOverTcx for LazyArray { + type Value<'tcx> = LazyArray>; +} + +impl ParameterizedOverTcx for LazyTable { + type Value<'tcx> = LazyTable>; +} + +macro_rules! trivially_parameterized_over_tcx { + ($($ty:ty),+ $(,)?) => { + $( + impl ParameterizedOverTcx for $ty { + #[allow(unused_lifetimes)] + type Value<'tcx> = $ty; + } + )* + } +} + +trivially_parameterized_over_tcx! { + bool, + u64, + usize, + std::string::String, + // tidy-alphabetical-start + crate::rmeta::AttrFlags, + crate::rmeta::CrateDep, + crate::rmeta::CrateHeader, + crate::rmeta::CrateRoot, + crate::rmeta::IncoherentImpls, + crate::rmeta::RawDefId, + crate::rmeta::TraitImpls, + crate::rmeta::VariantData, + rustc_abi::ReprOptions, + rustc_ast::DelimArgs, + rustc_attr_data_structures::ConstStability, + rustc_attr_data_structures::DefaultBodyStability, + rustc_attr_data_structures::Deprecation, + rustc_attr_data_structures::Stability, + rustc_attr_data_structures::StrippedCfgItem, + rustc_hir::Attribute, + rustc_hir::Constness, + rustc_hir::CoroutineKind, + rustc_hir::Defaultness, + rustc_hir::LangItem, + rustc_hir::OpaqueTyOrigin, + rustc_hir::PreciseCapturingArgKind, + rustc_hir::Safety, + rustc_hir::def::DefKind, + rustc_hir::def::DocLinkResMap, + rustc_hir::def_id::DefId, + rustc_hir::def_id::DefIndex, + rustc_hir::definitions::DefKey, + rustc_index::bit_set::DenseBitSet, + rustc_middle::metadata::ModChild, + rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs, + rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile, + rustc_middle::middle::exported_symbols::SymbolExportInfo, + rustc_middle::middle::lib_features::FeatureStability, + rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault, + rustc_middle::mir::ConstQualifs, + rustc_middle::ty::AnonConstKind, + rustc_middle::ty::AssocItemContainer, + rustc_middle::ty::AsyncDestructor, + rustc_middle::ty::Asyncness, + rustc_middle::ty::DeducedParamAttrs, + rustc_middle::ty::Destructor, + rustc_middle::ty::Generics, + rustc_middle::ty::ImplTraitInTraitData, + rustc_middle::ty::IntrinsicDef, + rustc_middle::ty::TraitDef, + rustc_middle::ty::Variance, + rustc_middle::ty::Visibility, + rustc_middle::ty::adjustment::CoerceUnsizedInfo, + rustc_middle::ty::fast_reject::SimplifiedType, + rustc_session::config::TargetModifier, + rustc_session::cstore::ForeignModule, + rustc_session::cstore::LinkagePreference, + rustc_session::cstore::NativeLib, + rustc_span::ExpnData, + rustc_span::ExpnHash, + rustc_span::ExpnId, + rustc_span::Ident, + rustc_span::SourceFile, + rustc_span::Span, + rustc_span::Symbol, + rustc_span::hygiene::SyntaxContextKey, + // tidy-alphabetical-end +} + +// HACK(compiler-errors): This macro rule can only take a fake path, +// not a real, due to parsing ambiguity reasons. +macro_rules! parameterized_over_tcx { + ($($( $fake_path:ident )::+ ),+ $(,)?) => { + $( + impl ParameterizedOverTcx for $( $fake_path )::+ <'static> { + type Value<'tcx> = $( $fake_path )::+ <'tcx>; + } + )* + } +} + +parameterized_over_tcx! { + // tidy-alphabetical-start + crate::rmeta::DefPathHashMapRef, + rustc_middle::middle::exported_symbols::ExportedSymbol, + rustc_middle::mir::Body, + rustc_middle::mir::CoroutineLayout, + rustc_middle::mir::interpret::ConstAllocation, + rustc_middle::ty::Clause, + rustc_middle::ty::ClauseKind, + rustc_middle::ty::Const, + rustc_middle::ty::ConstConditions, + rustc_middle::ty::FnSig, + rustc_middle::ty::GenericPredicates, + rustc_middle::ty::ImplTraitHeader, + rustc_middle::ty::TraitRef, + rustc_middle::ty::Ty, + // tidy-alphabetical-end +} diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index bb70c61cd141..5b7f34e0e77a 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -85,7 +85,6 @@ pub use self::fold::*; pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams}; pub use self::list::{List, ListWithCachedTypeInfo}; pub use self::opaque_types::OpaqueTypeKey; -pub use self::parameterized::ParameterizedOverTcx; pub use self::pattern::{Pattern, PatternKind}; pub use self::predicate::{ AliasTerm, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate, ExistentialPredicate, @@ -158,7 +157,6 @@ mod instance; mod intrinsic; mod list; mod opaque_types; -mod parameterized; mod predicate; mod region; mod rvalue_scopes; diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs deleted file mode 100644 index d9c8fe96c473..000000000000 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ /dev/null @@ -1,142 +0,0 @@ -use std::hash::Hash; - -use rustc_data_structures::unord::UnordMap; -use rustc_hir::def_id::DefIndex; -use rustc_index::{Idx, IndexVec}; -use rustc_span::Symbol; - -use crate::ty; - -pub trait ParameterizedOverTcx: 'static { - type Value<'tcx>; -} - -impl ParameterizedOverTcx for Option { - type Value<'tcx> = Option>; -} - -impl ParameterizedOverTcx for (A, B) { - type Value<'tcx> = (A::Value<'tcx>, B::Value<'tcx>); -} - -impl ParameterizedOverTcx for Vec { - type Value<'tcx> = Vec>; -} - -impl ParameterizedOverTcx for IndexVec { - type Value<'tcx> = IndexVec>; -} - -impl ParameterizedOverTcx for UnordMap { - type Value<'tcx> = UnordMap>; -} - -impl ParameterizedOverTcx for ty::Binder<'static, T> { - type Value<'tcx> = ty::Binder<'tcx, T::Value<'tcx>>; -} - -impl ParameterizedOverTcx for ty::EarlyBinder<'static, T> { - type Value<'tcx> = ty::EarlyBinder<'tcx, T::Value<'tcx>>; -} - -#[macro_export] -macro_rules! trivially_parameterized_over_tcx { - ($($ty:ty),+ $(,)?) => { - $( - impl $crate::ty::ParameterizedOverTcx for $ty { - #[allow(unused_lifetimes)] - type Value<'tcx> = $ty; - } - )* - } -} - -trivially_parameterized_over_tcx! { - usize, - u64, - bool, - std::string::String, - crate::metadata::ModChild, - crate::middle::codegen_fn_attrs::CodegenFnAttrs, - crate::middle::debugger_visualizer::DebuggerVisualizerFile, - crate::middle::exported_symbols::SymbolExportInfo, - crate::middle::lib_features::FeatureStability, - crate::middle::resolve_bound_vars::ObjectLifetimeDefault, - crate::mir::ConstQualifs, - ty::AsyncDestructor, - ty::AssocItemContainer, - ty::Asyncness, - ty::AnonConstKind, - ty::DeducedParamAttrs, - ty::Destructor, - ty::Generics, - ty::ImplTraitInTraitData, - ty::ReprOptions, - ty::TraitDef, - ty::Visibility, - ty::adjustment::CoerceUnsizedInfo, - ty::fast_reject::SimplifiedType, - ty::IntrinsicDef, - rustc_ast::DelimArgs, - rustc_attr_data_structures::StrippedCfgItem, - rustc_attr_data_structures::ConstStability, - rustc_attr_data_structures::DefaultBodyStability, - rustc_attr_data_structures::Deprecation, - rustc_attr_data_structures::Stability, - rustc_hir::Constness, - rustc_hir::Defaultness, - rustc_hir::Safety, - rustc_hir::CoroutineKind, - rustc_hir::LangItem, - rustc_hir::def::DefKind, - rustc_hir::def::DocLinkResMap, - rustc_hir::def_id::DefId, - rustc_hir::def_id::DefIndex, - rustc_hir::definitions::DefKey, - rustc_hir::OpaqueTyOrigin, - rustc_hir::PreciseCapturingArgKind, - rustc_index::bit_set::DenseBitSet, - rustc_session::cstore::ForeignModule, - rustc_session::cstore::LinkagePreference, - rustc_session::cstore::NativeLib, - rustc_session::config::TargetModifier, - rustc_span::ExpnData, - rustc_span::ExpnHash, - rustc_span::ExpnId, - rustc_span::SourceFile, - rustc_span::Span, - rustc_span::Symbol, - rustc_span::hygiene::SyntaxContextKey, - rustc_span::Ident, - rustc_type_ir::Variance, - rustc_hir::Attribute, -} - -// HACK(compiler-errors): This macro rule can only take a fake path, -// not a real, due to parsing ambiguity reasons. -#[macro_export] -macro_rules! parameterized_over_tcx { - ($($($fake_path:ident)::+),+ $(,)?) => { - $( - impl $crate::ty::ParameterizedOverTcx for $($fake_path)::+<'static> { - type Value<'tcx> = $($fake_path)::+<'tcx>; - } - )* - } -} - -parameterized_over_tcx! { - crate::middle::exported_symbols::ExportedSymbol, - crate::mir::Body, - crate::mir::CoroutineLayout, - crate::mir::interpret::ConstAllocation, - ty::Ty, - ty::FnSig, - ty::GenericPredicates, - ty::ConstConditions, - ty::TraitRef, - ty::Const, - ty::Clause, - ty::ClauseKind, - ty::ImplTraitHeader, -} From c4e3cc02281d898a6c9424f1bcebfb5ca38ca37f Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 13:01:27 +1000 Subject: [PATCH 363/809] Move `TermVid` out of `rustc_middle`. It's only used in `rustc_infer`. --- .../src/infer/relate/generalize.rs | 36 +++++++++++++------ compiler/rustc_middle/src/ty/mod.rs | 18 ---------- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index 9e451f16a9d8..a000bb1123c1 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -19,6 +19,24 @@ use crate::infer::type_variable::TypeVariableValue; use crate::infer::unify_key::ConstVariableValue; use crate::infer::{InferCtxt, RegionVariableOrigin, relate}; +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +enum TermVid { + Ty(ty::TyVid), + Const(ty::ConstVid), +} + +impl From for TermVid { + fn from(value: ty::TyVid) -> Self { + TermVid::Ty(value) + } +} + +impl From for TermVid { + fn from(value: ty::ConstVid) -> Self { + TermVid::Const(value) + } +} + impl<'tcx> InferCtxt<'tcx> { /// The idea is that we should ensure that the type variable `target_vid` /// is equal to, a subtype of, or a supertype of `source_ty`. @@ -238,20 +256,18 @@ impl<'tcx> InferCtxt<'tcx> { &self, span: Span, structurally_relate_aliases: StructurallyRelateAliases, - target_vid: impl Into, + target_vid: impl Into, ambient_variance: ty::Variance, source_term: T, ) -> RelateResult<'tcx, Generalization> { assert!(!source_term.has_escaping_bound_vars()); let (for_universe, root_vid) = match target_vid.into() { - ty::TermVid::Ty(ty_vid) => { - (self.probe_ty_var(ty_vid).unwrap_err(), ty::TermVid::Ty(self.root_var(ty_vid))) + TermVid::Ty(ty_vid) => { + (self.probe_ty_var(ty_vid).unwrap_err(), TermVid::Ty(self.root_var(ty_vid))) } - ty::TermVid::Const(ct_vid) => ( + TermVid::Const(ct_vid) => ( self.probe_const_var(ct_vid).unwrap_err(), - ty::TermVid::Const( - self.inner.borrow_mut().const_unification_table().find(ct_vid).vid, - ), + TermVid::Const(self.inner.borrow_mut().const_unification_table().find(ct_vid).vid), ), }; @@ -299,7 +315,7 @@ struct Generalizer<'me, 'tcx> { /// The vid of the type variable that is in the process of being /// instantiated. If we find this within the value we are folding, /// that means we would have created a cyclic value. - root_vid: ty::TermVid, + root_vid: TermVid, /// The universe of the type variable that is in the process of being /// instantiated. If we find anything that this universe cannot name, @@ -469,7 +485,7 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { ty::Infer(ty::TyVar(vid)) => { let mut inner = self.infcx.inner.borrow_mut(); let vid = inner.type_variables().root_var(vid); - if ty::TermVid::Ty(vid) == self.root_vid { + if TermVid::Ty(vid) == self.root_vid { // If sub-roots are equal, then `root_vid` and // `vid` are related via subtyping. Err(self.cyclic_term_error()) @@ -621,7 +637,7 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { // If root const vids are equal, then `root_vid` and // `vid` are related and we'd be inferring an infinitely // deep const. - if ty::TermVid::Const( + if TermVid::Const( self.infcx.inner.borrow_mut().const_unification_table().find(vid).vid, ) == self.root_vid { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 1e70d63539df..abbb3f2f59a8 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -673,24 +673,6 @@ impl<'tcx> TermKind<'tcx> { } } -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub enum TermVid { - Ty(ty::TyVid), - Const(ty::ConstVid), -} - -impl From for TermVid { - fn from(value: ty::TyVid) -> Self { - TermVid::Ty(value) - } -} - -impl From for TermVid { - fn from(value: ty::ConstVid) -> Self { - TermVid::Const(value) - } -} - /// Represents the bounds declared on a particular set of type /// parameters. Should eventually be generalized into a flag list of /// where-clauses. You can obtain an `InstantiatedPredicates` list from a From a949c47f0d3c0fb0b444c25cb2eb3323fcc845e6 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 09:02:15 +1000 Subject: [PATCH 364/809] Remove `ParamEnvAnd::into_parts`. The fields are public, so this doesn't need a method, normal deconstruction and/or field access is good enough. --- .../rustc_borrowck/src/diagnostics/bound_region_errors.rs | 4 ++-- compiler/rustc_infer/src/infer/canonical/canonicalizer.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 6 ------ .../src/traits/query/type_op/ascribe_user_type.rs | 2 +- compiler/rustc_traits/src/implied_outlives_bounds.rs | 4 ++-- compiler/rustc_traits/src/type_op.rs | 4 ++-- 6 files changed, 8 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs index 0de4bd67f0ce..5545f622cde2 100644 --- a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs @@ -277,7 +277,7 @@ where // `QueryNormalizeExt::query_normalize` used in the query and `normalize` called below: // the former fails to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs` // test. Check after #85499 lands to see if its fixes have erased this difference. - let (param_env, value) = key.into_parts(); + let ty::ParamEnvAnd { param_env, value } = key; let _ = ocx.normalize(&cause, param_env, value.value); let diag = try_extract_error_from_fulfill_cx( @@ -324,7 +324,7 @@ where mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query); let ocx = ObligationCtxt::new(&infcx); - let (param_env, value) = key.into_parts(); + let ty::ParamEnvAnd { param_env, value } = key; let _ = ocx.deeply_normalize(&cause, param_env, value.value); let diag = try_extract_error_from_fulfill_cx( diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index 060447ba7206..db37669d85b5 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -44,7 +44,7 @@ impl<'tcx> InferCtxt<'tcx> { where V: TypeFoldable>, { - let (param_env, value) = value.into_parts(); + let ty::ParamEnvAnd { param_env, value } = value; let canonical_param_env = self.tcx.canonical_param_env_cache.get_or_insert( self.tcx, param_env, diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index abbb3f2f59a8..a8992b88acd4 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1011,12 +1011,6 @@ pub struct ParamEnvAnd<'tcx, T> { pub value: T, } -impl<'tcx, T> ParamEnvAnd<'tcx, T> { - pub fn into_parts(self) -> (ParamEnv<'tcx>, T) { - (self.param_env, self.value) - } -} - /// The environment in which to do trait solving. /// /// Most of the time you only need to care about the `ParamEnv` diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs index 81b5a131a32e..78e7aef78f1b 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs @@ -44,7 +44,7 @@ pub fn type_op_ascribe_user_type_with_span<'tcx>( key: ParamEnvAnd<'tcx, AscribeUserType<'tcx>>, span: Span, ) -> Result<(), NoSolution> { - let (param_env, AscribeUserType { mir_ty, user_ty }) = key.into_parts(); + let ty::ParamEnvAnd { param_env, value: AscribeUserType { mir_ty, user_ty } } = key; debug!("type_op_ascribe_user_type: mir_ty={:?} user_ty={:?}", mir_ty, user_ty); match user_ty.kind { UserTypeKind::Ty(user_ty) => relate_mir_and_user_ty(ocx, param_env, span, mir_ty, user_ty)?, diff --git a/compiler/rustc_traits/src/implied_outlives_bounds.rs b/compiler/rustc_traits/src/implied_outlives_bounds.rs index 6fb483e6dac9..397c24ff70ca 100644 --- a/compiler/rustc_traits/src/implied_outlives_bounds.rs +++ b/compiler/rustc_traits/src/implied_outlives_bounds.rs @@ -7,7 +7,7 @@ use rustc_infer::infer::canonical::{self, Canonical}; use rustc_infer::traits::query::OutlivesBound; use rustc_infer::traits::query::type_op::ImpliedOutlivesBounds; use rustc_middle::query::Providers; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_span::DUMMY_SP; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::type_op::implied_outlives_bounds::compute_implied_outlives_bounds_inner; @@ -25,7 +25,7 @@ fn implied_outlives_bounds<'tcx>( NoSolution, > { tcx.infer_ctxt().enter_canonical_trait_query(&goal, |ocx, key| { - let (param_env, ImpliedOutlivesBounds { ty }) = key.into_parts(); + let ParamEnvAnd { param_env, value: ImpliedOutlivesBounds { ty } } = key; compute_implied_outlives_bounds_inner( ocx, param_env, diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index e58ad639d206..f77e1994cf47 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -43,7 +43,7 @@ fn type_op_normalize<'tcx, T>( where T: fmt::Debug + TypeFoldable>, { - let (param_env, Normalize { value }) = key.into_parts(); + let ParamEnvAnd { param_env, value: Normalize { value } } = key; let Normalized { value, obligations } = ocx.infcx.at(&ObligationCause::dummy(), param_env).query_normalize(value)?; ocx.register_obligations(obligations); @@ -96,6 +96,6 @@ pub fn type_op_prove_predicate_with_cause<'tcx>( key: ParamEnvAnd<'tcx, ProvePredicate<'tcx>>, cause: ObligationCause<'tcx>, ) { - let (param_env, ProvePredicate { predicate }) = key.into_parts(); + let ParamEnvAnd { param_env, value: ProvePredicate { predicate } } = key; ocx.register_obligation(Obligation::new(ocx.infcx.tcx, cause, param_env, predicate)); } From 0b3c980c241ccbd0c1b8b90f4f7b62e618bd3f93 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 09:08:46 +1000 Subject: [PATCH 365/809] Remove `TyCtxt::get_attrs_unchecked`. It's identical to `TyCtxt::get_all_attrs` except it takes `DefId` instead of `impl Into`. --- compiler/rustc_middle/src/ty/mod.rs | 12 ++---------- src/librustdoc/clean/inline.rs | 2 +- src/librustdoc/clean/types.rs | 7 ++----- .../src/matches/significant_drop_in_scrutinee.rs | 2 +- .../clippy_lints/src/significant_drop_tightening.rs | 2 +- src/tools/clippy/clippy_utils/src/macros.rs | 2 +- 6 files changed, 8 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index a8992b88acd4..36d57c89ddb9 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1706,15 +1706,6 @@ impl<'tcx> TyCtxt<'tcx> { } } - // FIXME(@lcnr): Remove this function. - pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [hir::Attribute] { - if let Some(did) = did.as_local() { - self.hir_attrs(self.local_def_id_to_hir_id(did)) - } else { - self.attrs_for_def(did) - } - } - /// Gets all attributes with the given name. pub fn get_attrs( self, @@ -1726,7 +1717,8 @@ impl<'tcx> TyCtxt<'tcx> { /// Gets all attributes. /// - /// To see if an item has a specific attribute, you should use [`rustc_attr_data_structures::find_attr!`] so you can use matching. + /// To see if an item has a specific attribute, you should use + /// [`rustc_attr_data_structures::find_attr!`] so you can use matching. pub fn get_all_attrs(self, did: impl Into) -> &'tcx [hir::Attribute] { let did: DefId = did.into(); if let Some(did) = did.as_local() { diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 9603399f2359..8c0f897c9926 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -217,7 +217,7 @@ pub(crate) fn try_inline_glob( } pub(crate) fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> &'hir [hir::Attribute] { - cx.tcx.get_attrs_unchecked(did) + cx.tcx.get_all_attrs(did) } pub(crate) fn item_relative_path(tcx: TyCtxt<'_>, def_id: DefId) -> Vec { diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 5ac5da24299f..7d0d2e62c853 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -404,10 +404,7 @@ impl Item { } pub(crate) fn inner_docs(&self, tcx: TyCtxt<'_>) -> bool { - self.item_id - .as_def_id() - .map(|did| inner_docs(tcx.get_attrs_unchecked(did))) - .unwrap_or(false) + self.item_id.as_def_id().map(|did| inner_docs(tcx.get_all_attrs(did))).unwrap_or(false) } pub(crate) fn span(&self, tcx: TyCtxt<'_>) -> Option { @@ -452,7 +449,7 @@ impl Item { kind: ItemKind, cx: &mut DocContext<'_>, ) -> Item { - let hir_attrs = cx.tcx.get_attrs_unchecked(def_id); + let hir_attrs = cx.tcx.get_all_attrs(def_id); Self::from_def_id_and_attrs_and_parts( def_id, diff --git a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs index 88b4d9b7d544..027dd7ce0534 100644 --- a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs index 521754f7bab7..9110f684bd10 100644 --- a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/macros.rs b/src/tools/clippy/clippy_utils/src/macros.rs index ba126fcd05de..60473a26493d 100644 --- a/src/tools/clippy/clippy_utils/src/macros.rs +++ b/src/tools/clippy/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 cf95e45ec6907c21b642e1b33d1d363221b50c23 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 13:19:54 +1000 Subject: [PATCH 366/809] Move `InferVarInfo` out of `rustc_middle`. It's only used in `rustc_hir_typeck`. --- compiler/rustc_hir_typeck/src/fallback.rs | 3 ++- compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs | 15 ++++++++++++++- compiler/rustc_middle/src/ty/mod.rs | 13 ------------- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 9406697dfed6..ef88e02fd98c 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -18,6 +18,7 @@ use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; use tracing::debug; +use crate::typeck_root_ctxt::InferVarInfo; use crate::{FnCtxt, errors}; #[derive(Copy, Clone)] @@ -345,7 +346,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { .map(|(_, info)| *info) .collect(); - let found_infer_var_info = ty::InferVarInfo { + let found_infer_var_info = InferVarInfo { self_in_trait: infer_var_infos.items().any(|info| info.self_in_trait), output: infer_var_infos.items().any(|info| info.output), }; diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index 6a985fc91e7d..65a6cd29f766 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -17,6 +17,19 @@ use tracing::{debug, instrument}; use super::callee::DeferredCallResolution; +#[derive(Debug, Default, Copy, Clone)] +pub(crate) struct InferVarInfo { + /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo` + /// obligation, where: + /// + /// * `Foo` is not `Sized` + /// * `(): Foo` may be satisfied + pub self_in_trait: bool, + /// This is true if we identified that this Ty (`?T`) is found in a `<_ as + /// _>::AssocType = ?T` + pub output: bool, +} + /// Data shared between a "typeck root" and its nested bodies, /// e.g. closures defined within the function. For example: /// ```ignore (illustrative) @@ -71,7 +84,7 @@ pub(crate) struct TypeckRootCtxt<'tcx> { /// fallback. See the `fallback` module for details. pub(super) diverging_type_vars: RefCell>>, - pub(super) infer_var_info: RefCell>, + pub(super) infer_var_info: RefCell>, } impl<'tcx> Deref for TypeckRootCtxt<'tcx> { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 36d57c89ddb9..acafbf26513b 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2232,19 +2232,6 @@ impl<'tcx> fmt::Debug for SymbolName<'tcx> { } } -#[derive(Debug, Default, Copy, Clone)] -pub struct InferVarInfo { - /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo` - /// obligation, where: - /// - /// * `Foo` is not `Sized` - /// * `(): Foo` may be satisfied - pub self_in_trait: bool, - /// This is true if we identified that this Ty (`?T`) is found in a `<_ as - /// _>::AssocType = ?T` - pub output: bool, -} - /// The constituent parts of a type level constant of kind ADT or array. #[derive(Copy, Clone, Debug, HashStable)] pub struct DestructuredConst<'tcx> { From c78d589243cede0605a4ba26b452c50f4a09ccc3 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 09:08:46 +1000 Subject: [PATCH 367/809] 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 7aec38b6d9077bcd0b8b4b7fefaea73262ccd7d6 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 12:39:33 +1000 Subject: [PATCH 368/809] Fix up size asserts. - Put them in the module that defines the type. - Add some `WithCachedTypeInfo` asserts for consistency. --- compiler/rustc_middle/src/ty/mod.rs | 12 ------------ compiler/rustc_middle/src/ty/predicate.rs | 12 ++++++++++++ compiler/rustc_middle/src/ty/region.rs | 12 ++++++++++++ compiler/rustc_middle/src/ty/sty.rs | 4 ++-- 4 files changed, 26 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index acafbf26513b..e0325d1be6df 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2238,15 +2238,3 @@ pub struct DestructuredConst<'tcx> { pub variant: Option, pub fields: &'tcx [ty::Const<'tcx>], } - -// Some types are used a lot. Make sure they don't unintentionally get bigger. -#[cfg(target_pointer_width = "64")] -mod size_asserts { - use rustc_data_structures::static_assert_size; - - use super::*; - // tidy-alphabetical-start - static_assert_size!(PredicateKind<'_>, 32); - static_assert_size!(WithCachedTypeInfo>, 48); - // tidy-alphabetical-end -} diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index 46f254e9d304..73a6f1829afe 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -704,3 +704,15 @@ impl<'tcx> Predicate<'tcx> { } } } + +// Some types are used a lot. Make sure they don't unintentionally get bigger. +#[cfg(target_pointer_width = "64")] +mod size_asserts { + use rustc_data_structures::static_assert_size; + + use super::*; + // tidy-alphabetical-start + static_assert_size!(PredicateKind<'_>, 32); + static_assert_size!(WithCachedTypeInfo>, 56); + // tidy-alphabetical-end +} diff --git a/compiler/rustc_middle/src/ty/region.rs b/compiler/rustc_middle/src/ty/region.rs index 600dfc2ff690..3a7852dea068 100644 --- a/compiler/rustc_middle/src/ty/region.rs +++ b/compiler/rustc_middle/src/ty/region.rs @@ -495,3 +495,15 @@ impl BoundRegionKind { } } } + +// Some types are used a lot. Make sure they don't unintentionally get bigger. +#[cfg(target_pointer_width = "64")] +mod size_asserts { + use rustc_data_structures::static_assert_size; + + use super::*; + // tidy-alphabetical-start + static_assert_size!(RegionKind<'_>, 20); + static_assert_size!(ty::WithCachedTypeInfo>, 48); + // tidy-alphabetical-end +} diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 4569596cfbe8..746b429a3805 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -2040,7 +2040,7 @@ mod size_asserts { use super::*; // tidy-alphabetical-start - static_assert_size!(ty::RegionKind<'_>, 20); - static_assert_size!(ty::TyKind<'_>, 24); + static_assert_size!(TyKind<'_>, 24); + static_assert_size!(ty::WithCachedTypeInfo>, 48); // tidy-alphabetical-end } From 7b667e7811f4a4b496f38d25c5e824f13638cdbb Mon Sep 17 00:00:00 2001 From: xizheyin Date: Thu, 31 Jul 2025 00:44:22 +0800 Subject: [PATCH 369/809] Extend `is_case_difference` to handle digit-letter confusables Signed-off-by: xizheyin --- compiler/rustc_errors/src/emitter.rs | 135 ++++++++++++++---- compiler/rustc_errors/src/lib.rs | 11 +- .../tests/ui/match_str_case_mismatch.stderr | 2 +- tests/ui/error-codes/E0423.stderr | 2 +- .../ui/lint/lint-non-uppercase-usages.stderr | 2 +- tests/ui/parser/item-kw-case-mismatch.stderr | 6 +- tests/ui/parser/kw-in-trait-bounds.stderr | 8 +- .../ui/parser/misspelled-keywords/hrdt.stderr | 2 +- .../misspelled-keywords/impl-return.stderr | 2 +- .../parser/misspelled-keywords/static.stderr | 2 +- .../parser/misspelled-keywords/struct.stderr | 2 +- .../recover-fn-trait-from-fn-kw.stderr | 4 +- .../typod-const-in-const-param-def.stderr | 8 +- .../assoc-ct-for-assoc-method.stderr | 2 +- .../suggestions/bool_typo_err_suggest.stderr | 2 +- .../case-difference-suggestions.rs | 57 ++++++++ .../case-difference-suggestions.stderr | 99 +++++++++++++ .../suggestions/incorrect-variant-literal.svg | 2 +- 18 files changed, 290 insertions(+), 58 deletions(-) create mode 100644 tests/ui/suggestions/case-difference-suggestions.rs create mode 100644 tests/ui/suggestions/case-difference-suggestions.stderr diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 46a4a1868247..55a42d0426e1 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -262,19 +262,11 @@ pub trait Emitter { format!("help: {msg}") } else { // Show the default suggestion text with the substitution - format!( - "help: {}{}: `{}`", - msg, - if self - .source_map() - .is_some_and(|sm| is_case_difference(sm, snippet, part.span,)) - { - " (notice the capitalization)" - } else { - "" - }, - snippet, - ) + let confusion_type = self + .source_map() + .map(|sm| detect_confusion_type(sm, snippet, part.span)) + .unwrap_or(ConfusionType::None); + format!("help: {}{}: `{}`", msg, confusion_type.label_text(), snippet,) }; primary_span.push_span_label(part.span, msg); @@ -2028,12 +2020,12 @@ impl HumanEmitter { buffer.append(0, ": ", Style::HeaderMsg); let mut msg = vec![(suggestion.msg.to_owned(), Style::NoStyle)]; - if suggestions - .iter() - .take(MAX_SUGGESTIONS) - .any(|(_, _, _, only_capitalization)| *only_capitalization) + if let Some(confusion_type) = + suggestions.iter().take(MAX_SUGGESTIONS).find_map(|(_, _, _, confusion_type)| { + if confusion_type.has_confusion() { Some(*confusion_type) } else { None } + }) { - msg.push((" (notice the capitalization difference)".into(), Style::NoStyle)); + msg.push((confusion_type.label_text().into(), Style::NoStyle)); } self.msgs_to_buffer( &mut buffer, @@ -3528,24 +3520,107 @@ pub fn is_different(sm: &SourceMap, suggested: &str, sp: Span) -> bool { } /// Whether the original and suggested code are visually similar enough to warrant extra wording. -pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool { - // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode. +pub fn detect_confusion_type(sm: &SourceMap, suggested: &str, sp: Span) -> ConfusionType { let found = match sm.span_to_snippet(sp) { Ok(snippet) => snippet, Err(e) => { warn!(error = ?e, "Invalid span {:?}", sp); - return false; + return ConfusionType::None; } }; - let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z']; - // All the chars that differ in capitalization are confusable (above): - let confusable = iter::zip(found.chars(), suggested.chars()) - .filter(|(f, s)| f != s) - .all(|(f, s)| ascii_confusables.contains(&f) || ascii_confusables.contains(&s)); - confusable && found.to_lowercase() == suggested.to_lowercase() - // FIXME: We sometimes suggest the same thing we already have, which is a - // bug, but be defensive against that here. - && found != suggested + + let mut has_case_confusion = false; + let mut has_digit_letter_confusion = false; + + if found.len() == suggested.len() { + let mut has_case_diff = false; + let mut has_digit_letter_confusable = false; + let mut has_other_diff = false; + + let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z']; + + let digit_letter_confusables = [('0', 'O'), ('1', 'l'), ('5', 'S'), ('8', 'B'), ('9', 'g')]; + + for (f, s) in iter::zip(found.chars(), suggested.chars()) { + if f != s { + if f.to_lowercase().to_string() == s.to_lowercase().to_string() { + // Check for case differences (any character that differs only in case) + if ascii_confusables.contains(&f) || ascii_confusables.contains(&s) { + has_case_diff = true; + } else { + has_other_diff = true; + } + } else if digit_letter_confusables.contains(&(f, s)) + || digit_letter_confusables.contains(&(s, f)) + { + // Check for digit-letter confusables (like 0 vs O, 1 vs l, etc.) + has_digit_letter_confusable = true; + } else { + has_other_diff = true; + } + } + } + + // If we have case differences and no other differences + if has_case_diff && !has_other_diff && found != suggested { + has_case_confusion = true; + } + if has_digit_letter_confusable && !has_other_diff && found != suggested { + has_digit_letter_confusion = true; + } + } + + match (has_case_confusion, has_digit_letter_confusion) { + (true, true) => ConfusionType::Both, + (true, false) => ConfusionType::Case, + (false, true) => ConfusionType::DigitLetter, + (false, false) => ConfusionType::None, + } +} + +/// Represents the type of confusion detected between original and suggested code. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConfusionType { + /// No confusion detected + None, + /// Only case differences (e.g., "hello" vs "Hello") + Case, + /// Only digit-letter confusion (e.g., "0" vs "O", "1" vs "l") + DigitLetter, + /// Both case and digit-letter confusion + Both, +} + +impl ConfusionType { + /// Returns the appropriate label text for this confusion type. + pub fn label_text(&self) -> &'static str { + match self { + ConfusionType::None => "", + ConfusionType::Case => " (notice the capitalization)", + ConfusionType::DigitLetter => " (notice the digit/letter confusion)", + ConfusionType::Both => " (notice the capitalization and digit/letter confusion)", + } + } + + /// Combines two confusion types. If either is `Both`, the result is `Both`. + /// If one is `Case` and the other is `DigitLetter`, the result is `Both`. + /// Otherwise, returns the non-`None` type, or `None` if both are `None`. + pub fn combine(self, other: ConfusionType) -> ConfusionType { + match (self, other) { + (ConfusionType::None, other) => other, + (this, ConfusionType::None) => this, + (ConfusionType::Both, _) | (_, ConfusionType::Both) => ConfusionType::Both, + (ConfusionType::Case, ConfusionType::DigitLetter) + | (ConfusionType::DigitLetter, ConfusionType::Case) => ConfusionType::Both, + (ConfusionType::Case, ConfusionType::Case) => ConfusionType::Case, + (ConfusionType::DigitLetter, ConfusionType::DigitLetter) => ConfusionType::DigitLetter, + } + } + + /// Returns true if this confusion type represents any kind of confusion. + pub fn has_confusion(&self) -> bool { + *self != ConfusionType::None + } } pub(crate) fn should_show_source_code( diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 381d780077d1..2534cddf1057 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -50,7 +50,7 @@ pub use diagnostic_impls::{ IndicateAnonymousLifetime, SingleLabelManySpans, }; pub use emitter::ColorConfig; -use emitter::{DynEmitter, Emitter, is_case_difference, is_different}; +use emitter::{ConfusionType, DynEmitter, Emitter, detect_confusion_type, is_different}; use rustc_data_structures::AtomicRef; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::stable_hasher::StableHasher; @@ -308,7 +308,7 @@ impl CodeSuggestion { pub(crate) fn splice_lines( &self, sm: &SourceMap, - ) -> Vec<(String, Vec, Vec>, bool)> { + ) -> Vec<(String, Vec, Vec>, ConfusionType)> { // For the `Vec>` value, the first level of the vector // corresponds to the output snippet's lines, while the second level corresponds to the // substrings within that line that should be highlighted. @@ -414,14 +414,15 @@ impl CodeSuggestion { // We need to keep track of the difference between the existing code and the added // or deleted code in order to point at the correct column *after* substitution. let mut acc = 0; - let mut only_capitalization = false; + let mut confusion_type = ConfusionType::None; for part in &mut substitution.parts { // If this is a replacement of, e.g. `"a"` into `"ab"`, adjust the // suggestion and snippet to look as if we just suggested to add // `"b"`, which is typically much easier for the user to understand. part.trim_trivial_replacements(sm); - only_capitalization |= is_case_difference(sm, &part.snippet, part.span); + let part_confusion = detect_confusion_type(sm, &part.snippet, part.span); + confusion_type = confusion_type.combine(part_confusion); let cur_lo = sm.lookup_char_pos(part.span.lo()); if prev_hi.line == cur_lo.line { let mut count = @@ -511,7 +512,7 @@ impl CodeSuggestion { if highlights.iter().all(|parts| parts.is_empty()) { None } else { - Some((buf, substitution.parts, highlights, only_capitalization)) + Some((buf, substitution.parts, highlights, confusion_type)) } }) .collect() diff --git a/src/tools/clippy/tests/ui/match_str_case_mismatch.stderr b/src/tools/clippy/tests/ui/match_str_case_mismatch.stderr index 8068edfff947..c2b58b952aaa 100644 --- a/src/tools/clippy/tests/ui/match_str_case_mismatch.stderr +++ b/src/tools/clippy/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" => {}, diff --git a/tests/ui/error-codes/E0423.stderr b/tests/ui/error-codes/E0423.stderr index e50b8bd820cf..b699e53fb480 100644 --- a/tests/ui/error-codes/E0423.stderr +++ b/tests/ui/error-codes/E0423.stderr @@ -54,7 +54,7 @@ help: use struct literal syntax instead LL - let f = Foo(); LL + let f = Foo { a: val }; | -help: a function with a similar name exists (notice the capitalization difference) +help: a function with a similar name exists (notice the capitalization) | LL - let f = Foo(); LL + let f = foo(); diff --git a/tests/ui/lint/lint-non-uppercase-usages.stderr b/tests/ui/lint/lint-non-uppercase-usages.stderr index 7c7e573a88ed..b34be31216d3 100644 --- a/tests/ui/lint/lint-non-uppercase-usages.stderr +++ b/tests/ui/lint/lint-non-uppercase-usages.stderr @@ -29,7 +29,7 @@ warning: const parameter `foo` should have an upper case name LL | fn foo() { | ^^^ | -help: convert the identifier to upper case (notice the capitalization difference) +help: convert the identifier to upper case (notice the capitalization) | LL - fn foo() { LL + fn foo() { diff --git a/tests/ui/parser/item-kw-case-mismatch.stderr b/tests/ui/parser/item-kw-case-mismatch.stderr index df39eb10fdbe..d2a1eb7f2f52 100644 --- a/tests/ui/parser/item-kw-case-mismatch.stderr +++ b/tests/ui/parser/item-kw-case-mismatch.stderr @@ -4,7 +4,7 @@ error: keyword `use` is written in the wrong case LL | Use std::ptr::read; | ^^^ | -help: write it in the correct case (notice the capitalization difference) +help: write it in the correct case (notice the capitalization) | LL - Use std::ptr::read; LL + use std::ptr::read; @@ -28,7 +28,7 @@ error: keyword `fn` is written in the wrong case LL | async Fn _a() {} | ^^ | -help: write it in the correct case (notice the capitalization difference) +help: write it in the correct case (notice the capitalization) | LL - async Fn _a() {} LL + async fn _a() {} @@ -40,7 +40,7 @@ error: keyword `fn` is written in the wrong case LL | Fn _b() {} | ^^ | -help: write it in the correct case (notice the capitalization difference) +help: write it in the correct case (notice the capitalization) | LL - Fn _b() {} LL + fn _b() {} diff --git a/tests/ui/parser/kw-in-trait-bounds.stderr b/tests/ui/parser/kw-in-trait-bounds.stderr index 1892d0b62265..5a4adf3e37b4 100644 --- a/tests/ui/parser/kw-in-trait-bounds.stderr +++ b/tests/ui/parser/kw-in-trait-bounds.stderr @@ -4,7 +4,7 @@ error: expected identifier, found keyword `fn` LL | fn _f(_: impl fn(), _: &dyn fn()) | ^^ | -help: use `Fn` to refer to the trait (notice the capitalization difference) +help: use `Fn` to refer to the trait (notice the capitalization) | LL - fn _f(_: impl fn(), _: &dyn fn()) LL + fn _f(_: impl fn(), _: &dyn fn()) @@ -16,7 +16,7 @@ error: expected identifier, found keyword `fn` LL | fn _f(_: impl fn(), _: &dyn fn()) | ^^ | -help: use `Fn` to refer to the trait (notice the capitalization difference) +help: use `Fn` to refer to the trait (notice the capitalization) | LL - fn _f(_: impl fn(), _: &dyn fn()) LL + fn _f(_: impl Fn(), _: &dyn fn()) @@ -28,7 +28,7 @@ error: expected identifier, found keyword `fn` LL | fn _f(_: impl fn(), _: &dyn fn()) | ^^ | -help: use `Fn` to refer to the trait (notice the capitalization difference) +help: use `Fn` to refer to the trait (notice the capitalization) | LL - fn _f(_: impl fn(), _: &dyn fn()) LL + fn _f(_: impl fn(), _: &dyn Fn()) @@ -40,7 +40,7 @@ error: expected identifier, found keyword `fn` LL | G: fn(), | ^^ | -help: use `Fn` to refer to the trait (notice the capitalization difference) +help: use `Fn` to refer to the trait (notice the capitalization) | LL - G: fn(), LL + G: Fn(), diff --git a/tests/ui/parser/misspelled-keywords/hrdt.stderr b/tests/ui/parser/misspelled-keywords/hrdt.stderr index e5fc1a503820..497bd613bf45 100644 --- a/tests/ui/parser/misspelled-keywords/hrdt.stderr +++ b/tests/ui/parser/misspelled-keywords/hrdt.stderr @@ -4,7 +4,7 @@ error: expected one of `!`, `(`, `+`, `::`, `<`, `where`, or `{`, found keyword LL | Where for<'a> F: Fn(&'a (u8, u16)) -> &'a u8, | ^^^ expected one of 7 possible tokens | -help: write keyword `where` in lowercase (notice the capitalization difference) +help: write keyword `where` in lowercase (notice the capitalization) | LL - Where for<'a> F: Fn(&'a (u8, u16)) -> &'a u8, LL + where for<'a> F: Fn(&'a (u8, u16)) -> &'a u8, diff --git a/tests/ui/parser/misspelled-keywords/impl-return.stderr b/tests/ui/parser/misspelled-keywords/impl-return.stderr index ff5391461a9f..d49d962d7e95 100644 --- a/tests/ui/parser/misspelled-keywords/impl-return.stderr +++ b/tests/ui/parser/misspelled-keywords/impl-return.stderr @@ -4,7 +4,7 @@ error: expected one of `!`, `(`, `+`, `::`, `<`, `where`, or `{`, found `Display LL | fn code() -> Impl Display {} | ^^^^^^^ expected one of 7 possible tokens | -help: write keyword `impl` in lowercase (notice the capitalization difference) +help: write keyword `impl` in lowercase (notice the capitalization) | LL - fn code() -> Impl Display {} LL + fn code() -> impl Display {} diff --git a/tests/ui/parser/misspelled-keywords/static.stderr b/tests/ui/parser/misspelled-keywords/static.stderr index e559f2be1091..0df40bcdc33b 100644 --- a/tests/ui/parser/misspelled-keywords/static.stderr +++ b/tests/ui/parser/misspelled-keywords/static.stderr @@ -4,7 +4,7 @@ error: expected one of `!` or `::`, found `a` LL | Static a = 0; | ^ expected one of `!` or `::` | -help: write keyword `static` in lowercase (notice the capitalization difference) +help: write keyword `static` in lowercase (notice the capitalization) | LL - Static a = 0; LL + static a = 0; diff --git a/tests/ui/parser/misspelled-keywords/struct.stderr b/tests/ui/parser/misspelled-keywords/struct.stderr index edbec3b9456b..af8614ef14b7 100644 --- a/tests/ui/parser/misspelled-keywords/struct.stderr +++ b/tests/ui/parser/misspelled-keywords/struct.stderr @@ -4,7 +4,7 @@ error: expected one of `!` or `::`, found `Foor` LL | Struct Foor { | ^^^^ expected one of `!` or `::` | -help: write keyword `struct` in lowercase (notice the capitalization difference) +help: write keyword `struct` in lowercase (notice the capitalization) | LL - Struct Foor { LL + struct Foor { diff --git a/tests/ui/parser/recover/recover-fn-trait-from-fn-kw.stderr b/tests/ui/parser/recover/recover-fn-trait-from-fn-kw.stderr index 4e1fcaf49368..bd809e77a8f9 100644 --- a/tests/ui/parser/recover/recover-fn-trait-from-fn-kw.stderr +++ b/tests/ui/parser/recover/recover-fn-trait-from-fn-kw.stderr @@ -4,7 +4,7 @@ error: expected identifier, found keyword `fn` LL | fn foo(_: impl fn() -> i32) {} | ^^ | -help: use `Fn` to refer to the trait (notice the capitalization difference) +help: use `Fn` to refer to the trait (notice the capitalization) | LL - fn foo(_: impl fn() -> i32) {} LL + fn foo(_: impl Fn() -> i32) {} @@ -16,7 +16,7 @@ error: expected identifier, found keyword `fn` LL | fn foo2(_: T) {} | ^^ | -help: use `Fn` to refer to the trait (notice the capitalization difference) +help: use `Fn` to refer to the trait (notice the capitalization) | LL - fn foo2(_: T) {} LL + fn foo2(_: T) {} diff --git a/tests/ui/parser/typod-const-in-const-param-def.stderr b/tests/ui/parser/typod-const-in-const-param-def.stderr index bf7168a01573..cc1600fe5cb8 100644 --- a/tests/ui/parser/typod-const-in-const-param-def.stderr +++ b/tests/ui/parser/typod-const-in-const-param-def.stderr @@ -4,7 +4,7 @@ error: `const` keyword was mistyped as `Const` LL | pub fn foo() {} | ^^^^^ | -help: use the `const` keyword (notice the capitalization difference) +help: use the `const` keyword (notice the capitalization) | LL - pub fn foo() {} LL + pub fn foo() {} @@ -16,7 +16,7 @@ error: `const` keyword was mistyped as `Const` LL | pub fn baz() {} | ^^^^^ | -help: use the `const` keyword (notice the capitalization difference) +help: use the `const` keyword (notice the capitalization) | LL - pub fn baz() {} LL + pub fn baz() {} @@ -28,7 +28,7 @@ error: `const` keyword was mistyped as `Const` LL | pub fn qux() {} | ^^^^^ | -help: use the `const` keyword (notice the capitalization difference) +help: use the `const` keyword (notice the capitalization) | LL - pub fn qux() {} LL + pub fn qux() {} @@ -40,7 +40,7 @@ error: `const` keyword was mistyped as `Const` LL | pub fn quux() {} | ^^^^^ | -help: use the `const` keyword (notice the capitalization difference) +help: use the `const` keyword (notice the capitalization) | LL - pub fn quux() {} LL + pub fn quux() {} diff --git a/tests/ui/suggestions/assoc-ct-for-assoc-method.stderr b/tests/ui/suggestions/assoc-ct-for-assoc-method.stderr index 6d6fd9830384..47efe69cfc21 100644 --- a/tests/ui/suggestions/assoc-ct-for-assoc-method.stderr +++ b/tests/ui/suggestions/assoc-ct-for-assoc-method.stderr @@ -8,7 +8,7 @@ LL | let x: i32 = MyS::foo; | = note: expected type `i32` found fn item `fn() -> MyS {MyS::foo}` -help: try referring to the associated const `FOO` instead (notice the capitalization difference) +help: try referring to the associated const `FOO` instead (notice the capitalization) | LL - let x: i32 = MyS::foo; LL + let x: i32 = MyS::FOO; diff --git a/tests/ui/suggestions/bool_typo_err_suggest.stderr b/tests/ui/suggestions/bool_typo_err_suggest.stderr index faf799d0fda2..d46ce1ad8a9b 100644 --- a/tests/ui/suggestions/bool_typo_err_suggest.stderr +++ b/tests/ui/suggestions/bool_typo_err_suggest.stderr @@ -16,7 +16,7 @@ error[E0425]: cannot find value `False` in this scope LL | let y = False; | ^^^^^ not found in this scope | -help: you may want to use a bool value instead (notice the capitalization difference) +help: you may want to use a bool value instead (notice the capitalization) | LL - let y = False; LL + let y = false; diff --git a/tests/ui/suggestions/case-difference-suggestions.rs b/tests/ui/suggestions/case-difference-suggestions.rs new file mode 100644 index 000000000000..d554b6e93673 --- /dev/null +++ b/tests/ui/suggestions/case-difference-suggestions.rs @@ -0,0 +1,57 @@ +fn main() { + + // Simple case difference, no hit + let hello = "hello"; + println!("{}", Hello); //~ ERROR cannot find value `Hello` in this scope + + // Multiple case differences, hit + let myVariable = 10; + println!("{}", myvariable); //~ ERROR cannot find value `myvariable` in this scope + + // Case difference with special characters, hit + let user_name = "john"; + println!("{}", User_Name); //~ ERROR cannot find value `User_Name` in this scope + + // All uppercase vs all lowercase, hit + let FOO = 42; + println!("{}", foo); //~ ERROR cannot find value `foo` in this scope + + + // 0 vs O + let FFO0 = 100; + println!("{}", FFOO); //~ ERROR cannot find value `FFOO` in this scope + + let l1st = vec![1, 2, 3]; + println!("{}", list); //~ ERROR cannot find value `list` in this scope + + let S5 = "test"; + println!("{}", SS); //~ ERROR cannot find value `SS` in this scope + + let aS5 = "test"; + println!("{}", a55); //~ ERROR cannot find value `a55` in this scope + + let B8 = 8; + println!("{}", BB); //~ ERROR cannot find value `BB` in this scope + + let g9 = 9; + println!("{}", gg); //~ ERROR cannot find value `gg` in this scope + + let o1d = "old"; + println!("{}", old); //~ ERROR cannot find value `old` in this scope + + let new1 = "new"; + println!("{}", newl); //~ ERROR cannot find value `newl` in this scope + + let apple = "apple"; + println!("{}", app1e); //~ ERROR cannot find value `app1e` in this scope + + let a = 1; + println!("{}", A); //~ ERROR cannot find value `A` in this scope + + let worldlu = "world"; + println!("{}", world1U); //~ ERROR cannot find value `world1U` in this scope + + let myV4rlable = 42; + println!("{}", myv4r1able); //~ ERROR cannot find value `myv4r1able` in this scope + +} diff --git a/tests/ui/suggestions/case-difference-suggestions.stderr b/tests/ui/suggestions/case-difference-suggestions.stderr new file mode 100644 index 000000000000..c3d2410a6eb2 --- /dev/null +++ b/tests/ui/suggestions/case-difference-suggestions.stderr @@ -0,0 +1,99 @@ +error[E0425]: cannot find value `Hello` in this scope + --> $DIR/case-difference-suggestions.rs:5:20 + | +LL | println!("{}", Hello); + | ^^^^^ help: a local variable with a similar name exists: `hello` + +error[E0425]: cannot find value `myvariable` in this scope + --> $DIR/case-difference-suggestions.rs:9:20 + | +LL | println!("{}", myvariable); + | ^^^^^^^^^^ help: a local variable with a similar name exists (notice the capitalization): `myVariable` + +error[E0425]: cannot find value `User_Name` in this scope + --> $DIR/case-difference-suggestions.rs:13:20 + | +LL | println!("{}", User_Name); + | ^^^^^^^^^ help: a local variable with a similar name exists: `user_name` + +error[E0425]: cannot find value `foo` in this scope + --> $DIR/case-difference-suggestions.rs:17:20 + | +LL | println!("{}", foo); + | ^^^ help: a local variable with a similar name exists (notice the capitalization): `FOO` + +error[E0425]: cannot find value `FFOO` in this scope + --> $DIR/case-difference-suggestions.rs:22:20 + | +LL | println!("{}", FFOO); + | ^^^^ help: a local variable with a similar name exists (notice the digit/letter confusion): `FFO0` + +error[E0425]: cannot find value `list` in this scope + --> $DIR/case-difference-suggestions.rs:25:20 + | +LL | println!("{}", list); + | ^^^^ help: a local variable with a similar name exists: `l1st` + +error[E0425]: cannot find value `SS` in this scope + --> $DIR/case-difference-suggestions.rs:28:20 + | +LL | println!("{}", SS); + | ^^ help: a local variable with a similar name exists (notice the digit/letter confusion): `S5` + +error[E0425]: cannot find value `a55` in this scope + --> $DIR/case-difference-suggestions.rs:31:20 + | +LL | println!("{}", a55); + | ^^^ help: a local variable with a similar name exists (notice the digit/letter confusion): `aS5` + +error[E0425]: cannot find value `BB` in this scope + --> $DIR/case-difference-suggestions.rs:34:20 + | +LL | println!("{}", BB); + | ^^ help: a local variable with a similar name exists (notice the digit/letter confusion): `B8` + +error[E0425]: cannot find value `gg` in this scope + --> $DIR/case-difference-suggestions.rs:37:20 + | +LL | println!("{}", gg); + | ^^ help: a local variable with a similar name exists (notice the digit/letter confusion): `g9` + +error[E0425]: cannot find value `old` in this scope + --> $DIR/case-difference-suggestions.rs:40:20 + | +LL | println!("{}", old); + | ^^^ help: a local variable with a similar name exists (notice the digit/letter confusion): `o1d` + +error[E0425]: cannot find value `newl` in this scope + --> $DIR/case-difference-suggestions.rs:43:20 + | +LL | println!("{}", newl); + | ^^^^ help: a local variable with a similar name exists (notice the digit/letter confusion): `new1` + +error[E0425]: cannot find value `app1e` in this scope + --> $DIR/case-difference-suggestions.rs:46:20 + | +LL | println!("{}", app1e); + | ^^^^^ help: a local variable with a similar name exists (notice the digit/letter confusion): `apple` + +error[E0425]: cannot find value `A` in this scope + --> $DIR/case-difference-suggestions.rs:49:20 + | +LL | println!("{}", A); + | ^ help: a local variable with a similar name exists: `a` + +error[E0425]: cannot find value `world1U` in this scope + --> $DIR/case-difference-suggestions.rs:52:20 + | +LL | println!("{}", world1U); + | ^^^^^^^ help: a local variable with a similar name exists (notice the capitalization and digit/letter confusion): `worldlu` + +error[E0425]: cannot find value `myv4r1able` in this scope + --> $DIR/case-difference-suggestions.rs:55:20 + | +LL | println!("{}", myv4r1able); + | ^^^^^^^^^^ help: a local variable with a similar name exists (notice the capitalization and digit/letter confusion): `myV4rlable` + +error: aborting due to 16 previous errors + +For more information about this error, try `rustc --explain E0425`. diff --git a/tests/ui/suggestions/incorrect-variant-literal.svg b/tests/ui/suggestions/incorrect-variant-literal.svg index 279fd30f2165..2cab1f4b60f6 100644 --- a/tests/ui/suggestions/incorrect-variant-literal.svg +++ b/tests/ui/suggestions/incorrect-variant-literal.svg @@ -455,7 +455,7 @@ | - help: there is a variant with a similar name (notice the capitalization difference) + help: there is a variant with a similar name (notice the capitalization) | From d7b7e236e74f45bdef7e082ac361b699abac20a2 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Thu, 31 Jul 2025 00:44:22 +0800 Subject: [PATCH 370/809] 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 761c4e308ca17c1d6d893c7d512f579728b1552f Mon Sep 17 00:00:00 2001 From: Scott Schafer Date: Tue, 22 Jul 2025 07:55:31 -0600 Subject: [PATCH 371/809] fix: Only "close the window" when its the last annotated file --- compiler/rustc_errors/src/emitter.rs | 7 +++++-- tests/ui/error-emitter/close_window.unicode.stderr | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 46a4a1868247..3fe525df94f4 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -1597,8 +1597,9 @@ impl HumanEmitter { annotated_files.swap(0, pos); } + let annotated_files_len = annotated_files.len(); // Print out the annotate source lines that correspond with the error - for annotated_file in annotated_files { + for (file_idx, annotated_file) in annotated_files.into_iter().enumerate() { // we can't annotate anything if the source is unavailable. if !should_show_source_code( &self.ignored_directories_in_source_blocks, @@ -1855,7 +1856,9 @@ impl HumanEmitter { width_offset, code_offset, margin, - !is_cont && line_idx + 1 == annotated_file.lines.len(), + !is_cont + && file_idx + 1 == annotated_files_len + && line_idx + 1 == annotated_file.lines.len(), ); let mut to_add = FxHashMap::default(); diff --git a/tests/ui/error-emitter/close_window.unicode.stderr b/tests/ui/error-emitter/close_window.unicode.stderr index c24b6939af5a..56ab6daa278d 100644 --- a/tests/ui/error-emitter/close_window.unicode.stderr +++ b/tests/ui/error-emitter/close_window.unicode.stderr @@ -2,7 +2,7 @@ error[E0624]: method `method` is private ╭▸ $DIR/close_window.rs:9:7 │ LL │ s.method(); - ╰╴ ━━━━━━ private method + │ ━━━━━━ private method │ ⸬ $DIR/auxiliary/close_window.rs:3:5 │ From c51e5ce452c96886bab78a8e736c750dd9e79fbd Mon Sep 17 00:00:00 2001 From: Tsukasa OI Date: Thu, 31 Jul 2025 07:39:10 +0000 Subject: [PATCH 372/809] std_detect: Linux 6.16 support for RISC-V It adds feature detection of 1 extension (new in std_detect). New RISC-V Extension: 1. "Zabha" --- library/std_detect/src/detect/arch/riscv.rs | 3 +++ library/std_detect/src/detect/os/linux/riscv.rs | 8 +++++--- library/std_detect/src/detect/os/riscv.rs | 2 +- library/std_detect/tests/cpu-detection.rs | 1 + 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/library/std_detect/src/detect/arch/riscv.rs b/library/std_detect/src/detect/arch/riscv.rs index b86190d7bbf0..1d21b1d48558 100644 --- a/library/std_detect/src/detect/arch/riscv.rs +++ b/library/std_detect/src/detect/arch/riscv.rs @@ -73,6 +73,7 @@ features! { /// * Zihintpause: `"zihintpause"` /// * Zihpm: `"zihpm"` /// * Zimop: `"zimop"` + /// * Zabha: `"zabha"` /// * Zacas: `"zacas"` /// * Zawrs: `"zawrs"` /// * Zfa: `"zfa"` @@ -195,6 +196,8 @@ features! { /// "Zaamo" Extension for Atomic Memory Operations @FEATURE: #[unstable(feature = "stdarch_riscv_feature_detection", issue = "111192")] zawrs: "zawrs"; /// "Zawrs" Extension for Wait-on-Reservation-Set Instructions + @FEATURE: #[unstable(feature = "stdarch_riscv_feature_detection", issue = "111192")] zabha: "zabha"; + /// "Zabha" Extension for Byte and Halfword Atomic Memory Operations @FEATURE: #[unstable(feature = "stdarch_riscv_feature_detection", issue = "111192")] zacas: "zacas"; /// "Zacas" Extension for Atomic Compare-and-Swap (CAS) Instructions @FEATURE: #[unstable(feature = "stdarch_riscv_feature_detection", issue = "111192")] zam: "zam"; diff --git a/library/std_detect/src/detect/os/linux/riscv.rs b/library/std_detect/src/detect/os/linux/riscv.rs index dbb3664890e5..18f9f68ec67e 100644 --- a/library/std_detect/src/detect/os/linux/riscv.rs +++ b/library/std_detect/src/detect/os/linux/riscv.rs @@ -10,13 +10,13 @@ use super::super::riscv::imply_features; use super::auxvec; use crate::detect::{Feature, bit, cache}; -// See +// See // for runtime status query constants. const PR_RISCV_V_GET_CONTROL: libc::c_int = 70; const PR_RISCV_V_VSTATE_CTRL_ON: libc::c_int = 2; const PR_RISCV_V_VSTATE_CTRL_CUR_MASK: libc::c_int = 3; -// See +// See // for riscv_hwprobe struct and hardware probing constants. #[repr(C)] @@ -98,6 +98,7 @@ const RISCV_HWPROBE_EXT_ZVFBFWMA: u64 = 1 << 54; const RISCV_HWPROBE_EXT_ZICBOM: u64 = 1 << 55; const RISCV_HWPROBE_EXT_ZAAMO: u64 = 1 << 56; const RISCV_HWPROBE_EXT_ZALRSC: u64 = 1 << 57; +const RISCV_HWPROBE_EXT_ZABHA: u64 = 1 << 58; const RISCV_HWPROBE_KEY_CPUPERF_0: i64 = 5; const RISCV_HWPROBE_MISALIGNED_FAST: u64 = 3; @@ -138,7 +139,7 @@ pub(crate) fn detect_features() -> cache::Initializer { // Use auxiliary vector to enable single-letter ISA extensions. // The values are part of the platform-specific [asm/hwcap.h][hwcap] // - // [hwcap]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/riscv/include/uapi/asm/hwcap.h?h=v6.15 + // [hwcap]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/riscv/include/uapi/asm/hwcap.h?h=v6.16 let auxv = auxvec::auxv().expect("read auxvec"); // should not fail on RISC-V platform let mut has_i = bit::test(auxv.hwcap, (b'i' - b'a').into()); #[allow(clippy::eq_op)] @@ -233,6 +234,7 @@ pub(crate) fn detect_features() -> cache::Initializer { enable_feature(Feature::zalrsc, test(RISCV_HWPROBE_EXT_ZALRSC)); enable_feature(Feature::zaamo, test(RISCV_HWPROBE_EXT_ZAAMO)); enable_feature(Feature::zawrs, test(RISCV_HWPROBE_EXT_ZAWRS)); + enable_feature(Feature::zabha, test(RISCV_HWPROBE_EXT_ZABHA)); enable_feature(Feature::zacas, test(RISCV_HWPROBE_EXT_ZACAS)); enable_feature(Feature::ztso, test(RISCV_HWPROBE_EXT_ZTSO)); diff --git a/library/std_detect/src/detect/os/riscv.rs b/library/std_detect/src/detect/os/riscv.rs index dc9a4036d86a..c6acbd3525bd 100644 --- a/library/std_detect/src/detect/os/riscv.rs +++ b/library/std_detect/src/detect/os/riscv.rs @@ -90,7 +90,7 @@ pub(crate) fn imply_features(mut value: cache::Initializer) -> cache::Initialize group!(zks == zbkb & zbkc & zbkx & zksed & zksh); group!(zk == zkn & zkr & zkt); - imply!(zacas => zaamo); + imply!(zabha | zacas => zaamo); group!(a == zalrsc & zaamo); group!(b == zba & zbb & zbs); diff --git a/library/std_detect/tests/cpu-detection.rs b/library/std_detect/tests/cpu-detection.rs index 5ad32d83237c..0c4fa57f2b46 100644 --- a/library/std_detect/tests/cpu-detection.rs +++ b/library/std_detect/tests/cpu-detection.rs @@ -242,6 +242,7 @@ fn riscv_linux() { println!("zalrsc: {}", is_riscv_feature_detected!("zalrsc")); println!("zaamo: {}", is_riscv_feature_detected!("zaamo")); println!("zawrs: {}", is_riscv_feature_detected!("zawrs")); + println!("zabha: {}", is_riscv_feature_detected!("zabha")); println!("zacas: {}", is_riscv_feature_detected!("zacas")); println!("zam: {}", is_riscv_feature_detected!("zam")); println!("ztso: {}", is_riscv_feature_detected!("ztso")); From 7a127fba657ed627cc4877f2871abaf7d9819caa Mon Sep 17 00:00:00 2001 From: Flakebi Date: Fri, 28 Mar 2025 10:15:56 +0100 Subject: [PATCH 373/809] Fix linker-plugin-lto only doing thin lto When rust provides LLVM bitcode files to lld and the bitcode contains function summaries as used for thin lto, lld defaults to using thin lto. This prevents some optimizations that are only applied for fat lto. We solve this by not creating function summaries when fat lto is enabled. The bitcode for the module is just directly written out. An alternative solution would be to set the `ThinLTO=0` module flag to signal lld to do fat lto. The code in clang that sets this flag is here: https://github.com/llvm/llvm-project/blob/560149b5e3c891c64899e9912e29467a69dc3a4c/clang/lib/CodeGen/BackendUtil.cpp#L1150 The code in LLVM that queries the flag and defaults to thin lto if not set is here: https://github.com/llvm/llvm-project/blob/e258bca9505f35e0a22cb213a305eea9b76d11ea/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4441-L4446 --- compiler/rustc_codegen_ssa/src/back/write.rs | 4 +- .../src/external_deps/llvm.rs | 30 ++++++++++ .../src/external_deps/rustc.rs | 6 ++ src/tools/run-make-support/src/lib.rs | 5 +- tests/run-make/cross-lang-lto-clang/rmake.rs | 59 ++++++++++++------- tests/run-make/fat-then-thin-lto/lib.rs | 13 ++++ tests/run-make/fat-then-thin-lto/main.rs | 11 ++++ tests/run-make/fat-then-thin-lto/rmake.rs | 25 ++++++++ tests/run-make/linker-plugin-lto-fat/ir.ll | 6 ++ tests/run-make/linker-plugin-lto-fat/main.rs | 22 +++++++ tests/run-make/linker-plugin-lto-fat/rmake.rs | 33 +++++++++++ 11 files changed, 189 insertions(+), 25 deletions(-) create mode 100644 tests/run-make/fat-then-thin-lto/lib.rs create mode 100644 tests/run-make/fat-then-thin-lto/main.rs create mode 100644 tests/run-make/fat-then-thin-lto/rmake.rs create mode 100644 tests/run-make/linker-plugin-lto-fat/ir.ll create mode 100644 tests/run-make/linker-plugin-lto-fat/main.rs create mode 100644 tests/run-make/linker-plugin-lto-fat/rmake.rs diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 7be274df1d41..0394ddf2bee9 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -215,7 +215,9 @@ impl ModuleConfig { false ), emit_obj, - emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto, + // thin lto summaries prevent fat lto, so do not emit them if fat + // lto is requested. See PR #136840 for background information. + emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat, emit_thin_lto_summary: if_regular!( sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode), false diff --git a/src/tools/run-make-support/src/external_deps/llvm.rs b/src/tools/run-make-support/src/external_deps/llvm.rs index 9a6e35da3fe2..939160d9f41d 100644 --- a/src/tools/run-make-support/src/external_deps/llvm.rs +++ b/src/tools/run-make-support/src/external_deps/llvm.rs @@ -60,6 +60,12 @@ pub fn llvm_pdbutil() -> LlvmPdbutil { LlvmPdbutil::new() } +/// Construct a new `llvm-as` invocation. This assumes that `llvm-as` is available +/// at `$LLVM_BIN_DIR/llvm-as`. +pub fn llvm_as() -> LlvmAs { + LlvmAs::new() +} + /// Construct a new `llvm-dis` invocation. This assumes that `llvm-dis` is available /// at `$LLVM_BIN_DIR/llvm-dis`. pub fn llvm_dis() -> LlvmDis { @@ -135,6 +141,13 @@ pub struct LlvmPdbutil { cmd: Command, } +/// A `llvm-as` invocation builder. +#[derive(Debug)] +#[must_use] +pub struct LlvmAs { + cmd: Command, +} + /// A `llvm-dis` invocation builder. #[derive(Debug)] #[must_use] @@ -158,6 +171,7 @@ crate::macros::impl_common_helpers!(LlvmNm); crate::macros::impl_common_helpers!(LlvmBcanalyzer); crate::macros::impl_common_helpers!(LlvmDwarfdump); crate::macros::impl_common_helpers!(LlvmPdbutil); +crate::macros::impl_common_helpers!(LlvmAs); crate::macros::impl_common_helpers!(LlvmDis); crate::macros::impl_common_helpers!(LlvmObjcopy); @@ -441,6 +455,22 @@ impl LlvmObjcopy { } } +impl LlvmAs { + /// Construct a new `llvm-as` invocation. This assumes that `llvm-as` is available + /// at `$LLVM_BIN_DIR/llvm-as`. + pub fn new() -> Self { + let llvm_as = llvm_bin_dir().join("llvm-as"); + let cmd = Command::new(llvm_as); + Self { cmd } + } + + /// Provide an input file. + pub fn input>(&mut self, path: P) -> &mut Self { + self.cmd.arg(path.as_ref()); + self + } +} + impl LlvmDis { /// Construct a new `llvm-dis` invocation. This assumes that `llvm-dis` is available /// at `$LLVM_BIN_DIR/llvm-dis`. diff --git a/src/tools/run-make-support/src/external_deps/rustc.rs b/src/tools/run-make-support/src/external_deps/rustc.rs index 08ba1388dc14..60d3366ee98c 100644 --- a/src/tools/run-make-support/src/external_deps/rustc.rs +++ b/src/tools/run-make-support/src/external_deps/rustc.rs @@ -173,6 +173,12 @@ impl Rustc { self } + /// This flag enables LTO in the specified form. + pub fn lto(&mut self, option: &str) -> &mut Self { + self.cmd.arg(format!("-Clto={option}")); + self + } + /// This flag defers LTO optimizations to the linker. pub fn linker_plugin_lto(&mut self, option: &str) -> &mut Self { self.cmd.arg(format!("-Clinker-plugin-lto={option}")); diff --git a/src/tools/run-make-support/src/lib.rs b/src/tools/run-make-support/src/lib.rs index 29cd6c4ad159..b7d89b130c6b 100644 --- a/src/tools/run-make-support/src/lib.rs +++ b/src/tools/run-make-support/src/lib.rs @@ -63,8 +63,9 @@ pub use crate::external_deps::clang::{Clang, clang}; pub use crate::external_deps::htmldocck::htmldocck; pub use crate::external_deps::llvm::{ self, LlvmAr, LlvmBcanalyzer, LlvmDis, LlvmDwarfdump, LlvmFilecheck, LlvmNm, LlvmObjcopy, - LlvmObjdump, LlvmProfdata, LlvmReadobj, llvm_ar, llvm_bcanalyzer, llvm_dis, llvm_dwarfdump, - llvm_filecheck, llvm_nm, llvm_objcopy, llvm_objdump, llvm_profdata, llvm_readobj, + LlvmObjdump, LlvmProfdata, LlvmReadobj, llvm_ar, llvm_as, llvm_bcanalyzer, llvm_dis, + llvm_dwarfdump, llvm_filecheck, llvm_nm, llvm_objcopy, llvm_objdump, llvm_profdata, + llvm_readobj, }; pub use crate::external_deps::python::python_command; pub use crate::external_deps::rustc::{self, Rustc, bare_rustc, rustc, rustc_path}; diff --git a/tests/run-make/cross-lang-lto-clang/rmake.rs b/tests/run-make/cross-lang-lto-clang/rmake.rs index 3fed6ea20667..f209318abbcc 100644 --- a/tests/run-make/cross-lang-lto-clang/rmake.rs +++ b/tests/run-make/cross-lang-lto-clang/rmake.rs @@ -28,7 +28,17 @@ static C_NEVER_INLINED_PATTERN: &'static str = "bl.*"; static C_NEVER_INLINED_PATTERN: &'static str = "call.*c_never_inlined"; fn main() { + test_lto(false); + test_lto(true); +} + +fn test_lto(fat_lto: bool) { + let lto = if fat_lto { "fat" } else { "thin" }; + let clang_lto = if fat_lto { "full" } else { "thin" }; + println!("Running {lto} lto"); + rustc() + .lto(lto) .linker_plugin_lto("on") .output(static_lib_name("rustlib-xlto")) .opt_level("2") @@ -36,30 +46,36 @@ fn main() { .input("rustlib.rs") .run(); clang() - .lto("thin") + .lto(clang_lto) .use_ld("lld") .arg("-lrustlib-xlto") .out_exe("cmain") .input("cmain.c") .arg("-O3") .run(); + + let dump = llvm_objdump().disassemble().input("cmain").run(); // Make sure we don't find a call instruction to the function we expect to // always be inlined. - llvm_objdump() - .disassemble() - .input("cmain") - .run() - .assert_stdout_not_contains_regex(RUST_ALWAYS_INLINED_PATTERN); + dump.assert_stdout_not_contains_regex(RUST_ALWAYS_INLINED_PATTERN); // As a sanity check, make sure we do find a call instruction to a // non-inlined function - llvm_objdump() - .disassemble() - .input("cmain") - .run() - .assert_stdout_contains_regex(RUST_NEVER_INLINED_PATTERN); - clang().input("clib.c").lto("thin").arg("-c").out_exe("clib.o").arg("-O2").run(); + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + dump.assert_stdout_contains_regex(RUST_NEVER_INLINED_PATTERN); + #[cfg(any(target_arch = "aarch64", target_arch = "arm"))] + { + if fat_lto { + // fat lto inlines this anyway + dump.assert_stdout_not_contains_regex(RUST_NEVER_INLINED_PATTERN); + } else { + dump.assert_stdout_contains_regex(RUST_NEVER_INLINED_PATTERN); + } + } + + clang().input("clib.c").lto(clang_lto).arg("-c").out_exe("clib.o").arg("-O2").run(); llvm_ar().obj_to_ar().output_input(static_lib_name("xyz"), "clib.o").run(); rustc() + .lto(lto) .linker_plugin_lto("on") .opt_level("2") .linker(&env_var("CLANG")) @@ -67,14 +83,13 @@ fn main() { .input("main.rs") .output("rsmain") .run(); - llvm_objdump() - .disassemble() - .input("rsmain") - .run() - .assert_stdout_not_contains_regex(C_ALWAYS_INLINED_PATTERN); - llvm_objdump() - .disassemble() - .input("rsmain") - .run() - .assert_stdout_contains_regex(C_NEVER_INLINED_PATTERN); + + let dump = llvm_objdump().disassemble().input("rsmain").run(); + dump.assert_stdout_not_contains_regex(C_ALWAYS_INLINED_PATTERN); + if fat_lto { + // fat lto inlines this anyway + dump.assert_stdout_not_contains_regex(C_NEVER_INLINED_PATTERN); + } else { + dump.assert_stdout_contains_regex(C_NEVER_INLINED_PATTERN); + } } diff --git a/tests/run-make/fat-then-thin-lto/lib.rs b/tests/run-make/fat-then-thin-lto/lib.rs new file mode 100644 index 000000000000..c675dcb6e8a8 --- /dev/null +++ b/tests/run-make/fat-then-thin-lto/lib.rs @@ -0,0 +1,13 @@ +#![allow(internal_features)] +#![feature(no_core, lang_items)] +#![no_core] +#![crate_type = "rlib"] + +#[lang = "pointee_sized"] +trait PointeeSized {} +#[lang = "meta_sized"] +trait MetaSized: PointeeSized {} +#[lang = "sized"] +trait Sized: MetaSized {} + +pub fn foo() {} diff --git a/tests/run-make/fat-then-thin-lto/main.rs b/tests/run-make/fat-then-thin-lto/main.rs new file mode 100644 index 000000000000..a3f2e18158bc --- /dev/null +++ b/tests/run-make/fat-then-thin-lto/main.rs @@ -0,0 +1,11 @@ +#![allow(internal_features)] +#![feature(no_core, lang_items)] +#![no_core] +#![crate_type = "cdylib"] + +extern crate lib; + +#[unsafe(no_mangle)] +pub fn bar() { + lib::foo(); +} diff --git a/tests/run-make/fat-then-thin-lto/rmake.rs b/tests/run-make/fat-then-thin-lto/rmake.rs new file mode 100644 index 000000000000..ef4f26689d4e --- /dev/null +++ b/tests/run-make/fat-then-thin-lto/rmake.rs @@ -0,0 +1,25 @@ +// Compile a library with lto=fat, then compile a binary with lto=thin +// and check that lto is applied with the library. +// The goal is to mimic the standard library being build with lto=fat +// and allowing users to build with lto=thin. + +//@ only-x86_64-unknown-linux-gnu + +use run_make_support::{dynamic_lib_name, llvm_objdump, rustc}; + +fn main() { + rustc().input("lib.rs").opt_level("3").lto("fat").run(); + rustc().input("main.rs").panic("abort").opt_level("3").lto("thin").run(); + + llvm_objdump() + .input(dynamic_lib_name("main")) + .arg("--disassemble-symbols=bar") + .run() + // The called function should be inlined. + // Check that we have a ret (to detect tail + // calls with a jmp) and no call. + .assert_stdout_contains("bar") + .assert_stdout_contains("ret") + .assert_stdout_not_contains("foo") + .assert_stdout_not_contains("call"); +} diff --git a/tests/run-make/linker-plugin-lto-fat/ir.ll b/tests/run-make/linker-plugin-lto-fat/ir.ll new file mode 100644 index 000000000000..fa3dbdd4e088 --- /dev/null +++ b/tests/run-make/linker-plugin-lto-fat/ir.ll @@ -0,0 +1,6 @@ +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-unknown-linux-gnu" + +define void @ir_callee() { + ret void +} diff --git a/tests/run-make/linker-plugin-lto-fat/main.rs b/tests/run-make/linker-plugin-lto-fat/main.rs new file mode 100644 index 000000000000..ad2a90bc8019 --- /dev/null +++ b/tests/run-make/linker-plugin-lto-fat/main.rs @@ -0,0 +1,22 @@ +#![allow(internal_features)] +#![feature(no_core, lang_items)] +#![no_core] +#![crate_type = "cdylib"] + +#[lang = "pointee_sized"] +trait PointeeSized {} +#[lang = "meta_sized"] +trait MetaSized: PointeeSized {} +#[lang = "sized"] +trait Sized: MetaSized {} + +extern "C" { + fn ir_callee(); +} + +#[no_mangle] +extern "C" fn rs_foo() { + unsafe { + ir_callee(); + } +} diff --git a/tests/run-make/linker-plugin-lto-fat/rmake.rs b/tests/run-make/linker-plugin-lto-fat/rmake.rs new file mode 100644 index 000000000000..ff5b647a5941 --- /dev/null +++ b/tests/run-make/linker-plugin-lto-fat/rmake.rs @@ -0,0 +1,33 @@ +// Check that -C lto=fat with -C linker-plugin-lto actually works and can inline functions. +// A library is created from LLVM IR, defining a single function. Then a dylib is compiled, +// linking to the library and calling the function from the library. +// The function from the library should end up inlined and disappear from the output. + +//@ only-x86_64-unknown-linux-gnu +//@ needs-rust-lld + +use run_make_support::{dynamic_lib_name, llvm_as, llvm_objdump, rustc}; + +fn main() { + llvm_as().input("ir.ll").run(); + rustc() + .input("main.rs") + .opt_level("3") + .lto("fat") + .linker_plugin_lto("on") + .link_arg("ir.bc") + .arg("-Zunstable-options") + .arg("-Clinker-features=+lld") + .run(); + + llvm_objdump() + .input(dynamic_lib_name("main")) + .arg("--disassemble-symbols=rs_foo") + .run() + // The called function should be inlined. + // Check that we have a ret (to detect tail + // calls with a jmp) and no call. + .assert_stdout_contains("foo") + .assert_stdout_contains("ret") + .assert_stdout_not_contains("call"); +} From 227abb70ab2e3d10f05fe933d3c77ecbb04eb9a9 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 22 Jul 2025 12:03:15 +0200 Subject: [PATCH 374/809] Make `libtest::ERROR_EXIT_CODE` const public to not redefine it in rustdoc --- library/test/src/lib.rs | 4 ++-- src/librustdoc/doctest.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 7f56d1e36269..1190bb56b97a 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -89,8 +89,8 @@ use options::RunStrategy; use test_result::*; use time::TestExecTime; -// Process exit code to be used to indicate test failures. -const ERROR_EXIT_CODE: i32 = 101; +/// Process exit code to be used to indicate test failures. +pub const ERROR_EXIT_CODE: i32 = 101; const SECONDARY_TEST_INVOKER_VAR: &str = "__RUST_TEST_INVOKE"; const SECONDARY_TEST_BENCH_BENCHMARKS_VAR: &str = "__RUST_TEST_BENCH_BENCHMARKS"; diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 0bef091468f2..a4344c87e028 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -410,7 +410,7 @@ pub(crate) fn run_tests( std::mem::drop(temp_dir); times.display_times(); // libtest::ERROR_EXIT_CODE is not public but it's the same value. - std::process::exit(101); + std::process::exit(test::ERROR_EXIT_CODE); } } From bee5fbf36e9cbb7f3317ce6a71b3574dc007dee5 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 22 Jul 2025 13:31:12 +0200 Subject: [PATCH 375/809] Fix CI build failure when using new libtest public constant --- src/librustdoc/doctest.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index a4344c87e028..35ace6566381 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -409,8 +409,9 @@ pub(crate) fn run_tests( // We ensure temp dir destructor is called. std::mem::drop(temp_dir); times.display_times(); - // libtest::ERROR_EXIT_CODE is not public but it's the same value. - std::process::exit(test::ERROR_EXIT_CODE); + // FIXME(GuillaumeGomez): Uncomment the next line once #144297 has been merged. + // std::process::exit(test::ERROR_EXIT_CODE); + std::process::exit(101); } } From 94cc5bb9620cdee942b8b79e7026f622fcc695a0 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 30 Jul 2025 14:29:28 +1000 Subject: [PATCH 376/809] 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 377/809] 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 378/809] 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 1901dde97bdff7b6b308c41d751e826df4eb2016 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 11:52:42 +1000 Subject: [PATCH 379/809] 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. --- Cargo.lock | 1 + compiler/rustc_ast/src/ast.rs | 101 +-------- compiler/rustc_ast/src/util/literal.rs | 6 +- compiler/rustc_ast_ir/Cargo.toml | 2 + compiler/rustc_ast_ir/src/lib.rs | 210 ++++++++++++++++++ .../src/hir_ty_lowering/mod.rs | 6 +- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 8 +- compiler/rustc_lint/src/types/literal.rs | 4 +- compiler/rustc_middle/src/ty/mod.rs | 53 ----- compiler/rustc_type_ir/src/lib.rs | 2 +- compiler/rustc_type_ir/src/ty_kind.rs | 174 +-------------- src/librustdoc/clean/types.rs | 37 --- .../clippy/clippy_lints/src/float_literal.rs | 10 +- .../clippy/clippy_lints/src/utils/author.rs | 35 ++- src/tools/clippy/clippy_utils/src/consts.rs | 10 +- 15 files changed, 269 insertions(+), 390 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c1076f05ef12..a7f8082f3289 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3417,6 +3417,7 @@ dependencies = [ "rustc_data_structures", "rustc_macros", "rustc_serialize", + "rustc_span", ] [[package]] diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 984b280e81b5..fdff18ffd471 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -23,7 +23,7 @@ use std::{cmp, fmt}; pub use GenericArgs::*; pub use UnsafeSource::*; -pub use rustc_ast_ir::{Movability, Mutability, Pinnedness}; +pub use rustc_ast_ir::{FloatTy, IntTy, Movability, Mutability, Pinnedness, UintTy}; use rustc_data_structures::packed::Pu128; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::stack::ensure_sufficient_stack; @@ -2285,105 +2285,6 @@ pub struct FnSig { pub span: Span, } -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[derive(Encodable, Decodable, HashStable_Generic)] -pub enum FloatTy { - F16, - F32, - F64, - F128, -} - -impl FloatTy { - pub fn name_str(self) -> &'static str { - match self { - FloatTy::F16 => "f16", - FloatTy::F32 => "f32", - FloatTy::F64 => "f64", - FloatTy::F128 => "f128", - } - } - - pub fn name(self) -> Symbol { - match self { - FloatTy::F16 => sym::f16, - FloatTy::F32 => sym::f32, - FloatTy::F64 => sym::f64, - FloatTy::F128 => sym::f128, - } - } -} - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[derive(Encodable, Decodable, HashStable_Generic)] -pub enum IntTy { - Isize, - I8, - I16, - I32, - I64, - I128, -} - -impl IntTy { - pub fn name_str(&self) -> &'static str { - match *self { - IntTy::Isize => "isize", - IntTy::I8 => "i8", - IntTy::I16 => "i16", - IntTy::I32 => "i32", - IntTy::I64 => "i64", - IntTy::I128 => "i128", - } - } - - pub fn name(&self) -> Symbol { - match *self { - IntTy::Isize => sym::isize, - IntTy::I8 => sym::i8, - IntTy::I16 => sym::i16, - IntTy::I32 => sym::i32, - IntTy::I64 => sym::i64, - IntTy::I128 => sym::i128, - } - } -} - -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)] -#[derive(Encodable, Decodable, HashStable_Generic)] -pub enum UintTy { - Usize, - U8, - U16, - U32, - U64, - U128, -} - -impl UintTy { - pub fn name_str(&self) -> &'static str { - match *self { - UintTy::Usize => "usize", - UintTy::U8 => "u8", - UintTy::U16 => "u16", - UintTy::U32 => "u32", - UintTy::U64 => "u64", - UintTy::U128 => "u128", - } - } - - pub fn name(&self) -> Symbol { - match *self { - UintTy::Usize => sym::usize, - UintTy::U8 => sym::u8, - UintTy::U16 => sym::u16, - UintTy::U32 => sym::u32, - UintTy::U64 => sym::u64, - UintTy::U128 => sym::u128, - } - } -} - /// A constraint on an associated item. /// /// ### Examples diff --git a/compiler/rustc_ast/src/util/literal.rs b/compiler/rustc_ast/src/util/literal.rs index 2dfd695d8802..e9cf3cf07372 100644 --- a/compiler/rustc_ast/src/util/literal.rs +++ b/compiler/rustc_ast/src/util/literal.rs @@ -190,15 +190,15 @@ impl fmt::Display for LitKind { LitKind::Int(n, ty) => { write!(f, "{n}")?; match ty { - ast::LitIntType::Unsigned(ty) => write!(f, "{}", ty.name())?, - ast::LitIntType::Signed(ty) => write!(f, "{}", ty.name())?, + ast::LitIntType::Unsigned(ty) => write!(f, "{}", ty.name_str())?, + ast::LitIntType::Signed(ty) => write!(f, "{}", ty.name_str())?, ast::LitIntType::Unsuffixed => {} } } LitKind::Float(symbol, ty) => { write!(f, "{symbol}")?; match ty { - ast::LitFloatType::Suffixed(ty) => write!(f, "{}", ty.name())?, + ast::LitFloatType::Suffixed(ty) => write!(f, "{}", ty.name_str())?, ast::LitFloatType::Unsuffixed => {} } } diff --git a/compiler/rustc_ast_ir/Cargo.toml b/compiler/rustc_ast_ir/Cargo.toml index 76bdd9f7eb6d..ee2ab62b7257 100644 --- a/compiler/rustc_ast_ir/Cargo.toml +++ b/compiler/rustc_ast_ir/Cargo.toml @@ -8,12 +8,14 @@ edition = "2024" rustc_data_structures = { path = "../rustc_data_structures", optional = true } rustc_macros = { path = "../rustc_macros", optional = true } rustc_serialize = { path = "../rustc_serialize", optional = true } +rustc_span = { path = "../rustc_span", optional = true } # tidy-alphabetical-end [features] default = ["nightly"] nightly = [ "dep:rustc_serialize", + "dep:rustc_span", "dep:rustc_data_structures", "dep:rustc_macros", ] diff --git a/compiler/rustc_ast_ir/src/lib.rs b/compiler/rustc_ast_ir/src/lib.rs index 0898433a74c5..8f2a37c12108 100644 --- a/compiler/rustc_ast_ir/src/lib.rs +++ b/compiler/rustc_ast_ir/src/lib.rs @@ -11,11 +11,221 @@ #![cfg_attr(feature = "nightly", feature(rustc_attrs))] // tidy-alphabetical-end +use std::fmt; + #[cfg(feature = "nightly")] use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; +#[cfg(feature = "nightly")] +use rustc_span::{Symbol, sym}; pub mod visit; +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] +pub enum IntTy { + Isize, + I8, + I16, + I32, + I64, + I128, +} + +impl IntTy { + pub fn name_str(&self) -> &'static str { + match *self { + IntTy::Isize => "isize", + IntTy::I8 => "i8", + IntTy::I16 => "i16", + IntTy::I32 => "i32", + IntTy::I64 => "i64", + IntTy::I128 => "i128", + } + } + + #[cfg(feature = "nightly")] + pub fn name(self) -> Symbol { + match self { + IntTy::Isize => sym::isize, + IntTy::I8 => sym::i8, + IntTy::I16 => sym::i16, + IntTy::I32 => sym::i32, + IntTy::I64 => sym::i64, + IntTy::I128 => sym::i128, + } + } + + pub fn bit_width(&self) -> Option { + Some(match *self { + IntTy::Isize => return None, + IntTy::I8 => 8, + IntTy::I16 => 16, + IntTy::I32 => 32, + IntTy::I64 => 64, + IntTy::I128 => 128, + }) + } + + pub fn normalize(&self, target_width: u32) -> Self { + match self { + IntTy::Isize => match target_width { + 16 => IntTy::I16, + 32 => IntTy::I32, + 64 => IntTy::I64, + _ => unreachable!(), + }, + _ => *self, + } + } + + pub fn to_unsigned(self) -> UintTy { + match self { + IntTy::Isize => UintTy::Usize, + IntTy::I8 => UintTy::U8, + IntTy::I16 => UintTy::U16, + IntTy::I32 => UintTy::U32, + IntTy::I64 => UintTy::U64, + IntTy::I128 => UintTy::U128, + } + } +} + +impl fmt::Debug for IntTy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name_str()) + } +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] +pub enum UintTy { + Usize, + U8, + U16, + U32, + U64, + U128, +} + +impl UintTy { + pub fn name_str(&self) -> &'static str { + match *self { + UintTy::Usize => "usize", + UintTy::U8 => "u8", + UintTy::U16 => "u16", + UintTy::U32 => "u32", + UintTy::U64 => "u64", + UintTy::U128 => "u128", + } + } + + #[cfg(feature = "nightly")] + pub fn name(self) -> Symbol { + match self { + UintTy::Usize => sym::usize, + UintTy::U8 => sym::u8, + UintTy::U16 => sym::u16, + UintTy::U32 => sym::u32, + UintTy::U64 => sym::u64, + UintTy::U128 => sym::u128, + } + } + + pub fn bit_width(&self) -> Option { + Some(match *self { + UintTy::Usize => return None, + UintTy::U8 => 8, + UintTy::U16 => 16, + UintTy::U32 => 32, + UintTy::U64 => 64, + UintTy::U128 => 128, + }) + } + + pub fn normalize(&self, target_width: u32) -> Self { + match self { + UintTy::Usize => match target_width { + 16 => UintTy::U16, + 32 => UintTy::U32, + 64 => UintTy::U64, + _ => unreachable!(), + }, + _ => *self, + } + } + + pub fn to_signed(self) -> IntTy { + match self { + UintTy::Usize => IntTy::Isize, + UintTy::U8 => IntTy::I8, + UintTy::U16 => IntTy::I16, + UintTy::U32 => IntTy::I32, + UintTy::U64 => IntTy::I64, + UintTy::U128 => IntTy::I128, + } + } +} + +impl fmt::Debug for UintTy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name_str()) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] +pub enum FloatTy { + F16, + F32, + F64, + F128, +} + +impl FloatTy { + pub fn name_str(self) -> &'static str { + match self { + FloatTy::F16 => "f16", + FloatTy::F32 => "f32", + FloatTy::F64 => "f64", + FloatTy::F128 => "f128", + } + } + + #[cfg(feature = "nightly")] + pub fn name(self) -> Symbol { + match self { + FloatTy::F16 => sym::f16, + FloatTy::F32 => sym::f32, + FloatTy::F64 => sym::f64, + FloatTy::F128 => sym::f128, + } + } + + pub fn bit_width(self) -> u64 { + match self { + FloatTy::F16 => 16, + FloatTy::F32 => 32, + FloatTy::F64 => 64, + FloatTy::F128 => 128, + } + } +} + +impl fmt::Debug for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name_str()) + } +} + /// The movability of a coroutine / closure literal: /// whether a coroutine contains self-references, causing it to be `!Unpin`. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)] 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..3daeb548a799 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -2037,9 +2037,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { match prim_ty { hir::PrimTy::Bool => tcx.types.bool, hir::PrimTy::Char => tcx.types.char, - hir::PrimTy::Int(it) => Ty::new_int(tcx, ty::int_ty(it)), - hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, ty::uint_ty(uit)), - hir::PrimTy::Float(ft) => Ty::new_float(tcx, ty::float_ty(ft)), + hir::PrimTy::Int(it) => Ty::new_int(tcx, it), + hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit), + hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft), hir::PrimTy::Str => tcx.types.str_, } } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 719989d57930..36abd7c85550 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -1658,8 +1658,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ), ast::LitKind::Byte(_) => tcx.types.u8, ast::LitKind::Char(_) => tcx.types.char, - ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => Ty::new_int(tcx, ty::int_ty(t)), - ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => Ty::new_uint(tcx, ty::uint_ty(t)), + ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => Ty::new_int(tcx, t), + ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => Ty::new_uint(tcx, t), ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) => { let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() { ty::Int(_) | ty::Uint(_) => Some(ty), @@ -1686,9 +1686,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }); opt_ty.unwrap_or_else(|| self.next_int_var()) } - ast::LitKind::Float(_, ast::LitFloatType::Suffixed(t)) => { - Ty::new_float(tcx, ty::float_ty(t)) - } + ast::LitKind::Float(_, ast::LitFloatType::Suffixed(t)) => Ty::new_float(tcx, t), ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => { let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() { ty::Float(_) => Some(ty), diff --git a/compiler/rustc_lint/src/types/literal.rs b/compiler/rustc_lint/src/types/literal.rs index 2bac58ba23d0..b869d657720e 100644 --- a/compiler/rustc_lint/src/types/literal.rs +++ b/compiler/rustc_lint/src/types/literal.rs @@ -272,7 +272,7 @@ fn lint_int_literal<'tcx>( cx, hir_id, span, - attrs::IntType::SignedInt(ty::ast_int_ty(t)), + attrs::IntType::SignedInt(t), Integer::from_int_ty(cx, t).size(), repr_str, v, @@ -358,7 +358,7 @@ fn lint_uint_literal<'tcx>( cx, hir_id, span, - attrs::IntType::UnsignedInt(ty::ast_uint_ty(t)), + attrs::IntType::UnsignedInt(t), Integer::from_uint_ty(cx, t).size(), repr_str, lit_val, diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index bb70c61cd141..4524fb5a0977 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2198,59 +2198,6 @@ impl<'tcx> TyCtxt<'tcx> { } } -pub fn int_ty(ity: ast::IntTy) -> IntTy { - match ity { - ast::IntTy::Isize => IntTy::Isize, - ast::IntTy::I8 => IntTy::I8, - ast::IntTy::I16 => IntTy::I16, - ast::IntTy::I32 => IntTy::I32, - ast::IntTy::I64 => IntTy::I64, - ast::IntTy::I128 => IntTy::I128, - } -} - -pub fn uint_ty(uty: ast::UintTy) -> UintTy { - match uty { - ast::UintTy::Usize => UintTy::Usize, - ast::UintTy::U8 => UintTy::U8, - ast::UintTy::U16 => UintTy::U16, - ast::UintTy::U32 => UintTy::U32, - ast::UintTy::U64 => UintTy::U64, - ast::UintTy::U128 => UintTy::U128, - } -} - -pub fn float_ty(fty: ast::FloatTy) -> FloatTy { - match fty { - ast::FloatTy::F16 => FloatTy::F16, - ast::FloatTy::F32 => FloatTy::F32, - ast::FloatTy::F64 => FloatTy::F64, - ast::FloatTy::F128 => FloatTy::F128, - } -} - -pub fn ast_int_ty(ity: IntTy) -> ast::IntTy { - match ity { - IntTy::Isize => ast::IntTy::Isize, - IntTy::I8 => ast::IntTy::I8, - IntTy::I16 => ast::IntTy::I16, - IntTy::I32 => ast::IntTy::I32, - IntTy::I64 => ast::IntTy::I64, - IntTy::I128 => ast::IntTy::I128, - } -} - -pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy { - match uty { - UintTy::Usize => ast::UintTy::Usize, - UintTy::U8 => ast::UintTy::U8, - UintTy::U16 => ast::UintTy::U16, - UintTy::U32 => ast::UintTy::U32, - UintTy::U64 => ast::UintTy::U64, - UintTy::U128 => ast::UintTy::U128, - } -} - pub fn provide(providers: &mut Providers) { closure::provide(providers); context::provide(providers); diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index a483c18813b0..ad1a7a633e4e 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -75,7 +75,7 @@ pub use pattern::*; pub use predicate::*; pub use predicate_kind::*; pub use region_kind::*; -pub use rustc_ast_ir::{Movability, Mutability, Pinnedness}; +pub use rustc_ast_ir::{FloatTy, IntTy, Movability, Mutability, Pinnedness, UintTy}; pub use ty_info::*; pub use ty_kind::*; pub use upcast::*; diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 7c6654247505..d11f17352198 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -15,7 +15,7 @@ pub use self::closure::*; use crate::inherent::*; #[cfg(feature = "nightly")] use crate::visit::TypeVisitable; -use crate::{self as ty, DebruijnIndex, Interner}; +use crate::{self as ty, DebruijnIndex, FloatTy, IntTy, Interner, UintTy}; mod closure; @@ -509,160 +509,6 @@ impl AliasTy { } } -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr( - feature = "nightly", - derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) -)] -pub enum IntTy { - Isize, - I8, - I16, - I32, - I64, - I128, -} - -impl IntTy { - pub fn name_str(&self) -> &'static str { - match *self { - IntTy::Isize => "isize", - IntTy::I8 => "i8", - IntTy::I16 => "i16", - IntTy::I32 => "i32", - IntTy::I64 => "i64", - IntTy::I128 => "i128", - } - } - - pub fn bit_width(&self) -> Option { - Some(match *self { - IntTy::Isize => return None, - IntTy::I8 => 8, - IntTy::I16 => 16, - IntTy::I32 => 32, - IntTy::I64 => 64, - IntTy::I128 => 128, - }) - } - - pub fn normalize(&self, target_width: u32) -> Self { - match self { - IntTy::Isize => match target_width { - 16 => IntTy::I16, - 32 => IntTy::I32, - 64 => IntTy::I64, - _ => unreachable!(), - }, - _ => *self, - } - } - - pub fn to_unsigned(self) -> UintTy { - match self { - IntTy::Isize => UintTy::Usize, - IntTy::I8 => UintTy::U8, - IntTy::I16 => UintTy::U16, - IntTy::I32 => UintTy::U32, - IntTy::I64 => UintTy::U64, - IntTy::I128 => UintTy::U128, - } - } -} - -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)] -#[cfg_attr( - feature = "nightly", - derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) -)] -pub enum UintTy { - Usize, - U8, - U16, - U32, - U64, - U128, -} - -impl UintTy { - pub fn name_str(&self) -> &'static str { - match *self { - UintTy::Usize => "usize", - UintTy::U8 => "u8", - UintTy::U16 => "u16", - UintTy::U32 => "u32", - UintTy::U64 => "u64", - UintTy::U128 => "u128", - } - } - - pub fn bit_width(&self) -> Option { - Some(match *self { - UintTy::Usize => return None, - UintTy::U8 => 8, - UintTy::U16 => 16, - UintTy::U32 => 32, - UintTy::U64 => 64, - UintTy::U128 => 128, - }) - } - - pub fn normalize(&self, target_width: u32) -> Self { - match self { - UintTy::Usize => match target_width { - 16 => UintTy::U16, - 32 => UintTy::U32, - 64 => UintTy::U64, - _ => unreachable!(), - }, - _ => *self, - } - } - - pub fn to_signed(self) -> IntTy { - match self { - UintTy::Usize => IntTy::Isize, - UintTy::U8 => IntTy::I8, - UintTy::U16 => IntTy::I16, - UintTy::U32 => IntTy::I32, - UintTy::U64 => IntTy::I64, - UintTy::U128 => IntTy::I128, - } - } -} - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr( - feature = "nightly", - derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) -)] -pub enum FloatTy { - F16, - F32, - F64, - F128, -} - -impl FloatTy { - pub fn name_str(self) -> &'static str { - match self { - FloatTy::F16 => "f16", - FloatTy::F32 => "f32", - FloatTy::F64 => "f64", - FloatTy::F128 => "f128", - } - } - - pub fn bit_width(self) -> u64 { - match self { - FloatTy::F16 => 16, - FloatTy::F32 => 32, - FloatTy::F64 => 64, - FloatTy::F128 => 128, - } - } -} - #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum IntVarValue { Unknown, @@ -860,24 +706,6 @@ impl fmt::Display for InferTy { } } -impl fmt::Debug for IntTy { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.name_str()) - } -} - -impl fmt::Debug for UintTy { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.name_str()) - } -} - -impl fmt::Debug for FloatTy { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.name_str()) - } -} - impl fmt::Debug for InferTy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use InferTy::*; diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 5ac5da24299f..13bb53f8fc41 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1963,43 +1963,6 @@ impl PrimitiveType { } } -impl From for PrimitiveType { - fn from(int_ty: ast::IntTy) -> PrimitiveType { - match int_ty { - ast::IntTy::Isize => PrimitiveType::Isize, - ast::IntTy::I8 => PrimitiveType::I8, - ast::IntTy::I16 => PrimitiveType::I16, - ast::IntTy::I32 => PrimitiveType::I32, - ast::IntTy::I64 => PrimitiveType::I64, - ast::IntTy::I128 => PrimitiveType::I128, - } - } -} - -impl From for PrimitiveType { - fn from(uint_ty: ast::UintTy) -> PrimitiveType { - match uint_ty { - ast::UintTy::Usize => PrimitiveType::Usize, - ast::UintTy::U8 => PrimitiveType::U8, - ast::UintTy::U16 => PrimitiveType::U16, - ast::UintTy::U32 => PrimitiveType::U32, - ast::UintTy::U64 => PrimitiveType::U64, - ast::UintTy::U128 => PrimitiveType::U128, - } - } -} - -impl From for PrimitiveType { - fn from(float_ty: ast::FloatTy) -> PrimitiveType { - match float_ty { - ast::FloatTy::F16 => PrimitiveType::F16, - ast::FloatTy::F32 => PrimitiveType::F32, - ast::FloatTy::F64 => PrimitiveType::F64, - ast::FloatTy::F128 => PrimitiveType::F128, - } - } -} - impl From for PrimitiveType { fn from(int_ty: ty::IntTy) -> PrimitiveType { match int_ty { diff --git a/src/tools/clippy/clippy_lints/src/float_literal.rs b/src/tools/clippy/clippy_lints/src/float_literal.rs index c51267567d01..ccaf38aee4d8 100644 --- a/src/tools/clippy/clippy_lints/src/float_literal.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs index ac92ab5a245c..299317384122 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/consts.rs b/src/tools/clippy/clippy_utils/src/consts.rs index 25afa12e95d6..ecd88daa6b39 100644 --- a/src/tools/clippy/clippy_utils/src/consts.rs +++ b/src/tools/clippy/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 618a90d1b0682f687b63cc591ef78814538d5a8f Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 11:52:42 +1000 Subject: [PATCH 380/809] 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 704f2ca17224dc1d208423c675313521b0f49645 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 31 Jul 2025 13:15:49 +1000 Subject: [PATCH 381/809] Tidy up `Cargo.toml` files. - Add some missing `tidy-alphabetical-*` markers. - Remove some unnecessary blank lines. --- compiler/rustc_ast_ir/Cargo.toml | 6 ++++-- compiler/rustc_codegen_llvm/Cargo.toml | 3 +++ compiler/rustc_driver_impl/Cargo.toml | 2 +- compiler/rustc_index/Cargo.toml | 2 +- compiler/rustc_index_macros/Cargo.toml | 7 ++++++- compiler/rustc_llvm/Cargo.toml | 2 ++ compiler/rustc_mir_build/Cargo.toml | 1 - compiler/rustc_next_trait_solver/Cargo.toml | 2 ++ compiler/rustc_parse/Cargo.toml | 3 +++ compiler/rustc_pattern_analysis/Cargo.toml | 5 ++++- compiler/rustc_proc_macro/Cargo.toml | 4 ++++ compiler/rustc_public/Cargo.toml | 2 ++ compiler/rustc_sanitizers/Cargo.toml | 6 ++++-- compiler/rustc_symbol_mangling/Cargo.toml | 1 - compiler/rustc_transmute/Cargo.toml | 2 ++ compiler/rustc_type_ir/Cargo.toml | 10 ++++++---- 16 files changed, 44 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_ast_ir/Cargo.toml b/compiler/rustc_ast_ir/Cargo.toml index ee2ab62b7257..1d21a07dc440 100644 --- a/compiler/rustc_ast_ir/Cargo.toml +++ b/compiler/rustc_ast_ir/Cargo.toml @@ -12,10 +12,12 @@ rustc_span = { path = "../rustc_span", optional = true } # tidy-alphabetical-end [features] +# tidy-alphabetical-start default = ["nightly"] nightly = [ - "dep:rustc_serialize", - "dep:rustc_span", "dep:rustc_data_structures", "dep:rustc_macros", + "dep:rustc_serialize", + "dep:rustc_span", ] +# tidy-alphabetical-end diff --git a/compiler/rustc_codegen_llvm/Cargo.toml b/compiler/rustc_codegen_llvm/Cargo.toml index 5ab22f8fc4d9..adf9f709410a 100644 --- a/compiler/rustc_codegen_llvm/Cargo.toml +++ b/compiler/rustc_codegen_llvm/Cargo.toml @@ -45,4 +45,7 @@ tracing = "0.1" # tidy-alphabetical-end [features] +# tidy-alphabetical-start check_only = ["rustc_llvm/check_only"] +# tidy-alphabetical-end + diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml index 0d6b49607eb4..ae1dbd2cf514 100644 --- a/compiler/rustc_driver_impl/Cargo.toml +++ b/compiler/rustc_driver_impl/Cargo.toml @@ -4,8 +4,8 @@ version = "0.0.0" edition = "2024" [dependencies] -jiff = { version = "0.2.5", default-features = false, features = ["std"] } # tidy-alphabetical-start +jiff = { version = "0.2.5", default-features = false, features = ["std"] } rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_lowering = { path = "../rustc_ast_lowering" } diff --git a/compiler/rustc_index/Cargo.toml b/compiler/rustc_index/Cargo.toml index 3d83a3c98daf..e46a1a7f7606 100644 --- a/compiler/rustc_index/Cargo.toml +++ b/compiler/rustc_index/Cargo.toml @@ -15,8 +15,8 @@ smallvec = "1.8.1" # tidy-alphabetical-start default = ["nightly"] nightly = [ - "dep:rustc_serialize", "dep:rustc_macros", + "dep:rustc_serialize", "rustc_index_macros/nightly", ] rustc_randomized_layouts = [] diff --git a/compiler/rustc_index_macros/Cargo.toml b/compiler/rustc_index_macros/Cargo.toml index 891e7ded6199..34f3109a526b 100644 --- a/compiler/rustc_index_macros/Cargo.toml +++ b/compiler/rustc_index_macros/Cargo.toml @@ -7,9 +7,14 @@ edition = "2024" proc-macro = true [dependencies] -syn = { version = "2.0.9", features = ["full", "extra-traits"] } +# tidy-alphabetical-start proc-macro2 = "1" quote = "1" +syn = { version = "2.0.9", features = ["full", "extra-traits"] } +# tidy-alphabetical-end [features] +# tidy-alphabetical-start nightly = [] +# tidy-alphabetical-end + diff --git a/compiler/rustc_llvm/Cargo.toml b/compiler/rustc_llvm/Cargo.toml index 85a2a9c09f08..cd352ce3d0f4 100644 --- a/compiler/rustc_llvm/Cargo.toml +++ b/compiler/rustc_llvm/Cargo.toml @@ -16,5 +16,7 @@ cc = "=1.2.16" # tidy-alphabetical-end [features] +# tidy-alphabetical-start # Used by ./x.py check --compile-time-deps to skip building C++ code check_only = [] +# tidy-alphabetical-end diff --git a/compiler/rustc_mir_build/Cargo.toml b/compiler/rustc_mir_build/Cargo.toml index c4c2d8a7ac8e..b9f23400516a 100644 --- a/compiler/rustc_mir_build/Cargo.toml +++ b/compiler/rustc_mir_build/Cargo.toml @@ -6,7 +6,6 @@ edition = "2024" [dependencies] # tidy-alphabetical-start itertools = "0.12" - rustc_abi = { path = "../rustc_abi" } rustc_apfloat = "0.2.0" rustc_arena = { path = "../rustc_arena" } diff --git a/compiler/rustc_next_trait_solver/Cargo.toml b/compiler/rustc_next_trait_solver/Cargo.toml index 36d53901d9e8..05bcabad02f9 100644 --- a/compiler/rustc_next_trait_solver/Cargo.toml +++ b/compiler/rustc_next_trait_solver/Cargo.toml @@ -15,6 +15,7 @@ tracing = "0.1" # tidy-alphabetical-end [features] +# tidy-alphabetical-start default = ["nightly"] nightly = [ "dep:rustc_data_structures", @@ -22,3 +23,4 @@ nightly = [ "rustc_index/nightly", "rustc_type_ir/nightly", ] +# tidy-alphabetical-end diff --git a/compiler/rustc_parse/Cargo.toml b/compiler/rustc_parse/Cargo.toml index 88f93782de16..0ae0b613fa27 100644 --- a/compiler/rustc_parse/Cargo.toml +++ b/compiler/rustc_parse/Cargo.toml @@ -26,5 +26,8 @@ unicode-width = "0.2.0" # tidy-alphabetical-end [dev-dependencies] +# tidy-alphabetical-start termcolor = "1.2" +# tidy-alphabetical-end + diff --git a/compiler/rustc_pattern_analysis/Cargo.toml b/compiler/rustc_pattern_analysis/Cargo.toml index 40d549630aca..a59f7bbeb9e5 100644 --- a/compiler/rustc_pattern_analysis/Cargo.toml +++ b/compiler/rustc_pattern_analysis/Cargo.toml @@ -6,7 +6,6 @@ edition = "2024" [dependencies] # tidy-alphabetical-start rustc-hash = "2.0.0" - rustc_abi = { path = "../rustc_abi", optional = true } rustc_apfloat = "0.2.0" rustc_arena = { path = "../rustc_arena", optional = true } @@ -24,10 +23,13 @@ tracing = "0.1" # tidy-alphabetical-end [dev-dependencies] +# tidy-alphabetical-start tracing-subscriber = { version = "0.3.3", default-features = false, features = ["fmt", "env-filter", "ansi"] } tracing-tree = "0.3.0" +# tidy-alphabetical-end [features] +# tidy-alphabetical-start default = ["rustc"] rustc = [ "dep:rustc_abi", @@ -43,3 +45,4 @@ rustc = [ "smallvec/may_dangle", "rustc_index/nightly", ] +# tidy-alphabetical-end diff --git a/compiler/rustc_proc_macro/Cargo.toml b/compiler/rustc_proc_macro/Cargo.toml index 762acf9a1eb4..beb95aa3b52f 100644 --- a/compiler/rustc_proc_macro/Cargo.toml +++ b/compiler/rustc_proc_macro/Cargo.toml @@ -15,7 +15,11 @@ test = false doctest = false [dependencies] +# tidy-alphabetical-start rustc-literal-escaper = "0.0.5" +# tidy-alphabetical-end [features] +# tidy-alphabetical-start rustc-dep-of-std = [] +# tidy-alphabetical-end diff --git a/compiler/rustc_public/Cargo.toml b/compiler/rustc_public/Cargo.toml index fa782166e4f4..70af30c1a5f4 100644 --- a/compiler/rustc_public/Cargo.toml +++ b/compiler/rustc_public/Cargo.toml @@ -18,7 +18,9 @@ tracing = "0.1" # tidy-alphabetical-end [features] +# tidy-alphabetical-start # Provides access to APIs that expose internals of the rust compiler. # APIs enabled by this feature are unstable. They can be removed or modified # at any point and they are not included in the crate's semantic versioning. rustc_internal = [] +# tidy-alphabetical-end diff --git a/compiler/rustc_sanitizers/Cargo.toml b/compiler/rustc_sanitizers/Cargo.toml index 66488bc96259..9069d2c233db 100644 --- a/compiler/rustc_sanitizers/Cargo.toml +++ b/compiler/rustc_sanitizers/Cargo.toml @@ -4,9 +4,8 @@ version = "0.0.0" edition = "2024" [dependencies] +# tidy-alphabetical-start bitflags = "2.5.0" -tracing = "0.1" -twox-hash = "1.6.3" rustc_abi = { path = "../rustc_abi" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_hir = { path = "../rustc_hir" } @@ -14,3 +13,6 @@ rustc_middle = { path = "../rustc_middle" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } +tracing = "0.1" +twox-hash = "1.6.3" +# tidy-alphabetical-end diff --git a/compiler/rustc_symbol_mangling/Cargo.toml b/compiler/rustc_symbol_mangling/Cargo.toml index 12fe6b719f9b..0df9c7682bf8 100644 --- a/compiler/rustc_symbol_mangling/Cargo.toml +++ b/compiler/rustc_symbol_mangling/Cargo.toml @@ -7,7 +7,6 @@ edition = "2024" # tidy-alphabetical-start punycode = "0.4.0" rustc-demangle = "0.1.21" - rustc_abi = { path = "../rustc_abi" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_transmute/Cargo.toml b/compiler/rustc_transmute/Cargo.toml index 246b66d3d030..e61717e5e9ce 100644 --- a/compiler/rustc_transmute/Cargo.toml +++ b/compiler/rustc_transmute/Cargo.toml @@ -20,9 +20,11 @@ itertools = "0.12" # tidy-alphabetical-end [features] +# tidy-alphabetical-start rustc = [ "dep:rustc_abi", "dep:rustc_hir", "dep:rustc_middle", "dep:rustc_span", ] +# tidy-alphabetical-end diff --git a/compiler/rustc_type_ir/Cargo.toml b/compiler/rustc_type_ir/Cargo.toml index 4bd7bfe79bef..e7fee574dd46 100644 --- a/compiler/rustc_type_ir/Cargo.toml +++ b/compiler/rustc_type_ir/Cargo.toml @@ -23,14 +23,16 @@ tracing = "0.1" # tidy-alphabetical-end [features] +# tidy-alphabetical-start default = ["nightly"] nightly = [ - "dep:rustc_serialize", - "dep:rustc_span", "dep:rustc_data_structures", "dep:rustc_macros", + "dep:rustc_serialize", + "dep:rustc_span", + "rustc_ast_ir/nightly", + "rustc_index/nightly", "smallvec/may_dangle", "smallvec/union", - "rustc_index/nightly", - "rustc_ast_ir/nightly", ] +# tidy-alphabetical-end From 75a1f47750fb34031f00cc2ee2b0d385426bec94 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 25 Jul 2025 19:52:08 +1000 Subject: [PATCH 382/809] Avoid vacuous `Constraint::{VarSubVar,RegSubReg}` constraints. If the two regions are the same, we can skip it. This is a small perf win. --- compiler/rustc_infer/src/infer/region_constraints/mod.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_infer/src/infer/region_constraints/mod.rs b/compiler/rustc_infer/src/infer/region_constraints/mod.rs index a1744b4df80f..4747c203c807 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/mod.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/mod.rs @@ -471,7 +471,9 @@ impl<'tcx> RegionConstraintCollector<'_, 'tcx> { // all regions are subregions of static, so we can ignore this } (ReVar(sub_id), ReVar(sup_id)) => { - self.add_constraint(Constraint::VarSubVar(sub_id, sup_id), origin); + if sub_id != sup_id { + self.add_constraint(Constraint::VarSubVar(sub_id, sup_id), origin); + } } (_, ReVar(sup_id)) => { self.add_constraint(Constraint::RegSubVar(sub, sup_id), origin); @@ -480,7 +482,9 @@ impl<'tcx> RegionConstraintCollector<'_, 'tcx> { self.add_constraint(Constraint::VarSubReg(sub_id, sup), origin); } _ => { - self.add_constraint(Constraint::RegSubReg(sub, sup), origin); + if sub != sup { + self.add_constraint(Constraint::RegSubReg(sub, sup), origin); + } } } } From 066a973312066b792c5de4b41b92dcb437f22bac Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 25 Jul 2025 20:34:36 +1000 Subject: [PATCH 383/809] Overhaul `Constraint`. This commit changes it to store a `Region` instead of a `RegionVid` for the `Var` cases: - We avoid having to call `Region::new_var` to re-create `Region`s from `RegionVid`s in a few places, avoiding the interning process, giving a small perf win. (At the cost of the type allowing some invalid combinations of values.) - All the cases now store two `Region`s, so the commit also separates the `ConstraintKind` (a new type) from the `sub` and `sup` arguments in `Constraint`. --- .../src/diagnostics/bound_region_errors.rs | 39 ++- .../src/infer/canonical/query_response.rs | 25 +- .../src/infer/lexical_region_resolve/mod.rs | 230 +++++++++--------- .../rustc_infer/src/infer/outlives/mod.rs | 8 +- .../infer/region_constraints/leak_check.rs | 29 +-- .../src/infer/region_constraints/mod.rs | 46 ++-- .../src/solve/delegate.rs | 1 - .../src/traits/auto_trait.rs | 44 ++-- .../src/traits/query/type_op/custom.rs | 1 - .../rustc_traits/src/coroutine_witnesses.rs | 1 - src/librustdoc/clean/auto_trait.rs | 40 +-- 11 files changed, 225 insertions(+), 239 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs index 0de4bd67f0ce..6ccded01e886 100644 --- a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs @@ -3,7 +3,7 @@ use std::rc::Rc; use rustc_errors::Diag; use rustc_hir::def_id::LocalDefId; -use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; +use rustc_infer::infer::region_constraints::{Constraint, ConstraintKind, RegionConstraintData}; use rustc_infer::infer::{ InferCtxt, RegionResolutionError, RegionVariableOrigin, SubregionOrigin, TyCtxtInferExt as _, }; @@ -454,25 +454,24 @@ fn try_extract_error_from_region_constraints<'a, 'tcx>( (RePlaceholder(a_p), RePlaceholder(b_p)) => a_p.bound == b_p.bound, _ => a_region == b_region, }; - let mut check = - |constraint: &Constraint<'tcx>, cause: &SubregionOrigin<'tcx>, exact| match *constraint { - Constraint::RegSubReg(sub, sup) - if ((exact && sup == placeholder_region) - || (!exact && regions_the_same(sup, placeholder_region))) - && sup != sub => - { - Some((sub, cause.clone())) - } - Constraint::VarSubReg(vid, sup) - if (exact - && sup == placeholder_region - && !universe_of_region(vid).can_name(placeholder_universe)) - || (!exact && regions_the_same(sup, placeholder_region)) => - { - Some((ty::Region::new_var(infcx.tcx, vid), cause.clone())) - } - _ => None, - }; + let mut check = |c: &Constraint<'tcx>, cause: &SubregionOrigin<'tcx>, exact| match c.kind { + ConstraintKind::RegSubReg + if ((exact && c.sup == placeholder_region) + || (!exact && regions_the_same(c.sup, placeholder_region))) + && c.sup != c.sub => + { + Some((c.sub, cause.clone())) + } + ConstraintKind::VarSubReg + if (exact + && c.sup == placeholder_region + && !universe_of_region(c.sub.as_var()).can_name(placeholder_universe)) + || (!exact && regions_the_same(c.sup, placeholder_region)) => + { + Some((c.sub, cause.clone())) + } + _ => None, + }; let mut find_culprit = |exact_match: bool| { region_constraints diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 6be53c948c84..d92f4c2444b6 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -21,7 +21,7 @@ use crate::infer::canonical::{ Canonical, CanonicalQueryResponse, CanonicalVarValues, Certainty, OriginalQueryValues, QueryRegionConstraints, QueryResponse, }; -use crate::infer::region_constraints::{Constraint, RegionConstraintData}; +use crate::infer::region_constraints::RegionConstraintData; use crate::infer::{ DefineOpaqueTypes, InferCtxt, InferOk, InferResult, SubregionOrigin, TypeOutlivesConstraint, }; @@ -105,8 +105,6 @@ impl<'tcx> InferCtxt<'tcx> { where T: Debug + TypeFoldable>, { - let tcx = self.tcx; - // Select everything, returning errors. let errors = fulfill_cx.select_all_or_error(self); @@ -120,7 +118,6 @@ impl<'tcx> InferCtxt<'tcx> { debug!(?region_obligations); let region_constraints = self.with_region_constraints(|region_constraints| { make_query_region_constraints( - tcx, region_obligations, region_constraints, region_assumptions, @@ -587,7 +584,6 @@ impl<'tcx> InferCtxt<'tcx> { /// Given the region obligations and constraints scraped from the infcx, /// creates query region constraints. pub fn make_query_region_constraints<'tcx>( - tcx: TyCtxt<'tcx>, outlives_obligations: Vec>, region_constraints: &RegionConstraintData<'tcx>, assumptions: Vec>, @@ -600,22 +596,9 @@ pub fn make_query_region_constraints<'tcx>( let outlives: Vec<_> = constraints .iter() - .map(|(k, origin)| { - let constraint = match *k { - // Swap regions because we are going from sub (<=) to outlives - // (>=). - Constraint::VarSubVar(v1, v2) => ty::OutlivesPredicate( - ty::Region::new_var(tcx, v2).into(), - ty::Region::new_var(tcx, v1), - ), - Constraint::VarSubReg(v1, r2) => { - ty::OutlivesPredicate(r2.into(), ty::Region::new_var(tcx, v1)) - } - Constraint::RegSubVar(r1, v2) => { - ty::OutlivesPredicate(ty::Region::new_var(tcx, v2).into(), r1) - } - Constraint::RegSubReg(r1, r2) => ty::OutlivesPredicate(r2.into(), r1), - }; + .map(|(c, origin)| { + // Swap regions because we are going from sub (<=) to outlives (>=). + let constraint = ty::OutlivesPredicate(c.sup.into(), c.sub); (constraint, origin.to_constraint_category()) }) .chain(outlives_obligations.into_iter().map(|obl| { diff --git a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs index 2185886901e5..3adcfb427278 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -19,7 +19,7 @@ use tracing::{debug, instrument}; use super::outlives::test_type_match; use crate::infer::region_constraints::{ - Constraint, GenericKind, RegionConstraintData, VarInfos, VerifyBound, + Constraint, ConstraintKind, GenericKind, RegionConstraintData, VarInfos, VerifyBound, }; use crate::infer::{RegionRelations, RegionVariableOrigin, SubregionOrigin}; @@ -187,91 +187,96 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { let mut constraints = IndexVec::from_elem(Vec::new(), &var_values.values); // Tracks the changed region vids. let mut changes = Vec::new(); - for (constraint, _) in &self.data.constraints { - match *constraint { - Constraint::RegSubVar(a_region, b_vid) => { - let b_data = var_values.value_mut(b_vid); + for (c, _) in &self.data.constraints { + match c.kind { + ConstraintKind::RegSubVar => { + let sup_vid = c.sup.as_var(); + let sup_data = var_values.value_mut(sup_vid); - if self.expand_node(a_region, b_vid, b_data) { - changes.push(b_vid); + if self.expand_node(c.sub, sup_vid, sup_data) { + changes.push(sup_vid); } } - Constraint::VarSubVar(a_vid, b_vid) => match *var_values.value(a_vid) { - VarValue::ErrorValue => continue, - VarValue::Empty(a_universe) => { - let b_data = var_values.value_mut(b_vid); + ConstraintKind::VarSubVar => { + let sub_vid = c.sub.as_var(); + let sup_vid = c.sup.as_var(); + match *var_values.value(sub_vid) { + VarValue::ErrorValue => continue, + VarValue::Empty(sub_universe) => { + let sup_data = var_values.value_mut(sup_vid); - let changed = match *b_data { - VarValue::Empty(b_universe) => { - // Empty regions are ordered according to the universe - // they are associated with. - let ui = a_universe.min(b_universe); + let changed = match *sup_data { + VarValue::Empty(sup_universe) => { + // Empty regions are ordered according to the universe + // they are associated with. + let ui = sub_universe.min(sup_universe); - debug!( - "Expanding value of {:?} \ + debug!( + "Expanding value of {:?} \ from empty lifetime with universe {:?} \ to empty lifetime with universe {:?}", - b_vid, b_universe, ui - ); + sup_vid, sup_universe, ui + ); - *b_data = VarValue::Empty(ui); - true - } - VarValue::Value(cur_region) => { - match cur_region.kind() { - // If this empty region is from a universe that can name the - // placeholder universe, then the LUB is the Placeholder region - // (which is the cur_region). Otherwise, the LUB is the Static - // lifetime. - RePlaceholder(placeholder) - if !a_universe.can_name(placeholder.universe) => - { - let lub = self.tcx().lifetimes.re_static; - debug!( - "Expanding value of {:?} from {:?} to {:?}", - b_vid, cur_region, lub - ); + *sup_data = VarValue::Empty(ui); + true + } + VarValue::Value(cur_region) => { + match cur_region.kind() { + // If this empty region is from a universe that can name + // the placeholder universe, then the LUB is the + // Placeholder region (which is the cur_region). Otherwise, + // the LUB is the Static lifetime. + RePlaceholder(placeholder) + if !sub_universe.can_name(placeholder.universe) => + { + let lub = self.tcx().lifetimes.re_static; + debug!( + "Expanding value of {:?} from {:?} to {:?}", + sup_vid, cur_region, lub + ); - *b_data = VarValue::Value(lub); - true + *sup_data = VarValue::Value(lub); + true + } + + _ => false, } + } - _ => false, + VarValue::ErrorValue => false, + }; + + if changed { + changes.push(sup_vid); + } + match sup_data { + VarValue::Value(Region(Interned(ReStatic, _))) + | VarValue::ErrorValue => (), + _ => { + constraints[sub_vid].push((sub_vid, sup_vid)); + constraints[sup_vid].push((sub_vid, sup_vid)); } } - - VarValue::ErrorValue => false, - }; - - if changed { - changes.push(b_vid); } - match b_data { - VarValue::Value(Region(Interned(ReStatic, _))) - | VarValue::ErrorValue => (), - _ => { - constraints[a_vid].push((a_vid, b_vid)); - constraints[b_vid].push((a_vid, b_vid)); + VarValue::Value(sub_region) => { + let sup_data = var_values.value_mut(sup_vid); + + if self.expand_node(sub_region, sup_vid, sup_data) { + changes.push(sup_vid); + } + match sup_data { + VarValue::Value(Region(Interned(ReStatic, _))) + | VarValue::ErrorValue => (), + _ => { + constraints[sub_vid].push((sub_vid, sup_vid)); + constraints[sup_vid].push((sub_vid, sup_vid)); + } } } } - VarValue::Value(a_region) => { - let b_data = var_values.value_mut(b_vid); - - if self.expand_node(a_region, b_vid, b_data) { - changes.push(b_vid); - } - match b_data { - VarValue::Value(Region(Interned(ReStatic, _))) - | VarValue::ErrorValue => (), - _ => { - constraints[a_vid].push((a_vid, b_vid)); - constraints[b_vid].push((a_vid, b_vid)); - } - } - } - }, - Constraint::RegSubReg(..) | Constraint::VarSubReg(..) => { + } + ConstraintKind::RegSubReg | ConstraintKind::VarSubReg => { // These constraints are checked after expansion // is done, in `collect_errors`. continue; @@ -528,49 +533,48 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { var_data: &mut LexicalRegionResolutions<'tcx>, errors: &mut Vec>, ) { - for (constraint, origin) in &self.data.constraints { - debug!(?constraint, ?origin); - match *constraint { - Constraint::RegSubVar(..) | Constraint::VarSubVar(..) => { + for (c, origin) in &self.data.constraints { + debug!(?c, ?origin); + match c.kind { + ConstraintKind::RegSubVar | ConstraintKind::VarSubVar => { // Expansion will ensure that these constraints hold. Ignore. } - Constraint::RegSubReg(sub, sup) => { - if self.sub_concrete_regions(sub, sup) { + ConstraintKind::RegSubReg => { + if self.sub_concrete_regions(c.sub, c.sup) { continue; } debug!( - "region error at {:?}: \ - cannot verify that {:?} <= {:?}", - origin, sub, sup + "region error at {:?}: cannot verify that {:?} <= {:?}", + origin, c.sub, c.sup ); errors.push(RegionResolutionError::ConcreteFailure( (*origin).clone(), - sub, - sup, + c.sub, + c.sup, )); } - Constraint::VarSubReg(a_vid, b_region) => { - let a_data = var_data.value_mut(a_vid); - debug!("contraction: {:?} == {:?}, {:?}", a_vid, a_data, b_region); + ConstraintKind::VarSubReg => { + let sub_vid = c.sub.as_var(); + let sub_data = var_data.value_mut(sub_vid); + debug!("contraction: {:?} == {:?}, {:?}", sub_vid, sub_data, c.sup); - let VarValue::Value(a_region) = *a_data else { + let VarValue::Value(sub_region) = *sub_data else { continue; }; // Do not report these errors immediately: // instead, set the variable value to error and // collect them later. - if !self.sub_concrete_regions(a_region, b_region) { + if !self.sub_concrete_regions(sub_region, c.sup) { debug!( - "region error at {:?}: \ - cannot verify that {:?}={:?} <= {:?}", - origin, a_vid, a_region, b_region + "region error at {:?}: cannot verify that {:?}={:?} <= {:?}", + origin, sub_vid, sub_region, c.sup ); - *a_data = VarValue::ErrorValue; + *sub_data = VarValue::ErrorValue; } } } @@ -682,18 +686,20 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { let dummy_source = graph.add_node(()); let dummy_sink = graph.add_node(()); - for (constraint, _) in &self.data.constraints { - match *constraint { - Constraint::VarSubVar(a_id, b_id) => { - graph.add_edge(NodeIndex(a_id.index()), NodeIndex(b_id.index()), *constraint); + for (c, _) in &self.data.constraints { + match c.kind { + ConstraintKind::VarSubVar => { + let sub_vid = c.sub.as_var(); + let sup_vid = c.sup.as_var(); + graph.add_edge(NodeIndex(sub_vid.index()), NodeIndex(sup_vid.index()), *c); } - Constraint::RegSubVar(_, b_id) => { - graph.add_edge(dummy_source, NodeIndex(b_id.index()), *constraint); + ConstraintKind::RegSubVar => { + graph.add_edge(dummy_source, NodeIndex(c.sup.as_var().index()), *c); } - Constraint::VarSubReg(a_id, _) => { - graph.add_edge(NodeIndex(a_id.index()), dummy_sink, *constraint); + ConstraintKind::VarSubReg => { + graph.add_edge(NodeIndex(c.sub.as_var().index()), dummy_sink, *c); } - Constraint::RegSubReg(..) => { + ConstraintKind::RegSubReg => { // this would be an edge from `dummy_source` to // `dummy_sink`; just ignore it. } @@ -878,26 +884,30 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { let source_node_index = NodeIndex(source_vid.index()); for (_, edge) in graph.adjacent_edges(source_node_index, dir) { - match edge.data { - Constraint::VarSubVar(from_vid, to_vid) => { + let get_origin = + || this.constraints.iter().find(|(c, _)| *c == edge.data).unwrap().1.clone(); + + match edge.data.kind { + ConstraintKind::VarSubVar => { + let from_vid = edge.data.sub.as_var(); + let to_vid = edge.data.sup.as_var(); let opp_vid = if from_vid == source_vid { to_vid } else { from_vid }; if state.set.insert(opp_vid) { state.stack.push(opp_vid); } } - Constraint::RegSubVar(region, _) | Constraint::VarSubReg(_, region) => { - let origin = this - .constraints - .iter() - .find(|(c, _)| *c == edge.data) - .unwrap() - .1 - .clone(); - state.result.push(RegionAndOrigin { region, origin }); + ConstraintKind::RegSubVar => { + let origin = get_origin(); + state.result.push(RegionAndOrigin { region: edge.data.sub, origin }); } - Constraint::RegSubReg(..) => panic!( + ConstraintKind::VarSubReg => { + let origin = get_origin(); + state.result.push(RegionAndOrigin { region: edge.data.sup, origin }); + } + + ConstraintKind::RegSubReg => panic!( "cannot reach reg-sub-reg edge in region inference \ post-processing" ), diff --git a/compiler/rustc_infer/src/infer/outlives/mod.rs b/compiler/rustc_infer/src/infer/outlives/mod.rs index 19911bfbd48b..c992cda8aaed 100644 --- a/compiler/rustc_infer/src/infer/outlives/mod.rs +++ b/compiler/rustc_infer/src/infer/outlives/mod.rs @@ -10,7 +10,7 @@ use super::region_constraints::{RegionConstraintData, UndoLog}; use super::{InferCtxt, RegionResolutionError, SubregionOrigin}; use crate::infer::free_regions::RegionRelations; use crate::infer::lexical_region_resolve; -use crate::infer::region_constraints::Constraint; +use crate::infer::region_constraints::ConstraintKind; pub mod env; pub mod for_liveness; @@ -70,10 +70,10 @@ impl<'tcx> InferCtxt<'tcx> { // Filter out any region-region outlives assumptions that are implied by // coroutine well-formedness. if self.tcx.sess.opts.unstable_opts.higher_ranked_assumptions { - storage.data.constraints.retain(|(constraint, _)| match *constraint { - Constraint::RegSubReg(r1, r2) => !outlives_env + storage.data.constraints.retain(|(c, _)| match c.kind { + ConstraintKind::RegSubReg => !outlives_env .higher_ranked_assumptions() - .contains(&ty::OutlivesPredicate(r2.into(), r1)), + .contains(&ty::OutlivesPredicate(c.sup.into(), c.sub)), _ => true, }); } diff --git a/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs b/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs index e332b6d0447a..4d76bc2e17a1 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs @@ -83,7 +83,7 @@ impl<'tcx> RegionConstraintCollector<'_, 'tcx> { return Ok(()); } - let mini_graph = MiniGraph::new(tcx, &self, only_consider_snapshot); + let mini_graph = MiniGraph::new(&self, only_consider_snapshot); let mut leak_check = LeakCheck::new(tcx, outer_universe, max_universe, mini_graph, self); leak_check.assign_placeholder_values()?; @@ -359,7 +359,6 @@ struct MiniGraph<'tcx> { impl<'tcx> MiniGraph<'tcx> { fn new( - tcx: TyCtxt<'tcx>, region_constraints: &RegionConstraintCollector<'_, 'tcx>, only_consider_snapshot: Option<&CombinedSnapshot<'tcx>>, ) -> Self { @@ -368,7 +367,6 @@ impl<'tcx> MiniGraph<'tcx> { // Note that if `R2: R1`, we get a callback `r1, r2`, so `target` is first parameter. Self::iterate_region_constraints( - tcx, region_constraints, only_consider_snapshot, |target, source| { @@ -384,33 +382,18 @@ impl<'tcx> MiniGraph<'tcx> { /// Invokes `each_edge(R1, R2)` for each edge where `R2: R1` fn iterate_region_constraints( - tcx: TyCtxt<'tcx>, region_constraints: &RegionConstraintCollector<'_, 'tcx>, only_consider_snapshot: Option<&CombinedSnapshot<'tcx>>, mut each_edge: impl FnMut(ty::Region<'tcx>, ty::Region<'tcx>), ) { - let mut each_constraint = |constraint| match constraint { - &Constraint::VarSubVar(a, b) => { - each_edge(ty::Region::new_var(tcx, a), ty::Region::new_var(tcx, b)); - } - &Constraint::RegSubVar(a, b) => { - each_edge(a, ty::Region::new_var(tcx, b)); - } - &Constraint::VarSubReg(a, b) => { - each_edge(ty::Region::new_var(tcx, a), b); - } - &Constraint::RegSubReg(a, b) => { - each_edge(a, b); - } - }; - if let Some(snapshot) = only_consider_snapshot { for undo_entry in region_constraints.undo_log.region_constraints_in_snapshot(&snapshot.undo_snapshot) { match undo_entry { &AddConstraint(i) => { - each_constraint(®ion_constraints.data().constraints[i].0); + let c = region_constraints.data().constraints[i].0; + each_edge(c.sub, c.sup); } &AddVerify(i) => span_bug!( region_constraints.data().verifys[i].origin.span(), @@ -420,11 +403,7 @@ impl<'tcx> MiniGraph<'tcx> { } } } else { - region_constraints - .data() - .constraints - .iter() - .for_each(|(constraint, _)| each_constraint(constraint)); + region_constraints.data().constraints.iter().for_each(|(c, _)| each_edge(c.sub, c.sup)) } } diff --git a/compiler/rustc_infer/src/infer/region_constraints/mod.rs b/compiler/rustc_infer/src/infer/region_constraints/mod.rs index 4747c203c807..85f5e55a8e1e 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/mod.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/mod.rs @@ -80,31 +80,37 @@ pub struct RegionConstraintData<'tcx> { /// Represents a constraint that influences the inference process. #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] -pub enum Constraint<'tcx> { +pub enum ConstraintKind { /// A region variable is a subregion of another. - VarSubVar(RegionVid, RegionVid), + VarSubVar, /// A concrete region is a subregion of region variable. - RegSubVar(Region<'tcx>, RegionVid), + RegSubVar, /// A region variable is a subregion of a concrete region. This does not /// directly affect inference, but instead is checked after /// inference is complete. - VarSubReg(RegionVid, Region<'tcx>), + VarSubReg, /// A constraint where neither side is a variable. This does not /// directly affect inference, but instead is checked after /// inference is complete. - RegSubReg(Region<'tcx>, Region<'tcx>), + RegSubReg, +} + +/// Represents a constraint that influences the inference process. +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +pub struct Constraint<'tcx> { + pub kind: ConstraintKind, + // If `kind` is `VarSubVar` or `VarSubReg`, this must be a `ReVar`. + pub sub: Region<'tcx>, + // If `kind` is `VarSubVar` or `RegSubVar`, this must be a `ReVar`. + pub sup: Region<'tcx>, } impl Constraint<'_> { pub fn involves_placeholders(&self) -> bool { - match self { - Constraint::VarSubVar(_, _) => false, - Constraint::VarSubReg(_, r) | Constraint::RegSubVar(r, _) => r.is_placeholder(), - Constraint::RegSubReg(r, s) => r.is_placeholder() || s.is_placeholder(), - } + self.sub.is_placeholder() || self.sup.is_placeholder() } } @@ -472,18 +478,22 @@ impl<'tcx> RegionConstraintCollector<'_, 'tcx> { } (ReVar(sub_id), ReVar(sup_id)) => { if sub_id != sup_id { - self.add_constraint(Constraint::VarSubVar(sub_id, sup_id), origin); + self.add_constraint( + Constraint { kind: ConstraintKind::VarSubVar, sub, sup }, + origin, + ); } } - (_, ReVar(sup_id)) => { - self.add_constraint(Constraint::RegSubVar(sub, sup_id), origin); - } - (ReVar(sub_id), _) => { - self.add_constraint(Constraint::VarSubReg(sub_id, sup), origin); - } + (_, ReVar(_)) => self + .add_constraint(Constraint { kind: ConstraintKind::RegSubVar, sub, sup }, origin), + (ReVar(_), _) => self + .add_constraint(Constraint { kind: ConstraintKind::VarSubReg, sub, sup }, origin), _ => { if sub != sup { - self.add_constraint(Constraint::RegSubReg(sub, sup), origin); + self.add_constraint( + Constraint { kind: ConstraintKind::RegSubReg, sub, sup }, + origin, + ) } } } diff --git a/compiler/rustc_trait_selection/src/solve/delegate.rs b/compiler/rustc_trait_selection/src/solve/delegate.rs index 7426504e1393..96c6e5893734 100644 --- a/compiler/rustc_trait_selection/src/solve/delegate.rs +++ b/compiler/rustc_trait_selection/src/solve/delegate.rs @@ -205,7 +205,6 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate< let region_assumptions = self.0.inner.borrow().region_assumptions().to_owned(); let region_constraints = self.0.with_region_constraints(|region_constraints| { make_query_region_constraints( - self.tcx, region_obligations, region_constraints, region_assumptions, diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 759db1d18c01..c63cc0e17ab9 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -13,7 +13,7 @@ use tracing::debug; use super::*; use crate::errors::UnableToConstructConstantValue; -use crate::infer::region_constraints::{Constraint, RegionConstraintData}; +use crate::infer::region_constraints::{ConstraintKind, RegionConstraintData}; use crate::regions::OutlivesEnvironmentBuildExt; use crate::traits::project::ProjectAndUnifyResult; @@ -452,37 +452,41 @@ impl<'tcx> AutoTraitFinder<'tcx> { let mut vid_map = FxIndexMap::, RegionDeps<'cx>>::default(); let mut finished_map = FxIndexMap::default(); - for (constraint, _) in ®ions.constraints { - match constraint { - &Constraint::VarSubVar(r1, r2) => { + for (c, _) in ®ions.constraints { + match c.kind { + ConstraintKind::VarSubVar => { + let sub_vid = c.sub.as_var(); + let sup_vid = c.sup.as_var(); { - let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default(); - deps1.larger.insert(RegionTarget::RegionVid(r2)); + let deps1 = vid_map.entry(RegionTarget::RegionVid(sub_vid)).or_default(); + deps1.larger.insert(RegionTarget::RegionVid(sup_vid)); } - let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default(); - deps2.smaller.insert(RegionTarget::RegionVid(r1)); + let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default(); + deps2.smaller.insert(RegionTarget::RegionVid(sub_vid)); } - &Constraint::RegSubVar(region, vid) => { + ConstraintKind::RegSubVar => { + let sup_vid = c.sup.as_var(); { - let deps1 = vid_map.entry(RegionTarget::Region(region)).or_default(); - deps1.larger.insert(RegionTarget::RegionVid(vid)); + let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default(); + deps1.larger.insert(RegionTarget::RegionVid(sup_vid)); } - let deps2 = vid_map.entry(RegionTarget::RegionVid(vid)).or_default(); - deps2.smaller.insert(RegionTarget::Region(region)); + let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default(); + deps2.smaller.insert(RegionTarget::Region(c.sub)); } - &Constraint::VarSubReg(vid, region) => { - finished_map.insert(vid, region); + ConstraintKind::VarSubReg => { + let sub_vid = c.sub.as_var(); + finished_map.insert(sub_vid, c.sup); } - &Constraint::RegSubReg(r1, r2) => { + ConstraintKind::RegSubReg => { { - let deps1 = vid_map.entry(RegionTarget::Region(r1)).or_default(); - deps1.larger.insert(RegionTarget::Region(r2)); + let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default(); + deps1.larger.insert(RegionTarget::Region(c.sup)); } - let deps2 = vid_map.entry(RegionTarget::Region(r2)).or_default(); - deps2.smaller.insert(RegionTarget::Region(r1)); + let deps2 = vid_map.entry(RegionTarget::Region(c.sup)).or_default(); + deps2.smaller.insert(RegionTarget::Region(c.sub)); } } } diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs index f027ba1c5cbf..0ca2d2162288 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs @@ -108,7 +108,6 @@ where let region_assumptions = infcx.take_registered_region_assumptions(); let region_constraint_data = infcx.take_and_reset_region_constraints(); let region_constraints = query_response::make_query_region_constraints( - infcx.tcx, region_obligations, ®ion_constraint_data, region_assumptions, diff --git a/compiler/rustc_traits/src/coroutine_witnesses.rs b/compiler/rustc_traits/src/coroutine_witnesses.rs index 87d17f3e131a..8a2a0832ddb7 100644 --- a/compiler/rustc_traits/src/coroutine_witnesses.rs +++ b/compiler/rustc_traits/src/coroutine_witnesses.rs @@ -70,7 +70,6 @@ fn compute_assumptions<'tcx>( let region_constraints = infcx.take_and_reset_region_constraints(); let outlives = make_query_region_constraints( - tcx, region_obligations, ®ion_constraints, region_assumptions, diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index a91ea55bcae6..e6ac0270f783 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -1,6 +1,6 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet, IndexEntry}; use rustc_hir as hir; -use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; +use rustc_infer::infer::region_constraints::{ConstraintKind, RegionConstraintData}; use rustc_middle::bug; use rustc_middle::ty::{self, Region, Ty, fold_regions}; use rustc_span::def_id::DefId; @@ -233,31 +233,35 @@ fn clean_region_outlives_constraints<'tcx>( // Each `RegionTarget` (a `RegionVid` or a `Region`) maps to its smaller and larger regions. // Note that "larger" regions correspond to sub regions in the surface language. // E.g., in `'a: 'b`, `'a` is the larger region. - for (constraint, _) in ®ions.constraints { - match *constraint { - Constraint::VarSubVar(vid1, vid2) => { - let deps1 = map.entry(RegionTarget::RegionVid(vid1)).or_default(); - deps1.larger.insert(RegionTarget::RegionVid(vid2)); + for (c, _) in ®ions.constraints { + match c.kind { + ConstraintKind::VarSubVar => { + let sub_vid = c.sub.as_var(); + let sup_vid = c.sup.as_var(); + let deps1 = map.entry(RegionTarget::RegionVid(sub_vid)).or_default(); + deps1.larger.insert(RegionTarget::RegionVid(sup_vid)); - let deps2 = map.entry(RegionTarget::RegionVid(vid2)).or_default(); - deps2.smaller.insert(RegionTarget::RegionVid(vid1)); + let deps2 = map.entry(RegionTarget::RegionVid(sup_vid)).or_default(); + deps2.smaller.insert(RegionTarget::RegionVid(sub_vid)); } - Constraint::RegSubVar(region, vid) => { - let deps = map.entry(RegionTarget::RegionVid(vid)).or_default(); - deps.smaller.insert(RegionTarget::Region(region)); + ConstraintKind::RegSubVar => { + let sup_vid = c.sup.as_var(); + let deps = map.entry(RegionTarget::RegionVid(sup_vid)).or_default(); + deps.smaller.insert(RegionTarget::Region(c.sub)); } - Constraint::VarSubReg(vid, region) => { - let deps = map.entry(RegionTarget::RegionVid(vid)).or_default(); - deps.larger.insert(RegionTarget::Region(region)); + ConstraintKind::VarSubReg => { + let sub_vid = c.sub.as_var(); + let deps = map.entry(RegionTarget::RegionVid(sub_vid)).or_default(); + deps.larger.insert(RegionTarget::Region(c.sup)); } - Constraint::RegSubReg(r1, r2) => { + ConstraintKind::RegSubReg => { // The constraint is already in the form that we want, so we're done with it // The desired order is [larger, smaller], so flip them. - if early_bound_region_name(r1) != early_bound_region_name(r2) { + if early_bound_region_name(c.sub) != early_bound_region_name(c.sup) { outlives_predicates - .entry(early_bound_region_name(r2).expect("no region_name found")) + .entry(early_bound_region_name(c.sup).expect("no region_name found")) .or_default() - .push(r1); + .push(c.sub); } } } From e1d3ad89c7a2ad4f5d944a7fee1298ffe8c99645 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 384/809] remove rustc_attr_data_structures --- Cargo.lock | 40 +---------- compiler/rustc_ast_lowering/Cargo.toml | 1 - compiler/rustc_ast_lowering/src/expr.rs | 4 +- compiler/rustc_ast_lowering/src/item.rs | 4 +- .../rustc_attr_data_structures/Cargo.toml | 16 ----- .../rustc_attr_data_structures/src/lints.rs | 16 ----- compiler/rustc_attr_parsing/Cargo.toml | 1 - .../src/attributes/allow_unstable.rs | 2 +- .../rustc_attr_parsing/src/attributes/cfg.rs | 3 +- .../src/attributes/cfg_old.rs | 2 +- .../src/attributes/codegen_attrs.rs | 2 +- .../src/attributes/confusables.rs | 2 +- .../src/attributes/deprecation.rs | 2 +- .../src/attributes/dummy.rs | 2 +- .../src/attributes/inline.rs | 4 +- .../src/attributes/link_attrs.rs | 4 +- .../src/attributes/lint_helpers.rs | 2 +- .../src/attributes/loop_match.rs | 2 +- .../src/attributes/macro_attrs.rs | 2 +- .../rustc_attr_parsing/src/attributes/mod.rs | 2 +- .../src/attributes/must_use.rs | 2 +- .../src/attributes/no_implicit_prelude.rs | 2 +- .../src/attributes/non_exhaustive.rs | 2 +- .../rustc_attr_parsing/src/attributes/path.rs | 2 +- .../src/attributes/proc_macro_attrs.rs | 2 +- .../rustc_attr_parsing/src/attributes/repr.rs | 2 +- .../src/attributes/rustc_internal.rs | 2 +- .../src/attributes/semantics.rs | 2 +- .../src/attributes/stability.rs | 9 +-- .../src/attributes/test_attrs.rs | 4 +- .../src/attributes/traits.rs | 2 +- .../src/attributes/transparency.rs | 2 +- .../rustc_attr_parsing/src/attributes/util.rs | 2 +- compiler/rustc_attr_parsing/src/context.rs | 4 +- compiler/rustc_attr_parsing/src/lib.rs | 10 +-- compiler/rustc_attr_parsing/src/lints.rs | 2 +- compiler/rustc_builtin_macros/Cargo.toml | 1 - .../src/deriving/generic/mod.rs | 2 +- .../src/proc_macro_harness.rs | 2 +- compiler/rustc_codegen_gcc/src/attributes.rs | 4 +- compiler/rustc_codegen_gcc/src/callee.rs | 2 +- compiler/rustc_codegen_gcc/src/lib.rs | 1 - compiler/rustc_codegen_llvm/Cargo.toml | 3 +- compiler/rustc_codegen_llvm/src/attributes.rs | 2 +- compiler/rustc_codegen_llvm/src/callee.rs | 2 +- .../rustc_codegen_llvm/src/debuginfo/gdb.rs | 3 +- compiler/rustc_codegen_ssa/Cargo.toml | 1 - .../src/back/symbol_export.rs | 2 +- compiler/rustc_codegen_ssa/src/base.rs | 2 +- .../rustc_codegen_ssa/src/codegen_attrs.rs | 6 +- .../rustc_codegen_ssa/src/mir/naked_asm.rs | 2 +- .../rustc_codegen_ssa/src/target_features.rs | 2 +- compiler/rustc_const_eval/Cargo.toml | 1 - .../src/check_consts/check.rs | 15 ++--- .../rustc_const_eval/src/check_consts/mod.rs | 5 +- compiler/rustc_errors/Cargo.toml | 3 +- compiler/rustc_errors/src/diagnostic_impls.rs | 2 +- compiler/rustc_expand/Cargo.toml | 1 - compiler/rustc_expand/src/base.rs | 3 +- compiler/rustc_expand/src/mbe/macro_rules.rs | 3 +- compiler/rustc_feature/Cargo.toml | 2 +- compiler/rustc_feature/src/builtin_attrs.rs | 4 +- compiler/rustc_hir/Cargo.toml | 2 +- .../src/attrs/data_structures.rs} | 9 +-- .../src/attrs}/encode_cross_crate.rs | 2 +- compiler/rustc_hir/src/attrs/mod.rs | 54 +++++++++++++++ .../src/attrs/pretty_printing.rs} | 67 ------------------- compiler/rustc_hir/src/hir.rs | 2 +- compiler/rustc_hir/src/lib.rs | 5 ++ compiler/rustc_hir/src/lints.rs | 26 +++++-- .../src/stability.rs | 3 +- compiler/rustc_hir/src/stable_hash_impls.rs | 6 +- .../src/version.rs | 2 +- compiler/rustc_hir_analysis/Cargo.toml | 1 - .../rustc_hir_analysis/src/check/check.rs | 14 ++-- .../rustc_hir_analysis/src/check/entry.rs | 4 +- .../src/coherence/inherent_impls.rs | 3 +- compiler/rustc_hir_analysis/src/collect.rs | 4 +- .../src/collect/predicates_of.rs | 3 +- compiler/rustc_hir_pretty/Cargo.toml | 1 - compiler/rustc_hir_pretty/src/lib.rs | 2 +- compiler/rustc_hir_typeck/Cargo.toml | 1 - compiler/rustc_hir_typeck/src/coercion.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 4 +- compiler/rustc_hir_typeck/src/lib.rs | 4 +- compiler/rustc_hir_typeck/src/loops.rs | 4 +- .../rustc_hir_typeck/src/method/suggest.rs | 4 +- .../rustc_hir_typeck/src/naked_functions.rs | 4 +- compiler/rustc_lint/Cargo.toml | 1 - compiler/rustc_lint/src/builtin.rs | 4 +- compiler/rustc_lint/src/dangling.rs | 4 +- .../src/default_could_be_derived.rs | 3 +- compiler/rustc_lint/src/foreign_modules.rs | 3 +- compiler/rustc_lint/src/nonstandard_style.rs | 4 +- compiler/rustc_lint/src/pass_by_value.rs | 4 +- compiler/rustc_lint/src/types/literal.rs | 4 +- compiler/rustc_lint/src/unused.rs | 4 +- compiler/rustc_macros/src/lib.rs | 2 +- compiler/rustc_metadata/Cargo.toml | 1 - compiler/rustc_metadata/src/native_libs.rs | 3 +- .../src/rmeta/decoder/cstore_impl.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 3 +- compiler/rustc_metadata/src/rmeta/mod.rs | 14 ++-- .../rustc_metadata/src/rmeta/parameterized.rs | 10 +-- compiler/rustc_middle/Cargo.toml | 1 - compiler/rustc_middle/src/arena.rs | 2 +- compiler/rustc_middle/src/hir/map.rs | 2 +- .../src/middle/codegen_fn_attrs.rs | 2 +- compiler/rustc_middle/src/middle/stability.rs | 12 ++-- compiler/rustc_middle/src/mir/mono.rs | 2 +- compiler/rustc_middle/src/query/erase.rs | 14 ++-- compiler/rustc_middle/src/query/mod.rs | 10 +-- compiler/rustc_middle/src/ty/adt.rs | 4 +- compiler/rustc_middle/src/ty/assoc.rs | 3 +- compiler/rustc_middle/src/ty/context.rs | 4 +- compiler/rustc_middle/src/ty/instance.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 10 +-- compiler/rustc_mir_build/Cargo.toml | 1 - compiler/rustc_mir_build/src/thir/cx/expr.rs | 3 +- .../src/thir/pattern/const_to_pat.rs | 3 +- compiler/rustc_mir_transform/Cargo.toml | 1 - .../rustc_mir_transform/src/check_inline.rs | 2 +- .../rustc_mir_transform/src/coverage/query.rs | 3 +- .../src/cross_crate_inline.rs | 2 +- compiler/rustc_mir_transform/src/inline.rs | 2 +- compiler/rustc_mir_transform/src/validate.rs | 2 +- compiler/rustc_monomorphize/Cargo.toml | 1 - compiler/rustc_monomorphize/src/collector.rs | 2 +- .../rustc_monomorphize/src/partitioning.rs | 2 +- compiler/rustc_passes/Cargo.toml | 1 - compiler/rustc_passes/src/check_attr.rs | 10 ++- compiler/rustc_passes/src/check_export.rs | 3 +- compiler/rustc_passes/src/lib_features.rs | 4 +- compiler/rustc_passes/src/liveness.rs | 4 +- compiler/rustc_passes/src/stability.rs | 33 ++++----- compiler/rustc_privacy/Cargo.toml | 1 - compiler/rustc_privacy/src/lib.rs | 7 +- compiler/rustc_query_system/Cargo.toml | 1 - compiler/rustc_query_system/src/ich/hcx.rs | 1 - compiler/rustc_resolve/Cargo.toml | 1 - .../rustc_resolve/src/build_reduced_graph.rs | 2 +- compiler/rustc_resolve/src/diagnostics.rs | 10 +-- compiler/rustc_resolve/src/lib.rs | 2 +- compiler/rustc_resolve/src/macros.rs | 3 +- compiler/rustc_trait_selection/Cargo.toml | 1 - .../error_reporting/infer/note_and_explain.rs | 3 +- src/librustdoc/clean/mod.rs | 4 +- src/librustdoc/clean/types.rs | 10 ++- src/librustdoc/formats/cache.rs | 2 +- src/librustdoc/html/format.rs | 2 +- src/librustdoc/html/render/mod.rs | 6 +- src/librustdoc/json/conversions.rs | 2 +- src/librustdoc/lib.rs | 1 - src/librustdoc/passes/propagate_stability.rs | 2 +- .../clippy/clippy_lints/src/approx_const.rs | 2 +- .../src/arbitrary_source_item_ordering.rs | 2 +- .../clippy_lints/src/attrs/inline_always.rs | 3 +- .../clippy_lints/src/attrs/repr_attributes.rs | 3 +- src/tools/clippy/clippy_lints/src/booleans.rs | 2 +- .../src/default_union_representation.rs | 3 +- .../src/doc/suspicious_doc_comments.rs | 2 +- .../src/doc/too_long_first_doc_paragraph.rs | 2 +- .../clippy/clippy_lints/src/eta_reduction.rs | 3 +- .../clippy_lints/src/exhaustive_items.rs | 3 +- .../clippy/clippy_lints/src/format_args.rs | 3 +- .../clippy_lints/src/functions/must_use.rs | 3 +- .../clippy_lints/src/incompatible_msrv.rs | 2 +- .../src/inline_fn_without_body.rs | 3 +- src/tools/clippy/clippy_lints/src/lib.rs | 1 - .../clippy/clippy_lints/src/macro_use.rs | 3 +- .../clippy_lints/src/manual_non_exhaustive.rs | 3 +- .../clippy/clippy_lints/src/missing_inline.rs | 3 +- .../src/no_mangle_with_rust_abi.rs | 2 +- .../clippy_lints/src/pass_by_ref_or_value.rs | 3 +- .../src/return_self_not_must_use.rs | 3 +- .../clippy_lints/src/std_instead_of_core.rs | 2 +- .../derive_deserialize_allowing_unknown.rs | 3 +- .../clippy/clippy_lints_internal/src/lib.rs | 1 - src/tools/clippy/clippy_utils/src/attrs.rs | 3 +- src/tools/clippy/clippy_utils/src/lib.rs | 4 +- src/tools/clippy/clippy_utils/src/msrvs.rs | 2 +- .../clippy_utils/src/qualify_min_const_fn.rs | 4 +- src/tools/clippy/clippy_utils/src/ty/mod.rs | 3 +- src/tools/miri/src/lib.rs | 1 - src/tools/miri/src/machine.rs | 2 +- triagebot.toml | 6 +- 186 files changed, 380 insertions(+), 452 deletions(-) delete mode 100644 compiler/rustc_attr_data_structures/Cargo.toml delete mode 100644 compiler/rustc_attr_data_structures/src/lints.rs rename compiler/{rustc_attr_data_structures/src/attributes.rs => rustc_hir/src/attrs/data_structures.rs} (98%) rename compiler/{rustc_attr_data_structures/src => rustc_hir/src/attrs}/encode_cross_crate.rs (98%) create mode 100644 compiler/rustc_hir/src/attrs/mod.rs rename compiler/{rustc_attr_data_structures/src/lib.rs => rustc_hir/src/attrs/pretty_printing.rs} (68%) rename compiler/{rustc_attr_data_structures => rustc_hir}/src/stability.rs (99%) rename compiler/{rustc_attr_data_structures => rustc_hir}/src/version.rs (97%) diff --git a/Cargo.lock b/Cargo.lock index c1076f05ef12..ca76f733e17f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3426,7 +3426,6 @@ dependencies = [ "rustc_abi", "rustc_ast", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -3476,20 +3475,6 @@ dependencies = [ "thin-vec", ] -[[package]] -name = "rustc_attr_data_structures" -version = "0.0.0" -dependencies = [ - "rustc_abi", - "rustc_ast", - "rustc_ast_pretty", - "rustc_data_structures", - "rustc_macros", - "rustc_serialize", - "rustc_span", - "thin-vec", -] - [[package]] name = "rustc_attr_parsing" version = "0.0.0" @@ -3497,7 +3482,6 @@ dependencies = [ "rustc_abi", "rustc_ast", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_errors", "rustc_feature", "rustc_fluent_macro", @@ -3553,7 +3537,6 @@ version = "0.0.0" dependencies = [ "rustc_ast", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -3589,7 +3572,6 @@ dependencies = [ "rustc-demangle", "rustc_abi", "rustc_ast", - "rustc_attr_data_structures", "rustc_codegen_ssa", "rustc_data_structures", "rustc_errors", @@ -3630,7 +3612,6 @@ dependencies = [ "rustc_abi", "rustc_arena", "rustc_ast", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -3668,7 +3649,6 @@ dependencies = [ "rustc_abi", "rustc_apfloat", "rustc_ast", - "rustc_attr_data_structures", "rustc_data_structures", "rustc_errors", "rustc_fluent_macro", @@ -3814,7 +3794,6 @@ dependencies = [ "rustc_abi", "rustc_ast", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_data_structures", "rustc_error_codes", "rustc_error_messages", @@ -3844,7 +3823,6 @@ dependencies = [ "rustc_ast", "rustc_ast_passes", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -3868,8 +3846,8 @@ dependencies = [ name = "rustc_feature" version = "0.0.0" dependencies = [ - "rustc_attr_data_structures", "rustc_data_structures", + "rustc_hir", "rustc_span", "serde", "serde_json", @@ -3914,7 +3892,7 @@ dependencies = [ "rustc_abi", "rustc_arena", "rustc_ast", - "rustc_attr_data_structures", + "rustc_ast_pretty", "rustc_data_structures", "rustc_hashes", "rustc_index", @@ -3935,7 +3913,6 @@ dependencies = [ "rustc_abi", "rustc_arena", "rustc_ast", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -3962,7 +3939,6 @@ dependencies = [ "rustc_abi", "rustc_ast", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_hir", "rustc_span", ] @@ -3974,7 +3950,6 @@ dependencies = [ "itertools", "rustc_abi", "rustc_ast", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -4120,7 +4095,6 @@ dependencies = [ "rustc_abi", "rustc_ast", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -4194,7 +4168,6 @@ dependencies = [ "odht", "rustc_abi", "rustc_ast", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -4230,7 +4203,6 @@ dependencies = [ "rustc_arena", "rustc_ast", "rustc_ast_ir", - "rustc_attr_data_structures", "rustc_data_structures", "rustc_error_messages", "rustc_errors", @@ -4264,7 +4236,6 @@ dependencies = [ "rustc_apfloat", "rustc_arena", "rustc_ast", - "rustc_attr_data_structures", "rustc_data_structures", "rustc_errors", "rustc_fluent_macro", @@ -4311,7 +4282,6 @@ dependencies = [ "rustc_abi", "rustc_arena", "rustc_ast", - "rustc_attr_data_structures", "rustc_const_eval", "rustc_data_structures", "rustc_errors", @@ -4337,7 +4307,6 @@ version = "0.0.0" dependencies = [ "rustc_abi", "rustc_ast", - "rustc_attr_data_structures", "rustc_data_structures", "rustc_errors", "rustc_fluent_macro", @@ -4408,7 +4377,6 @@ dependencies = [ "rustc_ast", "rustc_ast_lowering", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -4455,7 +4423,6 @@ name = "rustc_privacy" version = "0.0.0" dependencies = [ "rustc_ast", - "rustc_attr_data_structures", "rustc_data_structures", "rustc_errors", "rustc_fluent_macro", @@ -4530,7 +4497,6 @@ dependencies = [ "parking_lot", "rustc_abi", "rustc_ast", - "rustc_attr_data_structures", "rustc_data_structures", "rustc_errors", "rustc_feature", @@ -4557,7 +4523,6 @@ dependencies = [ "rustc_arena", "rustc_ast", "rustc_ast_pretty", - "rustc_attr_data_structures", "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", @@ -4720,7 +4685,6 @@ dependencies = [ "itertools", "rustc_abi", "rustc_ast", - "rustc_attr_data_structures", "rustc_data_structures", "rustc_errors", "rustc_fluent_macro", diff --git a/compiler/rustc_ast_lowering/Cargo.toml b/compiler/rustc_ast_lowering/Cargo.toml index dc571f5c3671..6ac258155fe9 100644 --- a/compiler/rustc_ast_lowering/Cargo.toml +++ b/compiler/rustc_ast_lowering/Cargo.toml @@ -11,7 +11,6 @@ doctest = false rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 657792c93971..1245d4897547 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -4,11 +4,11 @@ use std::sync::Arc; use rustc_ast::ptr::P as AstP; use rustc_ast::*; use rustc_ast_pretty::pprust::expr_to_string; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; -use rustc_hir::HirId; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; +use rustc_hir::{HirId, find_attr}; use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; use rustc_session::errors::report_lit_error; diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 1899dcda3619..9f54af575280 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -2,11 +2,11 @@ use rustc_abi::ExternAbi; use rustc_ast::ptr::P; use rustc_ast::visit::AssocCtxt; use rustc_ast::*; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err}; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, PerNS, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; -use rustc_hir::{self as hir, HirId, LifetimeSource, PredicateOrigin}; +use rustc_hir::{self as hir, HirId, LifetimeSource, PredicateOrigin, find_attr}; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::span_bug; use rustc_middle::ty::{ResolverAstLowering, TyCtxt}; diff --git a/compiler/rustc_attr_data_structures/Cargo.toml b/compiler/rustc_attr_data_structures/Cargo.toml deleted file mode 100644 index b18923c337ff..000000000000 --- a/compiler/rustc_attr_data_structures/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "rustc_attr_data_structures" -version = "0.0.0" -edition = "2024" - -[dependencies] -# tidy-alphabetical-start -rustc_abi = {path = "../rustc_abi"} -rustc_ast = {path = "../rustc_ast"} -rustc_ast_pretty = {path = "../rustc_ast_pretty"} -rustc_data_structures = {path = "../rustc_data_structures"} -rustc_macros = {path = "../rustc_macros"} -rustc_serialize = {path = "../rustc_serialize"} -rustc_span = {path = "../rustc_span"} -thin-vec = "0.2.12" -# tidy-alphabetical-end diff --git a/compiler/rustc_attr_data_structures/src/lints.rs b/compiler/rustc_attr_data_structures/src/lints.rs deleted file mode 100644 index 60ca4d43ce9b..000000000000 --- a/compiler/rustc_attr_data_structures/src/lints.rs +++ /dev/null @@ -1,16 +0,0 @@ -use rustc_macros::HashStable_Generic; -use rustc_span::Span; - -#[derive(Clone, Debug, HashStable_Generic)] -pub struct AttributeLint { - pub id: Id, - pub span: Span, - pub kind: AttributeLintKind, -} - -#[derive(Clone, Debug, HashStable_Generic)] -pub enum AttributeLintKind { - UnusedDuplicate { this: Span, other: Span, warning: bool }, - IllFormedAttributeInput { suggestions: Vec }, - EmptyAttribute { first_span: Span }, -} diff --git a/compiler/rustc_attr_parsing/Cargo.toml b/compiler/rustc_attr_parsing/Cargo.toml index 32029137268b..cec9d62e6560 100644 --- a/compiler/rustc_attr_parsing/Cargo.toml +++ b/compiler/rustc_attr_parsing/Cargo.toml @@ -8,7 +8,6 @@ edition = "2024" rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } diff --git a/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs b/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs index a6bd2306ec50..95104b896acc 100644 --- a/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs +++ b/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs @@ -1,7 +1,7 @@ use std::iter; -use rustc_attr_data_structures::AttributeKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol, sym}; use super::{CombineAttributeParser, ConvertFn}; diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index 6373cf6e08ad..947be28bc956 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -1,6 +1,7 @@ use rustc_ast::{LitKind, NodeId}; -use rustc_attr_data_structures::{CfgEntry, RustcVersion}; use rustc_feature::{AttributeTemplate, Features, template}; +use rustc_hir::RustcVersion; +use rustc_hir::attrs::CfgEntry; use rustc_session::Session; use rustc_session::config::ExpectedValues; use rustc_session::lint::BuiltinLintDiag; diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg_old.rs b/compiler/rustc_attr_parsing/src/attributes/cfg_old.rs index c5025a8b6eac..3257d898eccb 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg_old.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg_old.rs @@ -1,7 +1,7 @@ use rustc_ast::{LitKind, MetaItem, MetaItemInner, MetaItemKind, MetaItemLit, NodeId}; use rustc_ast_pretty::pprust; -use rustc_attr_data_structures::RustcVersion; use rustc_feature::{Features, GatedCfg, find_gated_cfg}; +use rustc_hir::RustcVersion; use rustc_session::Session; use rustc_session::config::ExpectedValues; use rustc_session::lint::builtin::UNEXPECTED_CFGS; diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index afa9abed0bb5..7c8ef90ed7f1 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -1,5 +1,5 @@ -use rustc_attr_data_structures::{AttributeKind, CoverageAttrKind, OptimizeAttr, UsedBy}; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::{AttributeKind, CoverageAttrKind, OptimizeAttr, UsedBy}; use rustc_session::parse::feature_err; use rustc_span::{Span, Symbol, sym}; diff --git a/compiler/rustc_attr_parsing/src/attributes/confusables.rs b/compiler/rustc_attr_parsing/src/attributes/confusables.rs index c911908dfb38..7d24c89a6e8d 100644 --- a/compiler/rustc_attr_parsing/src/attributes/confusables.rs +++ b/compiler/rustc_attr_parsing/src/attributes/confusables.rs @@ -1,5 +1,5 @@ -use rustc_attr_data_structures::AttributeKind; use rustc_feature::template; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol, sym}; use thin_vec::ThinVec; diff --git a/compiler/rustc_attr_parsing/src/attributes/deprecation.rs b/compiler/rustc_attr_parsing/src/attributes/deprecation.rs index 08cf1ab5d190..38ec4bd5645c 100644 --- a/compiler/rustc_attr_parsing/src/attributes/deprecation.rs +++ b/compiler/rustc_attr_parsing/src/attributes/deprecation.rs @@ -1,5 +1,5 @@ -use rustc_attr_data_structures::{AttributeKind, DeprecatedSince, Deprecation}; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::{AttributeKind, DeprecatedSince, Deprecation}; use rustc_span::{Span, Symbol, sym}; use super::util::parse_version; diff --git a/compiler/rustc_attr_parsing/src/attributes/dummy.rs b/compiler/rustc_attr_parsing/src/attributes/dummy.rs index e5e1c3bb6b6a..bbcd9ab530c5 100644 --- a/compiler/rustc_attr_parsing/src/attributes/dummy.rs +++ b/compiler/rustc_attr_parsing/src/attributes/dummy.rs @@ -1,5 +1,5 @@ -use rustc_attr_data_structures::AttributeKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Symbol, sym}; use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser}; diff --git a/compiler/rustc_attr_parsing/src/attributes/inline.rs b/compiler/rustc_attr_parsing/src/attributes/inline.rs index fe812175218d..8437713206e3 100644 --- a/compiler/rustc_attr_parsing/src/attributes/inline.rs +++ b/compiler/rustc_attr_parsing/src/attributes/inline.rs @@ -2,9 +2,9 @@ // note: need to model better how duplicate attr errors work when not using // SingleAttributeParser which is what we have two of here. -use rustc_attr_data_structures::lints::AttributeLintKind; -use rustc_attr_data_structures::{AttributeKind, InlineAttr}; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::{AttributeKind, InlineAttr}; +use rustc_hir::lints::AttributeLintKind; use rustc_span::{Symbol, sym}; use super::{AcceptContext, AttributeOrder, OnDuplicate}; diff --git a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs index 960cebd89259..7eab30908704 100644 --- a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs @@ -1,6 +1,6 @@ -use rustc_attr_data_structures::AttributeKind; -use rustc_attr_data_structures::AttributeKind::{LinkName, LinkOrdinal, LinkSection}; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::attrs::AttributeKind::{LinkName, LinkOrdinal, LinkSection}; use rustc_span::{Span, Symbol, sym}; use crate::attributes::{ diff --git a/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs b/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs index 0eceff53e8b4..9530fec07d61 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol, sym}; use crate::attributes::{NoArgsAttributeParser, OnDuplicate}; diff --git a/compiler/rustc_attr_parsing/src/attributes/loop_match.rs b/compiler/rustc_attr_parsing/src/attributes/loop_match.rs index 80808b90dc66..868c113a6d13 100644 --- a/compiler/rustc_attr_parsing/src/attributes/loop_match.rs +++ b/compiler/rustc_attr_parsing/src/attributes/loop_match.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol, sym}; use crate::attributes::{NoArgsAttributeParser, OnDuplicate}; diff --git a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs index eade49180ace..886f7a889d30 100644 --- a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs @@ -1,6 +1,6 @@ -use rustc_attr_data_structures::{AttributeKind, MacroUseArgs}; use rustc_errors::DiagArgValue; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::{AttributeKind, MacroUseArgs}; use rustc_span::{Span, Symbol, sym}; use thin_vec::ThinVec; diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index 0c10517d0440..c574ef78bdf7 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -16,8 +16,8 @@ use std::marker::PhantomData; -use rustc_attr_data_structures::AttributeKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol}; use thin_vec::ThinVec; diff --git a/compiler/rustc_attr_parsing/src/attributes/must_use.rs b/compiler/rustc_attr_parsing/src/attributes/must_use.rs index 42af3ed0bfab..d767abbc250f 100644 --- a/compiler/rustc_attr_parsing/src/attributes/must_use.rs +++ b/compiler/rustc_attr_parsing/src/attributes/must_use.rs @@ -1,6 +1,6 @@ -use rustc_attr_data_structures::AttributeKind; use rustc_errors::DiagArgValue; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Symbol, sym}; use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser}; diff --git a/compiler/rustc_attr_parsing/src/attributes/no_implicit_prelude.rs b/compiler/rustc_attr_parsing/src/attributes/no_implicit_prelude.rs index 47cc925f7f6b..40f8d00685ea 100644 --- a/compiler/rustc_attr_parsing/src/attributes/no_implicit_prelude.rs +++ b/compiler/rustc_attr_parsing/src/attributes/no_implicit_prelude.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, sym}; use crate::attributes::{NoArgsAttributeParser, OnDuplicate}; diff --git a/compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs b/compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs index 94f6a65c74ec..361ac8e959dc 100644 --- a/compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs +++ b/compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol, sym}; use crate::attributes::{NoArgsAttributeParser, OnDuplicate}; diff --git a/compiler/rustc_attr_parsing/src/attributes/path.rs b/compiler/rustc_attr_parsing/src/attributes/path.rs index febb1b45a18f..5700d780d712 100644 --- a/compiler/rustc_attr_parsing/src/attributes/path.rs +++ b/compiler/rustc_attr_parsing/src/attributes/path.rs @@ -1,5 +1,5 @@ -use rustc_attr_data_structures::AttributeKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Symbol, sym}; use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser}; diff --git a/compiler/rustc_attr_parsing/src/attributes/proc_macro_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/proc_macro_attrs.rs index 4de77dc268ea..b156a7c58450 100644 --- a/compiler/rustc_attr_parsing/src/attributes/proc_macro_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/proc_macro_attrs.rs @@ -1,5 +1,5 @@ -use rustc_attr_data_structures::AttributeKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol, sym}; use thin_vec::ThinVec; diff --git a/compiler/rustc_attr_parsing/src/attributes/repr.rs b/compiler/rustc_attr_parsing/src/attributes/repr.rs index 521acbb607c7..6087afe6ded4 100644 --- a/compiler/rustc_attr_parsing/src/attributes/repr.rs +++ b/compiler/rustc_attr_parsing/src/attributes/repr.rs @@ -1,7 +1,7 @@ use rustc_abi::Align; use rustc_ast::{IntTy, LitIntType, LitKind, UintTy}; -use rustc_attr_data_structures::{AttributeKind, IntType, ReprAttr}; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::{AttributeKind, IntType, ReprAttr}; use rustc_span::{DUMMY_SP, Span, Symbol, sym}; use super::{AcceptMapping, AttributeParser, CombineAttributeParser, ConvertFn, FinalizeContext}; diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 7ca951dc0bbb..b465d2e62ff2 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -1,5 +1,5 @@ -use rustc_attr_data_structures::AttributeKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Symbol, sym}; use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser}; diff --git a/compiler/rustc_attr_parsing/src/attributes/semantics.rs b/compiler/rustc_attr_parsing/src/attributes/semantics.rs index 74fdff5d2e18..70a8a0020996 100644 --- a/compiler/rustc_attr_parsing/src/attributes/semantics.rs +++ b/compiler/rustc_attr_parsing/src/attributes/semantics.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::AttributeKind; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol, sym}; use crate::attributes::{NoArgsAttributeParser, OnDuplicate}; diff --git a/compiler/rustc_attr_parsing/src/attributes/stability.rs b/compiler/rustc_attr_parsing/src/attributes/stability.rs index c54fc6b41f8e..3c4ec133d51c 100644 --- a/compiler/rustc_attr_parsing/src/attributes/stability.rs +++ b/compiler/rustc_attr_parsing/src/attributes/stability.rs @@ -1,11 +1,12 @@ use std::num::NonZero; -use rustc_attr_data_structures::{ - AttributeKind, DefaultBodyStability, PartialConstStability, Stability, StabilityLevel, - StableSince, UnstableReason, VERSION_PLACEHOLDER, -}; use rustc_errors::ErrorGuaranteed; use rustc_feature::template; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::{ + DefaultBodyStability, PartialConstStability, Stability, StabilityLevel, StableSince, + UnstableReason, VERSION_PLACEHOLDER, +}; use rustc_span::{Ident, Span, Symbol, sym}; use super::util::parse_version; diff --git a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs index ee81f64860f8..a90ed830cd1d 100644 --- a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs @@ -1,6 +1,6 @@ -use rustc_attr_data_structures::AttributeKind; -use rustc_attr_data_structures::lints::AttributeLintKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::lints::AttributeLintKind; use rustc_span::{Symbol, sym}; use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser}; diff --git a/compiler/rustc_attr_parsing/src/attributes/traits.rs b/compiler/rustc_attr_parsing/src/attributes/traits.rs index e69a533699ba..a954617ca577 100644 --- a/compiler/rustc_attr_parsing/src/attributes/traits.rs +++ b/compiler/rustc_attr_parsing/src/attributes/traits.rs @@ -1,7 +1,7 @@ use core::mem; -use rustc_attr_data_structures::AttributeKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::{Span, Symbol, sym}; use crate::attributes::{ diff --git a/compiler/rustc_attr_parsing/src/attributes/transparency.rs b/compiler/rustc_attr_parsing/src/attributes/transparency.rs index c9fdc57cc06e..1c57dc1ebe2e 100644 --- a/compiler/rustc_attr_parsing/src/attributes/transparency.rs +++ b/compiler/rustc_attr_parsing/src/attributes/transparency.rs @@ -1,5 +1,5 @@ -use rustc_attr_data_structures::AttributeKind; use rustc_feature::{AttributeTemplate, template}; +use rustc_hir::attrs::AttributeKind; use rustc_span::hygiene::Transparency; use rustc_span::{Symbol, sym}; diff --git a/compiler/rustc_attr_parsing/src/attributes/util.rs b/compiler/rustc_attr_parsing/src/attributes/util.rs index 503d2f1fae16..10134915b278 100644 --- a/compiler/rustc_attr_parsing/src/attributes/util.rs +++ b/compiler/rustc_attr_parsing/src/attributes/util.rs @@ -1,6 +1,6 @@ use rustc_ast::attr::{AttributeExt, first_attr_value_str_by_name}; -use rustc_attr_data_structures::RustcVersion; use rustc_feature::is_builtin_attr_name; +use rustc_hir::RustcVersion; use rustc_span::{Symbol, sym}; /// Parse a rustc version number written inside string literal in an attribute, diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 9b86d1018408..54c0fbcd0626 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -5,10 +5,10 @@ use std::sync::LazyLock; use private::Sealed; use rustc_ast::{self as ast, LitKind, MetaItemLit, NodeId}; -use rustc_attr_data_structures::AttributeKind; -use rustc_attr_data_structures::lints::{AttributeLint, AttributeLintKind}; use rustc_errors::{DiagCtxtHandle, Diagnostic}; use rustc_feature::{AttributeTemplate, Features}; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::lints::{AttributeLint, AttributeLintKind}; use rustc_hir::{AttrArgs, AttrItem, AttrPath, Attribute, HashIgnoredAttrId, HirId}; use rustc_session::Session; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym}; diff --git a/compiler/rustc_attr_parsing/src/lib.rs b/compiler/rustc_attr_parsing/src/lib.rs index dc54cb6b840c..fc1377e53143 100644 --- a/compiler/rustc_attr_parsing/src/lib.rs +++ b/compiler/rustc_attr_parsing/src/lib.rs @@ -1,13 +1,13 @@ //! Centralized logic for parsing and attributes. //! //! ## Architecture -//! This crate is part of a series of crates that handle attribute processing. -//! - [rustc_attr_data_structures](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_attr_data_structures/index.html): Defines the data structures that store parsed attributes +//! This crate is part of a series of crates and modules that handle attribute processing. +//! - [rustc_hir::attrs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/index.html): Defines the data structures that store parsed attributes //! - [rustc_attr_parsing](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_attr_parsing/index.html): This crate, handles the parsing of attributes -//! - (planned) rustc_attr_validation: Will handle attribute validation +//! - (planned) rustc_attr_validation: Will handle attribute validation, logic currently handled in `rustc_passes` //! //! The separation between data structures and parsing follows the principle of separation of concerns. -//! Data structures (`rustc_attr_data_structures`) define what attributes look like after parsing. +//! Data structures (`rustc_hir::attrs`) define what attributes look like after parsing. //! This crate (`rustc_attr_parsing`) handles how to convert raw tokens into those structures. //! This split allows other parts of the compiler to use the data structures without needing //! the parsing logic, making the codebase more modular and maintainable. @@ -62,7 +62,7 @@ //! a "stability" of an item. So, the stability attribute has an //! [`AttributeParser`](attributes::AttributeParser) that recognizes both the `#[stable()]` //! and `#[unstable()]` syntactic attributes, and at the end produce a single -//! [`AttributeKind::Stability`](rustc_attr_data_structures::AttributeKind::Stability). +//! [`AttributeKind::Stability`](rustc_hir::attrs::AttributeKind::Stability). //! //! When multiple instances of the same attribute are allowed, they're combined into a single //! semantic attribute. For example: diff --git a/compiler/rustc_attr_parsing/src/lints.rs b/compiler/rustc_attr_parsing/src/lints.rs index e648ca4fdf80..22f5531bc807 100644 --- a/compiler/rustc_attr_parsing/src/lints.rs +++ b/compiler/rustc_attr_parsing/src/lints.rs @@ -1,6 +1,6 @@ -use rustc_attr_data_structures::lints::{AttributeLint, AttributeLintKind}; use rustc_errors::{DiagArgValue, LintEmitter}; use rustc_hir::HirId; +use rustc_hir::lints::{AttributeLint, AttributeLintKind}; use crate::session_diagnostics; diff --git a/compiler/rustc_builtin_macros/Cargo.toml b/compiler/rustc_builtin_macros/Cargo.toml index 4c1264c6f1ce..e56b9e641a10 100644 --- a/compiler/rustc_builtin_macros/Cargo.toml +++ b/compiler/rustc_builtin_macros/Cargo.toml @@ -10,7 +10,6 @@ doctest = false # tidy-alphabetical-start rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index b24e55637613..fc9eed24ee08 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -187,10 +187,10 @@ use rustc_ast::{ self as ast, AnonConst, AttrArgs, BindingMode, ByRef, DelimArgs, EnumDef, Expr, GenericArg, GenericParamKind, Generics, Mutability, PatKind, Safety, VariantData, }; -use rustc_attr_data_structures::{AttributeKind, ReprPacked}; use rustc_attr_parsing::AttributeParser; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_hir::Attribute; +use rustc_hir::attrs::{AttributeKind, ReprPacked}; use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym}; use thin_vec::{ThinVec, thin_vec}; use ty::{Bounds, Path, Ref, Self_, Ty}; diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index 09f5e6f6efc1..df70c93c1c2d 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -4,12 +4,12 @@ use rustc_ast::ptr::P; use rustc_ast::visit::{self, Visitor}; use rustc_ast::{self as ast, HasNodeId, NodeId, attr}; use rustc_ast_pretty::pprust; -use rustc_attr_data_structures::AttributeKind; use rustc_attr_parsing::AttributeParser; use rustc_errors::DiagCtxtHandle; use rustc_expand::base::{ExtCtxt, ResolverExpand}; use rustc_expand::expand::{AstFragment, ExpansionConfig}; use rustc_feature::Features; +use rustc_hir::attrs::AttributeKind; use rustc_session::Session; use rustc_span::hygiene::AstPass; use rustc_span::source_map::SourceMap; diff --git a/compiler/rustc_codegen_gcc/src/attributes.rs b/compiler/rustc_codegen_gcc/src/attributes.rs index 7a1ae6ca9c8b..04b43bb8bb7c 100644 --- a/compiler/rustc_codegen_gcc/src/attributes.rs +++ b/compiler/rustc_codegen_gcc/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/compiler/rustc_codegen_gcc/src/callee.rs b/compiler/rustc_codegen_gcc/src/callee.rs index e7ca95af594c..8487a85bd035 100644 --- a/compiler/rustc_codegen_gcc/src/callee.rs +++ b/compiler/rustc_codegen_gcc/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/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index a31206825007..613315f77a6b 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/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; diff --git a/compiler/rustc_codegen_llvm/Cargo.toml b/compiler/rustc_codegen_llvm/Cargo.toml index 5ab22f8fc4d9..71bb3e3767ef 100644 --- a/compiler/rustc_codegen_llvm/Cargo.toml +++ b/compiler/rustc_codegen_llvm/Cargo.toml @@ -19,7 +19,6 @@ object = { version = "0.37.0", default-features = false, features = ["std", "rea rustc-demangle = "0.1.21" rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_codegen_ssa = { path = "../rustc_codegen_ssa" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } @@ -38,7 +37,7 @@ rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_symbol_mangling = { path = "../rustc_symbol_mangling" } rustc_target = { path = "../rustc_target" } -serde = { version = "1", features = [ "derive" ]} +serde = { version = "1", features = ["derive"] } serde_json = "1" smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } tracing = "0.1" diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index c32f11b27f3d..c548f4675834 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -1,6 +1,6 @@ //! Set and unset common attributes on LLVM values. -use rustc_attr_data_structures::{InlineAttr, InstructionSetAttr, OptimizeAttr}; use rustc_codegen_ssa::traits::*; +use rustc_hir::attrs::{InlineAttr, InstructionSetAttr, OptimizeAttr}; use rustc_hir::def_id::DefId; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, PatchableFunctionEntry}; use rustc_middle::ty::{self, TyCtxt}; diff --git a/compiler/rustc_codegen_llvm/src/callee.rs b/compiler/rustc_codegen_llvm/src/callee.rs index 5a3dd90ab240..791a71d73ae5 100644 --- a/compiler/rustc_codegen_llvm/src/callee.rs +++ b/compiler/rustc_codegen_llvm/src/callee.rs @@ -103,7 +103,7 @@ pub(crate) fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'t // 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/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index 61555ac2f6f6..bcfa0381cc1b 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -1,9 +1,10 @@ // .debug_gdb_scripts binary section. -use rustc_attr_data_structures::{AttributeKind, find_attr}; 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}; diff --git a/compiler/rustc_codegen_ssa/Cargo.toml b/compiler/rustc_codegen_ssa/Cargo.toml index 94501da69a76..30956fd18557 100644 --- a/compiler/rustc_codegen_ssa/Cargo.toml +++ b/compiler/rustc_codegen_ssa/Cargo.toml @@ -17,7 +17,6 @@ regex = "1.4" rustc_abi = { path = "../rustc_abi" } rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index 297bdec2bc21..4b4b39f53533 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -384,7 +384,7 @@ fn exported_generic_symbols_provider_local<'tcx>( if !tcx.sess.opts.share_generics() { if tcx.codegen_fn_attrs(mono_item.def_id()).inline - == rustc_attr_data_structures::InlineAttr::Never + == rustc_hir::attrs::InlineAttr::Never { // this is OK, we explicitly allow sharing inline(never) across crates even // without share-generics. diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index a5807c56e317..b4556ced0b3f 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -7,11 +7,11 @@ use itertools::Itertools; use rustc_abi::FIRST_VARIANT; use rustc_ast as ast; use rustc_ast::expand::allocator::AllocatorKind; -use rustc_attr_data_structures::OptimizeAttr; use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; use rustc_data_structures::sync::{IntoDynSyncSend, par_map}; use rustc_data_structures::unord::UnordMap; +use rustc_hir::attrs::OptimizeAttr; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::lang_items::LangItem; use rustc_hir::{ItemId, Target}; diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 78edc69b237a..7f54a47327af 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -3,13 +3,11 @@ use std::str::FromStr; use rustc_abi::{Align, ExternAbi}; use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode}; use rustc_ast::{LitKind, MetaItem, MetaItemInner, attr}; -use rustc_attr_data_structures::{ - AttributeKind, InlineAttr, InstructionSetAttr, UsedBy, find_attr, -}; +use rustc_hir::attrs::{AttributeKind, InlineAttr, InstructionSetAttr, UsedBy}; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS; -use rustc_hir::{self as hir, Attribute, LangItem, lang_items}; +use rustc_hir::{self as hir, Attribute, LangItem, find_attr, lang_items}; use rustc_middle::middle::codegen_fn_attrs::{ CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, }; diff --git a/compiler/rustc_codegen_ssa/src/mir/naked_asm.rs b/compiler/rustc_codegen_ssa/src/mir/naked_asm.rs index 42e435cf0a32..2a9b5c9019b9 100644 --- a/compiler/rustc_codegen_ssa/src/mir/naked_asm.rs +++ b/compiler/rustc_codegen_ssa/src/mir/naked_asm.rs @@ -1,5 +1,5 @@ use rustc_abi::{BackendRepr, Float, Integer, Primitive, RegKind}; -use rustc_attr_data_structures::InstructionSetAttr; +use rustc_hir::attrs::InstructionSetAttr; use rustc_middle::mir::mono::{Linkage, MonoItemData, Visibility}; use rustc_middle::mir::{InlineAsmOperand, START_BLOCK}; use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout}; diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index def4ec13e87b..d984156c674c 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -1,6 +1,6 @@ -use rustc_attr_data_structures::InstructionSetAttr; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::unord::{UnordMap, UnordSet}; +use rustc_hir::attrs::InstructionSetAttr; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_middle::middle::codegen_fn_attrs::TargetFeature; diff --git a/compiler/rustc_const_eval/Cargo.toml b/compiler/rustc_const_eval/Cargo.toml index 93d0d5b9a71e..51dcee8d8822 100644 --- a/compiler/rustc_const_eval/Cargo.toml +++ b/compiler/rustc_const_eval/Cargo.toml @@ -9,7 +9,6 @@ either = "1" rustc_abi = { path = "../rustc_abi" } rustc_apfloat = "0.2.0" rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 44e5d1d5ee7e..8e2c138282af 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -6,7 +6,6 @@ use std::mem; use std::num::NonZero; use std::ops::Deref; -use rustc_attr_data_structures as attrs; use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; @@ -466,7 +465,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { /// Check the const stability of the given item (fn or trait). fn check_callee_stability(&mut self, def_id: DefId) { match self.tcx.lookup_const_stability(def_id) { - Some(attrs::ConstStability { level: attrs::StabilityLevel::Stable { .. }, .. }) => { + Some(hir::ConstStability { level: hir::StabilityLevel::Stable { .. }, .. }) => { // All good. } None => { @@ -482,8 +481,8 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { }); } } - Some(attrs::ConstStability { - level: attrs::StabilityLevel::Unstable { implied_by: implied_feature, issue, .. }, + Some(hir::ConstStability { + level: hir::StabilityLevel::Unstable { implied_by: implied_feature, issue, .. }, feature, .. }) => { @@ -891,8 +890,8 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { }); } } - Some(attrs::ConstStability { - level: attrs::StabilityLevel::Unstable { .. }, + Some(hir::ConstStability { + level: hir::StabilityLevel::Unstable { .. }, feature, .. }) => { @@ -902,8 +901,8 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { const_stable_indirect: is_const_stable, }); } - Some(attrs::ConstStability { - level: attrs::StabilityLevel::Stable { .. }, + Some(hir::ConstStability { + level: hir::StabilityLevel::Stable { .. }, .. }) => { // All good. Note that a `#[rustc_const_stable]` intrinsic (meaning it diff --git a/compiler/rustc_const_eval/src/check_consts/mod.rs b/compiler/rustc_const_eval/src/check_consts/mod.rs index ebf18c6f2ac8..4a88d039ef3c 100644 --- a/compiler/rustc_const_eval/src/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/check_consts/mod.rs @@ -5,11 +5,12 @@ //! it finds operations that are invalid in a certain context. use rustc_errors::DiagCtxtHandle; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::{self as hir, find_attr}; use rustc_middle::ty::{self, PolyFnSig, TyCtxt}; use rustc_middle::{bug, mir}; use rustc_span::Symbol; -use {rustc_attr_data_structures as attrs, rustc_hir as hir}; pub use self::qualifs::Qualif; @@ -82,7 +83,7 @@ pub fn rustc_allow_const_fn_unstable( ) -> bool { let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); - attrs::find_attr!(attrs, attrs::AttributeKind::AllowConstFnUnstable(syms, _) if syms.contains(&feature_gate)) + find_attr!(attrs, AttributeKind::AllowConstFnUnstable(syms, _) if syms.contains(&feature_gate)) } /// Returns `true` if the given `def_id` (trait or function) is "safe to expose on stable". diff --git a/compiler/rustc_errors/Cargo.toml b/compiler/rustc_errors/Cargo.toml index c4181a62a35d..3e8cf6207aed 100644 --- a/compiler/rustc_errors/Cargo.toml +++ b/compiler/rustc_errors/Cargo.toml @@ -10,7 +10,6 @@ derive_setters = "0.1.6" rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_error_codes = { path = "../rustc_error_codes" } rustc_error_messages = { path = "../rustc_error_messages" } @@ -25,7 +24,7 @@ rustc_serialize = { path = "../rustc_serialize" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } rustc_type_ir = { path = "../rustc_type_ir" } -serde = { version = "1.0.125", features = [ "derive" ] } +serde = { version = "1.0.125", features = ["derive"] } serde_json = "1.0.59" termcolor = "1.2.0" termize = "0.2" diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index eeb9ac28808b..eca5806fac52 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -8,7 +8,7 @@ use std::process::ExitStatus; use rustc_abi::TargetDataLayoutErrors; use rustc_ast::util::parser::ExprPrecedence; use rustc_ast_pretty::pprust; -use rustc_attr_data_structures::RustcVersion; +use rustc_hir::RustcVersion; use rustc_macros::Subdiagnostic; use rustc_span::edition::Edition; use rustc_span::{Ident, MacroRulesNormalizedIdent, Span, Symbol}; diff --git a/compiler/rustc_expand/Cargo.toml b/compiler/rustc_expand/Cargo.toml index 57dd3a3128df..f897833d85c0 100644 --- a/compiler/rustc_expand/Cargo.toml +++ b/compiler/rustc_expand/Cargo.toml @@ -12,7 +12,6 @@ doctest = false rustc_ast = { path = "../rustc_ast" } rustc_ast_passes = { path = "../rustc_ast_passes" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index c01320fc6446..1a9832b2fe26 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -12,12 +12,13 @@ use rustc_ast::token::MetaVarKind; use rustc_ast::tokenstream::TokenStream; use rustc_ast::visit::{AssocCtxt, Visitor}; use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind}; -use rustc_attr_data_structures::{AttributeKind, CfgEntry, Deprecation, Stability, find_attr}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_data_structures::sync; use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, PResult}; use rustc_feature::Features; use rustc_hir as hir; +use rustc_hir::attrs::{AttributeKind, CfgEntry, Deprecation}; +use rustc_hir::{Stability, find_attr}; use rustc_lint_defs::{BufferedEarlyLint, RegisteredTools}; use rustc_parse::MACRO_ARGUMENTS; use rustc_parse::parser::{ForceCollect, Parser}; diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index febe6f8b88cc..52d38c35f980 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -10,11 +10,12 @@ use rustc_ast::token::{self, NonterminalKind, Token, TokenKind}; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; use rustc_ast::{self as ast, DUMMY_NODE_ID, NodeId}; use rustc_ast_pretty::pprust; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; use rustc_feature::Features; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::find_attr; use rustc_lint_defs::BuiltinLintDiag; use rustc_lint_defs::builtin::{ RUST_2021_INCOMPATIBLE_OR_PATTERNS, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS, diff --git a/compiler/rustc_feature/Cargo.toml b/compiler/rustc_feature/Cargo.toml index 78d7b698b720..a4746ac455c1 100644 --- a/compiler/rustc_feature/Cargo.toml +++ b/compiler/rustc_feature/Cargo.toml @@ -5,8 +5,8 @@ edition = "2024" [dependencies] # tidy-alphabetical-start -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" } +rustc_hir = { path = "../rustc_hir" } rustc_span = { path = "../rustc_span" } serde = { version = "1.0.125", features = ["derive"] } serde_json = "1.0.59" diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 96df6aa19bcc..ceb7fc5bf6f8 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -5,8 +5,8 @@ use std::sync::LazyLock; use AttributeDuplicates::*; use AttributeGate::*; use AttributeType::*; -use rustc_attr_data_structures::EncodeCrossCrate; use rustc_data_structures::fx::FxHashMap; +use rustc_hir::attrs::EncodeCrossCrate; use rustc_span::edition::Edition; use rustc_span::{Symbol, sym}; @@ -112,7 +112,7 @@ pub enum AttributeGate { Ungated, } -// FIXME(jdonszelmann): move to rustc_attr_data_structures +// FIXME(jdonszelmann): move to rustc_hir::attrs /// A template that the attribute input must match. /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now. #[derive(Clone, Copy, Default)] diff --git a/compiler/rustc_hir/Cargo.toml b/compiler/rustc_hir/Cargo.toml index 7ca8539845a0..539d2e6f0b17 100644 --- a/compiler/rustc_hir/Cargo.toml +++ b/compiler/rustc_hir/Cargo.toml @@ -9,7 +9,7 @@ odht = { version = "0.3.1", features = ["nightly"] } rustc_abi = { path = "../rustc_abi" } rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } +rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_hashes = { path = "../rustc_hashes" } rustc_index = { path = "../rustc_index" } diff --git a/compiler/rustc_attr_data_structures/src/attributes.rs b/compiler/rustc_hir/src/attrs/data_structures.rs similarity index 98% rename from compiler/rustc_attr_data_structures/src/attributes.rs rename to compiler/rustc_hir/src/attrs/data_structures.rs index 55019cd57a71..80f5e6177f75 100644 --- a/compiler/rustc_attr_data_structures/src/attributes.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -1,12 +1,15 @@ +pub use ReprAttr::*; use rustc_abi::Align; use rustc_ast::token::CommentKind; -use rustc_ast::{self as ast, AttrStyle}; +use rustc_ast::{AttrStyle, ast}; use rustc_macros::{Decodable, Encodable, HashStable_Generic, PrintAttribute}; +use rustc_span::def_id::DefId; use rustc_span::hygiene::Transparency; use rustc_span::{Ident, Span, Symbol}; use thin_vec::ThinVec; -use crate::{DefaultBodyStability, PartialConstStability, PrintAttribute, RustcVersion, Stability}; +use crate::attrs::pretty_printing::PrintAttribute; +use crate::{DefaultBodyStability, PartialConstStability, RustcVersion, Stability}; #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, PrintAttribute)] pub enum InlineAttr { @@ -68,8 +71,6 @@ pub enum ReprAttr { ReprTransparent, ReprAlign(Align), } -pub use ReprAttr::*; -use rustc_span::def_id::DefId; pub enum TransparencyError { UnknownTransparency(Symbol, Span), diff --git a/compiler/rustc_attr_data_structures/src/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs similarity index 98% rename from compiler/rustc_attr_data_structures/src/encode_cross_crate.rs rename to compiler/rustc_hir/src/attrs/encode_cross_crate.rs index af2d46d0bc71..bbdecb2986e0 100644 --- a/compiler/rustc_attr_data_structures/src/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -1,4 +1,4 @@ -use crate::AttributeKind; +use crate::attrs::AttributeKind; #[derive(PartialEq)] pub enum EncodeCrossCrate { diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs new file mode 100644 index 000000000000..482e6c90739f --- /dev/null +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -0,0 +1,54 @@ +//! Data structures for representing parsed attributes in the Rust compiler. +//! Formerly `rustc_attr_data_structures`. +//! +//! For detailed documentation about attribute processing, +//! see [rustc_attr_parsing](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_attr_parsing/index.html). + +pub use data_structures::*; +pub use encode_cross_crate::EncodeCrossCrate; +pub use pretty_printing::PrintAttribute; + +mod data_structures; +mod encode_cross_crate; +mod pretty_printing; + +/// Finds attributes in sequences of attributes by pattern matching. +/// +/// A little like `matches` but for attributes. +/// +/// ```rust,ignore (illustrative) +/// // finds the repr attribute +/// if let Some(r) = find_attr!(attrs, AttributeKind::Repr(r) => r) { +/// +/// } +/// +/// // checks if one has matched +/// if find_attr!(attrs, AttributeKind::Repr(_)) { +/// +/// } +/// ``` +/// +/// Often this requires you to first end up with a list of attributes. +/// A common way to get those is through `tcx.get_all_attrs(did)` +#[macro_export] +macro_rules! find_attr { + ($attributes_list: expr, $pattern: pat $(if $guard: expr)?) => {{ + $crate::find_attr!($attributes_list, $pattern $(if $guard)? => ()).is_some() + }}; + + ($attributes_list: expr, $pattern: pat $(if $guard: expr)? => $e: expr) => {{ + 'done: { + for i in $attributes_list { + let i: &rustc_hir::Attribute = i; + match i { + rustc_hir::Attribute::Parsed($pattern) $(if $guard)? => { + break 'done Some($e); + } + _ => {} + } + } + + None + } + }}; +} diff --git a/compiler/rustc_attr_data_structures/src/lib.rs b/compiler/rustc_hir/src/attrs/pretty_printing.rs similarity index 68% rename from compiler/rustc_attr_data_structures/src/lib.rs rename to compiler/rustc_hir/src/attrs/pretty_printing.rs index 4c5af805ca90..e44b29141da9 100644 --- a/compiler/rustc_attr_data_structures/src/lib.rs +++ b/compiler/rustc_hir/src/attrs/pretty_printing.rs @@ -1,38 +1,12 @@ -//! Data structures for representing parsed attributes in the Rust compiler. -//! For detailed documentation about attribute processing, -//! see [rustc_attr_parsing](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_attr_parsing/index.html). - -// tidy-alphabetical-start -#![allow(internal_features)] -#![doc(rust_logo)] -#![feature(rustdoc_internals)] -// tidy-alphabetical-end - -mod attributes; -mod encode_cross_crate; -mod stability; -mod version; - -pub mod lints; - use std::num::NonZero; -pub use attributes::*; -pub use encode_cross_crate::EncodeCrossCrate; use rustc_abi::Align; use rustc_ast::token::CommentKind; use rustc_ast::{AttrStyle, IntTy, UintTy}; use rustc_ast_pretty::pp::Printer; use rustc_span::hygiene::Transparency; use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol}; -pub use stability::*; use thin_vec::ThinVec; -pub use version::*; - -/// Requirements for a `StableHashingContext` to be used in this crate. -/// This is a hack to allow using the `HashStable_Generic` derive macro -/// instead of implementing everything in `rustc_middle`. -pub trait HashStableContext: rustc_ast::HashStableContext + rustc_abi::HashStableContext {} /// This trait is used to print attributes in `rustc_hir_pretty`. /// @@ -173,44 +147,3 @@ print_tup!(A B C D E F G H); print_skip!(Span, (), ErrorGuaranteed); print_disp!(u16, bool, NonZero); print_debug!(Symbol, Ident, UintTy, IntTy, Align, AttrStyle, CommentKind, Transparency); - -/// Finds attributes in sequences of attributes by pattern matching. -/// -/// A little like `matches` but for attributes. -/// -/// ```rust,ignore (illustrative) -/// // finds the repr attribute -/// if let Some(r) = find_attr!(attrs, AttributeKind::Repr(r) => r) { -/// -/// } -/// -/// // checks if one has matched -/// if find_attr!(attrs, AttributeKind::Repr(_)) { -/// -/// } -/// ``` -/// -/// Often this requires you to first end up with a list of attributes. -/// A common way to get those is through `tcx.get_all_attrs(did)` -#[macro_export] -macro_rules! find_attr { - ($attributes_list: expr, $pattern: pat $(if $guard: expr)?) => {{ - $crate::find_attr!($attributes_list, $pattern $(if $guard)? => ()).is_some() - }}; - - ($attributes_list: expr, $pattern: pat $(if $guard: expr)? => $e: expr) => {{ - 'done: { - for i in $attributes_list { - let i: &rustc_hir::Attribute = i; - match i { - rustc_hir::Attribute::Parsed($pattern) $(if $guard)? => { - break 'done Some($e); - } - _ => {} - } - } - - None - } - }}; -} diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 4ccc2e5a97c7..1b1b3ced44db 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -14,7 +14,6 @@ pub use rustc_ast::{ BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto, MetaItemInner, MetaItemLit, Movability, Mutability, UnOp, }; -use rustc_attr_data_structures::AttributeKind; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::tagged_ptr::TaggedRef; @@ -30,6 +29,7 @@ use thin_vec::ThinVec; use tracing::debug; use crate::LangItem; +use crate::attrs::AttributeKind; use crate::def::{CtorKind, DefKind, PerNS, Res}; use crate::def_id::{DefId, LocalDefIdMap}; pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId}; diff --git a/compiler/rustc_hir/src/lib.rs b/compiler/rustc_hir/src/lib.rs index dafd31336fbb..f1212d07ff60 100644 --- a/compiler/rustc_hir/src/lib.rs +++ b/compiler/rustc_hir/src/lib.rs @@ -18,6 +18,7 @@ extern crate self as rustc_hir; mod arena; +pub mod attrs; pub mod def; pub mod def_path_hash_map; pub mod definitions; @@ -29,8 +30,10 @@ pub mod intravisit; pub mod lang_items; pub mod lints; pub mod pat_util; +mod stability; mod stable_hash_impls; mod target; +mod version; pub mod weak_lang_items; #[cfg(test)] @@ -40,7 +43,9 @@ mod tests; pub use hir::*; pub use hir_id::*; pub use lang_items::{LangItem, LanguageItems}; +pub use stability::*; pub use stable_hash_impls::HashStableContext; pub use target::{MethodKind, Target}; +pub use version::*; arena_types!(rustc_arena::declare_arena); diff --git a/compiler/rustc_hir/src/lints.rs b/compiler/rustc_hir/src/lints.rs index 7be6c32e57ed..c55a41eb2b76 100644 --- a/compiler/rustc_hir/src/lints.rs +++ b/compiler/rustc_hir/src/lints.rs @@ -1,9 +1,16 @@ -use rustc_attr_data_structures::lints::AttributeLint; use rustc_data_structures::fingerprint::Fingerprint; use rustc_macros::HashStable_Generic; +use rustc_span::Span; use crate::HirId; +#[derive(Debug)] +pub struct DelayedLints { + pub lints: Box<[DelayedLint]>, + // Only present when the crate hash is needed. + pub opt_hash: Option, +} + /// During ast lowering, no lints can be emitted. /// That is because lints attach to nodes either in the AST, or on the built HIR. /// When attached to AST nodes, they're emitted just before building HIR, @@ -15,9 +22,16 @@ pub enum DelayedLint { AttributeParsing(AttributeLint), } -#[derive(Debug)] -pub struct DelayedLints { - pub lints: Box<[DelayedLint]>, - // Only present when the crate hash is needed. - pub opt_hash: Option, +#[derive(Clone, Debug, HashStable_Generic)] +pub struct AttributeLint { + pub id: Id, + pub span: Span, + pub kind: AttributeLintKind, +} + +#[derive(Clone, Debug, HashStable_Generic)] +pub enum AttributeLintKind { + UnusedDuplicate { this: Span, other: Span, warning: bool }, + IllFormedAttributeInput { suggestions: Vec }, + EmptyAttribute { first_span: Span }, } diff --git a/compiler/rustc_attr_data_structures/src/stability.rs b/compiler/rustc_hir/src/stability.rs similarity index 99% rename from compiler/rustc_attr_data_structures/src/stability.rs rename to compiler/rustc_hir/src/stability.rs index bd31c0621176..2b3a2a793163 100644 --- a/compiler/rustc_attr_data_structures/src/stability.rs +++ b/compiler/rustc_hir/src/stability.rs @@ -3,7 +3,8 @@ use std::num::NonZero; use rustc_macros::{Decodable, Encodable, HashStable_Generic, PrintAttribute}; use rustc_span::{ErrorGuaranteed, Symbol, sym}; -use crate::{PrintAttribute, RustcVersion}; +use crate::RustcVersion; +use crate::attrs::PrintAttribute; /// The version placeholder that recently stabilized features contain inside the /// `since` field of the `#[stable]` attribute. diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index 6acf1524b608..ecc608d437b8 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -11,11 +11,7 @@ use crate::lints::DelayedLints; /// Requirements for a `StableHashingContext` to be used in this crate. /// This is a hack to allow using the `HashStable_Generic` derive macro /// instead of implementing everything in `rustc_middle`. -pub trait HashStableContext: - rustc_attr_data_structures::HashStableContext - + rustc_ast::HashStableContext - + rustc_abi::HashStableContext -{ +pub trait HashStableContext: rustc_ast::HashStableContext + rustc_abi::HashStableContext { fn hash_attr_id(&mut self, id: &HashIgnoredAttrId, hasher: &mut StableHasher); } diff --git a/compiler/rustc_attr_data_structures/src/version.rs b/compiler/rustc_hir/src/version.rs similarity index 97% rename from compiler/rustc_attr_data_structures/src/version.rs rename to compiler/rustc_hir/src/version.rs index 030e95209405..ab5ab026b4ca 100644 --- a/compiler/rustc_attr_data_structures/src/version.rs +++ b/compiler/rustc_hir/src/version.rs @@ -5,7 +5,7 @@ use rustc_macros::{ Decodable, Encodable, HashStable_Generic, PrintAttribute, current_rustc_version, }; -use crate::PrintAttribute; +use crate::attrs::PrintAttribute; #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(HashStable_Generic, PrintAttribute)] diff --git a/compiler/rustc_hir_analysis/Cargo.toml b/compiler/rustc_hir_analysis/Cargo.toml index 5d6c49ee862f..e5017794d8f2 100644 --- a/compiler/rustc_hir_analysis/Cargo.toml +++ b/compiler/rustc_hir_analysis/Cargo.toml @@ -13,7 +13,6 @@ itertools = "0.12" rustc_abi = { path = "../rustc_abi" } rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 6e63ce310243..161a8566b04f 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -2,13 +2,14 @@ use std::cell::LazyCell; use std::ops::ControlFlow; use rustc_abi::{ExternAbi, FieldIdx}; -use rustc_attr_data_structures::ReprAttr::ReprPacked; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::codes::*; use rustc_errors::{EmissionGuarantee, MultiSpan}; +use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::attrs::ReprAttr::ReprPacked; use rustc_hir::def::{CtorKind, DefKind}; -use rustc_hir::{LangItem, Node, intravisit}; +use rustc_hir::{LangItem, Node, attrs, find_attr, intravisit}; use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt}; use rustc_infer::traits::{Obligation, ObligationCauseCode, WellFormedLoc}; use rustc_lint_defs::builtin::{ @@ -32,7 +33,6 @@ use rustc_trait_selection::traits; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use tracing::{debug, instrument}; use ty::TypingMode; -use {rustc_attr_data_structures as attrs, rustc_hir as hir}; use super::compare_impl_item::check_type_bounds; use super::*; @@ -1401,7 +1401,7 @@ fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) { let repr = def.repr(); if repr.packed() { - if let Some(reprs) = attrs::find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr { reprs, .. } => reprs) + if let Some(reprs) = find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr { reprs, .. } => reprs) { for (r, _) in reprs { if let ReprPacked(pack) = r @@ -1536,7 +1536,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) ty::Array(ty, _) => check_non_exhaustive(tcx, *ty), ty::Adt(def, args) => { if !def.did().is_local() - && !attrs::find_attr!( + && !find_attr!( tcx.get_all_attrs(def.did()), AttributeKind::PubTransparent(_) ) @@ -1622,7 +1622,7 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) { def.destructor(tcx); // force the destructor to be evaluated if def.variants().is_empty() { - attrs::find_attr!( + find_attr!( tcx.get_all_attrs(def_id), attrs::AttributeKind::Repr { reprs, first_span } => { struct_span_code_err!( diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs index b556683e80a5..97787270be7c 100644 --- a/compiler/rustc_hir_analysis/src/check/entry.rs +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -1,9 +1,9 @@ use std::ops::Not; use rustc_abi::ExternAbi; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_hir as hir; -use rustc_hir::Node; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::{Node, find_attr}; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::span_bug; use rustc_middle::ty::{self, TyCtxt, TypingMode}; diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index 80bf13dc4b7a..38ae7852ca99 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -7,10 +7,11 @@ //! `tcx.inherent_impls(def_id)`). That value, however, //! is computed by selecting an idea from this table. -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::find_attr; use rustc_middle::bug; use rustc_middle::ty::fast_reject::{SimplifiedType, TreatParams, simplify_type}; use rustc_middle::ty::{self, CrateInherentImpls, Ty, TyCtxt}; diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index afe79bed851c..8ccbfbbb3b49 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -21,16 +21,16 @@ use std::ops::Bound; use rustc_abi::ExternAbi; use rustc_ast::Recovered; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::unord::UnordMap; use rustc_errors::{ Applicability, Diag, DiagCtxtHandle, E0228, ErrorGuaranteed, StashKey, struct_span_code_err, }; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{InferKind, Visitor, VisitorExt}; -use rustc_hir::{self as hir, GenericParamKind, HirId, Node, PreciseCapturingArgKind}; +use rustc_hir::{self as hir, GenericParamKind, HirId, Node, PreciseCapturingArgKind, find_attr}; use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::{DynCompatibilityViolation, ObligationCause}; use rustc_middle::query::Providers; diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index cc53919626e6..522409a5ee52 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -1,11 +1,12 @@ use std::assert_matches::assert_matches; use hir::Node; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::find_attr; use rustc_middle::ty::{ self, GenericPredicates, ImplTraitInTraitData, Ty, TyCtxt, TypeVisitable, TypeVisitor, Upcast, }; diff --git a/compiler/rustc_hir_pretty/Cargo.toml b/compiler/rustc_hir_pretty/Cargo.toml index 91da8cb3fc5f..f5d7dbd3f96e 100644 --- a/compiler/rustc_hir_pretty/Cargo.toml +++ b/compiler/rustc_hir_pretty/Cargo.toml @@ -8,7 +8,6 @@ edition = "2024" rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_hir = { path = "../rustc_hir" } rustc_span = { path = "../rustc_span" } # tidy-alphabetical-end diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index bda02042aa66..235eec96d74f 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -15,7 +15,7 @@ use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent}; use rustc_ast_pretty::pp::{self, BoxMarker, Breaks}; use rustc_ast_pretty::pprust::state::MacHeader; use rustc_ast_pretty::pprust::{Comments, PrintState}; -use rustc_attr_data_structures::{AttributeKind, PrintAttribute}; +use rustc_hir::attrs::{AttributeKind, PrintAttribute}; use rustc_hir::{ BindingMode, ByRef, ConstArgKind, GenericArg, GenericBound, GenericParam, GenericParamKind, HirId, ImplicitSelfKind, LifetimeParamKind, Node, PatKind, PreciseCapturingArg, RangeEnd, Term, diff --git a/compiler/rustc_hir_typeck/Cargo.toml b/compiler/rustc_hir_typeck/Cargo.toml index c963f0ddefd4..f00125c3e090 100644 --- a/compiler/rustc_hir_typeck/Cargo.toml +++ b/compiler/rustc_hir_typeck/Cargo.toml @@ -8,7 +8,6 @@ edition = "2024" itertools = "0.12" rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 6d67535da5fb..9a4c6f98a480 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -37,10 +37,10 @@ use std::ops::Deref; -use rustc_attr_data_structures::InlineAttr; use rustc_errors::codes::*; use rustc_errors::{Applicability, Diag, struct_span_code_err}; use rustc_hir as hir; +use rustc_hir::attrs::InlineAttr; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer::relate::RelateResult; diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 08e8164078cb..454ec7ddcafb 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -7,7 +7,6 @@ use rustc_abi::{FIRST_VARIANT, FieldIdx}; use rustc_ast::util::parser::ExprPrecedence; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::unord::UnordMap; @@ -16,10 +15,11 @@ use rustc_errors::{ Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize, struct_span_code_err, }; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; -use rustc_hir::{ExprKind, HirId, QPath}; +use rustc_hir::{ExprKind, HirId, QPath, find_attr}; use rustc_hir_analysis::NoVariantNamed; use rustc_hir_analysis::hir_ty_lowering::{FeedConstTy, HirTyLowerer as _}; use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, RegionVariableOrigin}; diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index b395aa8162c3..aae870f7ee3e 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -42,13 +42,13 @@ mod writeback; pub use coercion::can_coerce; use fn_ctxt::FnCtxt; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::{HirId, HirIdMap, Node}; +use rustc_hir::{HirId, HirIdMap, Node, find_attr}; use rustc_hir_analysis::check::{check_abi, check_custom_abi}; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc}; diff --git a/compiler/rustc_hir_typeck/src/loops.rs b/compiler/rustc_hir_typeck/src/loops.rs index 80eab578f134..d47a32469640 100644 --- a/compiler/rustc_hir_typeck/src/loops.rs +++ b/compiler/rustc_hir_typeck/src/loops.rs @@ -3,12 +3,12 @@ use std::fmt; use Context::*; use rustc_ast::Label; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{Destination, Node}; +use rustc_hir::{Destination, Node, find_attr}; use rustc_middle::hir::nested_filter; use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index e64af8fb7b38..495f592baa81 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -9,7 +9,6 @@ use std::path::PathBuf; use hir::Expr; use rustc_ast::ast::Mutability; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::unord::UnordSet; @@ -17,11 +16,12 @@ use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagStyledString, MultiSpan, StashKey, pluralize, struct_span_code_err, }; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::lang_items::LangItem; -use rustc_hir::{self as hir, ExprKind, HirId, Node, PathSegment, QPath}; +use rustc_hir::{self as hir, ExprKind, HirId, Node, PathSegment, QPath, find_attr}; use rustc_infer::infer::{BoundRegionConversionTime, RegionVariableOrigin}; use rustc_middle::bug; use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type}; diff --git a/compiler/rustc_hir_typeck/src/naked_functions.rs b/compiler/rustc_hir_typeck/src/naked_functions.rs index d055fa68fc34..d3fd63d871aa 100644 --- a/compiler/rustc_hir_typeck/src/naked_functions.rs +++ b/compiler/rustc_hir_typeck/src/naked_functions.rs @@ -1,10 +1,10 @@ //! Checks validity of naked functions. -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::Visitor; -use rustc_hir::{ExprKind, HirIdSet, StmtKind}; +use rustc_hir::{ExprKind, HirIdSet, StmtKind, find_attr}; use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; use rustc_span::Span; diff --git a/compiler/rustc_lint/Cargo.toml b/compiler/rustc_lint/Cargo.toml index 64751eaf1fea..7718f16984da 100644 --- a/compiler/rustc_lint/Cargo.toml +++ b/compiler/rustc_lint/Cargo.toml @@ -8,7 +8,6 @@ edition = "2024" rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 152971c4ed69..c893b7233755 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -21,14 +21,14 @@ use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_ast::visit::{FnCtxt, FnKind}; use rustc_ast::{self as ast, *}; use rustc_ast_pretty::pprust::expr_to_string; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_errors::{Applicability, LintDiagnostic}; use rustc_feature::GateIssue; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_hir::intravisit::FnKind as HirFnKind; -use rustc_hir::{Body, FnDecl, PatKind, PredicateOrigin}; +use rustc_hir::{Body, FnDecl, PatKind, PredicateOrigin, find_attr}; use rustc_middle::bug; use rustc_middle::lint::LevelAndSource; use rustc_middle::ty::layout::LayoutOf; diff --git a/compiler/rustc_lint/src/dangling.rs b/compiler/rustc_lint/src/dangling.rs index c737919db9c2..9e19949c3b6e 100644 --- a/compiler/rustc_lint/src/dangling.rs +++ b/compiler/rustc_lint/src/dangling.rs @@ -1,8 +1,8 @@ use rustc_ast::visit::{visit_opt, walk_list}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{FnKind, Visitor, walk_expr}; -use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, LangItem}; +use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, LangItem, find_attr}; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_session::{declare_lint, impl_lint_pass}; use rustc_span::{Span, sym}; diff --git a/compiler/rustc_lint/src/default_could_be_derived.rs b/compiler/rustc_lint/src/default_could_be_derived.rs index b5fc083a0958..7c39d8917cef 100644 --- a/compiler/rustc_lint/src/default_could_be_derived.rs +++ b/compiler/rustc_lint/src/default_could_be_derived.rs @@ -1,7 +1,8 @@ -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Applicability, Diag}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::find_attr; use rustc_middle::ty; use rustc_middle::ty::TyCtxt; use rustc_session::{declare_lint, impl_lint_pass}; diff --git a/compiler/rustc_lint/src/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index d6c402d481f4..759e6c927b82 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -1,9 +1,10 @@ use rustc_abi::FIRST_VARIANT; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; +use rustc_hir::find_attr; use rustc_middle::query::Providers; use rustc_middle::ty::{self, AdtDef, Instance, Ty, TyCtxt}; use rustc_session::declare_lint; diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index 76e374deef6a..7e5f43ba77f4 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -1,11 +1,11 @@ use rustc_abi::ExternAbi; -use rustc_attr_data_structures::{AttributeKind, ReprAttr, find_attr}; use rustc_attr_parsing::AttributeParser; use rustc_errors::Applicability; +use rustc_hir::attrs::{AttributeKind, ReprAttr}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{FnKind, Visitor}; -use rustc_hir::{AttrArgs, AttrItem, Attribute, GenericParamKind, PatExprKind, PatKind}; +use rustc_hir::{AttrArgs, AttrItem, Attribute, GenericParamKind, PatExprKind, PatKind, find_attr}; use rustc_middle::hir::nested_filter::All; use rustc_middle::ty; use rustc_session::config::CrateType; diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index a3cf3d568b1c..4f65acd8001e 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -1,6 +1,6 @@ -use rustc_attr_data_structures::{AttributeKind, find_attr}; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::Res; -use rustc_hir::{self as hir, AmbigArg, GenericArg, PathSegment, QPath, TyKind}; +use rustc_hir::{self as hir, AmbigArg, GenericArg, PathSegment, QPath, TyKind, find_attr}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; diff --git a/compiler/rustc_lint/src/types/literal.rs b/compiler/rustc_lint/src/types/literal.rs index 2bac58ba23d0..e8826b997320 100644 --- a/compiler/rustc_lint/src/types/literal.rs +++ b/compiler/rustc_lint/src/types/literal.rs @@ -1,11 +1,11 @@ use hir::{ExprKind, Node, is_range_literal}; use rustc_abi::{Integer, Size}; -use rustc_hir::HirId; +use rustc_hir::{HirId, attrs}; use rustc_middle::ty::Ty; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::{bug, ty}; use rustc_span::Span; -use {rustc_ast as ast, rustc_attr_data_structures as attrs, rustc_hir as hir}; +use {rustc_ast as ast, rustc_hir as hir}; use crate::LateContext; use crate::context::LintContext; diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 00e40b515a32..22d89d246127 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -2,12 +2,12 @@ use std::iter; use rustc_ast::util::{classify, parser}; use rustc_ast::{self as ast, ExprKind, FnRetTy, HasAttrs as _, StmtKind}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{MultiSpan, pluralize}; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; -use rustc_hir::{self as hir, LangItem}; +use rustc_hir::{self as hir, LangItem, find_attr}; use rustc_infer::traits::util::elaborate; use rustc_middle::ty::{self, Ty, adjustment}; use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass}; diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 101f5ccb7a47..803b3621c887 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -187,7 +187,7 @@ decl_derive! { decl_derive! { [PrintAttribute] => /// Derives `PrintAttribute` for `AttributeKind`. - /// This macro is pretty specific to `rustc_attr_data_structures` and likely not that useful in + /// This macro is pretty specific to `rustc_hir::attrs` and likely not that useful in /// other places. It's deriving something close to `Debug` without printing some extraneous /// things like spans. print_attribute::print_attribute diff --git a/compiler/rustc_metadata/Cargo.toml b/compiler/rustc_metadata/Cargo.toml index 0edc1d18ecc7..1b40d9f684ef 100644 --- a/compiler/rustc_metadata/Cargo.toml +++ b/compiler/rustc_metadata/Cargo.toml @@ -10,7 +10,6 @@ libloading = "0.8.0" odht = { version = "0.3.1", features = ["nightly"] } rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index ed0f084ea83c..8855766ca98f 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -3,9 +3,10 @@ use std::path::{Path, PathBuf}; use rustc_abi::ExternAbi; use rustc_ast::CRATE_NODE_ID; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_attr_parsing as attr; use rustc_data_structures::fx::FxHashSet; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::find_attr; use rustc_middle::query::LocalCrate; use rustc_middle::ty::{self, List, Ty, TyCtxt}; use rustc_session::Session; diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 9415e420eed5..0f3896fd9be8 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -2,7 +2,7 @@ use std::any::Any; use std::mem; use std::sync::Arc; -use rustc_attr_data_structures::Deprecation; +use rustc_hir::attrs::Deprecation; use rustc_hir::def::{CtorKind, DefKind}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE}; use rustc_hir::definitions::{DefKey, DefPath, DefPathHash}; diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 4075bee707c0..ff9f77be9455 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -5,7 +5,6 @@ use std::io::{Read, Seek, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; -use rustc_attr_data_structures::{AttributeKind, EncodeCrossCrate, find_attr}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::memmap::{Mmap, MmapMut}; use rustc_data_structures::sync::{join, par_for_each_in}; @@ -13,8 +12,10 @@ use rustc_data_structures::temp_dir::MaybeTempDir; use rustc_data_structures::thousands::usize_with_underscores; use rustc_feature::Features; use rustc_hir as hir; +use rustc_hir::attrs::{AttributeKind, EncodeCrossCrate}; use rustc_hir::def_id::{CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId, LocalDefIdSet}; use rustc_hir::definitions::DefPathData; +use rustc_hir::find_attr; use rustc_hir_pretty::id_to_string; use rustc_middle::dep_graph::WorkProductId; use rustc_middle::middle::dependency_format::Linkage; diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 9de5e12d5bb6..99174e4ad2fd 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -8,14 +8,14 @@ use encoder::EncodeContext; pub use encoder::{EncodedMetadata, encode_metadata, rendered_const}; pub(crate) use parameterized::ParameterizedOverTcx; use rustc_abi::{FieldIdx, ReprOptions, VariantIdx}; -use rustc_attr_data_structures::StrippedCfgItem; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::svh::Svh; -use rustc_hir::PreciseCapturingArgKind; +use rustc_hir::attrs::StrippedCfgItem; use rustc_hir::def::{CtorKind, DefKind, DocLinkResMap}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIndex, DefPathHash, StableCrateId}; use rustc_hir::definitions::DefKey; use rustc_hir::lang_items::LangItem; +use rustc_hir::{PreciseCapturingArgKind, attrs}; use rustc_index::IndexVec; use rustc_index::bit_set::DenseBitSet; use rustc_macros::{ @@ -39,7 +39,7 @@ use rustc_span::hygiene::{ExpnIndex, MacroKind, SyntaxContextKey}; use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Ident, Span, Symbol}; use rustc_target::spec::{PanicStrategy, TargetTuple}; use table::TableBuilder; -use {rustc_ast as ast, rustc_attr_data_structures as attrs, rustc_hir as hir}; +use {rustc_ast as ast, rustc_hir as hir}; use crate::creader::CrateMetadataRef; @@ -188,7 +188,7 @@ type ExpnHashTable = LazyTable>>; #[derive(MetadataEncodable, MetadataDecodable)] pub(crate) struct ProcMacroData { proc_macro_decls_static: DefIndex, - stability: Option, + stability: Option, macros: LazyArray, } @@ -410,9 +410,9 @@ define_tables! { safety: Table, def_span: Table>, def_ident_span: Table>, - lookup_stability: Table>, - lookup_const_stability: Table>, - lookup_default_body_stability: Table>, + lookup_stability: Table>, + lookup_const_stability: Table>, + lookup_default_body_stability: Table>, lookup_deprecation_entry: Table>, explicit_predicates_of: Table>>, generics_of: Table>, diff --git a/compiler/rustc_metadata/src/rmeta/parameterized.rs b/compiler/rustc_metadata/src/rmeta/parameterized.rs index 7cd399baa42e..d632e65104a7 100644 --- a/compiler/rustc_metadata/src/rmeta/parameterized.rs +++ b/compiler/rustc_metadata/src/rmeta/parameterized.rs @@ -79,19 +79,19 @@ trivially_parameterized_over_tcx! { crate::rmeta::VariantData, rustc_abi::ReprOptions, rustc_ast::DelimArgs, - rustc_attr_data_structures::ConstStability, - rustc_attr_data_structures::DefaultBodyStability, - rustc_attr_data_structures::Deprecation, - rustc_attr_data_structures::Stability, - rustc_attr_data_structures::StrippedCfgItem, rustc_hir::Attribute, + rustc_hir::ConstStability, rustc_hir::Constness, rustc_hir::CoroutineKind, + rustc_hir::DefaultBodyStability, rustc_hir::Defaultness, rustc_hir::LangItem, rustc_hir::OpaqueTyOrigin, rustc_hir::PreciseCapturingArgKind, rustc_hir::Safety, + rustc_hir::Stability, + rustc_hir::attrs::Deprecation, + rustc_hir::attrs::StrippedCfgItem, rustc_hir::def::DefKind, rustc_hir::def::DocLinkResMap, rustc_hir::def_id::DefId, diff --git a/compiler/rustc_middle/Cargo.toml b/compiler/rustc_middle/Cargo.toml index edd0af6e4f53..fbcce16cedca 100644 --- a/compiler/rustc_middle/Cargo.toml +++ b/compiler/rustc_middle/Cargo.toml @@ -14,7 +14,6 @@ rustc_apfloat = "0.2.0" rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } rustc_ast_ir = { path = "../rustc_ast_ir" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_error_messages = { path = "../rustc_error_messages" } # Used for intra-doc links rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index 43a7af9ce380..4b6e38cd52dd 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -110,7 +110,7 @@ macro_rules! arena_types { [] external_constraints: rustc_middle::traits::solve::ExternalConstraintsData>, [] predefined_opaques_in_body: rustc_middle::traits::solve::PredefinedOpaquesData>, [decode] doc_link_resolutions: rustc_hir::def::DocLinkResMap, - [] stripped_cfg_items: rustc_attr_data_structures::StrippedCfgItem, + [] stripped_cfg_items: rustc_hir::attrs::StrippedCfgItem, [] mod_child: rustc_middle::metadata::ModChild, [] features: rustc_feature::Features, [decode] specialization_graph: rustc_middle::traits::specialization_graph::Graph, diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index 42a1e7377f4b..3683d1e251cb 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -4,11 +4,11 @@ use rustc_abi::ExternAbi; use rustc_ast::visit::{VisitorResult, walk_list}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::svh::Svh; use rustc_data_structures::sync::{DynSend, DynSync, par_for_each_in, try_par_for_each_in}; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId, LocalModDefId}; use rustc_hir::definitions::{DefKey, DefPath, DefPathHash}; diff --git a/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs b/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs index 34a29acdc85a..94384e64afd1 100644 --- a/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs +++ b/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use rustc_abi::Align; use rustc_ast::expand::autodiff_attrs::AutoDiffAttrs; -use rustc_attr_data_structures::{InlineAttr, InstructionSetAttr, OptimizeAttr}; +use rustc_hir::attrs::{InlineAttr, InstructionSetAttr, OptimizeAttr}; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_span::Symbol; use rustc_target::spec::SanitizerSet; diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index dc9311188e80..4a19cf1563cf 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -4,13 +4,11 @@ use std::num::NonZero; use rustc_ast::NodeId; -use rustc_attr_data_structures::{ - self as attrs, ConstStability, DefaultBodyStability, DeprecatedSince, Deprecation, Stability, -}; use rustc_errors::{Applicability, Diag, EmissionGuarantee}; use rustc_feature::GateIssue; +use rustc_hir::attrs::{DeprecatedSince, Deprecation}; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::{self as hir, HirId}; +use rustc_hir::{self as hir, ConstStability, DefaultBodyStability, HirId, Stability}; use rustc_macros::{Decodable, Encodable, HashStable, Subdiagnostic}; use rustc_session::Session; use rustc_session::lint::builtin::{DEPRECATED, DEPRECATED_IN_FUTURE, SOFT_UNSTABLE}; @@ -368,7 +366,7 @@ impl<'tcx> TyCtxt<'tcx> { match stability { Some(Stability { - level: attrs::StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. }, + level: hir::StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. }, feature, .. }) => { @@ -451,7 +449,7 @@ impl<'tcx> TyCtxt<'tcx> { match stability { Some(DefaultBodyStability { - level: attrs::StabilityLevel::Unstable { reason, issue, is_soft, .. }, + level: hir::StabilityLevel::Unstable { reason, issue, is_soft, .. }, feature, }) => { if span.allows_unstable(feature) { @@ -600,7 +598,7 @@ impl<'tcx> TyCtxt<'tcx> { match stability { Some(ConstStability { - level: attrs::StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. }, + level: hir::StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. }, feature, .. }) => { diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 105736b9e243..e5864660575c 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -3,7 +3,6 @@ use std::fmt; use std::hash::Hash; use rustc_ast::expand::autodiff_attrs::AutoDiffItem; -use rustc_attr_data_structures::InlineAttr; use rustc_data_structures::base_n::{BaseNString, CASE_INSENSITIVE, ToBaseN}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxIndexMap; @@ -11,6 +10,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHas use rustc_data_structures::unord::UnordMap; use rustc_hashes::Hash128; use rustc_hir::ItemId; +use rustc_hir::attrs::InlineAttr; use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, LOCAL_CRATE}; use rustc_index::Idx; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index dab5900b4ab1..a8b357bf105b 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -246,9 +246,9 @@ trivial! { bool, Option<(rustc_span::def_id::DefId, rustc_session::config::EntryFnType)>, Option, - Option, - Option, - Option, + Option, + Option, + Option, Option, Option, Option, @@ -272,13 +272,12 @@ trivial! { Result, rustc_abi::ReprOptions, rustc_ast::expand::allocator::AllocatorKind, - rustc_attr_data_structures::ConstStability, - rustc_attr_data_structures::DefaultBodyStability, - rustc_attr_data_structures::Deprecation, - rustc_attr_data_structures::Stability, + rustc_hir::DefaultBodyStability, + rustc_hir::attrs::Deprecation, rustc_data_structures::svh::Svh, rustc_errors::ErrorGuaranteed, rustc_hir::Constness, + rustc_hir::ConstStability, rustc_hir::def_id::DefId, rustc_hir::def_id::DefIndex, rustc_hir::def_id::LocalDefId, @@ -293,6 +292,7 @@ trivial! { rustc_hir::LangItem, rustc_hir::OpaqueTyOrigin, rustc_hir::OwnerId, + rustc_hir::Stability, rustc_hir::Upvar, rustc_index::bit_set::FiniteBitSet, rustc_middle::middle::dependency_format::Linkage, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 587349d4cf41..b02433d2feb1 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -70,7 +70,6 @@ use std::sync::Arc; use rustc_abi::Align; use rustc_arena::TypedArena; use rustc_ast::expand::allocator::AllocatorKind; -use rustc_attr_data_structures::StrippedCfgItem; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; @@ -78,6 +77,7 @@ use rustc_data_structures::steal::Steal; use rustc_data_structures::svh::Svh; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::ErrorGuaranteed; +use rustc_hir::attrs::StrippedCfgItem; use rustc_hir::def::{DefKind, DocLinkResMap}; use rustc_hir::def_id::{ CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap, LocalDefIdSet, LocalModDefId, @@ -101,7 +101,7 @@ use rustc_span::def_id::LOCAL_CRATE; use rustc_span::source_map::Spanned; use rustc_span::{DUMMY_SP, Span, Symbol}; use rustc_target::spec::PanicStrategy; -use {rustc_abi as abi, rustc_ast as ast, rustc_attr_data_structures as attr, rustc_hir as hir}; +use {rustc_abi as abi, rustc_ast as ast, rustc_hir as hir}; use crate::infer::canonical::{self, Canonical}; use crate::lint::LintExpectation; @@ -1454,19 +1454,19 @@ rustc_queries! { cache_on_disk_if { true } } - query lookup_stability(def_id: DefId) -> Option { + query lookup_stability(def_id: DefId) -> Option { desc { |tcx| "looking up stability of `{}`", tcx.def_path_str(def_id) } cache_on_disk_if { def_id.is_local() } separate_provide_extern } - query lookup_const_stability(def_id: DefId) -> Option { + query lookup_const_stability(def_id: DefId) -> Option { desc { |tcx| "looking up const stability of `{}`", tcx.def_path_str(def_id) } cache_on_disk_if { def_id.is_local() } separate_provide_extern } - query lookup_default_body_stability(def_id: DefId) -> Option { + query lookup_default_body_stability(def_id: DefId) -> Option { desc { |tcx| "looking up default body stability of `{}`", tcx.def_path_str(def_id) } separate_provide_extern } diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 3bf80d37e656..df82c7a826be 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -4,15 +4,15 @@ use std::ops::Range; use std::str; use rustc_abi::{FIRST_VARIANT, ReprOptions, VariantIdx}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, HashingControls, StableHasher}; use rustc_errors::ErrorGuaranteed; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; -use rustc_hir::{self as hir, LangItem}; +use rustc_hir::{self as hir, LangItem, find_attr}; use rustc_index::{IndexSlice, IndexVec}; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_query_system::ich::StableHashingContext; diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index 1d15e4de7b69..a902a8a61e5a 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -1,8 +1,9 @@ -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::sorted_map::SortedIndexMultiMap; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Namespace}; use rustc_hir::def_id::DefId; +use rustc_hir::find_attr; use rustc_macros::{Decodable, Encodable, HashStable}; use rustc_span::{Ident, Symbol}; diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 6f21160d1f66..f4ee3d7971c3 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -17,7 +17,6 @@ use std::{fmt, iter, mem}; use rustc_abi::{ExternAbi, FieldIdx, Layout, LayoutData, TargetDataLayout, VariantIdx}; use rustc_ast as ast; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::defer; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; @@ -33,12 +32,13 @@ use rustc_data_structures::sync::{ use rustc_errors::{ Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, LintDiagnostic, LintEmitter, MultiSpan, }; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind}; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::definitions::{DefPathData, Definitions, DisambiguatorState}; use rustc_hir::intravisit::VisitorExt; use rustc_hir::lang_items::LangItem; -use rustc_hir::{self as hir, Attribute, HirId, Node, TraitCandidate}; +use rustc_hir::{self as hir, Attribute, HirId, Node, TraitCandidate, find_attr}; use rustc_index::IndexVec; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_query_system::cache::WithDepNode; diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index d5767ca3786e..eb35a9520326 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -212,7 +212,7 @@ impl<'tcx> Instance<'tcx> { if !tcx.sess.opts.share_generics() // However, if the def_id is marked inline(never), then it's fine to just reuse the // upstream monomorphization. - && tcx.codegen_fn_attrs(self.def_id()).inline != rustc_attr_data_structures::InlineAttr::Never + && tcx.codegen_fn_attrs(self.def_id()).inline != rustc_hir::attrs::InlineAttr::Never { return None; } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index fe41aaa8e3d2..2e91adeef7b1 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -27,17 +27,17 @@ pub use intrinsic::IntrinsicDef; use rustc_abi::{Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, VariantIdx}; use rustc_ast::node_id::NodeMap; pub use rustc_ast_ir::{Movability, Mutability, try_visit}; -use rustc_attr_data_structures::{AttributeKind, StrippedCfgItem, find_attr}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::steal::Steal; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::{Diag, ErrorGuaranteed}; -use rustc_hir::LangItem; +use rustc_hir::attrs::{AttributeKind, StrippedCfgItem}; use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap}; use rustc_hir::definitions::DisambiguatorState; +use rustc_hir::{LangItem, attrs as attr, find_attr}; use rustc_index::IndexVec; use rustc_index::bit_set::BitMatrix; use rustc_macros::{ @@ -65,7 +65,7 @@ pub use rustc_type_ir::*; use rustc_type_ir::{InferCtxtLike, Interner}; use tracing::{debug, instrument}; pub use vtable::*; -use {rustc_ast as ast, rustc_attr_data_structures as attr, rustc_hir as hir}; +use {rustc_ast as ast, rustc_hir as hir}; pub use self::closure::{ BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo, @@ -1459,7 +1459,7 @@ impl<'tcx> TyCtxt<'tcx> { } if let Some(reprs) = - attr::find_attr!(self.get_all_attrs(did), AttributeKind::Repr { reprs, .. } => reprs) + find_attr!(self.get_all_attrs(did), AttributeKind::Repr { reprs, .. } => reprs) { for (r, _) in reprs { flags.insert(match *r { @@ -1716,7 +1716,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Gets all attributes. /// /// To see if an item has a specific attribute, you should use - /// [`rustc_attr_data_structures::find_attr!`] so you can use matching. + /// [`rustc_hir::find_attr!`] so you can use matching. pub fn get_all_attrs(self, did: impl Into) -> &'tcx [hir::Attribute] { let did: DefId = did.into(); if let Some(did) = did.as_local() { diff --git a/compiler/rustc_mir_build/Cargo.toml b/compiler/rustc_mir_build/Cargo.toml index c4c2d8a7ac8e..1534865cdd34 100644 --- a/compiler/rustc_mir_build/Cargo.toml +++ b/compiler/rustc_mir_build/Cargo.toml @@ -11,7 +11,6 @@ rustc_abi = { path = "../rustc_abi" } rustc_apfloat = "0.2.0" rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 16df58cd76df..a0d3913c1595 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -1,10 +1,11 @@ use itertools::Itertools; use rustc_abi::{FIRST_VARIANT, FieldIdx}; use rustc_ast::UnsafeBinderCastKind; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; +use rustc_hir::find_attr; use rustc_index::Idx; use rustc_middle::hir::place::{ Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind, diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 91fcbb9390f7..a501cdf88c20 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -2,10 +2,11 @@ use core::ops::ControlFlow; use rustc_abi::{FieldIdx, VariantIdx}; use rustc_apfloat::Float; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Diag; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; +use rustc_hir::find_attr; use rustc_index::Idx; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::Obligation; diff --git a/compiler/rustc_mir_transform/Cargo.toml b/compiler/rustc_mir_transform/Cargo.toml index a7d0b3acbe49..08c43a4648c6 100644 --- a/compiler/rustc_mir_transform/Cargo.toml +++ b/compiler/rustc_mir_transform/Cargo.toml @@ -10,7 +10,6 @@ itertools = "0.12" rustc_abi = { path = "../rustc_abi" } rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_const_eval = { path = "../rustc_const_eval" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_mir_transform/src/check_inline.rs b/compiler/rustc_mir_transform/src/check_inline.rs index 14d9532894fd..af6da209081b 100644 --- a/compiler/rustc_mir_transform/src/check_inline.rs +++ b/compiler/rustc_mir_transform/src/check_inline.rs @@ -1,7 +1,7 @@ //! Check that a body annotated with `#[rustc_force_inline]` will not fail to inline based on its //! definition alone (irrespective of any specific caller). -use rustc_attr_data_structures::InlineAttr; +use rustc_hir::attrs::InlineAttr; use rustc_hir::def_id::DefId; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir::{Body, TerminatorKind}; diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 73795e47d2e9..c195ca51540d 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -1,4 +1,5 @@ -use rustc_attr_data_structures::{AttributeKind, CoverageAttrKind, find_attr}; +use rustc_hir::attrs::{AttributeKind, CoverageAttrKind}; +use rustc_hir::find_attr; use rustc_index::bit_set::DenseBitSet; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir::coverage::{BasicCoverageBlock, CoverageIdsInfo, CoverageKind, MappingKind}; diff --git a/compiler/rustc_mir_transform/src/cross_crate_inline.rs b/compiler/rustc_mir_transform/src/cross_crate_inline.rs index 6d7b7e10ef69..b186c2bd7758 100644 --- a/compiler/rustc_mir_transform/src/cross_crate_inline.rs +++ b/compiler/rustc_mir_transform/src/cross_crate_inline.rs @@ -1,4 +1,4 @@ -use rustc_attr_data_structures::InlineAttr; +use rustc_hir::attrs::InlineAttr; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_middle::mir::visit::Visitor; diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 1c0fc7748675..3d49eb4e8ef7 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -5,7 +5,7 @@ use std::iter; use std::ops::{Range, RangeFrom}; use rustc_abi::{ExternAbi, FieldIdx}; -use rustc_attr_data_structures::{InlineAttr, OptimizeAttr}; +use rustc_hir::attrs::{InlineAttr, OptimizeAttr}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_index::Idx; diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index 98d12bf0a38b..99e4782e4700 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -1,9 +1,9 @@ //! Validates the MIR to ensure that invariants are upheld. use rustc_abi::{ExternAbi, FIRST_VARIANT, Size}; -use rustc_attr_data_structures::InlineAttr; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::LangItem; +use rustc_hir::attrs::InlineAttr; use rustc_index::IndexVec; use rustc_index::bit_set::DenseBitSet; use rustc_infer::infer::TyCtxtInferExt; diff --git a/compiler/rustc_monomorphize/Cargo.toml b/compiler/rustc_monomorphize/Cargo.toml index 063fc8f1c749..0ed5b4fc0d09 100644 --- a/compiler/rustc_monomorphize/Cargo.toml +++ b/compiler/rustc_monomorphize/Cargo.toml @@ -7,7 +7,6 @@ edition = "2024" # tidy-alphabetical-start rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 1bfd83d97ac4..35b80a9b96f4 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -208,11 +208,11 @@ use std::cell::OnceCell; use std::path::PathBuf; -use rustc_attr_data_structures::InlineAttr; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync::{MTLock, par_for_each_in}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; +use rustc_hir::attrs::InlineAttr; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId}; use rustc_hir::lang_items::LangItem; diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index cee15e0f6969..d76b27d9970b 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -100,11 +100,11 @@ use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; -use rustc_attr_data_structures::InlineAttr; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sync; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir::LangItem; +use rustc_hir::attrs::InlineAttr; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, DefIdSet, LOCAL_CRATE}; use rustc_hir::definitions::DefPathDataName; diff --git a/compiler/rustc_passes/Cargo.toml b/compiler/rustc_passes/Cargo.toml index 503fc98da76d..ba81ef3103bd 100644 --- a/compiler/rustc_passes/Cargo.toml +++ b/compiler/rustc_passes/Cargo.toml @@ -9,7 +9,6 @@ rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_ast_lowering = { path = "../rustc_ast_lowering" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 0b329cc38b07..ede74bdc0df6 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -11,10 +11,6 @@ use std::slice; use rustc_abi::{Align, ExternAbi, Size}; use rustc_ast::{AttrStyle, LitKind, MetaItemInner, MetaItemKind, ast, join_path_syms}; -use rustc_attr_data_structures::{ - AttributeKind, InlineAttr, PartialConstStability, ReprAttr, Stability, StabilityLevel, - find_attr, -}; use rustc_attr_parsing::{AttributeParser, Late}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Applicability, DiagCtxtHandle, IntoDiagArg, MultiSpan, StashKey}; @@ -22,12 +18,14 @@ use rustc_feature::{ ACCEPTED_LANG_FEATURES, AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute, }; +use rustc_hir::attrs::{AttributeKind, InlineAttr, ReprAttr}; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalModDefId; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{ - self as hir, self, Attribute, CRATE_HIR_ID, CRATE_OWNER_ID, FnSig, ForeignItem, HirId, Item, - ItemKind, MethodKind, Safety, Target, TraitItem, + self as hir, Attribute, CRATE_HIR_ID, CRATE_OWNER_ID, FnSig, ForeignItem, HirId, Item, + ItemKind, MethodKind, PartialConstStability, Safety, Stability, StabilityLevel, Target, + TraitItem, find_attr, }; use rustc_macros::LintDiagnostic; use rustc_middle::hir::nested_filter; diff --git a/compiler/rustc_passes/src/check_export.rs b/compiler/rustc_passes/src/check_export.rs index b1f4584c2a88..6eded3a9eb9a 100644 --- a/compiler/rustc_passes/src/check_export.rs +++ b/compiler/rustc_passes/src/check_export.rs @@ -2,11 +2,12 @@ use std::iter; use std::ops::ControlFlow; use rustc_abi::ExternAbi; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::find_attr; use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::hir::nested_filter; use rustc_middle::middle::privacy::{EffectiveVisibility, Level}; diff --git a/compiler/rustc_passes/src/lib_features.rs b/compiler/rustc_passes/src/lib_features.rs index 35d2a655991e..8d0ef88610af 100644 --- a/compiler/rustc_passes/src/lib_features.rs +++ b/compiler/rustc_passes/src/lib_features.rs @@ -4,9 +4,9 @@ //! but are not declared in one single location (unlike lang features), which means we need to //! collect them instead. -use rustc_attr_data_structures::{AttributeKind, StabilityLevel, StableSince}; -use rustc_hir::Attribute; +use rustc_hir::attrs::AttributeKind; use rustc_hir::intravisit::Visitor; +use rustc_hir::{Attribute, StabilityLevel, StableSince}; use rustc_middle::hir::nested_filter; use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures}; use rustc_middle::query::{LocalCrate, Providers}; diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index 7350c6a5a82f..801a533c9433 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -85,13 +85,13 @@ use std::io; use std::io::prelude::*; use std::rc::Rc; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::*; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{Expr, HirId, HirIdMap, HirIdSet}; +use rustc_hir::{Expr, HirId, HirIdMap, HirIdSet, find_attr}; use rustc_index::IndexVec; use rustc_middle::query::Providers; use rustc_middle::span_bug; diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 9ed7293873f5..c5056b9df76c 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -4,17 +4,18 @@ use std::num::NonZero; use rustc_ast_lowering::stability::extern_abi_stability; -use rustc_attr_data_structures::{ - self as attrs, AttributeKind, ConstStability, DefaultBodyStability, DeprecatedSince, Stability, - StabilityLevel, StableSince, UnstableReason, VERSION_PLACEHOLDER, find_attr, -}; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet}; use rustc_feature::{EnabledLangFeature, EnabledLibFeature}; +use rustc_hir::attrs::{AttributeKind, DeprecatedSince}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, Visitor, VisitorExt}; -use rustc_hir::{self as hir, AmbigArg, FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant}; +use rustc_hir::{ + self as hir, AmbigArg, ConstStability, DefaultBodyStability, FieldDef, Item, ItemKind, + Stability, StabilityLevel, StableSince, TraitRef, Ty, TyKind, UnstableReason, + VERSION_PLACEHOLDER, Variant, find_attr, +}; use rustc_middle::hir::nested_filter; use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures}; use rustc_middle::middle::privacy::EffectiveVisibilities; @@ -96,7 +97,7 @@ fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind { fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); - let depr = attrs::find_attr!(attrs, + let depr = find_attr!(attrs, AttributeKind::Deprecation { deprecation, span: _ } => *deprecation ); @@ -128,7 +129,7 @@ fn inherit_stability(def_kind: DefKind) -> bool { /// while maintaining the invariant that all sysroot crates are unstable /// by default and are unable to be used. const FORCE_UNSTABLE: Stability = Stability { - level: attrs::StabilityLevel::Unstable { + level: StabilityLevel::Unstable { reason: UnstableReason::Default, issue: NonZero::new(27812), is_soft: false, @@ -161,8 +162,7 @@ fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { // # Regular stability let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); - let stab = - attrs::find_attr!(attrs, AttributeKind::Stability { stability, span: _ } => *stability); + let stab = find_attr!(attrs, AttributeKind::Stability { stability, span: _ } => *stability); if let Some(stab) = stab { return Some(stab); @@ -197,7 +197,7 @@ fn lookup_default_body_stability( let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); // FIXME: check that this item can have body stability - attrs::find_attr!(attrs, AttributeKind::BodyStability { stability, .. } => *stability) + find_attr!(attrs, AttributeKind::BodyStability { stability, .. } => *stability) } #[instrument(level = "debug", skip(tcx))] @@ -224,7 +224,8 @@ fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option *stability); + let const_stab = + find_attr!(attrs, AttributeKind::ConstStability { stability, span: _ } => *stability); // After checking the immediate attributes, get rid of the span and compute implied // const stability: inherit feature gate from regular stability. @@ -376,7 +377,7 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { macro_rules! find_attr_span { ($name:ident) => {{ let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id)); - attrs::find_attr!(attrs, AttributeKind::$name { span, .. } => *span) + find_attr!(attrs, AttributeKind::$name { span, .. } => *span) }} } @@ -403,7 +404,7 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { // this is *almost surely* an accident. if let Some(depr) = depr && let DeprecatedSince::RustcVersion(dep_since) = depr.attr.since - && let attrs::StabilityLevel::Stable { since: stab_since, .. } = stab.level + && let StabilityLevel::Stable { since: stab_since, .. } = stab.level && let Some(span) = find_attr_span!(Stability) { let item_sp = self.tcx.def_span(def_id); @@ -644,10 +645,10 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { let features = self.tcx.features(); if features.staged_api() { let attrs = self.tcx.hir_attrs(item.hir_id()); - let stab = attrs::find_attr!(attrs, AttributeKind::Stability{stability, span} => (*stability, *span)); + let stab = find_attr!(attrs, AttributeKind::Stability{stability, span} => (*stability, *span)); // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem - let const_stab = attrs::find_attr!(attrs, AttributeKind::ConstStability{stability, ..} => *stability); + let const_stab = find_attr!(attrs, AttributeKind::ConstStability{stability, ..} => *stability); let unstable_feature_stab = find_attr!(attrs, AttributeKind::UnstableFeatureBound(i) => i) @@ -670,7 +671,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { // impl Foo for Bar {} // ``` if let Some(( - Stability { level: attrs::StabilityLevel::Unstable { .. }, feature }, + Stability { level: StabilityLevel::Unstable { .. }, feature }, span, )) = stab { diff --git a/compiler/rustc_privacy/Cargo.toml b/compiler/rustc_privacy/Cargo.toml index 109a7bf49fe6..c8bfdb913041 100644 --- a/compiler/rustc_privacy/Cargo.toml +++ b/compiler/rustc_privacy/Cargo.toml @@ -6,7 +6,6 @@ edition = "2024" [dependencies] # tidy-alphabetical-start rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index b4fa11a8eb37..e12e74c0f1a6 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -23,10 +23,12 @@ use rustc_ast::visit::{VisitorResult, try_visit}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::intern::Interned; use rustc_errors::{MultiSpan, listify}; +use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, InferKind, Visitor}; -use rustc_hir::{AmbigArg, ForeignItemId, ItemId, PatKind}; +use rustc_hir::{AmbigArg, ForeignItemId, ItemId, PatKind, find_attr}; use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level}; use rustc_middle::query::Providers; use rustc_middle::ty::print::PrintTraitRefExt as _; @@ -39,7 +41,6 @@ use rustc_session::lint; use rustc_span::hygiene::Transparency; use rustc_span::{Ident, Span, Symbol, sym}; use tracing::debug; -use {rustc_attr_data_structures as attrs, rustc_hir as hir}; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } @@ -495,7 +496,7 @@ impl<'tcx> EmbargoVisitor<'tcx> { let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id); let attrs = self.tcx.hir_attrs(hir_id); - if attrs::find_attr!(attrs, attrs::AttributeKind::MacroTransparency(x) => *x) + if find_attr!(attrs, AttributeKind::MacroTransparency(x) => *x) .unwrap_or(Transparency::fallback(md.macro_rules)) != Transparency::Opaque { diff --git a/compiler/rustc_query_system/Cargo.toml b/compiler/rustc_query_system/Cargo.toml index 3d2d879a7644..7480ba03474f 100644 --- a/compiler/rustc_query_system/Cargo.toml +++ b/compiler/rustc_query_system/Cargo.toml @@ -8,7 +8,6 @@ edition = "2024" parking_lot = "0.12" rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } diff --git a/compiler/rustc_query_system/src/ich/hcx.rs b/compiler/rustc_query_system/src/ich/hcx.rs index 96d0c02c4a64..be838f689e53 100644 --- a/compiler/rustc_query_system/src/ich/hcx.rs +++ b/compiler/rustc_query_system/src/ich/hcx.rs @@ -129,4 +129,3 @@ impl<'a> rustc_span::HashStableContext for StableHashingContext<'a> { } impl<'a> rustc_session::HashStableContext for StableHashingContext<'a> {} -impl<'a> rustc_attr_data_structures::HashStableContext for StableHashingContext<'a> {} diff --git a/compiler/rustc_resolve/Cargo.toml b/compiler/rustc_resolve/Cargo.toml index 1238ce0125a1..9ea9c58cfd17 100644 --- a/compiler/rustc_resolve/Cargo.toml +++ b/compiler/rustc_resolve/Cargo.toml @@ -11,7 +11,6 @@ pulldown-cmark = { version = "0.11", features = ["html"], default-features = fal rustc_arena = { path = "../rustc_arena" } rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_attr_data_structures = { path = "../rustc_attr_data_structures" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 7912345ec56a..82eae0888038 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -13,12 +13,12 @@ use rustc_ast::{ self as ast, AssocItem, AssocItemKind, Block, ConstItem, Delegation, Fn, ForeignItem, ForeignItemKind, Impl, Item, ItemKind, NodeId, StaticItem, StmtKind, TyAlias, }; -use rustc_attr_data_structures::{AttributeKind, MacroUseArgs}; use rustc_attr_parsing as attr; use rustc_attr_parsing::AttributeParser; use rustc_expand::base::ResolverExpand; use rustc_expand::expand::AstFragment; use rustc_hir::Attribute; +use rustc_hir::attrs::{AttributeKind, MacroUseArgs}; use rustc_hir::def::{self, *}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_index::bit_set::DenseBitSet; diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 3af69b28780d..b14a6edb7914 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -4,9 +4,6 @@ use rustc_ast::{ self as ast, CRATE_NODE_ID, Crate, ItemKind, ModKind, NodeId, Path, join_path_idents, }; use rustc_ast_pretty::pprust; -use rustc_attr_data_structures::{ - self as attr, AttributeKind, CfgEntry, Stability, StrippedCfgItem, find_attr, -}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::codes::*; @@ -15,10 +12,11 @@ use rustc_errors::{ report_ambiguity_error, struct_span_code_err, }; use rustc_feature::BUILTIN_ATTRIBUTES; -use rustc_hir::PrimTy; +use rustc_hir::attrs::{AttributeKind, CfgEntry, StrippedCfgItem}; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; +use rustc_hir::{PrimTy, Stability, StabilityLevel, find_attr}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_session::Session; @@ -1362,9 +1360,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { match self.tcx.lookup_stability(did) { Some(Stability { - level: attr::StabilityLevel::Unstable { implied_by, .. }, - feature, - .. + level: StabilityLevel::Unstable { implied_by, .. }, feature, .. }) => { if span.allows_unstable(feature) { true diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index a70ae4fd57a0..dbde6f7cfd7e 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -41,7 +41,6 @@ use rustc_ast::{ self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, NodeId, Path, attr, }; -use rustc_attr_data_structures::StrippedCfgItem; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::steal::Steal; @@ -50,6 +49,7 @@ use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed}; use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind}; use rustc_feature::BUILTIN_ATTRIBUTES; +use rustc_hir::attrs::StrippedCfgItem; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{ self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS, diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 20504ea609df..4e3c0cd5bc00 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -8,7 +8,6 @@ use std::sync::Arc; use rustc_ast::{self as ast, Crate, NodeId, attr}; use rustc_ast_pretty::pprust; -use rustc_attr_data_structures::{CfgEntry, StabilityLevel, StrippedCfgItem}; use rustc_errors::{Applicability, DiagCtxtHandle, StashKey}; use rustc_expand::base::{ Annotatable, DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension, @@ -18,6 +17,8 @@ use rustc_expand::expand::{ AstFragment, AstFragmentKind, Invocation, InvocationKind, SupportsMacroExpansion, }; use rustc_expand::{MacroRulesMacroExpander, compile_declarative_macro}; +use rustc_hir::StabilityLevel; +use rustc_hir::attrs::{CfgEntry, StrippedCfgItem}; use rustc_hir::def::{self, DefKind, Namespace, NonMacroAttrKind}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_middle::middle::stability; diff --git a/compiler/rustc_trait_selection/Cargo.toml b/compiler/rustc_trait_selection/Cargo.toml index 62f1d9086015..1071105522d1 100644 --- a/compiler/rustc_trait_selection/Cargo.toml +++ b/compiler/rustc_trait_selection/Cargo.toml @@ -8,7 +8,6 @@ edition = "2024" itertools = "0.12" rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } -rustc_attr_data_structures = {path = "../rustc_attr_data_structures"} rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } 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 db35c988bf7f..8e0620f20487 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 @@ -1,8 +1,9 @@ -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect}; use rustc_errors::{Diag, MultiSpan, pluralize}; use rustc_hir as hir; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; +use rustc_hir::find_attr; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fast_reject::DeepRejectCtxt; diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 14295ce0a31d..743ed2b50453 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -36,13 +36,13 @@ use std::mem; use rustc_ast::token::{Token, TokenKind}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; -use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry}; use rustc_errors::codes::*; use rustc_errors::{FatalError, struct_span_code_err}; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LOCAL_CRATE, LocalDefId}; -use rustc_hir::{LangItem, PredicateOrigin}; +use rustc_hir::{LangItem, PredicateOrigin, find_attr}; use rustc_hir_analysis::hir_ty_lowering::FeedConstTy; use rustc_hir_analysis::{lower_const_arg_for_rustdoc, lower_ty}; use rustc_middle::metadata::Reexport; diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 7d0d2e62c853..db93dfd328aa 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -6,14 +6,12 @@ use std::{fmt, iter}; use arrayvec::ArrayVec; use itertools::Either; use rustc_abi::{ExternAbi, VariantIdx}; -use rustc_attr_data_structures::{ - AttributeKind, ConstStability, Deprecation, Stability, StableSince, find_attr, -}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; +use rustc_hir::attrs::{AttributeKind, DeprecatedSince, Deprecation}; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::lang_items::LangItem; -use rustc_hir::{BodyId, Mutability}; +use rustc_hir::{BodyId, ConstStability, Mutability, Stability, StableSince, find_attr}; use rustc_index::IndexVec; use rustc_metadata::rendered_const; use rustc_middle::span_bug; @@ -387,13 +385,13 @@ impl Item { // versions; the paths that are exposed through it are "deprecated" because they // were never supposed to work at all. let stab = self.stability(tcx)?; - if let rustc_attr_data_structures::StabilityLevel::Stable { + if let rustc_hir::StabilityLevel::Stable { allowed_through_unstable_modules: Some(note), .. } = stab.level { Some(Deprecation { - since: rustc_attr_data_structures::DeprecatedSince::Unspecified, + since: DeprecatedSince::Unspecified, note: Some(note), suggestion: None, }) diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index e28cc3a542e5..80399cf3842a 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -1,8 +1,8 @@ use std::mem; use rustc_ast::join_path_syms; -use rustc_attr_data_structures::StabilityLevel; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; +use rustc_hir::StabilityLevel; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet}; use rustc_metadata::creader::CStore; use rustc_middle::ty::{self, TyCtxt}; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index be8a2d511e91..0f23413074f4 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -15,11 +15,11 @@ use std::slice; use itertools::{Either, Itertools}; use rustc_abi::ExternAbi; use rustc_ast::join_path_syms; -use rustc_attr_data_structures::{ConstStability, StabilityLevel, StableSince}; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; +use rustc_hir::{ConstStability, StabilityLevel, StableSince}; use rustc_metadata::creader::{CStore, LoadedMacro}; use rustc_middle::ty::{self, TyCtxt, TypingMode}; use rustc_span::symbol::kw; diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 872dbbcd19e1..a46253237db2 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -50,12 +50,10 @@ use std::{fs, str}; use askama::Template; use itertools::Either; use rustc_ast::join_path_syms; -use rustc_attr_data_structures::{ - ConstStability, DeprecatedSince, Deprecation, RustcVersion, StabilityLevel, StableSince, -}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; -use rustc_hir::Mutability; +use rustc_hir::attrs::{DeprecatedSince, Deprecation}; use rustc_hir::def_id::{DefId, DefIdSet}; +use rustc_hir::{ConstStability, Mutability, RustcVersion, StabilityLevel, StableSince}; use rustc_middle::ty::print::PrintTraitRefExt; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::symbol::{Symbol, sym}; diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 08bc0bb19505..031d018c8b3e 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -4,8 +4,8 @@ use rustc_abi::ExternAbi; use rustc_ast::ast; -use rustc_attr_data_structures::{self as attrs, DeprecatedSince}; use rustc_hir as hir; +use rustc_hir::attrs::{self, DeprecatedSince}; use rustc_hir::def::CtorKind; use rustc_hir::def_id::DefId; use rustc_hir::{HeaderSafety, Safety}; diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 7431ff8e1ade..28dbd8ba7d3a 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -32,7 +32,6 @@ extern crate pulldown_cmark; extern crate rustc_abi; extern crate rustc_ast; extern crate rustc_ast_pretty; -extern crate rustc_attr_data_structures; extern crate rustc_attr_parsing; extern crate rustc_data_structures; extern crate rustc_driver; diff --git a/src/librustdoc/passes/propagate_stability.rs b/src/librustdoc/passes/propagate_stability.rs index 7b3da8d7c0fb..14ec58702e35 100644 --- a/src/librustdoc/passes/propagate_stability.rs +++ b/src/librustdoc/passes/propagate_stability.rs @@ -6,8 +6,8 @@ //! [`core::error`] module is marked as stable since 1.81.0, so we want to show //! [`core::error::Error`] as stable since 1.81.0 as well. -use rustc_attr_data_structures::{Stability, StabilityLevel}; use rustc_hir::def_id::CRATE_DEF_ID; +use rustc_hir::{Stability, StabilityLevel}; use crate::clean::{Crate, Item, ItemId, ItemKind}; use crate::core::DocContext; diff --git a/src/tools/clippy/clippy_lints/src/approx_const.rs b/src/tools/clippy/clippy_lints/src/approx_const.rs index 184fbbf77962..ab47e3097524 100644 --- a/src/tools/clippy/clippy_lints/src/approx_const.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs b/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs index 7b4cf0336741..d6469d32931d 100644 --- a/src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/attrs/inline_always.rs b/src/tools/clippy/clippy_lints/src/attrs/inline_always.rs index b8f93ee5e2c1..409bb698665f 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/inline_always.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/attrs/repr_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/repr_attributes.rs index 3e8808cec617..4ece3ed44fdf 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/repr_attributes.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/booleans.rs b/src/tools/clippy/clippy_lints/src/booleans.rs index 61c2fc49bd70..ba1135d745ae 100644 --- a/src/tools/clippy/clippy_lints/src/booleans.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/default_union_representation.rs b/src/tools/clippy/clippy_lints/src/default_union_representation.rs index 9bf2144e445d..f41255e54db6 100644 --- a/src/tools/clippy/clippy_lints/src/default_union_representation.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/doc/suspicious_doc_comments.rs b/src/tools/clippy/clippy_lints/src/doc/suspicious_doc_comments.rs index ebfc9972aefd..1e7d1f92fa31 100644 --- a/src/tools/clippy/clippy_lints/src/doc/suspicious_doc_comments.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/doc/too_long_first_doc_paragraph.rs b/src/tools/clippy/clippy_lints/src/doc/too_long_first_doc_paragraph.rs index 7f7224ecfc65..32ba696b3ec7 100644 --- a/src/tools/clippy/clippy_lints/src/doc/too_long_first_doc_paragraph.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index 9b627678bd35..ba539d05b6be 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/exhaustive_items.rs b/src/tools/clippy/clippy_lints/src/exhaustive_items.rs index 8ad092790718..5f40e5764435 100644 --- a/src/tools/clippy/clippy_lints/src/exhaustive_items.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/format_args.rs b/src/tools/clippy/clippy_lints/src/format_args.rs index a251f15ba3da..af4202422e44 100644 --- a/src/tools/clippy/clippy_lints/src/format_args.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index b8d0cec5aeb1..55ca0d9ecb71 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs b/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs index 116d63c3bb15..85ebc830d3bc 100644 --- a/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs b/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs index ffe6ad14f630..ee59a4cc8cb7 100644 --- a/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index 96a6dee58852..914aa6b9b804 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index 3aa449f64118..bf89556fbb61 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs b/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs index 2d52a93f34e3..6b0f74468492 100644 --- a/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/missing_inline.rs b/src/tools/clippy/clippy_lints/src/missing_inline.rs index 5a5025973b5b..c637fb247ff2 100644 --- a/src/tools/clippy/clippy_lints/src/missing_inline.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/no_mangle_with_rust_abi.rs b/src/tools/clippy/clippy_lints/src/no_mangle_with_rust_abi.rs index dee8efeb2910..791bbbe30a8e 100644 --- a/src/tools/clippy/clippy_lints/src/no_mangle_with_rust_abi.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index b8005dfd6f8e..303c5dfed891 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -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/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs index 3497216d1c56..2cdb8ef3a654 100644 --- a/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs +++ b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs @@ -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/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs b/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs index 216f168471e6..50c44a8e75c4 100644 --- a/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs b/src/tools/clippy/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs index 41fafc08c259..e0ae0c11cc2d 100644 --- a/src/tools/clippy/clippy_lints_internal/src/derive_deserialize_allowing_unknown.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_lints_internal/src/lib.rs b/src/tools/clippy/clippy_lints_internal/src/lib.rs index 0c94d100c417..43cde86504f5 100644 --- a/src/tools/clippy/clippy_lints_internal/src/lib.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/attrs.rs b/src/tools/clippy/clippy_utils/src/attrs.rs index 34472eaab93c..4ccd9c5300b1 100644 --- a/src/tools/clippy/clippy_utils/src/attrs.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 67e09e772a77..5b9b0ef30014 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/msrvs.rs b/src/tools/clippy/clippy_utils/src/msrvs.rs index 24ed4c3a8bec..480e0687756f 100644 --- a/src/tools/clippy/clippy_utils/src/msrvs.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index 11c17a77b154..79116eba971a 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/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/src/tools/clippy/clippy_utils/src/ty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/mod.rs index d70232ef3aa5..02a8eda5893e 100644 --- a/src/tools/clippy/clippy_utils/src/ty/mod.rs +++ b/src/tools/clippy/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}; diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index 507d4f7b4289..1de0e5f48c6a 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -57,7 +57,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_const_eval; extern crate rustc_data_structures; extern crate rustc_errors; diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 8f0814a070cb..00c3373bb0f3 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -12,7 +12,7 @@ use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; use rustc_abi::{Align, ExternAbi, Size}; use rustc_apfloat::{Float, FloatConvert}; -use rustc_attr_data_structures::InlineAttr; +use rustc_hir::attrs::InlineAttr; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; #[allow(unused)] use rustc_data_structures::static_assert_size; diff --git a/triagebot.toml b/triagebot.toml index e1b4983adf7b..168815465b61 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -269,7 +269,7 @@ trigger_files = [ "compiler/rustc_codegen_ssa/src/codegen_attrs.rs", "compiler/rustc_passes/src/check_attr.rs", "compiler/rustc_attr_parsing", - "compiler/rustc_attr_data_structures", + "compiler/rustc_hir/src/attrs", ] [autolabel."A-compiler-builtins"] @@ -1261,13 +1261,11 @@ cc = ["@ehuss"] message = "The rustc-dev-guide subtree was changed. If this PR *only* touches the dev guide consider submitting a PR directly to [rust-lang/rustc-dev-guide](https://github.com/rust-lang/rustc-dev-guide/pulls) otherwise thank you for updating the dev guide with your changes." cc = ["@BoxyUwU", "@jieyouxu", "@kobzol", "@tshepang"] -[mentions."compiler/rustc_codegen_ssa/src/codegen_attrs.rs"] -cc = ["@jdonszelmann"] [mentions."compiler/rustc_passes/src/check_attr.rs"] cc = ["@jdonszelmann"] [mentions."compiler/rustc_attr_parsing"] cc = ["@jdonszelmann"] -[mentions."compiler/rustc_attr_data_structures"] +[mentions."compiler/rustc_hir/src/attrs"] cc = ["@jdonszelmann"] [mentions."src/tools/enzyme"] 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 385/809] 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 386/809] 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 935fdb6980f0f4133a26a91aefe81b4e2cea01c9 Mon Sep 17 00:00:00 2001 From: Scott Schafer Date: Tue, 29 Jul 2025 03:41:09 -0600 Subject: [PATCH 387/809] fix: Match width of ascii and unicode secondary file start --- compiler/rustc_errors/src/emitter.rs | 2 +- tests/ui/error-emitter/close_window.unicode.stderr | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 3fe525df94f4..8794bf930fd6 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -2988,7 +2988,7 @@ impl HumanEmitter { fn secondary_file_start(&self) -> &'static str { match self.theme { OutputTheme::Ascii => "::: ", - OutputTheme::Unicode => " ⸬ ", + OutputTheme::Unicode => " ⸬ ", } } diff --git a/tests/ui/error-emitter/close_window.unicode.stderr b/tests/ui/error-emitter/close_window.unicode.stderr index 56ab6daa278d..b4aa78a5ac91 100644 --- a/tests/ui/error-emitter/close_window.unicode.stderr +++ b/tests/ui/error-emitter/close_window.unicode.stderr @@ -4,7 +4,7 @@ error[E0624]: method `method` is private LL │ s.method(); │ ━━━━━━ private method │ - ⸬ $DIR/auxiliary/close_window.rs:3:5 + ⸬ $DIR/auxiliary/close_window.rs:3:5 │ LL │ fn method(&self) {} ╰╴ ──────────────── private method defined here From 26c03e206a7c45f5767d5f2eb521d9961a4aeaf5 Mon Sep 17 00:00:00 2001 From: lcnr Date: Mon, 28 Jul 2025 09:34:44 +0000 Subject: [PATCH 388/809] 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 389/809] 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 bb08a4dfc784ad5558e42db3b41b4abbebafc5a9 Mon Sep 17 00:00:00 2001 From: Stypox Date: Thu, 31 Jul 2025 15:36:44 +0200 Subject: [PATCH 390/809] Make Miri's enter_trace_span! call const_eval's --- .../rustc_const_eval/src/interpret/util.rs | 8 +++---- src/tools/miri/src/helpers.rs | 23 ++++--------------- src/tools/miri/src/lib.rs | 4 +--- 3 files changed, 9 insertions(+), 26 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/util.rs b/compiler/rustc_const_eval/src/interpret/util.rs index 341756f837ee..6696a0c50260 100644 --- a/compiler/rustc_const_eval/src/interpret/util.rs +++ b/compiler/rustc_const_eval/src/interpret/util.rs @@ -114,11 +114,11 @@ impl EnteredTraceSpan for tracing::span::EnteredSpan {} /// ``` #[macro_export] macro_rules! enter_trace_span { - ($machine:ident, $name:ident :: $subname:ident $($tt:tt)*) => {{ + ($machine:ty, $name:ident :: $subname:ident $($tt:tt)*) => { $crate::enter_trace_span!($machine, stringify!($name), $name = %stringify!($subname) $($tt)*) - }}; + }; - ($machine:ident, $($tt:tt)*) => { + ($machine:ty, $($tt:tt)*) => { <$machine as $crate::interpret::Machine>::enter_trace_span(|| tracing::info_span!($($tt)*)) - } + }; } diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index c52796d358de..43cb1c9ae053 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -1245,29 +1245,14 @@ impl ToU64 for usize { } } -/// This struct is needed to enforce `#[must_use]` on values produced by [enter_trace_span] even -/// when the "tracing" feature is not enabled. -#[must_use] -pub struct MaybeEnteredTraceSpan { - #[cfg(feature = "tracing")] - pub _entered_span: tracing::span::EnteredSpan, -} - /// Enters a [tracing::info_span] only if the "tracing" feature is enabled, otherwise does nothing. -/// This is like [rustc_const_eval::enter_trace_span] except that it does not depend on the -/// [Machine] trait to check if tracing is enabled, because from the Miri codebase we can directly -/// check whether the "tracing" feature is enabled, unlike from the rustc_const_eval codebase. +/// This calls [rustc_const_eval::enter_trace_span] with [MiriMachine] as the first argument, which +/// will in turn call [MiriMachine::enter_trace_span], which takes care of determining at compile +/// time whether to trace or not (and supposedly the call is compiled out if tracing is disabled). /// Look at [rustc_const_eval::enter_trace_span] for complete documentation, examples and tips. #[macro_export] macro_rules! enter_trace_span { - ($name:ident :: $subname:ident $($tt:tt)*) => {{ - $crate::enter_trace_span!(stringify!($name), $name = %stringify!($subname) $($tt)*) - }}; - ($($tt:tt)*) => { - $crate::MaybeEnteredTraceSpan { - #[cfg(feature = "tracing")] - _entered_span: tracing::info_span!($($tt)*).entered() - } + rustc_const_eval::enter_trace_span!($crate::MiriMachine<'static>, $($tt)*) }; } diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index 507d4f7b4289..8d34b8fc23ad 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -143,9 +143,7 @@ pub use crate::eval::{ AlignmentCheck, BacktraceStyle, IsolatedOp, MiriConfig, MiriEntryFnType, RejectOpWith, ValidationMode, create_ecx, eval_entry, }; -pub use crate::helpers::{ - AccessKind, EvalContextExt as _, MaybeEnteredTraceSpan, ToU64 as _, ToUsize as _, -}; +pub use crate::helpers::{AccessKind, EvalContextExt as _, ToU64 as _, ToUsize as _}; pub use crate::intrinsics::EvalContextExt as _; pub use crate::machine::{ AllocExtra, DynMachineCallback, FrameExtra, MachineCallback, MemoryKind, MiriInterpCx, From 42c520d631ef2eb3cb44b8490b8330b6651bd22f Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Thu, 31 Jul 2025 10:03:06 -0400 Subject: [PATCH 391/809] Update cargo --- src/tools/cargo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/cargo b/src/tools/cargo index 9b296973b425..840b83a10fb0 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 9b296973b425ffb159e12cf3cd56580fd5c85382 +Subproject commit 840b83a10fb0e039a83f4d70ad032892c287570a From 9f7a8f8f9efb57af1f46faf45086201c50e1afde Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Wed, 30 Jul 2025 20:31:27 +0500 Subject: [PATCH 392/809] 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 393/809] 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 a4a5bf5a71bd0c3fb52a28f81d88ce1755b3bc30 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Thu, 24 Jul 2025 17:22:54 +0500 Subject: [PATCH 394/809] comments --- .../deref-chain-method-calls-13264.rs} | 2 + ...lts.rs => blocks-without-results-11709.rs} | 2 + .../moved-value-in-thread-loop-12041.rs} | 2 + .../moved-value-in-thread-loop-12041.stderr} | 2 +- ....rs => refcell-borrow-comparison-12033.rs} | 2 + .../string-literal-match-patterns-11869.rs} | 2 + ...d-twice.rs => fnonce-moved-twice-12127.rs} | 2 + .../fnonce-moved-twice-12127.stderr} | 6 +-- ...ind.rs => moved-upvar-mut-rebind-11958.rs} | 2 + .../moved-upvar-mut-rebind-11958.stderr} | 4 +- .../any-trait-object-debug-12744.rs} | 2 + ...r.rs => hashset-connected-border-12860.rs} | 2 + .../vec-macro-in-static-array.rs | 2 + .../vec-macro-in-static-array.stderr} | 2 +- tests/ui/extern/format-message-windows-ffi.rs | 39 --------------- tests/ui/extern/windows-tcb-trash-13259.rs | 49 +++++++++++++++++++ ...rs => anonymous-parameters-trait-13105.rs} | 2 + ...clone.rs => bytes-iterator-clone-12677.rs} | 2 + ...=> iterator-trait-lifetime-error-13058.rs} | 2 + ...terator-trait-lifetime-error-13058.stderr} | 2 +- .../lifetime-inference-destructuring-arg.rs} | 2 + .../matcher-trait-equality-13323.rs} | 2 + ...struct-lifetime-field-assignment-13405.rs} | 2 + .../unsafe-transmute-in-find-11740.rs} | 2 + ...tch.rs => option-result-mismatch-11844.rs} | 2 + .../option-result-mismatch-11844.stderr} | 2 +- ...ption-result-type-param-mismatch-13466.rs} | 2 + ...n-result-type-param-mismatch-13466.stderr} | 4 +- ...s => overeager-sub-match-pruning-13027.rs} | 2 + ...error.rs => slice-move-out-error-12567.rs} | 2 + .../slice-move-out-error-12567.stderr} | 4 +- ....rs => struct-reference-patterns-12285.rs} | 2 + .../encode-symbol-ice-12920.rs} | 2 + .../privacy/private-unit-struct-assignment.rs | 2 + .../private-unit-struct-assignment.stderr} | 6 +-- .../use-in-impl-scope-12729.rs} | 2 + .../reference-clone-nonclone-11820.rs} | 2 + ... => enum-with-static-str-variant-13214.rs} | 2 + ...> default-method-lifetime-params-13204.rs} | 2 + ...pl.rs => fnonce-repro-trait-impl-13434.rs} | 2 + ...nference.rs => partial-type-hint-12909.rs} | 2 + .../function-in-pattern-error-12863.rs} | 2 + .../function-in-pattern-error-12863.stderr} | 2 +- .../isize-usize-mismatch-error.rs | 2 + .../isize-usize-mismatch-error.stderr} | 8 +-- .../unit-type-add-error-11771.rs} | 2 + .../unit-type-add-error-11771.stderr} | 4 +- .../unwrap-or-panic-input-13202.rs} | 2 + 48 files changed, 140 insertions(+), 62 deletions(-) rename tests/ui/{traits/deref-chain-method-calls.rs => autoref-autoderef/deref-chain-method-calls-13264.rs} (93%) rename tests/ui/block-result/{blocks-without-results.rs => blocks-without-results-11709.rs} (91%) rename tests/ui/{threads/moved-value-in-thread-loop.rs => borrowck/moved-value-in-thread-loop-12041.rs} (78%) rename tests/ui/{issues/issue-12041.stderr => borrowck/moved-value-in-thread-loop-12041.stderr} (87%) rename tests/ui/borrowck/{refcell-borrow-comparison.rs => refcell-borrow-comparison-12033.rs} (61%) rename tests/ui/{match/string-literal-match-patterns.rs => borrowck/string-literal-match-patterns-11869.rs} (75%) rename tests/ui/closures/{fnonce-moved-twice.rs => fnonce-moved-twice-12127.rs} (82%) rename tests/ui/{issues/issue-12127.stderr => closures/fnonce-moved-twice-12127.stderr} (62%) rename tests/ui/closures/{moved-upvar-mut-rebind.rs => moved-upvar-mut-rebind-11958.rs} (78%) rename tests/ui/{issues/issue-11958.stderr => closures/moved-upvar-mut-rebind-11958.stderr} (84%) rename tests/ui/{traits/any-trait-object-debug.rs => coercion/any-trait-object-debug-12744.rs} (62%) rename tests/ui/collections/{hashset-connected-border.rs => hashset-connected-border-12860.rs} (95%) rename tests/ui/{issues/issue-13446.stderr => const-generics/vec-macro-in-static-array.stderr} (90%) delete mode 100644 tests/ui/extern/format-message-windows-ffi.rs create mode 100644 tests/ui/extern/windows-tcb-trash-13259.rs rename tests/ui/fn/{anonymous-parameters-trait.rs => anonymous-parameters-trait-13105.rs} (61%) rename tests/ui/iterators/{bytes-iterator-clone.rs => bytes-iterator-clone-12677.rs} (71%) rename tests/ui/lifetimes/{iterator-trait-lifetime-error.rs => iterator-trait-lifetime-error-13058.rs} (90%) rename tests/ui/{issues/issue-13058.stderr => lifetimes/iterator-trait-lifetime-error-13058.stderr} (90%) rename tests/ui/{iterators/phf-map-entries-iterator.rs => lifetimes/lifetime-inference-destructuring-arg.rs} (88%) rename tests/ui/{traits/matcher-trait-equality.rs => lifetimes/matcher-trait-equality-13323.rs} (93%) rename tests/ui/lifetimes/{struct-lifetime-field-assignment.rs => struct-lifetime-field-assignment-13405.rs} (79%) rename tests/ui/{unsafe/unsafe-transmute-in-find.rs => lifetimes/unsafe-transmute-in-find-11740.rs} (87%) rename tests/ui/match/{option-result-mismatch.rs => option-result-mismatch-11844.rs} (69%) rename tests/ui/{issues/issue-11844.stderr => match/option-result-mismatch-11844.stderr} (90%) rename tests/ui/match/{option-result-type-param-mismatch.rs => option-result-type-param-mismatch-13466.rs} (91%) rename tests/ui/{issues/issue-13466.stderr => match/option-result-type-param-mismatch-13466.stderr} (87%) rename tests/ui/match/{guard-literal-range-shadow.rs => overeager-sub-match-pruning-13027.rs} (97%) rename tests/ui/match/{slice-move-out-error.rs => slice-move-out-error-12567.rs} (85%) rename tests/ui/{issues/issue-12567.stderr => match/slice-move-out-error-12567.stderr} (94%) rename tests/ui/match/{struct-reference-patterns.rs => struct-reference-patterns-12285.rs} (73%) rename tests/ui/{panics/explicit-panic-unreachable.rs => parser/encode-symbol-ice-12920.rs} (63%) rename tests/ui/{issues/issue-13407.stderr => privacy/private-unit-struct-assignment.stderr} (79%) rename tests/ui/{imports/use-in-impl-scope.rs => privacy/use-in-impl-scope-12729.rs} (68%) rename tests/ui/{traits/reference-clone-noclone.rs => resolve/reference-clone-nonclone-11820.rs} (73%) rename tests/ui/statics/{enum-with-static-str-variant.rs => enum-with-static-str-variant-13214.rs} (81%) rename tests/ui/traits/{default-method-lifetime-params.rs => default-method-lifetime-params-13204.rs} (88%) rename tests/ui/traits/{fnonce-repro-trait-impl.rs => fnonce-repro-trait-impl-13434.rs} (84%) rename tests/ui/type-inference/{type-collect-inference.rs => partial-type-hint-12909.rs} (86%) rename tests/ui/{match/function-in-pattern-error.rs => typeck/function-in-pattern-error-12863.rs} (71%) rename tests/ui/{issues/issue-12863.stderr => typeck/function-in-pattern-error-12863.stderr} (85%) rename tests/ui/{type-inference => typeck}/isize-usize-mismatch-error.rs (80%) rename tests/ui/{issues/issue-13359.stderr => typeck/isize-usize-mismatch-error.stderr} (85%) rename tests/ui/{type-inference/unit-type-add-error.rs => typeck/unit-type-add-error-11771.rs} (63%) rename tests/ui/{issues/issue-11771.stderr => typeck/unit-type-add-error-11771.stderr} (93%) rename tests/ui/{panics/unwrap-or-panic-input.rs => typeck/unwrap-or-panic-input-13202.rs} (65%) diff --git a/tests/ui/traits/deref-chain-method-calls.rs b/tests/ui/autoref-autoderef/deref-chain-method-calls-13264.rs similarity index 93% rename from tests/ui/traits/deref-chain-method-calls.rs rename to tests/ui/autoref-autoderef/deref-chain-method-calls-13264.rs index bf4ec388c4fd..f471c1c7eefc 100644 --- a/tests/ui/traits/deref-chain-method-calls.rs +++ b/tests/ui/autoref-autoderef/deref-chain-method-calls-13264.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13264 + //@ run-pass #![allow(non_camel_case_types)] #![allow(non_snake_case)] diff --git a/tests/ui/block-result/blocks-without-results.rs b/tests/ui/block-result/blocks-without-results-11709.rs similarity index 91% rename from tests/ui/block-result/blocks-without-results.rs rename to tests/ui/block-result/blocks-without-results-11709.rs index 8a11074eca8e..97ea6f9e19ed 100644 --- a/tests/ui/block-result/blocks-without-results.rs +++ b/tests/ui/block-result/blocks-without-results-11709.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11709 + //@ run-pass #![allow(dead_code)] diff --git a/tests/ui/threads/moved-value-in-thread-loop.rs b/tests/ui/borrowck/moved-value-in-thread-loop-12041.rs similarity index 78% rename from tests/ui/threads/moved-value-in-thread-loop.rs rename to tests/ui/borrowck/moved-value-in-thread-loop-12041.rs index 091e8fe8b2a6..98f9cdbdef79 100644 --- a/tests/ui/threads/moved-value-in-thread-loop.rs +++ b/tests/ui/borrowck/moved-value-in-thread-loop-12041.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12041 + use std::sync::mpsc::channel; use std::thread; diff --git a/tests/ui/issues/issue-12041.stderr b/tests/ui/borrowck/moved-value-in-thread-loop-12041.stderr similarity index 87% rename from tests/ui/issues/issue-12041.stderr rename to tests/ui/borrowck/moved-value-in-thread-loop-12041.stderr index f2c10b833836..627dd193dade 100644 --- a/tests/ui/issues/issue-12041.stderr +++ b/tests/ui/borrowck/moved-value-in-thread-loop-12041.stderr @@ -1,5 +1,5 @@ error[E0382]: use of moved value: `tx` - --> $DIR/issue-12041.rs:8:22 + --> $DIR/moved-value-in-thread-loop-12041.rs:10:22 | LL | let tx = tx; | ^^ value moved here, in previous iteration of loop diff --git a/tests/ui/borrowck/refcell-borrow-comparison.rs b/tests/ui/borrowck/refcell-borrow-comparison-12033.rs similarity index 61% rename from tests/ui/borrowck/refcell-borrow-comparison.rs rename to tests/ui/borrowck/refcell-borrow-comparison-12033.rs index 0bf6490bafed..de22cedd5b94 100644 --- a/tests/ui/borrowck/refcell-borrow-comparison.rs +++ b/tests/ui/borrowck/refcell-borrow-comparison-12033.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12033 + //@ run-pass use std::cell::RefCell; diff --git a/tests/ui/match/string-literal-match-patterns.rs b/tests/ui/borrowck/string-literal-match-patterns-11869.rs similarity index 75% rename from tests/ui/match/string-literal-match-patterns.rs rename to tests/ui/borrowck/string-literal-match-patterns-11869.rs index dd752227bbec..4c159e457cf1 100644 --- a/tests/ui/match/string-literal-match-patterns.rs +++ b/tests/ui/borrowck/string-literal-match-patterns-11869.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11869 + //@ check-pass #![allow(dead_code)] diff --git a/tests/ui/closures/fnonce-moved-twice.rs b/tests/ui/closures/fnonce-moved-twice-12127.rs similarity index 82% rename from tests/ui/closures/fnonce-moved-twice.rs rename to tests/ui/closures/fnonce-moved-twice-12127.rs index 199d542e816f..369ddcafaabd 100644 --- a/tests/ui/closures/fnonce-moved-twice.rs +++ b/tests/ui/closures/fnonce-moved-twice-12127.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12127 + #![feature(unboxed_closures, tuple_trait)] fn to_fn_once>(f: F) -> F { f } diff --git a/tests/ui/issues/issue-12127.stderr b/tests/ui/closures/fnonce-moved-twice-12127.stderr similarity index 62% rename from tests/ui/issues/issue-12127.stderr rename to tests/ui/closures/fnonce-moved-twice-12127.stderr index 2a6233547ee8..c2e12827527b 100644 --- a/tests/ui/issues/issue-12127.stderr +++ b/tests/ui/closures/fnonce-moved-twice-12127.stderr @@ -1,5 +1,5 @@ error[E0382]: use of moved value: `f` - --> $DIR/issue-12127.rs:11:9 + --> $DIR/fnonce-moved-twice-12127.rs:13:9 | LL | f(); | --- `f` moved due to this call @@ -7,11 +7,11 @@ LL | f(); | ^ value used here after move | note: this value implements `FnOnce`, which causes it to be moved when called - --> $DIR/issue-12127.rs:10:9 + --> $DIR/fnonce-moved-twice-12127.rs:12:9 | LL | f(); | ^ - = note: move occurs because `f` has type `{closure@$DIR/issue-12127.rs:8:24: 8:30}`, which does not implement the `Copy` trait + = note: move occurs because `f` has type `{closure@$DIR/fnonce-moved-twice-12127.rs:10:24: 10:30}`, which does not implement the `Copy` trait error: aborting due to 1 previous error diff --git a/tests/ui/closures/moved-upvar-mut-rebind.rs b/tests/ui/closures/moved-upvar-mut-rebind-11958.rs similarity index 78% rename from tests/ui/closures/moved-upvar-mut-rebind.rs rename to tests/ui/closures/moved-upvar-mut-rebind-11958.rs index 9185c5158af6..701dc1a2cefd 100644 --- a/tests/ui/closures/moved-upvar-mut-rebind.rs +++ b/tests/ui/closures/moved-upvar-mut-rebind-11958.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11958 + //@ run-pass // We shouldn't need to rebind a moved upvar as mut if it's already diff --git a/tests/ui/issues/issue-11958.stderr b/tests/ui/closures/moved-upvar-mut-rebind-11958.stderr similarity index 84% rename from tests/ui/issues/issue-11958.stderr rename to tests/ui/closures/moved-upvar-mut-rebind-11958.stderr index 5dca4c2f01d5..b12bbcad9258 100644 --- a/tests/ui/issues/issue-11958.stderr +++ b/tests/ui/closures/moved-upvar-mut-rebind-11958.stderr @@ -1,5 +1,5 @@ warning: value assigned to `x` is never read - --> $DIR/issue-11958.rs:8:36 + --> $DIR/moved-upvar-mut-rebind-11958.rs:10:36 | LL | let _thunk = Box::new(move|| { x = 2; }); | ^ @@ -8,7 +8,7 @@ LL | let _thunk = Box::new(move|| { x = 2; }); = note: `#[warn(unused_assignments)]` on by default warning: unused variable: `x` - --> $DIR/issue-11958.rs:8:36 + --> $DIR/moved-upvar-mut-rebind-11958.rs:10:36 | LL | let _thunk = Box::new(move|| { x = 2; }); | ^ diff --git a/tests/ui/traits/any-trait-object-debug.rs b/tests/ui/coercion/any-trait-object-debug-12744.rs similarity index 62% rename from tests/ui/traits/any-trait-object-debug.rs rename to tests/ui/coercion/any-trait-object-debug-12744.rs index eaf92d413d57..4d981c077ee2 100644 --- a/tests/ui/traits/any-trait-object-debug.rs +++ b/tests/ui/coercion/any-trait-object-debug-12744.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12744 + //@ run-pass fn main() { fn test() -> Box { Box::new(1) } diff --git a/tests/ui/collections/hashset-connected-border.rs b/tests/ui/collections/hashset-connected-border-12860.rs similarity index 95% rename from tests/ui/collections/hashset-connected-border.rs rename to tests/ui/collections/hashset-connected-border-12860.rs index 255f66707937..40185bef7c8d 100644 --- a/tests/ui/collections/hashset-connected-border.rs +++ b/tests/ui/collections/hashset-connected-border-12860.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12860 + //@ run-pass use std::collections::HashSet; diff --git a/tests/ui/const-generics/vec-macro-in-static-array.rs b/tests/ui/const-generics/vec-macro-in-static-array.rs index 9f1fc42774fb..7a81836e2556 100644 --- a/tests/ui/const-generics/vec-macro-in-static-array.rs +++ b/tests/ui/const-generics/vec-macro-in-static-array.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13446 + // Used to cause ICE static VEC: [u32; 256] = vec![]; diff --git a/tests/ui/issues/issue-13446.stderr b/tests/ui/const-generics/vec-macro-in-static-array.stderr similarity index 90% rename from tests/ui/issues/issue-13446.stderr rename to tests/ui/const-generics/vec-macro-in-static-array.stderr index 28c459e6e62c..de21f2274f3a 100644 --- a/tests/ui/issues/issue-13446.stderr +++ b/tests/ui/const-generics/vec-macro-in-static-array.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-13446.rs:3:26 + --> $DIR/vec-macro-in-static-array.rs:5:26 | LL | static VEC: [u32; 256] = vec![]; | ^^^^^^ expected `[u32; 256]`, found `Vec<_>` diff --git a/tests/ui/extern/format-message-windows-ffi.rs b/tests/ui/extern/format-message-windows-ffi.rs deleted file mode 100644 index 381e3f152590..000000000000 --- a/tests/ui/extern/format-message-windows-ffi.rs +++ /dev/null @@ -1,39 +0,0 @@ -//@ run-pass - -#[cfg(windows)] -mod imp { - type LPVOID = *mut u8; - type DWORD = u32; - type LPWSTR = *mut u16; - - extern "system" { - fn FormatMessageW(flags: DWORD, - lpSrc: LPVOID, - msgId: DWORD, - langId: DWORD, - buf: LPWSTR, - nsize: DWORD, - args: *const u8) - -> DWORD; - } - - pub fn test() { - let mut buf: [u16; 50] = [0; 50]; - let ret = unsafe { - FormatMessageW(0x1000, core::ptr::null_mut(), 1, 0x400, - buf.as_mut_ptr(), buf.len() as u32, core::ptr::null()) - }; - // On some 32-bit Windowses (Win7-8 at least) this will panic with segmented - // stacks taking control of pvArbitrary - assert!(ret != 0); - } -} - -#[cfg(not(windows))] -mod imp { - pub fn test() { } -} - -fn main() { - imp::test() -} diff --git a/tests/ui/extern/windows-tcb-trash-13259.rs b/tests/ui/extern/windows-tcb-trash-13259.rs new file mode 100644 index 000000000000..0852e31251ac --- /dev/null +++ b/tests/ui/extern/windows-tcb-trash-13259.rs @@ -0,0 +1,49 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13259 + +//@ run-pass + +#[cfg(windows)] +mod imp { + type LPVOID = *mut u8; + type DWORD = u32; + type LPWSTR = *mut u16; + + extern "system" { + fn FormatMessageW( + flags: DWORD, + lpSrc: LPVOID, + msgId: DWORD, + langId: DWORD, + buf: LPWSTR, + nsize: DWORD, + args: *const u8, + ) -> DWORD; + } + + pub fn test() { + let mut buf: [u16; 50] = [0; 50]; + let ret = unsafe { + FormatMessageW( + 0x1000, + core::ptr::null_mut(), + 1, + 0x400, + buf.as_mut_ptr(), + buf.len() as u32, + core::ptr::null(), + ) + }; + // On some 32-bit Windowses (Win7-8 at least) this will panic with segmented + // stacks taking control of pvArbitrary + assert!(ret != 0); + } +} + +#[cfg(not(windows))] +mod imp { + pub fn test() {} +} + +fn main() { + imp::test() +} diff --git a/tests/ui/fn/anonymous-parameters-trait.rs b/tests/ui/fn/anonymous-parameters-trait-13105.rs similarity index 61% rename from tests/ui/fn/anonymous-parameters-trait.rs rename to tests/ui/fn/anonymous-parameters-trait-13105.rs index d119aa9c788d..171dab15fe71 100644 --- a/tests/ui/fn/anonymous-parameters-trait.rs +++ b/tests/ui/fn/anonymous-parameters-trait-13105.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13105 + //@ edition: 2015 //@ check-pass diff --git a/tests/ui/iterators/bytes-iterator-clone.rs b/tests/ui/iterators/bytes-iterator-clone-12677.rs similarity index 71% rename from tests/ui/iterators/bytes-iterator-clone.rs rename to tests/ui/iterators/bytes-iterator-clone-12677.rs index dbc2dbc85276..cfbb85a3ecba 100644 --- a/tests/ui/iterators/bytes-iterator-clone.rs +++ b/tests/ui/iterators/bytes-iterator-clone-12677.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12677 + //@ run-pass fn main() { diff --git a/tests/ui/lifetimes/iterator-trait-lifetime-error.rs b/tests/ui/lifetimes/iterator-trait-lifetime-error-13058.rs similarity index 90% rename from tests/ui/lifetimes/iterator-trait-lifetime-error.rs rename to tests/ui/lifetimes/iterator-trait-lifetime-error-13058.rs index a5806feb720d..6cfe440b43d7 100644 --- a/tests/ui/lifetimes/iterator-trait-lifetime-error.rs +++ b/tests/ui/lifetimes/iterator-trait-lifetime-error-13058.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13058 + use std::ops::Range; trait Itble<'r, T, I: Iterator> { fn iter(&'r self) -> I; } diff --git a/tests/ui/issues/issue-13058.stderr b/tests/ui/lifetimes/iterator-trait-lifetime-error-13058.stderr similarity index 90% rename from tests/ui/issues/issue-13058.stderr rename to tests/ui/lifetimes/iterator-trait-lifetime-error-13058.stderr index 4f4108fa1825..e6564e36b215 100644 --- a/tests/ui/issues/issue-13058.stderr +++ b/tests/ui/lifetimes/iterator-trait-lifetime-error-13058.stderr @@ -1,5 +1,5 @@ error[E0621]: explicit lifetime required in the type of `cont` - --> $DIR/issue-13058.rs:14:21 + --> $DIR/iterator-trait-lifetime-error-13058.rs:16:21 | LL | let cont_iter = cont.iter(); | ^^^^^^^^^^^ lifetime `'r` required diff --git a/tests/ui/iterators/phf-map-entries-iterator.rs b/tests/ui/lifetimes/lifetime-inference-destructuring-arg.rs similarity index 88% rename from tests/ui/iterators/phf-map-entries-iterator.rs rename to tests/ui/lifetimes/lifetime-inference-destructuring-arg.rs index 5f733e859488..7a019a71d75c 100644 --- a/tests/ui/iterators/phf-map-entries-iterator.rs +++ b/tests/ui/lifetimes/lifetime-inference-destructuring-arg.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13167 + //@ check-pass //@ revisions: current next //@ ignore-compare-mode-next-solver (explicit revisions) diff --git a/tests/ui/traits/matcher-trait-equality.rs b/tests/ui/lifetimes/matcher-trait-equality-13323.rs similarity index 93% rename from tests/ui/traits/matcher-trait-equality.rs rename to tests/ui/lifetimes/matcher-trait-equality-13323.rs index 8f334404f9ab..efd56294b398 100644 --- a/tests/ui/traits/matcher-trait-equality.rs +++ b/tests/ui/lifetimes/matcher-trait-equality-13323.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13323 + //@ run-pass struct StrWrap { diff --git a/tests/ui/lifetimes/struct-lifetime-field-assignment.rs b/tests/ui/lifetimes/struct-lifetime-field-assignment-13405.rs similarity index 79% rename from tests/ui/lifetimes/struct-lifetime-field-assignment.rs rename to tests/ui/lifetimes/struct-lifetime-field-assignment-13405.rs index 80b298d2f37a..9482d89681b5 100644 --- a/tests/ui/lifetimes/struct-lifetime-field-assignment.rs +++ b/tests/ui/lifetimes/struct-lifetime-field-assignment-13405.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13405 + //@ check-pass #![allow(dead_code)] #![allow(unused_variables)] diff --git a/tests/ui/unsafe/unsafe-transmute-in-find.rs b/tests/ui/lifetimes/unsafe-transmute-in-find-11740.rs similarity index 87% rename from tests/ui/unsafe/unsafe-transmute-in-find.rs rename to tests/ui/lifetimes/unsafe-transmute-in-find-11740.rs index c6099c2a0c04..eeecd2e9e404 100644 --- a/tests/ui/unsafe/unsafe-transmute-in-find.rs +++ b/tests/ui/lifetimes/unsafe-transmute-in-find-11740.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11740 + //@ check-pass struct Attr { diff --git a/tests/ui/match/option-result-mismatch.rs b/tests/ui/match/option-result-mismatch-11844.rs similarity index 69% rename from tests/ui/match/option-result-mismatch.rs rename to tests/ui/match/option-result-mismatch-11844.rs index f974a4702960..24a2004134df 100644 --- a/tests/ui/match/option-result-mismatch.rs +++ b/tests/ui/match/option-result-mismatch-11844.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11844 + fn main() { let a = Some(Box::new(1)); match a { diff --git a/tests/ui/issues/issue-11844.stderr b/tests/ui/match/option-result-mismatch-11844.stderr similarity index 90% rename from tests/ui/issues/issue-11844.stderr rename to tests/ui/match/option-result-mismatch-11844.stderr index 9ff66eaef498..8a84b7b8a486 100644 --- a/tests/ui/issues/issue-11844.stderr +++ b/tests/ui/match/option-result-mismatch-11844.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-11844.rs:4:9 + --> $DIR/option-result-mismatch-11844.rs:6:9 | LL | match a { | - this expression has type `Option>` diff --git a/tests/ui/match/option-result-type-param-mismatch.rs b/tests/ui/match/option-result-type-param-mismatch-13466.rs similarity index 91% rename from tests/ui/match/option-result-type-param-mismatch.rs rename to tests/ui/match/option-result-type-param-mismatch-13466.rs index 78ce4c1d2f60..05dbdfdee0e3 100644 --- a/tests/ui/match/option-result-type-param-mismatch.rs +++ b/tests/ui/match/option-result-type-param-mismatch-13466.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13466 + // Regression test for #13466 //@ dont-require-annotations: NOTE diff --git a/tests/ui/issues/issue-13466.stderr b/tests/ui/match/option-result-type-param-mismatch-13466.stderr similarity index 87% rename from tests/ui/issues/issue-13466.stderr rename to tests/ui/match/option-result-type-param-mismatch-13466.stderr index 68a555a16260..b0cf1591f5ee 100644 --- a/tests/ui/issues/issue-13466.stderr +++ b/tests/ui/match/option-result-type-param-mismatch-13466.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-13466.rs:10:9 + --> $DIR/option-result-type-param-mismatch-13466.rs:12:9 | LL | let _x: usize = match Some(1) { | ------- this expression has type `Option<{integer}>` @@ -10,7 +10,7 @@ LL | Ok(u) => u, found enum `Result<_, _>` error[E0308]: mismatched types - --> $DIR/issue-13466.rs:16:9 + --> $DIR/option-result-type-param-mismatch-13466.rs:18:9 | LL | let _x: usize = match Some(1) { | ------- this expression has type `Option<{integer}>` diff --git a/tests/ui/match/guard-literal-range-shadow.rs b/tests/ui/match/overeager-sub-match-pruning-13027.rs similarity index 97% rename from tests/ui/match/guard-literal-range-shadow.rs rename to tests/ui/match/overeager-sub-match-pruning-13027.rs index fbd1d75067b5..c4feb697f7d1 100644 --- a/tests/ui/match/guard-literal-range-shadow.rs +++ b/tests/ui/match/overeager-sub-match-pruning-13027.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13027 + //@ run-pass // Tests that match expression handles overlapped literal and range diff --git a/tests/ui/match/slice-move-out-error.rs b/tests/ui/match/slice-move-out-error-12567.rs similarity index 85% rename from tests/ui/match/slice-move-out-error.rs rename to tests/ui/match/slice-move-out-error-12567.rs index 1b2a37de4753..3f9bf9c76cf3 100644 --- a/tests/ui/match/slice-move-out-error.rs +++ b/tests/ui/match/slice-move-out-error-12567.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12567 + fn match_vecs<'a, T>(l1: &'a [T], l2: &'a [T]) { match (l1, l2) { //~^ ERROR: cannot move out of type `[T]`, a non-copy slice diff --git a/tests/ui/issues/issue-12567.stderr b/tests/ui/match/slice-move-out-error-12567.stderr similarity index 94% rename from tests/ui/issues/issue-12567.stderr rename to tests/ui/match/slice-move-out-error-12567.stderr index 0b19299ece3e..ab5377d47013 100644 --- a/tests/ui/issues/issue-12567.stderr +++ b/tests/ui/match/slice-move-out-error-12567.stderr @@ -1,5 +1,5 @@ error[E0508]: cannot move out of type `[T]`, a non-copy slice - --> $DIR/issue-12567.rs:2:11 + --> $DIR/slice-move-out-error-12567.rs:4:11 | LL | match (l1, l2) { | ^^^^^^^^ cannot move out of here @@ -23,7 +23,7 @@ LL + (&[hd1, ..], [hd2, ..]) | error[E0508]: cannot move out of type `[T]`, a non-copy slice - --> $DIR/issue-12567.rs:2:11 + --> $DIR/slice-move-out-error-12567.rs:4:11 | LL | match (l1, l2) { | ^^^^^^^^ cannot move out of here diff --git a/tests/ui/match/struct-reference-patterns.rs b/tests/ui/match/struct-reference-patterns-12285.rs similarity index 73% rename from tests/ui/match/struct-reference-patterns.rs rename to tests/ui/match/struct-reference-patterns-12285.rs index fe199147128b..246e230b0de7 100644 --- a/tests/ui/match/struct-reference-patterns.rs +++ b/tests/ui/match/struct-reference-patterns-12285.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12285 + //@ run-pass struct S; diff --git a/tests/ui/panics/explicit-panic-unreachable.rs b/tests/ui/parser/encode-symbol-ice-12920.rs similarity index 63% rename from tests/ui/panics/explicit-panic-unreachable.rs rename to tests/ui/parser/encode-symbol-ice-12920.rs index f3b1b643c45a..87389c0ffb42 100644 --- a/tests/ui/panics/explicit-panic-unreachable.rs +++ b/tests/ui/parser/encode-symbol-ice-12920.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12920 + //@ run-fail //@ error-pattern:explicit panic //@ needs-subprocess diff --git a/tests/ui/privacy/private-unit-struct-assignment.rs b/tests/ui/privacy/private-unit-struct-assignment.rs index 7794be37b850..b8e1c4ecb188 100644 --- a/tests/ui/privacy/private-unit-struct-assignment.rs +++ b/tests/ui/privacy/private-unit-struct-assignment.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13407 + mod A { struct C; } diff --git a/tests/ui/issues/issue-13407.stderr b/tests/ui/privacy/private-unit-struct-assignment.stderr similarity index 79% rename from tests/ui/issues/issue-13407.stderr rename to tests/ui/privacy/private-unit-struct-assignment.stderr index ac2eb6581fe2..8c36a08846d8 100644 --- a/tests/ui/issues/issue-13407.stderr +++ b/tests/ui/privacy/private-unit-struct-assignment.stderr @@ -1,17 +1,17 @@ error[E0603]: unit struct `C` is private - --> $DIR/issue-13407.rs:6:8 + --> $DIR/private-unit-struct-assignment.rs:8:8 | LL | A::C = 1; | ^ private unit struct | note: the unit struct `C` is defined here - --> $DIR/issue-13407.rs:2:5 + --> $DIR/private-unit-struct-assignment.rs:4:5 | LL | struct C; | ^^^^^^^^^ error[E0308]: mismatched types - --> $DIR/issue-13407.rs:6:5 + --> $DIR/private-unit-struct-assignment.rs:8:5 | LL | struct C; | -------- unit struct defined here diff --git a/tests/ui/imports/use-in-impl-scope.rs b/tests/ui/privacy/use-in-impl-scope-12729.rs similarity index 68% rename from tests/ui/imports/use-in-impl-scope.rs rename to tests/ui/privacy/use-in-impl-scope-12729.rs index 4d45846bc608..58fe042beece 100644 --- a/tests/ui/imports/use-in-impl-scope.rs +++ b/tests/ui/privacy/use-in-impl-scope-12729.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12729 + //@ edition: 2015 //@ check-pass #![allow(dead_code)] diff --git a/tests/ui/traits/reference-clone-noclone.rs b/tests/ui/resolve/reference-clone-nonclone-11820.rs similarity index 73% rename from tests/ui/traits/reference-clone-noclone.rs rename to tests/ui/resolve/reference-clone-nonclone-11820.rs index ada844f8ee12..74dad96da94e 100644 --- a/tests/ui/traits/reference-clone-noclone.rs +++ b/tests/ui/resolve/reference-clone-nonclone-11820.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11820 + //@ run-pass #![allow(noop_method_call)] diff --git a/tests/ui/statics/enum-with-static-str-variant.rs b/tests/ui/statics/enum-with-static-str-variant-13214.rs similarity index 81% rename from tests/ui/statics/enum-with-static-str-variant.rs rename to tests/ui/statics/enum-with-static-str-variant-13214.rs index 8140ec943a01..1db37da632de 100644 --- a/tests/ui/statics/enum-with-static-str-variant.rs +++ b/tests/ui/statics/enum-with-static-str-variant-13214.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13214 + //@ build-pass #![allow(dead_code)] // defining static with struct that contains enum diff --git a/tests/ui/traits/default-method-lifetime-params.rs b/tests/ui/traits/default-method-lifetime-params-13204.rs similarity index 88% rename from tests/ui/traits/default-method-lifetime-params.rs rename to tests/ui/traits/default-method-lifetime-params-13204.rs index 01362f6fe61d..cdf34ab773c1 100644 --- a/tests/ui/traits/default-method-lifetime-params.rs +++ b/tests/ui/traits/default-method-lifetime-params-13204.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13204 + //@ run-pass #![allow(unused_mut)] // Test that when instantiating trait default methods, typeck handles diff --git a/tests/ui/traits/fnonce-repro-trait-impl.rs b/tests/ui/traits/fnonce-repro-trait-impl-13434.rs similarity index 84% rename from tests/ui/traits/fnonce-repro-trait-impl.rs rename to tests/ui/traits/fnonce-repro-trait-impl-13434.rs index caf7b6323933..61d5a1d74aee 100644 --- a/tests/ui/traits/fnonce-repro-trait-impl.rs +++ b/tests/ui/traits/fnonce-repro-trait-impl-13434.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13434 + //@ run-pass #[derive(Debug)] struct MyStruct; diff --git a/tests/ui/type-inference/type-collect-inference.rs b/tests/ui/type-inference/partial-type-hint-12909.rs similarity index 86% rename from tests/ui/type-inference/type-collect-inference.rs rename to tests/ui/type-inference/partial-type-hint-12909.rs index f2c33806aae8..d7017f451e32 100644 --- a/tests/ui/type-inference/type-collect-inference.rs +++ b/tests/ui/type-inference/partial-type-hint-12909.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12909 + //@ run-pass #![allow(unused_variables)] diff --git a/tests/ui/match/function-in-pattern-error.rs b/tests/ui/typeck/function-in-pattern-error-12863.rs similarity index 71% rename from tests/ui/match/function-in-pattern-error.rs rename to tests/ui/typeck/function-in-pattern-error-12863.rs index 1ac1c3d818e5..d2fa25556584 100644 --- a/tests/ui/match/function-in-pattern-error.rs +++ b/tests/ui/typeck/function-in-pattern-error-12863.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/12863 + mod foo { pub fn bar() {} } fn main() { diff --git a/tests/ui/issues/issue-12863.stderr b/tests/ui/typeck/function-in-pattern-error-12863.stderr similarity index 85% rename from tests/ui/issues/issue-12863.stderr rename to tests/ui/typeck/function-in-pattern-error-12863.stderr index 95d4a704e72d..f28874b5d485 100644 --- a/tests/ui/issues/issue-12863.stderr +++ b/tests/ui/typeck/function-in-pattern-error-12863.stderr @@ -1,5 +1,5 @@ error[E0532]: expected unit struct, unit variant or constant, found function `foo::bar` - --> $DIR/issue-12863.rs:5:9 + --> $DIR/function-in-pattern-error-12863.rs:7:9 | LL | foo::bar => {} | ^^^^^^^^ not a unit struct, unit variant or constant diff --git a/tests/ui/type-inference/isize-usize-mismatch-error.rs b/tests/ui/typeck/isize-usize-mismatch-error.rs similarity index 80% rename from tests/ui/type-inference/isize-usize-mismatch-error.rs rename to tests/ui/typeck/isize-usize-mismatch-error.rs index 5d31d7f861c6..2fb5cf489c03 100644 --- a/tests/ui/type-inference/isize-usize-mismatch-error.rs +++ b/tests/ui/typeck/isize-usize-mismatch-error.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13359 + //@ dont-require-annotations: NOTE fn foo(_s: i16) { } diff --git a/tests/ui/issues/issue-13359.stderr b/tests/ui/typeck/isize-usize-mismatch-error.stderr similarity index 85% rename from tests/ui/issues/issue-13359.stderr rename to tests/ui/typeck/isize-usize-mismatch-error.stderr index 91f5de8e8f3a..d5724665a03c 100644 --- a/tests/ui/issues/issue-13359.stderr +++ b/tests/ui/typeck/isize-usize-mismatch-error.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-13359.rs:8:9 + --> $DIR/isize-usize-mismatch-error.rs:10:9 | LL | foo(1*(1 as isize)); | --- ^^^^^^^^^^^^^^ expected `i16`, found `isize` @@ -7,7 +7,7 @@ LL | foo(1*(1 as isize)); | arguments to this function are incorrect | note: function defined here - --> $DIR/issue-13359.rs:3:4 + --> $DIR/isize-usize-mismatch-error.rs:5:4 | LL | fn foo(_s: i16) { } | ^^^ ------- @@ -17,7 +17,7 @@ LL | foo((1*(1 as isize)).try_into().unwrap()); | + +++++++++++++++++++++ error[E0308]: mismatched types - --> $DIR/issue-13359.rs:12:9 + --> $DIR/isize-usize-mismatch-error.rs:14:9 | LL | bar(1*(1 as usize)); | --- ^^^^^^^^^^^^^^ expected `u32`, found `usize` @@ -25,7 +25,7 @@ LL | bar(1*(1 as usize)); | arguments to this function are incorrect | note: function defined here - --> $DIR/issue-13359.rs:5:4 + --> $DIR/isize-usize-mismatch-error.rs:7:4 | LL | fn bar(_s: u32) { } | ^^^ ------- diff --git a/tests/ui/type-inference/unit-type-add-error.rs b/tests/ui/typeck/unit-type-add-error-11771.rs similarity index 63% rename from tests/ui/type-inference/unit-type-add-error.rs rename to tests/ui/typeck/unit-type-add-error-11771.rs index c69cd1e79e37..d009f50f4b92 100644 --- a/tests/ui/type-inference/unit-type-add-error.rs +++ b/tests/ui/typeck/unit-type-add-error-11771.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/11771 + fn main() { let x = (); 1 + diff --git a/tests/ui/issues/issue-11771.stderr b/tests/ui/typeck/unit-type-add-error-11771.stderr similarity index 93% rename from tests/ui/issues/issue-11771.stderr rename to tests/ui/typeck/unit-type-add-error-11771.stderr index 5603dc18b635..155cc0935245 100644 --- a/tests/ui/issues/issue-11771.stderr +++ b/tests/ui/typeck/unit-type-add-error-11771.stderr @@ -1,5 +1,5 @@ error[E0277]: cannot add `()` to `{integer}` - --> $DIR/issue-11771.rs:3:7 + --> $DIR/unit-type-add-error-11771.rs:5:7 | LL | 1 + | ^ no implementation for `{integer} + ()` @@ -17,7 +17,7 @@ LL | 1 + and 56 others error[E0277]: cannot add `()` to `{integer}` - --> $DIR/issue-11771.rs:8:7 + --> $DIR/unit-type-add-error-11771.rs:10:7 | LL | 1 + | ^ no implementation for `{integer} + ()` diff --git a/tests/ui/panics/unwrap-or-panic-input.rs b/tests/ui/typeck/unwrap-or-panic-input-13202.rs similarity index 65% rename from tests/ui/panics/unwrap-or-panic-input.rs rename to tests/ui/typeck/unwrap-or-panic-input-13202.rs index 99ffba3fba51..29833a727c55 100644 --- a/tests/ui/panics/unwrap-or-panic-input.rs +++ b/tests/ui/typeck/unwrap-or-panic-input-13202.rs @@ -1,3 +1,5 @@ +//! Regression test for https://github.com/rust-lang/rust/issues/13202 + //@ run-fail //@ error-pattern:bad input //@ needs-subprocess From 2f7a2fa00fd06f9a1dcd51891b11a255cbf9d32b Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 31 Jul 2025 19:33:12 +0300 Subject: [PATCH 395/809] 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 396/809] 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 d525e79157e32abc510714dd32628c9c155f2997 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 18 Jul 2025 18:17:15 +0000 Subject: [PATCH 397/809] Stall coroutines based off of ty::Coroutine, not ty::CoroutineWitness --- .../src/solve/trait_goals.rs | 11 +- .../src/solve/fulfill.rs | 2 +- .../src/traits/select/candidate_assembly.rs | 60 +++--- .../src/traits/select/mod.rs | 2 +- compiler/rustc_type_ir/src/flags.rs | 11 +- tests/ui/async-await/issue-70818.rs | 1 + tests/ui/async-await/issue-70818.stderr | 23 ++- tests/ui/async-await/issue-86507.stderr | 2 +- tests/ui/coroutine/clone-impl-async.rs | 6 +- tests/ui/coroutine/clone-impl-async.stderr | 180 ++++++++---------- tests/ui/coroutine/clone-impl-static.stderr | 12 +- tests/ui/coroutine/clone-impl.rs | 1 + tests/ui/coroutine/clone-impl.stderr | 88 ++++----- tests/ui/coroutine/ref-upvar-not-send.stderr | 14 +- .../ui/impl-trait/issues/issue-55872-3.stderr | 15 +- 15 files changed, 218 insertions(+), 210 deletions(-) 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..31991565b0dc 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -229,7 +229,7 @@ where } // We need to make sure to stall any coroutines we are inferring to avoid query cycles. - if let Some(cand) = ecx.try_stall_coroutine_witness(goal.predicate.self_ty()) { + if let Some(cand) = ecx.try_stall_coroutine(goal.predicate.self_ty()) { return cand; } @@ -294,7 +294,7 @@ where } // We need to make sure to stall any coroutines we are inferring to avoid query cycles. - if let Some(cand) = ecx.try_stall_coroutine_witness(goal.predicate.self_ty()) { + if let Some(cand) = ecx.try_stall_coroutine(goal.predicate.self_ty()) { return cand; } @@ -1432,11 +1432,8 @@ where self.merge_trait_candidates(candidates) } - fn try_stall_coroutine_witness( - &mut self, - self_ty: I::Ty, - ) -> Option, NoSolution>> { - if let ty::CoroutineWitness(def_id, _) = self_ty.kind() { + fn try_stall_coroutine(&mut self, self_ty: I::Ty) -> Option, NoSolution>> { + if let ty::Coroutine(def_id, _) = self_ty.kind() { match self.typing_mode() { TypingMode::Analysis { defining_opaque_types_and_generators: stalled_generators, diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 01bdae7435d7..3f628d806620 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -355,7 +355,7 @@ impl<'tcx> TypeVisitor> for StalledOnCoroutines<'tcx> { return ControlFlow::Continue(()); } - if let ty::CoroutineWitness(def_id, _) = *ty.kind() + if let ty::Coroutine(def_id, _) = *ty.kind() && def_id.as_local().is_some_and(|def_id| self.stalled_coroutines.contains(&def_id)) { ControlFlow::Break(()) diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 2c7089507a89..af6dafb30629 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -794,18 +794,25 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // The auto impl might apply; we don't know. candidates.ambiguous = true; } - ty::Coroutine(coroutine_def_id, _) - if self.tcx().is_lang_item(def_id, LangItem::Unpin) => - { - match self.tcx().coroutine_movability(coroutine_def_id) { - hir::Movability::Static => { - // Immovable coroutines are never `Unpin`, so - // suppress the normal auto-impl candidate for it. + ty::Coroutine(coroutine_def_id, _) => { + if self.tcx().is_lang_item(def_id, LangItem::Unpin) { + match self.tcx().coroutine_movability(coroutine_def_id) { + hir::Movability::Static => { + // Immovable coroutines are never `Unpin`, so + // suppress the normal auto-impl candidate for it. + } + hir::Movability::Movable => { + // Movable coroutines are always `Unpin`, so add an + // unconditional builtin candidate with no sub-obligations. + candidates.vec.push(BuiltinCandidate); + } } - hir::Movability::Movable => { - // Movable coroutines are always `Unpin`, so add an - // unconditional builtin candidate. - candidates.vec.push(BuiltinCandidate); + } else { + if self.should_stall_coroutine(coroutine_def_id) { + candidates.ambiguous = true; + } else { + // Coroutines implement all other auto traits normally. + candidates.vec.push(AutoImplCandidate); } } } @@ -842,12 +849,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::CoroutineWitness(def_id, _) => { - if self.should_stall_coroutine_witness(def_id) { - candidates.ambiguous = true; - } else { - candidates.vec.push(AutoImplCandidate); - } + ty::CoroutineWitness(..) => { + candidates.vec.push(AutoImplCandidate); } ty::Bool @@ -866,7 +869,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { | ty::FnPtr(..) | ty::Closure(..) | ty::CoroutineClosure(..) - | ty::Coroutine(..) | ty::Never | ty::Tuple(_) | ty::UnsafeBinder(_) => { @@ -1153,6 +1155,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Ref(_, _, hir::Mutability::Mut) => {} ty::Coroutine(coroutine_def_id, args) => { + if self.should_stall_coroutine(coroutine_def_id) { + candidates.ambiguous = true; + return; + } + match self.tcx().coroutine_movability(coroutine_def_id) { hir::Movability::Static => {} hir::Movability::Movable => { @@ -1194,12 +1201,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::CoroutineWitness(coroutine_def_id, _) => { - if self.should_stall_coroutine_witness(coroutine_def_id) { - candidates.ambiguous = true; - } else { - candidates.vec.push(SizedCandidate); - } + ty::CoroutineWitness(..) => { + candidates.vec.push(SizedCandidate); } // Fallback to whatever user-defined impls or param-env clauses exist in this case. @@ -1238,7 +1241,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { | ty::RawPtr(..) | ty::Char | ty::Ref(..) - | ty::Coroutine(..) | ty::Array(..) | ty::Closure(..) | ty::CoroutineClosure(..) @@ -1247,14 +1249,18 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { candidates.vec.push(SizedCandidate); } - ty::CoroutineWitness(coroutine_def_id, _) => { - if self.should_stall_coroutine_witness(coroutine_def_id) { + ty::Coroutine(coroutine_def_id, _) => { + if self.should_stall_coroutine(coroutine_def_id) { candidates.ambiguous = true; } else { candidates.vec.push(SizedCandidate); } } + ty::CoroutineWitness(..) => { + candidates.vec.push(SizedCandidate); + } + // Conditionally `Sized`. ty::Tuple(..) | ty::Pat(..) | ty::Adt(..) | ty::UnsafeBinder(_) => { candidates.vec.push(SizedCandidate); diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index d7c3543cb3fd..e893add81c8f 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2841,7 +2841,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { obligations } - fn should_stall_coroutine_witness(&self, def_id: DefId) -> bool { + fn should_stall_coroutine(&self, def_id: DefId) -> bool { match self.infcx.typing_mode() { TypingMode::Analysis { defining_opaque_types_and_generators: stalled_generators } => { def_id.as_local().is_some_and(|def_id| stalled_generators.contains(&def_id)) diff --git a/compiler/rustc_type_ir/src/flags.rs b/compiler/rustc_type_ir/src/flags.rs index d7b9e0ca340a..23b7f55fbbe5 100644 --- a/compiler/rustc_type_ir/src/flags.rs +++ b/compiler/rustc_type_ir/src/flags.rs @@ -131,10 +131,7 @@ bitflags::bitflags! { /// Does this have any binders with bound vars (e.g. that need to be anonymized)? const HAS_BINDER_VARS = 1 << 23; - /// Does this type have any coroutine witnesses in it? - // FIXME: This should probably be changed to track whether the type has any - // *coroutines* in it, though this will happen if we remove coroutine witnesses - // altogether. + /// Does this type have any coroutines in it? const HAS_TY_CORO = 1 << 24; } } @@ -246,11 +243,13 @@ impl FlagComputation { self.add_flags(TypeFlags::HAS_TY_PARAM); } - ty::Closure(_, args) | ty::Coroutine(_, args) | ty::CoroutineClosure(_, args) => { + ty::Closure(_, args) + | ty::CoroutineClosure(_, args) + | ty::CoroutineWitness(_, args) => { self.add_args(args.as_slice()); } - ty::CoroutineWitness(_, args) => { + ty::Coroutine(_, args) => { self.add_flags(TypeFlags::HAS_TY_CORO); self.add_args(args.as_slice()); } diff --git a/tests/ui/async-await/issue-70818.rs b/tests/ui/async-await/issue-70818.rs index bc181de8d925..c11332fe7d84 100644 --- a/tests/ui/async-await/issue-70818.rs +++ b/tests/ui/async-await/issue-70818.rs @@ -4,6 +4,7 @@ use std::future::Future; fn foo(ty: T, ty1: U) -> impl Future + Send { //~^ ERROR future cannot be sent between threads safely async { (ty, ty1) } + //~^ ERROR future cannot be sent between threads safely } fn main() {} diff --git a/tests/ui/async-await/issue-70818.stderr b/tests/ui/async-await/issue-70818.stderr index 8de6a825042b..07fd20cdd77e 100644 --- a/tests/ui/async-await/issue-70818.stderr +++ b/tests/ui/async-await/issue-70818.stderr @@ -1,3 +1,24 @@ +error: future cannot be sent between threads safely + --> $DIR/issue-70818.rs:6:5 + | +LL | async { (ty, ty1) } + | ^^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` + | +note: captured value is not `Send` + --> $DIR/issue-70818.rs:6:18 + | +LL | async { (ty, ty1) } + | ^^^ has type `U` which is not `Send` +note: required by a bound in an opaque type + --> $DIR/issue-70818.rs:4:69 + | +LL | fn foo(ty: T, ty1: U) -> impl Future + Send { + | ^^^^ +help: consider restricting type parameter `U` with trait `Send` + | +LL | fn foo(ty: T, ty1: U) -> impl Future + Send { + | +++++++++++++++++++ + error: future cannot be sent between threads safely --> $DIR/issue-70818.rs:4:38 | @@ -14,5 +35,5 @@ help: consider restricting type parameter `U` with trait `Send` LL | fn foo(ty: T, ty1: U) -> impl Future + Send { | +++++++++++++++++++ -error: aborting due to 1 previous error +error: aborting due to 2 previous errors diff --git a/tests/ui/async-await/issue-86507.stderr b/tests/ui/async-await/issue-86507.stderr index 6385a8c975e3..c71801dcfc85 100644 --- a/tests/ui/async-await/issue-86507.stderr +++ b/tests/ui/async-await/issue-86507.stderr @@ -13,7 +13,7 @@ note: captured value is not `Send` because `&` references cannot be sent unless | LL | let x = x; | ^ has type `&T` which is not `Send`, because `T` is not `Sync` - = note: required for the cast from `Pin>` to `Pin + Send + 'async_trait)>>` + = note: required for the cast from `Pin>` to `Pin + Send>>` help: consider further restricting type parameter `T` with trait `Sync` | LL | fn bar<'me, 'async_trait, T: Send + std::marker::Sync>(x: &'me T) diff --git a/tests/ui/coroutine/clone-impl-async.rs b/tests/ui/coroutine/clone-impl-async.rs index 2794b167aa20..4e2b26d02957 100644 --- a/tests/ui/coroutine/clone-impl-async.rs +++ b/tests/ui/coroutine/clone-impl-async.rs @@ -9,7 +9,7 @@ use std::future::ready; struct NonClone; -fn main() { +fn local() { let inner_non_clone = async { let non_clone = NonClone; let () = ready(()).await; @@ -34,7 +34,9 @@ fn main() { //~^ ERROR : Copy` is not satisfied check_clone(&maybe_copy_clone); //~^ ERROR : Clone` is not satisfied +} +fn non_local() { let inner_non_clone_fn = the_inner_non_clone_fn(); check_copy(&inner_non_clone_fn); //~^ ERROR : Copy` is not satisfied @@ -69,3 +71,5 @@ async fn the_maybe_copy_clone_fn() {} fn check_copy(_x: &T) {} fn check_clone(_x: &T) {} + +fn main() {} diff --git a/tests/ui/coroutine/clone-impl-async.stderr b/tests/ui/coroutine/clone-impl-async.stderr index 62bcce2fbcbe..319a5ed3d8d3 100644 --- a/tests/ui/coroutine/clone-impl-async.stderr +++ b/tests/ui/coroutine/clone-impl-async.stderr @@ -1,89 +1,5 @@ -error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:13:27: 13:32}: Copy` is not satisfied - --> $DIR/clone-impl-async.rs:18:16 - | -LL | check_copy(&inner_non_clone); - | ---------- ^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/clone-impl-async.rs:13:27: 13:32}` - | | - | required by a bound introduced by this call - | -note: required by a bound in `check_copy` - --> $DIR/clone-impl-async.rs:70:18 - | -LL | fn check_copy(_x: &T) {} - | ^^^^ required by this bound in `check_copy` - -error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:13:27: 13:32}: Clone` is not satisfied - --> $DIR/clone-impl-async.rs:20:17 - | -LL | check_clone(&inner_non_clone); - | ----------- ^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `{async block@$DIR/clone-impl-async.rs:13:27: 13:32}` - | | - | required by a bound introduced by this call - | -note: required by a bound in `check_clone` - --> $DIR/clone-impl-async.rs:71:19 - | -LL | fn check_clone(_x: &T) {} - | ^^^^^ required by this bound in `check_clone` - -error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:24:27: 24:37}: Copy` is not satisfied - --> $DIR/clone-impl-async.rs:27:16 - | -LL | check_copy(&outer_non_clone); - | ---------- ^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/clone-impl-async.rs:24:27: 24:37}` - | | - | required by a bound introduced by this call - | -note: required by a bound in `check_copy` - --> $DIR/clone-impl-async.rs:70:18 - | -LL | fn check_copy(_x: &T) {} - | ^^^^ required by this bound in `check_copy` - -error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:24:27: 24:37}: Clone` is not satisfied - --> $DIR/clone-impl-async.rs:29:17 - | -LL | check_clone(&outer_non_clone); - | ----------- ^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `{async block@$DIR/clone-impl-async.rs:24:27: 24:37}` - | | - | required by a bound introduced by this call - | -note: required by a bound in `check_clone` - --> $DIR/clone-impl-async.rs:71:19 - | -LL | fn check_clone(_x: &T) {} - | ^^^^^ required by this bound in `check_clone` - -error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:32:28: 32:38}: Copy` is not satisfied - --> $DIR/clone-impl-async.rs:33:16 - | -LL | check_copy(&maybe_copy_clone); - | ---------- ^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/clone-impl-async.rs:32:28: 32:38}` - | | - | required by a bound introduced by this call - | -note: required by a bound in `check_copy` - --> $DIR/clone-impl-async.rs:70:18 - | -LL | fn check_copy(_x: &T) {} - | ^^^^ required by this bound in `check_copy` - -error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:32:28: 32:38}: Clone` is not satisfied - --> $DIR/clone-impl-async.rs:35:17 - | -LL | check_clone(&maybe_copy_clone); - | ----------- ^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `{async block@$DIR/clone-impl-async.rs:32:28: 32:38}` - | | - | required by a bound introduced by this call - | -note: required by a bound in `check_clone` - --> $DIR/clone-impl-async.rs:71:19 - | -LL | fn check_clone(_x: &T) {} - | ^^^^^ required by this bound in `check_clone` - error[E0277]: the trait bound `impl Future: Copy` is not satisfied - --> $DIR/clone-impl-async.rs:39:16 + --> $DIR/clone-impl-async.rs:41:16 | LL | check_copy(&inner_non_clone_fn); | ---------- ^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `impl Future` @@ -91,13 +7,13 @@ LL | check_copy(&inner_non_clone_fn); | required by a bound introduced by this call | note: required by a bound in `check_copy` - --> $DIR/clone-impl-async.rs:70:18 + --> $DIR/clone-impl-async.rs:72:18 | LL | fn check_copy(_x: &T) {} | ^^^^ required by this bound in `check_copy` error[E0277]: the trait bound `impl Future: Clone` is not satisfied - --> $DIR/clone-impl-async.rs:41:17 + --> $DIR/clone-impl-async.rs:43:17 | LL | check_clone(&inner_non_clone_fn); | ----------- ^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `impl Future` @@ -105,13 +21,13 @@ LL | check_clone(&inner_non_clone_fn); | required by a bound introduced by this call | note: required by a bound in `check_clone` - --> $DIR/clone-impl-async.rs:71:19 + --> $DIR/clone-impl-async.rs:73:19 | LL | fn check_clone(_x: &T) {} | ^^^^^ required by this bound in `check_clone` error[E0277]: the trait bound `impl Future: Copy` is not satisfied - --> $DIR/clone-impl-async.rs:45:16 + --> $DIR/clone-impl-async.rs:47:16 | LL | check_copy(&outer_non_clone_fn); | ---------- ^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `impl Future` @@ -119,13 +35,13 @@ LL | check_copy(&outer_non_clone_fn); | required by a bound introduced by this call | note: required by a bound in `check_copy` - --> $DIR/clone-impl-async.rs:70:18 + --> $DIR/clone-impl-async.rs:72:18 | LL | fn check_copy(_x: &T) {} | ^^^^ required by this bound in `check_copy` error[E0277]: the trait bound `impl Future: Clone` is not satisfied - --> $DIR/clone-impl-async.rs:47:17 + --> $DIR/clone-impl-async.rs:49:17 | LL | check_clone(&outer_non_clone_fn); | ----------- ^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `impl Future` @@ -133,13 +49,13 @@ LL | check_clone(&outer_non_clone_fn); | required by a bound introduced by this call | note: required by a bound in `check_clone` - --> $DIR/clone-impl-async.rs:71:19 + --> $DIR/clone-impl-async.rs:73:19 | LL | fn check_clone(_x: &T) {} | ^^^^^ required by this bound in `check_clone` error[E0277]: the trait bound `impl Future: Copy` is not satisfied - --> $DIR/clone-impl-async.rs:51:16 + --> $DIR/clone-impl-async.rs:53:16 | LL | check_copy(&maybe_copy_clone_fn); | ---------- ^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `impl Future` @@ -147,13 +63,13 @@ LL | check_copy(&maybe_copy_clone_fn); | required by a bound introduced by this call | note: required by a bound in `check_copy` - --> $DIR/clone-impl-async.rs:70:18 + --> $DIR/clone-impl-async.rs:72:18 | LL | fn check_copy(_x: &T) {} | ^^^^ required by this bound in `check_copy` error[E0277]: the trait bound `impl Future: Clone` is not satisfied - --> $DIR/clone-impl-async.rs:53:17 + --> $DIR/clone-impl-async.rs:55:17 | LL | check_clone(&maybe_copy_clone_fn); | ----------- ^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `impl Future` @@ -161,7 +77,79 @@ LL | check_clone(&maybe_copy_clone_fn); | required by a bound introduced by this call | note: required by a bound in `check_clone` - --> $DIR/clone-impl-async.rs:71:19 + --> $DIR/clone-impl-async.rs:73:19 + | +LL | fn check_clone(_x: &T) {} + | ^^^^^ required by this bound in `check_clone` + +error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:13:27: 13:32}: Copy` is not satisfied + --> $DIR/clone-impl-async.rs:18:5 + | +LL | check_copy(&inner_non_clone); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/clone-impl-async.rs:13:27: 13:32}` + | +note: required by a bound in `check_copy` + --> $DIR/clone-impl-async.rs:72:18 + | +LL | fn check_copy(_x: &T) {} + | ^^^^ required by this bound in `check_copy` + +error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:13:27: 13:32}: Clone` is not satisfied + --> $DIR/clone-impl-async.rs:20:5 + | +LL | check_clone(&inner_non_clone); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `{async block@$DIR/clone-impl-async.rs:13:27: 13:32}` + | +note: required by a bound in `check_clone` + --> $DIR/clone-impl-async.rs:73:19 + | +LL | fn check_clone(_x: &T) {} + | ^^^^^ required by this bound in `check_clone` + +error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:24:27: 24:37}: Copy` is not satisfied + --> $DIR/clone-impl-async.rs:27:5 + | +LL | check_copy(&outer_non_clone); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/clone-impl-async.rs:24:27: 24:37}` + | +note: required by a bound in `check_copy` + --> $DIR/clone-impl-async.rs:72:18 + | +LL | fn check_copy(_x: &T) {} + | ^^^^ required by this bound in `check_copy` + +error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:24:27: 24:37}: Clone` is not satisfied + --> $DIR/clone-impl-async.rs:29:5 + | +LL | check_clone(&outer_non_clone); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `{async block@$DIR/clone-impl-async.rs:24:27: 24:37}` + | +note: required by a bound in `check_clone` + --> $DIR/clone-impl-async.rs:73:19 + | +LL | fn check_clone(_x: &T) {} + | ^^^^^ required by this bound in `check_clone` + +error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:32:28: 32:38}: Copy` is not satisfied + --> $DIR/clone-impl-async.rs:33:5 + | +LL | check_copy(&maybe_copy_clone); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/clone-impl-async.rs:32:28: 32:38}` + | +note: required by a bound in `check_copy` + --> $DIR/clone-impl-async.rs:72:18 + | +LL | fn check_copy(_x: &T) {} + | ^^^^ required by this bound in `check_copy` + +error[E0277]: the trait bound `{async block@$DIR/clone-impl-async.rs:32:28: 32:38}: Clone` is not satisfied + --> $DIR/clone-impl-async.rs:35:5 + | +LL | check_clone(&maybe_copy_clone); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `{async block@$DIR/clone-impl-async.rs:32:28: 32:38}` + | +note: required by a bound in `check_clone` + --> $DIR/clone-impl-async.rs:73:19 | LL | fn check_clone(_x: &T) {} | ^^^^^ required by this bound in `check_clone` diff --git a/tests/ui/coroutine/clone-impl-static.stderr b/tests/ui/coroutine/clone-impl-static.stderr index 9fb71fd5fd01..4df6b9759c3f 100644 --- a/tests/ui/coroutine/clone-impl-static.stderr +++ b/tests/ui/coroutine/clone-impl-static.stderr @@ -1,10 +1,8 @@ error[E0277]: the trait bound `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}: Copy` is not satisfied - --> $DIR/clone-impl-static.rs:14:16 + --> $DIR/clone-impl-static.rs:14:5 | LL | check_copy(&generator); - | ---------- ^^^^^^^^^^ the trait `Copy` is not implemented for `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}` - | | - | required by a bound introduced by this call + | ^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}` | note: required by a bound in `check_copy` --> $DIR/clone-impl-static.rs:20:18 @@ -13,12 +11,10 @@ LL | fn check_copy(_x: &T) {} | ^^^^ required by this bound in `check_copy` error[E0277]: the trait bound `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}: Clone` is not satisfied - --> $DIR/clone-impl-static.rs:16:17 + --> $DIR/clone-impl-static.rs:16:5 | LL | check_clone(&generator); - | ----------- ^^^^^^^^^^ the trait `Clone` is not implemented for `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}` - | | - | required by a bound introduced by this call + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `{static coroutine@$DIR/clone-impl-static.rs:11:5: 11:19}` | note: required by a bound in `check_clone` --> $DIR/clone-impl-static.rs:21:19 diff --git a/tests/ui/coroutine/clone-impl.rs b/tests/ui/coroutine/clone-impl.rs index e528f031d526..9e04e256fc11 100644 --- a/tests/ui/coroutine/clone-impl.rs +++ b/tests/ui/coroutine/clone-impl.rs @@ -42,6 +42,7 @@ fn test3_upvars() { let clonable_0: Vec = Vec::new(); let gen_clone_0 = #[coroutine] move || { + yield; drop(clonable_0); }; check_copy(&gen_clone_0); diff --git a/tests/ui/coroutine/clone-impl.stderr b/tests/ui/coroutine/clone-impl.stderr index 714e5aa3d9e3..f316902a42d0 100644 --- a/tests/ui/coroutine/clone-impl.stderr +++ b/tests/ui/coroutine/clone-impl.stderr @@ -1,59 +1,81 @@ error[E0277]: the trait bound `Vec: Copy` is not satisfied in `{coroutine@$DIR/clone-impl.rs:44:5: 44:12}` - --> $DIR/clone-impl.rs:47:16 + --> $DIR/clone-impl.rs:48:5 | LL | move || { | ------- within this `{coroutine@$DIR/clone-impl.rs:44:5: 44:12}` ... LL | check_copy(&gen_clone_0); - | ^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:44:5: 44:12}`, the trait `Copy` is not implemented for `Vec` + | ^^^^^^^^^^^^^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:44:5: 44:12}`, the trait `Copy` is not implemented for `Vec` | note: captured value does not implement `Copy` - --> $DIR/clone-impl.rs:45:14 + --> $DIR/clone-impl.rs:46:14 | LL | drop(clonable_0); | ^^^^^^^^^^ has type `Vec` which does not implement `Copy` note: required by a bound in `check_copy` - --> $DIR/clone-impl.rs:91:18 + --> $DIR/clone-impl.rs:92:18 | LL | fn check_copy(_x: &T) {} | ^^^^ required by this bound in `check_copy` -error[E0277]: the trait bound `Vec: Copy` is not satisfied in `{coroutine@$DIR/clone-impl.rs:67:5: 67:12}` - --> $DIR/clone-impl.rs:73:16 +error[E0277]: the trait bound `Vec: Copy` is not satisfied in `{coroutine@$DIR/clone-impl.rs:55:5: 55:12}` + --> $DIR/clone-impl.rs:60:5 | LL | move || { - | ------- within this `{coroutine@$DIR/clone-impl.rs:67:5: 67:12}` + | ------- within this `{coroutine@$DIR/clone-impl.rs:55:5: 55:12}` ... LL | check_copy(&gen_clone_1); - | ^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:67:5: 67:12}`, the trait `Copy` is not implemented for `Vec` + | ^^^^^^^^^^^^^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:55:5: 55:12}`, the trait `Copy` is not implemented for `Vec` + | +note: coroutine does not implement `Copy` as this value is used across a yield + --> $DIR/clone-impl.rs:57:9 + | +LL | let v = vec!['a']; + | - has type `Vec` which does not implement `Copy` +LL | yield; + | ^^^^^ yield occurs here, with `v` maybe used later +note: required by a bound in `check_copy` + --> $DIR/clone-impl.rs:92:18 + | +LL | fn check_copy(_x: &T) {} + | ^^^^ required by this bound in `check_copy` + +error[E0277]: the trait bound `Vec: Copy` is not satisfied in `{coroutine@$DIR/clone-impl.rs:68:5: 68:12}` + --> $DIR/clone-impl.rs:74:5 + | +LL | move || { + | ------- within this `{coroutine@$DIR/clone-impl.rs:68:5: 68:12}` +... +LL | check_copy(&gen_clone_1); + | ^^^^^^^^^^^^^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:68:5: 68:12}`, the trait `Copy` is not implemented for `Vec` | note: captured value does not implement `Copy` - --> $DIR/clone-impl.rs:71:14 + --> $DIR/clone-impl.rs:72:14 | LL | drop(clonable_1); | ^^^^^^^^^^ has type `Vec` which does not implement `Copy` note: required by a bound in `check_copy` - --> $DIR/clone-impl.rs:91:18 + --> $DIR/clone-impl.rs:92:18 | LL | fn check_copy(_x: &T) {} | ^^^^ required by this bound in `check_copy` -error[E0277]: the trait bound `NonClone: Copy` is not satisfied in `{coroutine@$DIR/clone-impl.rs:81:5: 81:12}` - --> $DIR/clone-impl.rs:85:16 +error[E0277]: the trait bound `NonClone: Copy` is not satisfied in `{coroutine@$DIR/clone-impl.rs:82:5: 82:12}` + --> $DIR/clone-impl.rs:86:5 | LL | move || { - | ------- within this `{coroutine@$DIR/clone-impl.rs:81:5: 81:12}` + | ------- within this `{coroutine@$DIR/clone-impl.rs:82:5: 82:12}` ... LL | check_copy(&gen_non_clone); - | ^^^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:81:5: 81:12}`, the trait `Copy` is not implemented for `NonClone` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:82:5: 82:12}`, the trait `Copy` is not implemented for `NonClone` | note: captured value does not implement `Copy` - --> $DIR/clone-impl.rs:83:14 + --> $DIR/clone-impl.rs:84:14 | LL | drop(non_clonable); | ^^^^^^^^^^^^ has type `NonClone` which does not implement `Copy` note: required by a bound in `check_copy` - --> $DIR/clone-impl.rs:91:18 + --> $DIR/clone-impl.rs:92:18 | LL | fn check_copy(_x: &T) {} | ^^^^ required by this bound in `check_copy` @@ -63,22 +85,22 @@ LL + #[derive(Copy)] LL | struct NonClone; | -error[E0277]: the trait bound `NonClone: Clone` is not satisfied in `{coroutine@$DIR/clone-impl.rs:81:5: 81:12}` - --> $DIR/clone-impl.rs:87:17 +error[E0277]: the trait bound `NonClone: Clone` is not satisfied in `{coroutine@$DIR/clone-impl.rs:82:5: 82:12}` + --> $DIR/clone-impl.rs:88:5 | LL | move || { - | ------- within this `{coroutine@$DIR/clone-impl.rs:81:5: 81:12}` + | ------- within this `{coroutine@$DIR/clone-impl.rs:82:5: 82:12}` ... LL | check_clone(&gen_non_clone); - | ^^^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:81:5: 81:12}`, the trait `Clone` is not implemented for `NonClone` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:82:5: 82:12}`, the trait `Clone` is not implemented for `NonClone` | note: captured value does not implement `Clone` - --> $DIR/clone-impl.rs:83:14 + --> $DIR/clone-impl.rs:84:14 | LL | drop(non_clonable); | ^^^^^^^^^^^^ has type `NonClone` which does not implement `Clone` note: required by a bound in `check_clone` - --> $DIR/clone-impl.rs:92:19 + --> $DIR/clone-impl.rs:93:19 | LL | fn check_clone(_x: &T) {} | ^^^^^ required by this bound in `check_clone` @@ -88,28 +110,6 @@ LL + #[derive(Clone)] LL | struct NonClone; | -error[E0277]: the trait bound `Vec: Copy` is not satisfied in `{coroutine@$DIR/clone-impl.rs:54:5: 54:12}` - --> $DIR/clone-impl.rs:59:5 - | -LL | move || { - | ------- within this `{coroutine@$DIR/clone-impl.rs:54:5: 54:12}` -... -LL | check_copy(&gen_clone_1); - | ^^^^^^^^^^^^^^^^^^^^^^^^ within `{coroutine@$DIR/clone-impl.rs:54:5: 54:12}`, the trait `Copy` is not implemented for `Vec` - | -note: coroutine does not implement `Copy` as this value is used across a yield - --> $DIR/clone-impl.rs:56:9 - | -LL | let v = vec!['a']; - | - has type `Vec` which does not implement `Copy` -LL | yield; - | ^^^^^ yield occurs here, with `v` maybe used later -note: required by a bound in `check_copy` - --> $DIR/clone-impl.rs:91:18 - | -LL | fn check_copy(_x: &T) {} - | ^^^^ required by this bound in `check_copy` - error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/coroutine/ref-upvar-not-send.stderr b/tests/ui/coroutine/ref-upvar-not-send.stderr index 892b5d261c2b..3a5e8ec4dab0 100644 --- a/tests/ui/coroutine/ref-upvar-not-send.stderr +++ b/tests/ui/coroutine/ref-upvar-not-send.stderr @@ -1,14 +1,13 @@ error: coroutine cannot be sent between threads safely - --> $DIR/ref-upvar-not-send.rs:15:30 + --> $DIR/ref-upvar-not-send.rs:15:5 | -LL | assert_send(#[coroutine] move || { - | ______________________________^ +LL | / assert_send(#[coroutine] move || { LL | | LL | | LL | | yield; LL | | let _x = x; LL | | }); - | |_____^ coroutine is not `Send` + | |______^ coroutine is not `Send` | = help: the trait `Sync` is not implemented for `*mut ()` note: captured value is not `Send` because `&` references cannot be sent unless their referent is `Sync` @@ -23,16 +22,15 @@ LL | fn assert_send(_: T) {} | ^^^^ required by this bound in `assert_send` error: coroutine cannot be sent between threads safely - --> $DIR/ref-upvar-not-send.rs:23:30 + --> $DIR/ref-upvar-not-send.rs:23:5 | -LL | assert_send(#[coroutine] move || { - | ______________________________^ +LL | / assert_send(#[coroutine] move || { LL | | LL | | LL | | yield; LL | | let _y = y; LL | | }); - | |_____^ coroutine is not `Send` + | |______^ coroutine is not `Send` | = help: within `{coroutine@$DIR/ref-upvar-not-send.rs:23:30: 23:37}`, the trait `Send` is not implemented for `*mut ()` note: captured value is not `Send` because `&mut` references cannot be sent unless their referent is `Send` diff --git a/tests/ui/impl-trait/issues/issue-55872-3.stderr b/tests/ui/impl-trait/issues/issue-55872-3.stderr index ce2dd7f02b4c..b7711e47468e 100644 --- a/tests/ui/impl-trait/issues/issue-55872-3.stderr +++ b/tests/ui/impl-trait/issues/issue-55872-3.stderr @@ -1,12 +1,3 @@ -error[E0277]: the trait bound `{async block@$DIR/issue-55872-3.rs:18:9: 18:14}: Copy` is not satisfied - --> $DIR/issue-55872-3.rs:14:20 - | -LL | fn foo() -> Self::E { - | ^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/issue-55872-3.rs:18:9: 18:14}` -... -LL | async {} - | -------- return type was inferred to be `{async block@$DIR/issue-55872-3.rs:18:9: 18:14}` here - error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias --> $DIR/issue-55872-3.rs:14:20 | @@ -21,6 +12,12 @@ LL | fn foo() -> Self::E { | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +error[E0277]: the trait bound `{async block@$DIR/issue-55872-3.rs:18:9: 18:14}: Copy` is not satisfied + --> $DIR/issue-55872-3.rs:14:20 + | +LL | fn foo() -> Self::E { + | ^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/issue-55872-3.rs:18:9: 18:14}` + error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0277`. From e58e6f857f1335ef2436cb7bf3a4a55ddfc79387 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 31 Jul 2025 20:33:33 +0300 Subject: [PATCH 398/809] 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 d05bb98d6bb448a221ed479842acda5923fb5eb1 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 18 Jul 2025 19:47:08 +0000 Subject: [PATCH 399/809] Extract borrowck coroutine drop-liveness hack --- .../src/traits/query/dropck_outlives.rs | 7 ++- compiler/rustc_ty_utils/src/needs_drop.rs | 43 +++++++++++-------- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs index 38cfdcdc22d3..b1b331d1b61e 100644 --- a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs @@ -318,7 +318,7 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( }) } - ty::Coroutine(_, args) => { + ty::Coroutine(def_id, args) => { // rust-lang/rust#49918: types can be constructed, stored // in the interior, and sit idle when coroutine yields // (and is subsequently dropped). @@ -346,7 +346,10 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( // While we conservatively assume that all coroutines require drop // to avoid query cycles during MIR building, we can check the actual // witness during borrowck to avoid unnecessary liveness constraints. - if args.witness().needs_drop(tcx, tcx.erase_regions(typing_env)) { + let typing_env = tcx.erase_regions(typing_env); + if tcx.mir_coroutine_witnesses(def_id).is_some_and(|witness| { + witness.field_tys.iter().any(|field| field.ty.needs_drop(tcx, typing_env)) + }) { constraints.outlives.extend(args.upvar_tys().iter().map(ty::GenericArg::from)); constraints.outlives.push(args.resume_ty().into()); } diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index c3b04c20f4b6..13d56889bd12 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -101,9 +101,6 @@ fn has_significant_drop_raw<'tcx>( struct NeedsDropTypes<'tcx, F> { tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, - /// Whether to reveal coroutine witnesses, this is set - /// to `false` unless we compute `needs_drop` for a coroutine witness. - reveal_coroutine_witnesses: bool, query_ty: Ty<'tcx>, seen_tys: FxHashSet>, /// A stack of types left to process, and the recursion depth when we @@ -115,6 +112,15 @@ struct NeedsDropTypes<'tcx, F> { adt_components: F, /// Set this to true if an exhaustive list of types involved in /// drop obligation is requested. + // FIXME: Calling this bool `exhaustive` is confusing and possibly a footgun, + // since it does two things: It makes the iterator yield *all* of the types + // that need drop, and it also affects the computation of the drop components + // on `Coroutine`s. The latter is somewhat confusing, and probably should be + // a function of `typing_env`. See the HACK comment below for why this is + // necessary. If this isn't possible, then we probably should turn this into + // a `NeedsDropMode` so that we can have a variant like `CollectAllSignificantDrops`, + // which will more accurately indicate that we want *all* of the *significant* + // drops, which are the two important behavioral changes toggled by this bool. exhaustive: bool, } @@ -131,7 +137,6 @@ impl<'tcx, F> NeedsDropTypes<'tcx, F> { Self { tcx, typing_env, - reveal_coroutine_witnesses: exhaustive, seen_tys, query_ty: ty, unchecked_tys: vec![(ty, 0)], @@ -195,23 +200,27 @@ where // for the coroutine witness and check whether any of the contained types // need to be dropped, and only require the captured types to be live // if they do. - ty::Coroutine(_, args) => { - if self.reveal_coroutine_witnesses { - queue_type(self, args.as_coroutine().witness()); + ty::Coroutine(def_id, args) => { + // FIXME: See FIXME on `exhaustive` field above. + if self.exhaustive { + for upvar in args.as_coroutine().upvar_tys() { + queue_type(self, upvar); + } + queue_type(self, args.as_coroutine().resume_ty()); + if let Some(witness) = tcx.mir_coroutine_witnesses(def_id) { + for field_ty in &witness.field_tys { + queue_type( + self, + EarlyBinder::bind(field_ty.ty).instantiate(tcx, args), + ); + } + } } else { return Some(self.always_drop_component(ty)); } } - ty::CoroutineWitness(def_id, args) => { - if let Some(witness) = tcx.mir_coroutine_witnesses(def_id) { - self.reveal_coroutine_witnesses = true; - for field_ty in &witness.field_tys { - queue_type( - self, - EarlyBinder::bind(field_ty.ty).instantiate(tcx, args), - ); - } - } + ty::CoroutineWitness(..) => { + unreachable!("witness should be handled in parent"); } ty::UnsafeBinder(bound_ty) => { From e9765781b2857da90161157a3fc523f9e1d58848 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 25 Jul 2025 16:46:11 +0000 Subject: [PATCH 400/809] Remove the witness type from coroutine args --- .../src/type_check/input_output.rs | 1 - .../src/collect/generics_of.rs | 12 ++------ compiler/rustc_hir_typeck/src/closure.rs | 5 ---- compiler/rustc_middle/src/ty/generic_args.rs | 29 +++++++------------ compiler/rustc_middle/src/ty/print/pretty.rs | 8 ++--- .../src/solve/assembly/structural_traits.rs | 20 +++++++++++-- .../src/traits/select/candidate_assembly.rs | 4 +-- .../src/traits/select/mod.rs | 14 +++++++-- compiler/rustc_type_ir/src/ty_kind/closure.rs | 27 ----------------- ...await.b-{closure#0}.coroutine_resume.0.mir | 8 ----- .../async-closures/def-path.stderr | 4 +-- ...-ranked-auto-trait-6.no_assumptions.stderr | 26 +---------------- .../print/coroutine-print-verbose-2.stderr | 4 +-- .../print/coroutine-print-verbose-3.stderr | 2 +- tests/ui/impl-trait/issues/issue-55872-2.rs | 1 - .../ui/impl-trait/issues/issue-55872-2.stderr | 10 +------ tests/ui/impl-trait/issues/issue-55872-3.rs | 1 - .../ui/impl-trait/issues/issue-55872-3.stderr | 14 ++------- 18 files changed, 54 insertions(+), 136 deletions(-) diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index 99392ea19151..eb31b5de05d2 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -86,7 +86,6 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // them with fresh ty vars. resume_ty: next_ty_var(), yield_ty: next_ty_var(), - witness: next_ty_var(), }, ) .args, diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 31e9c3b80fba..e2462c2d4659 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -379,20 +379,14 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { // for info on the usage of each of these fields. let dummy_args = match kind { ClosureKind::Closure => &["", "", ""][..], - ClosureKind::Coroutine(_) => &[ - "", - "", - "", - "", - "", - "", - ][..], + ClosureKind::Coroutine(_) => { + &["", "", "", "", ""][..] + } ClosureKind::CoroutineClosure(_) => &[ "", "", "", "", - "", ][..], }; diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index a413f805873d..82b7c578a1f2 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -161,8 +161,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Resume type defaults to `()` if the coroutine has no argument. let resume_ty = liberated_sig.inputs().get(0).copied().unwrap_or(tcx.types.unit); - let interior = Ty::new_coroutine_witness(tcx, expr_def_id.to_def_id(), parent_args); - // Coroutines that come from coroutine closures have not yet determined // their kind ty, so make a fresh infer var which will be constrained // later during upvar analysis. Regular coroutines always have the kind @@ -182,7 +180,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { resume_ty, yield_ty, return_ty: liberated_sig.output(), - witness: interior, tupled_upvars_ty, }, ); @@ -210,7 +207,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Compute all of the variables that will be used to populate the coroutine. let resume_ty = self.next_ty_var(expr_span); - let interior = self.next_ty_var(expr_span); let closure_kind_ty = match expected_kind { Some(kind) => Ty::from_closure_kind(tcx, kind), @@ -243,7 +239,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ), tupled_upvars_ty, coroutine_captures_by_ref_ty, - coroutine_witness_ty: interior, }, ); diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 7d34d8df3f3b..b02abb5ab43b 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -96,14 +96,12 @@ impl<'tcx> rustc_type_ir::inherent::GenericArgs> for ty::GenericArg signature_parts_ty, tupled_upvars_ty, coroutine_captures_by_ref_ty, - coroutine_witness_ty, ] => ty::CoroutineClosureArgsParts { parent_args, closure_kind_ty: closure_kind_ty.expect_ty(), signature_parts_ty: signature_parts_ty.expect_ty(), tupled_upvars_ty: tupled_upvars_ty.expect_ty(), coroutine_captures_by_ref_ty: coroutine_captures_by_ref_ty.expect_ty(), - coroutine_witness_ty: coroutine_witness_ty.expect_ty(), }, _ => bug!("closure args missing synthetics"), } @@ -111,23 +109,16 @@ impl<'tcx> rustc_type_ir::inherent::GenericArgs> for ty::GenericArg fn split_coroutine_args(self) -> ty::CoroutineArgsParts> { match self[..] { - [ - ref parent_args @ .., - kind_ty, - resume_ty, - yield_ty, - return_ty, - witness, - tupled_upvars_ty, - ] => ty::CoroutineArgsParts { - parent_args, - kind_ty: kind_ty.expect_ty(), - resume_ty: resume_ty.expect_ty(), - yield_ty: yield_ty.expect_ty(), - return_ty: return_ty.expect_ty(), - witness: witness.expect_ty(), - tupled_upvars_ty: tupled_upvars_ty.expect_ty(), - }, + [ref parent_args @ .., kind_ty, resume_ty, yield_ty, return_ty, tupled_upvars_ty] => { + ty::CoroutineArgsParts { + parent_args, + kind_ty: kind_ty.expect_ty(), + resume_ty: resume_ty.expect_ty(), + yield_ty: yield_ty.expect_ty(), + return_ty: return_ty.expect_ty(), + tupled_upvars_ty: tupled_upvars_ty.expect_ty(), + } + } _ => bug!("coroutine args missing synthetics"), } } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 5c44b10ba71c..71eac294f155 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -913,9 +913,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { " yield_ty=", print(args.as_coroutine().yield_ty()), " return_ty=", - print(args.as_coroutine().return_ty()), - " witness=", - print(args.as_coroutine().witness()) + print(args.as_coroutine().return_ty()) ); } @@ -1035,9 +1033,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { " 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()), - " coroutine_witness_ty=", - print(args.as_coroutine_closure().coroutine_witness_ty()) + print(args.as_coroutine_closure().coroutine_captures_by_ref_ty()) ); } p!("}}"); diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs index c0bebdf6fb63..faa86734d08c 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs @@ -75,9 +75,16 @@ where Ok(ty::Binder::dummy(vec![args.as_coroutine_closure().tupled_upvars_ty()])) } - ty::Coroutine(_, args) => { + ty::Coroutine(def_id, args) => { let coroutine_args = args.as_coroutine(); - Ok(ty::Binder::dummy(vec![coroutine_args.tupled_upvars_ty(), coroutine_args.witness()])) + Ok(ty::Binder::dummy(vec![ + coroutine_args.tupled_upvars_ty(), + Ty::new_coroutine_witness( + ecx.cx(), + def_id, + ecx.cx().mk_args(coroutine_args.parent_args().as_slice()), + ), + ])) } ty::CoroutineWitness(def_id, args) => Ok(ecx @@ -245,7 +252,14 @@ where Movability::Movable => { if ecx.cx().features().coroutine_clone() { let coroutine = args.as_coroutine(); - Ok(ty::Binder::dummy(vec![coroutine.tupled_upvars_ty(), coroutine.witness()])) + Ok(ty::Binder::dummy(vec![ + coroutine.tupled_upvars_ty(), + Ty::new_coroutine_witness( + ecx.cx(), + def_id, + ecx.cx().mk_args(coroutine.parent_args().as_slice()), + ), + ])) } else { Err(NoSolution) } diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index af6dafb30629..62795c8a3a68 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -1166,9 +1166,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { if self.tcx().features().coroutine_clone() { let resolved_upvars = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty()); - let resolved_witness = - self.infcx.shallow_resolve(args.as_coroutine().witness()); - if resolved_upvars.is_ty_var() || resolved_witness.is_ty_var() { + if resolved_upvars.is_ty_var() { // Not yet resolved. candidates.ambiguous = true; } else { diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index e893add81c8f..7ea1548f8f29 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2196,7 +2196,11 @@ impl<'tcx> SelectionContext<'_, 'tcx> { args.as_coroutine() .upvar_tys() .iter() - .chain([args.as_coroutine().witness()]) + .chain([Ty::new_coroutine_witness( + self.tcx(), + coroutine_def_id, + self.tcx().mk_args(args.as_coroutine().parent_args()), + )]) .collect::>(), ) } else { @@ -2327,9 +2331,13 @@ impl<'tcx> SelectionContext<'_, 'tcx> { ty::Binder::dummy(AutoImplConstituents { types: vec![ty], assumptions: vec![] }) } - ty::Coroutine(_, args) => { + ty::Coroutine(def_id, args) => { let ty = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty()); - let witness = args.as_coroutine().witness(); + let witness = Ty::new_coroutine_witness( + self.tcx(), + def_id, + self.tcx().mk_args(args.as_coroutine().parent_args()), + ); ty::Binder::dummy(AutoImplConstituents { types: [ty].into_iter().chain(iter::once(witness)).collect(), assumptions: vec![], diff --git a/compiler/rustc_type_ir/src/ty_kind/closure.rs b/compiler/rustc_type_ir/src/ty_kind/closure.rs index d1ca9bdb7fbd..c32f8339d0b7 100644 --- a/compiler/rustc_type_ir/src/ty_kind/closure.rs +++ b/compiler/rustc_type_ir/src/ty_kind/closure.rs @@ -101,7 +101,6 @@ use crate::{self as ty, Interner}; /// `yield` inside the coroutine. /// * `GR`: The "return type", which is the type of value returned upon /// completion of the coroutine. -/// * `GW`: The "coroutine witness". #[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct ClosureArgs { @@ -239,8 +238,6 @@ pub struct CoroutineClosureArgsParts { /// while the `tupled_upvars_ty`, representing the by-move version of the same /// captures, will be `(String,)`. pub coroutine_captures_by_ref_ty: I::Ty, - /// Witness type returned by the generator produced by this coroutine-closure. - pub coroutine_witness_ty: I::Ty, } impl CoroutineClosureArgs { @@ -251,7 +248,6 @@ impl CoroutineClosureArgs { parts.signature_parts_ty.into(), parts.tupled_upvars_ty.into(), parts.coroutine_captures_by_ref_ty.into(), - parts.coroutine_witness_ty.into(), ])), } } @@ -292,7 +288,6 @@ impl CoroutineClosureArgs { } pub fn coroutine_closure_sig(self) -> ty::Binder> { - let interior = self.coroutine_witness_ty(); let ty::FnPtr(sig_tys, hdr) = self.signature_parts_ty().kind() else { panic!() }; sig_tys.map_bound(|sig_tys| { let [resume_ty, tupled_inputs_ty] = *sig_tys.inputs().as_slice() else { @@ -302,7 +297,6 @@ impl CoroutineClosureArgs { panic!() }; CoroutineClosureSignature { - interior, tupled_inputs_ty, resume_ty, yield_ty, @@ -318,10 +312,6 @@ impl CoroutineClosureArgs { self.split().coroutine_captures_by_ref_ty } - pub fn coroutine_witness_ty(self) -> I::Ty { - self.split().coroutine_witness_ty - } - pub fn has_self_borrows(&self) -> bool { match self.coroutine_captures_by_ref_ty().kind() { ty::FnPtr(sig_tys, _) => sig_tys @@ -361,7 +351,6 @@ impl TypeVisitor for HasRegionsBoundAt { #[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] pub struct CoroutineClosureSignature { - pub interior: I::Ty, pub tupled_inputs_ty: I::Ty, pub resume_ty: I::Ty, pub yield_ty: I::Ty, @@ -407,7 +396,6 @@ impl CoroutineClosureSignature { resume_ty: self.resume_ty, yield_ty: self.yield_ty, return_ty: self.return_ty, - witness: self.interior, tupled_upvars_ty, }, ); @@ -587,11 +575,6 @@ pub struct CoroutineArgsParts { pub yield_ty: I::Ty, pub return_ty: I::Ty, - /// The interior type of the coroutine. - /// Represents all types that are stored in locals - /// in the coroutine's body. - pub witness: I::Ty, - /// The upvars captured by the closure. Remains an inference variable /// until the upvar analysis, which happens late in HIR typeck. pub tupled_upvars_ty: I::Ty, @@ -607,7 +590,6 @@ impl CoroutineArgs { parts.resume_ty.into(), parts.yield_ty.into(), parts.return_ty.into(), - parts.witness.into(), parts.tupled_upvars_ty.into(), ])), } @@ -629,15 +611,6 @@ impl CoroutineArgs { self.split().kind_ty } - /// This describes the types that can be contained in a coroutine. - /// It will be a type variable initially and unified in the last stages of typeck of a body. - /// It contains a tuple of all the types that could end up on a coroutine frame. - /// The state transformation MIR pass may only produce layouts which mention types - /// in this tuple. Upvars are not counted here. - pub fn witness(self) -> I::Ty { - self.split().witness - } - /// Returns an iterator over the list of types of captured paths by the coroutine. /// In case there was a type error in figuring out the types of the captured path, an /// empty iterator is returned. diff --git a/tests/mir-opt/building/async_await.b-{closure#0}.coroutine_resume.0.mir b/tests/mir-opt/building/async_await.b-{closure#0}.coroutine_resume.0.mir index 109a41d1ef90..9bff257e0639 100644 --- a/tests/mir-opt/building/async_await.b-{closure#0}.coroutine_resume.0.mir +++ b/tests/mir-opt/building/async_await.b-{closure#0}.coroutine_resume.0.mir @@ -9,10 +9,6 @@ std::future::ResumeTy, (), (), - CoroutineWitness( - DefId(0:5 ~ async_await[ccf8]::a::{closure#0}), - [], - ), (), ], ), @@ -30,10 +26,6 @@ std::future::ResumeTy, (), (), - CoroutineWitness( - DefId(0:5 ~ async_await[ccf8]::a::{closure#0}), - [], - ), (), ], ), diff --git a/tests/ui/async-await/async-closures/def-path.stderr b/tests/ui/async-await/async-closures/def-path.stderr index 58a5b0b79c4e..a507fa697604 100644 --- a/tests/ui/async-await/async-closures/def-path.stderr +++ b/tests/ui/async-await/async-closures/def-path.stderr @@ -5,11 +5,11 @@ LL | let x = async || {}; | -- the expected `async` closure body LL | LL | let () = x(); - | ^^ --- this expression has type `{static main::{closure#0}::{closure#0} upvar_tys=?15t resume_ty=ResumeTy yield_ty=() return_ty=() witness={main::{closure#0}::{closure#0}}}` + | ^^ --- this expression has type `{static main::{closure#0}::{closure#0} upvar_tys=?14t resume_ty=ResumeTy yield_ty=() return_ty=()}` | | | expected `async` closure body, found `()` | - = note: expected `async` closure body `{static main::{closure#0}::{closure#0} upvar_tys=?15t resume_ty=ResumeTy yield_ty=() return_ty=() witness={main::{closure#0}::{closure#0}}}` + = note: expected `async` closure body `{static main::{closure#0}::{closure#0} upvar_tys=?14t resume_ty=ResumeTy yield_ty=() return_ty=()}` found unit type `()` error: aborting due to 1 previous error diff --git a/tests/ui/async-await/higher-ranked-auto-trait-6.no_assumptions.stderr b/tests/ui/async-await/higher-ranked-auto-trait-6.no_assumptions.stderr index d1f2d9a07530..d1c88101618a 100644 --- a/tests/ui/async-await/higher-ranked-auto-trait-6.no_assumptions.stderr +++ b/tests/ui/async-await/higher-ranked-auto-trait-6.no_assumptions.stderr @@ -21,30 +21,6 @@ LL | Box::new(async { new(|| async { f().await }).await }) = help: consider pinning your async block and casting it to a trait object = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error[E0308]: mismatched types - --> $DIR/higher-ranked-auto-trait-6.rs:16:5 - | -LL | Box::new(async { new(|| async { f().await }).await }) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one type is more general than the other - | - = note: expected `async` block `{async block@$DIR/higher-ranked-auto-trait-6.rs:16:29: 16:34}` - found `async` block `{async block@$DIR/higher-ranked-auto-trait-6.rs:16:29: 16:34}` - = note: no two async blocks, even if identical, have the same type - = help: consider pinning your async block and casting it to a trait object - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0308]: mismatched types - --> $DIR/higher-ranked-auto-trait-6.rs:16:5 - | -LL | Box::new(async { new(|| async { f().await }).await }) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one type is more general than the other - | - = note: expected `async` block `{async block@$DIR/higher-ranked-auto-trait-6.rs:16:29: 16:34}` - found `async` block `{async block@$DIR/higher-ranked-auto-trait-6.rs:16:29: 16:34}` - = note: no two async blocks, even if identical, have the same type - = help: consider pinning your async block and casting it to a trait object - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 4 previous errors +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/coroutine/print/coroutine-print-verbose-2.stderr b/tests/ui/coroutine/print/coroutine-print-verbose-2.stderr index 8877d45dddad..11b78e3bcf89 100644 --- a/tests/ui/coroutine/print/coroutine-print-verbose-2.stderr +++ b/tests/ui/coroutine/print/coroutine-print-verbose-2.stderr @@ -9,7 +9,7 @@ LL | | drop(a); LL | | }); | |______^ coroutine is not `Sync` | - = help: within `{main::{closure#0} upvar_tys=() resume_ty=() yield_ty=() return_ty=() witness={main::{closure#0}}}`, the trait `Sync` is not implemented for `NotSync` + = help: within `{main::{closure#0} upvar_tys=() resume_ty=() yield_ty=() return_ty=()}`, the trait `Sync` is not implemented for `NotSync` note: coroutine is not `Sync` as this value is used across a yield --> $DIR/coroutine-print-verbose-2.rs:20:9 | @@ -34,7 +34,7 @@ LL | | drop(a); LL | | }); | |______^ coroutine is not `Send` | - = help: within `{main::{closure#1} upvar_tys=() resume_ty=() yield_ty=() return_ty=() witness={main::{closure#1}}}`, the trait `Send` is not implemented for `NotSend` + = help: within `{main::{closure#1} upvar_tys=() resume_ty=() yield_ty=() return_ty=()}`, the trait `Send` is not implemented for `NotSend` note: coroutine is not `Send` as this value is used across a yield --> $DIR/coroutine-print-verbose-2.rs:27:9 | diff --git a/tests/ui/coroutine/print/coroutine-print-verbose-3.stderr b/tests/ui/coroutine/print/coroutine-print-verbose-3.stderr index 4a1e5b078a80..135e81757938 100644 --- a/tests/ui/coroutine/print/coroutine-print-verbose-3.stderr +++ b/tests/ui/coroutine/print/coroutine-print-verbose-3.stderr @@ -11,7 +11,7 @@ LL | | }; | |_____^ expected `()`, found coroutine | = note: expected unit type `()` - found coroutine `{main::{closure#0} upvar_tys=?4t resume_ty=() yield_ty=i32 return_ty=&'?1 str witness={main::{closure#0}}}` + found coroutine `{main::{closure#0} upvar_tys=?4t resume_ty=() yield_ty=i32 return_ty=&'?1 str}` error: aborting due to 1 previous error diff --git a/tests/ui/impl-trait/issues/issue-55872-2.rs b/tests/ui/impl-trait/issues/issue-55872-2.rs index a3b2225126a2..aea00dd9e3d5 100644 --- a/tests/ui/impl-trait/issues/issue-55872-2.rs +++ b/tests/ui/impl-trait/issues/issue-55872-2.rs @@ -12,7 +12,6 @@ impl Bar for S { type E = impl std::marker::Send; fn foo() -> Self::E { //~^ ERROR type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias - //~| ERROR type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias async {} } } diff --git a/tests/ui/impl-trait/issues/issue-55872-2.stderr b/tests/ui/impl-trait/issues/issue-55872-2.stderr index 51a7dd00ade6..91c2ecdc8a47 100644 --- a/tests/ui/impl-trait/issues/issue-55872-2.stderr +++ b/tests/ui/impl-trait/issues/issue-55872-2.stderr @@ -4,13 +4,5 @@ error: type parameter `T` is part of concrete type but not used in parameter lis LL | fn foo() -> Self::E { | ^^^^^^^ -error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias - --> $DIR/issue-55872-2.rs:13:20 - | -LL | fn foo() -> Self::E { - | ^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/impl-trait/issues/issue-55872-3.rs b/tests/ui/impl-trait/issues/issue-55872-3.rs index 763b4b9fd32d..698e7f362341 100644 --- a/tests/ui/impl-trait/issues/issue-55872-3.rs +++ b/tests/ui/impl-trait/issues/issue-55872-3.rs @@ -14,7 +14,6 @@ impl Bar for S { fn foo() -> Self::E { //~^ ERROR : Copy` is not satisfied [E0277] //~| ERROR type parameter `T` is part of concrete type - //~| ERROR type parameter `T` is part of concrete type async {} } } diff --git a/tests/ui/impl-trait/issues/issue-55872-3.stderr b/tests/ui/impl-trait/issues/issue-55872-3.stderr index b7711e47468e..5124c46baeb9 100644 --- a/tests/ui/impl-trait/issues/issue-55872-3.stderr +++ b/tests/ui/impl-trait/issues/issue-55872-3.stderr @@ -4,20 +4,12 @@ error: type parameter `T` is part of concrete type but not used in parameter lis LL | fn foo() -> Self::E { | ^^^^^^^ -error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias +error[E0277]: the trait bound `{async block@$DIR/issue-55872-3.rs:17:9: 17:14}: Copy` is not satisfied --> $DIR/issue-55872-3.rs:14:20 | LL | fn foo() -> Self::E { - | ^^^^^^^ - | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + | ^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/issue-55872-3.rs:17:9: 17:14}` -error[E0277]: the trait bound `{async block@$DIR/issue-55872-3.rs:18:9: 18:14}: Copy` is not satisfied - --> $DIR/issue-55872-3.rs:14:20 - | -LL | fn foo() -> Self::E { - | ^^^^^^^ the trait `Copy` is not implemented for `{async block@$DIR/issue-55872-3.rs:18:9: 18:14}` - -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. From 32f4876bf156317536c7a2a06f451fedf8afc22a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 31 Jul 2025 19:39:59 +0200 Subject: [PATCH 401/809] Create a typed wrapper for codegen backends To avoid representing them just with strings. --- src/bootstrap/src/core/build_steps/check.rs | 19 +++++---- src/bootstrap/src/core/build_steps/compile.rs | 24 ++++++----- src/bootstrap/src/core/build_steps/dist.rs | 30 +++++++------- src/bootstrap/src/core/build_steps/install.rs | 4 +- src/bootstrap/src/core/build_steps/test.rs | 10 +++-- src/bootstrap/src/core/builder/cargo.rs | 2 +- src/bootstrap/src/core/builder/mod.rs | 16 ++++---- src/bootstrap/src/core/builder/tests.rs | 24 +++++------ src/bootstrap/src/core/config/config.rs | 12 +++--- src/bootstrap/src/core/config/toml/rust.rs | 27 +++++++++---- src/bootstrap/src/core/config/toml/target.rs | 8 ++-- src/bootstrap/src/lib.rs | 40 +++++++++++++++++++ src/bootstrap/src/utils/build_stamp.rs | 6 +-- 13 files changed, 143 insertions(+), 79 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index b4232409ba83..f6653ed899bf 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -13,7 +13,7 @@ use crate::core::builder::{ }; use crate::core::config::TargetSelection; use crate::utils::build_stamp::{self, BuildStamp}; -use crate::{Compiler, Mode, Subcommand}; +use crate::{CodegenBackendKind, Compiler, Mode, Subcommand}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Std { @@ -312,7 +312,7 @@ fn prepare_compiler_for_check( pub struct CodegenBackend { pub build_compiler: Compiler, pub target: TargetSelection, - pub backend: &'static str, + pub backend: CodegenBackendKind, } impl Step for CodegenBackend { @@ -327,14 +327,14 @@ impl Step for CodegenBackend { fn make_run(run: RunConfig<'_>) { // FIXME: only check the backend(s) that were actually selected in run.paths let build_compiler = prepare_compiler_for_check(run.builder, run.target, Mode::Codegen); - for &backend in &["cranelift", "gcc"] { + for backend in [CodegenBackendKind::Cranelift, CodegenBackendKind::Gcc] { run.builder.ensure(CodegenBackend { build_compiler, target: run.target, backend }); } } fn run(self, builder: &Builder<'_>) { // FIXME: remove once https://github.com/rust-lang/rust/issues/112393 is resolved - if builder.build.config.vendor && self.backend == "gcc" { + if builder.build.config.vendor && self.backend.is_gcc() { println!("Skipping checking of `rustc_codegen_gcc` with vendoring enabled."); return; } @@ -354,19 +354,22 @@ impl Step for CodegenBackend { cargo .arg("--manifest-path") - .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml"))); + .arg(builder.src.join(format!("compiler/{}/Cargo.toml", backend.crate_name()))); rustc_cargo_env(builder, &mut cargo, target); - let _guard = builder.msg_check(format!("rustc_codegen_{backend}"), target, None); + let _guard = builder.msg_check(backend.crate_name(), target, None); - let stamp = build_stamp::codegen_backend_stamp(builder, build_compiler, target, backend) + let stamp = build_stamp::codegen_backend_stamp(builder, build_compiler, target, &backend) .with_prefix("check"); run_cargo(builder, cargo, builder.config.free_args.clone(), &stamp, vec![], true, false); } fn metadata(&self) -> Option { - Some(StepMetadata::check(self.backend, self.target).built_by(self.build_compiler)) + Some( + StepMetadata::check(&self.backend.crate_name(), self.target) + .built_by(self.build_compiler), + ) } } diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 4abfe1843ebe..59541bf12def 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -33,7 +33,10 @@ use crate::utils::exec::command; use crate::utils::helpers::{ exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date, }; -use crate::{CLang, Compiler, DependencyType, FileType, GitRepo, LLVM_TOOLS, Mode, debug, trace}; +use crate::{ + CLang, CodegenBackendKind, Compiler, DependencyType, FileType, GitRepo, LLVM_TOOLS, Mode, + debug, trace, +}; /// Build a standard library for the given `target` using the given `compiler`. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -1330,7 +1333,7 @@ pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetS } if let Some(backend) = builder.config.default_codegen_backend(target) { - cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", backend); + cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", backend.name()); } let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib")); @@ -1543,7 +1546,7 @@ impl Step for RustcLink { pub struct CodegenBackend { pub target: TargetSelection, pub compiler: Compiler, - pub backend: String, + pub backend: CodegenBackendKind, } fn needs_codegen_config(run: &RunConfig<'_>) -> bool { @@ -1568,7 +1571,7 @@ fn is_codegen_cfg_needed(path: &TaskPath, run: &RunConfig<'_>) -> bool { if path.contains(CODEGEN_BACKEND_PREFIX) { let mut needs_codegen_backend_config = true; for backend in run.builder.config.codegen_backends(run.target) { - if path.ends_with(&(CODEGEN_BACKEND_PREFIX.to_owned() + backend)) { + if path.ends_with(&(CODEGEN_BACKEND_PREFIX.to_owned() + backend.name())) { needs_codegen_backend_config = false; } } @@ -1602,7 +1605,7 @@ impl Step for CodegenBackend { } for backend in run.builder.config.codegen_backends(run.target) { - if backend == "llvm" { + if backend.is_llvm() { continue; // Already built as part of rustc } @@ -1663,20 +1666,21 @@ impl Step for CodegenBackend { ); cargo .arg("--manifest-path") - .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml"))); + .arg(builder.src.join(format!("compiler/{}/Cargo.toml", backend.crate_name()))); rustc_cargo_env(builder, &mut cargo, target); // Ideally, we'd have a separate step for the individual codegen backends, // like we have in tests (test::CodegenGCC) but that would require a lot of restructuring. // If the logic gets more complicated, it should probably be done. - if backend == "gcc" { + if backend.is_gcc() { let gcc = builder.ensure(Gcc { target }); add_cg_gcc_cargo_flags(&mut cargo, &gcc); } let tmp_stamp = BuildStamp::new(&out_dir).with_prefix("tmp"); - let _guard = builder.msg_build(compiler, format_args!("codegen backend {backend}"), target); + let _guard = + builder.msg_build(compiler, format_args!("codegen backend {}", backend.name()), target); let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false, false); if builder.config.dry_run() { return; @@ -1731,7 +1735,7 @@ fn copy_codegen_backends_to_sysroot( } for backend in builder.config.codegen_backends(target) { - if backend == "llvm" { + if backend.is_llvm() { continue; // Already built as part of rustc } @@ -2161,7 +2165,7 @@ impl Step for Assemble { let _codegen_backend_span = span!(tracing::Level::DEBUG, "building requested codegen backends").entered(); for backend in builder.config.codegen_backends(target_compiler.host) { - if backend == "llvm" { + if backend.is_llvm() { debug!("llvm codegen backend is already built as part of rustc"); continue; // Already built as part of rustc } diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index c8a54ad250cb..4699813abf42 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -32,7 +32,7 @@ use crate::utils::helpers::{ exe, is_dylib, move_file, t, target_supports_cranelift_backend, timeit, }; use crate::utils::tarball::{GeneratedTarball, OverlayKind, Tarball}; -use crate::{Compiler, DependencyType, FileType, LLVM_TOOLS, Mode, trace}; +use crate::{CodegenBackendKind, Compiler, DependencyType, FileType, LLVM_TOOLS, Mode, trace}; pub fn pkgname(builder: &Builder<'_>, component: &str) -> String { format!("{}-{}", component, builder.rust_package_vers()) @@ -1372,10 +1372,10 @@ impl Step for Miri { } } -#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] +#[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct CodegenBackend { pub compiler: Compiler, - pub backend: String, + pub backend: CodegenBackendKind, } impl Step for CodegenBackend { @@ -1389,7 +1389,7 @@ impl Step for CodegenBackend { fn make_run(run: RunConfig<'_>) { for backend in run.builder.config.codegen_backends(run.target) { - if backend == "llvm" { + if backend.is_llvm() { continue; // Already built as part of rustc } @@ -1412,12 +1412,11 @@ impl Step for CodegenBackend { return None; } - if !builder.config.codegen_backends(self.compiler.host).contains(&self.backend.to_string()) - { + if !builder.config.codegen_backends(self.compiler.host).contains(&self.backend) { return None; } - if self.backend == "cranelift" && !target_supports_cranelift_backend(self.compiler.host) { + if self.backend.is_cranelift() && !target_supports_cranelift_backend(self.compiler.host) { builder.info("target not supported by rustc_codegen_cranelift. skipping"); return None; } @@ -1425,15 +1424,18 @@ impl Step for CodegenBackend { let compiler = self.compiler; let backend = self.backend; - let mut tarball = - Tarball::new(builder, &format!("rustc-codegen-{backend}"), &compiler.host.triple); - if backend == "cranelift" { + let mut tarball = Tarball::new( + builder, + &format!("rustc-codegen-{}", backend.name()), + &compiler.host.triple, + ); + if backend.is_cranelift() { tarball.set_overlay(OverlayKind::RustcCodegenCranelift); } else { - panic!("Unknown backend rustc_codegen_{backend}"); + panic!("Unknown codegen backend {}", backend.name()); } tarball.is_preview(true); - tarball.add_legal_and_readme_to(format!("share/doc/rustc_codegen_{backend}")); + tarball.add_legal_and_readme_to(format!("share/doc/{}", backend.crate_name())); let src = builder.sysroot(compiler); let backends_src = builder.sysroot_codegen_backends(compiler); @@ -1445,7 +1447,7 @@ impl Step for CodegenBackend { // Don't use custom libdir here because ^lib/ will be resolved again with installer let backends_dst = PathBuf::from("lib").join(backends_rel); - let backend_name = format!("rustc_codegen_{backend}"); + let backend_name = backend.crate_name(); let mut found_backend = false; for backend in fs::read_dir(&backends_src).unwrap() { let file_name = backend.unwrap().file_name(); @@ -1575,7 +1577,7 @@ impl Step for Extended { add_component!("analysis" => Analysis { compiler, target }); add_component!("rustc-codegen-cranelift" => CodegenBackend { compiler: builder.compiler(stage, target), - backend: "cranelift".to_string(), + backend: CodegenBackendKind::Cranelift, }); add_component!("llvm-bitcode-linker" => LlvmBitcodeLinker { build_compiler: compiler, diff --git a/src/bootstrap/src/core/build_steps/install.rs b/src/bootstrap/src/core/build_steps/install.rs index 4156b49a8b33..4513a138e192 100644 --- a/src/bootstrap/src/core/build_steps/install.rs +++ b/src/bootstrap/src/core/build_steps/install.rs @@ -12,7 +12,7 @@ use crate::core::config::{Config, TargetSelection}; use crate::utils::exec::command; use crate::utils::helpers::t; use crate::utils::tarball::GeneratedTarball; -use crate::{Compiler, Kind}; +use crate::{CodegenBackendKind, Compiler, Kind}; #[cfg(target_os = "illumos")] const SHELL: &str = "bash"; @@ -276,7 +276,7 @@ install!((self, builder, _config), RustcCodegenCranelift, alias = "rustc-codegen-cranelift", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::CodegenBackend { compiler: self.compiler, - backend: "cranelift".to_string(), + backend: CodegenBackendKind::Cranelift, }) { install_sh(builder, "rustc-codegen-cranelift", self.compiler.stage, Some(self.target), &tarball); } else { diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 951ca73fcc49..119fa4237bcf 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -33,7 +33,7 @@ use crate::utils::helpers::{ 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, DocTests, GitRepo, Mode, PathSet, debug, envify}; +use crate::{CLang, CodegenBackendKind, DocTests, GitRepo, Mode, PathSet, debug, envify}; const ADB_TEST_DIR: &str = "/data/local/tmp/work"; @@ -1786,7 +1786,9 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.host_target)); if let Some(codegen_backend) = builder.config.default_codegen_backend(compiler.host) { - cmd.arg("--codegen-backend").arg(&codegen_backend); + // Tells compiletest which codegen backend is used by default by the compiler. + // It is used to e.g. ignore tests that don't support that codegen backend. + cmd.arg("--codegen-backend").arg(codegen_backend.name()); } if builder.build.config.llvm_enzyme { @@ -3406,7 +3408,7 @@ impl Step for CodegenCranelift { return; } - if !builder.config.codegen_backends(run.target).contains(&"cranelift".to_owned()) { + if !builder.config.codegen_backends(run.target).contains(&CodegenBackendKind::Cranelift) { builder.info("cranelift not in rust.codegen-backends. skipping"); return; } @@ -3533,7 +3535,7 @@ impl Step for CodegenGCC { return; } - if !builder.config.codegen_backends(run.target).contains(&"gcc".to_owned()) { + if !builder.config.codegen_backends(run.target).contains(&CodegenBackendKind::Gcc) { builder.info("gcc not in rust.codegen-backends. skipping"); return; } diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index badd5f24dba7..6b3236ef47ef 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -1286,7 +1286,7 @@ impl Builder<'_> { if let Some(limit) = limit && (build_compiler_stage == 0 - || self.config.default_codegen_backend(target).unwrap_or_default() == "llvm") + || self.config.default_codegen_backend(target).unwrap_or_default().is_llvm()) { rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={limit}")); } diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 020622d1c121..96289a63785e 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -141,7 +141,7 @@ pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash { #[allow(unused)] #[derive(Debug, PartialEq, Eq)] pub struct StepMetadata { - name: &'static str, + name: String, kind: Kind, target: TargetSelection, built_by: Option, @@ -151,28 +151,28 @@ pub struct StepMetadata { } impl StepMetadata { - pub fn build(name: &'static str, target: TargetSelection) -> Self { + pub fn build(name: &str, target: TargetSelection) -> Self { Self::new(name, target, Kind::Build) } - pub fn check(name: &'static str, target: TargetSelection) -> Self { + pub fn check(name: &str, target: TargetSelection) -> Self { Self::new(name, target, Kind::Check) } - pub fn doc(name: &'static str, target: TargetSelection) -> Self { + pub fn doc(name: &str, target: TargetSelection) -> Self { Self::new(name, target, Kind::Doc) } - pub fn dist(name: &'static str, target: TargetSelection) -> Self { + pub fn dist(name: &str, target: TargetSelection) -> Self { Self::new(name, target, Kind::Dist) } - pub fn test(name: &'static str, target: TargetSelection) -> Self { + pub fn test(name: &str, target: TargetSelection) -> Self { Self::new(name, target, Kind::Test) } - fn new(name: &'static str, target: TargetSelection, kind: Kind) -> Self { - Self { name, kind, target, built_by: None, stage: None, metadata: None } + fn new(name: &str, target: TargetSelection, kind: Kind) -> Self { + Self { name: name.to_string(), kind, target, built_by: None, stage: None, metadata: None } } pub fn built_by(mut self, compiler: Compiler) -> Self { diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 6ea5d4e65532..7192c9f9a175 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1309,8 +1309,8 @@ mod snapshot { .path("compiler") .render_steps(), @r" [check] rustc 0 -> rustc 1 - [check] rustc 0 -> cranelift 1 - [check] rustc 0 -> gcc 1 + [check] rustc 0 -> rustc_codegen_cranelift 1 + [check] rustc 0 -> rustc_codegen_gcc 1 "); } @@ -1341,8 +1341,8 @@ mod snapshot { .stage(1) .render_steps(), @r" [check] rustc 0 -> rustc 1 - [check] rustc 0 -> cranelift 1 - [check] rustc 0 -> gcc 1 + [check] rustc 0 -> rustc_codegen_cranelift 1 + [check] rustc 0 -> rustc_codegen_gcc 1 "); } @@ -1358,8 +1358,8 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 [check] rustc 1 -> rustc 2 - [check] rustc 1 -> cranelift 2 - [check] rustc 1 -> gcc 2 + [check] rustc 1 -> rustc_codegen_cranelift 2 + [check] rustc 1 -> rustc_codegen_gcc 2 "); } @@ -1377,8 +1377,8 @@ mod snapshot { [build] rustc 1 -> std 1 [check] rustc 1 -> rustc 2 [check] rustc 1 -> Rustdoc 2 - [check] rustc 1 -> cranelift 2 - [check] rustc 1 -> gcc 2 + [check] rustc 1 -> rustc_codegen_cranelift 2 + [check] rustc 1 -> rustc_codegen_gcc 2 [check] rustc 1 -> Clippy 2 [check] rustc 1 -> Miri 2 [check] rustc 1 -> CargoMiri 2 @@ -1472,8 +1472,8 @@ mod snapshot { .args(&args) .render_steps(), @r" [check] rustc 0 -> rustc 1 - [check] rustc 0 -> cranelift 1 - [check] rustc 0 -> gcc 1 + [check] rustc 0 -> rustc_codegen_cranelift 1 + [check] rustc 0 -> rustc_codegen_gcc 1 "); } @@ -1557,8 +1557,8 @@ mod snapshot { .path("rustc_codegen_cranelift") .render_steps(), @r" [check] rustc 0 -> rustc 1 - [check] rustc 0 -> cranelift 1 - [check] rustc 0 -> gcc 1 + [check] rustc 0 -> rustc_codegen_cranelift 1 + [check] rustc 0 -> rustc_codegen_gcc 1 "); } diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 78abdd7f9b8c..6055876c4757 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -51,7 +51,7 @@ use crate::core::download::{ use crate::utils::channel; use crate::utils::exec::{ExecutionContext, command}; use crate::utils::helpers::{exe, get_host_target}; -use crate::{GitInfo, OnceLock, TargetSelection, check_ci_llvm, helpers, t}; +use crate::{CodegenBackendKind, GitInfo, OnceLock, TargetSelection, check_ci_llvm, helpers, t}; /// Each path in this list is considered "allowed" in the `download-rustc="if-unchanged"` logic. /// This means they can be modified and changes to these paths should never trigger a compiler build @@ -208,7 +208,7 @@ pub struct Config { pub rustc_default_linker: Option, pub rust_optimize_tests: bool, pub rust_dist_src: bool, - pub rust_codegen_backends: Vec, + pub rust_codegen_backends: Vec, pub rust_verify_llvm_ir: bool, pub rust_thin_lto_import_instr_limit: Option, pub rust_randomize_layout: bool, @@ -350,7 +350,7 @@ impl Config { channel: "dev".to_string(), codegen_tests: true, rust_dist_src: true, - rust_codegen_backends: vec!["llvm".to_owned()], + rust_codegen_backends: vec![CodegenBackendKind::Llvm], deny_warnings: true, bindir: "bin".into(), dist_include_mingw_linker: true, @@ -1747,7 +1747,7 @@ impl Config { .unwrap_or(self.profiler) } - pub fn codegen_backends(&self, target: TargetSelection) -> &[String] { + pub fn codegen_backends(&self, target: TargetSelection) -> &[CodegenBackendKind] { self.target_config .get(&target) .and_then(|cfg| cfg.codegen_backends.as_deref()) @@ -1758,7 +1758,7 @@ impl Config { self.target_config.get(&target).and_then(|cfg| cfg.jemalloc).unwrap_or(self.jemalloc) } - pub fn default_codegen_backend(&self, target: TargetSelection) -> Option { + pub fn default_codegen_backend(&self, target: TargetSelection) -> Option { self.codegen_backends(target).first().cloned() } @@ -1774,7 +1774,7 @@ impl Config { } pub fn llvm_enabled(&self, target: TargetSelection) -> bool { - self.codegen_backends(target).contains(&"llvm".to_owned()) + self.codegen_backends(target).contains(&CodegenBackendKind::Llvm) } pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind { diff --git a/src/bootstrap/src/core/config/toml/rust.rs b/src/bootstrap/src/core/config/toml/rust.rs index c136bd4a6f9b..03da993a17dd 100644 --- a/src/bootstrap/src/core/config/toml/rust.rs +++ b/src/bootstrap/src/core/config/toml/rust.rs @@ -11,7 +11,9 @@ use crate::core::config::{ DebuginfoLevel, Merge, ReplaceOpt, RustcLto, StringOrBool, set, threads_from_config, }; use crate::flags::Warnings; -use crate::{BTreeSet, Config, HashSet, PathBuf, TargetSelection, define_config, exit}; +use crate::{ + BTreeSet, CodegenBackendKind, Config, HashSet, PathBuf, TargetSelection, define_config, exit, +}; define_config! { /// TOML representation of how the Rust build is configured. @@ -389,9 +391,13 @@ pub fn check_incompatible_options_for_ci_rustc( Ok(()) } -pub(crate) const VALID_CODEGEN_BACKENDS: &[&str] = &["llvm", "cranelift", "gcc"]; +pub(crate) const BUILTIN_CODEGEN_BACKENDS: &[&str] = &["llvm", "cranelift", "gcc"]; -pub(crate) fn validate_codegen_backends(backends: Vec, section: &str) -> Vec { +pub(crate) fn parse_codegen_backends( + backends: Vec, + section: &str, +) -> Vec { + let mut found_backends = vec![]; for backend in &backends { if let Some(stripped) = backend.strip_prefix(CODEGEN_BACKEND_PREFIX) { panic!( @@ -400,14 +406,21 @@ pub(crate) fn validate_codegen_backends(backends: Vec, section: &str) -> Please, use '{stripped}' instead." ) } - if !VALID_CODEGEN_BACKENDS.contains(&backend.as_str()) { + if !BUILTIN_CODEGEN_BACKENDS.contains(&backend.as_str()) { println!( "HELP: '{backend}' for '{section}.codegen-backends' might fail. \ - List of known good values: {VALID_CODEGEN_BACKENDS:?}" + List of known codegen backends: {BUILTIN_CODEGEN_BACKENDS:?}" ); } + let backend = match backend.as_str() { + "llvm" => CodegenBackendKind::Llvm, + "cranelift" => CodegenBackendKind::Cranelift, + "gcc" => CodegenBackendKind::Gcc, + backend => CodegenBackendKind::Custom(backend.to_string()), + }; + found_backends.push(backend); } - backends + found_backends } #[cfg(not(test))] @@ -609,7 +622,7 @@ impl Config { llvm_libunwind.map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")); set( &mut self.rust_codegen_backends, - codegen_backends.map(|backends| validate_codegen_backends(backends, "rust")), + codegen_backends.map(|backends| parse_codegen_backends(backends, "rust")), ); self.rust_codegen_units = codegen_units.map(threads_from_config); diff --git a/src/bootstrap/src/core/config/toml/target.rs b/src/bootstrap/src/core/config/toml/target.rs index 337276948b32..9dedadff3a19 100644 --- a/src/bootstrap/src/core/config/toml/target.rs +++ b/src/bootstrap/src/core/config/toml/target.rs @@ -16,9 +16,9 @@ use std::collections::HashMap; use serde::{Deserialize, Deserializer}; -use crate::core::config::toml::rust::validate_codegen_backends; +use crate::core::config::toml::rust::parse_codegen_backends; use crate::core::config::{LlvmLibunwind, Merge, ReplaceOpt, SplitDebuginfo, StringOrBool}; -use crate::{Config, HashSet, PathBuf, TargetSelection, define_config, exit}; +use crate::{CodegenBackendKind, Config, HashSet, PathBuf, TargetSelection, define_config, exit}; define_config! { /// TOML representation of how each build target is configured. @@ -76,7 +76,7 @@ pub struct Target { pub qemu_rootfs: Option, pub runner: Option, pub no_std: bool, - pub codegen_backends: Option>, + pub codegen_backends: Option>, pub optimized_compiler_builtins: Option, pub jemalloc: Option, } @@ -144,7 +144,7 @@ impl Config { target.jemalloc = cfg.jemalloc; if let Some(backends) = cfg.codegen_backends { target.codegen_backends = - Some(validate_codegen_backends(backends, &format!("target.{triple}"))) + Some(parse_codegen_backends(backends, &format!("target.{triple}"))) } target.split_debuginfo = cfg.split_debuginfo.as_ref().map(|v| { diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 51a84ad5272c..011b52df97bb 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -123,6 +123,46 @@ impl PartialEq for Compiler { } } +/// Represents a codegen backend. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)] +pub enum CodegenBackendKind { + #[default] + Llvm, + Cranelift, + Gcc, + Custom(String), +} + +impl CodegenBackendKind { + /// Name of the codegen backend, as identified in the `compiler` directory + /// (`rustc_codegen_`). + pub fn name(&self) -> &str { + match self { + CodegenBackendKind::Llvm => "llvm", + CodegenBackendKind::Cranelift => "cranelift", + CodegenBackendKind::Gcc => "gcc", + CodegenBackendKind::Custom(name) => name, + } + } + + /// Name of the codegen backend's crate, e.g. `rustc_codegen_cranelift`. + pub fn crate_name(&self) -> String { + format!("rustc_codegen_{}", self.name()) + } + + pub fn is_llvm(&self) -> bool { + matches!(self, Self::Llvm) + } + + pub fn is_cranelift(&self) -> bool { + matches!(self, Self::Cranelift) + } + + pub fn is_gcc(&self) -> bool { + matches!(self, Self::Gcc) + } +} + #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum DocTests { /// Run normal tests and doc tests (default). diff --git a/src/bootstrap/src/utils/build_stamp.rs b/src/bootstrap/src/utils/build_stamp.rs index f43d860893f6..bd4eb790ae50 100644 --- a/src/bootstrap/src/utils/build_stamp.rs +++ b/src/bootstrap/src/utils/build_stamp.rs @@ -10,7 +10,7 @@ use sha2::digest::Digest; use crate::core::builder::Builder; use crate::core::config::TargetSelection; use crate::utils::helpers::{hex_encode, mtime}; -use crate::{Compiler, Mode, helpers, t}; +use crate::{CodegenBackendKind, Compiler, Mode, helpers, t}; #[cfg(test)] mod tests; @@ -129,10 +129,10 @@ pub fn codegen_backend_stamp( builder: &Builder<'_>, compiler: Compiler, target: TargetSelection, - backend: &str, + backend: &CodegenBackendKind, ) -> BuildStamp { BuildStamp::new(&builder.cargo_out(compiler, Mode::Codegen, target)) - .with_prefix(&format!("librustc_codegen_{backend}")) + .with_prefix(&format!("lib{}", backend.crate_name())) } /// Cargo's output path for the standard library in a given stage, compiled From f554c79ef819cbc0f9983d0d5306cd7a9bfea6d8 Mon Sep 17 00:00:00 2001 From: Zachary S Date: Wed, 30 Jul 2025 15:35:19 -0500 Subject: [PATCH 402/809] 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 403/809] 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 37d52ed092b1bb2d263702f59da56c06b7b26613 Mon Sep 17 00:00:00 2001 From: Curtis D'Alves Date: Thu, 31 Jul 2025 15:49:23 -0400 Subject: [PATCH 404/809] add correct dynamic_lib_extension for aix --- src/tools/run-make-support/src/artifact_names.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tools/run-make-support/src/artifact_names.rs b/src/tools/run-make-support/src/artifact_names.rs index a889b30e145d..a2bb11869446 100644 --- a/src/tools/run-make-support/src/artifact_names.rs +++ b/src/tools/run-make-support/src/artifact_names.rs @@ -35,6 +35,8 @@ pub fn dynamic_lib_extension() -> &'static str { "dylib" } else if target.contains("windows") { "dll" + } else if target.contains("aix") { + "a" } else { "so" } From 4e806c8a342589f64f61119f69fc68c565e331c8 Mon Sep 17 00:00:00 2001 From: Stypox Date: Wed, 30 Jul 2025 23:50:31 +0200 Subject: [PATCH 405/809] Add tracing calls to eval_statement/terminator --- .../rustc_const_eval/src/interpret/step.rs | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index 629dcc3523ca..b43854fd60bc 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -9,13 +9,14 @@ use rustc_middle::ty::{self, Instance, Ty}; use rustc_middle::{bug, mir, span_bug}; use rustc_span::source_map::Spanned; use rustc_target::callconv::FnAbi; +use tracing::field::Empty; use tracing::{info, instrument, trace}; use super::{ FnArg, FnVal, ImmTy, Immediate, InterpCx, InterpResult, Machine, MemPlaceMeta, PlaceTy, Projectable, Scalar, interp_ok, throw_ub, throw_unsup_format, }; -use crate::util; +use crate::{enter_trace_span, util}; struct EvaluatedCalleeAndArgs<'tcx, M: Machine<'tcx>> { callee: FnVal<'tcx, M::ExtraFnVal>, @@ -74,7 +75,14 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// /// This does NOT move the statement counter forward, the caller has to do that! pub fn eval_statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> { - info!("{:?}", stmt); + let _span = enter_trace_span!( + M, + step::eval_statement, + stmt = ?stmt.kind, + span = ?stmt.source_info.span, + tracing_separate_thread = Empty, + ); + info!(stmt = ?stmt.kind); use rustc_middle::mir::StatementKind::*; @@ -456,7 +464,14 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } fn eval_terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> InterpResult<'tcx> { - info!("{:?}", terminator.kind); + let _span = enter_trace_span!( + M, + step::eval_terminator, + terminator = ?terminator.kind, + span = ?terminator.source_info.span, + tracing_separate_thread = Empty, + ); + info!(terminator = ?terminator.kind); use rustc_middle::mir::TerminatorKind::*; match terminator.kind { From 188f7367bff680a9e3ef2141a08cec24163ba70d Mon Sep 17 00:00:00 2001 From: Stypox Date: Thu, 31 Jul 2025 00:27:42 +0200 Subject: [PATCH 406/809] Add tracing to more functions related to step.rs --- compiler/rustc_const_eval/src/interpret/call.rs | 7 ++++++- compiler/rustc_const_eval/src/interpret/operand.rs | 12 ++++++++++++ compiler/rustc_const_eval/src/interpret/place.rs | 5 +++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 5b3adba02659..24c440844226 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -11,6 +11,7 @@ use rustc_middle::ty::{self, AdtDef, Instance, Ty, VariantDef}; use rustc_middle::{bug, mir, span_bug}; use rustc_span::sym; use rustc_target::callconv::{ArgAbi, FnAbi, PassMode}; +use tracing::field::Empty; use tracing::{info, instrument, trace}; use super::{ @@ -18,7 +19,7 @@ use super::{ Projectable, Provenance, ReturnAction, ReturnContinuation, Scalar, StackPopInfo, interp_ok, throw_ub, throw_ub_custom, throw_unsup_format, }; -use crate::fluent_generated as fluent; +use crate::{enter_trace_span, fluent_generated as fluent}; /// An argument passed to a function. #[derive(Clone, Debug)] @@ -344,6 +345,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { destination: &PlaceTy<'tcx, M::Provenance>, mut cont: ReturnContinuation, ) -> InterpResult<'tcx> { + let _span = enter_trace_span!(M, step::init_stack_frame, %instance, tracing_separate_thread = Empty); + // Compute callee information. // FIXME: for variadic support, do we have to somehow determine callee's extra_args? let callee_fn_abi = self.fn_abi_of_instance(instance, ty::List::empty())?; @@ -523,6 +526,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { target: Option, unwind: mir::UnwindAction, ) -> InterpResult<'tcx> { + let _span = + enter_trace_span!(M, step::init_fn_call, tracing_separate_thread = Empty, ?fn_val); trace!("init_fn_call: {:#?}", fn_val); let instance = match fn_val { diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 21afd082a055..417134579086 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -13,6 +13,7 @@ use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter}; use rustc_middle::ty::{ConstInt, ScalarInt, Ty, TyCtxt}; use rustc_middle::{bug, mir, span_bug, ty}; use rustc_span::DUMMY_SP; +use tracing::field::Empty; use tracing::trace; use super::{ @@ -20,6 +21,7 @@ use super::{ OffsetMode, PlaceTy, Pointer, Projectable, Provenance, Scalar, alloc_range, err_ub, from_known_layout, interp_ok, mir_assign_valid_types, throw_ub, }; +use crate::enter_trace_span; /// An `Immediate` represents a single immediate self-contained Rust value. /// @@ -770,6 +772,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { mir_place: mir::Place<'tcx>, layout: Option>, ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> { + let _span = enter_trace_span!( + M, + step::eval_place_to_op, + ?mir_place, + tracing_separate_thread = Empty + ); + // Do not use the layout passed in as argument if the base we are looking at // here is not the entire place. let layout = if mir_place.projection.is_empty() { layout } else { None }; @@ -813,6 +822,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { mir_op: &mir::Operand<'tcx>, layout: Option>, ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> { + let _span = + enter_trace_span!(M, step::eval_operand, ?mir_op, tracing_separate_thread = Empty); + use rustc_middle::mir::Operand::*; let op = match mir_op { // FIXME: do some more logic on `move` to invalidate the old location diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index e2284729efdc..45c4edb85037 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -9,6 +9,7 @@ use rustc_abi::{BackendRepr, HasDataLayout, Size}; use rustc_middle::ty::Ty; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::{bug, mir, span_bug}; +use tracing::field::Empty; use tracing::{instrument, trace}; use super::{ @@ -16,6 +17,7 @@ use super::{ InterpResult, Machine, MemoryKind, Misalignment, OffsetMode, OpTy, Operand, Pointer, Projectable, Provenance, Scalar, alloc_range, interp_ok, mir_assign_valid_types, }; +use crate::enter_trace_span; #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)] /// Information required for the sound usage of a `MemPlace`. @@ -524,6 +526,9 @@ where &self, mir_place: mir::Place<'tcx>, ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> { + let _span = + enter_trace_span!(M, step::eval_place, ?mir_place, tracing_separate_thread = Empty); + let mut place = self.local_to_place(mir_place.local)?; // Using `try_fold` turned out to be bad for performance, hence the loop. for elem in mir_place.projection.iter() { From 88c9a256a94dfc3545dadd33fef15e52a6b7d73e Mon Sep 17 00:00:00 2001 From: Stypox Date: Thu, 31 Jul 2025 00:12:48 +0200 Subject: [PATCH 407/809] Add EnteredTraceSpan::or_if_tracing_disabled --- .../rustc_const_eval/src/interpret/call.rs | 5 +-- .../rustc_const_eval/src/interpret/step.rs | 9 ++--- .../rustc_const_eval/src/interpret/util.rs | 35 ++++++++++++++++--- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 24c440844226..b8a653698258 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -19,6 +19,7 @@ use super::{ Projectable, Provenance, ReturnAction, ReturnContinuation, Scalar, StackPopInfo, interp_ok, throw_ub, throw_ub_custom, throw_unsup_format, }; +use crate::interpret::EnteredTraceSpan; use crate::{enter_trace_span, fluent_generated as fluent}; /// An argument passed to a function. @@ -527,8 +528,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { unwind: mir::UnwindAction, ) -> InterpResult<'tcx> { let _span = - enter_trace_span!(M, step::init_fn_call, tracing_separate_thread = Empty, ?fn_val); - trace!("init_fn_call: {:#?}", fn_val); + enter_trace_span!(M, step::init_fn_call, tracing_separate_thread = Empty, ?fn_val) + .or_if_tracing_disabled(|| trace!("init_fn_call: {:#?}", fn_val)); let instance = match fn_val { FnVal::Instance(instance) => instance, diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index b43854fd60bc..9df49c0f4ccd 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -16,6 +16,7 @@ use super::{ FnArg, FnVal, ImmTy, Immediate, InterpCx, InterpResult, Machine, MemPlaceMeta, PlaceTy, Projectable, Scalar, interp_ok, throw_ub, throw_unsup_format, }; +use crate::interpret::EnteredTraceSpan; use crate::{enter_trace_span, util}; struct EvaluatedCalleeAndArgs<'tcx, M: Machine<'tcx>> { @@ -81,8 +82,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { stmt = ?stmt.kind, span = ?stmt.source_info.span, tracing_separate_thread = Empty, - ); - info!(stmt = ?stmt.kind); + ) + .or_if_tracing_disabled(|| info!(stmt = ?stmt.kind)); use rustc_middle::mir::StatementKind::*; @@ -470,8 +471,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { terminator = ?terminator.kind, span = ?terminator.source_info.span, tracing_separate_thread = Empty, - ); - info!(terminator = ?terminator.kind); + ) + .or_if_tracing_disabled(|| info!(terminator = ?terminator.kind)); use rustc_middle::mir::TerminatorKind::*; match terminator.kind { diff --git a/compiler/rustc_const_eval/src/interpret/util.rs b/compiler/rustc_const_eval/src/interpret/util.rs index 6696a0c50260..71800950faab 100644 --- a/compiler/rustc_const_eval/src/interpret/util.rs +++ b/compiler/rustc_const_eval/src/interpret/util.rs @@ -48,10 +48,24 @@ pub(crate) fn create_static_alloc<'tcx>( /// A marker trait returned by [crate::interpret::Machine::enter_trace_span], identifying either a /// real [tracing::span::EnteredSpan] in case tracing is enabled, or the dummy type `()` when -/// tracing is disabled. -pub trait EnteredTraceSpan {} -impl EnteredTraceSpan for () {} -impl EnteredTraceSpan for tracing::span::EnteredSpan {} +/// tracing is disabled. Also see [crate::enter_trace_span!] below. +pub trait EnteredTraceSpan { + /// Allows executing an alternative function when tracing is disabled. Useful for example if you + /// want to open a trace span when tracing is enabled, and alternatively just log a line when + /// tracing is disabled. + fn or_if_tracing_disabled(self, f: impl FnOnce()) -> Self; +} +impl EnteredTraceSpan for () { + fn or_if_tracing_disabled(self, f: impl FnOnce()) -> Self { + f(); // tracing is disabled, execute the function + self + } +} +impl EnteredTraceSpan for tracing::span::EnteredSpan { + fn or_if_tracing_disabled(self, _f: impl FnOnce()) -> Self { + self // tracing is enabled, don't execute anything + } +} /// Shortand for calling [crate::interpret::Machine::enter_trace_span] on a [tracing::info_span!]. /// This is supposed to be compiled out when [crate::interpret::Machine::enter_trace_span] has the @@ -112,6 +126,19 @@ impl EnteredTraceSpan for tracing::span::EnteredSpan {} /// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>; /// let _span = enter_trace_span!(M, step::eval_statement, tracing_separate_thread = tracing::field::Empty); /// ``` +/// +/// ### Executing something else when tracing is disabled +/// +/// [crate::interpret::Machine::enter_trace_span] returns [EnteredTraceSpan], on which you can call +/// [EnteredTraceSpan::or_if_tracing_disabled], to e.g. log a line as an alternative to the tracing +/// span for when tracing is disabled. For example: +/// ```rust +/// # use rustc_const_eval::enter_trace_span; +/// # use rustc_const_eval::interpret::EnteredTraceSpan; +/// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>; +/// let _span = enter_trace_span!(M, step::eval_statement) +/// .or_if_tracing_disabled(|| tracing::info!("eval_statement")); +/// ``` #[macro_export] macro_rules! enter_trace_span { ($machine:ty, $name:ident :: $subname:ident $($tt:tt)*) => { From 8a3a7e625a8b607c018cdcf776fa79e29eaa56c8 Mon Sep 17 00:00:00 2001 From: Urgau Date: Tue, 22 Jul 2025 20:54:22 +0200 Subject: [PATCH 408/809] 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 409/809] 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 410/809] 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 eae1d392e7453f6f1fcd03eb74452dd05929db4e Mon Sep 17 00:00:00 2001 From: Scott Schafer Date: Thu, 31 Jul 2025 15:57:41 -0600 Subject: [PATCH 411/809] chore: Ping Muscraft when annnotate snippets emitter is modified --- triagebot.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/triagebot.toml b/triagebot.toml index 168815465b61..819a4b108974 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1064,6 +1064,10 @@ cc = ["@oli-obk", "@RalfJung", "@JakobDegen", "@davidtwco", "@vakaras"] message = "`rustc_error_messages` was changed" cc = ["@davidtwco", "@compiler-errors", "@TaKO8Ki"] +[mentions."compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs"] +message = "`rustc_errors::annotate_snippet_emitter_writer` was changed" +cc = ["@Muscraft"] + [mentions."compiler/rustc_errors/src/translation.rs"] message = "`rustc_errors::translation` was changed" cc = ["@davidtwco", "@compiler-errors", "@TaKO8Ki"] From 1f787383d4463f18a8ec6da89ca962246b92f226 Mon Sep 17 00:00:00 2001 From: Scott Schafer Date: Thu, 31 Jul 2025 15:57:41 -0600 Subject: [PATCH 412/809] chore: Ping Muscraft when rustc_errors::emitter is modified --- triagebot.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/triagebot.toml b/triagebot.toml index 819a4b108974..b0b0f8d87527 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1068,6 +1068,10 @@ cc = ["@davidtwco", "@compiler-errors", "@TaKO8Ki"] message = "`rustc_errors::annotate_snippet_emitter_writer` was changed" cc = ["@Muscraft"] +[mentions."compiler/rustc_errors/src/emitter.rs"] +message = "`rustc_errors::emitter` was changed" +cc = ["@Muscraft"] + [mentions."compiler/rustc_errors/src/translation.rs"] message = "`rustc_errors::translation` was changed" cc = ["@davidtwco", "@compiler-errors", "@TaKO8Ki"] From 040f71e8123b5994177f787e64aecd9b06cdfa7e Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Fri, 25 Jul 2025 15:18:51 +0200 Subject: [PATCH 413/809] 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