-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathreserve_after_initialization.rs
148 lines (138 loc) · 5.07 KB
/
reserve_after_initialization.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::{VecInitKind, get_vec_init_kind};
use clippy_utils::source::snippet;
use clippy_utils::{is_from_proc_macro, path_to_local_id};
use rustc_errors::Applicability;
use rustc_hir::def::Res;
use rustc_hir::{BindingMode, Block, Expr, ExprKind, HirId, LetStmt, PatKind, QPath, Stmt, StmtKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_session::impl_lint_pass;
use rustc_span::Span;
declare_clippy_lint! {
/// ### What it does
/// Informs the user about a more concise way to create a vector with a known capacity.
///
/// ### Why is this bad?
/// The `Vec::with_capacity` constructor is less complex.
///
/// ### Example
/// ```no_run
/// let mut v: Vec<usize> = vec![];
/// v.reserve(10);
/// ```
/// Use instead:
/// ```no_run
/// let mut v: Vec<usize> = Vec::with_capacity(10);
/// ```
#[clippy::version = "1.74.0"]
pub RESERVE_AFTER_INITIALIZATION,
complexity,
"`reserve` called immediately after `Vec` creation"
}
impl_lint_pass!(ReserveAfterInitialization => [RESERVE_AFTER_INITIALIZATION]);
#[derive(Default)]
pub struct ReserveAfterInitialization {
searcher: Option<VecReserveSearcher>,
}
struct VecReserveSearcher {
local_id: HirId,
err_span: Span,
init_part: String,
space_hint: String,
}
impl VecReserveSearcher {
fn display_err(&self, cx: &LateContext<'_>) {
if self.space_hint.is_empty() {
return;
}
let s = format!("{}Vec::with_capacity({});", self.init_part, self.space_hint);
span_lint_and_sugg(
cx,
RESERVE_AFTER_INITIALIZATION,
self.err_span,
"call to `reserve` immediately after creation",
"consider using `Vec::with_capacity(/* Space hint */)`",
s,
Applicability::HasPlaceholders,
);
}
}
impl<'tcx> LateLintPass<'tcx> for ReserveAfterInitialization {
fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
self.searcher = None;
}
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx LetStmt<'tcx>) {
if let Some(init_expr) = local.init
&& let PatKind::Binding(BindingMode::MUT, id, _, None) = local.pat.kind
&& !local.span.in_external_macro(cx.sess().source_map())
&& let Some(init) = get_vec_init_kind(cx, init_expr)
&& !matches!(
init,
VecInitKind::WithExprCapacity(_) | VecInitKind::WithConstCapacity(_)
)
{
self.searcher = Some(VecReserveSearcher {
local_id: id,
err_span: local.span,
init_part: snippet(
cx,
local
.span
.shrink_to_lo()
.to(init_expr.span.source_callsite().shrink_to_lo()),
"..",
)
.into_owned(),
space_hint: String::new(),
});
}
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if self.searcher.is_none()
&& let ExprKind::Assign(left, right, _) = expr.kind
&& let ExprKind::Path(QPath::Resolved(None, path)) = left.kind
&& let Res::Local(id) = path.res
&& !expr.span.in_external_macro(cx.sess().source_map())
&& let Some(init) = get_vec_init_kind(cx, right)
&& !matches!(
init,
VecInitKind::WithExprCapacity(_) | VecInitKind::WithConstCapacity(_)
)
{
self.searcher = Some(VecReserveSearcher {
local_id: id,
err_span: expr.span,
init_part: snippet(
cx,
left.span.shrink_to_lo().to(right.span.source_callsite().shrink_to_lo()),
"..",
)
.into_owned(), // see `assign_expression` test
space_hint: String::new(),
});
}
}
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
if let Some(searcher) = self.searcher.take() {
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
&& let ExprKind::MethodCall(name, self_arg, [space_hint], _) = expr.kind
&& path_to_local_id(self_arg, searcher.local_id)
&& name.ident.as_str() == "reserve"
&& !is_from_proc_macro(cx, expr)
{
self.searcher = Some(VecReserveSearcher {
err_span: searcher.err_span.to(stmt.span),
space_hint: snippet(cx, space_hint.span, "..").into_owned(),
..searcher
});
} else {
searcher.display_err(cx);
}
}
}
fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
if let Some(searcher) = self.searcher.take() {
searcher.display_err(cx);
}
}
}