Commit graph

5707 commits

Author SHA1 Message Date
tamaron
8d8588941e fix 2022-05-07 19:50:34 +09:00
Preston From
41c7e4d382 Lint for significant drops who may have surprising lifetimes #1
author Preston From <prestonfrom@gmail.com> 1645164142 -0600
committer Preston From <prestonfrom@gmail.com> 1650005351 -0600
2022-05-06 21:48:17 -06:00
Guillaume Gomez
13e8ace73c Rollup merge of #96557 - nbdd0121:const, r=oli-obk
Allow inline consts to reference generic params

Tracking issue: #76001

The RFC says that inline consts cannot reference to generic parameters (for now), same as array length expressions. And expresses that it's desirable for it to reference in-scope generics, when array length expressions gain that feature as well.

However it is possible to implement this for inline consts before doing this for all anon consts, because inline consts are only used as values and they won't be used in the type system. So we can have:
```rust
fn foo<T>() {
    let x = [4i32; std::mem::size_of::<T>()];   // NOT ALLOWED (for now)
    let x = const { std::mem::size_of::<T>() }; // ALLOWED with this PR!
    let x = [4i32; const { std::mem::size_of::<T>() }];   // NOT ALLOWED (for now)
}
```

This would make inline consts super useful for compile-time checks and assertions:
```rust
fn assert_zst<T>() {
    const { assert!(std::mem::size_of::<T>() == 0) };
}
```

This would create an error during monomorphization when `assert_zst` is instantiated with non-ZST `T`s. A error during mono might sound scary, but this is exactly what a "desugared" inline const would do:
```rust
fn assert_zst<T>() {
    struct F<T>(T);
    impl<T> F<T> {
        const V: () = assert!(std::mem::size_of::<T>() == 0);
    }
    let _ = F::<T>::V;
}
```

It should also be noted that the current inline const implementation can already reference the type params via type inference, so this resolver-level restriction is not any useful either:
```rust
fn foo<T>() -> usize {
    let (_, size): (PhantomData<T>, usize) = const {
        const fn my_size_of<T>() -> (PhantomData<T>, usize) {
            (PhantomData, std::mem::size_of::<T>())
        }
        my_size_of()
    };
    size
}
```

```@rustbot``` label: F-inline_const
2022-05-06 20:05:37 +02:00
tamaron
5d0ca74c75 Resolved conflicts 2022-05-07 00:05:45 +09:00
Samuel E. Moelius III
91a822c162 Address unnecessary_to_owned false positive 2022-05-06 09:31:27 -04:00
bors
1594e986ea Auto merge of #8763 - arieluy:manual_range_contains, r=xFrednet
Support negative ints in manual_range_contains

fixes: #8721
changelog: Fixes issue where ranges containing ints with different signs would be
incorrect due to comparing as unsigned.
2022-05-06 11:33:47 +00:00
bors
5dad51736c Auto merge of #8778 - sunfishcode:main, r=giraffate
Fix `cast_lossless` to avoid warning on `usize` to `f64` conversion.

Previously, the `cast_lossless` lint would issue a warning on code that
converted a `usize` value to `f64`, on 32-bit targets.

`usize` to `f64` is a lossless cast on 32-bit targets, however there is
no corresponding `f64::from` that takes a `usize`, so `cast_lossless`'s
suggested replacement does not compile.

This PR disables the lint in the case of casting from `usize` or `isize`.

Fixes #3689.

changelog: [`cast_lossless`] no longer gives wrong suggestion on usize,isize->f64
2022-05-06 00:26:18 +00:00
flip1995
ed8458f67a (Partially) Revert "HACK: Move buggy lints to nursery"
This reverts commit bb01aca86f.

Partial: Keep regression tests
2022-05-05 15:20:07 +01:00
flip1995
7cd86aa1be Merge commit '7c21f91b15b7604f818565646b686d90f99d1baf' into clippyup 2022-05-05 15:12:52 +01:00
Gary Guo
f0c2ac8a29 Bless clippy error msg 2022-05-05 14:27:11 +01:00
flip1995
006282964f
Fix ICE in EarlyAttribtues lints 2022-05-05 14:10:06 +01:00
flip1995
bb01aca86f
HACK: Move buggy lints to nursery
Those lints are trait_duplication_in_bounds and
type_repetition_in_bounds. I don't think those can be fixed on the
Clippy side alone, but need changes in the compiler. So let's move them
to nursery to get the sync through and then fix them on the rustc side.

Also adds a regression test that has to be fixed before they can be
moved back to pedantic.
2022-05-05 13:32:31 +01:00
flip1995
3b0c78d283
Merge remote-tracking branch 'upstream/master' into rustup 2022-05-05 13:32:06 +01:00
Alex Macleod
ee8fae3f5d identity_op: add parenthesis to suggestions where required 2022-05-04 21:19:43 +01:00
bors
c7a705a842 Auto merge of #8575 - FoseFx:trim_split_whitespace2, r=flip1995
add `trim_split_whitespace`

Closes #8521

changelog: [`trim_split_whitespace`]
2022-05-04 13:31:19 +00:00
bors
751fd0d735 Auto merge of #8780 - Alexendoo:init-numbered-field-alias, r=flip1995
Ignore type aliases in `init_numbered_fields`

changelog: Ignore type aliases in [`init_numbered_fields`]

Fixes #8638
2022-05-04 13:17:35 +00:00
Max Baumann
fea177fafe
add trim_split_whitespace 2022-05-04 15:04:05 +02:00
Alex Macleod
d53293d52a Ignore type aliases in init_numbered_fields 2022-05-03 14:28:27 +01:00
binggh
7017eb102d cargo dev bless 2022-05-03 17:51:34 +08:00
bors
0ceacbe185 Auto merge of #8730 - tamaroning:fix8724, r=Alexendoo
[FP] identity_op in front of if

fix #8724

changelog: FP: [`identity_op`]: is now allowed in front of if statements, blocks and other expressions where the suggestion would be invalid.

