Skip to content

Commit 24974f7

Browse files
committed
Don't lint vec_init_then_push when further extended
1 parent 38ba055 commit 24974f7

File tree

5 files changed

+256
-71
lines changed

5 files changed

+256
-71
lines changed

clippy_lints/src/vec_init_then_push.rs

Lines changed: 124 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
22
use clippy_utils::higher::{get_vec_init_kind, VecInitKind};
33
use clippy_utils::source::snippet;
4-
use clippy_utils::{path_to_local, path_to_local_id};
5-
use if_chain::if_chain;
4+
use clippy_utils::visitors::for_each_local_use_after_expr;
5+
use clippy_utils::{get_parent_expr, path_to_local_id};
6+
use core::ops::ControlFlow;
67
use rustc_errors::Applicability;
7-
use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, Stmt, StmtKind};
8+
use rustc_hir::def::Res;
9+
use rustc_hir::{
10+
BindingAnnotation, Block, Expr, ExprKind, HirId, Local, Mutability, PatKind, QPath, Stmt, StmtKind, UnOp,
11+
};
812
use rustc_lint::{LateContext, LateLintPass, LintContext};
913
use rustc_middle::lint::in_external_macro;
1014
use rustc_session::{declare_tool_lint, impl_lint_pass};
11-
use rustc_span::Span;
15+
use rustc_span::{Span, Symbol};
1216

