This checks for sequences in strings that would be octal character
escapes in C, but are not supported in Rust. It suggests either
to use the `\x00` escape, or an equivalent hex escape if the octal
was intended.
Pluralize `disallowed_type` lint
This was brought up in [Zulip] and is also mentioned in the lint naming
conventions. Since this is still a nursery lint, I think there shouldn't
be any problem in renaming it.
[Zulip]: rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/disallow_type.20vs.20disallowed-types
changelog: Rename nursery lint [`disallowed_type`] to [`disallowed_types`].
Improve `needless_borrow` lint
fixes: #5327fixes: #1726fixes: #1212
This is merging `needless_borrow` into the `dereference` pass in preparation for `explicit_auto_deref`. `explicit_auto_deref` needs to implement most of what `needless_borrow` implements in order to work.
There is a minor regression here where `let x: &str = &x.deref()` will trigger `needless_borrow` without triggering `explicit_deref_methods`. Removing the redundant borrow will cause `explicit_deref_methods` to trigger. This will be fixed when `explicit_auto_deref` is implemented.
changelog: Lint `needless_borrow` when a borrow is auto-derefed more than once
changelog: Lint `needless_borrow` in the trailing expression of a block for a match arm
Don't show no_effect warning on unit structs implementing fn_once
Fixes#7792
changelog: Don't show [`no_effect`] or [`unecessary_operation`] warning for unit struct implementing FnOnce
Fix for #7889 and add new lint needless_splitn
fixes: #7889
1. Fix the problem of manual_split_once changing the original behavior.
2. Add a new lint needless_splitn.
changelog: Fix the problem of manual_split_once changing the original behavior and add a new lint needless_splitn.
1. Fix the problem of manual_split_once changing the original behavior.
2. Add a new lint needless_splitn.
changelog: Fix the problem of manual_split_once changing the original behavior and add a new lint needless_splitn.
Fix `needless_collect`'s tendency to suggest code requiring multiple mutable borrows of the same value.
Fixes error specified in #7975.
changelog: [`needless_collect`] no longer suggests removal of `collect` when removal would create code requiring mutably borrowing a value multiple times.
* Lint when a borrow is auto dereferenced more than once
* Lint when the expression is used as the expression of a block for a match arm
Moves `needless_borrow` and `ref_binding_to_reference` to `dereference`
lint pass in preperation for `explicit_auto_deref` lint.
Support suggestion for #7854
I think the detection of parking_lot's mutex and rwlock is valuable, so submit this pr, please help judge and review, thank you.
Make let_underscore_lock support parking_lot.(Fixes#7854)
changelog: Make let_underscore_lock support parking_lot
I think the detection of parking_lot's mutex and rwlock is valuable, so submit this pr, please help judge and review, thank you.
Make let_underscore_lock support parking_lot.
changelog: Make let_underscore_lock support parking_lot
Lint for bool to integer casts in `cast_lossless`
The lint description says
> Checks for casts between *numerical* types that may be replaced by safe conversion functions.
Which is strictly speaking being violated here, but it seems within the spirit of the lint. I think it is still a useful lint to have, and having a different lint for just this feels excessive. Thoughts?
Fixes#7947
changelog: Lint for bool to integer casts in [`cast_lossless`]
Author improvements
changelog: none
Various aspects of the author implementation are re-imagined to be much less repetitive. Also fixes some bugs. I hope this makes author more fun to work on for future contributors.
The last commit is pretty heavy but I tried to at least separate some changes so that the test file diffs per commit are simple.
* Finding pattern slices for `avoidable_slice_indexing`
* `avoidable_slice_indexing` analysing slice usage
* Add configuration to `avoidable_slice_indexing`
* Emitting `avoidable_slice_indexing` with suggestions
* Dogfooding and fixing bugs
* Add ui-toml test for `avoidable_slice_indexing`
* Correctly suggest `ref` keywords for `avoidable_slice_indexing`
* Test and document `mut` for `avoid_slice_indexing`
* Handle macros with `avoidable_slice_indexing` lint
* Ignore slices with sub patterns in `avoidable_slice_indexing`
* Update lint description for `avoidable_slice_indexing`
* Move `avoidable_slice_indexing` to nursery
* Added more tests for `avoidable_slice_indexing`
* Update documentation and message for `avoidable_slice_indexing`
* Teach `avoidable_slice_indexing` about `HirId`s and `Visitors`
* Rename lint to `index_refutable_slice` and connected config
Fix `explicit_counter_loop` suggestion for non-usize types
changelog: Add a new suggestion for non-usize types in [`explicit_counter_loop`]
closes: #7920
Fix suggestion for deref expressions in redundant_pattern_matching
changelog: Fix suggestion for deref expressions in [`redundant_pattern_matching`]
closes: #7921
The only reason to use `abort_if_errors` is when the program is so broken that either:
1. later passes get confused and ICE
2. any diagnostics from later passes would be noise
This is never the case for lints, because the compiler has to be able to deal with `allow`-ed lints.
So it can continue to lint and compile even if there are lint errors.
Replace `in_macro` usage with `from_expansion`
changelog: none
Generally replace `in_macro(span)` with `span.from_expansion()`. If we're just trying to avoid expanded code, this seems more appropriate because any kind of expanded code is prone to false positives. One place I did not touch is `macro_use.rs`. I think this lint could use a rewrite so I moved `in_macro` there, the only place it is still used.
Prevent clippy::needless_lifetimes false positive in async function definition
Scan `OpaqueDef` bounds for lifetimes as well. Those `OpaqueDef` instances are generated while desugaring an `async` function definition.
This fixes#7893
changelog: Prevent [`clippy::needless_lifetimes`] false positive in `async` function definition
Fix manual_assert and match_wild_err_arm for `#![no_std]` and Rust 2021
Rust 2015 `std::panic!` has a wrapping block while `core::panic!` and Rust 2021 `std::panic!` does not. See rust-lang/rust#88919 for details.
Note that the test won't pass until clippy changes in rust-lang/rust#88860 is synced.
---
changelog: Fix [`manual_assert`] and [`match_wild_err_arm`] for `#![no_std]` and Rust 2021.
Fixes#7723
Unseparated literal suffix
Closes#7658
Since `literal_suffix` style is opinionated, we should disable by default and only enforce if it's stated as so.
changelog: [`unseparated_literal_suffix`] is renamed to `literal_suffix`, adds a new configuration `literal-suffix-style` to enforce a certain style writing literal_suffix. Possible values for `literal-suffix-style`: `"separated"`, `"unseparated"`
avoid linting `possible_truncation` on bit-reducing operations
---
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: avoid linting `possible_truncation` on bit-reducing operations
update most tests to 2021 edition
Some tests would no longer work at all, so I added `edition:2015` or `edition:2018` to them.
Notably 2021 panics are not yet detected correctly. Once ready, this closes#7842.
---
changelog: none
`unseparated_literal_suffix`
This commit adds a configuration `literal-suffix-style` to enforce a
specific style for unseparated_literal_suffix. The configuration accepts
two values:
- "separated"
enforce all literals to be written separately (e.g. `123_i32`)
- "unseparated"
enforce all literals to be written as unseparated (e.g. `123i32`)
Not specifying a value means that there is no preference on style and
any style should not be warned.
Disable "if_not_else" lints from firing on else-ifs
Fixes#7892
1. Convert `['if_not_else']` to `LateLintPass` and use `clippy_utils::is_else_clause` for checking.
2. Update tests.
changelog: [`if_not_else`] now ignores else if statements.
1. Convert IfNotElse to LateLintPass and use clippy_utils::is_else_clause for checking.
2. Handle the case where the span comes from desugaring.
3. Update tests.
Ignore references to type aliases in ptr_arg
Works using the fact that the hir path will point to a TyAlias, rather than being resolved to the underlying type
Fixes#7699
changelog: [`ptr_arg`] No longer lints references to type aliases
Add unit-hash lint
changelog: [`unit_hash`] Add lint for hashing unit values
This will lint for situations where the end user is attempting to hash a unit value (`()`), as the implementation in `std` simply [does nothing][impl]. Closes#7159 .
Example:
```rust
().hash(&mut state);
// Should (probably) be replaced with:
0_u8.hash(&mut state);
```
[impl]: a5f164faad/library/core/src/hash/mod.rs (L656)
Fix `question_mark` FP on custom error type
Closes#7859#7840 aims to ignore `question_mark` when the return type is custom, which is [covered here](df65291edd/tests/ui/question_mark.rs (L144-L149)). But this fails when there is a call in conditional predicate
changelog: [`question_mark`] Fix false positive when there is call in conditional predicate
Clean up tests/ui/rename.rs
Part one of #7057, cleaning up `tests/ui/rename.rs`. `tests/ui/deprecated.rs` will be updated in a subsequent PR.
changelog: none
new lint: string-slice
This is a restriction lint to highlight code that should have tests containing non-ascii characters. See #6623.
changelog: new lint: [`string-slice`]
Fix `match_str_case_mismatch` on uncased chars
False positives would result because `char::is_lowercase` and friends will return `false` for non-alphabetic chars and alphabetic chars lacking case (such as CJK scripts). Care also has to be taken for handling titlecase characters (`Dz`) and lowercased chars with no uppercase equivalent (`ʁ`).
For example, when verifying lowercase:
* Check `!any(char::is_ascii_uppercase)` instead of `all(char::is_ascii_lowercase)` for ASCII.
* Check that `all(|c| c.to_lowercase() == c)` instead of `all(char::is_lowercase)` for non-ASCII
Fixes#7863.
changelog: Fix false positives in [`match_str_case_mismatch`] on uncased characters
missing_safety_doc: Handle 'implementation safety' headers as well
We hit some FPs on this in `yoke`, it's somewhat normal to mark trait impl safety with "implementation safety". We could also broaden the check for headers which contain the word "safety" somehow, or split out impl safety stuff to only apply to traits.
changelog: handle 'implementation safety' headers in `missing_safety_doc`
Fix FP: no lint when cast is coming from `signum` method call for `cast_possible_truncation` lint
Fixes a FP when cast is coming from `signum` method call
fixes: #5395
changelog: [`cast_possible_truncation`] Fix FP when cast is coming from `signum` method call
Warn on structs with a trailing zero-sized array but no `repr` attribute
Closes#2868
changelog: Implement ``[`trailing_empty_array`]``, which warns if a struct is defined where the last field is a zero-sized array but there are no `repr` attributes. Zero-sized arrays aren't very useful in Rust itself, so such a struct is likely being created to pass to C code or in some other situation where control over memory layout matters. Either way, a `repr` attribute is needed.
FIx FP in `missing_safety_doc` lint
Fix FP where lint souldn't fire if any parent has `#[doc(hidden)]` attribute
fixes: #7347
changelog: [`missing_safety_doc`] Fix FP if any parent has `#[doc(hidden)]` attribute
Some "parenthesis" and "parentheses" fixes
"Parenthesis" is the singular (e.g. one `(` or one `)`) and "parentheses" is the plural (multiple `(` or `)`s) and this is not hard to mix up so here are some fixes for that.
Inspired by #89958
Add `format_in_format_args` and `to_string_in_format_args` lints
Fixes#7667 and #7729
I put these in `perf` since that was one of `@jplatte's` suggestions, and `redundant_clone` (which I consider to be similar) lives there as well.
However, I am open to changing the category or anything else.
r? `@camsteffen`
changelog: Add `format_in_format_args` and `to_string_in_format_args` lints
Do not expand macros in equatable_if_let suggestion
Fixes#7781
Let's use Hacktoberfest as a motivation to start contributing PRs myself again :)
changelog: [`equatable_if_let`]: No longer expands macros in the suggestion
Add #[must_use] to From::from and Into::into
Risk of churn: **High**
Magic 8-Ball says: **Outlook not so good**
I figured I'd put this out there. If we don't do it now maybe we save it for a rainy day.
Parent issue: #89692
r? `@joshtriplett`
Fix FP in external macros for `mut_mut` lint
Fix FP in `mut_mut` lint when type is defined in external macros.
fixes: #6922
changelog: [`mut_mut`] Fix FP when type is defined in external macros
Refactor `clippy::match_ref_pats` to check for multiple reference patterns
fixes#7740
When there is only one pattern, to begin with, i.e. a single deref(`&`), then in such cases we suppress `clippy::match_ref_pats`.
This is done by checking the count of the reference pattern and emitting `clippy::match_ref_pats` when more than one pattern is present.
Removed certain errors in the `stderr` tests as they would not be triggered.
changelog: Refactor `clippy::match_ref_pats` to check for multiple reference patterns
Before this lint didn't trigger on macros. With rust-lang/rust#88175
this isn't enough anymore. In this PR a `WhileLoop` desugaring kind was
introduced. This overrides the span of expanded expressions when
lowering the while loop. So if a while loop is in a macro, the
expressions that it expands to are no longer marked with
`ExpnKind::Macro`, but with `ExpnKind::Desugaring`. In general, this is
the correct behavior and the same that is done for `ForLoop`s. It just
tripped up this lint.
Restriction lint for function pointer casts
The existing lints for function pointer casts cover the cases where a cast is non-portable or would result in truncation, however there's currently no way to forbid numeric function pointer casts entirely.
I've added a new lint `fn_to_numeric_cast_any`, which allows one to ban _all_ numeric function pointer casts, including to `usize`. This is useful if you're writing high-level Rust and want to opt-out of potentially surprising behaviour, avoiding silent bugs from forgotten parentheses, e.g.
```rust
fn foo() -> u32 {
10
}
fn main() {
let _ = foo as usize; // oops, forgot to call foo and got a random address instead!
}
```
~~I'm open to suggestions for the naming of the lint, because `fn_to_numeric_cast_any` is a bit clunky. Ideally I'd call this lint `fn_to_numeric_cast`, but that name is already taken for the more specific lint~~. We've stuck with `fn_to_numeric_cast_any` to avoid renaming the existing lint, or choosing a different name that's too generic (like `fn_cast`).
I'm also open to changing the suggestion behaviour, as adding parentheses is only one of many possible ways to fix the lint.
changelog: add ``[`fn_to_numeric_cast_any`]`` restriction lint
Make `shadow_reuse` suggestion less verbose
Closes#7764
Make `shadow_reuse` suggestion less verbose.
changelog: [`shadow_reuse`] does not warn shadowing statement
make test module detection more strict
I started with some small improvements to clippy_utils/src/lib.rs, but then found that our "test" module detection would also catch words containing "test" like e.g. "attestation". So I made this a bit more strict (splitting by `'_'` and checking for `test` or `tests`), adding a test case as I went.
---
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: none
Fix ICE when `start` lang item has wrong generics
In my previous pr #87875 I missed the requirements on the `start` lang item due to its relative difficulty to test and opting for more conservative estimates. This fixes that by updating the requirement to be exactly one generic type.
The `start` lang item should have exactly one generic type for the return type of the `main` fn ptr passed to it. I believe having zero would previously *sometimes* compile (often with the use of `fn() -> ()` as the fn ptr but it was likely UB to call if the return type of `main` was not `()` as far as I know) however it also sometimes would not for various errors including ICEs and LLVM errors depending on exact situations. Having more than 1 generic has always failed with an ICE because only the one generic type is expected and provided.
Fixes#79559, fixes#73584, fixes#83117 (all duplicates)
Relevant to #9307
r? ````@cjgillot````
fix bug for large_enum_variants
Fix the discussion problem in the issue of https://github.com/rust-lang/rust-clippy/issues/7666#issuecomment-919654291
About the false positive problem of case:
```rust
enum LargeEnum6 {
A,
B([u8;255]),
C([u8;200]),
}
```
changelog: Fix largest_enum_variant wrongly identifying the second largest variant.
Rustup
This needs a review this time. Especially 521bf8f0fa cc `@camsteffen` I think this is necessary now, because `itertools` is no longer a dependency of `clippy_utils` and therefore this path can't be found 🤔
( I forgot about the sync last week. I should get to document this process better, so other people can do it when I'm not around )
changelog: none
Don't lint `suspicious_else_formatting` inside proc-macros
fixes: #7650
I'll add a test for this one soon.
changelog: Don't lint `suspicious_else_formatting` inside proc-macros
Expand box_vec lint to box_collection
fixed#7451
changelog: Expand `box_vec` into [`box_collection`], and have it error on all sorts of boxed collections
Change `while_let_on_iterator` suggestion to use `by_ref()`
It came up in the discussion #7659 that suggesting `iter.by_ref()` is a clearer suggestion than `&mut iter`. I personally think they're equivalent, but if `by_ref()` is clearer to people then that should be the suggestion.
changelog: Change `while_let_on_iterator` suggestion when using `&mut` to use `by_ref()`
New lint: `same_name_method`
changelog: ``[`same_name_method`]``
fix: https://github.com/rust-lang/rust-clippy/issues/7632
It only compares a method in `impl` with another in `impl trait for`
It doesn't lint two methods in two traits.
I'm not sure my approach is the best way. I meet difficulty in other approaches.
Fix various redundant_closure bugs
changelog: Fix various false negatives and false positives for [`redundant_closure`]
Closes#3071Closes#4002
This lint is full of weird nuances and this is basically a re-write to tighten up the logic.
Fix result order for `manual_split_once` when `rsplitn` is used
fixes: #7656
changelog: Fix result order for `manual_split_once` when `rsplitn` is used
Add new lint `iter_not_returning_iterator`
Add new lint [`iter_not_returning_iterator`] to detect method `iter()` or `iter_mut()` returning a type not implementing `Iterator`
changelog: Add new lint [`iter_not_returning_iterator`]
Fix `option_if_let_else`
fixes: #5822fixes: #6737fixes: #7567
The inference from #6137 still exists so I'm not sure if this should be moved from the nursery. Before doing that though I'd almost want to see this split into two lints. One suggesting `map_or` and the other suggesting `map_or_else`.
`map_or_else` tends to have longer expressions for both branches so it doesn't end up much shorter than a match expression in practice. It also seems most people find it harder to read. `map_or` at least has the terseness benefit of being on one line most of the time, especially when the `None` branch is just a literal or path expression.
changelog: `break` and `continue` statments local to the would-be closure are allowed in `option_if_let_else`
changelog: don't lint in const contexts in `option_if_let_else`
changelog: don't lint when yield expressions are used in `option_if_let_else`
changelog: don't lint when the captures made by the would-be closure conflict with the other branch in `option_if_let_else`
changelog: don't lint when a field of a local is used when the type could be pontentially moved from in `option_if_let_else`
changelog: in some cases, don't lint when scrutinee expression conflicts with the captures of the would-be closure in `option_if_let_else`
Don't report function calls as unnecessary operation if used in array index
Attempts to fix: #7412
changelog: Don't report function calls used in indexing as unnecessary operation. [`unnecessary_operation`]
Add new lint `negative_feature_names` and `redundant_feature_names`
Add new lint [`negative_feature_names`] to detect feature names with prefixes `no-` or `not-` and new lint [`redundant_feature_names`] to detect feature names with prefixes `use-`, `with-` or suffix `-support`
changelog: Add new lint [`negative_feature_names`] and [`redundant_feature_names`]
* `break` and `continue` statments local to the would-be closure are allowed
* don't lint in const contexts
* don't lint when yield expressions are used
* don't lint when the captures made by the would-be closure conflict with the other branch
* don't lint when a field of a local is used when the type could be pontentially moved from
* in some cases, don't lint when scrutinee expression conflicts with the captures of the would-be closure
Uplift the invalid_atomic_ordering lint from clippy to rustc
This is mostly just a rebase of https://github.com/rust-lang/rust/pull/79654; I've copy/pasted the text from that PR below.
r? `@lcnr` since you reviewed the last one, but feel free to reassign.
---
This is an implementation of https://github.com/rust-lang/compiler-team/issues/390.
As mentioned, in general this turns an unconditional runtime panic into a (compile time) lint failure. It has no false positives, and the only false negatives I'm aware of are if `Ordering` isn't specified directly and is comes from an argument/constant/whatever.
As a result of it having no false positives, and the alternative always being strictly wrong, it's on as deny by default. This seems right.
In the [zulip stream](https://rust-lang.zulipchat.com/#narrow/stream/233931-t-compiler.2Fmajor-changes/topic/Uplift.20the.20.60invalid_atomic_ordering.60.20lint.20from.20clippy/near/218483957) `@joshtriplett` suggested that lang team should FCP this before landing it. Perhaps libs team cares too?
---
Some notes on the code for reviewers / others below
## Changes from clippy
The code is changed from [the implementation in clippy](68cf94f6a6/clippy_lints/src/atomic_ordering.rs) in the following ways:
1. Uses `Symbols` and `rustc_diagnostic_item`s instead of string literals.
- It's possible I should have just invoked Symbol::intern for some of these instead? Seems better to use symbol, but it did require adding several.
2. The functions are moved to static methods inside the lint struct, as a way to namespace them.
- There's a lot of other code in that file — which I picked as the location for this lint because `@jyn514` told me that seemed reasonable.
3. Supports unstable AtomicU128/AtomicI128.
- I did this because it was almost easier to support them than not — not supporting them would have (ideally) required finding a way not to give them a `rustc_diagnostic_item`, which would have complicated an already big macro.
- These don't have tests since I wasn't sure if/how I should make tests conditional on whether or not the target has the atomic... This is to a certain extent an issue of 64bit atomics too, but 128-bit atomics are much less common. Regardless, the existing tests should be *more* than thorough enough here.
4. Minor changes like:
- grammar tweaks ("loads cannot have `Release` **and** `AcqRel` ordering" => "loads cannot have `Release` **or** `AcqRel` ordering")
- function renames (`match_ordering_def_path` => `matches_ordering_def_path`),
- avoiding clippy-specific helper methods that don't exist in rustc_lint and didn't seem worth adding for this case (for example `cx.struct_span_lint` vs clippy's `span_lint_and_help` helper).
## Potential issues
(This is just about the code in this PR, not conceptual issues with the lint or anything)
1. I'm not sure if I should have used a diagnostic item for `Ordering` and its variants (I couldn't figure out how really, so if I should do this some pointers would be appreciated).
- It seems possible that failing to do this might possibly mean there are more cases this lint would miss, but I don't really know how `match_def_path` works and if it has any pitfalls like that, so maybe not.
2. I *think* I deprecated the lint in clippy (CC `@flip1995` who asked to be notified about clippy changes in the future in [this comment](https://github.com/rust-lang/rust/pull/75671#issuecomment-718731659)) but I'm not sure if I need to do anything else there.
- I'm kind of hoping CI will catch if I missed anything, since `x.py test src/tools/clippy` fails with a lot of errors with and without my changes (and is probably a nonsense command regardless). Running `cargo test` from src/tools/clippy also fails with unrelated errors that seem like refactorings that didnt update clippy? So, honestly no clue.
3. I wasn't sure if the description/example I gave good. Hopefully it is. The example is less thorough than the one from clippy here: https://rust-lang.github.io/rust-clippy/master/index.html#invalid_atomic_ordering. Let me know if/how I should change it if it needs changing.
4. It pulls in the `if_chain` crate. This crate was already used in clippy, and seems like it's used elsewhere in rustc, but I'm willing to rewrite it to not use this if needed (I'd prefer not to, all things being equal).
- Deprecate clippy::invalid_atomic_ordering
- Use rustc_diagnostic_item for the orderings in the invalid_atomic_ordering lint
- Reduce code duplication
- Give up on making enum variants diagnostic items and just look for
`Ordering` instead
I ran into tons of trouble with this because apparently the change to
store HIR attrs in a side table also gave the DefIds of the
constructor instead of the variant itself. So I had to change
`matches_ordering` to also check the grandparent of the defid as well.
- Rename `atomic_ordering_x` symbols to just the name of the variant
- Fix typos in checks - there were a few places that said "may not be
Release" in the diagnostic but actually checked for SeqCst in the lint.
- Make constant items const
- Use fewer diagnostic items
- Only look at arguments after making sure the method matches
This prevents an ICE when there aren't enough arguments.
- Ignore trait methods
- Only check Ctors instead of going through `qpath_res`
The functions take values, so this couldn't ever be anything else.
- Add if_chain to allowed dependencies
- Fix grammar
- Remove unnecessary allow
* Captures by sub closures are now considered
* Copy types are correctly borrowed by reference when their value is used
* Fields are no longer automatically borrowed by value
* Bindings in `match` and `let` patterns are now checked to determine how a local is captured
Link to edition guide instead of issues for 2021 lints.
This changes the 2021 lints to not link to github issues, but to the edition guide instead.
Fixes #86996
Add `unwrap_or_else_default` lint
---
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: Add a new [`unwrap_or_else_default`] style lint. This will catch `unwrap_or_else(Default::default)` on Result and Option and suggest `unwrap_or_default()` instead.
`never_loop`: suggest using an `if let` instead of a `for` loop
changelog: suggest using an `if let` statement instead of a `for` loop that [`never_loop`]s
Fixes#7537, r? `@camsteffen.`
Make `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` warn by default
This PR makes the `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint warn by default.
To avoid showing a large number of un-actionable warnings to users, we only enable the lint for macros defined in the same crate. This ensures that users will be able to fix the warning by simply removing a semicolon.
In the future, I'd like to enable this lint unconditionally, and eventually make it into a hard error in a future edition. This PR is a step towards that goal.
Prefer a code snipped over formatting the self type (`new_without_default`)
Fixes: rust-lang/rust-clippy#7220
changelog: [`new_without_default`]: The `Default` impl block type doesn't use the full type path qualification
Have a nice day to everyone reading this 🙃
similar_names: No longer suggest inserting or appending an underscore
changelog: [`similar_names`] lint no longer suggests to insert or add an underscore to "fix" too similar names
New lint: [`self_named_constructor`]
Adds the `self_named_constructor` lint for detecting when an implemented method has the same name as the type it is implemented for.
changelog: [`self_named_constructor`]
closes: #7142
FP fix and documentation for `branches_sharing_code` lint
Closesrust-lang/rust-clippy#7369
Related rust-lang/rust-clippy#7452 I'm still thinking about the best way to fix this. I could simply add another visitor to ensure that the moved expressions don't modify values being used in the condition, but I'm not totally happy with this due to the complexity. I therefore only documented it for now
changelog: [`branches_sharing_code`] fixed false positive where block expressions would sometimes be ignored.
Don't suggest doc(hidden) or unstable variants in wildcard lint
Clippy's wildcard lint would suggest doc(hidden) and unstable variants for non_exhaustive enums, even though those aren't part of the public interface (yet) and should only be matched on using a `_`, just like potential future additions to the enum. There was already some logic to exclude a *single* doc(hidden) variant. This extends that to all hidden variants, and also hides `#[unstable]` variants.
See https://github.com/rust-lang/rust/pull/85746#issuecomment-868886893
This PR includes https://github.com/rust-lang/rust-clippy/pull/7406 as the first commit.
Here's the diff that this PR adds on top of that PR: https://github.com/m-ou-se/rust-clippy/compare/std-errorkind...m-ou-se:doc-hidden-variants
---
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: No longer suggest unstable and doc(hidden) variants in wildcard lint. wildcard_enum_match_arm, match_wildcard_for_single_variants
This fixes a bug where match_wildcard_for_single_variants produced a
bad suggestion where besides the missing variant, one or more hidden
variants were left.
This also adds tests to the ui-tests match_wildcard_for_single_variants
and wildcard_enum_match_arm to make sure that the correct suggestion is
produced.
New lint: `disallowed_script_idents`
This PR implements a new lint to restrict locales that can be used in the code,
as proposed in #7376.
Current concerns / unresolved questions:
- ~~Mixed usage of `script` (as a Unicode term) and `locale` (as something that is easier to understand for the broad audience). I'm not sure whether these terms are fully interchangeable and whether in the current form it is more confusing than helpful.~~ `script` is now used everywhere.
- ~~Having to mostly copy-paste `AllowedScript`. Probably it's not a big problem, as the list of scripts is standardized and is unlikely to change, and even if we'd stick to the `unicode_script::Script`, we'll still have to implement custom deserialization, and I don't think that it will be shorter in terms of the amount of LoC.~~ `unicode::Script` is used together with a filtering deserialize function.
- Should we stick to the list of "recommended scripts" from [UAX #31](http://www.unicode.org/reports/tr31/#Table_Recommended_Scripts) in the configuration?
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: ``[`disallowed_script_idents`]``
r? `@Manishearth`
Improve lint message for match-same-arms lint
fixes#7331
Follow-up to #7377
This PR improves the lint message for `match-same-arms` lint and adds `todo!(..)` example to the lint docs.
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: None
Do not spawn blacklisted_name lint in test context
---
fixed#7305
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: `blacklisted_name` lint is not spawned in the test context anymore.
Fix detecting of the 'test' attribute
Update UI test to actually check that warning is not triggered in the test code
Fix approach for detecting the test module
Add nested test case
Remove code duplication by extracting 'is_test_module_or_function' into 'clippy_utils'
Cleanup the code
Problem:
for code like
````
fn main() {
println!("Hello, world!");
}
````
clippy will issue a warning to use a clippy.toml option instead:
````
warning: lint `clippy::wrong_pub_self_convention` has been removed: set the `avoid_breaking_exported_api` config option to `false` to enable the `wrong_self_convention` lint for public items
--> src/main.rs:2:9
|
2 | #![warn(clippy::wrong_pub_self_convention)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(renamed_and_removed_lints)]` on by default
````
But using the lint name as seen in the warning message
echo "avoid_breaking_exported_api = true\n" > clippy.toml
Will cause an error:
````
error: error reading Clippy's configuration file `/tmp/clippytest/clippy.toml`: unknown field `avoid_breaking_exported_api`, expected one of `avoid-breaking-exported-api`, ...
````
Replace the underscores with dashes in the deprecation message.
changelog: avoid_breaking_exported_api: suggest correct clippy config toml option in the deprecation message
Add macro_braces lint to check for irregular brace use in certain macros
The name is a bit long but this sounds good as `#[allow(unconventional_macro_braces)]` and it seems more clear that we are talking about the macro call not macro definitions, any feedback let me know. Thanks!
fixes#7278
changelog: Add ``[`unconventional_macro_braces`]`` lint that checks for uncommon brace usage with macros.
Rename unconventional -> nonstandard, add config field
Add standard_macro_braces fields so users can specify macro names and
brace combinations to lint for in the clippy.toml file.
Fix errors caused by nonstandard_macro_braces in other lint tests
Fix users ability to override the default nonstandard macro braces
Add type position macros impl `check_ty`
Vec extend to append
This PR adds a check to suggest changes of vector from
```
vec.extend(other_vec.drain(..))
```
could be written as
```
vec![].append(&mut vec![]);
```
changelog: Add vec_extend_to_append lint
issue: #7209
Don't trigger `field_reassign_with_default` in macros
Fixes#7155
Producing a good suggestion for this lint is already hard when no macros
are involved. With macros the lint message and the suggestion are just
confusing. Since both, producing a good suggestion and figuring out if
this pattern can be re-written inside a macro is nearly impossible, just
bail out.
changelog: [`field_reassign_with_default`] No longer triggers in macros
---
No that our reviewing queue is under control, I want to start hacking on Clippy myself again. Starting with an easy issue to get back in :)
Fix false positive on `semicolon_if_nothing_returned`
Currently the [`semicolon_if_nothing_returned`](https://rust-lang.github.io/rust-clippy/master/index.html#semicolon_if_nothing_returned) lint fires in unwanted situations where a block only spans one line. An example of this was given in #7324. This code:
```rust
use std::mem::MaybeUninit;
use std::ptr;
fn main() {
let mut s = MaybeUninit::<String>::uninit();
let _d = || unsafe { ptr::drop_in_place(s.as_mut_ptr()) };
}
```
yields the following clippy error:
```
error: consider adding a `;` to the last statement for consistent formatting
--> src/main.rs:6:26
|
6 | let _d = || unsafe { ptr::drop_in_place(s.as_mut_ptr()) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: add a `;` here: `ptr::drop_in_place(s.as_mut_ptr());`
|
= note: `-D clippy::semicolon-if-nothing-returned` implied by `-D clippy::pedantic`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#semicolon_if_nothing_returned
```
I updated the lint to check if the statement is inside an `unsafe` block, a closure or a normal block and if the block only spans one line, in that case the lint is not emitted.
This closes#7324.
changelog: enhanced semicolon if nothing returned according to #7324.
Refactoring identity function lints
I've noticed that we have several lints that all check for identity functions and each used their own check implementation. I moved the `is_expr_identity_function` function to `clippy_utils` and adapted all lints to reuse that one function. This should make the addition of new lints like this also easier in the future.
I've also moved the `map_identity` lint into the `methods` module. It's probably the best to review this PR by checking each commit individually. And that's it, have a great day 🙃
changelog: none
fix `while_let_on_iterator` suggestion in a closure
fixes: #7249
A future improvement would be to check if the closure is being used as `FnOnce`, in which case the original suggestion would be correct.
changelog: Suggest `&mut iter` inside a closure for `while_let_on_iterator`
Fix missing_docs_in_private_items false negative
changelog: Fix [`missing_docs_in_private_items`] false negative when the item has any `#[name = "value"]` attribute
Closes#7247 (decided not to use the rustc method since it calls `Session::check_name`, which is for rustc only)
Fix allow on some statement lints
changelog: Fix `#[allow(..)]` over statements for [`needless_collect`], [`short_circuit_statement`] and [`unnecessary_operation`]
Fixes#7171Fixes#7202
Fix invalid syntax in `from_iter_instead_of_collect` suggestion
First attempt at contributing, hopefully this is a good start and can be improved. :)
fixes#7259
changelog: [`from_iter_instead_of_collect`] fix invalid suggestion involving "as Trait"
Don't lint `multiple_inherent_impl` with generic arguments
fixes: #5772
changelog: Treat different generic arguments as different types in `multiple_inherent_impl`
Remove powi, "square can be computed more efficiently"
powi(2) produces exactly the same native code as x * x
powi was part of the [`suboptimal_flops`] lint
fixes#7058
changelog: Remove powi [`suboptimal_flops`], "square can be computed more efficiently"
Add `needless_bitwise_bool` lint
fixes#6827fixes#1594
changelog: Add ``[`needless_bitwise_bool`]`` lint
Creates a new `bitwise_bool` lint to convert `x & y` to `x && y` when both `x` and `y` are booleans. I also had to adjust thh `needless_bool` lint slightly, and fix a couple failing dogfood tests. I made it a correctness lint as per flip1995's comment [here](https://github.com/rust-lang/rust-clippy/pull/3385#issuecomment-434715723), from a previous WIP attempt at this lint.
Fix FPs about generic args
Fix 2 false positives in [`use_self`] and [`useless_conversion`] lints, by taking into account generic args and comparing them.
Fixes: #7205Fixes: #7206
changelog: Fix FPs about generic args in [`use_self`] and [`useless_conversion`] lints
New lint: `unused_async`
changelog: Adds a lint, `unused_async`, which checks for async functions with no await statements
`unused_async` is a lint that reduces code smell and overhead by encouraging async functions to be refactored into synchronous functions.
Fixes#7176
### Examples
```rust
async fn get_random_number() -> i64 {
4 // Chosen by fair dice roll. Guaranteed to be random.
}
```
Could be written as:
```rust
fn get_random_number() -> i64 {
4 // Chosen by fair dice roll. Guaranteed to be random.
}
```
Something like this, however, should **not** be caught by clippy:
```rust
#[async_trait]
trait AsyncTrait {
async fn foo();
}
struct Bar;
#[async_trait]
impl AsyncTrait for Bar {
async fn foo() {
println!("bar");
}
}
```
Stop linting `else if let` pattern in [`option_if_let_else`] lint
For readability concerns, it is counterproductive to lint `else if let` pattern.
Unfortunately the suggested code is much less readable.
Fixes: #7006
changelog: stop linting `else if let` pattern in [`option_if_let_else`] lint
`needless_collect` enhancements
fixes#7164
changelog: `needless_collect`: For `BTreeMap` and `HashMap` lint only `is_empty`, as `len` might produce different results than iter's `count`
changelog: `needless_collect`: Lint `LinkedList` and `BinaryHeap` in direct usage case as well
Trigger [`wrong_self_convention`] only if it has implicit self
Lint [`wrong_self_convention`] only if the impl or trait has `self` _per sé_.
Fixes: #7179
changelog: trigger [`wrong_self_convention`] only if it has implicit self
match_single_binding: Fix invalid suggestion when match scrutinee has side effects
fixes#7094
changelog: `match_single_binding`: Fix invalid suggestion when match scrutinee has side effects
---
`Expr::can_have_side_effects` is used to determine the scrutinee has side effects, while this method is a little bit conservative for our use case. But I'd like to use it to avoid reimplementation of the method and too much heuristics. If you think this is problematic, then I'll implement a custom visitor to address it.
* Suggest `&mut iter` when the iterator is used after the loop.
* Suggest `&mut iter` when the iterator is a field in a struct.
* Don't lint when the iterator is a field in a struct, and the struct is
used in the loop.
* Lint when the loop is nested in another loop, but suggest `&mut iter`
unless the iterator is from a local declared inside the loop.