Resolved simular problems with blocks, mathces, and loops.
identity_op always does NOT suggest reducing `0 + if b { 1 } else { 2 } + 3` into  `if b { 1 } else { 2 } + 3` even in the case that the expression is in `f(expr)` or `let x = expr;` for now.
2022-05-03 07:05:51 +00:00
Dan Gohman
6ff77b96f1 Fix cast_lossless to avoid warning on usize to f64 conversion.
Previously, the `cast_lossless` lint would issue a warning on code that
converted a `usize` value to `f64`, on 32-bit targets.

`usize` to `f64` is a lossless cast on 32-bit targets, however there is
no corresponding `f64::from` that takes a `usize`, so `cast_lossless`'s
suggested replacement does not compile.

This PR disables the lint in the case of casting from `usize` or `isize`.

Fixes #3689.

changelog: [`cast_lossless`] no longer gives wrong suggestion on usize->f64
2022-05-02 13:52:13 -07:00
tamaron
6ad810f94e improve identity_op
fix

Update identity_op.rs

ok

update without_loop_counters test

chore

fix

chore

remove visitor and leftmost

fix

add document
2022-05-01 11:03:27 +09:00
bors
32fe4762bf Auto merge of #8625 - Jarcho:rename_lint, r=xFrednet
Add `cargo dev rename_lint`

fixes #7799

changelog: None
2022-04-30 17:22:34 +00:00
bors
ec46992008 Auto merge of #8720 - asquared31415:ptr-cast-ice-fix, r=Alexendoo,xFrednet
fix ICE in `cast_slice_different_sizes`

fixes #8708

changelog: fixes an ICE introduced in #8445
2022-04-30 16:51:01 +00:00
Camille GILLOT
e46c782662 Bless tests. 2022-04-30 13:55:17 +02:00
Ariel Uy
d10296910f Support negative ints in manual_range_contains
Fixes issue where ranges containing ints with different signs would be
incorrect due to comparing as unsigned.
2022-04-29 19:11:00 -07:00
bors
d5c62fd399 Auto merge of #8431 - dswij:8416, r=xFrednet
`redundant_closure` fix FP on coerced closure

Closes https://github.com/rust-lang/rust-clippy/issues/8416,
Closes https://github.com/rust-lang/rust-clippy/issues/7812
Closes https://github.com/rust-lang/rust-clippy/issues/8091

~~Seems like this is fixed in #817 and regressed.~~

Ignore coerced closure false positives, but this will lead to some false negatives on resolvable generics. IMO, this is still an overall improvement

changelog: [`redundant_closure`] ignores coerced closure
2022-04-27 09:47:08 +00:00
bors
18a1831377 Auto merge of #8743 - Alexendoo:useless-attribute-redundant-pub-crate, r=llogiq
ignore `redundant_pub_crate` in `useless_attribute`

changelog: [`useless_attribute`] no longer lints [`redundant_pub_crate`]

As mentioned in https://github.com/rust-lang/rust-clippy/issues/8732#issuecomment-1106489634

> And it turns out I can't even explicitly allow it at the usage site, because then `clippy::useless_attribute` fires (which would also be a FP?), which is deny-by-default.
>
> Though it does work if I then allow `clippy::useless_attribute`. 😂
>
> ```rust
> #[allow(clippy::useless_attribute)]
> #[allow(clippy::redundant_pub_crate)]
> pub(crate) use bit;
> ```
>
> The originally-reported warning now no longer occurs.
2022-04-27 05:43:13 +00:00
dswij
33bf9e9a54 redundant_closure ignore coerced closure 2022-04-27 13:05:01 +08:00
Jason Newcomb
948af01633 Don't lint vec_init_then_push when further extended 2022-04-27 00:38:39 -04:00
bors
95396f61bc Auto merge of #8617 - Alexendoo:relax-needless-late-init, r=giraffate
`needless_late_init`: ignore `if let`, `let mut` and significant drops

No longer lints `if let`, personal taste on this one is pretty split, so it probably shouldn't be warning by default. Fixes #8613

```rust
let x = if let Some(n) = y {
    n
} else {
    1
}
```

No longer lints `let mut`, things like the following are not uncommon and look fine as they are

b169c16d86/src/sixty_four.rs (L88-L93)

Avoids changing the drop order in an observable way, where the type of `x` has a drop with side effects and something between `x` and the first use also does, e.g.

48cc6cb791/tests/test_api.rs (L159-L167)

The implementation of `type_needs_ordered_drop_inner` was changed a bit, it now uses `Ty::has_significant_drop` and reordered the ifs to check diagnostic name before checking the implicit drop impl

changelog: [`needless_late_init`]: No longer lints `if let` statements, `let mut` bindings and no longer significantly changes drop order
2022-04-27 00:11:17 +00:00
Alex Macleod
1d1fecff0f needless_late_init: ignore if let, let mut and significant drops 2022-04-26 13:16:54 +01:00
bors
94623ee882 Auto merge of #8737 - smoelius:extra-impl-lifetimes, r=giraffate
Extend `extra_unused_lifetimes` to handle impl lifetimes

Fixes #6437 (cc: `@carols10cents)`

changelog: fix #6437
2022-04-26 00:06:53 +00:00
bors
760f293d79 Auto merge of #8727 - Serial-ATA:lint-large-includes, r=xFrednet
Add `large_include_file` lint

changelog: Add [`large_include_file`] lint
closes #7005
2022-04-25 17:29:27 +00:00
Samuel E. Moelius III
e6fa163fad Fix false positives 2022-04-25 05:20:08 -04:00
bors
388e6b7854 Auto merge of #8742 - goth-turtle:mistyped-literal-suffix, r=llogiq
mistyped_literal_suffix: improve integer suggestions, avoid wrong float suggestions

This PR fixes 2 things:
- The known problem that integer types are always suggested as signed, by suggesting an unsigned suffix for literals that wouldnt fit in the signed type, and ignores any literals too big for the corresponding unsigned type too.
- The lint would only look at the integer part of any floating point literals without an exponent, this causing #6129. This just ignores those literals.

