Add lint for comparing to empty slices instead of using .is_empty()
Hey first time making a clippy lint
I added the implementation of the lint the `len_zero` since it shared a lot of the code, I would otherwise have to rewrite. Just tell me if the lint should use it's own file instead
changelog: Add lint for comparing to empty slices
Fixes#6217
Lint items after statements in local macro expansions
The items_after_statements lint was skipping all expansions. Instead
we should still lint local macros.
Fixes#578
---
*Please keep the line below*
changelog: The items_after_statements now applies to local macro expansions
No lint in macro for `toplevel_ref_arg`
Do not lint when the span is from a macro.
Question: shouldn't we extend this for external macros also ?
Fixes: #5849
changelog: none
Hex bin digit grouping
This revives and updates an old pr (#3391) for the current API.
Closes#2538.
---
*Please keep the line below*
changelog: Add [`unusual_byte_groupings`] lint.
Remove redundant `expect_local()` call
The field `owner` of `HirId` is `LocalDefId` and `hir_id.owner.to_def_id().expect_local()` is redundant. I wonder they were introduced in some rustups.
changelog: none
No lint with `cfg!` and fix sugg for macro in `needless_bool` lint
Don't lint if `cfg!` macro is one of the operand.
Fix suggestion when the span originated from a macro, using `hir_with_macro_callsite`.
Fixes: #3973
changelog: none
New lint: manual-range-contains
This fixes#1110, at least for the contains-suggesting part.
- \[x] Followed [lint naming conventions][lint_naming]
- \[x] Added passing UI tests (including committed `.stderr` file)
- \[x] `cargo test` passes locally
- \[x] Executed `cargo dev update_lints`
- \[x] Added lint documentation
- \[x] Run `cargo dev fmt`
---
changelog: new lint: manual-range-contains
Add lint for `&mut Mutex::lock`
Fixes#1765
changelog: Add lint [`mut_mutex_lock`] for `&mut Mutex::lock` and suggests using `&mut Mutex::get_mut` instead.
Update empty_loop documentation/message.
Originally part of #6161, but now this PR only deals with `std` crates
This change:
- Updates the `std` message .
- Updates the docs to mention how the busy loops should be fixed
- Gives examples of how to do this for `no_std` targets
- Updates the tests/stderr files to test this change.
changelog: Update `empty_loop` lint documentation
Split out statement attributes changes from #78306
This is the same as PR https://github.com/rust-lang/rust/pull/78306, but `unused_doc_comments` is modified to explicitly ignore statement items (which preserves the current behavior).
This shouldn't have any user-visible effects, so it can be landed without lang team discussion.
---------
When the 'early' and 'late' visitors visit an attribute target, they
activate any lint attributes (e.g. `#[allow]`) that apply to it.
This can affect warnings emitted on sibiling attributes. For example,
the following code does not produce an `unused_attributes` for
`#[inline]`, since the sibiling `#[allow(unused_attributes)]` suppressed
the warning.
```rust
trait Foo {
#[allow(unused_attributes)] #[inline] fn first();
#[inline] #[allow(unused_attributes)] fn second();
}
```
However, we do not do this for statements - instead, the lint attributes
only become active when we visit the struct nested inside `StmtKind`
(e.g. `Item`).
Currently, this is difficult to observe due to another issue - the
`HasAttrs` impl for `StmtKind` ignores attributes for `StmtKind::Item`.
As a result, the `unused_doc_comments` lint will never see attributes on
item statements.
This commit makes two interrelated fixes to the handling of inert
(non-proc-macro) attributes on statements:
* The `HasAttr` impl for `StmtKind` now returns attributes for
`StmtKind::Item`, treating it just like every other `StmtKind`
variant. The only place relying on the old behavior was macro
which has been updated to explicitly ignore attributes on item
statements. This allows the `unused_doc_comments` lint to fire for
item statements.
* The `early` and `late` lint visitors now activate lint attributes when
invoking the callback for `Stmt`. This ensures that a lint
attribute (e.g. `#[allow(unused_doc_comments)]`) can be applied to
sibiling attributes on an item statement.
For now, the `unused_doc_comments` lint is explicitly disabled on item
statements, which preserves the current behavior. The exact locatiosn
where this lint should fire are being discussed in PR #78306
Add new lint for undropped ManuallyDrop values
Adds a new lint for the following code:
```rust
struct S;
impl Drop for S {
fn drop(&mut self) {
println!("drip drop");
}
}
fn main() {
// This will not drop the `S`!!!
drop(std::mem::ManuallyDrop::new(S));
unsafe {
// This will.
std::mem::ManuallyDrop::drop(&mut std::mem::ManuallyDrop::new(S));
}
}
```
The inner value of a `ManuallyDrop` will not be dropped unless the proper, unsafe drop function is called on it. This lint makes sure that a user does not accidently use the wrong function and forget to drop a `ManuallyDrop` value.
Fixes#5581.
---
*Please keep the line below*
changelog: none
Add lint for holding RefCell Ref across an await
Fixes#6008
This introduces the lint await_holding_refcell_ref. For async functions, we iterate
over all types in generator_interior_types and look for `core::cell::Ref` or `core::cell::RefMut`. If we find one then we emit a lint.
Heavily cribs from: https://github.com/rust-lang/rust-clippy/pull/5439
changelog: introduce the await_holding_refcell_ref lint
Lint unnecessary int-to-int and float-to-float casts
This is an implementation of a lint that detects unnecessary casts of number literals, as discussed here:
https://github.com/rust-lang/rust-clippy/issues/6116
---
changelog: lint unnecessary as-casts of literals when they could be written using literal syntax.
Refactor trivially_copy_pass_by_ref and the new lint into pass_by_ref_or_value module
Update stderr of conf_unknown_key test
Rename lint to large_types_passed_by_value
Increase `pass_by_value_size_limit` default value to 256
Improve rules for `large_types_passed_by_value`
Improve tests for `large_types_passed_by_value`
Improve documentation for `large_types_passed_by_value`
Make minor corrections to pass_by_ref_or_value.rs suggested by clippy itself
Fix `large_types_passed_by_value` example and improve docs
pass_by_ref_or_value: Tweak check for mut annotation in params
large_types_passed_by_value: add tests for pub trait, trait impl and inline attributes
When the 'early' and 'late' visitors visit an attribute target, they
activate any lint attributes (e.g. `#[allow]`) that apply to it.
This can affect warnings emitted on sibiling attributes. For example,
the following code does not produce an `unused_attributes` for
`#[inline]`, since the sibiling `#[allow(unused_attributes)]` suppressed
the warning.
```rust
trait Foo {
#[allow(unused_attributes)] #[inline] fn first();
#[inline] #[allow(unused_attributes)] fn second();
}
```
However, we do not do this for statements - instead, the lint attributes
only become active when we visit the struct nested inside `StmtKind`
(e.g. `Item`).
Currently, this is difficult to observe due to another issue - the
`HasAttrs` impl for `StmtKind` ignores attributes for `StmtKind::Item`.
As a result, the `unused_doc_comments` lint will never see attributes on
item statements.
This commit makes two interrelated fixes to the handling of inert
(non-proc-macro) attributes on statements:
* The `HasAttr` impl for `StmtKind` now returns attributes for
`StmtKind::Item`, treating it just like every other `StmtKind`
variant. The only place relying on the old behavior was macro
which has been updated to explicitly ignore attributes on item
statements. This allows the `unused_doc_comments` lint to fire for
item statements.
* The `early` and `late` lint visitors now activate lint attributes when
invoking the callback for `Stmt`. This ensures that a lint
attribute (e.g. `#[allow(unused_doc_comments)]`) can be applied to
sibiling attributes on an item statement.
For now, the `unused_doc_comments` lint is explicitly disabled on item
statements, which preserves the current behavior. The exact locatiosn
where this lint should fire are being discussed in PR #78306
We also update the documentation to note that the remediations are
different for `std` and `no_std` crates.
Signed-off-by: Joe Richey <joerichey@google.com>
Identical arguments on assert macro family
Lint when identical args are used on `assert_eq!`, `debug_assert_eq!`, `assert_ne!` and `debug_assert_ne!` macros.
Added to the lint `eq_op`.
Common functions added to `utils/higher.rs`
Fixes: #3574Fixes: #4694
changelog: Lint on identical args when calling `assert_eq!`, `debug_assert_eq!`, `assert_ne!` and `debug_assert_ne!` macros
BTreeMap: refactor Entry out of map.rs into its own file
btree/map.rs is approaching the 3000 line mark, splitting out the entry
code buys about 500 lines of headroom.
I've created this PR because the changes I've made in #77438 will push `map.rs` over the 3000 line limit and cause tidy to complain.
I picked `Entry` to factor out because it feels less tightly coupled to the rest of `BTreeMap` than the various iterator implementations.
Related: #60302
Sync from rust
Fix rustc breakage by running:
```rust
git subtree push -P src/tools/clippy git@github.com:josephlr/rust-clippy sync-from-rust
```
and then adding a commit that runs `cargo dev fmt`
---
changelog: none
The wrapper type led to tons of target.target
across the compiler. Its ptr_width field isn't
required any more, as target_pointer_width
is already present in parsed form.
Fix two ICEs caused by ty.is_{sized,freeze}
Fixes#6153
Properly fixes#6139
The test case in #6153 is kind of weird. Even removing one of the arguments of the `foo` function prevented the ICE. I think this test case is actually minimal.
changelog: none
Ref style link false positive
This PR does not fix#5834, but it records the problematic link text as a **known problem** inside `doc_markdown` lint.
r? `@flip1995`
- [ ] Followed [lint naming conventions][lint_naming]
- [ ] Added passing UI tests (including committed `.stderr` file)
- [x] `cargo test` passes locally
- [x] Executed `cargo dev update_lints`
- [ ] Added lint documentation
- [x] Run `cargo dev fmt`
---
*Please keep the line below*
changelog: Document problematic link text style as known problem for `doc_markdown`
Expands `manual_memcpy` to lint ones with loop counters
Closes#1670
This PR expands `manual_memcpy` to lint ones with loop counters as described in https://github.com/rust-lang/rust-clippy/issues/1670#issuecomment-293280204
Although the current code is working, I have a couple of questions and concerns.
~~Firstly, I manually implemented `Clone` for `Sugg` because `AssocOp` lacks `Clone`. As `AssocOp` only holds an enum, which is `Copy`, as a value, it seems `AssocOp` can be `Clone`; but, I was not sure where to ask it. Should I make a PR to `rustc`?~~ The [PR]( https://github.com/rust-lang/rust/pull/73629) was made.
Secondly, manual copying with loop counters are likely to trigger `needless_range_loop` and `explicit_counter_loop` along with `manual_memcpy`; in fact, I explicitly allowed them in the tests. Is there any way to disable these two lints when a code triggers `manual_memcpy`?
And, another thing I'd like to note is that `Sugg` adds unnecessary parentheses when expressions with parentheses passed to its `hir` function, as seen here:
```
error: it looks like you're manually copying between slices
--> $DIR/manual_memcpy.rs:145:14
|
LL | for i in 3..(3 + src.len()) {
| ^^^^^^^^^^^^^^^^^^ help: try replacing the loop by: `dst[3..((3 + src.len()))].clone_from_slice(&src[..((3 + src.len()) - 3)])
```
However, using the `hir` function is needed to prevent the suggestion causing errors when users use bitwise operations; and also this have already existed, for example: `verbose_bit_mask`. Thus, I think this is fine.
changelog: Expands `manual_memcpy` to lint ones with loop counters
Preserve raw strs for: format!(s) to s.to_string() lint
fixes#6142
clippy::useless_format will keep the source's string (after converting {{ and }} to { and }) when suggesting a change from format!() to .to_string() usage. Ie:
| let s = format!(r#""hello {{}}""#);
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `r#""hello {}""#.to_string()`
changelog: [`useless_format`]: preserve raw string literals when no arguments to `format!()` are provided.
New lint: Recommend using `ptr::eq` when possible
This is based almost entirely on the code available in the previous PR #4596. I merely updated the code to make it compile.
Fixes#3661.
- [ ] I'm not sure about the lint name, but it was the one used in the original PR.
- [X] Added passing UI tests (including committed `.stderr` file)
- [X] `cargo test` passes locally
- [X] Executed `cargo dev update_lints`
- [X] Added lint documentation
- [X] Run `cargo dev fmt`
---
changelog: none
clippy_lints: Do not warn against Box parameter in C FFI
changelog: [`boxed_local`]: don't lint in `extern fn` arguments
Fixes#5542.
When using C FFI, to handle pointers in parameters it is needed to
declare them as `Box` in its Rust-side signature. However, the current
linter warns against the usage of Box stating that "local variable
doesn't need to be boxed here".
This commit fixes it by ignoring functions whose Abi is C.
Downgrade string_lit_as_bytes to nursery
Between #1402 (regarding `to_owned`) and #4494 (regarding `impl Read`), as well as other confusion I've seen hit in my work codebase involving string_lit_as_bytes (`"...".as_bytes().into()`), I don't think this lint is at a quality to be enabled by default.
I would consider re-enabling this lint after it is updated to understand when the surrounding type information is sufficient to unsize `b"..."` to &\[u8\] without causing a type error.
As currently implemented, this lint is pushing people to write `&b"_"[..]` which is not an improvement over `"_".as_bytes()` as far as I am concerned.
---
changelog: Remove string_lit_as_bytes from default set of enabled lints
Fix unicode regexen with bytes::Regex
fixes#6005
The rationale for this is that since we wrote that lint, `bytes::Regex` was extended to be able to use unicode character classes.
---
changelog: [`invalid_regex`]: allow unicode character classes in bytes regex.
Fixes#5542.
When using C FFI, to handle pointers in parameters it is needed to
declare them as `Box` in its Rust-side signature. However, the current
linter warns against the usage of Box stating that "local variable
doesn't need to be boxed here".
This commit fixes it by ignoring functions whose Abi is Cdecl.
Downgrade rc_buffer to restriction
I think Arc\<Vec\<T\>\> and Arc\<String\> and similar are a totally reasonable data structure, as observed by others in the comments on [#6044](https://github.com/rust-lang/rust-clippy/pull/6044#event-3799579830) as well. Doing `Arc::make_mut(&mut self.vec).push(...)` or `Arc::make_mut(&mut self.string).push_str("...")` is a terrific and well performing copy-on-write pattern. Linting this with an enabled-by-default <kbd>performance</kbd> lint strikes me as an unacceptable false positive balance.
As of #6090 the documentation of this lint now contains:
> **Known problems:** This pattern can be desirable ...
which should indicate that we shouldn't be linting against correct, reasonable, well-performing patterns with an enabled-by-default lint.
Mentioning #6044, #6090.
r? `@yaahc,` who reviewed the lint.
---
changelog: Remove rc_buffer from default set of enabled lints
Fix LitKind's byte buffer to use refcounted slice
While working on adding a new lint for clippy (see https://github.com/rust-lang/rust-clippy/pull/6044) for avoiding shared ownership of "mutable buffer" types (such as using `Rc<Vec<T>>` instead of `Rc<[T]>`), I noticed a type exported from rustc_ast and used by clippy gets caught by the lint. This PR fixes the exported type.
This PR includes the actual change to clippy too, but I will open a PR directly against clippy for that part (although it will currently fail to build there).
unnecessary sort by: avoid dereferencing the suggested closure parameter
This change tries to simplify the solution for problematic cases but is less restrictive than #6006.
* We can't dereference shared references to non-Copy types, so the new suggestion does not do that. Note that this implies that the suggested closure parameter will be a reference.
* We can't take a reference to the closure parameter in the returned key, so we don't lint in those cases. This can happen either because the key borrows from the parameter (e.g. `|a| a.borrows()`), or because we suggest `|a| Reverse(a)`. If we did we would hit this error:
```
error: lifetime may not live long enough
--> /home/ebroto/src/ebroto-clippy/tests/ui/unnecessary_sort_by.fixed:19:25
|
19 | vec.sort_by_key(|b| Reverse(b));
| -- ^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
| ||
| |return type of closure is Reverse<&'2 isize>
| has type `&'1 isize`
error: aborting due to previous error
```
Note that Clippy does not currently have the (MIR-based) machinery necessary to check that what is borrowed is actually the closure parameter.
changelog: [`unnecessary_sort_by`]: avoid dereferencing the suggested closure parameter
Fixes#6001
Do not lint float fractions in `mistyped_literal_suffixes`
As suggested in https://github.com/rust-lang/rust-clippy/issues/4706#issuecomment-544797928, the fractional part is now ignored (the integer part is checked instead).
Fixes: #4706
changelog: `mistyped_literal_suffixes` no longer warns on the fractional part of a float (e.g. 713.23_64)
fix a false positive in two `interior_mutable_const` lints where a constant with enums gets linted
even if it uses a clearly unfrozen variant. Note that the code uses the MIR interpreter, which
the author of #3962 thought unlikely to be a solution. This might be over-engineering;
but, I think it's important to be able to work with the 'http' crate (#3825).
Lint for invisible Unicode characters other than ZWSP
This PR extends the existing `zero_width_space` lint to look for other invisible characters as well (in this case, `\\u{ad}` soft hyphen.
I feel like this lint is the logical place to add the check, but I also realize the lint name is not particularly flexible, but I also understand that it shouldn't be renamed for compatibility reasons.
Open questions:
- What other characters should trigger the lint?
- What should be done with the lint name?
- How to indicate the change in functionality?
Motivation behind this PR: https://github.com/rust-lang/rust/issues/77417 - I managed to shoot myself in the foot by an invisible character pasted into my test case.
changelog: rename [`zero_width_space`] to [`invisible_characters`] and add SHY and WJ to the list.
Don't emit a lint for the suggestion leading to errors in `needless_range_loop`
Fix#5945
changelog: Don't emit a lint for the suggestion leading to errors in `needless_range_loop`
New Lint: disallowed_method
Fixes https://github.com/rust-lang/rust-clippy/issues/6073
I added a `disallowed_method` lint that works similar to `blacklisted_name`, e.g allows config-defined disallowed method calls.
This lint allows advanced users to patch in undesired method calls for specific projects. It basically uses the DefId of method calls and matches it to parsed strings. Is there an alternative approach that could use more easily digestible configuration strings?
All tests pass as expected except for a linting error on `ui/redundant_pattern_matching_option`, which I am not sure how to resolve since I don't think I changed anything affecting it.
changelog: Add disallowed_method lint to warn on user-defined method calls
Fix FP in `print_stdout`
Fix#6041
This lint shouldn't be emitted in `build.rs` as `println!` and `print!` are used for the build script.
changelog: none
Allow a unique name to be assigned to dataflow graphviz output
Previously, if the same analysis were invoked multiple times in a single compilation session, the graphviz output for later runs would overwrite that of previous runs. Allow callers to add a unique identifier to each run so this can be avoided.
Revert: or_fun_call should lint calls to `const fn`s with no args
The changes in #5889 and #5984 were done under the incorrect assumption that a `const fn` with no args was guaranteed to be evaluated at compile time. A `const fn` is only guaranteed to be evaluated at compile time if it's inside a const context (the initializer of a `const` or a `static`).
See this [zulip conversation](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/Common.20misconception.3A.20.60const.20fn.60.20and.20its.20effect.20on.20codegen/near/208059113) for more details on this common misconception.
Given that none of the linted methods by `or_fun_call` can be called in const contexts, the lint should make no exceptions.
changelog: [`or_fun_call`] lints again calls to `const fn` with no args
Fix a FP in `explicit_counter_loop`
Fixes#4677 and #6074
Fix a false positive in `explicit_counter_loop` where the loop counter is used after incremented, adjust the test so that counters are incremented at the end of the loop and add the test for this false positive.
---
changelog: Fix a false positive in `explicit_counter_loop` where the loop counter is used after incremented
Add `rc_buffer` lint for checking Rc<String> and friends
Fixes#2623
This is a bit different from the original PR attempting to implement this type of lint. Rather than linting against converting into the unwanted types, this PR lints against declaring the unwanted type in a struct or function definition.
I'm reasonably happy with what I have here, although I used the fully qualified type names for the Path and OsString suggestions, and I'm not sure if I should have just used the short versions instead, even if they might not have been declared via use.
Also, I don't know if "buffer type" is the best way to put it or not. Alternatively I could call it a "growable type" or "growable buffer type", but I was thinking of PathBuf when I started making the lint.
changelog: Add `rc_buffer` lint
Fix a false positive in `explicit_counter_loop` where the loop counter is used after incremented,
adjust the test so that counters are incremented at the end of the loop
and add the test for this false positive.
Stabilize some Result methods as const
Stabilize the following methods of Result as const:
- `is_ok`
- `is_err`
- `as_ref`
A test is also included, analogous to the test for `const_option`.
These methods are currently const under the unstable feature `const_result` (tracking issue: #67520).
I believe these methods to be eligible for stabilization because of the stabilization of #49146 (Allow if and match in constants) and the trivial implementations, see also: [PR#75463](https://github.com/rust-lang/rust/pull/75463) and [PR#76135](https://github.com/rust-lang/rust/pull/76135).
Note: these methods are the only methods currently under the `const_result` feature, thus this PR results in the removal of the feature.
Related: #76225
* stop linting associated types and generic type parameters
* start linting ones in trait impls
whose corresponding definitions in the traits are generic
* remove the `is_copy` check
as presumably the only purpose of it is to allow
generics with `Copy` bounds as `Freeze` is internal
and generics are no longer linted
* remove the term 'copy' from the tests
as being `Copy` no longer have meaning