Skip to content

Commit 1853f8b

Browse files
committed
Add lint
1 parent 0d8a27a commit 1853f8b

File tree

5 files changed

+247
-0
lines changed

5 files changed

+247
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2152,6 +2152,7 @@ Released 2018-09-13
21522152
[`useless_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_transmute
21532153
[`useless_vec`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec
21542154
[`vec_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_box
2155+
[`vec_init_then_push`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_init_then_push
21552156
[`vec_resize_to_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_resize_to_zero
21562157
[`verbose_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask
21572158
[`verbose_file_reads`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_file_reads

clippy_lints/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,7 @@ mod unwrap_in_result;
341341
mod use_self;
342342
mod useless_conversion;
343343
mod vec;
344+
mod vec_init_then_push;
344345
mod vec_resize_to_zero;
345346
mod verbose_file_reads;
346347
mod wildcard_dependencies;
@@ -935,6 +936,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
935936
&use_self::USE_SELF,
936937
&useless_conversion::USELESS_CONVERSION,
937938
&vec::USELESS_VEC,
939+
&vec_init_then_push::VEC_INIT_THEN_PUSH,
938940
&vec_resize_to_zero::VEC_RESIZE_TO_ZERO,
939941
&verbose_file_reads::VERBOSE_FILE_READS,
940942
&wildcard_dependencies::WILDCARD_DEPENDENCIES,
@@ -1215,6 +1217,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12151217
store.register_late_pass(|| box strings::StrToString);
12161218
store.register_late_pass(|| box strings::StringToString);
12171219
store.register_late_pass(|| box zero_sized_map_values::ZeroSizedMapValues);
1220+
store.register_late_pass(|| box vec_init_then_push::VecInitThenPush::default());
12181221

12191222
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
12201223
LintId::of(&arithmetic::FLOAT_ARITHMETIC),
@@ -1636,6 +1639,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
16361639
LintId::of(&unwrap::UNNECESSARY_UNWRAP),
16371640
LintId::of(&useless_conversion::USELESS_CONVERSION),
16381641
LintId::of(&vec::USELESS_VEC),
1642+
LintId::of(&vec_init_then_push::VEC_INIT_THEN_PUSH),
16391643
LintId::of(&vec_resize_to_zero::VEC_RESIZE_TO_ZERO),
16401644
LintId::of(&write::PRINTLN_EMPTY_STRING),
16411645
LintId::of(&write::PRINT_LITERAL),
@@ -1935,6 +1939,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
19351939
LintId::of(&types::BOX_VEC),
19361940
LintId::of(&types::REDUNDANT_ALLOCATION),
19371941
LintId::of(&vec::USELESS_VEC),
1942+
LintId::of(&vec_init_then_push::VEC_INIT_THEN_PUSH),
19381943
]);
19391944

19401945
store.register_group(true, "clippy::cargo", Some("clippy_cargo"), vec![
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
use crate::utils::{is_type_diagnostic_item, match_def_path, paths, snippet, span_lint_and_sugg};
2+
use if_chain::if_chain;
3+
use rustc_ast::ast::LitKind;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, Local, PatKind, QPath, Stmt, StmtKind};
6+
use rustc_lint::{LateContext, LateLintPass, LintContext};
7+
use rustc_middle::lint::in_external_macro;
8+
use rustc_session::{declare_tool_lint, impl_lint_pass};
9+
use rustc_span::{symbol::sym, Span, Symbol};
10+
11+
declare_clippy_lint! {
12+
/// **What it does:** Checks for calls to `push` immediately after creating a new `Vec`.
13+
///
14+
/// **Why is this bad?** The `vec![]` macro is both more performant and easier to read than
15+
/// multiple `push` calls.
16+
///
17+
/// **Known problems:** None.
18+
///
19+
/// **Example:**
20+
///
21+
/// ```rust
22+
/// let mut v: Vec<u32> = Vec::new();
23+
/// v.push(0);
24+
/// ```
25+
/// Use instead:
26+
/// ```rust
27+
/// let v: Vec<u32> = vec![0];
28+
/// ```
29+
pub VEC_INIT_THEN_PUSH,
30+
perf,
31+
"`push` immediately after `Vec` creation"
32+
}
33+
34+
impl_lint_pass!(VecInitThenPush => [VEC_INIT_THEN_PUSH]);
35+
36+
#[derive(Default)]
37+
pub struct VecInitThenPush {
38+
searcher: Option<VecPushSearcher>,
39+
}
40+
41+
#[derive(Clone, Copy)]
42+
enum VecInitKind {
43+
New,
44+
WithCapacity(u64),
45+
}
46+
struct VecPushSearcher {
47+
init: VecInitKind,
48+
name: Symbol,
49+
lhs_is_local: bool,
50+
lhs_span: Span,
51+
err_span: Span,
52+
found: u64,
53+
}
54+
impl VecPushSearcher {
55+
fn display_err(&self, cx: &LateContext<'_>) {
56+
match self.init {
57+
_ if self.found == 0 => return,
58+
VecInitKind::WithCapacity(x) if x > self.found => return,
59+
_ => (),
60+
};
61+
62+
let mut s = if self.lhs_is_local {
63+
String::from("let ")
64+
} else {
65+
String::new()
66+
};
67+
s.push_str(&snippet(cx, self.lhs_span, ".."));
68+
s.push_str(" = vec![..];");
69+
70+
span_lint_and_sugg(
71+
cx,
72+
VEC_INIT_THEN_PUSH,
73+
self.err_span,
74+
"calls to `push` immediately after creation",
75+
"consider using the `vec![]` macro",
76+
s,
77+
Applicability::HasPlaceholders,
78+
);
79+
}
80+
}
81+
82+
impl LateLintPass<'_> for VecInitThenPush {
83+
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
84+
self.searcher = None;
85+
if_chain! {
86+
if !in_external_macro(cx.sess(), local.span);
87+
if let Some(init) = local.init;
88+
if let PatKind::Binding(BindingAnnotation::Mutable, _, ident, None) = local.pat.kind;
89+
if let Some(init_kind) = get_vec_init_kind(cx, init);
90+
then {
91+
self.searcher = Some(VecPushSearcher {
92+
init: init_kind,
93+
name: ident.name,
94+
lhs_is_local: true,
95+
lhs_span: local.ty.map(|t| local.pat.span.to(t.span)).unwrap_or(local.pat.span),
96+
err_span: local.span,
97+
found: 0,
98+
});
99+
}
100+
}
101+
}
102+
103+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
104+
if self.searcher.is_none() {
105+
if_chain! {
106+
if !in_external_macro(cx.sess(), expr.span);
107+
if let ExprKind::Assign(left, right, _) = expr.kind;
108+
if let ExprKind::Path(QPath::Resolved(_, path)) = left.kind;
109+
if let Some(name) = path.segments.get(0);
110+
if let Some(init_kind) = get_vec_init_kind(cx, right);
111+
then {
112+
self.searcher = Some(VecPushSearcher {
113+
init: init_kind,
114+
name: name.ident.name,
115+
lhs_is_local: false,
116+
lhs_span: left.span,
117+
err_span: expr.span,
118+
found: 0,
119+
});
120+
}
121+
}
122+
}
123+
}
124+
125+
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
126+
if let Some(searcher) = self.searcher.take() {
127+
if_chain! {
128+
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind;
129+
if let ExprKind::MethodCall(path, _, [self_arg, _], _) = expr.kind;
130+
if path.ident.name.as_str() == "push";
131+
if let ExprKind::Path(QPath::Resolved(_, self_path)) = self_arg.kind;
132+
if let [self_name] = self_path.segments;
133+
if self_name.ident.name == searcher.name;
134+
then {
135+
self.searcher = Some(VecPushSearcher {
136+
found: searcher.found + 1,
137+
err_span: searcher.err_span.to(stmt.span),
138+
.. searcher
139+
});
140+
} else {
141+
searcher.display_err(cx);
142+
}
143+
}
144+
}
145+
}
146+
147+
fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
148+
if let Some(searcher) = self.searcher.take() {
149+
searcher.display_err(cx);
150+
}
151+
}
152+
}
153+
154+
fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<VecInitKind> {
155+
if let ExprKind::Call(func, args) = expr.kind {
156+
match func.kind {
157+
ExprKind::Path(QPath::TypeRelative(ty, name))
158+
if is_type_diagnostic_item(cx, cx.typeck_results().node_type(ty.hir_id), sym::vec_type) =>
159+
{
160+
if name.ident.name.as_str() == "new" {
161+
return Some(VecInitKind::New);
162+
} else if name.ident.name.as_str() == "with_capacity" {
163+
return args.get(0).and_then(|arg| {
164+
if_chain! {
165+
if let ExprKind::Lit(lit) = &arg.kind;
166+
if let LitKind::Int(num, _) = lit.node;
167+
then {
168+
Some(VecInitKind::WithCapacity(num as u64))
169+
} else {
170+
None
171+
}
172+
}
173+
});
174+
}
175+
}
176+
ExprKind::Path(QPath::Resolved(_, path))
177+
if match_def_path(cx, path.res.opt_def_id()?, &paths::DEFAULT_TRAIT_METHOD)
178+
&& is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type) =>
179+
{
180+
return Some(VecInitKind::New);
181+
}
182+
_ => (),
183+
}
184+
}
185+
None
186+
}