Examples:
```rust
let _ = 2_32; // still 2_i32
let _ = 234_8; // would now suggest 234_u8

// these are now ignored
let _ = 500_8;
let _ = 123_32.123;
```

changelog: suggest correct integer types in [`mistyped_literal_suffix`], ignore float literals without an exponent
fixes #6129
2022-04-24 20:16:40 +00:00
Serial
a85dc87c4c Add large_include_file lint 2022-04-24 10:08:31 -04:00
goth-turtle
b4a50e9ee5 mistyped_literal_suffixes: ignore floats without exponent
Previously this lint would only look at the integer part of floating
point literals without an exponent, giving wrong suggestions like:

```
  |
8 |     let _ = 123_32.123;
  |             ^^^^^^^^^^ help: did you mean to write: `123.123_f32`
  |
```

Instead, it now ignores these literals.
Fixes #6129
2022-04-24 15:28:36 +02:00
goth-turtle
f290249461 mistyped_literal_suffixes: improve suggestions for integer types
Instead of just always suggesting signed suffixes regardless of size
of the value, it now suggests an unsigned suffix when the value wouldn't
fit into the corresponding signed type, and ignores the literal entirely
if it is too big for the unsigned type as well.
2022-04-24 15:28:36 +02:00
Jason Newcomb
b3de32ba3c Add rename_lint command 2022-04-24 09:15:26 -04:00
bors
6aa3684431 Auto merge of #8738 - tamaroning:fix_wrong_self_convention, r=xFrednet
wrong_self_convention allows `is_*` to take `&mut self`

fix #8480 and #8513
Allowing `is_*` to take `&self` or none is too restrictive.

changelog: FPs: [`wrong_self_convention`] now allows `&mut self` and no self as arguments for `is_*` methods
2022-04-24 12:40:15 +00:00
asquared31415
af9dfa3692 fix ICE by using a type to return the info we want and also fix some bugs in displaying an extra mut when a TypeAndMut was wrong 2022-04-23 13:07:13 -04:00
tamaron
51db157fb4 fix 2022-04-23 22:45:26 +09:00
Alex Macleod
0c164bbfdb ignore redundant_pub_crate in useless_attribute 2022-04-23 12:23:18 +01:00
Samuel E. Moelius III
b35c04f7dc Extend extra_unused_lifetimes to handle impl lifetimes 2022-04-22 20:05:18 -04:00
Serial
f20e890a4b Add macro export exemption to redundant_pub_crate 2022-04-22 18:09:14 -04:00
bors
cef882cc9d Auto merge of #8731 - Alexendoo:dogfood-allow-unknown-lints, r=xFrednet
dogfood: allow unknown lints when not running with `internal` feature

changelog: none

https://rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/unknown.20lint.20in.20test.20dogfood_clippy

It's only a warning so this wasn't causing the test to fail, but if you had another error somewhere or used `--nocapture` the extra warnings would be shown
2022-04-22 17:11:53 +00:00
Alex Macleod
a96bc7af12 dogfood: allow unknown lints when not running with internal feature 2022-04-22 13:15:11 +01:00
bors
ed22428b72 Auto merge of #8717 - Alexendoo:manual-split-once-manual-iter, r=dswij,xFrednet
`manual_split_once`: lint manual iteration of `SplitN`

changelog: `manual_split_once`: lint manual iteration of `SplitN`

Now lints:

```rust
let mut iter = "a.b.c".splitn(2, '.');
let first = iter.next().unwrap();
let second = iter.next().unwrap();

let mut iter = "a.b.c".splitn(2, '.');
let first = iter.next()?;
let second = iter.next()?;

let mut iter = "a.b.c".rsplitn(2, '.');
let first = iter.next().unwrap();
let second = iter.next().unwrap();

let mut iter = "a.b.c".rsplitn(2, '.');
let first = iter.next()?;
let second = iter.next()?;
```

It suggests (minus leftover whitespace):

```rust
let (first, second) = "a.b.c".split_once('.').unwrap();

let (first, second) = "a.b.c".split_once('.')?;

let (second, first) = "a.b.c".rsplit_once('.').unwrap();

let (second, first) = "a.b.c".rsplit_once('.')?;
```

Currently only lints if the statements are next to each other, as detecting the various kinds of shadowing was tricky, so the following won't lint

```rust
let mut iter = "a.b.c".splitn(2, '.');
let something_else = 1;
let first = iter.next()?;
let second = iter.next()?;
```
2022-04-22 09:57:00 +00:00
Serial
14667d1474 Fix missing whitespace in collapsible_else_if suggestion 2022-04-21 13:45:40 -04:00
Alex Macleod
4424aa444c manual_split_once: lint manual iteration of SplitN 2022-04-21 18:33:54 +01:00
Gryffon Bellish
8de3fb159d
Add empty_drop lint 2022-04-21 10:03:01 +02:00
bors
4c25880f0c Auto merge of #8716 - binggh:stable-sort-message-update, r=giraffate
Less authoritative stable_sort_primitive message

fixes #8241

Hey all - first contribution here so I'm deciding to start with something small.

Updated the linked message to be less authoritative as well as moved the lint grouping from `perf` to `pedantic` as suggested by `@camsteffen` under the issue.

changelog: [`stable_sort_primitive`]: emit less authoritative message and move to `pedantic`
2022-04-21 00:27:13 +00:00
bors
f99ad82f9e Auto merge of #8700 - youknowone:needless_match-false-positive, r=xFrednet
Fix needless_match false positive for if-let when the else block doesn't match to given expr

<!--

Thank you for making Clippy better!

We're collecting our changelog from pull request descriptions.
If your PR only includes internal changes, you can just write
`changelog: none`. Otherwise, please write a short comment
explaining your change. Also, it's helpful for us that
the lint name is put into brackets `[]` and backticks `` ` ` ``,
e.g. ``[`lint_name`]``.

If your PR fixes an issue, you can add "fixes #issue_number" into this
PR description. This way the issue will be automatically closed when
your PR is merged.

If you added a new lint, here's a checklist for things that will be
checked during review or continuous integration.

