2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_sugg;
|
2021-10-21 06:11:36 -05:00
|
|
|
use clippy_utils::higher::{get_vec_init_kind, VecInitKind};
|
2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::source::snippet;
|
2022-05-21 06:24:00 -05:00
|
|
|
use clippy_utils::visitors::for_each_local_use_after_expr;
|
|
|
|
use clippy_utils::{get_parent_expr, path_to_local_id};
|
|
|
|
use core::ops::ControlFlow;
|
2021-01-15 03:56:44 -06:00
|
|
|
use rustc_errors::Applicability;
|
2022-05-21 06:24:00 -05:00
|
|
|
use rustc_hir::def::Res;
|
|
|
|
use rustc_hir::{
|
|
|
|
BindingAnnotation, Block, Expr, ExprKind, HirId, Local, Mutability, PatKind, QPath, Stmt, StmtKind, UnOp,
|
|
|
|
};
|
2021-01-15 03:56:44 -06:00
|
|
|
use rustc_lint::{LateContext, LateLintPass, LintContext};
|
|
|
|
use rustc_middle::lint::in_external_macro;
|
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
2022-05-21 06:24:00 -05:00
|
|
|
use rustc_span::{Span, Symbol};
|
2021-01-15 03:56:44 -06:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for calls to `push` immediately after creating a new `Vec`.
|
2021-01-15 03:56:44 -06:00
|
|
|
///
|
2022-05-21 06:24:00 -05:00
|
|
|
/// If the `Vec` is created using `with_capacity` this will only lint if the capacity is a
|
|
|
|
/// constant and the number of pushes is greater than or equal to the initial capacity.
|
|
|
|
///
|
|
|
|
/// If the `Vec` is extended after the initial sequence of pushes and it was default initialized
|
|
|
|
/// then this will only lint after there were at least four pushes. This number may change in
|
|
|
|
/// the future.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// The `vec![]` macro is both more performant and easier to read than
|
2021-01-15 03:56:44 -06:00
|
|
|
/// multiple `push` calls.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2021-01-15 03:56:44 -06:00
|
|
|
/// ```rust
|
|
|
|
/// let mut v = Vec::new();
|
|
|
|
/// v.push(0);
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// let v = vec![0];
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "1.51.0"]
|
2021-01-15 03:56:44 -06:00
|
|
|
pub VEC_INIT_THEN_PUSH,
|
|
|
|
perf,
|
|
|
|
"`push` immediately after `Vec` creation"
|
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(VecInitThenPush => [VEC_INIT_THEN_PUSH]);
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct VecInitThenPush {
|
|
|
|
searcher: Option<VecPushSearcher>,
|
|
|
|
}
|
|
|
|
|
|
|
|
struct VecPushSearcher {
|
2021-02-25 04:25:22 -06:00
|
|
|
local_id: HirId,
|
2021-01-15 03:56:44 -06:00
|
|
|
init: VecInitKind,
|
2022-05-21 06:24:00 -05:00
|
|
|
lhs_is_let: bool,
|
|
|
|
let_ty_span: Option<Span>,
|
|
|
|
name: Symbol,
|
2021-01-15 03:56:44 -06:00
|
|
|
err_span: Span,
|
2022-05-21 06:24:00 -05:00
|
|
|
found: u128,
|
|
|
|
last_push_expr: HirId,
|
2021-01-15 03:56:44 -06:00
|
|
|
}
|
|
|
|
impl VecPushSearcher {
|
|
|
|
fn display_err(&self, cx: &LateContext<'_>) {
|
2022-05-21 06:24:00 -05:00
|
|
|
let required_pushes_before_extension = match self.init {
|
2021-01-15 03:56:44 -06:00
|
|
|
_ if self.found == 0 => return,
|
2022-05-21 06:24:00 -05:00
|
|
|
VecInitKind::WithConstCapacity(x) if x > self.found => return,
|
|
|
|
VecInitKind::WithConstCapacity(x) => x,
|
2021-10-21 06:11:36 -05:00
|
|
|
VecInitKind::WithExprCapacity(_) => return,
|
2022-05-21 06:24:00 -05:00
|
|
|
_ => 3,
|
2021-01-15 03:56:44 -06:00
|
|
|
};
|
|
|
|
|
2022-05-21 06:24:00 -05:00
|
|
|
let mut needs_mut = false;
|
|
|
|
let res = for_each_local_use_after_expr(cx, self.local_id, self.last_push_expr, |e| {
|
|
|
|
let Some(parent) = get_parent_expr(cx, e) else {
|
2023-07-17 03:19:29 -05:00
|
|
|
return ControlFlow::Continue(());
|
2022-05-21 06:24:00 -05:00
|
|
|
};
|
|
|
|
let adjusted_ty = cx.typeck_results().expr_ty_adjusted(e);
|
|
|
|
let adjusted_mut = adjusted_ty.ref_mutability().unwrap_or(Mutability::Not);
|
|
|
|
needs_mut |= adjusted_mut == Mutability::Mut;
|
|
|
|
match parent.kind {
|
|
|
|
ExprKind::AddrOf(_, Mutability::Mut, _) => {
|
|
|
|
needs_mut = true;
|
|
|
|
return ControlFlow::Break(true);
|
|
|
|
},
|
|
|
|
ExprKind::Unary(UnOp::Deref, _) | ExprKind::Index(..) if !needs_mut => {
|
|
|
|
let mut last_place = parent;
|
2022-09-09 06:36:26 -05:00
|
|
|
while let Some(parent) = get_parent_expr(cx, last_place) {
|
2022-05-21 06:24:00 -05:00
|
|
|
if matches!(parent.kind, ExprKind::Unary(UnOp::Deref, _) | ExprKind::Field(..))
|
|
|
|
|| matches!(parent.kind, ExprKind::Index(e, _) if e.hir_id == last_place.hir_id)
|
|
|
|
{
|
|
|
|
last_place = parent;
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
needs_mut |= cx.typeck_results().expr_ty_adjusted(last_place).ref_mutability()
|
|
|
|
== Some(Mutability::Mut)
|
|
|
|
|| get_parent_expr(cx, last_place)
|
|
|
|
.map_or(false, |e| matches!(e.kind, ExprKind::AddrOf(_, Mutability::Mut, _)));
|
|
|
|
},
|
2022-09-01 04:43:35 -05:00
|
|
|
ExprKind::MethodCall(_, recv, ..)
|
2022-05-21 06:24:00 -05:00
|
|
|
if recv.hir_id == e.hir_id
|
|
|
|
&& adjusted_mut == Mutability::Mut
|
|
|
|
&& !adjusted_ty.peel_refs().is_slice() =>
|
|
|
|
{
|
|
|
|
// No need to set `needs_mut` to true. The receiver will be either explicitly borrowed, or it will
|
|
|
|
// be implicitly borrowed via an adjustment. Both of these cases are already handled by this point.
|
|
|
|
return ControlFlow::Break(true);
|
|
|
|
},
|
|
|
|
ExprKind::Assign(lhs, ..) if e.hir_id == lhs.hir_id => {
|
|
|
|
needs_mut = true;
|
|
|
|
return ControlFlow::Break(false);
|
|
|
|
},
|
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
ControlFlow::Continue(())
|
|
|
|
});
|
|
|
|
|
|
|
|
// Avoid allocating small `Vec`s when they'll be extended right after.
|
|
|
|
if res == ControlFlow::Break(true) && self.found <= required_pushes_before_extension {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut s = if self.lhs_is_let {
|
2021-01-15 03:56:44 -06:00
|
|
|
String::from("let ")
|
|
|
|
} else {
|
|
|
|
String::new()
|
|
|
|
};
|
2022-05-21 06:24:00 -05:00
|
|
|
if needs_mut {
|
|
|
|
s.push_str("mut ");
|
|
|
|
}
|
|
|
|
s.push_str(self.name.as_str());
|
|
|
|
if let Some(span) = self.let_ty_span {
|
|
|
|
s.push_str(": ");
|
|
|
|
s.push_str(&snippet(cx, span, "_"));
|
|
|
|
}
|
2021-01-15 03:56:44 -06:00
|
|
|
s.push_str(" = vec![..];");
|
|
|
|
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
VEC_INIT_THEN_PUSH,
|
|
|
|
self.err_span,
|
|
|
|
"calls to `push` immediately after creation",
|
|
|
|
"consider using the `vec![]` macro",
|
|
|
|
s,
|
|
|
|
Applicability::HasPlaceholders,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-13 06:18:19 -06:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for VecInitThenPush {
|
2021-02-25 04:25:22 -06:00
|
|
|
fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
|
2021-01-15 03:56:44 -06:00
|
|
|
self.searcher = None;
|
2021-02-25 04:25:22 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
|
2022-05-21 06:24:00 -05:00
|
|
|
if let Some(init_expr) = local.init
|
2022-08-30 17:36:53 -05:00
|
|
|
&& let PatKind::Binding(BindingAnnotation::MUT, id, name, None) = local.pat.kind
|
2022-05-21 06:24:00 -05:00
|
|
|
&& !in_external_macro(cx.sess(), local.span)
|
|
|
|
&& let Some(init) = get_vec_init_kind(cx, init_expr)
|
|
|
|
&& !matches!(init, VecInitKind::WithExprCapacity(_))
|
|
|
|
{
|
|
|
|
self.searcher = Some(VecPushSearcher {
|
|
|
|
local_id: id,
|
|
|
|
init,
|
|
|
|
lhs_is_let: true,
|
|
|
|
name: name.name,
|
|
|
|
let_ty_span: local.ty.map(|ty| ty.span),
|
|
|
|
err_span: local.span,
|
|
|
|
found: 0,
|
|
|
|
last_push_expr: init_expr.hir_id,
|
|
|
|
});
|
2021-01-15 03:56:44 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
|
2022-05-21 06:24:00 -05:00
|
|
|
if self.searcher.is_none()
|
|
|
|
&& let ExprKind::Assign(left, right, _) = expr.kind
|
|
|
|
&& let ExprKind::Path(QPath::Resolved(None, path)) = left.kind
|
|
|
|
&& let [name] = &path.segments
|
|
|
|
&& let Res::Local(id) = path.res
|
|
|
|
&& !in_external_macro(cx.sess(), expr.span)
|
|
|
|
&& let Some(init) = get_vec_init_kind(cx, right)
|
|
|
|
&& !matches!(init, VecInitKind::WithExprCapacity(_))
|
|
|
|
{
|
|
|
|
self.searcher = Some(VecPushSearcher {
|
|
|
|
local_id: id,
|
|
|
|
init,
|
|
|
|
lhs_is_let: false,
|
|
|
|
let_ty_span: None,
|
|
|
|
name: name.ident.name,
|
|
|
|
err_span: expr.span,
|
|
|
|
found: 0,
|
|
|
|
last_push_expr: expr.hir_id,
|
|
|
|
});
|
2021-01-15 03:56:44 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
|
|
|
|
if let Some(searcher) = self.searcher.take() {
|
2022-05-21 06:24:00 -05:00
|
|
|
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
|
2022-09-01 04:43:35 -05:00
|
|
|
&& let ExprKind::MethodCall(name, self_arg, [_], _) = expr.kind
|
2022-05-21 06:24:00 -05:00
|
|
|
&& path_to_local_id(self_arg, searcher.local_id)
|
|
|
|
&& name.ident.as_str() == "push"
|
|
|
|
{
|
|
|
|
self.searcher = Some(VecPushSearcher {
|
|
|
|
found: searcher.found + 1,
|
|
|
|
err_span: searcher.err_span.to(stmt.span),
|
|
|
|
last_push_expr: expr.hir_id,
|
|
|
|
.. searcher
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
searcher.display_err(cx);
|
2021-01-15 03:56:44 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
|
|
|
|
if let Some(searcher) = self.searcher.take() {
|
|
|
|
searcher.display_err(cx);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|