Skip to content

Allow manual swap in const fn #9871

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion clippy_lints/src/swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::sugg::Sugg;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{can_mut_borrow_both, eq_expr_value, std_or_core};
use clippy_utils::{can_mut_borrow_both, eq_expr_value, in_constant, std_or_core};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Block, Expr, ExprKind, PatKind, QPath, Stmt, StmtKind};
Expand All @@ -16,6 +16,8 @@ declare_clippy_lint! {
/// ### What it does
/// Checks for manual swapping.
///
/// Note that the lint will not be emitted in const blocks, as the suggestion would not be applicable.
///
/// ### Why is this bad?
/// The `std::mem::swap` function exposes the intent better
/// without deinitializing or copying either variable.
Expand Down Expand Up @@ -138,6 +140,10 @@ fn generate_swap_warning(cx: &LateContext<'_>, e1: &Expr<'_>, e2: &Expr<'_>, spa

/// Implementation of the `MANUAL_SWAP` lint.
fn check_manual_swap(cx: &LateContext<'_>, block: &Block<'_>) {
if in_constant(cx, block.hir_id) {
return;
}

for w in block.stmts.windows(3) {
if_chain! {
// let t = foo();
Expand Down
9 changes: 9 additions & 0 deletions tests/ui/swap.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,12 @@ fn issue_8154() {
let s = S3(&mut s);
std::mem::swap(&mut s.0.x, &mut s.0.y);
}

const fn issue_9864(mut u: u32) -> u32 {
let mut v = 10;

let temp = u;
u = v;
v = temp;
u + v
}
9 changes: 9 additions & 0 deletions tests/ui/swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,12 @@ fn issue_8154() {
s.0.x = s.0.y;
s.0.y = t;
}

const fn issue_9864(mut u: u32) -> u32 {
let mut v = 10;

let temp = u;
u = v;
v = temp;
u + v
}