- \[ ] 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`

[lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints

Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.

Delete this line and everything above before opening your PR.

--->

fix #8695

*Please write a short comment explaining your change (or "none" for internal only changes)*

changelog: Fixed ``[`needless_match`]`` false positive when else block expression differs.
2022-04-20 17:16:39 +00:00
bors
e17b97c8e0 Auto merge of #8711 - kyoto7250:new-lint-bytes-count-to-len, r=giraffate
Take over: New lint bytes count to len

take over #8375
close #8083

This PR adds new lint about  considering replacing `.bytes().count()` with `.len()`.

Thank you in advance.

---

r! `@Manishearth`

changelog: adds new lint [`bytes_count_to_len`] to consider replacing `.bytes().count()` with `.len()`
2022-04-19 12:44:07 +00:00
asquared31415
c922bb9443 fix ICE 2022-04-18 22:19:34 -04:00
kyoto7250
f19387d237 add checking type
adding test patterns

cargo dev bless

fix comment

add ;

delete :

fix suggestion code

and update stderr in tests.

use match_def_path when checking method name
2022-04-19 10:48:12 +09:00
Chase Ruskin
df1ec91d95 adds lint logic and test for bytes_count_to_len
formats code with

fixes single match clippy error to replace with if let

swaps ident.name.as_str to ident.name == sym for count fn
2022-04-19 10:48:10 +09:00
bors
cbdf17c884 Auto merge of #8707 - OneSignal:await-invalid-types, r=llogiq
Add `await_holding_invalid_type` lint

changelog: [`await_holding_invalid_type`]

This lint allows users to create a denylist of types which are not allowed to be
held across await points. This is essentially a re-implementation of the
language-level [`must_not_suspend`
lint](https://github.com/rust-lang/rust/issues/83310). That lint has a lot of
work still to be done before it will reach Rust stable, and in the meantime
there are a lot of types which can trip up developers if they are used
improperly.

I originally implemented this specifically for `tracing::span::Entered`, until I discovered #8434 and read the commentary on that PR. Given this implementation is fully user configurable, doesn't tie clippy to any one particular crate, and introduces no additional dependencies, it seems more appropriate.
2022-04-18 18:36:50 +00:00
Lily Mara
7e26edce65 fixup! Add await_holding_invalid_type lint 2022-04-18 11:16:35 -07:00
bing
7a4d07105f Less authoritative stable_sort_primitive message 2022-04-18 14:42:24 +08:00
Jeong YunWon
b94e24e95f Fix needless_match false positive for if-let
when the else block doesn't match to given expr
2022-04-18 14:33:13 +09:00
bors
e5ebece910 Auto merge of #8665 - InfRandomness:option_take_on_temporary, r=llogiq
Introduce needless_option_take lint

- \[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`

Fixes #8618

changelog: Introduce [`needless_option_take`] lint
2022-04-17 18:34:16 +00:00
bors
cb1924a42a Auto merge of #95779 - cjgillot:ast-lifetimes-undeclared, r=petrochenkov
Report undeclared lifetimes during late resolution.

First step in https://github.com/rust-lang/rust/pull/91557

We reuse the rib design of the current resolution framework. Specific `LifetimeRib` and `LifetimeRibKind` types are introduced. The most important variant is `LifetimeRibKind::Generics`, which happens each time we encounter something which may introduce generic lifetime parameters. It can be an item or a `for<...>` binder. The `LifetimeBinderKind` specifies how this rib behaves with respect to in-band lifetimes.

r? `@petrochenkov`
2022-04-17 12:56:19 +00:00
Camille GILLOT
e4110cf633 Bless clippy. 2022-04-17 11:03:34 +02:00
bors
cc25cbd243 Auto merge of #95655 - kckeiks:create-hir-crate-items-query, r=cjgillot
Refactor HIR item-like traversal (part 1)

Issue  #95004

- Create hir_crate_items query which traverses tcx.hir_crate(()).owners to return a hir::ModuleItems
- use tcx.hir_crate_items in tcx.hir().items() to return an iterator of hir::ItemId
- use tcx.hir_crate_items to introduce a tcx.hir().par_items(impl Fn(hir::ItemId)) to traverse all items in parallel;

Signed-off-by: Miguel Guarniz <mi9uel9@gmail.com>

cc `@cjgillot`
2022-04-17 08:06:53 +00:00
Lily Mara
3cd8b5a5ef fixup! Add await_holding_invalid_type lint 2022-04-15 14:45:58 -07:00
Lily Mara
4844325faf Add await_holding_invalid_type lint
changelog: [`await_holding_invalid_type`]