1317
declare_clippy_lint! {
1418
/// ### What it does
@@ -43,26 +47,86 @@ pub struct VecInitThenPush {
4347
struct VecPushSearcher {
4448
local_id: HirId,
4549
init: VecInitKind,
46-
lhs_is_local: bool,
47-
lhs_span: Span,
50+
lhs_is_let: bool,
51+
let_ty_span: Option<Span>,
52+
name: Symbol,
4853
err_span: Span,
49-
found: u64,
54+
found: u128,
55+
last_push_expr: HirId,
5056
}
5157
impl VecPushSearcher {
5258
fn display_err(&self, cx: &LateContext<'_>) {
53-
match self.init {
59+
let min_pushes_for_extension = match self.init {
5460
_ if self.found == 0 => return,
55-
VecInitKind::WithLiteralCapacity(x) if x > self.found => return,
61+
VecInitKind::WithConstCapacity(x) if x > self.found => return,
62+
VecInitKind::WithConstCapacity(x) => x,
5663
VecInitKind::WithExprCapacity(_) => return,
57-
_ => (),
64+
_ => 3,
5865
};
5966

60-
let mut s = if self.lhs_is_local {
67+
let mut needs_mut = false;
68+
let res = for_each_local_use_after_expr(cx, self.local_id, self.last_push_expr, |e| {
69+
let Some(parent) = get_parent_expr(cx, e) else {
70+
return ControlFlow::Continue(())
71+
};
72+
let adjusted_ty = cx.typeck_results().expr_ty_adjusted(e);
73+
let adjusted_mut = adjusted_ty.ref_mutability().unwrap_or(Mutability::Not);
74+
needs_mut |= adjusted_mut == Mutability::Mut;
75+
match parent.kind {
76+
ExprKind::AddrOf(_, Mutability::Mut, _) => {
77+
needs_mut = true;
78+
return ControlFlow::Break(true);
79+
},
80+
ExprKind::Unary(UnOp::Deref, _) | ExprKind::Index(..) if !needs_mut => {
81+
let mut last_place = parent;
82+
while let Some(parent) = get_parent_expr(cx, parent) {
83+
if matches!(parent.kind, ExprKind::Unary(UnOp::Deref, _) | ExprKind::Field(..))
84+
|| matches!(parent.kind, ExprKind::Index(e, _) if e.hir_id == last_place.hir_id)
85+
{
86+
last_place = parent;
87+
} else {
88+
break;
89+
}
90+
}
91+
needs_mut |= cx.typeck_results().expr_ty_adjusted(last_place).ref_mutability()
92+
== Some(Mutability::Mut)
93+
|| get_parent_expr(cx, last_place)
94+
.map_or(false, |e| matches!(e.kind, ExprKind::AddrOf(_, Mutability::Mut, _)));
95+
},
96+
ExprKind::MethodCall(_, [recv, ..], _)
97+
if recv.hir_id == e.hir_id
98+
&& adjusted_mut == Mutability::Mut
99+
&& !adjusted_ty.peel_refs().is_slice() =>
100+
{
101+
return ControlFlow::Break(true);
102+
},
103+
ExprKind::Assign(lhs, ..) if e.hir_id == lhs.hir_id => {
104+
needs_mut = true;
105+
return ControlFlow::Break(false);
106+
},
107+
_ => (),
108+
}
109+
ControlFlow::Continue(())
110+
});
111+
112+
// Avoid allocating small `Vec`s when they'll be extended right after.
113+
if res == ControlFlow::Break(true) && self.found <= min_pushes_for_extension {
114+
return;
115+
}
116+
117+
let mut s = if self.lhs_is_let {
61118
String::from("let ")
62119
} else {
63120
String::new()
64121
};
65-
s.push_str(&snippet(cx, self.lhs_span, ".."));
122+
if needs_mut {
123+
s.push_str("mut ");
124+
}
125+
s.push_str(self.name.as_str());
126+
if let Some(span) = self.let_ty_span {
127+
s.push_str(": ");
128+
s.push_str(&snippet(cx, span, "_"));
129+
}
66130
s.push_str(" = vec![..];");
67131

68132
span_lint_and_sugg(
@@ -83,60 +147,63 @@ impl<'tcx> LateLintPass<'tcx> for VecInitThenPush {
83147
}
84148

85149
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
86-
if_chain! {
87-
if !in_external_macro(cx.sess(), local.span);
88-
if let Some(init) = local.init;
89-
if let PatKind::Binding(BindingAnnotation::Mutable, id, _, None) = local.pat.kind;
90-
if let Some(init_kind) = get_vec_init_kind(cx, init);
91-
then {
92-
self.searcher = Some(VecPushSearcher {
93-
local_id: id,
94-
init: init_kind,
95-
lhs_is_local: true,
96-
lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)),
97-
err_span: local.span,
98-
found: 0,
99-
});
100-
}
150+
if let Some(init_expr) = local.init
151+
&& let PatKind::Binding(BindingAnnotation::Mutable, id, name, None) = local.pat.kind
152+
&& !in_external_macro(cx.sess(), local.span)
153+
&& let Some(init) = get_vec_init_kind(cx, init_expr)
154+
&& !matches!(init, VecInitKind::WithExprCapacity(_))
155+
{
156+
self.searcher = Some(VecPushSearcher {
157+
local_id: id,
158+
init,
159+
lhs_is_let: true,
160+
name: name.name,
161+
let_ty_span: local.ty.map(|ty| ty.span),
162+
err_span: local.span,
163+
found: 0,
164+
last_push_expr: init_expr.hir_id,
165+
});
101166
}
102167
}
103168

104169
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
105-
if_chain! {
106-
if self.searcher.is_none();
107-
if !in_external_macro(cx.sess(), expr.span);
108-
if let ExprKind::Assign(left, right, _) = expr.kind;
109-
if let Some(id) = path_to_local(left);
110-
if let Some(init_kind) = get_vec_init_kind(cx, right);
111-
then {
112-
self.searcher = Some(VecPushSearcher {
113-
local_id: id,
114-
init: init_kind,
115-
lhs_is_local: false,
116-
lhs_span: left.span,
117-
err_span: expr.span,
118-
found: 0,
119-
});
120-
}
170+
if self.searcher.is_none()
171+
&& let ExprKind::Assign(left, right, _) = expr.kind
172+
&& let ExprKind::Path(QPath::Resolved(None, path)) = left.kind
173+
&& let [name] = &path.segments
174+
&& let Res::Local(id) = path.res
175+
&& !in_external_macro(cx.sess(), expr.span)
176+
&& let Some(init) = get_vec_init_kind(cx, right)
177+
&& !matches!(init, VecInitKind::WithExprCapacity(_))
178+
{
179+
self.searcher = Some(VecPushSearcher {
180+
local_id: id,
181+
init,
182+
lhs_is_let: false,
183+
let_ty_span: None,
184+
name: name.ident.name,
185+
err_span: expr.span,
186+
found: 0,
187+
last_push_expr: expr.hir_id,
188+
});
121189
}
122190
}
123191

124192
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
125193
if let Some(searcher) = self.searcher.take() {
126-
if_chain! {
127-
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind;
128-
if let ExprKind::MethodCall(path, [self_arg, _], _) = expr.kind;
129-
if path_to_local_id(self_arg, searcher.local_id);
130-
if path.ident.name.as_str() == "push";
131-
then {
132-
self.searcher = Some(VecPushSearcher {
133-
found: searcher.found + 1,
134-
err_span: searcher.err_span.to(stmt.span),
135-
.. searcher
136-
});
137-
} else {
138-
searcher.display_err(cx);
139-
}
194+
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
195+
&& let ExprKind::MethodCall(name, [self_arg, _], _) = expr.kind
196+
&& path_to_local_id(self_arg, searcher.local_id)
197+
&& name.ident.as_str() == "push"
198+
{
199+
self.searcher = Some(VecPushSearcher {
200+
found: searcher.found + 1,
201+
err_span: searcher.err_span.to(stmt.span),
202+
last_push_expr: expr.hir_id,
203+
.. searcher
204+
});
205+
} else {
206+
searcher.display_err(cx);
140207
}
141208
}
142209
}

clippy_utils/src/higher.rs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
33
#![deny(clippy::missing_docs_in_private_items)]
44

5+
use crate::consts::{constant_simple, Constant};
56
use crate::ty::is_type_diagnostic_item;
67
use crate::{is_expn_of, match_def_path, paths};
78
use if_chain::if_chain;
8-
use rustc_ast::ast::{self, LitKind};
9+
use rustc_ast::ast;
910
use rustc_hir as hir;
1011
use rustc_hir::{Arm, Block, Expr, ExprKind, HirId, LoopSource, MatchSource, Node, Pat, QPath};
1112
use rustc_lint::LateContext;
@@ -431,7 +432,7 @@ pub enum VecInitKind {
431432
/// `Vec::default()` or `Default::default()`
432433
Default,
433434
/// `Vec::with_capacity(123)`
434-
WithLiteralCapacity(u64),
435+
WithConstCapacity(u128),
435436
/// `Vec::with_capacity(slice.len())`
436437
WithExprCapacity(HirId),
437438
}
@@ -449,15 +450,11 @@ pub fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -
449450
return Some(VecInitKind::Default);
450451
} else if name.ident.name.as_str() == "with_capacity" {
451452
let arg = args.get(0)?;
452-
if_chain! {
453-
if let ExprKind::Lit(lit) = &arg.kind;
454-
if let LitKind::Int(num, _) = lit.node;
455-
then {
456-
return Some(VecInitKind::WithLiteralCapacity(num.try_into().ok()?));
457-
}
458-
}
459-
return Some(VecInitKind::WithExprCapacity(arg.hir_id));
460-
}
453+
return match constant_simple(cx, cx.typeck_results(), arg) {
454+
Some(Constant::Int(num)) => Some(VecInitKind::WithConstCapacity(num)),
455+
_ => Some(VecInitKind::WithExprCapacity(arg.hir_id)),
456+
};
457+
};
461458
},
462459
ExprKind::Path(QPath::Resolved(_, path))
463460
if match_def_path(cx, path.res.opt_def_id()?, &paths::DEFAULT_TRAIT_METHOD)

clippy_utils/src/visitors.rs

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
use crate::path_to_local_id;
1+
use crate::{get_enclosing_block, path_to_local_id};
2+
use core::ops::ControlFlow;
23
use rustc_hir as hir;
34
use rustc_hir::def::{DefKind, Res};
45
use rustc_hir::intravisit::{self, walk_block, walk_expr, Visitor};
@@ -402,3 +403,61 @@ pub fn contains_unsafe_block<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>)
402403
v.visit_expr(e);
403404
v.found_unsafe
404405
}
406+
407+
/// Runs the given function for each path expression referencing the given local which occur after
408+
/// the given expression.
409+
pub fn for_each_local_use_after_expr<'tcx, B>(
410+
cx: &LateContext<'tcx>,
411+
local_id: HirId,
412+
expr_id: HirId,
413+
f: impl FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>,
414+
) -> ControlFlow<B> {
415+
struct V<'cx, 'tcx, F, B> {
416+
cx: &'cx LateContext<'tcx>,
417+
local_id: HirId,
418+
expr_id: HirId,
419+
found: bool,
420+
res: ControlFlow<B>,
421+
f: F,
422+
}
423+
impl<'cx, 'tcx, F: FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>, B> Visitor<'tcx> for V<'cx, 'tcx, F, B> {
424+
type NestedFilter = nested_filter::OnlyBodies;
425+
fn nested_visit_map(&mut self) -> Self::Map {
426+
self.cx.tcx.hir()
427+
}
428+
429+
fn visit_expr(&mut self, e: &'tcx Expr<'tcx>) {
430+
if !self.found {
431+
if e.hir_id == self.expr_id {
432+
self.found = true;
433+
} else {
434+
walk_expr(self, e);
435+
}
436+
return;
437+
}
438+
if self.res.is_break() {
439+
return;
440+
}
441+
if path_to_local_id(e, self.local_id) {
442+
self.res = (self.f)(e);
443+
} else {
444+
walk_expr(self, e)
445+
}
446+
}
447+
}
448+
449+
if let Some(b) = get_enclosing_block(cx, local_id) {
450+
let mut v = V {
451+
cx,
452+
local_id,
453+
expr_id,
454+
found: false,
455+
res: ControlFlow::Continue(()),
456+
f,
457+
};
458+
v.visit_block(b);
459+
v.res
460+
} else {
461+
ControlFlow::Continue(())
462+
}
463+
}

