Repository navigation
Trigger single_element_loop if the block contains only a final expression
#16513
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| use super::SINGLE_ELEMENT_LOOP; | ||
| use clippy_utils::diagnostics::span_lint_and_sugg; | ||
| use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg}; | ||
| use clippy_utils::source::{indent_of, snippet, snippet_with_applicability}; | ||
| use clippy_utils::visitors::contains_break_or_continue; | ||
| use rustc_ast::Mutability; | ||
|
|
@@ -17,82 +17,112 @@ pub(super) fn check<'tcx>( | |
| body: &'tcx Expr<'_>, | ||
| expr: &'tcx Expr<'_>, | ||
| ) { | ||
| let (arg_expression, prefix) = match arg.kind { | ||
| let Some((arg_expression, prefix)) = extract_single_element(cx, arg) else { | ||
| return; | ||
| }; | ||
|
|
||
| if let ExprKind::Block(block, _) = body.kind | ||
| && (!block.stmts.is_empty() || block.expr.is_some()) | ||
| && !contains_break_or_continue(body) | ||
| { | ||
| emit_lint(cx, pat, arg, expr, arg_expression, prefix, block); | ||
| } | ||
| } | ||
|
|
||
| fn extract_single_element<'tcx>( | ||
| cx: &LateContext<'tcx>, | ||
| arg: &'tcx Expr<'_>, | ||
| ) -> Option<(&'tcx Expr<'tcx>, &'static str)> { | ||
| match arg.kind { | ||
| ExprKind::AddrOf( | ||
| BorrowKind::Ref, | ||
| Mutability::Not, | ||
| Expr { | ||
| kind: ExprKind::Array([arg]), | ||
| kind: ExprKind::Array([inner]), | ||
| .. | ||
| }, | ||
| ) => (arg, "&"), | ||
| ) => Some((inner, "&")), | ||
| ExprKind::AddrOf( | ||
| BorrowKind::Ref, | ||
| Mutability::Mut, | ||
| Expr { | ||
| kind: ExprKind::Array([arg]), | ||
| kind: ExprKind::Array([inner]), | ||
| .. | ||
| }, | ||
| ) => (arg, "&mut "), | ||
| ) => Some((inner, "&mut ")), | ||
| ExprKind::MethodCall( | ||
| method, | ||
| Expr { | ||
| kind: ExprKind::Array([arg]), | ||
| kind: ExprKind::Array([inner]), | ||
| .. | ||
| }, | ||
| [], | ||
| _, | ||
| ) if method.ident.name == sym::iter => (arg, "&"), | ||
| ) if method.ident.name == sym::iter => Some((inner, "&")), | ||
| ExprKind::MethodCall( | ||
| method, | ||
| Expr { | ||
| kind: ExprKind::Array([arg]), | ||
| kind: ExprKind::Array([inner]), | ||
| .. | ||
| }, | ||
| [], | ||
| _, | ||
| ) if method.ident.name == sym::iter_mut => (arg, "&mut "), | ||
| ) if method.ident.name == sym::iter_mut => Some((inner, "&mut ")), | ||
| ExprKind::MethodCall( | ||
| method, | ||
| Expr { | ||
| kind: ExprKind::Array([arg]), | ||
| kind: ExprKind::Array([inner]), | ||
| .. | ||
| }, | ||
| [], | ||
| _, | ||
| ) if method.ident.name == sym::into_iter => (arg, ""), | ||
| ) if method.ident.name == sym::into_iter => Some((inner, "")), | ||
| // Only check for arrays edition 2021 or later, as this case will trigger a compiler error otherwise. | ||
| ExprKind::Array([arg]) if cx.tcx.sess.edition() >= Edition::Edition2021 => (arg, ""), | ||
| _ => return, | ||
| ExprKind::Array([inner]) if cx.tcx.sess.edition() >= Edition::Edition2021 => Some((inner, "")), | ||
| _ => None, | ||
| } | ||
| } | ||
|
|
||
| fn emit_lint<'tcx>( | ||
| cx: &LateContext<'tcx>, | ||
| pat: &'tcx Pat<'_>, | ||
| arg: &'tcx Expr<'_>, | ||
| expr: &'tcx Expr<'_>, | ||
| arg_expression: &'tcx Expr<'_>, | ||
| prefix: &str, | ||
| block: &rustc_hir::Block<'_>, | ||
| ) { | ||
| let mut applicability = Applicability::MachineApplicable; | ||
| let mut pat_snip = snippet_with_applicability(cx, pat.span, "..", &mut applicability); | ||
| if matches!(pat.kind, PatKind::Or(..)) { | ||
| pat_snip = format!("({pat_snip})").into(); | ||
| } | ||
| let mut arg_snip = snippet_with_applicability(cx, arg_expression.span, "..", &mut applicability); | ||
| let mut block_str = snippet_with_applicability(cx, block.span, "..", &mut applicability).into_owned(); | ||
| block_str.remove(0); | ||
| block_str.pop(); | ||
| let indent = if let Some(first_stmt) = block.stmts.first() { | ||
| " ".repeat(indent_of(cx, first_stmt.span).unwrap_or(0)) | ||
| } else if let Some(block_expr) = block.expr { | ||
| " ".repeat(indent_of(cx, block_expr.span).unwrap_or(0)) | ||
| } else { | ||
| String::new() | ||
| }; | ||
| if let ExprKind::Block(block, _) = body.kind | ||
| && !block.stmts.is_empty() | ||
| && !contains_break_or_continue(body) | ||
| { | ||
| let mut applicability = Applicability::MachineApplicable; | ||
| let mut pat_snip = snippet_with_applicability(cx, pat.span, "..", &mut applicability); | ||
| if matches!(pat.kind, PatKind::Or(..)) { | ||
| pat_snip = format!("({pat_snip})").into(); | ||
| } | ||
| let mut arg_snip = snippet_with_applicability(cx, arg_expression.span, "..", &mut applicability); | ||
| let mut block_str = snippet_with_applicability(cx, block.span, "..", &mut applicability).into_owned(); | ||
| block_str.remove(0); | ||
| block_str.pop(); | ||
| let indent = " ".repeat(indent_of(cx, block.stmts[0].span).unwrap_or(0)); | ||
|
|
||
| // Reference iterator from `&(mut) []` or `[].iter(_mut)()`. | ||
| if !prefix.is_empty() | ||
| && ( | ||
| // Precedence of internal expression is less than or equal to precedence of `&expr`. | ||
| cx.precedence(arg_expression) <= ExprPrecedence::Prefix || is_range_literal(arg_expression) | ||
| ) | ||
| { | ||
| arg_snip = format!("({arg_snip})").into(); | ||
| } | ||
| // Reference iterator from `&(mut) []` or `[].iter(_mut)()`. | ||
| if !prefix.is_empty() | ||
| && ( | ||
| // Precedence of internal expression is less than or equal to precedence of `&expr`. | ||
| cx.precedence(arg_expression) <= ExprPrecedence::Prefix || is_range_literal(arg_expression) | ||
| ) | ||
| { | ||
| arg_snip = format!("({arg_snip})").into(); | ||
| } | ||
|
|
||
| if clippy_utils::higher::Range::hir(cx, arg_expression).is_some() { | ||
| if let Some(range) = clippy_utils::higher::Range::hir(cx, arg_expression) { | ||
| if range.start.is_some() { | ||
| // Only suggest iterating over ranges that have a start value. | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's difficult to make meaningful suggestions for a non-iterable range. |
||
| let range_expr = snippet(cx, arg_expression.span, "?").to_string(); | ||
|
|
||
| let sugg = snippet(cx, arg_expression.span, ".."); | ||
| span_lint_and_sugg( | ||
| cx, | ||
|
|
@@ -104,15 +134,17 @@ pub(super) fn check<'tcx>( | |
| Applicability::Unspecified, | ||
| ); | ||
| } else { | ||
| span_lint_and_sugg( | ||
| cx, | ||
| SINGLE_ELEMENT_LOOP, | ||
| expr.span, | ||
| "for loop over a single element", | ||
| "try", | ||
| format!("{{\n{indent}let {pat_snip} = {prefix}{arg_snip};{block_str}}}"), | ||
| applicability, | ||
| ); | ||
| span_lint(cx, SINGLE_ELEMENT_LOOP, expr.span, "for loop over a single element"); | ||
| } | ||
| } else { | ||
| span_lint_and_sugg( | ||
| cx, | ||
| SINGLE_ELEMENT_LOOP, | ||
| expr.span, | ||
| "for loop over a single element", | ||
| "try", | ||
| format!("{{\n{indent}let {pat_snip} = {prefix}{arg_snip};{block_str}}}"), | ||
| applicability, | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| //@no-rustfix | ||
| #![warn(clippy::single_element_loop)] | ||
| #![allow(clippy::single_range_in_vec_init)] | ||
|
|
||
| fn f(print: bool) { | ||
| for _ in [..5] { | ||
| //~^ single_element_loop | ||
| if print { | ||
| println!("Hello from f"); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| error: for loop over a single element | ||
| --> tests/ui/single_element_loop_nofix.rs:6:5 | ||
| | | ||
| LL | / for _ in [..5] { | ||
| LL | | | ||
| LL | | if print { | ||
| LL | | println!("Hello from f"); | ||
| LL | | } | ||
| LL | | } | ||
| | |_____^ | ||
| | | ||
| = note: `-D clippy::single-element-loop` implied by `-D warnings` | ||
| = help: to override `-D warnings` add `#[allow(clippy::single_element_loop)]` | ||
|
|
||
| error: aborting due to 1 previous error | ||
|
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Some existing code has been refactored into functions due to triggering the
clippy::too-many-linescheck.