Skip to content

Commit 8fe5c75

Browse files
committed
Auto merge of rust-lang#11700 - lengyijun:pathbuf_join, r=xFrednet
[`pathbuf_init_then_push`]: Checks for calls to `push` immediately a… changelog: [`pathbuf_init_then_push`]: new lint: Checks for calls to `push` immediately after creating a new `PathBuf` Just a mirror of VEC_INIT_THEN_PUSH
2 parents b02cb24 + cb77f12 commit 8fe5c75

14 files changed

+319
-35
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -5712,6 +5712,7 @@ Released 2018-09-13
57125712
[`partialeq_to_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#partialeq_to_none
57135713
[`path_buf_push_overwrite`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_buf_push_overwrite
57145714
[`path_ends_with_ext`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_ends_with_ext
5715+
[`pathbuf_init_then_push`]: https://rust-lang.github.io/rust-clippy/master/index.html#pathbuf_init_then_push
57155716
[`pattern_type_mismatch`]: https://rust-lang.github.io/rust-clippy/master/index.html#pattern_type_mismatch
57165717
[`permissions_set_readonly_false`]: https://rust-lang.github.io/rust-clippy/master/index.html#permissions_set_readonly_false
57175718
[`positional_named_format_parameters`]: https://rust-lang.github.io/rust-clippy/master/index.html#positional_named_format_parameters

clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
598598
crate::partialeq_to_none::PARTIALEQ_TO_NONE_INFO,
599599
crate::pass_by_ref_or_value::LARGE_TYPES_PASSED_BY_VALUE_INFO,
600600
crate::pass_by_ref_or_value::TRIVIALLY_COPY_PASS_BY_REF_INFO,
601+
crate::pathbuf_init_then_push::PATHBUF_INIT_THEN_PUSH_INFO,
601602
crate::pattern_type_mismatch::PATTERN_TYPE_MISMATCH_INFO,
602603
crate::permissions_set_readonly_false::PERMISSIONS_SET_READONLY_FALSE_INFO,
603604
crate::precedence::PRECEDENCE_INFO,

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,7 @@ mod partial_pub_fields;
287287
mod partialeq_ne_impl;
288288
mod partialeq_to_none;
289289
mod pass_by_ref_or_value;
290+
mod pathbuf_init_then_push;
290291
mod pattern_type_mismatch;
291292
mod permissions_set_readonly_false;
292293
mod precedence;
@@ -887,6 +888,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
887888
});
888889
store.register_late_pass(move |_| Box::new(manual_hash_one::ManualHashOne::new(conf)));
889890
store.register_late_pass(|_| Box::new(iter_without_into_iter::IterWithoutIntoIter));
891+
store.register_late_pass(|_| Box::<pathbuf_init_then_push::PathbufThenPush<'_>>::default());
890892
store.register_late_pass(|_| Box::new(iter_over_hash_type::IterOverHashType));
891893
store.register_late_pass(|_| Box::new(impl_hash_with_borrow_str_and_bytes::ImplHashWithBorrowStrBytes));
892894
store.register_late_pass(|_| Box::new(repeat_vec_with_capacity::RepeatVecWithCapacity));
+193
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
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_ast::{LitKind, StrStyle};
6+
use rustc_errors::Applicability;
7+
use rustc_hir::def::Res;
8+
use rustc_hir::{BindingMode, Block, Expr, ExprKind, HirId, LetStmt, PatKind, QPath, Stmt, StmtKind, TyKind};
9+
use rustc_lint::{LateContext, LateLintPass, LintContext};
10+
use rustc_middle::lint::in_external_macro;
11+
use rustc_session::impl_lint_pass;
12+
use rustc_span::{sym, Span, Symbol};
13+
14+
declare_clippy_lint! {
15+
/// ### What it does
16+
/// Checks for calls to `push` immediately after creating a new `PathBuf`.
17+
///
18+
/// ### Why is this bad?
19+
/// Multiple `.join()` calls are usually easier to read than multiple `.push`
20+
/// calls across multiple statements. It might also be possible to use
21+
/// `PathBuf::from` instead.
22+
///
23+
/// ### Known problems
24+
/// `.join()` introduces an implicit `clone()`. `PathBuf::from` can alternativly be
25+
/// used when the `PathBuf` is newly constructed. This will avoild the implicit clone.
26+
///
27+
/// ### Example
28+
/// ```rust
29+
/// # use std::path::PathBuf;
30+
/// let mut path_buf = PathBuf::new();
31+
/// path_buf.push("foo");
32+
/// ```
33+
/// Use instead:
34+
/// ```rust
35+
/// # use std::path::PathBuf;
36+
/// let path_buf = PathBuf::from("foo");
37+
/// // or
38+
/// let path_buf = PathBuf::new().join("foo");
39+
/// ```
40+
#[clippy::version = "1.81.0"]
41+
pub PATHBUF_INIT_THEN_PUSH,
42+
restriction,
43+
"`push` immediately after `PathBuf` creation"
44+
}
45+
46+
impl_lint_pass!(PathbufThenPush<'_> => [PATHBUF_INIT_THEN_PUSH]);
47+
48+
#[derive(Default)]
49+
pub struct PathbufThenPush<'tcx> {
50+
searcher: Option<PathbufPushSearcher<'tcx>>,
51+
}
52+
53+
struct PathbufPushSearcher<'tcx> {
54+
local_id: HirId,
55+
lhs_is_let: bool,
56+
let_ty_span: Option<Span>,
57+
init_val: Expr<'tcx>,
58+
arg: Option<Expr<'tcx>>,
59+
name: Symbol,
60+
err_span: Span,
61+
}
62+
63+
impl<'tcx> PathbufPushSearcher<'tcx> {
64+
/// Try to generate a suggestion with `PathBuf::from`.
65+
/// Returns `None` if the suggestion would be invalid.
66+
fn gen_pathbuf_from(&self, cx: &LateContext<'_>) -> Option<String> {
67+
if let ExprKind::Call(iter_expr, []) = &self.init_val.kind
68+
&& let ExprKind::Path(QPath::TypeRelative(ty, segment)) = &iter_expr.kind
69+
&& let TyKind::Path(ty_path) = &ty.kind
70+
&& let QPath::Resolved(None, path) = ty_path
71+
&& let Res::Def(_, def_id) = &path.res
72+
&& cx.tcx.is_diagnostic_item(sym::PathBuf, *def_id)
73+
&& segment.ident.name == sym::new
74+
&& let Some(arg) = self.arg
75+
&& let ExprKind::Lit(x) = arg.kind
76+
&& let LitKind::Str(_, StrStyle::Cooked) = x.node
77+
&& let Some(s) = snippet_opt(cx, arg.span)
78+
{
79+
Some(format!(" = PathBuf::from({s});"))
80+
} else {
81+
None
82+
}
83+
}
84+
85+
fn gen_pathbuf_join(&self, cx: &LateContext<'_>) -> Option<String> {
86+
let arg = self.arg?;
87+
let arg_str = snippet_opt(cx, arg.span)?;
88+
let init_val = snippet_opt(cx, self.init_val.span)?;
89+
Some(format!(" = {init_val}.join({arg_str});"))
90+
}
91+
92+
fn display_err(&self, cx: &LateContext<'_>) {
93+
if clippy_utils::attrs::span_contains_cfg(cx, self.err_span) {
94+
return;
95+
}
96+
let mut sugg = if self.lhs_is_let {
97+
String::from("let mut ")
98+
} else {
99+
String::new()
100+
};
101+
sugg.push_str(self.name.as_str());
102+
if let Some(span) = self.let_ty_span {
103+
sugg.push_str(": ");
104+
sugg.push_str(&snippet(cx, span, "_"));
105+
}
106+
match self.gen_pathbuf_from(cx) {
107+
Some(value) => {
108+
sugg.push_str(&value);
109+
},
110+
None => {
111+
if let Some(value) = self.gen_pathbuf_join(cx) {
112+
sugg.push_str(&value);
113+
} else {
114+
return;
115+
}
116+
},
117+
}
118+
119+
span_lint_and_sugg(
120+
cx,
121+
PATHBUF_INIT_THEN_PUSH,
122+
self.err_span,
123+
"calls to `push` immediately after creation",
124+
"consider using the `.join()`",
125+
sugg,
126+
Applicability::HasPlaceholders,
127+
);
128+
}
129+
}
130+
131+
impl<'tcx> LateLintPass<'tcx> for PathbufThenPush<'tcx> {
132+
fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
133+
self.searcher = None;
134+
}
135+
136+
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx LetStmt<'tcx>) {
137+
if let Some(init_expr) = local.init
138+
&& let PatKind::Binding(BindingMode::MUT, id, name, None) = local.pat.kind
139+
&& !in_external_macro(cx.sess(), local.span)
140+
&& let ty = cx.typeck_results().pat_ty(local.pat)
141+
&& is_type_diagnostic_item(cx, ty, sym::PathBuf)
142+
{
143+
self.searcher = Some(PathbufPushSearcher {
144+
local_id: id,
145+
lhs_is_let: true,
146+
name: name.name,
147+
let_ty_span: local.ty.map(|ty| ty.span),
148+
err_span: local.span,
149+
init_val: *init_expr,
150+
arg: None,
151+
});
152+
}
153+
}
154+
155+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
156+
if let ExprKind::Assign(left, right, _) = expr.kind
157+
&& let ExprKind::Path(QPath::Resolved(None, path)) = left.kind
158+
&& let [name] = &path.segments
159+
&& let Res::Local(id) = path.res
160+
&& !in_external_macro(cx.sess(), expr.span)
161+
&& let ty = cx.typeck_results().expr_ty(left)
162+
&& is_type_diagnostic_item(cx, ty, sym::PathBuf)
163+
{
164+
self.searcher = Some(PathbufPushSearcher {
165+
local_id: id,
166+
lhs_is_let: false,
167+
let_ty_span: None,
168+
name: name.ident.name,
169+
err_span: expr.span,
170+
init_val: *right,
171+
arg: None,
172+
});
173+
}
174+
}
175+
176+
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
177+
if let Some(mut searcher) = self.searcher.take() {
178+
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
179+
&& let ExprKind::MethodCall(name, self_arg, [arg_expr], _) = expr.kind
180+
&& path_to_local_id(self_arg, searcher.local_id)
181+
&& name.ident.as_str() == "push"
182+
{
183+
searcher.err_span = searcher.err_span.to(stmt.span);
184+
searcher.arg = Some(*arg_expr);
185+
searcher.display_err(cx);
186+
}
187+
}
188+
}
189+
190+
fn check_block_post(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
191+
self.searcher = None;
192+
}
193+
}

