Extend `implicit_saturating_sub` lint
Fixes#10070.
It can serve as base if we want to add equivalent checks for other arithmetic operations.
Also one important note: when writing this lint, I realized that I could check for wrong conditions performed beforehand on subtraction and added another part in the lint. Considering they both rely on the same checks, I kept both in the same place. Not sure if it makes sense though...
changelog: Extend `implicit_saturating_sub` lint
Use `is_diagnostic_item` for checking a def_id in `unnecessary_min_or_max`.
close#13191
This PR fixes the false positives in `unnecessary_min_or_max `.
We should use `is_diagnostic_item` for checking def_ids in this lint.
----
changelog: fix false positive in `unnecessary_min_or_max `.
Add new lint: `used_underscore_items`
Closes#13260
---
changelog: new [`used_underscore_items`] lint against using items with a single leading underscore
Fix manual_range_patterns case with one element at OR
Close#11825
As mentioned #11825 `OR` can be used for stylistic purposes with one element, we can filter this case from triggering lint
changelog: [`manual_range_patterns`]: not trigger when `OR` has only one element
check std::panic::panic_any in panic lint
close#13292
This PR detects `std::panic::panic_any` in panic lint.
changelog: check std::panic::panic_any in panic lint
Rewrite `empty_line_after_doc_comments` and `empty_line_after_outer_attr`, move them from `nursery` to `suspicious`
changelog: [`empty_line_after_doc_comments`], [`empty_line_after_outer_attr`]: rewrite and move them from `nursery` to `suspicious`
They now lint when there's a comment between the last attr/doc comment and the empty line, to cover the case:
```rust
/// Docs for `old_code
// fn old_code() {}
fn new_code() {}
```
When these lints or `suspicious_doc_comments` trigger we no longer trigger any other doc lint as a broad fix for #12917, reverts some of #13002 as the empty line lints cover it
I ended up not doing https://github.com/rust-lang/rust-clippy/issues/12917#issuecomment-2161828859 as I don't think it's needed
Ignore underscore-prefixed args for needless_pass_by_value lint
When a user explicitly tags a param as unused (yet?), there is no need to raise another lint on it.
fixes#7295
Note that I had to rename all `_*` params in the tests, but kept the variable name length to avoid extra changes in the expected output.
changelog: [`needless_pass_by_value`]: do not warn if the argument name starts with an `_`
Diverging subexpression lint should not fire on todo!()
As per #10243 it is not that helpful to point out that a subexpression diverges, so do not fire on todo
changelog: [`diverging_sub_expression`]: do not trigger on todo
Fix confusing message in double_must_use lint
Close#13003
As mentioned at #13003 it isn't quite clear what it means "an empty `#[must_use]` attribute" so clarify it
changelog: [none]
Trigger [`string_slice`] if expression is reference to `&str`
Close#12708
changelog: [`string_slice`]: trigger lint if expression is reference to `&str`
fix false positive in explicit_iter_loop with msrv
close#13184
This PR fix false positive in explicit_iter_loop when msrv < 1.80
changelog: fix false positive in explicit_iter_loop when msrv < 1.80
Clarify suggestion message for unwrap lint
Close#10217
As mentioned at #10217 message for `unwrap` uses `..` like `Some(..)` which can confuse with slice and other places mostly use `<item>` like `for (i, <item>) in target_groups_json.iter().enumerate().skip(1) {` So replace `..` to `<item>`
changelog: [`unnecessary_unwrap`] clarify suggestion message
Add a test for ice-3717.rs
this PR is a part of https://github.com/rust-lang/rust-clippy/issues/13099.
Based on the changes introduced in #13098 for introduce ui_test, we will update the uitest output.
This is a fix for `ice-3717.rs`.
Although fixes have already been made in #13216, it seems that he is a first-time contributor.
I thought it might be better for him to refer to my PR, so I created it accordingly.
Since this is my first contribution in a while, please let me know if there are any issues or required changes.
changelog: none
r! `@flip1995`
Replace `rustc_semver` with `rustc_session::RustcVersion`
Allows dropping a dependency but there is a behaviour change here, the following versions are no longer accepted:
* `1` (would need to be `1.0` or `1.0.0`)
* `1.0.0-alpha`
* `1.0.0-alpha.2`
* `1.0.0-beta`
But this seems unlikely to effect anybody, I did some GitHub searching and found no occurrences outside our UI tests
r? `@flip1995`
changelog: none
Apply "polymorphization at home" to RawVec
The idea here is to move all the logic in RawVec into functions with explicit size and alignment parameters. This should eliminate all the fussing about how tweaking RawVec code produces large swings in compile times.
This uncovered https://github.com/rust-lang/rust-clippy/issues/12979, so I've modified the relevant test in a way that tries to preserve the spirit of the test without tripping the ICE.
Fix case where doc_markdown is triggered on words ending with "ified"
Fixes#13097.
r? `@Alexendoo`
changelog: Fix case where doc_markdown is triggered on words ending with "ified"
[`macro_metavars_in_unsafe`]: recognize metavariables in tail expressions
Fixes#13219
`macro_metavars_in_unsafe` keeps track of the current "expansion depth" (incremented/decremented when entering/leaving a macro span) to tell if an expression from the root context is contained within a macro (see the doc comment I added for a hopefully better explanation)
Before this PR, we didn't increment said `expn_depth` for `unsafe` blocks within macros, because we already do that in `visit_stmt` anyway, so it would work fine for statements, but that's not enough for tail expressions of an unsafe block.
So we now also increment it for macro unsafe blocks.
Also updated the comment for `expn_depth` while I'm at it because "This is not necessary for correctness" isn't correct now that I think about it
------
changelog: none
Respect allow `inconsistent_struct_constructor` on the struct definition
Closes#13203
Now we check if the target type is marked with `#[allow(clippy:inconsistent_struct_constructor)]` before lining.
As a side-effect of this change, The rule in the subject no longer runs on non-local `AdtDef`s. However, as suggested by `@Jarcho` it shouldn't be a big deal since most of the time we didn't have access to this information anyway.
> You can't get lint attributes from other crates. I would probably just restrict the lint to only work with types from the current crate while you're at it. Upstream crates don't have a definition order from the point of view of the current crate (with the exception of #[repr(C)] structs).
changelog: Respect allow `inconsistent_struct_constructor` on the struct definition.
Add lint for `unused_result_ok`
This PR adds a lint to capture the use of `expr.ok();` when the result is not _really_ used.
This could be interpreted as the result being checked (like it is with `unwrap()` or `expect`) but
it actually only ignores the result.
`let _ = expr;` expresses that intent better.
This was also mentionned in #8994 (although not being the main topic of that issue).
changelog: [`misleading_use_of_ok`]: Add new lint to capture `.ok();` when the result is not _really_ used.
Remove `multispan_sugg[_with_applicability]`
They're thin wrappers over the corresponding diag method so we should just use that instead
changelog: none
Add test for `try_err` lint within try blocks.
Fixes#5757
Turns out the current `try_err` implementation already skips expressions inside of a try block.
When inside of a try block, `Err(_)?` is desugared to a `break` instead of normal `return` . This makes `find_return_type()` function at [this line](eb4d88e690/clippy_lints/src/matches/try_err.rs (L29)) always returns `None` and skips the check.
I just added a test case for try block.
changelog: none
Fix [`redundant_slicing`] when the slice is behind a mutable reference
Fixes#12751
changelog: Fix [`redundant_slicing`] when the slice is behind a mutable reference and a immutable reference is expected.
When a suggestion part is for already present code, do not highlight it. If after that there are no highlights left, do not show the suggestion at all.
Fix clippy lint suggestion incorrectly treated as `span_help`.
Fix `redundant_closure` false positive with closures has return type contains `'static`
Fix#13073 .
Please enable "ignore white-space change" settings in github UI for easy reviewing.
HACK: The third commit contains a hack to check if a type `T: 'static` when `fn() -> U where U: 'static`.
I don't have a clean way to check for it.
changelog: [`redundant_closure`] Fix false positive with closures has return type contains `'static`
Fix false positive for `missing_backticks` in footnote references
Fixes#13183.
changelog: Fix false positive for `missing_backticks` in footnote references
Emit `if_let_mutex` in presence of other mutexes
Currently (master, not nightly nor stable) `if_let_mutex` does not emit a warning here:
```rs
let m1 = Mutex::new(10);
let m2 = Mutex::new(());
if let 100..=200 = *m1.lock().unwrap() {
m2.lock();
} else {
m1.lock();
}
```
It currently looks for the first call to `.lock()` on *any* mutex receiver inside of the if/else body, and only later (outside of the visitor) checks that the receiver matches the mutex in the scrutinee. That means that in cases like the above, it finds the `m2.lock()` expression, stops the visitor, fails the check that it's the same mutex (`m2` != `m1`) and then does not look for any other `.lock()` calls.
So, just make the receiver check also part of the visitor so that we only stop the visitor when we also find the right receiver.
The first commit has the actual changes described here. The sceond one just unnests all the `if let`s
----
changelog: none
`missing_trait_methods`: lint methods in definition order
Lintcheck for #13157 showed a bunch of changes for `missing_trait_methods`
This is because `values_sorted` was sorting the entries by the key's [`DefPathHash`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/def_id/struct.DefPathHash.html), this is stable for a given compiler but can change across versions
changelog: none
Fix while_let_on_iterator dropping loop label when applying fix.
Loop label was not persisted when displaying help and was therefore producing broken rust code when applying fixes.
Solution was to store the `ast::Label` when creating a `higher::WhileLet` from an expression and add the label name to the lint suggestion and diagnostics.
---
Fixes: https://github.com/rust-lang/rust-clippy/issues/13123
changelog: [`while_let_on_iterator`]: Fix issue dropping loop label when displaying help and applying fixes.
Add `BTreeSet` detection to the `set_contains_or_insert` lint
* Detect `BTreeSet::contains` + `BTreeSet::insert` usage in the same way as with the `HashSet`.
CC: `@lochetti` `@bitfield`
----
changelog: [`set_contains_or_insert`]: Handle `BTreeSet` in addition to `HashSet`
Make `std_instead_of_core` somewhat MSRV aware
For #13158, this catches some things e.g. `core::net` and the recently stable `core::error` but not things moved individually like `UnwindSafe`, as far as I can see the version for those isn't easily available
Beta nominating since ideally we'd get this change in the same version as `core::error` becomes stable
cc `@kpreid`
changelog: none
Stabilize const `{integer}::from_str_radix` i.e. `const_int_from_str`
This PR stabilizes the feature `const_int_from_str`.
- ACP Issue: rust-lang/libs-team#74
- Implementation PR: rust-lang/rust#99322
- Part of Tracking Issue: rust-lang/rust#59133
API Change Diff:
```diff
impl {integer} {
- pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>;
+ pub const fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>;
}
impl ParseIntError {
- pub fn kind(&self) -> &IntErrorKind;
+ pub const fn kind(&self) -> &IntErrorKind;
}
```
This makes it easier to parse integers at compile-time, e.g.
the example from the Tracking Issue:
```rust
env!("SOMETHING").parse::<usize>().unwrap()
```
could now be achived with
```rust
match usize::from_str_radix(env!("SOMETHING"), 10) {
Ok(val) => val,
Err(err) => panic!("Invalid value for SOMETHING environment variable."),
}
```
rather than having to depend on a library that implements or manually implement the parsing at compile-time.
---
Checklist based on [Libs Stabilization Guide - When there's const involved](https://std-dev-guide.rust-lang.org/development/stabilization.html#when-theres-const-involved)
I am treating this as a [partial stabilization](https://std-dev-guide.rust-lang.org/development/stabilization.html#partial-stabilizations) as it shares a tracking issue (and is rather small), so directly opening the partial stabilization PR for the subset (feature `const_int_from_str`) being stabilized.
- [x] ping Constant Evaluation WG
- [x] no unsafe involved
- [x] no `#[allow_internal_unstable]`
- [ ] usage of `intrinsic::const_eval_select` rust-lang/rust#124625 in `from_str_radix_assert` to change the error message between compile-time and run-time
- [ ] [rust-labg/libs-api FCP](https://github.com/rust-lang/rust/pull/124941#issuecomment-2207021921)