Give corrected code
This PR adds corrected code for doc examples.
I did this in several commits to facilitate review.
Don't hesitate to tell me if I forgot some.
Also, sometimes I felt it was not necessary to give corrected code, but I maybe wrong.
fixes: #4829
changelog: Improve documentation examples across multiple lints.
New lint: iter_next_slice
Hello, this is a work-in-progress PR for issue: https://github.com/rust-lang/rust-clippy/issues/5572
I have implemented lint to replace `iter().next()` for `slice[index..]` and `array` with `get(index)` and `get(0)` respectively. However since I made a lot of changes, I would like to request some feedback before continuing so that I could fix mistakes.
Thank you!
---
changelog: implement `iter_next_slice` lint and test, and modify `needless_continues`, `for_loop_over_options_result` UI tests since they have `iter().next()`
Add regression test for endless loop / update `pulldown_cmark`
Closes#4917
This was fixed in pulldown_cmark 0.7.1, specifically raphlinus/pulldown-cmark#438
changelog: none
Rework suggestion generation of `unit_arg` lint
Found this bug while running `cargo fix --clippy` on quite a big codebase:
This would replace something like:
```rust
Some(fn_that_actually_does_something(&a, b))
```
with
```rust
Some(())
```
which obviously suppresses side effects.
Since pretty much every expression could have side effects, I think making this suggestion `MaybeIncorrect` is the best thing to do here.
A correct suggestion would be:
```rust
fn_that_actually_does_something(&a, b);
Some(())
```
Somehow the suggestion is not correctly applied to the arguments, when more than one argument is a unit value. I have to look into this a little more, though.
changelog: Fixes suggestion of `unit_arg` lint, so that it suggests semantic equivalent code
Fixes#4741
len_zero: skip ranges if feature `range_is_empty` is not enabled
If the feature is not enabled, calling `is_empty()` on a range is ambiguous. Moreover, the two possible resolutions are unstable methods, one inherent to the range and the other being part of the `ExactSizeIterator` trait.
Since `len_zero` only checks for existing `is_empty()` inherent methods, we only take into account the `range_is_empty` feature.
Related: https://github.com/rust-lang/rust/issues/48111#issuecomment-445132965
changelog: len_zero: avoid linting ranges without #![feature(range_is_empty)]
Fixes: #3807
Extend useless conversion
This PR extends `useless_conversion` lint with `TryFrom` and `TryInto`
fixes: #5344
changelog: Extend `useless_conversion` with `TryFrom` and `TryInto`
Make empty_line_after_outer_attr an early lint
Fixes#5567
Unfortunately I couldn't find a way to reproduce the issue without syn/quote. Considering that most real-world macros use syn and/or quote, I think it's okay to pull them in anyway.
changelog: Fix false positive in [`empty_line_after_outer_attr`]
reversed_empty_ranges: add suggestion for &slice[N..N]
As discussed in the issue thread, the user accepted this solution. Let me know if this is what we want, or if changing the way we lint the N..N case is prefered.
changelog: reversed_empty_ranges: add suggestion for &slice[N..N]
Closes#5628
ptr_arg: honor `allow` attribute on arguments
The `intravisit::Visitor` impl for `LateContextAndPass` only takes into account the attributes of a function parameter inside the `check_param` method. `ptr_arg` starts its heuristics at `check_item` / `check_impl_item` / `check_trait_item`, so the `allow` is not taken into account automatically.
changelog: ptr_arg: honor `allow` attribute on arguments
Fixes#5644
new_without_default: do not suggest deriving
---
changelog: do not suggest deriving `Default` in `new_without_default`
This commit changes the behavior of the `new_without_default` lint to not suggest deriving `Default`. This suggestion is misleading if the `new` implementation does something different than what a derived `Default` implementation would do, because then the two methods would not be equivalent.
Instead, the `can_derive_default` check is removed, and we always suggest implementing `Default` in terms of `new()`.
Clarify the documentation of the `unnecessary_mut_passed` lint
fixes#5433 by replacing "giving" with "passing"
changelog: Clarifies documentation for `unnecessary_mut_passed`
Add to the list of words clippy::doc_markdown ignores
"TypeScript" is the only one of these I actually ran into organically; I can remove the others if they're too much.
changelog: Add to the list of words `clippy::doc_markdown` ignores
New lint: `match_wildcard_for_single_variants`
changelog: Added a new lint match_wildcard_for_single_variants to warn on enum matches where a wildcard is used to match a single variant
Closes#5556
Rename lint `identity_conversion` to `useless_conversion`
Lint name `identity_conversion` was misleading, so this PR renames it to `useless_conversion`.
As decision has not really came up in the issue comments, this PR will probably need discussion.
fixes#3106
changelog: Rename lint `identity_conversion` to `useless_conversion`
Merge some lints together
This PR merges following lints:
- `block_in_if_condition_expr` and `block_in_if_condition_stmt` → `blocks_in_if_conditions`
- `option_map_unwrap_or`, `option_map_unwrap_or_else` and `result_map_unwrap_or_else` → `map_unwrap`
- `option_unwrap_used` and `result_unwrap_used` → `unwrap_used`
- `option_expect_used` and `result_expect_used` → `expect_used`
- `wrong_pub_self_convention` into `wrong_self_convention`
- `for_loop_over_option` and `for_loop_over_result` → `for_loops_over_fallibles`
Lints that have already been merged since the issue was created:
- [x] `new_without_default` and `new_without_default_derive` → `new_without_default`
Need more discussion:
- `string_add` and `string_add_assign`: do we agree to merge them or not? Is there something more to do? → **not merge finally**
- `identity_op` and `modulo_one` → `useless_arithmetic`: seems outdated, since `modulo_arithmetic` has been created.
fixes#1078
changelog: Merging some lints together:
- `block_in_if_condition_expr` and `block_in_if_condition_stmt` → `blocks_in_if_conditions`
- `option_map_unwrap_or`, `option_map_unwrap_or_else` and `result_map_unwrap_or_else` → `map_unwrap_or`
- `option_unwrap_used` and `result_unwrap_used` → `unwrap_used`
- `option_expect_used` and `result_expect_used` → `expect_used`
- `for_loop_over_option` and `for_loop_over_result` → `for_loops_over_fallibles`
Literal error reporting cleanup
While doing some performance work, I noticed some code duplication in `librustc_parser/lexer/mod.rs`, so I cleaned it up.
This PR is probably best reviewed commit by commit.
I'm not sure what the API stability practices for `librustc_lexer` are. Four public methods in `unescape.rs` can be removed, but two are used by clippy, so I left them in for now.
I could open a PR for Rust-Analyzer when this one lands.
But how do I open a PR for clippy? (Git submodules are frustrating to work with)
identity_op: allow `1 << 0`
I went for accepting `1 << 0` verbatim instead of something more general as it seems to be what everyone in the issue thread needed.
changelog: identity_op: allow `1 << 0` as it's a common pattern in bit manipulation code.
Fixes#3430
Downgrade useless_let_if_seq to nursery
I feel that this lint has the wrong balance of incorrect suggestions for a default-enabled lint.
The immediate code I faced was something like:
```rust
fn main() {
let mut good = do1();
if !do2() {
good = false;
}
if good {
println!("good");
}
}
fn do1() -> bool { println!("1"); false }
fn do2() -> bool { println!("2"); false }
```
On this code Clippy calls it unidiomatic and suggests the following diff, which has different behavior in a way that I don't necessarily want.
```diff
- let mut good = do1();
- if !do2() {
- good = false;
- }
+ let good = if !do2() {
+ false
+ } else {
+ do1()
+ };
```
On exploring issues filed about this lint, I have found that other users have also struggled with inappropriate suggestions (https://github.com/rust-lang/rust-clippy/issues/4124, https://github.com/rust-lang/rust-clippy/issues/3043, https://github.com/rust-lang/rust-clippy/issues/2918, https://github.com/rust-lang/rust-clippy/issues/2176) and suggestions that make the code worse (https://github.com/rust-lang/rust-clippy/issues/3769, https://github.com/rust-lang/rust-clippy/issues/2749). Overall I believe that this lint is still at nursery quality for now and should not be enabled.
---
changelog: Remove useless_let_if_seq from default set of enabled lints
Reversed empty ranges
This lint checks range expressions with inverted limits which result in empty ranges. This includes also the ranges used to index slices.
The lint reverse_range_loop was covering iteration of reversed ranges in a for loop, which is a subset of what this new lint covers, so it has been removed. I'm not sure if that's the best choice. It would be doable to check in the new lint that we are not in the arguments of a for loop; I went for removing it because the logic was too similar to keep them separated.
changelog: Added reversed_empty_ranges lint that checks for ranges where the limits have been inverted, resulting in empty ranges. Removed reverse_range_loop which was covering a subset of the new lint.
Closes#4192Closes#96
Extend example for the `unneeded_field_pattern` lint
Current example is incorrect (or pseudo-code) because a struct name is omitted. I have used the code from the tests instead. Perhaps this example can be made less verbose, but I think it is more convenient to see a "real" code as an example.
---
changelog: extend example for the `unneeded_field_pattern` lint
Fix match on vec items: match on vec[..]
- Added new tests
- Fixed false positive when matching on full range, which will never panic
Closes#5551
changelog: fix match_on_vec_items when matching full range
Fix `unnecessary_unwrap` lint when checks are done in parameters
Fixes a false positive in `unnecessary_unwrap` lint when checks are done in macro parameters.
FIxes#5174
changelog: Fixes a false positive in `unnecessary_unwrap` lint when checks are done in macro parameters.
Fix FP on while-let-on-iterator
- fix `is_refutable` for slice patterns
- fix `is_refutable` for bindings
- add some TODO-s for cases, which can not be fixed easily
fixes#3780
changelog: fix FP on while-let-on-iterator for arrays and bindings
Implement the manual_non_exhaustive lint
Some implementation notes:
* Not providing automatic fixups because additional changes may be needed in other parts of the code, e.g. when constructing a struct.
* Even though the attribute is valid on enum variants, it's not possible to use the manual implementation of the pattern because the visibility is always public, so the lint ignores enum variants.
* Unit structs are also ignored, it's not possible to implement the pattern manually without fields.
* The attribute is not accepted in unions, so those are ignored too.
* Even though the original issue did not mention it, tuple structs are also linted because it's possible to apply the pattern manually.
changelog: Added the manual non-exhaustive implementation lint
Closes#2017
Fix the bugs of `manual_memcpy`, simplify the suggestion and refactor it
While I’m working on the long procrastinated work to expand `manual_memcpy`(#1670), I found a few minor bugs and probably unidiomatic or old coding style. There is a brief explanation of changes to the behaviour this PR will make below. And, I have a questoin: do I need to add tests for the first and second fixed bugs? I thought it might be too rare cases to include the tests for those. I added for the last one though.
* Bug fix
* It negates resulted offsets (`src/dst_offset`) when `offset` is subtraction by 0. This PR will remove any subtraction by 0 as a part of minification.
```rust
for i in 0..5 {
dst[i - 0] = src[i];
}
```
```diff
warning: it looks like you're manually copying between slices
--> src/main.rs:2:14
|
LL | for i in 0..5 {
- | ^^^^ help: try replacing the loop by: `dst[..-5].clone_from_slice(&src[..5])`
+ | ^^^^ help: try replacing the loop by: `dst[..5].clone_from_slice(&src[..5])`
|
```
* It prints `RangeTo` or `RangeFull` when both of `end` and `offset` are 0, which have different meaning. This PR will print 0. I could reject the cases `end` is 0, but I thought I won’t catch other cases `reverse_range_loop` will trigger, and it’s over to catch every such cases.
```rust
for i in 0..0 {
dst[i] = src[i];
}
```
```diff
warning: it looks like you're manually copying between slices
--> src/main.rs:2:14
|
LL | for i in 0..0 {
- | ^^^^ help: try replacing the loop by: `dst.clone_from_slice(&src[..])`
+ | ^^^^ help: try replacing the loop by: `dst[..0].clone_from_slice(&src[..0])`
|
```
* it prints four dots when `end` is `None`. This PR will ignore any `for` loops without `end` because a `for` loop that takes `RangeFrom` as its argument and contains indexing without the statements or the expressions that end loops such as `break` will definitely panic, and `manual_memcpy` should ignore the loops with such control flow.
```rust
fn manual_copy(src: &[u32], dst: &mut [u32]) {
for i in 0.. {
dst[i] = src[i];
}
}
```
```diff
-warning: it looks like you're manually copying between slices
- --> src/main.rs:2:14
- |
-LL | for i in 0.. {
- | ^^^ help: try replacing the loop by: `dst[....].clone_from_slice(&src[....])`
- |
```
* Simplification of the suggestion
* It prints 0 when `start` or `end` and `offset` are same (from #3323). This PR will use `RangeTo`
changelog: fixed the bugs of `manual_memcpy` and also simplify the suggestion.
Current example is incorrect (or pseudo-code) because a struct name is omitted. I have used the code from the tests instead. Perhaps this example can be made less verbose, but I think it is more convenient to see a "real" code as an example.
New lint `match_vec_item`
Added new lint to warn a match on index item which can panic. It's always better to use `get(..)` instead.
Closes#5500
changelog: New lint `match_on_vec_items`
- Show just one error message with multiple suggestions in case of
using multiple times an OS in target family position
- Only suggest #[cfg(unix)] when the OS is in the Unix family
- Test all the operating systems
Don't trigger while_let_on_iterator when the iterator is recreated every iteration
r? @phansch
Fixes#1654
changelog: Fix false positive in [`while_let_on_iterator`]
Downgrade match_bool to pedantic
I don't quite buy the justification in https://rust-lang.github.io/rust-clippy/. The justification is:
> It makes the code less readable.
In the Rust codebases I've worked in, I have found people were comfortable using `match bool` (selectively) to make code more readable. For example, initializing struct fields is a place where the indentation of `match` can work better than the indentation of `if`:
```rust
let _ = Struct {
v: {
...
},
w: match doing_w {
true => ...,
false => ...,
},
x: Nested {
c: ...,
b: ...,
a: ...,
},
y: if doing_y {
...
} else { // :(
...
},
z: ...,
};
```
Or sometimes people prefer something a bit less pithy than `if` when the meaning of the bool doesn't read off clearly from the condition:
```rust
if set.insert(...) {
... // ???
} else {
...
}
match set.insert(...) {
// set.insert returns false if already present
false => ...,
true => ...,
}
```
Or `match` can be a better fit when the bool is playing the role more of a value than a branch condition:
```rust
impl ErrorCodes {
pub fn from(b: bool) -> Self {
match b {
true => ErrorCodes::Yes,
false => ErrorCodes::No,
}
}
}
```
And then there's plain old it's-1-line-shorter, which means we get 25% more content on a screen when stacking a sequence of conditions:
```rust
let old_noun = match old_binding.is_import() {
true => "import",
false => "definition",
};
let new_participle = match new_binding.is_import() {
true => "imported",
false => "defined",
};
```
Bottom line is I think this lint fits the bill better as a pedantic lint; I don't think linting on this by default is justified.
changelog: Remove match_bool from default set of enabled lints
Fixes#4226
This introduces the lint await_holding_lock. For async functions, we iterate
over all types in generator_interior_types and look for types named MutexGuard,
RwLockReadGuard, or RwLockWriteGuard. If we find one then we emit a lint.
If let else mutex
changelog: Adds lint to catch incorrect use of `Mutex::lock` in `if let` expressions with lock calls in any of the blocks.
closes: #5219
Fix issue #2907.
Update the "borrow box" lint to avoid recommending the following
conversion:
```
// Old
pub fn f(&mut Box<T>) {...}
// New
pub fn f(&mut T) {...}
```
Given a mutable reference to a box, functions may want to change
"which" object the Box is pointing at.
This change avoids recommending removing the "Box" parameter
for mutable references.
changelog: Don't trigger [`borrow_box`] lint on `&mut Box` references
Cleanup: `node_id` -> `hir_id`
This removes some more `node_id` terminology from Clippy and replaces one occurrence of `as_local_node_id` with `as_local_hir_id`, which should be doing the same for that particular case.
changelog: none
Update the "borrow box" lint to avoid recommending the following
conversion:
```
// Old
pub fn f(&mut Box<T>) {...}
// New
pub fn f(&mut T) {...}
```
Given a mutable reference to a box, functions may want to change
"which" object the Box is pointing at.
This change avoids recommending removing the "Box" parameter
for mutable references.
add lint futures_not_send
changelog: add lint futures_not_send
fixes#5379
~Remark: one thing that can (should?) still be improved is to directly include the error message from the `Send` check so that the programmer stays in the flow. Currently, getting the actual error message requires a restructuring of the code to make the `Send` constraint explicit.~
It now shows all unmet constraints for allowing the Future to be Send.
Fixes issue #4892.
First contribution here 😊 ! Do not hesitate to correct me.
This PR is related to issue #4892 .
# Summary
```rust
-literal.method_call(args)
```
The main idea is to not trigger `clippy::precedence` when the method call is an odd function.
# Example
```rust
// should trigger lint
let _ = -1.0_f64.abs() //precedence of method call abs() and neg ('-') is ambiguous
// should not trigger lint
let _ = -1.0_f64.sin() // sin is an odd function => -sin(x) = sin(-x)
```
# Theory
Rust allows following literals:
- char
- string
- integers
- floats
- byte
- bool
Only integers/floats implements the relevant `std::ops::Neg`.
Following odd functions are implemented on i[8-128] and/or f[32-64]:
- `asin`
- `asinh`
- `atan`
- `atanh`
- `cbrt`
- `fract`
- `round`
- `signum`
- `sin`
- `sinh`
- `tan`
- `tanh `
- `to_degrees`
- `to_radians`
# Implementation
As suggested by `flip1995` in [comment](https://github.com/rust-lang/rust-clippy/issues/4892#issuecomment-568249683), this PR add a whitelist of odd functions and compare method call to the the whitelist before triggering lint.
changelog: Don't trigger [`clippy::precedence`] on odd functions.
question_mark: don't add `as_ref()` for a call expression
If a call returns a `!Copy` value, it does so regardless of whether `as_ref()` is added. For example, `foo.into_option().as_ref()?` can be simplified to `foo.into_option()?`.
---
changelog: Improved `question_mark` lint suggestion so that it doesn't add redundant `as_ref()`