tests/integration.rs

+4-2
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

+2-1
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

+2-1
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

+1-1
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

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#![warn(clippy::pathbuf_init_then_push)]
2+
3+
use std::path::PathBuf;
4+
5+
fn main() {
6+
let mut path_buf = PathBuf::from("foo");
7+
8+
path_buf = PathBuf::from("foo").join("bar");
9+
10+
let bar = "bar";
11+
path_buf = PathBuf::from("foo").join(bar);
12+
13+
let mut path_buf = PathBuf::from("foo").join("bar").join("buz");
14+
15+
let mut x = PathBuf::new();
16+
println!("{}", x.display());
17+
x.push("Duck");
18+
19+
let mut path_buf = PathBuf::new();
20+
#[cfg(cats)]
21+
path_buf.push("foo");
22+
}

tests/ui/pathbuf_init_then_push.rs

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#![warn(clippy::pathbuf_init_then_push)]
2+
3+
use std::path::PathBuf;
4+
5+
fn main() {
6+
let mut path_buf = PathBuf::new(); //~ ERROR: calls to `push` immediately after creation
7+
path_buf.push("foo");
8+
9+
path_buf = PathBuf::from("foo"); //~ ERROR: calls to `push` immediately after creation
10+
path_buf.push("bar");
11+
12+
let bar = "bar";
13+
path_buf = PathBuf::from("foo"); //~ ERROR: calls to `push` immediately after creation
14+
path_buf.push(bar);
15+
16+
let mut path_buf = PathBuf::from("foo").join("bar"); //~ ERROR: calls to `push` immediately after creation
17+
path_buf.push("buz");
18+
19+
let mut x = PathBuf::new();
20+
println!("{}", x.display());
21+
x.push("Duck");
22+
23+
let mut path_buf = PathBuf::new();
24+
#[cfg(cats)]
25+
path_buf.push("foo");
26+
}
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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::from("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: calls to `push` immediately after creation
12+
--> tests/ui/pathbuf_init_then_push.rs:9:5
13+
|
14+
LL | / path_buf = PathBuf::from("foo");
15+
LL | | path_buf.push("bar");
16+
| |_________________________^ help: consider using the `.join()`: `path_buf = PathBuf::from("foo").join("bar");`
17+
18+
error: calls to `push` immediately after creation
19+
--> tests/ui/pathbuf_init_then_push.rs:13:5
20+
|
21+
LL | / path_buf = PathBuf::from("foo");
22+
LL | | path_buf.push(bar);
23+
| |_______________________^ help: consider using the `.join()`: `path_buf = PathBuf::from("foo").join(bar);`
24+
25+
error: calls to `push` immediately after creation
26+
--> tests/ui/pathbuf_init_then_push.rs:16:5
27+
|
28+
LL | / let mut path_buf = PathBuf::from("foo").join("bar");
29+
LL | | path_buf.push("buz");
30+
| |_________________________^ help: consider using the `.join()`: `let mut path_buf = PathBuf::from("foo").join("bar").join("buz");`
31+
32+
error: aborting due to 4 previous errors
33+

tests/ui/redundant_clone.fixed

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#![allow(
44
clippy::drop_non_drop,
55
clippy::implicit_clone,
6+
clippy::pathbuf_init_then_push,
67
clippy::uninlined_format_args,
78
clippy::unnecessary_literal_unwrap
89
)]

tests/ui/redundant_clone.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#![allow(
44
clippy::drop_non_drop,
55
clippy::implicit_clone,
6+
clippy::pathbuf_init_then_push,
67
clippy::uninlined_format_args,
78
clippy::unnecessary_literal_unwrap
89
)]

0 commit comments

Comments
 (0)