tests/ui/vec_init_then_push.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#![allow(unused_variables)]
2+
#![warn(clippy::vec_init_then_push)]
3+
4+
fn main() {
5+
let mut def_err: Vec<u32> = Default::default();
6+
def_err.push(0);
7+
8+
let mut new_err = Vec::<u32>::new();
9+
new_err.push(1);
10+
11+
let mut cap_err = Vec::with_capacity(2);
12+
cap_err.push(0);
13+
cap_err.push(1);
14+
cap_err.push(2);
15+
16+
let mut cap_ok = Vec::with_capacity(10);
17+
cap_ok.push(0);
18+
19+
new_err = Vec::new();
20+
new_err.push(0);
21+
}

tests/ui/vec_init_then_push.stderr

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
error: calls to `push` immediately after creation
2+
--> $DIR/vec_init_then_push.rs:5:5
3+
|
4+
LL | / let mut def_err: Vec<u32> = Default::default();
5+
LL | | def_err.push(0);
6+
| |____________________^ help: consider using the `vec![]` macro: `let mut def_err: Vec<u32> = vec![..];`
7+
|
8+
= note: `-D clippy::vec-init-then-push` implied by `-D warnings`
9+
10+
error: calls to `push` immediately after creation
11+
--> $DIR/vec_init_then_push.rs:8:5
12+
|
13+
LL | / let mut new_err = Vec::<u32>::new();
14+
LL | | new_err.push(1);
15+
| |____________________^ help: consider using the `vec![]` macro: `let mut new_err = vec![..];`
16+
17+
error: calls to `push` immediately after creation
18+
--> $DIR/vec_init_then_push.rs:11:5
19+
|
20+
LL | / let mut cap_err = Vec::with_capacity(2);
21+
LL | | cap_err.push(0);
22+
LL | | cap_err.push(1);
23+
LL | | cap_err.push(2);
24+
| |____________________^ help: consider using the `vec![]` macro: `let mut cap_err = vec![..];`
25+
26+
error: calls to `push` immediately after creation
27+
--> $DIR/vec_init_then_push.rs:19:5
28+
|
29+
LL | / new_err = Vec::new();
30+
LL | | new_err.push(0);
31+
| |____________________^ help: consider using the `vec![]` macro: `new_err = vec![..];`
32+
33+
error: aborting due to 4 previous errors
34+

0 commit comments

Comments
 (0)