Skip to content

Commit 7183542

Browse files
committed
[pathbuf_init_then_push]: Checks for calls to push immediately after creating a new PathBuf
1 parent cb87a57 commit 7183542

15 files changed

+229
-38
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5591,6 +5591,7 @@ Released 2018-09-13
55915591
[`partialeq_to_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#partialeq_to_none
55925592
[`path_buf_push_overwrite`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_buf_push_overwrite
55935593
[`path_ends_with_ext`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_ends_with_ext
5594+
[`pathbuf_init_then_push`]: https://rust-lang.github.io/rust-clippy/master/index.html#pathbuf_init_then_push
55945595
[`pattern_type_mismatch`]: https://rust-lang.github.io/rust-clippy/master/index.html#pattern_type_mismatch
55955596
[`permissions_set_readonly_false`]: https://rust-lang.github.io/rust-clippy/master/index.html#permissions_set_readonly_false
55965597
[`positional_named_format_parameters`]: https://rust-lang.github.io/rust-clippy/master/index.html#positional_named_format_parameters

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
590590
crate::partialeq_to_none::PARTIALEQ_TO_NONE_INFO,
591591
crate::pass_by_ref_or_value::LARGE_TYPES_PASSED_BY_VALUE_INFO,
592592
crate::pass_by_ref_or_value::TRIVIALLY_COPY_PASS_BY_REF_INFO,
593+
crate::pathbuf_init_then_push::PATHBUF_INIT_THEN_PUSH_INFO,
593594
crate::pattern_type_mismatch::PATTERN_TYPE_MISMATCH_INFO,
594595
crate::permissions_set_readonly_false::PERMISSIONS_SET_READONLY_FALSE_INFO,
595596
crate::precedence::PRECEDENCE_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,7 @@ mod partial_pub_fields;
282282
mod partialeq_ne_impl;
283283
mod partialeq_to_none;
284284
mod pass_by_ref_or_value;
285+
mod pathbuf_init_then_push;
285286
mod pattern_type_mismatch;
286287
mod permissions_set_readonly_false;
287288
mod precedence;
@@ -1110,6 +1111,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
11101111
});
11111112
store.register_late_pass(move |_| Box::new(manual_hash_one::ManualHashOne::new(msrv())));
11121113
store.register_late_pass(|_| Box::new(iter_without_into_iter::IterWithoutIntoIter));
1114+
store.register_late_pass(|_| Box::<pathbuf_init_then_push::PathbufThenPush>::default());
11131115
store.register_late_pass(|_| Box::new(iter_over_hash_type::IterOverHashType));
11141116
store.register_late_pass(|_| Box::new(impl_hash_with_borrow_str_and_bytes::ImplHashWithBorrowStrBytes));
11151117
store.register_late_pass(|_| Box::new(repeat_vec_with_capacity::RepeatVecWithCapacity));
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::path_to_local_id;
3+
use clippy_utils::source::{snippet, snippet_opt};
4+
use clippy_utils::ty::is_type_diagnostic_item;
5+
use rustc_errors::Applicability;
6+
use rustc_hir::def::Res;
7+
use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, QPath, Stmt, StmtKind};
8+
use rustc_lint::{LateContext, LateLintPass, LintContext};
9+
use rustc_middle::lint::in_external_macro;
10+
use rustc_session::impl_lint_pass;
11+
use rustc_span::{sym, Span, Symbol};
12+
13+
declare_clippy_lint! {
14+
/// ### What it does
15+
/// Checks for calls to `push` immediately after creating a new `PathBuf`.
16+
///
17+
/// ### Why is this bad?
18+
/// The `.join()` is easier to read than multiple `push` calls.
19+
///
20+
/// ### Known problems
21+
/// `.join()` introduces an implicit `clone()`
22+
///
23+
/// ### Example
24+
/// ```rust
25+
/// use std::path::PathBuf;
26+
/// let mut path_buf = PathBuf::new();
27+
/// path_buf.push("foo");
28+
/// ```
29+
/// Use instead:
30+
/// ```rust
31+
/// use std::path::PathBuf;
32+
/// let path_buf = PathBuf::new().join("foo");
33+
/// ```
34+
#[clippy::version = "1.75.0"]
35+
pub PATHBUF_INIT_THEN_PUSH,
36+
complexity,
37+
"`push` immediately after `PathBuf` creation"
38+
}
39+
40+
impl_lint_pass!(PathbufThenPush => [PATHBUF_INIT_THEN_PUSH]);
41+
42+
#[derive(Default)]
43+
pub struct PathbufThenPush {
44+
searcher: Option<PathbufPushSearcher>,
45+
}
46+
47+
struct PathbufPushSearcher {
48+
local_id: HirId,
49+
lhs_is_let: bool,
50+
let_ty_span: Option<Span>,
51+
init_val_span: Span,
52+
arg_span: Option<Span>,
53+
name: Symbol,
54+
err_span: Span,
55+
}
56+
57+
impl PathbufPushSearcher {
58+
fn display_err(&self, cx: &LateContext<'_>) {
59+
let Some(arg_span) = self.arg_span else { return };
60+
let Some(arg_str) = snippet_opt(cx, arg_span) else {
61+
return;
62+
};
63+
let Some(init_val) = snippet_opt(cx, self.init_val_span) else {
64+
return;
65+
};
66+
let mut s = if self.lhs_is_let {
67+
String::from("let ")
68+
} else {
69+
String::new()
70+
};
71+
s.push_str("mut ");
72+
s.push_str(self.name.as_str());
73+
if let Some(span) = self.let_ty_span {
74+
s.push_str(": ");
75+
s.push_str(&snippet(cx, span, "_"));
76+
}
77+
s.push_str(&format!(" = {init_val}.join({arg_str});",));
78+
79+
span_lint_and_sugg(
80+
cx,
81+
PATHBUF_INIT_THEN_PUSH,
82+
self.err_span,
83+
"calls to `push` immediately after creation",
84+
"consider using the `.join()`",
85+
s,
86+
Applicability::HasPlaceholders,
87+
);
88+
}
89+
}
90+
91+
impl<'tcx> LateLintPass<'tcx> for PathbufThenPush {
92+
fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
93+
self.searcher = None;
94+
}
95+
96+
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
97+
if let Some(init_expr) = local.init
98+
&& let PatKind::Binding(BindingAnnotation::MUT, id, name, None) = local.pat.kind
99+
&& !in_external_macro(cx.sess(), local.span)
100+
&& let ty = cx.typeck_results().pat_ty(local.pat)
101+
&& is_type_diagnostic_item(cx, ty, sym::PathBuf)
102+
{
103+
self.searcher = Some(PathbufPushSearcher {
104+
local_id: id,
105+
lhs_is_let: true,
106+
name: name.name,
107+
let_ty_span: local.ty.map(|ty| ty.span),
108+
err_span: local.span,
109+
init_val_span: init_expr.span,
110+
arg_span: None,
111+
});
112+
}
113+
}
114+
115+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
116+
if self.searcher.is_none()
117+
&& let ExprKind::Assign(left, right, _) = expr.kind
118+
&& let ExprKind::Path(QPath::Resolved(None, path)) = left.kind
119+
&& let [name] = &path.segments
120+
&& let Res::Local(id) = path.res
121+
&& !in_external_macro(cx.sess(), expr.span)
122+
&& let ty = cx.typeck_results().expr_ty(left)
123+
&& is_type_diagnostic_item(cx, ty, sym::PathBuf)
124+
{
125+
self.searcher = Some(PathbufPushSearcher {
126+
local_id: id,
127+
lhs_is_let: false,
128+
let_ty_span: None,
129+
name: name.ident.name,
130+
err_span: expr.span,
131+
init_val_span: right.span,
132+
arg_span: None,
133+
});
134+
}
135+
}
136+
137+
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
138+
if let Some(mut searcher) = self.searcher.take() {
139+
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
140+
&& let ExprKind::MethodCall(name, self_arg, [arg_expr], _) = expr.kind
141+
&& path_to_local_id(self_arg, searcher.local_id)
142+
&& name.ident.as_str() == "push"
143+
{
144+
searcher.err_span = searcher.err_span.to(stmt.span);
145+
searcher.arg_span = Some(arg_expr.span);
146+
searcher.display_err(cx);
147+
}
148+
}
149+
}
150+
151+
fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
152+
if let Some(searcher) = self.searcher.take() {
153+
searcher.display_err(cx);
154+
}
155+
}
156+
}

