handle exponent without digits in `numeric_literal`
Fixes#10912
The numeric literal util module didn't check for exponents with no digits.
So:
384cf37612/clippy_utils/src/numeric_literal.rs (L163-L168)
`exponent` here would be the empty string, which passed the `!= "0"` check (when it shouldn't have, it should probably be treated as if the user wrote `E0`), then later fails when counting the digits and subtracting one (0 - 1 = overflow).
Also, interestingly I can't even write a test for this because exponents with no digits is some kind of error by itself and `cargo dev fmt` fails on it.
changelog: [`unreadable_literal`]: don't (debug) ICE on numeric literal with empty exponent
Fix `diverging_sub_expression` not checking body of block
Fixes#10776
This also adds a warning to the test `ui/never_loop.rs`, not sure if this is correct or not.
changelog: [`diverging_sub_expression`]: Fix false negatives with body of block
[`unnecessary_to_owned`]: check that the adjusted type matches target
Fixes#10033.
Before this change, the lint would assume that removing the `.to_string()` in `f(&x.to_string())` would be ok if x is of some type that implements `Deref<Target = str>` and `f` takes a `&str`.
This turns out to not actually be ok if the `to_string` call is some method that exists on `x` directly, which happens if it implements `Display`/`ToString` itself.
changelog: [`unnecessary_to_owned`]: only lint if the adjusted receiver type actually matches
Ignore more pointer types in `unnecessary_cast`
Spotted this because
e2c655b4c0/tests/ui/suspicious_to_owned.rs (L9-L10)
currently fails on `aarch64-unknown-linux-gnu` as `c_char` is `u8` there
The current implementation checks for `as alias`, `as _`. This adds things like
- `as *const alias`
- `as *const cfg_dependant`
- `as *const _`
changelog: none
[`redundant_closure`]: special case inclusive ranges
Fixes#10684.
`x..=y` ranges need a bit of special handling in this lint because it desugars to a call to the lang item `RangeInclusiveNew`, where the callee span would be the same as the range expression itself, so the suggestion looked a bit weird. It now correctly suggests `RangeInclusive::new`.
changelog: [`redundant_closure`]: special case `RangeInclusive`
Adds new lint `arc_with_non_send_or_sync`
Fixes#653
Adds a new lint to check for uses of non-Send/Sync types within Arc.
```
changelog: [`arc_with_non_send_sync`]: Added a lint to detect uses of non-Send/Sync types within Arc.
```
[`useless_vec`]: lint `vec!` invocations when a slice or an array would do
First off, sorry for that large diff in tests. *A lot* of tests seem to trigger the lint with this new change, so I decided to `#![allow()]` the lint in the affected tests to make reviewing this easier, and also split the commits up so that the first commit is the actual logic of the lint and the second commit contains all the test changes. The stuff that changed in the tests is mostly just line numbers now. So, as large as the diff looks, it's not actually that bad. 😅
I manually went through all of these to find out about edge cases and decided to put them in `tests/ui/vec.rs`.
For more context, I wrote about the idea of this PR here: https://github.com/rust-lang/rust-clippy/issues/2262#issuecomment-1579155257 (that explains the logic)
Basically, it now also considers the case where a `Vec` is put in a local variable and the user only ever does things with it that one could also do with a slice or an array. This should catch a lot more cases, and (at least from looking at the tests) it does.
changelog: [`useless_vec`]: lint `vec!` invocations when a slice or an array would do (also considering local variables now)
`suspicious_else_formatting`: Don't warn if there is a comment between else and curly bracket
This PR fixes https://github.com/rust-lang/rust-clippy/issues/10273
The idea is that if the only thing after `else` and before `{` is a comment, we will not warn because, probably, the line break was "made" by rustfmt.
changelog: [`suspicious_else_formatting`]: Don't warn if the only thing between `else` and curly bracket is a comment
consider autoderef through user-defined `Deref` in `eager_or_lazy`
Fixes#10462
This PR handles autoderef in the `eager_or_lazy` util module and stops suggesting to change lazy to eager if autoderef in an expression goes through user defined `Deref` impls, e.g.
```rs
struct S;
impl Deref for S {
type Target = ();
fn deref(&self) -> &Self::Target { &() }
}
let _ = Some(()).as_ref().unwrap_or_else(|| &S); // autoderef `&S` -> `&()`
```
changelog: [`unnecessary_lazy_evaluations`]: don't suggest changing lazy evaluation to eager if autoderef goes through user-defined `Deref`
r? `@xFrednet` (because of the earlier review in #10864, might help for context here)
[`let_with_type_underscore`]: Don't emit on locals from procedural macros
closes#10498
changelog: [`let_with_type_underscore`]: Don't emit on locals from procedural macros
make cast_possible_wrap work correctly for 16 bit {u,i}size
These changes make `cast_possible_wrap` aware of the different pointer widths and fixes the implementation to print the correct pointer widths.
Fixes#9337
changelog: `cast_possible_wrap` does not lint on `u8 as isize` or `usize as i8`, since these can never wrap.
`cast_possible_wrap` now properly considers 16 bit pointer size and prints the correct bit widths.
Add redundant type annotations lint
Hello, I'm trying to add the `redundat_type_annotations` lint.
It's still WIP but I'd like to start gathering some feedbacks to be sure that I'm not doing things 100% wrong :)
Right now it still misses lints like:
- [x] `let foo: u32 = 5_u32`,
- [x] `let foo: String = STest2::func()`
- [x] `let foo: String = self.func()` (`MethodCall`)
- [x] refs
- [ ] Generics
I've some problems regarding the second example above, in the `init` part of the `Local` I have:
```rust
init: Some(
Expr {
hir_id: HirId(DefId(0:24 ~ playground[e1bd]::main).58),
kind: Call(
Expr {
hir_id: HirId(DefId(0:24 ~ playground[e1bd]::main).59),
kind: Path(
TypeRelative(
Ty {
hir_id: HirId(DefId(0:24 ~ playground[e1bd]::main).61),
kind: Path(
Resolved(
None,
Path {
span: src/main.rs:77:21: 77:27 (#0),
res: Def(
Struct,
DefId(0:17 ~ playground[e1bd]::STest2),
),
segments: [
PathSegment {
ident: STest2#0,
hir_id: HirId(DefId(0:24 ~ playground[e1bd]::main).60),
res: Def(
Struct,
DefId(0:17 ~ playground[e1bd]::STest2),
),
args: None,
infer_args: true,
},
],
},
),
),
span: src/main.rs:77:21: 77:27 (#0),
},
PathSegment {
ident: get_numb#0,
hir_id: HirId(DefId(0:24 ~ playground[e1bd]::main).62),
res: Err,
args: None,
infer_args: true,
},
),
),
span: src/main.rs:77:21: 77:37 (#0),
},
[],
),
span: src/main.rs:77:21: 77:39 (#0),
},
),
```
And I'm not sure how to get the return type of the function `STest2::func()` since the resolved path `DefId` points to the struct itself and not the function. Do you have any idea on how I could get this information in this case?
Thanks!
changelog: changelog: [`redundant_type_annotations`]: New lint to warn on redundant type annotations
fixes#9155
[`unnecessary_lazy_eval`]: don't lint on types with deref impl
Fixes#10437.
This PR changes clippy's util module `eager_or_lazy` to also consider deref expressions whose type has a non-builtin deref impl and not suggest replacing it as that might have observable side effects.
A prominent example might be the `lazy_static` macro, which creates a newtype with a `Deref` impl that you need to go through to get access to the inner value. Going from lazy to eager can make a difference there.
changelog: [`unnecessary_lazy_eval`]: don't lint on types with non-builtin deref impl
Add lints for disallowing usage of `to_xx_bytes` and `from_xx_bytes`
Adds `host_endian_bytes`, `little_endian_bytes` and `big_endian_bytes`
Closes#10765
v - not sure what to put here since this adds 3 lints
changelog: Add `host_endian_bytes`, `little_endian_bytes` and `big_endian_bytes` lints
[`allow_attributes`, `allow_attributes_without_reason`]: Ignore attributes from procedural macros
I use `lint_reasons` and `clap`, which is a bit overzealous when it comes to preventing warnings in its macros; it uses a ton of allow attributes on everything to, as ironic as it is, silence warnings. These two now ignore anything from procedural macros.
PS, I think `allow_attributes.rs` should be merged with `attrs.rs` in the future.
fixes#10377
changelog: [`allow_attributes`, `allow_attributes_without_reason`]: Ignore attributes from procedural macros
Ignore fix for `from_over_into` if the target type contains a `Self` reference
Fixes https://github.com/rust-lang/rust-clippy/issues/10838.
This is my first time contributing here, and the fix is kind of ugly.
I've worked a bit with `quote` and was trying to figure out a way to replace the type in a better way than just a raw string-replace but couldn't quite figure out how to.
The only thing really required to fix this, is to replace all `Self` references with the type stated in the `from` variable, this isn't entirely simple to do with raw strings without creating a mess though.
We need to find and replace all `Self`'s in a variable with `from` but there could be an arbitrary amount, in a lot of different positions. As well as some type that contains the name self, like `SelfVarSelf` which shouldn't be replaced.
The strategy is essentially, if `"Self"` is surrounded on both sides by something that isn't alphanumeric, then we're golden, then trying to make that reasonably efficient.
I would not be offended if the solution is too messy to accept!
changelog: [from_over_into]: Replace Self with the indicated variable in suggestion and fix.
new lint: `explicit_into_iter_fn_arg`
Closes#10743.
This adds a lint that looks for `.into_iter()` calls in a call expression to a function that already expects an `IntoIterator`. In those cases, explicitly calling `.into_iter()` is unnecessary.
There were a few instances of this in clippy itself so I fixed those as well in this PR.
changelog: new lint [`explicit_into_iter_fn_arg`]
manual_let_else: support struct patterns
This adds upon the improvements of #10797 and:
* Only prints `()` around `Or` patterns at the top level (fixing a regression of #10797)
* Supports multi-binding patterns: `let (u, v) = if let (Some(u_i), Ok(v_i)) = ex { (u_i, v_i) } else ...`
* Traverses through tuple patterns: `let v = if let (Some(v), None) = ex { v } else ...`
* Supports struct patterns: `let v = if let S { v, w, } = ex { (v, w) } else ...`
```
changelog: [`manual_let_else`]: improve pattern printing to support struct patterns
```
fixes#10708fixes#10424
[`ptr_cast_constness`]: Only lint on casts which don't change type
fixes#10874
changelog: [`ptr_cast_constness`]: Only lint on casts which don't change type
Emit `unnecessary_cast` on raw pointers as well
Supersedes(?) #10782, since this and #10567 will cover the original issue.
Does not lint on type aliases or inferred types.
changelog: [`unnecessary_cast`]: Also emit on casts between raw pointers with the same type and constness
add checking for cfg(features = ...)
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: [`maybe_misused_cfg`]: check if `#[cfg(feature = "...")]` misused as `#[cfg(features = "...")]`
I've found that there is no indication when `#[cfg(features = "...")]` is used incorrectly, which can easily make mistakes hard to spot. When I searched for this code on github, I also found many misuse cases([link](https://github.com/search?q=%23%5Bcfg%28features+language%3ARust&type=code)).
PS: This clippy name is just a temporary name, it can be replaced with a better name.
move some strings into consts, more tests
s/missing_field_in_debug/missing_fields_in_debug
dont trigger in macro expansions
make dogfood tests happy
minor cleanups
replace HashSet with FxHashSet
replace match_def_path with match_type
if_chain -> let chains, fix markdown, allow newtype pattern
fmt
consider string literal in `.field()` calls as used
don't intern defined symbol, remove mentions of 'debug_tuple'
special-case PD, account for field access through `Deref`
Improve pattern printing for manual_let_else
* Address a formatting issue pointed out in https://github.com/rust-lang/rust-clippy/pull/10175/files#r1137091002
* Replace variables inside | patterns in the if let: `let v = if let V::A(v) | V::B(v) = v { v } else ...`
* Support nested patterns: `let v = if let Ok(Ok(Ok(v))) = v { v } else ...`
* Support tuple structs with more than one arg: `let v = V::W(v, _) = v { v } else ...`; note that more than one *capture* is still not supported, so it bails for `let (v, w) = if let E::F(vi, wi) = x { (vi, wi)}`
* Correctly handle .. in tuple struct patterns: `let v = V::X(v, ..) = v { v } else ...`
- \[ ] Followed [lint naming conventions][lint_naming]
- \[x] Added passing UI tests (including committed `.stderr` file)
- \[x] `cargo test` passes locally
- \[ ] Executed `cargo dev update_lints`
- \[ ] Added lint documentation
- \[x] Run `cargo dev fmt`
[lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
---
changelog: [`manual_let_else`]: improve variable name in suggestions
Closes#10431 as this PR is adding a test for the `mut` case.
Ignore `#[cfg]`'d out code in `needless_else`
changelog: none (same release as #10810)
`#[cfg]` making things fun once more
This lead me to think about macro calls that expand to nothing as well, but apparently they produce an empty stmt in the AST so are already handled, added a test for that
r? `@llogiq`
[`default_constructed_unit_structs`]: do not lint on type alias paths
Fixes#10755.
Type aliases cannot be used as a constructor, so this lint should not trigger in those cases.
I also changed `clippy_utils::is_ty_alias` to also consider associated types since [they kinda are type aliases too](48ec50ae39/compiler/rustc_resolve/src/late/diagnostics.rs (L1520)).
changelog: [`default_constructed_unit_structs`]: do not lint on type alias paths
[`unused_async`]: do not consider `await` in nested `async` blocks as used
Fixes#10800.
This PR makes sure that `await` expressions inside of inner `async` blocks don't prevent the lint from triggering.
For example
```rs
async fn foo() {
async {
std::future::ready(()).await;
}
}
```
Even though there *is* a `.await` expression in this function, it's contained in an async block, which means that the enclosing function doesn't need to be `async` too.
changelog: [`unused_async`]: do not consider `await` in nested `async` blocks as used
Add new lint `ptr_cast_constness`
This adds a new lint which functions as the opposite side of the coin to `ptr_as_ptr`. Rather than linting only as casts that don't change constness, this lints only constness; suggesting to use `pointer::cast_const` or `pointer::cast_mut` instead.
changelog: new lint [`ptr_cast_constness`]
needless_else: new lint to check for empty `else` clauses
Empty `else` clauses are useless. They happen in the wild and are not linted yet: https://github.com/uutils/coreutils/pull/4880/files
`else` clauses containing or preceded by comments are not linted as the comments might be important.
changelog: [`needless_else`]: new lint
Fix missing block for unsafe code
If a block is declared as unsafe, it needs an extra layer of curly braces around it.
Fixes#10808
This code adds handling for `UnsafeSource::UserProvided` block, i.e. `unsafe { ... }`. Note that we do not handle the `UnsafeSource::CompilerGenerated` as it seems to not be possible to generate that with the user code (?), or at least doesn't seem to be needed to be handled explicitly.
There is an issue with this code: it does not add an extra indentation for the unsafe blocks. I think this is a relatively minor concern for such an edge case, and should probably be done by a separate PR (fixing compile bug is more important than getting styling perfect especially when `rustfmt` will fix it anyway)
```rust
// original code
unsafe {
...
}
// code that is now generated by this PR
{ unsafe {
...
} }
// what we would ideally like to get
{
unsafe {
...
}
}
```
changelog: [`single_match`](https://rust-lang.github.io/rust-clippy/master/#single_match): Fix suggestion for `unsafe` blocks
[`large_stack_arrays`]: check array initializer expressions
Fixes#10741.
Prior to this PR, the lint only checked array repeat expressions (ie. `[T; n]`). Now it also checks array initializer expressions.
changelog: [`large_stack_arrays`]: check array initializer expressions
These unit tests generate non-compilable code. I did NOT `bless` them on purpose because the stderr output is not good.
I'm surprised we don't auto-compile the suggestions here - is this something that can be easily enabled?
See #10808
Enhance `needless_collect`: lint in method/function arguments that take an `IntoIterator`
Updates `needless_collect` to also lint `collect` calls in method/function arguments that take an `IntoIterator` (for example `Extend::extend`). Every `Iterator` trivially implements `IntoIterator` and collecting it only causes an unnecessary allocation.
---
changelog: Enhancement: [`needless_collect`]: Now also detects function arguments, taking a generic `IntoIterator`
[#10777](https://github.com/rust-lang/rust-clippy/pull/10777)
<!-- changelog_checked -->
fixes#10762
* Don't consider expansions of different macros to be the same, even if they expand to the same tokens
* Don't consider `cfg!` expansions to be equal if they check different configs.
* Replace variables inside | patterns in the if let: let v = if let V::A(v) | V::B(v) = v { v } else ...
* Support nested patterns: let v = if let Ok(Ok(Ok(v))) = v { v } else ...
* Support tuple structs with more than one arg: let v = V::W(v, _) = v { v } else ...
* Correctly handle .. in tuple struct patterns: let v = V::X(v, ..) = v { v } else ...
Rename `integer_arithmetic`
The lack of official feedback in #10200 made me give up on pursuing the matter but after yet another use-case that is not handled by `integer_arithmetic` (#10615), I think it is worth trying again.
---
changelog: Move/Deprecation: Rename `integer_arithmetic` to `arithmetic_side_effects`
[#10674](https://github.com/rust-lang/rust-clippy/pull/10674)
<!-- changelog_checked -->
don't remove `dbg!` in arbitrary expressions
Fixes#9914
The `dbg_macro` lint replaces empty `dbg!` invocations with the empty string in its suggestion, which is not always valid code in certain contexts (e.g. `let _ = dbg!();` becomes `let _ = ;`). This PR changes it to `()`, which should always be valid where `dbg!()` is valid (`dbg!()` with no arguments evaluates to `()`).
It also special-cases "standalone" `dbg!();` expression statements, where it will suggest removing the whole statement entirely like it did before.
changelog: [`dbg_macro`]: don't remove `dbg!()` in arbitrary expressions as it sometimes results in syntax errors
fix [`invalid_regex`] not recognizing new syntax introduced after regex-1.8.0
fixes: #10680
---
changelog: fix [`invalid_regex`] not recognizing new syntax introduced after regex-1.8.0
bump up `regex-syntax` dependency version to 0.7.0