Skip to content

Commit b08fd94

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

15 files changed

+224
-38
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5340,6 +5340,7 @@ Released 2018-09-13
53405340
[`partialeq_to_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#partialeq_to_none
53415341
[`path_buf_push_overwrite`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_buf_push_overwrite
53425342
[`path_ends_with_ext`]: https://rust-lang.github.io/rust-clippy/master/index.html#path_ends_with_ext
5343+
[`pathbuf_init_then_push`]: https://rust-lang.github.io/rust-clippy/master/index.html#pathbuf_init_then_push
53435344
[`pattern_type_mismatch`]: https://rust-lang.github.io/rust-clippy/master/index.html#pattern_type_mismatch
53445345
[`permissions_set_readonly_false`]: https://rust-lang.github.io/rust-clippy/master/index.html#permissions_set_readonly_false
53455346
[`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
@@ -554,6 +554,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
554554
crate::partialeq_to_none::PARTIALEQ_TO_NONE_INFO,
555555
crate::pass_by_ref_or_value::LARGE_TYPES_PASSED_BY_VALUE_INFO,
556556
crate::pass_by_ref_or_value::TRIVIALLY_COPY_PASS_BY_REF_INFO,
557+
crate::pathbuf_init_then_push::PATHBUF_INIT_THEN_PUSH_INFO,
557558
crate::pattern_type_mismatch::PATTERN_TYPE_MISMATCH_INFO,
558559
crate::permissions_set_readonly_false::PERMISSIONS_SET_READONLY_FALSE_INFO,
559560
crate::precedence::PRECEDENCE_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@ mod partial_pub_fields;
263263
mod partialeq_ne_impl;
264264
mod partialeq_to_none;
265265
mod pass_by_ref_or_value;
266+
mod pathbuf_init_then_push;
266267
mod pattern_type_mismatch;
267268
mod permissions_set_readonly_false;
268269
mod precedence;
@@ -1070,6 +1071,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10701071
});
10711072
store.register_late_pass(move |_| Box::new(manual_hash_one::ManualHashOne::new(msrv())));
10721073
store.register_late_pass(|_| Box::new(iter_without_into_iter::IterWithoutIntoIter));
1074+
store.register_late_pass(|_| Box::<pathbuf_init_then_push::PathbufThenPush>::default());
10731075
// add lints here, do not remove this comment, it's used in `new_lint`
10741076
}
10751077

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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::{declare_tool_lint, 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+
/// ### Example
21+
/// ```rust
22+
/// let mut path_buf = PathBuf::new();
23+
/// path_buf.push("foo");
24+
/// ```
25+
/// Use instead:
26+
/// ```rust
27+
/// let path_buf = PathBuf::new().join("foo");
28+
/// ```
29+
#[clippy::version = "1.75.0"]
30+
pub PATHBUF_INIT_THEN_PUSH,
31+
complexity,
32+
"default lint description"
33+
}
34+
35+
impl_lint_pass!(PathbufThenPush => [PATHBUF_INIT_THEN_PUSH]);
36+
37+
#[derive(Default)]
38+
pub struct PathbufThenPush {
39+
searcher: Option<PathbufPushSearcher>,
40+
}
41+
42+
struct PathbufPushSearcher {
43+
local_id: HirId,
44+
lhs_is_let: bool,
45+
let_ty_span: Option<Span>,
46+
init_val_span: Span,
47+
arg_span: Option<Span>,
48+
name: Symbol,
49+
err_span: Span,
50+
}
51+
52+
impl PathbufPushSearcher {
53+
fn display_err(&self, cx: &LateContext<'_>) {
54+
let Some(arg_span) = self.arg_span else { return };
55+
let Some(arg_str) = snippet_opt(cx, arg_span) else {
56+
return;
57+
};
58+
let Some(init_val) = snippet_opt(cx, self.init_val_span) else {
59+
return;
60+
};
61+
let mut s = if self.lhs_is_let {
62+
String::from("let ")
63+
} else {
64+
String::new()
65+
};
66+
s.push_str("mut ");
67+
s.push_str(self.name.as_str());
68+
if let Some(span) = self.let_ty_span {
69+
s.push_str(": ");
70+
s.push_str(&snippet(cx, span, "_"));
71+
}
72+
s.push_str(&format!(" = {init_val}.join({arg_str});",));
73+
74+
span_lint_and_sugg(
75+
cx,
76+
PATHBUF_INIT_THEN_PUSH,
77+
self.err_span,
78+
"calls to `push` immediately after creation",
79+
"consider using the `.join()`",
80+
s,
81+
Applicability::HasPlaceholders,
82+
);
83+
}
84+
}
85+
86+
impl<'tcx> LateLintPass<'tcx> for PathbufThenPush {
87+
fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
88+
self.searcher = None;
89+
}
90+
91+
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
92+
if let Some(init_expr) = local.init
93+
&& let PatKind::Binding(BindingAnnotation::MUT, id, name, None) = local.pat.kind
94+
&& !in_external_macro(cx.sess(), local.span)
95+
&& let ty = cx.typeck_results().pat_ty(local.pat)
96+
&& is_type_diagnostic_item(cx, ty, sym::PathBuf)
97+
{
98+
self.searcher = Some(PathbufPushSearcher {
99+
local_id: id,
100+
lhs_is_let: true,
101+
name: name.name,
102+
let_ty_span: local.ty.map(|ty| ty.span),
103+
err_span: local.span,
104+
init_val_span: init_expr.span,
105+
arg_span: None,
106+
});
107+
}
108+
}
109+
110+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
111+
if self.searcher.is_none()
112+
&& let ExprKind::Assign(left, right, _) = expr.kind
113+
&& let ExprKind::Path(QPath::Resolved(None, path)) = left.kind
114+
&& let [name] = &path.segments
115+
&& let Res::Local(id) = path.res
116+
&& !in_external_macro(cx.sess(), expr.span)
117+
&& let ty = cx.typeck_results().expr_ty(left)
118+
&& is_type_diagnostic_item(cx, ty, sym::PathBuf)
119+
{
120+
self.searcher = Some(PathbufPushSearcher {
121+
local_id: id,
122+
lhs_is_let: false,
123+
let_ty_span: None,
124+
name: name.ident.name,
125+
err_span: expr.span,
126+
init_val_span: right.span,
127+
arg_span : None,
128+
});
129+
}
130+
}
131+
132+
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
133+
if let Some(mut searcher) = self.searcher.take() {
134+
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
135+
&& let ExprKind::MethodCall(name, self_arg, [arg_expr], _) = expr.kind
136+
&& path_to_local_id(self_arg, searcher.local_id)
137+
&& name.ident.as_str() == "push"
138+
{
139+
searcher.err_span = searcher.err_span.to(stmt.span);
140+
searcher.arg_span = Some(arg_expr.span);
141+
searcher.display_err(cx);
142+
}
143+
}
144+
}
145+
146+
fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
147+
if let Some(searcher) = self.searcher.take() {
148+
searcher.display_err(cx);
149+
}
150+
}
151+
}

lintcheck/src/main.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,10 +216,8 @@ impl CrateSource {
216216
options,
217217
} => {
218218
let repo_path = {
219-
let mut repo_path = PathBuf::from(LINTCHECK_SOURCES);
220219
// add a -git suffix in case we have the same crate from crates.io and a git repo
221-
repo_path.push(format!("{name}-git"));
222-
repo_path
220+
PathBuf::from(LINTCHECK_SOURCES).join(format!("{name}-git"))
223221
};
224222
// clone the repo if we have not done so
225223
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-
--> $DIR/path_buf_push_overwrite.rs:6:12
2+
--> $DIR/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+
--> $DIR/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 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)