tests/ui/vec_init_then_push.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,45 @@ pub fn no_lint() -> Vec<i32> {
4444
}
4545
}
4646
}
47+
48+
fn _from_iter(items: impl Iterator<Item = u32>) -> Vec<u32> {
49+
let mut v = Vec::new();
50+
v.push(0);
51+
v.push(1);
52+
v.extend(items);
53+
v
54+
}
55+
56+
fn _cond_push(x: bool) -> Vec<u32> {
57+
let mut v = Vec::new();
58+
v.push(0);
59+
if x {
60+
v.push(1);
61+
}
62+
v.push(2);
63+
v
64+
}
65+
66+
fn _push_then_edit(x: u32) -> Vec<u32> {
67+
let mut v = Vec::new();
68+
v.push(x);
69+
v.push(1);
70+
v[0] = v[1] + 5;
71+
v
72+
}
73+
74+
fn _cond_push_with_large_start(x: bool) -> Vec<u32> {
75+
let mut v = Vec::new();
76+
v.push(0);
77+
v.push(1);
78+
v.push(0);
79+
v.push(1);
80+
v.push(0);
81+
v.push(0);
82+
v.push(1);
83+
v.push(0);
84+
if x {
85+
v.push(1);
86+
}
87+
v
88+
}

0 commit comments

Comments
 (0)