-
Notifications
You must be signed in to change notification settings - Fork 1.7k
new lint: unnecessary_reserve
#14114
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
Open
wowinter13
wants to merge
7
commits into
rust-lang:master
Choose a base branch
from
wowinter13:new-lint-unnecessary-reserve
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
77ed024
new lint: unnecessary_reserve
wowinter13 6beddf4
fix: declared lints
wowinter13 9cecf41
fix: linter
wowinter13 fcbf890
unnecessary_reserve: address review comments
wowinter13 bdf6640
unnecessary_reserve: lint configuration
wowinter13 e08b89a
unnecessary_reserve: address review comments
wowinter13 37dfd0a
unnecessary_reserve: address review comments
wowinter13 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
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
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,126 @@ | ||
use clippy_config::Conf; | ||
use clippy_utils::diagnostics::span_lint_and_then; | ||
use clippy_utils::msrvs::{self, Msrv}; | ||
use clippy_utils::ty::adt_def_id; | ||
use clippy_utils::visitors::for_each_expr; | ||
use clippy_utils::{SpanlessEq, get_enclosing_block, match_def_path, paths}; | ||
use core::ops::ControlFlow; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{Block, Expr, ExprKind}; | ||
use rustc_lint::{LateContext, LateLintPass}; | ||
use rustc_session::impl_lint_pass; | ||
use rustc_span::sym; | ||
|
||
declare_clippy_lint! { | ||
/// ### What it does | ||
/// | ||
/// This lint checks for a call to `reserve` before `extend` on a `Vec` or `VecDeque`. | ||
/// ### Why is this bad? | ||
/// `extend` implicitly calls `reserve` | ||
/// | ||
/// ### Example | ||
/// ```rust | ||
/// let mut vec: Vec<usize> = vec![]; | ||
/// let array: &[usize] = &[1, 2]; | ||
/// vec.reserve(array.len()); | ||
/// vec.extend(array); | ||
/// ``` | ||
/// Use instead: | ||
/// ```rust | ||
/// let mut vec: Vec<usize> = vec![]; | ||
/// let array: &[usize] = &[1, 2]; | ||
/// vec.extend(array); | ||
/// ``` | ||
#[clippy::version = "1.86.0"] | ||
pub UNNECESSARY_RESERVE, | ||
complexity, | ||
"calling `reserve` before `extend` on a `Vec` or `VecDeque`, when it will be called implicitly" | ||
} | ||
|
||
impl_lint_pass!(UnnecessaryReserve => [UNNECESSARY_RESERVE]); | ||
|
||
pub struct UnnecessaryReserve { | ||
msrv: Msrv, | ||
} | ||
impl UnnecessaryReserve { | ||
pub fn new(conf: &'static Conf) -> Self { | ||
Self { | ||
msrv: conf.msrv.clone(), | ||
} | ||
} | ||
} | ||
|
||
impl<'tcx> LateLintPass<'tcx> for UnnecessaryReserve { | ||
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { | ||
if !self.msrv.meets(msrvs::EXTEND_IMPLICIT_RESERVE) { | ||
return; | ||
} | ||
|
||
if let ExprKind::MethodCall(method, receiver, [arg], _) = expr.kind | ||
&& method.ident.name.as_str() == "reserve" | ||
&& acceptable_type(cx, receiver) | ||
&& let Some(block) = get_enclosing_block(cx, expr.hir_id) | ||
&& let Some(next_stmt_span) = check_extend_method(cx, block, receiver, arg) | ||
&& !next_stmt_span.from_expansion() | ||
{ | ||
let stmt_span = cx | ||
.tcx | ||
.hir() | ||
.parent_id_iter(expr.hir_id) | ||
.next() | ||
.map_or(expr.span, |parent| cx.tcx.hir().span(parent)); | ||
|
||
span_lint_and_then( | ||
cx, | ||
UNNECESSARY_RESERVE, | ||
next_stmt_span, | ||
"unnecessary call to `reserve`", | ||
|diag| { | ||
diag.span_suggestion( | ||
stmt_span, | ||
"remove this line", | ||
String::new(), | ||
Applicability::MaybeIncorrect, | ||
); | ||
}, | ||
); | ||
} | ||
} | ||
|
||
extract_msrv_attr!(LateContext); | ||
} | ||
|
||
fn acceptable_type(cx: &LateContext<'_>, struct_calling_on: &Expr<'_>) -> bool { | ||
adt_def_id(cx.typeck_results().expr_ty_adjusted(struct_calling_on)) | ||
.is_some_and(|did| matches!(cx.tcx.get_diagnostic_name(did), Some(sym::Vec | sym::VecDeque))) | ||
} | ||
|
||
#[must_use] | ||
fn check_extend_method<'tcx>( | ||
cx: &LateContext<'tcx>, | ||
block: &'tcx Block<'tcx>, | ||
struct_expr: &Expr<'tcx>, | ||
arg: &Expr<'tcx>, | ||
) -> Option<rustc_span::Span> { | ||
let mut found_reserve = false; | ||
let mut spanless_eq = SpanlessEq::new(cx).deny_side_effects(); | ||
|
||
for_each_expr(cx, block, |expr: &Expr<'tcx>| { | ||
if !found_reserve { | ||
found_reserve = expr.hir_id == arg.hir_id; | ||
return ControlFlow::Continue(()); | ||
} | ||
|
||
if let ExprKind::MethodCall(_method, struct_calling_on, _, _) = expr.kind | ||
&& let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) | ||
&& let ExprKind::MethodCall(len_method, ..) = arg.kind | ||
&& len_method.ident.name == sym::len | ||
&& match_def_path(cx, expr_def_id, &paths::ITER_EXTEND) | ||
&& acceptable_type(cx, struct_calling_on) | ||
wowinter13 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
&& spanless_eq.eq_expr(struct_calling_on, struct_expr) | ||
{ | ||
return ControlFlow::Break(block.span); | ||
} | ||
ControlFlow::Continue(()) | ||
}) | ||
} |
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
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,114 @@ | ||
#![warn(clippy::unnecessary_reserve)] | ||
#![feature(custom_inner_attributes)] | ||
|
||
#![allow(clippy::unnecessary_operation)] | ||
use std::collections::{HashMap, VecDeque}; | ||
|
||
fn main() { | ||
vec_reserve(); | ||
vec_deque_reserve(); | ||
hash_map_reserve(); | ||
insufficient_msrv(); | ||
box_vec_reserve(); | ||
} | ||
|
||
fn vec_reserve() { | ||
let mut vec: Vec<usize> = vec![]; | ||
let array1: &[usize] = &[1, 2]; | ||
let array2: &[usize] = &[3, 4]; | ||
|
||
// do not lint - different arrays | ||
|
||
vec.extend(array2); | ||
|
||
// do not lint | ||
vec.reserve(1); | ||
vec.extend([1]); | ||
|
||
// do lint | ||
|
||
vec.extend(array1); | ||
|
||
// do lint | ||
{ | ||
|
||
vec.extend(array1) | ||
}; | ||
|
||
// do not lint | ||
|
||
vec.push(1); | ||
vec.extend(array1); | ||
|
||
// do not lint | ||
let mut other_vec: Vec<usize> = Vec::with_capacity(1); | ||
other_vec.extend([1]); | ||
|
||
// do not lint | ||
let mut vec2: Vec<usize> = vec![]; | ||
vec2.extend(array1); | ||
vec2.reserve(array1.len()); | ||
} | ||
|
||
fn vec_deque_reserve() { | ||
let mut vec_deque: VecDeque<usize> = [1].into(); | ||
let array: &[usize] = &[1, 2]; | ||
|
||
// do not lint | ||
vec_deque.reserve(1); | ||
vec_deque.extend([1]); | ||
|
||
// do lint | ||
|
||
vec_deque.extend(array); | ||
|
||
// do not lint | ||
{ | ||
vec_deque.reserve(1); | ||
vec_deque.extend([1]) | ||
}; | ||
|
||
// do not lint | ||
vec_deque.reserve(array.len() + 1); | ||
vec_deque.push_back(1); | ||
vec_deque.extend(array); | ||
|
||
// do not lint | ||
let mut other_vec_deque: VecDeque<usize> = [1].into(); | ||
other_vec_deque.reserve(1); | ||
vec_deque.extend([1]) | ||
} | ||
|
||
fn hash_map_reserve() { | ||
let mut map: HashMap<usize, usize> = HashMap::new(); | ||
let mut other_map: HashMap<usize, usize> = HashMap::new(); | ||
// do not lint | ||
map.reserve(other_map.len()); | ||
map.extend(other_map); | ||
} | ||
|
||
#[clippy::msrv = "1.61"] | ||
fn insufficient_msrv() { | ||
let mut vec: Vec<usize> = vec![]; | ||
let array: &[usize] = &[1, 2]; | ||
|
||
// do not lint | ||
vec.reserve(1); | ||
vec.extend([1]); | ||
|
||
let mut vec_deque: VecDeque<usize> = [1].into(); | ||
let array: &[usize] = &[1, 2]; | ||
|
||
// do not lint | ||
vec_deque.reserve(1); | ||
vec_deque.extend([1]); | ||
} | ||
|
||
fn box_vec_reserve() { | ||
let mut vec: Box<Vec<usize>> = Box::default(); | ||
let array: &[usize] = &[1, 2]; | ||
|
||
// do lint | ||
|
||
vec.extend(array); | ||
} |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.