lintcheck/src/main.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -223,10 +223,8 @@ impl CrateSource {
223223
options,
224224
} => {
225225
let repo_path = {
226-
let mut repo_path = PathBuf::from(LINTCHECK_SOURCES);
227226
// add a -git suffix in case we have the same crate from crates.io and a git repo
228-
repo_path.push(format!("{name}-git"));
229-
repo_path
227+
PathBuf::from(LINTCHECK_SOURCES).join(format!("{name}-git"))
230228
};
231229
// clone the repo if we have not done so
232230
if !repo_path.is_dir() {

tests/integration.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,10 @@ fn integration_test() {
2929
.nth(1)
3030
.expect("repo name should have format `<org>/<name>`");
3131

32-
let mut repo_dir = tempfile::tempdir().expect("couldn't create temp dir").into_path();
33-
repo_dir.push(crate_name);
32+
let repo_dir = tempfile::tempdir()
33+
.expect("couldn't create temp dir")
34+
.into_path()
35+
.join(crate_name);
3436

3537
let st = Command::new("git")
3638
.args([

tests/ui/path_buf_push_overwrite.fixed

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::path::PathBuf;
22

3-
#[warn(clippy::all, clippy::path_buf_push_overwrite)]
3+
#[warn(clippy::path_buf_push_overwrite)]
4+
#[allow(clippy::pathbuf_init_then_push)]
45
fn main() {
56
let mut x = PathBuf::from("/foo");
67
x.push("bar");

tests/ui/path_buf_push_overwrite.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::path::PathBuf;
22

3-
#[warn(clippy::all, clippy::path_buf_push_overwrite)]
3+
#[warn(clippy::path_buf_push_overwrite)]
4+
#[allow(clippy::pathbuf_init_then_push)]
45
fn main() {
56
let mut x = PathBuf::from("/foo");
67
x.push("/bar");

tests/ui/path_buf_push_overwrite.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: calling `push` with '/' or '\' (file system root) will overwrite the previous path definition
2-
--> tests/ui/path_buf_push_overwrite.rs:6:12
2+
--> tests/ui/path_buf_push_overwrite.rs:7:12
33
|
44
LL | x.push("/bar");
55
| ^^^^^^ help: try: `"bar"`

tests/ui/pathbuf_init_then_push.fixed

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#![warn(clippy::pathbuf_init_then_push)]
2+
3+
use std::path::PathBuf;
4+
5+
fn main() {
6+
let mut path_buf = PathBuf::new().join("foo");
7+
}

tests/ui/pathbuf_init_then_push.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#![warn(clippy::pathbuf_init_then_push)]
2+
3+
use std::path::PathBuf;
4+
5+
fn main() {
6+
let mut path_buf = PathBuf::new();
7+
path_buf.push("foo");
8+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
error: calls to `push` immediately after creation
2+
--> tests/ui/pathbuf_init_then_push.rs:6:5
3+
|
4+
LL | / let mut path_buf = PathBuf::new();
5+
LL | | path_buf.push("foo");
6+
| |_________________________^ help: consider using the `.join()`: `let mut path_buf = PathBuf::new().join("foo");`
7+
|
8+
= note: `-D clippy::pathbuf-init-then-push` implied by `-D warnings`
9+
= help: to override `-D warnings` add `#[allow(clippy::pathbuf_init_then_push)]`
10+
11+
error: aborting due to 1 previous error
12+

tests/ui/redundant_clone.fixed

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#![allow(
55
clippy::drop_non_drop,
66
clippy::implicit_clone,
7+
clippy::pathbuf_init_then_push,
78
clippy::uninlined_format_args,
89
clippy::unnecessary_literal_unwrap
910
)]

tests/ui/redundant_clone.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#![allow(
55
clippy::drop_non_drop,
66
clippy::implicit_clone,
7+
clippy::pathbuf_init_then_push,
78
clippy::uninlined_format_args,
89
clippy::unnecessary_literal_unwrap
910
)]

0 commit comments

Comments
 (0)