This lint allows users to create a denylist of types which are not allowed to be
held across await points. This is essentially a re-implementation of the
language-level [`must_not_suspend`
lint](https://github.com/rust-lang/rust/issues/83310). That lint has a lot of
work still to be done before it will reach Rust stable, and in the meantime
there are a lot of types which can trip up developers if they are used
improperly.
2022-04-15 14:39:10 -07:00
whodi
e475dde097 collapsible <> collspible 2022-04-15 14:19:01 -07:00
whodi
2be7ad5b39 initialization misspell 2022-04-15 14:19:00 -07:00
whodi
29ef80c78a adding spell checking 2022-04-15 14:18:09 -07:00
Jason Newcomb
70f7c624e4 Allow more complex expressions in let_unit_value 2022-04-14 21:34:33 -04:00
Jason Newcomb
48bcc1d95f Move let_unit_value back into style 2022-04-14 21:33:32 -04:00
Jason Newcomb
d68ac9ccce Don't lint let_unit_value when needed for type inferenece 2022-04-14 21:32:51 -04:00
bors
80bcd9bc6e Auto merge of #8614 - pitaj:fix-7597, r=giraffate
assertions_on_constants: ignore indirect `cfg!`

Fixes #7597

changelog: [`assertions_on_constants`] ignore constants indirectly based on `cfg!`
2022-04-14 23:58:51 +00:00
bors
aade96f902 Auto merge of #8626 - pitaj:format_add_string, r=llogiq
New lint `format_add_strings`

Closes #6261

changelog: Added [`format_add_string`]: recommend using `write!` instead of appending the result of  `format!`
2022-04-14 14:29:22 +00:00
bors
ecb3c3fc7e Auto merge of #8677 - xFrednet:8213-manual-bits-suggestion, r=giraffate
Add `usize` cast to `clippy::manual_bits` suggestion

A fix for the suggestion from https://github.com/rust-lang/rust-clippy/pull/8213

changelog: [`manual_bits`]: The suggestion now includes a cast for proper type conversion
2022-04-14 12:59:23 +00:00
infrandomness
2903b56f17 Add tests and docs
This adds test to make sure correct behavior of lint
- The first test's option variable is not a temporary variable
- The second test does not make usage of `take()`
- The third test makes usage of `take()` and uses a temporary variable
2022-04-14 13:16:46 +02:00
infrandomness
8b2b343b23 Delete unused variable y in test
This fixes the errors occuring while running the ui tests
2022-04-14 13:16:06 +02:00
infrandomness
f8f144117d Swap span_lint for span_lint_and_sugg
This implements a machine applicable suggestion to any matched usage of
`.as_ref().take()``
2022-04-14 13:15:51 +02:00
infrandomness
262b35ea2c Introduce option_take_on_temporary lints
This lint checks if Option::take() is used on a temporary value (a value
that is not of type &mut Option and that is not a Place expression) to
suggest omitting take()
2022-04-14 12:41:47 +02:00
Peter Jaszkowiak
67badbeef6 New lint format_add_strings 2022-04-13 22:48:36 -06:00
Peter Jaszkowiak
9f131e5a0b assertions_on_constants: ignore indirect cfg! 2022-04-13 22:47:08 -06:00
bors
38ba05508c Auto merge of #8676 - Alexendoo:local-used-across-loop, r=xFrednet
Check for loops/closures in `local_used_after_expr`

Follow up to #8646, catches when a local is used multiple times because it's in a loop or a closure

changelog: none
2022-04-14 04:44:33 +00:00
xFrednet
ba15cdd3c1
Add usize cast to clippy::manual_bits suggestion 2022-04-13 19:31:24 +02:00
bors
b6645d022e Auto merge of #8670 - yoav-lavi:main, r=giraffate
`pub_use` restriction

[`pub_use`]

Fixes https://github.com/rust-lang/rust-clippy/issues/8545

- \[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`

[lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints

changelog: Adds a lint called `pub_use` that restricts the usage of `pub use ...`
2022-04-13 13:03:51 +00:00
Yoav Lavi
66d253f0f2 pub_use 2022-04-13 13:48:27 +02:00
bors
f70c73f5c4 Auto merge of #8692 - kyoto7250:fixing_unnecessary_to_owned, r=giraffate
fix unnecessary_to_owned about msrv

This PR fixes ``[`unnecessary_owned`]``.

## What

```rust
# sample code
fn _msrv_1_35() {
    #![clippy::msrv = "1.35"]
    let _ = &["x"][..].to_vec().into_iter();
}

fn _msrv_1_36() {
    #![clippy::msrv = "1.36"]
    let _ = &["x"][..].to_vec().into_iter();
}
```

If we will check this code using clippy, ``[`unnecessary_owned`]`` will modify the code as follows.

```rust
error: unnecessary use of `to_vec`
  --> $DIR/unnecessary_to_owned.rs:219:14
   |
LL |     let _ = &["x"][..].to_vec().into_iter();
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `["x"][..].iter().copied()`

error: unnecessary use of `to_vec`
  --> $DIR/unnecessary_to_owned.rs:224:14
   |
LL |     let _ = &["x"][..].to_vec().into_iter();
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `["x"][..].iter().copied()`
```

This is incorrect. Because `Iterator::copied` was estabilished in 1.36.

## Why

This bug was caused by not separating "copied" and "clone" by reference to msrv.

89ee6aa6e3/clippy_lints/src/methods/unnecessary_to_owned.rs (L195)

So, I added a conditional branch and described the corresponding test.

Thank you in advance.

changelog: fix wrong suggestions about msrv in [`unnecessary_to_owned`]

r! `@giraffate`
2022-04-13 00:57:08 +00:00
bors
06b1695814 Auto merge of #8647 - Jarcho:mut_from_ref_6326, r=giraffate
Only lint `mut_from_ref` when unsafe code is used

fixes #6326

changelog: Only lint `mut_from_ref` when unsafe code is used.
2022-04-13 00:38:54 +00:00
bors
d8c97e6cf3 Auto merge of #8645 - Jarcho:manual_non_exhaustive_5714, r=Jarcho
Don't lint `manual_non_exhaustive` when the enum variant is used

fixes #5714

changelog: Don't lint `manual_non_exhaustive` when the enum variant is used
2022-04-12 18:38:45 +00:00
bors
849668ad71 Auto merge of #8690 - mucinoab:DoNot-rest_pat_in_fully_bound_structs-OnNonExhaustive, r=Manishearth
Do not trigger ``[`rest_pat_in_fully_bound_structs`]`` on `#[non_exhaustive]` structs

fixes #8029

Just adds an additional check to ensure that the`ty::VariantDef` is not marked as `#[non_exhaustive]`.

changelog: Do not apply ``[`rest_pat_in_fully_bound_structs`]`` on structs marked as non exhaustive.
2022-04-12 16:14:13 +00:00
kyoto7250
dfdc5ad7d8 fix unnecessary_to_owned about msrv 2022-04-12 22:59:25 +09:00
bors
b3bd03afcd Auto merge of #8686 - Jarcho:undocumented_unsafe_blocks_8681, r=flip1995
Fix ICE in `undocumented_unsafe_blocks`

fixes #8681

changelog: Fix ICE in `undocumented_unsafe_blocks`
2022-04-12 07:17:57 +00:00
Bruno A. Muciño
739f273739 Do not apply rest_pat_in_fully_bound_structs on #[non_exhaustive] structs 2022-04-11 22:47:04 -05:00
bors
bc069efb1f Auto merge of #8688 - kyoto7250:adding_condition_for_map_clone, r=giraffate
adding condition for map_clone message

This PR fixes the message about `map_clone`.

if msrv >= 1.36, the message is correct.

```bash
$ cat main.rs
fn main() {
  let x: Vec<&i32> = vec![&1, &2];
  let y: Vec<_>  = x.iter().map(|i| *i).collect();
  println!("{:?}", y);
}

$ cargo clippy
warning: you are using an explicit closure for copying elements
 --> main.rs:3:20
  |
3 |   let y: Vec<_>  = x.iter().map(|i| *i).collect();
  |                    ^^^^^^^^^^^^^^^^^^^^ help: consider calling the dedicated `copied` method: `x.iter().copied()`
  |
  = note: `#[warn(clippy::map_clone)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#map_clone

warning: `test` (build script) generated 1 warning
warning: `test` (bin "test") generated 1 warning (1 duplicate)
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
```

but, if msrv < 1.36, the suggestion is `cloned`, but the message is `copying`.
```bash
$ cat clippy.toml
msrv = "1.35"

$ cargo clippy
warning: you are using an explicit closure for copying elements
 --> main.rs:3:20
  |
3 |   let y: Vec<_>  = x.iter().map(|i| *i).collect();
  |                    ^^^^^^^^^^^^^^^^^^^^ help: consider calling the dedicated `cloned` method: `x.iter().cloned()`
```

I think  the separation of messages will make it more user-friendly.

thank you in advance.

changelog: Fixed a message in map_clone.
2022-04-12 01:11:54 +00:00
kyoto7250
9716a9eff0 adding condition for map_clone message
if msrv < 1.36, the message tells , but the suggestion is
2022-04-12 04:03:48 +09:00
bors
dbcd82885f Auto merge of #8624 - pitaj:is_digit_ascii_radix, r=xFrednet
New lint `is_digit_ascii_radix`

Closes #6399

changelog: Added [`is_digit_ascii_radix`]: recommend `is_ascii_digit()` or `is_ascii_hexdigit()` in place of `is_digit(10)` and `is_digit(16)`
2022-04-11 18:56:21 +00:00
bors
636ed84c81 Auto merge of #8687 - Alexendoo:cast-possible-truncation-overflow, r=xFrednet
Fix subtraction overflow in `cast_possible_truncation`

changelog: Fix false negative due to subtraction overflow in `cast_possible_truncation`

I *think* a false negative is the worst that can happen from this
2022-04-11 18:40:14 +00:00
Alex Macleod
4a21082da2 Fix subtraction overflow in cast_possible_truncation 2022-04-11 18:54:44 +01:00
Jason Newcomb
c82dd0f36e Fix ICE in undocumented_unsafe_blocks 2022-04-11 13:18:27 -04:00
bors
89ee6aa6e3 Auto merge of #8667 - Jarcho:proc_macro_check, r=flip1995
Don't lint various match lints when expanded by a proc-macro

fixes #4952

As always for proc-macro output this is a hack-job of a fix. It would be really nice if more proc-macro authors would set spans correctly.

changelog: Don't lint various lints on proc-macro output.
2022-04-11 16:41:51 +00:00
bors
131ff87a1e Auto merge of #8673 - Jarcho:same_functions_8139, r=Manishearth
Fix `same_functions_in_if_condition` FP

fixes #8139

changelog: Don't consider `Foo<{ SomeConstant }>` and `Foo<{ SomeOtherConstant }>` to be the same, even if the constants have the same value.
2022-04-11 15:36:55 +00:00
bors
18ab97d220 Auto merge of #8668 - Jarcho:iter_with_drain_8538, r=Manishearth
Don't lint `iter_with_drain` on references

fixes #8538
changelog: Don't lint `iter_with_drain` on references
2022-04-11 15:20:01 +00:00
bors
5c19ae96e7 Auto merge of #8660 - yoav-lavi:squashed-master, r=flip1995
`unnecessary_owned_empty_strings`

[`unnecessary_owned_empty_strings`]

Fixes https://github.com/rust-lang/rust-clippy/issues/8650

- \[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`

[lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints

changelog: Adds `unnecessary_owned_empty_strings`, a lint that detects passing owned empty strings to a function expecting `&str`
2022-04-11 11:12:33 +00:00
Yoav Lavi
10201370a1 unnecessary_owned_empty_string -> unnecessary_owned_empty_strings 2022-04-11 13:05:42 +02:00
Yoav Lavi
a4d1837f07 unnecessary_string_new 2022-04-11 12:35:44 +02:00
bors
85e91dc99e Auto merge of #8671 - andy-k:fix-typo, r=flip1995
fix typo

fix typo in #8630

changelog: none
2022-04-11 09:22:37 +00:00
bors
5344236715 Auto merge of #8631 - Alexendoo:splitn-overlap, r=xFrednet
Remove overlap between `manual_split_once` and `needless_splitn`

changelog: Remove overlap between [`manual_split_once`] and [`needless_splitn`]. Fixes some incorrect `rsplitn` suggestions for [`manual_split_once`]

Things that can trigger `needless_splitn` no longer trigger `manual_split_once`, e.g.

```rust
s.[r]splitn(2, '=').next();
s.[r]splitn(2, '=').nth(0);
s.[r]splitn(3, '=').next_tuple();
```

Fixes some suggestions:

```rust
let s = "should not match";

s.rsplitn(2, '.').nth(1);
// old -> Some("should not match")
Some(s.rsplit_once('.').map_or(s, |x| x.0));
// new -> None
s.rsplit_once('.').map(|x| x.0);

s.rsplitn(2, '.').nth(1)?;
// old -> "should not match"
s.rsplit_once('.').map_or(s, |x| x.0);
// new -> early returns
s.rsplit_once('.')?.0;
```
2022-04-10 17:45:19 +00:00
Alex Macleod
6fba89751b Remove overlap between manual_split_once and needless_splitn
Also fixes some incorrect suggestions for rsplitn
2022-04-10 17:05:07 +01:00
Alex Macleod
5e335a52bc Check for loops/closures in local_used_after_expr 2022-04-10 14:26:44 +01:00
Jason Newcomb
719a040397 Compare inline constants by their bodies rather than value in SpanlessEq 2022-04-10 00:54:41 -04:00
Andy Kurnia
1450c989ae fix typo 2022-04-10 01:07:01 +08:00
kyoto7250
a9511482d6 fix comments in test for split_once
split_once was stabilized in 1.52
2022-04-09 20:34:43 +09:00
Jason Newcomb
744b0ff903 Don't lint iter_with_drain on references 2022-04-08 23:41:50 -04:00
bors
b029a86c6b Auto merge of #8648 - Jarcho:transmute_collection_7706, r=xFrednet
Fix `unsound_collection_transmute`

fixes #7706

changelog: Better check size and alignment requirements in `unsound_collection_transmute`
2022-04-08 21:43:26 +00:00
Jason Newcomb
63f6a79bf8 Don't lint various match lints when expanded by a proc-macro 2022-04-08 16:51:40 -04:00
Miguel Guarniz
224916823a Refactor HIR item-like traversal (part 1)
- Create hir_crate_items query which traverses tcx.hir_crate(()).owners to return a hir::ModuleItems
- use tcx.hir_crate_items in tcx.hir().items() to return an iterator of hir::ItemId
- add par_items(impl Fn(hir::ItemId)) to traverse all items in parallel

Signed-off-by: Miguel Guarniz <mi9uel9@gmail.com>
2022-04-08 11:59:59 -04:00
flip1995
71131351de Merge commit '984330a6ee3c4d15626685d6dc8b7b759ff630bd' into clippyup 2022-04-08 10:06:10 +01:00
bors
a63308be0a Auto merge of #8619 - pitaj:fix-6973, r=giraffate
ignore `&x | &y` in unnested_or_patterns

replacing it with `&(x | y)` is actually more characters

Fixes #6973

changelog: [`unnested_or_patterns`] ignore `&x | &y`, nesting would result in more characters
2022-04-08 00:37:56 +00:00
Peter Jaszkowiak
06cfeb90c1 New lint is_digit_ascii_radix 2022-04-07 14:14:30 -06:00
bors
abc59bb914 Auto merge of #8656 - flip1995:rustup, r=flip1995
Rustup

r? `@ghost`

changelog: none
2022-04-07 15:30:27 +00:00
flip1995
669fddab37
Merge remote-tracking branch 'upstream/master' into rustup 2022-04-07 15:44:37 +01:00
bors
574bf88e3e Auto merge of #8635 - pbor:unsigned-abs, r=giraffate
Add a lint to detect cast to unsigned for abs() and suggest unsigned_…

…abs()

changelog: Add a [`cast_abs_to_unsigned`] that checks for uses of `abs()` that are cast to the corresponding unsigned integer type and suggest to replace them with `unsigned_abs()`.
2022-04-07 13:17:28 +00:00
bors
650a0e52b8 Auto merge of #8646 - Alexendoo:option-as-deref-mut, r=giraffate
Fix `as_deref_mut` false positives in `needless_option_as_deref`

Also moves it into `methods/`

Fixes #7846
Fixes #8047

changelog: [`needless_option_as_deref`]: No longer lints for `as_deref_mut` on Options that cannot be moved

supersedes #8064
2022-04-07 13:00:15 +00:00
Alex Macleod
182b7c38d7 Fix as_deref_mut false positives in needless_option_as_deref
Also moves the lint to the methods directory
2022-04-07 12:39:21 +01:00
Paolo Borelli
b0edbca0e6 new lint cast_abs_to_unsigned
Add a lint to detect cast to unsigned for abs() and suggest
unsigned_abs() to avoid panic when called on MIN.
2022-04-07 11:28:14 +02:00
bors
0d66404941 Auto merge of #8630 - Jarcho:forget_non_drop, r=Manishearth
Add lints `drop_non_drop` and `forget_non_drop`

fixes #1897

changelog: Add lints `drop_non_drop` and `forget_non_drop`
2022-04-06 23:04:20 +00:00
bors
409a936f3b Auto merge of #8606 - InfRandomness:err()-expect()-lint, r=xFrednet
Add [`err_expect`] lint

[`expect_err`] lint

- \[ ] 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`

Fixes https://github.com/rust-lang/rust-clippy/issues/1435

changelog: Added a lint to detect usage of .err().expect()
2022-04-06 18:07:56 +00:00
InfRandomness
cebe575aad Add .err().expect() lint 2022-04-06 19:25:58 +02:00
bors
81e004aadb Auto merge of #8549 - J-ZhengLi:issue8542, r=llogiq
fix FP in lint `[needless_match]`

fixes: #8542
fixes: #8551
fixes: #8595
fixes: #8599

---

changelog: check for more complex custom type, and ignore type coercion in [`needless_match`]
2022-04-06 17:23:14 +00:00
Jason Newcomb
d5e887c6f0 Better check size and alignment requirements in unsound_collection_transmute 2022-04-06 11:57:55 -04:00
Jason Newcomb
ddd3af2273 Only lint mut_from_ref when unsafe code is used 2022-04-06 10:59:57 -04:00
Jason Newcomb
6e20a634e7 Don't lint manual_non_exhaustive when the enum variant is used 2022-04-06 10:12:30 -04:00
bors
cf1e2e9c1c Auto merge of #8612 - SabrinaJewson:suggest-from-utf8-unchecked-in-const, r=flip1995
Suggest from_utf8_unchecked in const contexts

Unfortunately I couldn't figure out how to check whether a given expression is in an `unsafe` context or not, so I just unconditionally emit the wrapping `unsafe {}` block in the suggestion. If there is an easy way to get it to work better then I would love to hear it.

changelog: Suggest `from_utf8_unchecked` instead of `from_utf8` in const contexts for ``[`transmute_bytes_to_str`]``

refs: #8379
2022-04-06 09:32:51 +00:00
bors
880ff2497d Auto merge of #8596 - Jaic1:unnecessary_cast, r=flip1995
Fix unnecessary_cast suggestion for type aliasses

Fix #6923. The [`unnecessary_cast`] lint now will skip casting to non-primitive type.

changelog: fix lint [`unnecessary_cast `]
2022-04-06 08:27:03 +00:00
bors
41f2eccf92 Auto merge of #8588 - pitaj:fix-8348, r=flip1995
`indexing_slicing` should not fire if a valid array index comes from a constant function that is evaluated at compile-time

fix #8348

changelog: [`indexing_slicing`] fewer false positives in `const` contexts and with `const` indices
2022-04-06 08:13:26 +00:00
bors
938b9fd720 Auto merge of #8403 - nerdypepper:fix/diagnostic-message-mispelling, r=flip1995,Manishearth
fix misspelling in diagnostic message of `bytes_nth`

*Please write a short comment explaining your change (or "none" for internal only changes)*

changelog: fix misspelling in diagnostic message in ``[`bytes_nth`]``
2022-04-05 10:07:13 +00:00
Akshay
1582e7bf88
fix mispelling in diagnostic message of bytes_nth 2022-04-05 10:53:10 +01:00
bors
511752fd9d Auto merge of #8620 - Alexendoo:test-fmt-first, r=flip1995
Run fmt test before compile-test/dogfood

I seem to always forget to run `cargo dev fmt` before doing a test. This lets it fail fast rather than going through the much longer compile-test/dogfood tests first

changelog: none
2022-04-05 09:50:53 +00:00
Jason Newcomb
e4fc15e646 Don't lint cast_ptr_alignment when used for unaligned reads and writes 2022-04-04 13:54:52 -04:00
Jason Newcomb
5cd711b4f1 Add lints drop_non_drop and forget_non_drop 2022-04-04 12:30:09 -04:00
bors
190f0deac8 Auto merge of #8450 - Jarcho:unsafe_blocks_8449, r=giraffate
Rework `undocumented_unsafe_blocks`

fixes: #8264
fixes: #8449

One thing came up while working on this. Currently comments on the same line are supported like so:

```rust
/* SAFETY: reason */ unsafe {}
```

Is this worth supporting at all? Anything other than a couple of words doesn't really fit well.

edit: [zulip topic](https://rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/.60undocumented_unsafe_blocks.60.20same.20line.20comment)

changelog: Don't lint `undocumented_unsafe_blocks` when the unsafe block comes from a proc-macro.
changelog: Don't lint `undocumented_unsafe_blocks` when the preceding line has a safety comment and the unsafe block is a sub-expression.
2022-04-04 13:07:26 +00:00
bors
1cec8b30fa Auto merge of #8594 - FoseFx:unit_like_struct_brackets, r=giraffate
add `empty_structs_with_brackets`

<!-- Thank you for making Clippy better!

We're collecting our changelog from pull request descriptions.
If your PR only includes internal changes, you can just write
`changelog: none`. Otherwise, please write a short comment
explaining your change. Also, it's helpful for us that
the lint name is put into brackets `[]` and backticks `` ` ` ``,
e.g. ``[`lint_name`]``.

If your PR fixes an issue, you can add "fixes #issue_number" into this
PR description. This way the issue will be automatically closed when
your PR is merged.

If you added a new lint, here's a checklist for things that will be
checked during review or continuous integration.

- \[ ] Followed [lint naming conventions][lint_naming]
- \[ ] Added passing UI tests (including committed `.stderr` file)
- \[ ] `cargo test` passes locally
- \[ ] Executed `cargo dev update_lints`
- \[ ] Added lint documentation
- \[ ] Run `cargo dev fmt`

[lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints

Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.

Delete this line and everything above before opening your PR.

--

*Please write a short comment explaining your change (or "none" for internal only changes)*
-->
Closes #8591

I'm already sorry for the massive diff 😅

changelog: New lint [`empty_structs_with_brackets`]
2022-04-04 07:28:36 +00:00
Jason Newcomb
d5ef542d37 Generate renamed lint test 2022-04-03 22:52:42 -04:00
Jason Newcomb
4227411513 Generate deprecated lints test 2022-04-03 08:54:37 -04:00
Alex Macleod
515b4eceff Run fmt test before compile-test/dogfood 2022-04-02 12:34:06 +01:00
bors
85b88be2a4 Auto merge of #8605 - Jarcho:remove-deps, r=xFrednet
Remove deps

This remove both `regex` and `cargo_metadata` as dependencies making `clippy_dev` compile ~3x faster (~46s -> ~16s locally). `cargo_metadata` was used to extract the `version` field from `Cargo.toml`, which is done trivially without that. `regex` was used to parse `define_clippy_lint` in `update_lints` which is now done using `rustc_lexer`. This isn't any simpler, but it compiles ~15s faster and runs ~3x faster (~2.1s -> ~0.7s locally).

The next biggest offenders to compile times are `clap` and `winapi` on windows. `clap` could be removed, but re-implementing enough is probably more work than it's worth. `winapi` is used by `opener` and `walkdir` so it's stuck there.

changelog: none
2022-04-02 10:42:12 +00:00
bors
baaddf2b84 Auto merge of #8611 - Alexendoo:module-files-relative-paths, r=llogiq
Handle relative paths in module_files lints

The problem being that when clippy is run in the project's directory `lp` would be a relative path, this wasn't caught by the tests as there `lp` is an absolute path. Being a relative path it did not start with `trim_src_path` and so was ignored

Also allowed the removal of some `.to_os_string`/`.to_owned`s

changelog: Fixes [`self_named_module_files`] and [`mod_module_files`] not linting

Fixes #8123, cc `@DevinR528`
2022-04-02 07:06:03 +00:00
Jason Newcomb
17c8bee95a Add a couple of examples to undocumented_unsafe_blocks 2022-04-02 00:46:45 -04:00
Peter Jaszkowiak
c70f1e0f8f ignore &x | &y in unnested_or_patterns
replacing it with `&(x | y)` is actually more characters
2022-04-01 22:36:30 -06:00