Skip to content

Commit 8b191b5

Browse files
committed
Auto merge of #5666 - flip1995:rollup-yjyvvbg, r=flip1995
Rollup of 3 pull requests Successful merges: - #5637 (new lint: vec_resize_to_zero) - #5656 (len_zero: skip ranges if feature `range_is_empty` is not enabled) - #5663 (add testcase that no longer ICEs) Failed merges: r? @ghost changelog: rollup
2 parents 871f3ed + 00c656d commit 8b191b5

15 files changed

+244
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1630,6 +1630,7 @@ Released 2018-09-13
16301630
[`useless_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_transmute
16311631
[`useless_vec`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec
16321632
[`vec_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_box
1633+
[`vec_resize_to_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_resize_to_zero
16331634
[`verbose_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask
16341635
[`verbose_file_reads`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_file_reads
16351636
[`vtable_address_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#vtable_address_comparisons

clippy_lints/src/len_zero.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::utils::{get_item_name, snippet_with_applicability, span_lint, span_lint_and_sugg, walk_ptrs_ty};
1+
use crate::utils::{get_item_name, higher, snippet_with_applicability, span_lint, span_lint_and_sugg, walk_ptrs_ty};
22
use rustc_ast::ast::LitKind;
33
use rustc_data_structures::fx::FxHashSet;
44
use rustc_errors::Applicability;
@@ -259,6 +259,17 @@ fn check_len(
259259

260260
/// Checks if this type has an `is_empty` method.
261261
fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
262+
/// Special case ranges until `range_is_empty` is stabilized. See issue 3807.
263+
fn should_skip_range(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
264+
higher::range(cx, expr).map_or(false, |_| {
265+
!cx.tcx
266+
.features()
267+
.declared_lib_features
268+
.iter()
269+
.any(|(name, _)| name.as_str() == "range_is_empty")
270+
})
271+
}
272+
262273
/// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
263274
fn is_is_empty(cx: &LateContext<'_, '_>, item: &ty::AssocItem) -> bool {
264275
if let ty::AssocKind::Fn = item.kind {
@@ -284,6 +295,10 @@ fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
284295
})
285296
}
286297

298+
if should_skip_range(cx, expr) {
299+
return false;
300+
}
301+
287302
let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
288303
match ty.kind {
289304
ty::Dynamic(ref tt, ..) => {

clippy_lints/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,7 @@ mod unwrap;
325325
mod use_self;
326326
mod useless_conversion;
327327
mod vec;
328+
mod vec_resize_to_zero;
328329
mod verbose_file_reads;
329330
mod wildcard_dependencies;
330331
mod wildcard_imports;
@@ -847,6 +848,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
847848
&utils::internal_lints::OUTER_EXPN_EXPN_DATA,
848849
&utils::internal_lints::PRODUCE_ICE,
849850
&vec::USELESS_VEC,
851+
&vec_resize_to_zero::VEC_RESIZE_TO_ZERO,
850852
&verbose_file_reads::VERBOSE_FILE_READS,
851853
&wildcard_dependencies::WILDCARD_DEPENDENCIES,
852854
&wildcard_imports::ENUM_GLOB_USE,
@@ -1062,6 +1064,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10621064
store.register_early_pass(|| box manual_non_exhaustive::ManualNonExhaustive);
10631065
store.register_late_pass(|| box manual_async_fn::ManualAsyncFn);
10641066
store.register_early_pass(|| box redundant_field_names::RedundantFieldNames);
1067+
store.register_late_pass(|| box vec_resize_to_zero::VecResizeToZero);
10651068
let single_char_binding_names_threshold = conf.single_char_binding_names_threshold;
10661069
store.register_early_pass(move || box non_expressive_names::NonExpressiveNames {
10671070
single_char_binding_names_threshold,
@@ -1430,6 +1433,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14301433
LintId::of(&unwrap::UNNECESSARY_UNWRAP),
14311434
LintId::of(&useless_conversion::USELESS_CONVERSION),
14321435
LintId::of(&vec::USELESS_VEC),
1436+
LintId::of(&vec_resize_to_zero::VEC_RESIZE_TO_ZERO),
14331437
LintId::of(&write::PRINTLN_EMPTY_STRING),
14341438
LintId::of(&write::PRINT_LITERAL),
14351439
LintId::of(&write::PRINT_WITH_NEWLINE),
@@ -1677,6 +1681,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
16771681
LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS),
16781682
LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
16791683
LintId::of(&unwrap::PANICKING_UNWRAP),
1684+
LintId::of(&vec_resize_to_zero::VEC_RESIZE_TO_ZERO),
16801685
]);
16811686

16821687
store.register_group(true, "clippy::perf", Some("clippy_perf"), vec![

clippy_lints/src/utils/paths.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,5 +138,6 @@ pub const VEC_AS_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_slice"];
138138
pub const VEC_DEQUE: [&str; 4] = ["alloc", "collections", "vec_deque", "VecDeque"];
139139
pub const VEC_FROM_ELEM: [&str; 3] = ["alloc", "vec", "from_elem"];
140140
pub const VEC_NEW: [&str; 4] = ["alloc", "vec", "Vec", "new"];
141+
pub const VEC_RESIZE: [&str; 4] = ["alloc", "vec", "Vec", "resize"];
141142
pub const WEAK_ARC: [&str; 3] = ["alloc", "sync", "Weak"];
142143
pub const WEAK_RC: [&str; 3] = ["alloc", "rc", "Weak"];
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
use crate::utils::span_lint_and_then;
2+
use if_chain::if_chain;
3+
use rustc_errors::Applicability;
4+
use rustc_hir::{Expr, ExprKind};
5+
use rustc_lint::{LateContext, LateLintPass};
6+
use rustc_session::{declare_lint_pass, declare_tool_lint};
7+
use rustc_span::source_map::Spanned;
8+
9+
use crate::utils::{match_def_path, paths};
10+
use rustc_ast::ast::LitKind;
11+
use rustc_hir as hir;
12+
13+
declare_clippy_lint! {
14+
/// **What it does:** Finds occurences of `Vec::resize(0, an_int)`
15+
///
16+
/// **Why is this bad?** This is probably an argument inversion mistake.
17+
///
18+
/// **Known problems:** None.
19+
///
20+
/// **Example:**
21+
/// ```rust
22+
/// vec!(1, 2, 3, 4, 5).resize(0, 5)
23+
/// ```
24+
pub VEC_RESIZE_TO_ZERO,
25+
correctness,
26+
"emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake"
27+
}
28+
29+
declare_lint_pass!(VecResizeToZero => [VEC_RESIZE_TO_ZERO]);
30+
31+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VecResizeToZero {
32+
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
33+
if_chain! {
34+
if let hir::ExprKind::MethodCall(path_segment, _, ref args) = expr.kind;
35+
if let Some(method_def_id) = cx.tables.type_dependent_def_id(expr.hir_id);
36+
if match_def_path(cx, method_def_id, &paths::VEC_RESIZE) && args.len() == 3;
37+
if let ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = args[1].kind;
38+
if let ExprKind::Lit(Spanned { node: LitKind::Int(..), .. }) = args[2].kind;
39+
then {
40+
let method_call_span = expr.span.with_lo(path_segment.ident.span.lo());
41+
span_lint_and_then(
42+
cx,
43+
VEC_RESIZE_TO_ZERO,
44+
expr.span,
45+
"emptying a vector with `resize`",
46+
|db| {
47+
db.help("the arguments may be inverted...");
48+
db.span_suggestion(
49+
method_call_span,
50+
"...or you can empty the vector with",
51+
"clear()".to_string(),
52+
Applicability::MaybeIncorrect,
53+
);
54+
},
55+
);
56+
}
57+
}
58+
}
59+
}

src/lintlist/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2460,6 +2460,13 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
24602460
deprecation: None,
24612461
module: "types",
24622462
},
2463+
Lint {
2464+
name: "vec_resize_to_zero",
2465+
group: "correctness",
2466+
desc: "emptying a vector with `resize(0, an_int)` instead of `clear()` is probably an argument inversion mistake",
2467+
deprecation: None,
2468+
module: "vec_resize_to_zero",
2469+
},
24632470
Lint {
24642471
name: "verbose_bit_mask",
24652472
group: "style",

tests/ui/crashes/ice-3969.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// https://github.com/rust-lang/rust-clippy/issues/3969
2+
// used to crash: error: internal compiler error:
3+
// src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as
4+
// std::iter::Iterator>::Item test from rustc ./ui/trivial-bounds/trivial-bounds-inconsistent.rs
5+
6+
// Check that tautalogically false bounds are accepted, and are used
7+
// in type inference.
8+
#![feature(trivial_bounds)]
9+
#![allow(unused)]
10+
11+
trait A {}
12+
13+
impl A for i32 {}
14+
15+
struct Dst<X: ?Sized> {
16+
x: X,
17+
}
18+
19+
struct TwoStrs(str, str)
20+
where
21+
str: Sized;
22+
23+
fn unsized_local()
24+
where
25+
for<'a> Dst<A + 'a>: Sized,
26+
{
27+
let x: Dst<A> = *(Box::new(Dst { x: 1 }) as Box<Dst<A>>);
28+
}
29+
30+
fn return_str() -> str
31+
where
32+
str: Sized,
33+
{
34+
*"Sized".to_string().into_boxed_str()
35+
}
36+
37+
fn use_op(s: String) -> String
38+
where
39+
String: ::std::ops::Neg<Output = String>,
40+
{
41+
-s
42+
}
43+
44+
fn use_for()
45+
where
46+
i32: Iterator,
47+
{
48+
for _ in 2i32 {}
49+
}
50+
51+
fn main() {}

tests/ui/crashes/ice-3969.stderr

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error: trait objects without an explicit `dyn` are deprecated
2+
--> $DIR/ice-3969.rs:25:17
3+
|
4+
LL | for<'a> Dst<A + 'a>: Sized,
5+
| ^^^^^^ help: use `dyn`: `dyn A + 'a`
6+
|
7+
= note: `-D bare-trait-objects` implied by `-D warnings`
8+
9+
error: trait objects without an explicit `dyn` are deprecated
10+
--> $DIR/ice-3969.rs:27:16
11+
|
12+
LL | let x: Dst<A> = *(Box::new(Dst { x: 1 }) as Box<Dst<A>>);
13+
| ^ help: use `dyn`: `dyn A`
14+
15+
error: trait objects without an explicit `dyn` are deprecated
16+
--> $DIR/ice-3969.rs:27:57
17+
|
18+
LL | let x: Dst<A> = *(Box::new(Dst { x: 1 }) as Box<Dst<A>>);
19+
| ^ help: use `dyn`: `dyn A`
20+
21+
error: aborting due to 3 previous errors
22+

tests/ui/len_zero.fixed

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,11 @@ fn main() {
141141
fn test_slice(b: &[u8]) {
142142
if !b.is_empty() {}
143143
}
144+
145+
mod issue_3807 {
146+
// Avoid suggesting changes to ranges if the user did not enable `range_is_empty`.
147+
// See https://github.com/rust-lang/rust/issues/48111#issuecomment-445132965
148+
fn no_suggestion() {
149+
let _ = (0..42).len() == 0;
150+
}
151+
}

tests/ui/len_zero.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,11 @@ fn main() {
141141
fn test_slice(b: &[u8]) {
142142
if b.len() != 0 {}
143143
}
144+
145+
mod issue_3807 {
146+
// Avoid suggesting changes to ranges if the user did not enable `range_is_empty`.
147+
// See https://github.com/rust-lang/rust/issues/48111#issuecomment-445132965
148+
fn no_suggestion() {
149+
let _ = (0..42).len() == 0;
150+
}
151+
}

tests/ui/len_zero_ranges.fixed

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// run-rustfix
2+
3+
#![feature(range_is_empty)]
4+
#![warn(clippy::len_zero)]
5+
#![allow(unused)]
6+
7+
mod issue_3807 {
8+
// With the feature enabled, `is_empty` should be suggested
9+
fn suggestion_is_fine() {
10+
let _ = (0..42).is_empty();
11+
}
12+
}
13+
14+
fn main() {}

tests/ui/len_zero_ranges.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// run-rustfix
2+
3+
#![feature(range_is_empty)]
4+
#![warn(clippy::len_zero)]
5+
#![allow(unused)]
6+
7+
mod issue_3807 {
8+
// With the feature enabled, `is_empty` should be suggested
9+
fn suggestion_is_fine() {
10+
let _ = (0..42).len() == 0;
11+
}
12+
}
13+
14+
fn main() {}

tests/ui/len_zero_ranges.stderr

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: length comparison to zero
2+
--> $DIR/len_zero_ranges.rs:10:17
3+
|
4+
LL | let _ = (0..42).len() == 0;
5+
| ^^^^^^^^^^^^^^^^^^ help: using `is_empty` is clearer and more explicit: `(0..42).is_empty()`
6+
|
7+
= note: `-D clippy::len-zero` implied by `-D warnings`
8+
9+
error: aborting due to previous error
10+

tests/ui/vec_resize_to_zero.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#![warn(clippy::vec_resize_to_zero)]
2+
3+
fn main() {
4+
// applicable here
5+
vec![1, 2, 3, 4, 5].resize(0, 5);
6+
7+
// not applicable
8+
vec![1, 2, 3, 4, 5].resize(2, 5);
9+
10+
// applicable here, but only implemented for integer litterals for now
11+
vec!["foo", "bar", "baz"].resize(0, "bar");
12+
13+
// not applicable
14+
vec!["foo", "bar", "baz"].resize(2, "bar")
15+
}

tests/ui/vec_resize_to_zero.stderr

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
error: emptying a vector with `resize`
2+
--> $DIR/vec_resize_to_zero.rs:5:5
3+
|
4+
LL | vec![1, 2, 3, 4, 5].resize(0, 5);
5+
| ^^^^^^^^^^^^^^^^^^^^------------
6+
| |
7+
| help: ...or you can empty the vector with: `clear()`
8+
|
9+
= note: `-D clippy::vec-resize-to-zero` implied by `-D warnings`
10+
= help: the arguments may be inverted...
11+
12+
error: aborting due to previous error
13+

0 commit comments

Comments
 (0)