Commit graph

10950 commits

Author SHA1 Message Date
Guillaume Gomez
874f851ac5 Use std_or_core instead of doing check by hand every time 2024-01-15 20:53:00 +01:00
Martin Nordholts
6a74a0e17b compiler: Lower fn call arg spans down to MIR
To enable improved accuracy of diagnostics in upcoming commits.
2024-01-15 19:07:11 +01:00
Samuel Moelius
ad2a2ba94d Ensure callee_ids are body owners 2024-01-15 12:26:45 -05:00
y21
f09cd88199
fix false positive in suspicious_open_options, make paths work 2024-01-15 17:15:09 +00:00
atwam
515fe65ba8
Fix conflicts
- New ineffective_open_options had to be fixed.
- Now not raising an issue on missing `truncate` when `append(true)`
  makes the intent clear.
- Try implementing more advanced tests for non-chained operations. Fail
2024-01-15 17:15:09 +00:00
atwam
84588a8815
Add suggestion/fix to suspicious_open_options
Also rebase and fix conflicts
2024-01-15 17:15:09 +00:00
atwam
2ec8729962
PR Fixes 2024-01-15 17:15:08 +00:00
atwam
6fb471d646
More helpful text, small style changes. 2024-01-15 17:15:08 +00:00
atwam
6c201db005
Add suspicious_open_options lint.
Checks for the suspicious use of OpenOptions::create()
without an explicit OpenOptions::truncate().

create() alone will either create a new file or open an
existing file. If the file already exists, it will be
overwritten when written to, but the file will not be
truncated by default. If less data is written to the file
than it already contains, the remainder of the file will
remain unchanged, and the end of the file will contain old
data.
In most cases, one should either use `create_new` to ensure
the file is created from scratch, or ensure `truncate` is
called so that the truncation behaviour is explicit.
`truncate(true)` will ensure the file is entirely overwritten
with new data, whereas `truncate(false)` will explicitely
keep the default behavior.

```rust
use std::fs::OpenOptions;

OpenOptions::new().create(true).truncate(true);
```
2024-01-15 17:15:08 +00:00
Adam Reichold
33d8e47e98
Try to improve wording and fix dead link in description of arc_with_non_send_sync lint. 2024-01-15 09:07:48 +01:00
bors
692f53fe8f Auto merge of #12136 - y21:issue12135, r=Jarcho
[`useless_asref`]: check that the clone receiver is the parameter

Fixes #12135

There was no check for the receiver of the `clone` call in the map closure. This makes sure that it's a path to the parameter.

changelog: [`useless_asref`]: check that the clone receiver is the closure parameter
2024-01-15 05:08:16 +00:00
bors
d6ff2d2c2d Auto merge of #12141 - samueltardieu:issue-12138, r=Jarcho
from_over_into: suggest a correct conversion to ()

changelog: [`from_over_into`]: suggest a correct conversion to `()`

Fix #12138
2024-01-15 04:32:22 +00:00
bors
37b8ae7f17 Auto merge of #12114 - talagrand:patch-1, r=Jarcho
['arc_with_non_send_sync`] documentation edits

Arc's documentation uses the term "thread"; aligning to that terminology. Fix casing of "Rc".

changelog: None
2024-01-15 04:21:37 +00:00
Kristof Mattei
e8ec99811b
fix: crates are limited to ASCII values 2024-01-14 14:00:13 -07:00
Kristof Mattei
ea585ef321
chore: remove unneeded into_iter 2024-01-14 09:40:14 -07:00
Kristof Mattei
b1c52d502d
chore: add comments to explain reasoning 2024-01-14 09:32:36 -07:00
Kristof Mattei
5d06fbb46d
fix: don't allocate new string when not needed 2024-01-14 09:25:31 -07:00
Guillaume Gomez
1bcaf29e0b Correctly suggest std or core path depending if this is a no_std crate 2024-01-14 14:45:24 +01:00
y21
0774489086 find function path references early in the lint pass 2024-01-14 06:12:15 +01:00
Kristof Mattei
d975e267b9
fix: add fix for bug, fix test name 2024-01-13 17:44:27 -07:00
blyxyas
44f5d969d5
Change PublicallyExported -> PubliclyExported 2024-01-14 01:14:05 +01:00
y21
be5707ce1b lint on .map(|&x| x.clone()) 2024-01-13 17:46:46 +01:00
Quinn Sinclair
e0228eeb94 Fixes FP in redundant_closure_call when closures are passed to macros
There are cases where the closure call is needed in some macros, this in
particular occurs when the closure has parameters. To handle this case,
we allow the lint when there are no parameters in the closure, or the
closure is outside a macro invocation.

fixes: #11274, #1553
changelog: FP: [`redundant_closure_call`] when closures with parameters
are passed in macros.
2024-01-13 17:45:30 +01:00
Samuel Tardieu
e025356969 from_over_into: suggest a correct conversion to () 2024-01-13 13:19:55 +01:00
Guillaume Gomez
68aceeed03 Improve help message for search_is_some lint 2024-01-12 22:48:30 +01:00
bors
7eca5afd34 Auto merge of #12137 - GuillaumeGomez:fix-unconditional_recursion-false-positive, r=llogiq
Fix false positive in `PartialEq` check in `unconditional_recursion` lint

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

We needed to check for the type of the previous element <del>in case it's a field</del>.

EDIT: After some extra thoughts, no need to check if it's a field, just if it's the same type as `Self`.

r? `@llogiq`

changelog: Fix false positive in `PartialEq` check in `unconditional_recursion` lint
2024-01-12 18:30:11 +00:00
Guillaume Gomez
c8cd09a8e6 Fix false positive in PartialEq check in unconditional_recursion lint 2024-01-12 17:37:09 +01:00
y21
153b83f61b [useless_asref]: check that the clone receiver is the local 2024-01-12 13:39:42 +01:00
Bryanskiy
09d024117e Delegation implementation: step 1 2024-01-12 14:11:16 +03:00
bors
88b5d519a1 Auto merge of #12129 - GuillaumeGomez:map-clone-copy, r=llogiq
Fix suggestion for `map_clone` lint on types implementing `Copy`

Follow-up of https://github.com/rust-lang/rust-clippy/pull/12104.

It was missing this check to suggest the correct method.

r? `@llogiq`

changelog: Fix suggestion for `map_clone` lint on types implementing `Copy`
2024-01-11 23:28:12 +00:00
bors
6baa129fbc Auto merge of #119864 - matthiaskrgr:rollup-mc2qz13, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #119448 (annotate-snippets: update to 0.10)
 - #119813 (Silence some follow-up errors [2/x])
 - #119836 (chore: remove unnecessary blank line)
 - #119841 (Remove `DiagnosticBuilder::buffer`)
 - #119842 (coverage: Add enums to accommodate other kinds of coverage mappings)
 - #119845 (rint: further doc tweaks)
 - #119852 (give const-err4 a more descriptive name)
 - #119853 (rustfmt.toml: don't ignore just any tests path, only root one)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-11 20:01:01 +00:00
Guillaume Gomez
82841aada4 Fix suggestion for map_clone on types implementing Copy 2024-01-11 17:44:07 +01:00
Philipp Krones
aa220c7ee7 Merge commit '26ac6aab023393c94edf42f38f6ad31196009643' 2024-01-11 17:27:03 +01:00
Philipp Krones
2c0cea7cbc
Merge remote-tracking branch 'upstream/master' into rustup 2024-01-11 17:19:53 +01:00
Nicholas Nethercote
fb83ef6495 Stop using DiagnosticBuilder::buffer in the parser.
One consequence is that errors returned by
`maybe_new_parser_from_source_str` now must be consumed, so a bunch of
places that previously ignored those errors now cancel them. (Most of
them explicitly dropped the errors before. I guess that was to indicate
"we are explicitly ignoring these", though I'm not 100% sure.)
2024-01-11 18:37:56 +11:00
cocodery
7c389acd27 Fix error warning span for issue12045 2024-01-11 14:52:03 +08:00
Guillaume Gomez
f7ef9a6f1f Fix dogfood and add code comments 2024-01-09 18:03:55 +01:00
Guillaume Gomez
83ae5edd50 Don't lint with map_clone if current type is Option or Result and method call is as_ref. 2024-01-09 17:39:51 +01:00
Guillaume Gomez
e90eea7894 Clean up code in map_clone and useless_asref lints 2024-01-09 17:39:36 +01:00
Guillaume Gomez
8791a28c4a Also handle Result type for map_clone lint 2024-01-09 16:35:40 +01:00
Eugene
c2d071c11c
Documentation edits for arc_with_non_send_sync
Arc's documentation uses the term "thread", aligning to that terminology. Fix typo in "Rc".
2024-01-09 06:50:17 -08:00
Guillaume Gomez
4ab6924bca Extend useless_asref lint on map(clone) 2024-01-09 14:09:00 +01:00
Michael Goulet
89f511e4dd Rustdoc and Clippy stop misusing Key for Ty -> (adt) DefId 2024-01-08 20:30:10 +00:00
bors
3b8323d790 Auto merge of #12049 - cocodery:fix/issue#11243, r=Alexendoo
fix/issue#11243: allow 3-digit-grouped binary in non_octal_unix_permissions

fixes [Issue#11243](https://github.com/rust-lang/rust-clippy/issues/11243)

Issue#11243 suggest lint `non_octal_unix_permissions` should not report binary format literal unix permissions as an error, and we think binary format is a good way to understand these permissions.

To solve this problem, we need to add check for binary literal, which is written in function `check_binary_unix_permissions` , only `binary, 3 groups and each group length equals to 3` is a legal format.

changelog: [`non_octal_unix_permissions`]: Add check for binary format literal unix permissions like 0b111_111_111
2024-01-08 19:09:42 +00:00
bors
7fbaba856b Auto merge of #12080 - PartiallyTyped:12058, r=xFrednet
Fixed ICE introduced in #12004

Issue: in https://github.com/rust-lang/rust-clippy/pull/12004, we emit a lint for `filter(Option::is_some)`. If the
parent expression is a `.map` we don't emit that lint as there exists a
more specialized lint for that.

The ICE introduced in https://github.com/rust-lang/rust-clippy/pull/12004 is a consequence of the assumption that a
parent expression after a filter would be a method call with the filter
call being the receiver. However, it is entirely possible to have a
closure of the form

```
|| { vec![Some(1), None].into_iter().filter(Option::is_some) }
```
The previous implementation looked at the parent expression; namely the
closure, and tried to check the parameters by indexing [0] on an empty
list.

This commit is an overhaul of the lint with significantly more FP tests
and checks.

Impl details:

1. We verify that the filter method we are in is a proper trait method
   to avoid FPs.
2. We check that the parent expression is not a map by checking whether
   it exists; if is a trait method; and then a method call.
3. We check that we don't have comments in the span.
4. We verify that we are in an Iterator of Option and Result.
5. We check the contents of the filter.
   1. For closures we peel it. If it is not a single expression, we don't
     lint. We then try again by checking the peeled expression.
   2. For paths, we do a typecheck to avoid FPs for types that impl
     functions with the same names.
   3. For calls, we verify the type, via the path, and that the param of
     the closure is the single argument to the call.
   4. For method calls we verify that the receiver is the parameter of
     the closure. Since we handle single, non-block exprs, the
     parameter can't be shadowed, so no FP.

This commit also adds additional FP tests.

Fixes: #12058

Adding `@xFrednet` as you've the most context for this as you reviewed it last time.

`@rustbot` r? `@xFrednet`

---

changelog: none
(Will be backported and therefore don't effect stable)
2024-01-07 17:21:28 +00:00
Quinn Sinclair
bbadce9ec0 Fixed ICE introduced in #12004
Issue: in #12004, we emit a lint for `filter(Option::is_some)`. If the
parent expression is a `.map` we don't emit that lint as there exists a
more specialized lint for that.

The ICE introduced in #12004 is a consequence of the assumption that a
parent expression after a filter would be a method call with the filter
call being the receiver. However, it is entirely possible to have a
closure of the form

```
|| { vec![Some(1), None].into_iter().filter(Option::is_some) }
```
The previous implementation looked at the parent expression; namely the
closure, and tried to check the parameters by indexing [0] on an empty
list.

This commit is an overhaul of the lint with significantly more FP tests
and checks.

Impl details:

1. We verify that the filter method we are in is a proper trait method
   to avoid FPs.
2. We check that the parent expression is not a map by checking whether
   it exists; if is a trait method; and then a method call.
3. We check that we don't have comments in the span.
4. We verify that we are in an Iterator of Option and Result.
5. We check the contents of the filter.
  1. For closures we peel it. If it is not a single expression, we don't
     lint.
  2. For paths, we do a typecheck to avoid FPs for types that impl
     functions with the same names.
  3. For calls, we verify the type, via the path, and that the param of
     the closure is the single argument to the call.
  4. For method calls we verify that the receiver is the parameter of
     the closure. Since we handle single, non-block exprs, the
     parameter can't be shadowed, so no FP.

This commit also adds additional FP tests.
2024-01-07 17:11:34 +02:00
cocodery
a843996e81 Simplify check function, weirdly binary format literals happen not often 2024-01-07 22:35:21 +08:00
bors
f37e7f3585 Auto merge of #12109 - GuillaumeGomez:map-clone-call, r=llogiq
Handle "calls" inside the closure as well in `map_clone` lint

Follow-up of https://github.com/rust-lang/rust-clippy/pull/12104.

I just realized that I didn't handle the case where the `clone` method was made as a call and not a method call.

r? `@llogiq`

changelog: Handle "calls" inside the closure as well in `map_clone` lint
2024-01-07 14:23:02 +00:00
Guillaume Gomez
78aa2e29e2 Handle "calls" inside the closure as well in map_clone lint 2024-01-07 13:24:52 +01:00
Samuel Tardieu
5b7a0de3e7 Do not suggest bool::then() and bool::then_some in const contexts 2024-01-07 10:43:18 +01:00
bors
0e5dc8e630 Auto merge of #11883 - J-ZhengLi:issue11642, r=dswij
improve [`cast_sign_loss`], to skip warning on always positive expressions

fixes: #11642

changelog: improve [`cast_sign_loss`] to skip warning on always positive expressions

Turns out this is change became quite big, and I still can't cover all the cases, like method calls such as `POSITIVE_NUM.mul(POSITIVE_NUM)`, or `NEGATIVE_NUM.div(NEGATIVE_NUM)`... but well, if I do, I'm scared that this will goes forever, so I stopped, unless it needs to be done, lol.
2024-01-06 19:22:59 +00:00
bors
788094c235 Auto merge of #11972 - samueltardieu:issue-11958, r=llogiq
Do not suggest `[T; n]` instead of `vec![T; n]` if `T` is not `Copy`

changelog: [`useless_vec`]: do not suggest replacing `&vec![T; N]` by `&[T; N]` if `T` is not `Copy`

Fix #11958
2024-01-06 18:56:30 +00:00
bors
17b2418208 Auto merge of #12104 - GuillaumeGomez:map-clone, r=llogiq
Extend `map_clone` lint to also work on non-explicit closures

I found it weird that this case was not handled by the current line so I added it. The only thing is that I don't see an obvious way to infer the current type to determine if it's copyable or not, so for now I always suggest `cloned` and I added a FIXME.

r? `@llogiq`

changelog: Extend `map_clone` lint to also work on non-explicit closures
2024-01-06 16:54:20 +00:00
Guillaume Gomez
28c133b4bc Extend map_clone lint to also work on non-explicit closures 2024-01-06 17:22:21 +01:00
bors
d1b8d9c79f Auto merge of #119531 - petrochenkov:cmpctxt, r=cjgillot
rustc_span: Optimize syntax context comparisons

Including comparisons with root context.

- `eq_ctxt` doesn't require retrieving full `SpanData`, or taking the span interner lock twice.
- Checking `SyntaxContext` for "rootness" is cheaper than extracting a full outer `ExpnData` for it and checking *it* for rootness.

The internal lint for `eq_ctxt` is also tweaked to detect `a.ctxt() != b.ctxt()` in addition to `a.ctxt() == b.ctxt()`.
2024-01-06 13:51:01 +00:00
cocodery
60c647b262 Fix bug: allow no- '_'-split binary format string, add test 2024-01-06 21:41:25 +08:00
cocodery
bd6e9202b4 modify check that any macros will be ingored in this lint, and add test 2024-01-06 14:12:41 +08:00
Vadim Petrochenkov
e10a05dff3 rustc_span: Optimize syntax context comparisons
Including comparisons with root context
2024-01-06 01:25:20 +03:00
Matthias Krüger
84c4b5255c Rollup merge of #119554 - matthewjasper:remove-guard-distinction, r=compiler-errors
Fix scoping for let chains in match guards

If let guards were previously represented as a different type of guard in HIR and THIR. This meant that let chains in match guards were not handled correctly because they were treated exactly like normal guards.

- Remove `hir::Guard` and `thir::Guard`.
- Make the scoping different between normal guards and if let guards also check for let chains.

closes #118593
2024-01-05 20:39:52 +01:00
bors
7bb0e9c2f2 Auto merge of #12099 - GuillaumeGomez:struct-field-names-bool, r=llogiq
Don't emit `struct_field_names` lint if all fields are booleans and don't start with the type's name

Fixes #11936.

I only checked that all fields are booleans and not the prefix (nor the suffix) because when I started to list accepted prefixes (like "is", "has", "should", "could", etc), the list was starting to get a bit too long and I thought it was not really worth for such a small change.

r? `@llogiq`

changelog: Don't emit `struct_field_names` lint if all fields are booleans and don't start with the type's name
2024-01-05 16:58:50 +00:00
bors
394f63fe94 Auto merge of #10844 - Centri3:let_unit_value, r=Alexendoo
Don't lint `let_unit_value` when `()` is explicit

since these are explicitly written (and not the result of a function call or anything else), they should be allowed, as they are both useful in some cases described in #9048

Fixes #9048

changelog: [`let_unit_value`]: Don't lint when `()` is explicit
2024-01-05 16:13:38 +00:00
Centri3
fd9d330839 Don't lint let_unit_value when () is explicit 2024-01-05 16:04:02 +00:00
Michael Goulet
d2012259ca Rollup merge of #119601 - nnethercote:Emitter-cleanups, r=oli-obk
`Emitter` cleanups

Some improvements I found while looking at this code.

r? `@oli-obk`
2024-01-05 10:57:24 -05:00
Guillaume Gomez
9e4e8ef102 Don't emit struct_field_names lint if all fields are booleans and don't start with the type's name 2024-01-05 16:44:01 +01:00
bors
eec0f3d6aa Auto merge of #12036 - kpreid:patch-1, r=Alexendoo
Polish `missing_enforced_import_renames` documentation

* Fixes a typo in the name of the lint (`enforce-import-renames` instead of `enforced-import-renames`).
* Copyedit “Why” paragraph.
* Make the example configuration use a multi-line list, since it is not particularly expected that a real project will have *exactly one* rename to enforce (and the old formatting had unbalanced whitespace).

changelog: none
2024-01-05 15:31:27 +00:00
bors
d3dfecbd41 Auto merge of #12066 - y21:issue12048, r=Alexendoo
Don't look for safety comments in doc tests

Fixes #12048.

What happened in the linked issue is that the lint checks for lines that start with `//` and have `SAFETY:` somewhere in it above the function item.
This works for regular comments, but when the `//` is the start of a doc comment (e.g. `/// // SAFETY: ...`) and it's part of a doc test (i.e. within \`\`\`), we probably shouldn't lint that, since the user most likely meant to refer to a different node than the one currently being checked. For example in the linked issue, the safety comment refers to `unsafe { *five_pointer }`, but the lint believes it's part of the function item.

We also can't really easily test whether the `// SAFETY:` comment within a doc comment is necessary or not, since I think that would require creating a new compiler session to re-parse the contents of the doc comment. We already do this for one of the doc markdown lints, to look for a main function in doc tests, but I don't know how to feel about doing that in more places, so probably best to just ignore them?

changelog: [`unnecessary_safety_comment`]: don't look for safety comments in doc tests
2024-01-05 15:23:11 +00:00
bors
2d6c2386f5 Auto merge of #12091 - samueltardieu:issue-12068, r=Alexendoo
Add .as_ref() to suggestion to remove .to_string()

The case of `.to_owned().split(…)` is treated specially in the `unnecessary_to_owned` lint. Test cases check that it works both for slices and for strings, but they missed a corner case: `x.to_string().split(…)` when `x` implements `AsRef<str>` but not `Deref<Target = str>`. In this case, it is wrong to suggest to remove `.to_string()` without adding `.as_ref()` instead.

Fix #12068

changelog: [`unnecessary_to_owned`]: suggest replacing `.to_string()` by `.as_ref()`
2024-01-05 14:54:40 +00:00
Matthew Jasper
f73e37d00c Update clippy for hir::Guard removal 2024-01-05 10:56:59 +00:00
bors
ee8bfb7f7a Auto merge of #12051 - y21:option_as_ref_cloned, r=dswij
new lint: `option_as_ref_cloned`

Closes #12009

Adds a new lint that looks for `.as_ref().cloned()` on `Option`s. That's the same as just `.clone()`-ing the option directly.

changelog: new lint: [`option_as_ref_cloned`]
2024-01-05 06:39:46 +00:00
Nicholas Nethercote
0bac101c21 Rename EmitterWriter as HumanEmitter.
For consistency with other `Emitter` impls, such as `JsonEmitter`,
`SilentEmitter`, `SharedEmitter`, etc.
2024-01-05 10:02:40 +11:00
bors
8507e4c80e Auto merge of #12090 - GuillaumeGomez:default-unconditional-recursion, r=llogiq
Extend `unconditional_recursion` lint to check for `Default` trait implementation

In case the `Default` trait is implemented manually and is calling a static method (let's call it `a`) and then `a` is using `Self::default()`, it makes an infinite call recursion difficult to see without debugging. This extension checks that there is no such recursion possible.

r? `@llogiq`

changelog: Extend `unconditional_recursion` lint to check for `Default` trait implementation
2024-01-04 19:45:20 +00:00
Guillaume Gomez
2666f39d3e Detect unconditional recursion between Default trait impl and static methods 2024-01-04 17:40:28 +01:00
Samuel Tardieu
e758413973 Add .as_ref() to suggestion to remove .to_string() 2024-01-04 17:29:20 +01:00
bors
ebf5c1a928 Auto merge of #12031 - y21:eager_transmute_more_binops, r=llogiq
Lint nested binary operations and handle field projections in `eager_transmute`

This PR makes the lint a bit stronger. Previously it would only lint `(x < 4).then_some(transmute(x))` (that is, a single binary op in the condition). With this change, it understands:
- multiple, nested binary ops: `(x < 4 && x > 1).then_some(...)`
- local references with projections: `(x.field < 4 && x.field > 1).then_some(transmute(x.field))`

changelog: [`eager_transmute`]: lint nested binary operations and look through field/array accesses

r? llogiq (since you reviewed my initial PR #11981, I figured you have the most context here, sorry if you are too busy with other PRs, feel free to reassign to someone else then)
2024-01-03 21:43:01 +00:00
bors
17dcd0d2e4 Auto merge of #12030 - torfsen:11973-fix-quoting-of-double-quote-in-char-literal, r=llogiq
11973: Don't escape `"` in `'"'`

Fixes #11973.

```
changelog: [`single_char_pattern`]: don't escape `"` in `'"'`
```
2024-01-03 21:30:01 +00:00
bors
bc962c246a Auto merge of #12071 - ShE3py:deadlinks, r=blyxyas
Remove deadlinks from `unchecked_duration_subtraction`

See <https://rust-lang.github.io/rust-clippy/master/index.html#unchecked_duration_subtraction>

changelog: [`unchecked_duration_subtraction`]: remove deadlinks
2024-01-03 20:04:56 +00:00
y21
5960107415 new lint: option_as_ref_cloned 2024-01-03 19:40:47 +01:00
Yuxiang Qiu
b5a2192628
fix: incorrect suggestions generated by manual_retain lint 2024-01-03 13:05:55 -05:00
cocodery
090c228873 Fix/Issue11932: assert* in multi-condition after unrolling will cause lint emit warning 2024-01-03 22:12:27 +08:00
bors
0153ca95ae Auto merge of #12062 - GuillaumeGomez:fix-false-positive-unconditional_recursion, r=xFrednet
Fix false positive `unconditional_recursion`

Fixes #12052.

Only checking if both variables are `local` was not enough, we also need to confirm they have the same type as `Self`.

changelog: Fix false positive for `unconditional_recursion` lint
2024-01-03 09:14:58 +00:00
bors
2eb13d3a7c Auto merge of #12056 - PartiallyTyped:12050, r=xFrednet
Fixes: #12050 - `identity_op` correctly suggests a deference for coerced references

When `identity_op` identifies a `no_op`, provides a suggestion, it also checks the type of the type of the variable. If the variable is a reference that's been coerced into a value, e.g.

```
let x = &0i32;
let _ = x + 0;
```

the suggestion will now use a derefence. This is done by identifying whether the variable is a reference to an integral value, and then whether it gets dereferenced.

changelog: false positive: [`identity_op`]: corrected suggestion for reference coerced to value.

fixes: #12050
2024-01-03 09:02:02 +00:00
Yuxiang Qiu
88541d6637
fix some typos 2024-01-02 19:21:51 -05:00
Jake Goulding
de06ce886e Address unused tuple struct fields in clippy 2024-01-01 17:47:54 -05:00
Lieselotte
ff2919ac5d
Remove deadlinks from unchecked_duration_subtraction 2024-01-01 18:50:58 +01:00
Quinn Sinclair
70024e16c0 New Lint: [thread_local_initializer_can_be_made_const]
Adds a new lint to suggest using `const` on `thread_local!`
initializers that can be evaluated at compile time.

Impl details:

The lint relies on the expansion of `thread_local!`. For non
const-labelled initializers, `thread_local!` produces a function
called `__init` that lazily initializes the value. We check the function
and decide whether the body can be const. The body of the function is
exactly the initializer. If so, we lint the body.

changelog: new lint [`thread_local_initializer_can_be_made_const`]
2024-01-01 18:06:10 +02:00
roife
094ce3de3e Add comments for unnecessary_fallible_conversions 2024-01-01 16:34:42 +08:00
roife
84e797499b Add autofix for functions in unnecessary_fallible_conversions 2024-01-01 16:17:22 +08:00
y21
ef35e82ea3 don't look for safety comments in codeblocks 2024-01-01 02:57:23 +01:00
bors
e1dbafd875 Auto merge of #12065 - samueltardieu:issue-12063, r=llogiq
Add `.front()` to `get_first` lint description

Fix #12063

changelog: none
2023-12-31 16:35:58 +00:00
Samuel Tardieu
457ab585fc Add .front() to get_first lint description 2023-12-31 15:38:38 +01:00
Florian Brucker
fe35e08e9f 8733: Suggest str.lines when splitting at hard-coded newlines
Adds a new `splitting_strings_at_newlines` lint that suggests to use
`str.lines` instead of splitting a trimmed string at hard-coded
newlines.
2023-12-31 13:30:36 +01:00
Guillaume Gomez
d3bde854c4 Fix false positive in PartialEq implementation 2023-12-31 11:20:49 +01:00
bors
44c99a8089 Auto merge of #11980 - GuillaumeGomez:UNCONDITIONAL_RECURSION-tostring, r=llogiq
Extend UNCONDITIONAL_RECURSION to check for ToString implementations

Follow-up of https://github.com/rust-lang/rust-clippy/pull/11938.

r? `@llogiq`

changelog: Extend `UNCONDITIONAL_RECURSION` to check for `ToString` implementations
2023-12-31 09:12:42 +00:00
bors
7f185bdef6 Auto merge of #12047 - ARandomDev99:12007-empty-enum-variants-with-brackets, r=Jarcho
New Lint: empty_enum_variants_with_brackets

This PR:
- adds a new early pass lint that checks for enum variants with no fields that were defined using brackets. **Category: Restriction**
- adds relevant UI tests for the new lint.

Closes #12007

```
changelog: New lint: [`empty_enum_variants_with_brackets`]
```
2023-12-30 19:01:53 +00:00
Aneesh Kadiyala
5f1718810f Change empty_enum_variants_with_brackets applicability to MaybeIncorrect 2023-12-30 22:22:44 +05:30
bors
0cc53f48f5 Auto merge of #11957 - J-ZhengLi:issue11535, r=Jarcho
don't lint [`default_numeric_fallback`] on return and local assigned macro calls with type stated

fixes: #11535

changelog: don't lint [`default_numeric_fallback`] on return and local assigned macro calls with type stated
2023-12-30 16:47:14 +00:00
bors
c6aeb28a7b Auto merge of #11865 - yuxqiu:map_unwrap_or_default, r=Jarcho
feat: add `manual_is_variant_and` lint

changelog: add a new lint [`manual_is_variant_and`].
- Replace `option.map(f).unwrap_or_default()` and `result.map(f).unwrap_or_default()` with `option.is_some_and(f)` and `result.is_ok_and(f)` where `f` is a function or closure that returns `bool`.
- MSRV is set to 1.70.0 for this lint; when `is_some_and` and `is_ok_and` was stabilised

---

For example, for the following code:

```rust
let opt = Some(0);
opt.map(|x| x > 1).unwrap_or_default();
```

It suggests to instead write:

```rust
let opt = Some(0);
opt.is_some_and(|x| x > 1)
```
2023-12-30 16:37:36 +00:00
bors
b19b5f293e Auto merge of #12008 - J-ZhengLi:issue9872, r=Jarcho
make [`mutex_atomic`] more type aware

fixes: #9872

---

changelog: [`mutex_atomic`] now suggests more specific atomic types and skips mutex i128 and u128
2023-12-30 16:29:13 +00:00
Guillaume Gomez
ab2d1c28d5 Extend UNCONDITIONAL_RECURSION to check for ToString implementations 2023-12-30 17:11:56 +01:00
cocodery
79e70ccf6f add setuid, setgid and sticky bits on high 3-bits of 12 2023-12-30 23:03:47 +08:00
Quinn Sinclair
c2b3f5c767 identity_op correctly suggests a deference for coerced references
When `identity_op` identifies a `no_op`, provides a suggestion, it also
checks the type of the type of the variable. If the variable is
a reference that's been coerced into a value, e.g.

```
let x = &0i32;
let _ = x + 0;
```

the suggestion will now use a derefence. This is done by identifying
whether the variable is a reference to an integral value, and then
whether it gets dereferenced.

changelog: false positive: [`identity_op`]: corrected suggestion for
reference coerced to value.

fixes: #12050
2023-12-30 13:31:32 +02:00
y21
0848e120b2 add expansion checks to iter_without_into_iter and into_iter_without_iter 2023-12-30 04:56:46 +01:00
cocodery
ca40b0c284 fix/issue#11243: allow 3-digit-grouped binary in non_octal_unix_permissions 2023-12-30 01:58:30 +08:00
Aneesh Kadiyala
1ee9993a96 add new lint, empty_enum_variants_with_brackets
- Add a new early pass lint.
- Add relevant UI tests.
2023-12-29 19:23:31 +05:30
bors
a4c2cf181b Auto merge of #119387 - flip1995:clippy-subtree-sync, r=matthiaskrgr
Clippy subtree update

r? `@Manishearth`
2023-12-29 12:39:43 +00:00
bors
174a0d7be6 Auto merge of #10283 - ParkMyCar:lint/pub_underscore_fields, r=blyxyas
feature: add new lint `pub_underscore_fields`

fixes: #10282

This PR introduces a new lint `pub_underscore_fields` that lints when a user has marked a field of a struct as public, but also prefixed it with an underscore (`_`). This is something users should avoid because the two ideas are contradictory. Prefixing a field with an `_` is inferred as the field being unused, but making a field public infers that it will be used.

- \[x] Followed [lint naming conventions][lint_naming]
  - I believe I followed the naming conventions, more than happy to update the naming if I did not :)
- \[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: [`pub_underscore_fields`]
[#10283](https://github.com/rust-lang/rust-clippy/pull/10283)
<!-- changelog_checked -->
2023-12-29 10:52:00 +00:00
Parker Timmerman
fa7dd1c4e0
add new lint, pub_underscore_fields
- add a new late pass lint, with config options
- add ui tests for both variations of config option
- update CHANGELOG.md

github feedback

bump version to 1.77 and run cargo collect-metadata

Change `,` to `;` in `conf.rs`
2023-12-29 11:44:34 +01:00
Michael Goulet
3fceca23bb Remove mitigations for incorrect node args 2023-12-29 05:16:53 +00:00
Philipp Krones
15b1edb209 Merge commit 'ac4c2094a6030530661bee3876e0228ddfeb6b8b' into clippy-subtree-sync 2023-12-28 19:33:07 +01:00
Philipp Krones
2a4c7d2b0f
Bump Clippy version -> 0.1.77 2023-12-28 19:21:01 +01:00
Philipp Krones
9ff84af787
Merge remote-tracking branch 'upstream/master' into rustup 2023-12-28 19:20:18 +01:00
Kevin Reid
b8aab4bd1d Polish missing_enforced_import_renames documentation
* Fixes a typo in the name of the lint (`enforce-import-renames`
  instead of `enforced-import-renames`).
* Copyedit “Why” paragraph.
* Make the example configuration use a multi-line list, since it is not
  particularly expected that a real project will have *exactly one*
  rename to enforce (and the old formatting had unbalanced whitespace).
2023-12-28 09:45:19 -08:00
Michael Goulet
99b4330f5c Remove movability from TyKind::Coroutine 2023-12-28 16:35:01 +00:00
y21
6c28f0765e recognize contains calls on ranges 2023-12-28 05:27:56 +01:00
y21
affde93041 lint on nested binary operations involving local and handle projections 2023-12-27 23:38:20 +01:00
Florian Brucker
e5c9fb6827 11973: Don't escape " in '"' 2023-12-27 22:26:25 +01:00
Florian Brucker
ebc0588937 6459: Check for redundant matches! with Ready, Pending, V4, V6 2023-12-27 19:10:04 +01:00
bors
c689d32a90 Auto merge of #11981 - y21:eager_int_transmute, r=llogiq
new lint: `eager_transmute`

A small but still hopefully useful lint that looks for patterns such as `(x < 5).then_some(transmute(x))`.
This is almost certainly wrong because it evaluates the transmute eagerly and can lead to surprises such as the check being completely removed and always evaluating to `Some` no matter what `x` is (it is UB after all when the integer is not a valid bitpattern for the transmuted-to type). [Example](https://godbolt.org/z/xoY34fPzh).
The user most likely meant to use `then` instead.

I can't remember where I saw this but this is inspired by a real bug that happened in practice.

This could probably be a correctness lint?

changelog: new lint: [`eager_int_transmute`]
2023-12-27 15:16:46 +00:00
y21
08d8ca9edd new lint: eager_int_transmute 2023-12-27 14:16:35 +01:00
Yuxiang Qiu
c4a80f2e3e
feat: add manual_is_variant_and lint 2023-12-26 17:49:51 -07:00
Quinn Sinclair
57dd25e2ff FP: needless_return_with_question_mark with implicit Error Conversion
Return with a question mark was triggered in situations where the `?`
desuraging was performing error conversion via `Into`/`From`.

The desugared `?` produces a match over an expression with type
`std::ops::ControlFlow<B,C>` with `B:Result<Infallible, E:Error>` and
`C:Result<_, E':Error>`, and the arms perform the conversion. The patch
adds another check in the lint that checks that `E == E'`. If `E == E'`,
then the `?` is indeed unnecessary.

changelog: False Positive: `needless_return_with_question_mark` when
implicit Error Conversion occurs.
2023-12-26 21:25:06 +02:00
bors
eb679c7f34 Auto merge of #12019 - xFrednet:changelog-1-75, r=flip1995
Changelog for Rust 1.75 🎄

Roses are red,
Violets are blue,
Another year of development,
And a strong team, too

---

### The cat of this release:

<img width=500 src="https://cdn2.thecatapi.com/images/49r.gif?api_key=live_iA7QQQ2LdohvDfCghXThmLqVYCZ9kXIwGMcwyJyaYyOTRC8NZSYqykPoc2UypsMi" alt="The cats of this Clippy release" />

<sub>The cat for the next release can be nominated in the comments</sub>

---

changelog: none
2023-12-26 19:23:16 +00:00
bors
9dd2252b2c Auto merge of #12004 - PartiallyTyped:11843, r=xFrednet
New lints `iter_filter_is_some` and `iter_filter_is_ok`

Adds a pair of lints that check for cases of an iterator over `Result` and `Option` followed by `filter` without being followed by `map` as that is covered already by a different, specialized lint.

Fixes #11843

PS, I also made some minor documentations fixes in a case where a double tick (`) was included.

---

changelog: New Lint: [`iter_filter_is_some`]
[#12004](https://github.com/rust-lang/rust/pull/12004)
changelog: New Lint: [`iter_filter_is_ok`]
[#12004](https://github.com/rust-lang/rust/pull/12004)
2023-12-26 15:41:40 +00:00
xFrednet
8990153997
Update version attribute for 1.75 lints 2023-12-26 16:00:53 +01:00
bors
91859ed80a Auto merge of #119258 - compiler-errors:closure-kind, r=eholk
Make closures carry their own ClosureKind

Right now, we use the "`movability`" field of `hir::Closure` to distinguish a closure and a coroutine. This is paired together with the `CoroutineKind`, which is located not in the `hir::Closure`, but the `hir::Body`. This is strange and redundant.

This PR introduces `ClosureKind` with two variants -- `Closure` and `Coroutine`, which is put into `hir::Closure`. The `CoroutineKind` is thus removed from `hir::Body`, and `Option<Movability>` no longer needs to be a stand-in for "is this a closure or a coroutine".

r? eholk
2023-12-26 04:25:53 +00:00
Michael Goulet
e0097f5323 Fix clippy's usage of Body's coroutine_kind
Also fixes a bug where we weren't peeling blocks from async bodies
2023-12-25 21:13:41 +00:00
bors
99c783843d Auto merge of #11967 - samueltardieu:issue-11959, r=llogiq
Do not consider `async { (impl IntoFuture).await }` as redundant

changelog: [`redundant_async_block`]: do not trigger on `IntoFuture` instances

Fix #11959
2023-12-25 12:42:26 +00:00
J-ZhengLi
a578b9ba0b make [mutex_atomic] more type aware 2023-12-25 14:28:01 +08:00
Quinn Sinclair
2177f2cb96 formatting 2023-12-24 14:42:18 +02:00
Quinn Sinclair
4b1ac31c18 Added MSRV and more tests, improved wording 2023-12-24 14:40:14 +02:00
Nicholas Nethercote
620a1e4c2f Remove Session methods that duplicate DiagCtxt methods.
Also add some `dcx` methods to types that wrap `TyCtxt`, for easier
access.
2023-12-24 08:05:28 +11:00
bors
370615bc78 Auto merge of #11997 - TethysSvensson:uninhabited-references-pedantic, r=xFrednet
Move `uninhabited_references` to `nursery`

I think this lint has too many false positives and should be put in pedantic. See #11984 and #11985 for context.

The lint is already in beta and is causing trouble for us, so I would also like this PR to be backported to beta as well.

changelog: Moved [`uninhabited_references`] to `nursery` (Now allow-by-default)
[#11997](https://github.com/rust-lang/rust-clippy/pull/11997)
(Check if this has been backported)

Fixes #11984.
2023-12-23 16:25:53 +00:00
bors
830f1c58f4 Auto merge of #11994 - y21:issue11993-fn, r=xFrednet
[`question_mark`]: also trigger on `return` statements

This fixes the false negative mentioned in #11993: the lint only used to check for `return` expressions, and not a statement containing a `return` expression (doesn't close the issue tho since there's still a useful suggestion that we could make, which is to suggest `.ok_or()?`/`.ok_or_else()?` for `else { return Err(..) }`)

changelog: [`question_mark`]: also trigger on `return` statements
2023-12-23 16:17:35 +00:00
Tethys Svensson
1576ecce40 Move uninhabited_references to nursery 2023-12-23 17:00:14 +01:00
Matthias Krüger
870a5d957b Rollup merge of #119231 - aDotInTheVoid:PatKind-struct-bool-docs, r=compiler-errors
Clairify `ast::PatKind::Struct` presese of `..` by using an enum instead of a bool

The bool is mainly used for when a `..` is present, but it is also set on recovery to avoid errors. The doc comment not describes both of these cases.

See cee794ee98/compiler/rustc_parse/src/parser/pat.rs (L890-L897) for the only place this is constructed.

r? ``@compiler-errors``
2023-12-23 16:23:54 +01:00
y21
e44caea259 respect comments in question_mark 2023-12-23 16:22:12 +01:00
y21
dfb4ff8bbf [question_mark]: also trigger on return statements 2023-12-23 16:22:08 +01:00
bors
618fd4b494 Auto merge of #11999 - Takashiidobe:fix-typo-in-infinite-loop-lint, r=xFrednet
fix typo in infinite loop lint

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

changelog: This fixes a small typo introduced in https://github.com/rust-lang/rust-clippy/pull/11829
2023-12-23 14:46:52 +00:00
bors
858d96d63a Auto merge of #11871 - GuillaumeGomez:UNNECESSARY_TO_OWNED-split, r=llogiq
Extend `UNNECESSARY_TO_OWNED` to handle `split`

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

When you have `to_string().split('a')` or equivalent, it'll suggest to remove the `to_owned`/`to_string` part.

r? `@flip1995`

changelog: Extend `UNNECESSARY_TO_OWNED` to handle `split`
2023-12-23 11:36:53 +00:00
Alona Enraght-Moony
d72771ffeb bool->enum for ast::PatKind::Struct presence of ..
See cee794ee98/compiler/rustc_parse/src/parser/pat.rs (L890-L897) for the only place this is constructed.
2023-12-23 02:50:31 +00:00
Michael Goulet
5a9c25cc84 Split coroutine desugaring kind from source 2023-12-22 23:58:29 +00:00
Takashi Idobe
9c2be205b3 fix typos in default constructed unit structs, implied bounds, ineffective open options 2023-12-22 18:54:48 -05:00
Takashi Idobe
67a33e8cc8 fix typo in infinite loop lint 2023-12-22 18:44:20 -05:00
bors
e0b25c5a64 Auto merge of #11998 - cocodery:fix/issue11762, r=llogiq
Check whether out of bound when access a known length array with a constant index

fixes [Issue#11762](https://github.com/rust-lang/rust-clippy/issues/11762)

Issue#11762 points that `Array references with known length are not flagged when indexed out of bounds`.

To fix this problem, it is needed to add check for `Expr::Index`. We expand this issue include reference and direct accessing a array.

When we access a array with a constant index `off`, and already know the length `size`, if `off >= size`, these code will throw an error, instead rustc's lint checking them or runtime panic happening.

changelog: [`out_of_bound_indexing`]: Add check for illegal accessing known length array with a constant index
2023-12-22 17:01:17 +00:00
bors
4ad06d1adf Auto merge of #118847 - eholk:for-await, r=compiler-errors
Add support for `for await` loops

This adds support for `for await` loops. This includes parsing, desugaring in AST->HIR lowering, and adding some support functions to the library.

Given a loop like:
```rust
for await i in iter {
    ...
}
```
this is desugared to something like:
```rust
let mut iter = iter.into_async_iter();
while let Some(i) = loop {
    match core::pin::Pin::new(&mut iter).poll_next(cx) {
        Poll::Ready(i) => break i,
        Poll::Pending => yield,
    }
} {
    ...
}
```

This PR also adds a basic `IntoAsyncIterator` trait. This is partly for symmetry with the way `Iterator` and `IntoIterator` work. The other reason is that for async iterators it's helpful to have a place apart from the data structure being iterated over to store state. `IntoAsyncIterator` gives us a good place to do this.

I've gated this feature behind `async_for_loop` and opened #118898 as the feature tracking issue.

r? `@compiler-errors`
2023-12-22 14:17:10 +00:00
cocodery
d020196dc0 Add check for illegal accessing known length array with a constant index 2023-12-22 20:17:43 +08:00
J-ZhengLi
a556d00c0a stop [bool_comparison]'s suggestion from consuming parentheses 2023-12-21 18:20:25 +08:00
Quinn Sinclair
25b9ca3f64 New lints iter_filter_is_some and iter_filter_is_ok
Adds a pair of lints that check for cases of an iterator over `Result`
and `Option` followed by `filter` without being followed by `map` as
that is covered already by a different, specialized lint.

changelog: New Lint: [`iter_filter_is_some`]
changelog: New Lint: [`iter_filter_is_ok`]
2023-12-21 00:16:47 +02:00
Alona Enraght-Moony
062845421b Give VariantData::Struct named fields, to clairfy recovered. 2023-12-20 00:07:34 +00:00
Eric Holk
212ea0359c Plumb awaitness of for loops 2023-12-19 12:26:20 -08:00
Guillaume Gomez
71ea36b539 Extend UNNECESSARY_TO_OWNED to handle split 2023-12-18 16:46:41 +01:00
Guillaume Gomez
1c431f4da9 Move check for PartialEq in UNCONDITIONAL_RECURSION lint into its own function 2023-12-18 16:36:52 +01:00
Nicholas Nethercote
d165a38de0 Rename many DiagCtxt and EarlyDiagCtxt locals. 2023-12-18 16:06:22 +11:00
Nicholas Nethercote
bc3a3bcf0c Rename ParseSess::with_span_handler as ParseSess::with_dcx. 2023-12-18 16:06:21 +11:00
Nicholas Nethercote
22e769c032 Rename Handler as DiagCtxt. 2023-12-18 16:06:19 +11:00
bors
dd857f8207 Auto merge of #11966 - StackOverflowExcept1on:issue-8159, r=Jarcho
Do not lint `assertions_on_constants` for `const _: () = assert!(expr)`

Fixes #8159

```rust
pub fn f() {
    // warning
    assert!(true);
    assert!(usize::BITS >= 32);

    // ok
    const _: () = assert!(usize::BITS >= 32);
}
```

changelog: Fix `const _: () = assert!(expr)` false positive on `assertions_on_constants` lint
2023-12-17 14:03:13 +00:00
Samuel Tardieu
4cea5a8f33 Do not suggest [T; n] instead of vec![T; n] if T is not Copy 2023-12-17 11:32:15 +01:00
bors
f9b5def2ae Auto merge of #11869 - PartiallyTyped:result-filter-map, r=Alexendoo
New Lint: `result_filter_map` / Mirror of `option_filter_map`

Added the `Result` mirror of `option_filter_map`.

changelog: New Lint: [`result_filter_map`]

I had to move around some code because the function def was too long 🙃.

I have also added some pattern checks on `option_filter_map`
2023-12-16 23:29:07 +00:00
bors
9907b90b1e Auto merge of #11938 - GuillaumeGomez:unconditional_recursion, r=llogiq
Add new `unconditional_recursion` lint

Currently, rustc `unconditional_recursion` doesn't detect cases like:

```rust
enum Foo {
    A,
    B,
}

impl PartialEq for Foo {
    fn eq(&self, other: &Self) -> bool {
        self == other
    }
}
```

This is because the lint is currently implemented only for one level, and in the above code, `self == other` will then call `impl PartialEq for &T`, escaping from the detection. The fix for it seems to be a bit tricky (I started investigating potential solution to add one extra level of recursion [here](https://github.com/rust-lang/rust/compare/master...GuillaumeGomez:rust:trait-impl-recursion?expand=1) but completely broken at the moment).

I expect that this situation will remain for a while. In the meantime, I think it's acceptable to check it directly into clippy for the time being as a lot of easy cases like this one can be easily checked (next I plan to extend it to cover other traits like `ToString`).

changelog: Add new `unconditional_recursion` lint
2023-12-16 18:21:01 +00:00
Guillaume Gomez
6b444f3092 Also check code generated by macros 2023-12-16 18:45:24 +01:00
y21
bc22407b79 add tests, lint on while let true and matches!(.., true) 2023-12-16 17:40:32 +01:00
y21
850d77ed55 [redundant_pattern_matching]: catch if let true 2023-12-16 16:37:58 +01:00
Philipp Krones
3596d44988 Merge commit 'a859e5cc1ce100df22346a1005da30532d04de59' into clippyup 2023-12-16 14:12:50 +01:00
Philipp Krones
80ccd6392f
Merge remote-tracking branch 'upstream/master' into rustup 2023-12-16 13:59:56 +01:00
Quinn Sinclair
8892420aa7 New Lint: Result_filter_map
Added the `Result` mirror of `option_filter_map` to catch

```
   .into_iter().filter(Result::is_ok).map(Result::unwrap)
```

changelog: New Lint: [`result_filter_map`]
Co-authored-by: Alex Macleod <alex@macleod.io>
2023-12-16 00:43:52 +01:00
Samuel Tardieu
e52405a859 Do not consider async { (impl IntoFuture).await } as redundant 2023-12-15 22:58:22 +01:00
StackOverflowExcept1on
90ece568d3
simplify pattern 2023-12-15 23:02:13 +03:00
StackOverflowExcept1on
058b74fce4
Do not lint assertions_on_constants for const _: () = assert!(expr) 2023-12-15 22:52:38 +03:00
Michael Goulet
d47b7bb7aa Appease the tools: clippy, rustdoc 2023-12-15 16:17:27 +00:00
Matthias Krüger
f90e8ef6b8 Rollup merge of #118888 - compiler-errors:uplift-more-things, r=jackh726
Uplift `TypeAndMut` and `ClosureKind` to `rustc_type_ir`

Uplifts `TypeAndMut` and `ClosureKind`

I know I said I was just going to get rid of `TypeAndMut` (https://github.com/rust-lang/types-team/issues/124) but I think this is much simpler, lol

r? `@jackh726` or `@lcnr`
2023-12-15 06:50:18 +01:00
J-ZhengLi
eae2317977 improve [cast_sign_loss], to skip warning on mathmatical expression that is always positive 2023-12-14 09:27:01 +08:00
bors
29bdc8b2bc Auto merge of #11953 - Jarcho:issue_11952, r=Alexendoo
Fix binder handling in `unnecessary_to_owned`

fixes #11952

The use of `rebind` instead of `EarlyBinder::bind` isn't technically needed, but it is the semantically correct operation.

changelog: None
2023-12-13 18:57:50 +00:00
bors
1839b79e51 Auto merge of #11956 - intgr:doc_markdown-include-function-parenthesis, r=Alexendoo
[`doc_markdown`] Recognize words followed by empty parentheses `()` for quoting

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

changelog: [`doc_markdown`] Recognize words followed by empty parentheses for quoting, e.g. `func()`.

---

Developers often write function/method names with trailing `()`, but `doc_markdown` lint did not consider that.

Old clippy suggestion was not very good:

```patch
-/// There is no try (do() or do_not()).
+/// There is no try (do() or `do_not`()).
```

New behavior recognizes function names such as `do()` even they contain no `_`/`::`; and backticks are suggested outside of the `()`:

```patch
-/// There is no try (do() or do_not()).
+/// There is no try (`do()` or `do_not()`).
```
2023-12-13 17:53:59 +00:00
J-ZhengLi
60c059114c [default_numeric_fallback]: don't lint on return and macro calls with stated type 2023-12-13 11:09:08 +08:00
Michael Goulet
20de341bb0 Uplift TypeAndMut 2023-12-12 23:24:44 +00:00
Marti Raudsepp
1f2ca8127c [doc_markdown] Recognize words followed by empty parenthesis () for quoting 2023-12-13 01:16:12 +02:00
bors
c19508b356 Auto merge of #11895 - ericwu2003:useless_vec-FP, r=blyxyas
Useless vec false positive

changelog: [`useless_vec`]: fix false positive in macros.

fixes #11861

We delay the emission of `useless_vec` lints to the check_crate_post stage, which allows us to effectively undo lints if we find that a `vec![]` expression is being used multiple times after macro expansion.
2023-12-12 22:57:24 +00:00
bors
2e96c74dce Auto merge of #11829 - J-ZhengLi:issue11438, r=matthiaskrgr
new lint to detect infinite loop

closes: #11438

changelog: add new lint to detect infinite loop

~*I'll change the lint name*~. Should I name it  `infinite_loop` or `infinite_loops` is fine? Ahhhh, English is hard...
2023-12-12 17:53:51 +00:00
Eric
884bec3d85 emit lints in check_crate_post for useless_vec
this fixes issue #11861 by adding an extra map to
keep track of which spans are ok to lint
2023-12-12 08:47:22 -08:00
zetanumbers
fe37cc1d97 Move some methods from tcx.hir() to tcx
Renamings:
- find -> opt_hir_node
- get -> hir_node
- find_by_def_id -> opt_hir_node_by_def_id
- get_by_def_id -> hir_node_by_def_id

Fix rebase changes using removed methods

Use `tcx.hir_node_by_def_id()` whenever possible in compiler

Fix clippy errors

Fix compiler

Apply suggestions from code review

Co-authored-by: Vadim Petrochenkov <vadim.petrochenkov@gmail.com>

Add FIXME for `tcx.hir()` returned type about its removal

Simplify with with `tcx.hir_node_by_def_id`
2023-12-12 06:40:29 -08:00
Guillaume Gomez
bd38ff3c9b Add new unconditional_recursion lint 2023-12-12 15:37:50 +01:00
Guillaume Gomez
19f5b85330 Add write_and_append lint 2023-12-12 14:56:34 +01:00
Jason Newcomb
27c5b21fb6 Fix binder handling in unnecessary_to_owned 2023-12-11 13:52:55 -05:00
bors
c8213a49bb Auto merge of #117758 - Urgau:lint_pointer_trait_comparisons, r=davidtwco
Add lint against ambiguous wide pointer comparisons

This PR is the resolution of https://github.com/rust-lang/rust/issues/106447 decided in https://github.com/rust-lang/rust/issues/117717 by T-lang.

## `ambiguous_wide_pointer_comparisons`

*warn-by-default*

The `ambiguous_wide_pointer_comparisons` lint checks comparison of `*const/*mut ?Sized` as the operands.

### Example

```rust
let ab = (A, B);
let a = &ab.0 as *const dyn T;
let b = &ab.1 as *const dyn T;

let _ = a == b;
```

### Explanation

The comparison includes metadata which may not be expected.

-------

This PR also drops `clippy::vtable_address_comparisons` which is superseded by this one.

~~One thing: is the current naming right? `invalid` seems a bit too much.~~

Fixes https://github.com/rust-lang/rust/issues/117717
2023-12-11 14:33:16 +00:00
bors
1f9b674bbf Auto merge of #118661 - fee1-dead-contrib:restore-const-partialEq, r=compiler-errors
Restore `const PartialEq`

And thus fixes a number of tests. There is a bug that still needs to be fixed, so WIP for now.

r? `@compiler-errors`
2023-12-11 10:34:51 +00:00
bors
2a1645d009 Auto merge of #11878 - samueltardieu:uninhabited_reference, r=flip1995
uninhabited_reference: new lint

Close #11851

The lint is implemented on function parameters and return types, as this is the place where the risk of exchanging references to uninhabited types is the highest. Other constructs, such as in a local variable,
would require the use of `unsafe` and will clearly be done on purpose.

changelog: [`uninhabited_reference`]: new lint
2023-12-11 09:28:54 +00:00
Nicholas Nethercote
e35acc2def Add spacing information to delimiters.
This is an extension of the previous commit. It means the output of
something like this:
```
stringify!(let a: Vec<u32> = vec![];)
```
goes from this:
```
let a: Vec<u32> = vec![] ;
```
With this PR, it now produces this string:
```
let a: Vec<u32> = vec![];
```
2023-12-11 09:36:40 +11:00
Jason Newcomb
f3f2f17478 Delay several is_from_proc_macro checks 2023-12-10 15:36:35 -05:00
Deadbeef
782520088f fix clippy 2023-12-10 13:10:46 +00:00
surechen
0109fa6b49 remove redundant imports
detects redundant imports that can be eliminated.

for #117772 :

In order to facilitate review and modification, split the checking code and
removing redundant imports code into two PR.
2023-12-10 10:56:22 +08:00
Jubilee Young
9083b52122 Check $CARGO before $PATH 2023-12-09 14:08:03 -08:00
bors
0252580e72 Auto merge of #118420 - compiler-errors:async-gen, r=eholk
Introduce support for `async gen` blocks

I'm delighted to demonstrate that `async gen` block are not very difficult to support. They're simply coroutines that yield `Poll<Option<T>>` and return `()`.

**This PR is WIP and in draft mode for now** -- I'm mostly putting it up to show folks that it's possible. This PR needs a lang-team experiment associated with it or possible an RFC, since I don't think it falls under the jurisdiction of the `gen` RFC that was recently authored by oli (https://github.com/rust-lang/rfcs/pull/3513, https://github.com/rust-lang/rust/issues/117078).

### Technical note on the pre-generator-transform yield type:

The reason that the underlying coroutines yield `Poll<Option<T>>` and not `Poll<T>` (which would make more sense, IMO, for the pre-transformed coroutine), is because the `TransformVisitor` that is used to turn coroutines into built-in state machine functions would have to destructure and reconstruct the latter into the former, which requires at least inserting a new basic block (for a `switchInt` terminator, to match on the `Poll` discriminant).

This does mean that the desugaring (at the `rustc_ast_lowering` level) of `async gen` blocks is a bit more involved. However, since we already need to intercept both `.await` and `yield` operators, I don't consider it much of a technical burden.

r? `@ghost`
2023-12-08 19:13:57 +00:00
Michael Goulet
1512d37af5 coro_kind -> coroutine_kind 2023-12-08 17:23:25 +00:00
bors
f39d18b7a0 Auto merge of #118527 - Nadrieril:never_patterns_parse, r=compiler-errors
never_patterns: Parse match arms with no body

Never patterns are meant to signal unreachable cases, and thus don't take bodies:
```rust
let ptr: *const Option<!> = ...;
match *ptr {
    None => { foo(); }
    Some(!),
}
```
This PR makes rustc accept the above, and enforces that an arm has a body xor is a never pattern. This affects parsing of match arms even with the feature off, so this is delicate. (Plus this is my first non-trivial change to the parser).

~~The last commit is optional; it introduces a bit of churn to allow the new suggestions to be machine-applicable. There may be a better solution? I'm not sure.~~ EDIT: I removed that commit

r? `@compiler-errors`
2023-12-08 17:08:52 +00:00
Samuel Tardieu
cdfa38a9d1 new lint: uninhabited_reference 2023-12-08 17:21:30 +01:00
bors
1c8cbe79ab Auto merge of #11907 - cocodery:issue11885, r=y21,xFrednet
Add a function to check whether binary oprands are nontrivial

fixes [#issue11885](https://github.com/rust-lang/rust-clippy/issues/11885)

It's hard to check whether operator is overrided through context of lint.
So, assume non-trivial structure like tuple, array or sturt, using a overrided binary operator in this lint, which might cause a side effict.
This is not detected before.
Althrough this might weaken the ability of this lint, it may more useful than before. Maybe this lint will cause an error, but now, it not. And assuming side effect of non-trivial structure with operator  is not a bad thing, right?

changelog: Fix: [`no_effect`] check if binary operands are nontrivial
2023-12-08 13:39:47 +00:00
cocodery
56d20c2b53 Fix nits and add test for unnecessary_operation 2023-12-08 21:33:28 +08:00
bors
2793e8d103 Auto merge of #11913 - KisaragiEffective:fix/ptr-as-ptr-with-null, r=llogiq
fix(ptr_as_ptr): handle `std::ptr::null{_mut}`

close rust-lang#11066
close rust-lang#11665
close rust-lang#11911

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

changelog: [`ptr_as_ptr`]: handle `std::ptr::null` and `std::ptr::null_mut`
2023-12-06 13:53:07 +00:00
Urgau
a2ea760b88 Drop clippy::vtable_address_comparisons 2023-12-06 09:03:48 +01:00
cocodery
ee2354badf Add check for unary-operator
Fix typo and add test for unary-opeator
2023-12-06 12:17:48 +08:00
bors
4a56563154 Auto merge of #11900 - Enselic:needless-borrow-drop, r=Manishearth
needless_borrows_for_generic_args: Handle when field operand impl Drop

Before this fix, the lint had a false positive, namely when a reference was taken to a field when the field operand implements a custom Drop. The compiler will refuse to partially move a type that implements Drop, because that would put the type in a weird state.

## False Positive Example (Fixed)

```rs
struct CustomDrop(String);

impl Drop for CustomDrop {
    fn drop(&mut self) {}
}

fn check_str<P: AsRef<str>>(_to: P) {}

fn test() {
    let owner = CustomDrop(String::default());
    check_str(&owner.0); // Don't lint. `owner` can't be partially moved because it impl Drop
}
```

changelog: [`needless_borrows_for_generic_args`]: Handle when field operand impl Drop
2023-12-05 19:10:09 +00:00
bors
42b017d625 Auto merge of #11920 - KisaragiEffective:patch-2, r=xFrednet
docs(explicit_write): add missing backtick to complete code snippet

close #11918

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

changelog: [`explicit_write`]: add missing backtick to document to complete code snippet
2023-12-05 18:45:35 +00:00
bors
8fc8aa98d6 Auto merge of #11904 - pgerber:regex, r=xFrednet
Update regex-syntax to support new word boundry assertions

From the regex v1.10.0 release notes [1]:

    This is a new minor release of regex that adds support for start
    and end word boundary assertions. [...]

    The new word boundary assertions are:

        • \< or \b{start}: a Unicode start-of-word boundary (\W|\A
          on the left, \w on the right).
        • \> or \b{end}: a Unicode end-of-word boundary (\w on the
          left, \W|\z on the right)).
        • \b{start-half}: half of a Unicode start-of-word boundary
          (\W|\A on the left).
        • \b{end-half}: half of a Unicode end-of-word boundary
          (\W|\z on the right).

[1]: https://github.com/rust-lang/regex/blob/master/CHANGELOG.md#1100-2023-10-09

changelog: [`regex`]: add support for start and end word boundary assertions ("\<", "\b{start}", etc.) introduced in regex v0.10
2023-12-05 18:34:58 +00:00
cocodery
2e3c031528 Rename has_nontrivial_oprand to is_operator_overrided
Simpfy code of `is_operator_overrided`, directly use `is_method_call` to
check
if operator is overrided, at least one oprand of binary-expr must be ADT-type
So no need to check type of lhs and rhs
2023-12-05 09:29:20 +08:00
Eric Holk
5f191ce9b9 Fix build 2023-12-04 16:46:45 -08:00
Eric Holk
594a5f18a7 Update doctest 2023-12-04 16:37:45 -08:00
Eric Holk
c9eb8c9df6 Remove bad merge 2023-12-04 14:38:10 -08:00
Eric Holk
45be5dd8e6 Option<CoroutineKind> 2023-12-04 13:03:37 -08:00
Eric Holk
b4e3b859f1 Merge Async and Gen into CoroutineKind 2023-12-04 12:48:01 -08:00
cocodery
89774234be Rewrite logic of has_nontrivial_oprand.
Check whether operator is overrided with a `struct` operand.
The struct here refers to `struct`, `enum`, `union`.
Add and fix test for `no_effect` lint.
2023-12-04 15:57:27 +08:00
Kisaragi
a3ce379adc
docs(explicit_write): add missing backtick to complete code snippet 2023-12-04 08:03:39 +09:00
Nadrieril
7ffe1ff55f Parse a pattern with no arm 2023-12-03 12:25:46 +01:00
Kisaragi Marine
8eea8b1577
fix: handle std::ptr::null{_mut}
close rust-lang#11066
close rust-lang#11665
close rust-lang#11911
2023-12-03 10:38:46 +09:00
Peter Gerber
af1b58fa39
Update regex-syntax to support new word boundry assertions
From the regex v1.10.0 release notes [1]:

    This is a new minor release of regex that adds support for start
    and end word boundary assertions. [...]

    The new word boundary assertions are:

        • \< or \b{start}: a Unicode start-of-word boundary (\W|\A
          on the left, \w on the right).
        • \> or \b{end}: a Unicode end-of-word boundary (\w on the
          left, \W|\z on the right)).
        • \b{start-half}: half of a Unicode start-of-word boundary
          (\W|\A on the left).
        • \b{end-half}: half of a Unicode end-of-word boundary
          (\W|\z on the right).

[1]: https://github.com/rust-lang/regex/blob/master/CHANGELOG.md#1100-2023-10-09
2023-12-02 19:44:36 +00:00
cocodery
6d40b105ed Add a function to check whether binary oprands are nontrivial
It's hard to check whether oprator is overrided through context of lint
So assume nontrivial has overrided binary operator
2023-12-03 00:58:47 +08:00
bors
31aa0b2bbe Auto merge of #11899 - samueltardieu:redundant-if, r=llogiq
Do not check twice whether `qpath` is a `QPath::TypeRelative` variant

This is a style fix: the outer `if` check was useless.

changelog: none
2023-12-02 14:33:24 +00:00
bors
75bdbfcea5 Auto merge of #11853 - J-ZhengLi:issue11814, r=llogiq
expending lint [`blocks_in_if_conditions`] to check match expr as well

closes: #11814

changelog: rename lint `blocks_in_if_conditions` to [`blocks_in_conditions`] and expand it to check blocks in match scrutinees
2023-12-02 14:03:46 +00:00
bors
ee8376075d Auto merge of #11837 - y21:issue11835, r=dswij
[`missing_asserts_for_indexing`]: accept length equality checks

Fixes #11835

The lint now allows indexing with indices 0 and 1 when an `assert!(x.len() == 2);` is found.
(Also fixed a typo in the doc example)

changelog: [`missing_asserts_for_indexing`]: accept len equality checks as a valid assertion
2023-12-01 19:02:59 +00:00
bors
5ac76ac54f Auto merge of #11597 - y21:repeat_vec_with_capacity, r=dswij
new lint: `repeat_vec_with_capacity`

Closes #11537

[Lint description](https://github.com/y21/rust-clippy/blob/repeat_vec_with_capacity/clippy_lints/src/repeat_vec_with_capacity.rs#L14) should explain this PR :)

changelog: new lint: `repeat_vec_with_capacity`
2023-12-01 18:00:50 +00:00
Philipp Krones
c9a43b18f1 Merge commit 'f0cdee4a3f094416189261481eae374b76792af1' into clippy-subtree-sync 2023-12-01 18:21:58 +01:00
Philipp Krones
a9867e1847
Merge remote-tracking branch 'upstream/master' into rustup 2023-12-01 18:06:03 +01:00
y21
76eb781336 use iter::repeat_with in suggestion and add examples 2023-12-01 17:24:34 +01:00
y21
504941591f new lint: repeat_vec_with_capacity 2023-12-01 16:52:34 +01:00
Martin Nordholts
512f302fd2 needless_borrows_for_generic_args: Handle when field operand impl Drop
Before this fix, the lint had a false positive, namely when a reference
was taken to a field when the field operand implements a custom Drop.
The compiler will refuse to partially move a type that implements Drop,
because that would put the operand in a weird state. See added
regression test.
2023-12-01 09:14:56 +01:00
Samuel Tardieu
6275e77e6a Do not check twice whether qpath is a QPath::TypeRelative variant 2023-11-30 18:07:43 +01:00
clubby789
2cda044f8c Allow allowing upper_case_acronyms on enum variants 2023-11-30 16:00:40 +00:00
bors
646b28f5f6 Auto merge of #11896 - samueltardieu:issue-11893, r=Alexendoo
`option_if_let_else`: do not trigger on expressions returning `()`

Fix #11893

Trigerring on expressions returning `()` uses the arguments of the `map_or_else()` rewrite only for their side effects. This does lead to code which is harder to read than the original.

changelog: [`option_if_let_else`]: do not trigger on unit expressions
2023-11-30 15:17:29 +00:00
bors
665fd5219a Auto merge of #11872 - llogiq:test-attr-in-doctest, r=xFrednet
add lint against unit tests in doctests

During RustLab, Alice Ryhl brought to my attention that the Andoid team stumbled over the fact that if one attempts to write a unit test within a doctest, it will be summarily ignored. So this lint should help people wondering why their tests won't run.

---

changelog: New lint: [`test_attr_in_doctest`]
[#11872](https://github.com/rust-lang/rust-clippy/pull/11872)
2023-11-30 10:24:16 +00:00
J-ZhengLi
40b558af76 rename [blocks_in_if_conditions] to [blocks_in_conditions];
add more test cases with `match`;
minor fixes in message output regarding review feedback
2023-11-30 15:41:54 +08:00
J-ZhengLi
fff7aa0e18 expending lint [blocks_in_if_conditions] to check match expr as well 2023-11-30 14:44:27 +08:00
Samuel Tardieu
e3c73f17ec option_if_let_else: do not trigger on expressions returning ()
Fix #11893

Trigerring on expressions returning `()` uses the arguments of the
`map_or_else()` rewrite only for their side effects. This does lead
to code which is harder to read than the original.
2023-11-29 19:38:02 +01:00
bors
8b0bf6423d Auto merge of #11818 - y21:more_redundant_guards, r=llogiq
[`redundant_guards`]: catch `is_empty`, `starts_with` and `ends_with` on slices and `str`s

Fixes #11807

Few things worth mentioning:
- Taking `snippet`s is now done at callsite, instead of passing a span and doing it in `emit_redundant_guards`. This is because we now need custom suggestion strings in certain places, like `""` for `str::is_empty`.
- This now uses `snippet` instead of `snippet_with_applicability`. I don't think this really makes any difference for `MaybeIncorrect`, though?
- This could also lint byte strings, as they're of type `&[u8; N]`, but that can be ugly so I decided to leave it out for now

changelog: [`redundant_guards`]: catch `str::is_empty`, `slice::is_empty`, `slice::starts_with` and `slice::ends_with`
2023-11-29 13:20:59 +00:00
Matthias Krüger
071f8f610d Rollup merge of #118157 - Nadrieril:never_pat-feature-gate, r=compiler-errors
Add `never_patterns` feature gate

This PR adds the feature gate and most basic parsing for the experimental `never_patterns` feature. See the tracking issue (https://github.com/rust-lang/rust/issues/118155) for details on the experiment.

`@scottmcm` has agreed to be my lang-team liaison for this experiment.
2023-11-29 12:34:47 +01:00
Nadrieril
02e50f03bf Add never_patterns feature gate 2023-11-29 03:58:29 +01:00
Andre Bogus
0ba9bf9f9a add lint against unit tests in doctests 2023-11-28 21:29:08 +01:00
bors
57397a5190 Auto merge of #11363 - KisaragiEffective:fix_redundant_closure_call_on_closure_returns_async_block, r=llogiq
[`redundant_closure_call`]: avoid duplicated `async` keyword when triggering on closure that returns `async` block

close #11357

----

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

changelog: [`redundant_closure_call`]: avoid duplicated `async` keyword when triggering on closure that returns `async` block
2023-11-28 20:27:48 +00:00
y21
0565267f37 rename DocMarkdown to Documentation 2023-11-28 19:14:37 +01:00
J-ZhengLi
758d0e8661 change name to [infinite_loop];
& apply review suggestions;
2023-11-28 10:28:55 +08:00
Nicholas Nethercote
684c4bfef1 Rework ast::BinOpKind::to_string and ast::UnOp::to_string.
- Rename them both `as_str`, which is the typical name for a function
  that returns a `&str`. (`to_string` is appropriate for functions
  returning `String` or maybe `Cow<'a, str>`.)
- Change `UnOp::as_str` from an associated function (weird!) to a
  method.
- Avoid needless `self` dereferences.
2023-11-28 09:42:07 +11:00
bors
e6f33905e8 Auto merge of #11836 - lukaslueg:issue11831, r=Alexendoo
Don't suggest `a.mul_add(b, c)` if parameters are not float

clippy::suboptimal_flops used to not check if the second parameter to f32/f64.mul_add() was float. Since the method is only defined to take `Self` as parameters, the suggestion was wrong.

Fixes #11831

changelog: [`suboptimal_float`]: Don't suggest `a.mul_add(b, c)` if parameters are not f32/f64
2023-11-27 20:37:34 +00:00
bors
003e910760 Auto merge of #11817 - y21:ptr_arg_mut_ref, r=Alexendoo
[`ptr_arg`]: recognize methods that also exist on slices

Fixes #11816

Not a new lint, just a very small improvement to the existing `ptr_arg` lint which would have caught the linked issue.

The problem was that the lint checks if a `Vec`-specific method was called, that is, if the receiver is `Vec<_>`.
This is the case for `len` and `is_empty`, however these methods also exist on slices so we can still lint there.
This logic exists in a different lint, so we can just reuse that here.

Interestingly, there was even a comment up top that explained what it should have been doing, but the logic for it just wasn't there?

changelog: [`ptr_arg`]: recognize methods that also exist on slices

<sub>Also, this is my 100th PR to clippy 🎉 </sub>
2023-11-27 20:26:31 +00:00
bors
caa73941f8 Auto merge of #11879 - samueltardieu:issue-11876, r=Alexendoo
`manual_try_fold`: check that `fold` is really `Iterator::fold`

Fix #11876

changelog: [`manual_try_fold`]: suggest using `try_fold` only for `Iterator::fold` uses
2023-11-27 20:18:40 +00:00
Kisaragi Marine
0426913ca9
fix dogfood 2023-11-28 00:40:13 +09:00
Kisaragi Marine
33182495ac
don't add paren on occurrences that is in call args 2023-11-28 00:27:51 +09:00
Kisaragi Marine
1661e7ee76
re-implement fix for rust-lang#11357 2023-11-27 23:43:39 +09:00
J-ZhengLi
0d26f9183b eliminate the second visit to save a bit performance.
Thanks @y21 for the hint!
2023-11-27 10:30:47 +08:00
bors
f30a859ae3 Auto merge of #11867 - y21:implied_bounds_in_impls_complexity, r=Jarcho
Move `implied_bounds_in_impls` back to complexity

This lint was originally in the complexity category when I PR'd it. It was then moved to nursery by me due to a number of issues (a false positive, an invalid suggestion and an ICE), but that was probably an overreaction and all of the issues were fixed quickly after.
This is a useful lint imo and there hasn't been any issues with it in a few months, so I say we should give it another try and move it back to complexity.

I did a lintcheck run on the top 400 crates and all of them are legitimate, with 18 warnings. Most of them are from anstyle having a `impl Display + Copy + Clone` return type, or the bitvec crate with a return type like `impl Iterator + DoubleEndedIterator`.

changelog: Move [`implied_bounds_in_impls`] to `complexity` (Now warn-by-default)
[#11867](https://github.com/rust-lang/rust-clippy/pull/11867)
2023-11-26 22:28:13 +00:00
Samuel Tardieu
0d09cb0a6b manual_try_fold: check that fold is really Iterator::fold 2023-11-26 22:46:13 +01:00
Samuel Tardieu
23d533264f Fix box_default behaviour with empty vec![] coming from macro arg 2023-11-26 18:40:50 +01:00
Vadim Petrochenkov
bf86fe130c rustc: hir().local_def_id_to_hir_id() -> tcx.local_def_id_to_hir_id() cleanup 2023-11-26 12:41:21 +03:00
bors
a79a7d6510 Auto merge of #118250 - petrochenkov:optdefkind, r=compiler-errors
rustc: Make `def_kind` mandatory for all `DefId`s

Prerequisite for https://github.com/rust-lang/rust/pull/118188.
2023-11-26 04:44:20 +00:00
Michael Goulet
fffee10632 Appease the clippy 2023-11-25 18:02:11 +00:00
Alex Macleod
7093444bfa Use absolute path for declare_tool_lint in declare_clippy_lint 2023-11-25 17:45:27 +00:00
y21
5689a86fb8 move implied_bounds_in_impls to complexity 2023-11-25 13:54:37 +01:00
Vadim Petrochenkov
bafa200f6e rustc: Make def_kind mandatory for all DefIds 2023-11-25 14:49:43 +03:00
bors
3664d6328d Auto merge of #11864 - GuillaumeGomez:option_map_or_err_ok, r=flip1995
Create new lint `option_map_or_err_ok`

Fixes #10045.

For the following code:

```rust
let opt = Some(1);
opt.map_or(Err("error"), Ok);
```

It suggests to instead write:

```rust
let opt = Some(1);
opt.ok_or("error");
```

r? `@flip1995`

changelog: Create new lint `option_map_or_err_ok`
2023-11-25 11:35:46 +00:00
bors
fbf13cea16 Auto merge of #11866 - GuillaumeGomez:simplify-code-result_map_or_else_none, r=flip1995
Simplify code for `result_map_or_else_none`

As mentioned in https://github.com/rust-lang/rust-clippy/pull/11864.

r? `@flip1995`

changelog: Simplify code for `result_map_or_else_none`
2023-11-25 11:24:17 +00:00
Guillaume Gomez
148cd04140 Simplify code for result_map_or_else_none 2023-11-25 11:07:59 +01:00
bors
6cfbe57075 Auto merge of #11862 - christophbeberweil:7125-single-element-loop-over-range, r=llogiq
suggest alternatives to iterate an array of ranges

works towards #7125
changelog: [`single_element_loop`]: suggest better syntax when iterating over an array of a single range

`@thinkerdreamer` and myself worked on this issue during a workshop by `@llogiq` at the RustLab 2023 conference. It is our first contribution to clippy.

When iterating over an array of only one element, _which is a range_, our change suggests to replace the array with the contained range itself. Additionally, a hint is printed stating that the user probably intended to iterate over the range and not the array. If the single element in the array is not a range, the previous suggestion in the form of `let {pat_snip} = {prefix}{arg_snip};{block_str}`is used.

This change lints the array with the single range directly, so any prefixes or suffixes are covered as well.
2023-11-24 17:15:33 +00:00
Guillaume Gomez
ea733172e6 Create new lint option_map_or_err_ok 2023-11-24 18:14:34 +01:00
Christoph Beberweil
f9c6335a0f feat: 7125 code snippets are wrapped in backticks 2023-11-24 17:47:31 +01:00
Christoph Beberweil
bce869f0c0 fix: 7125 lint message should start with a small letter 2023-11-24 17:29:03 +01:00
bors
3e7a63b8d1 Auto merge of #11863 - smoelius:patch-1, r=dswij
Nit re `matches!` formatting

I think formatting `matches!` with `if` guards is [still unsupported](https://github.com/rust-lang/rustfmt/issues/5547), which is probably why this was missed.

changelog: none
2023-11-24 14:58:07 +00:00
bors
e075823e2c Auto merge of #11850 - Nilstrieb:tbd, r=dswij
[`deprecated_semver`]: Allow `#[deprecated(since = "TBD")]`

"TBD" is allowed by rustdoc, saying that it will be deprecated in a future version. rustc will also not actually warn on it.
I found this while checking the rust-lang/rust with clippy.

changelog: [`deprecated_semver`]: allow using `since = "TBD"`
2023-11-24 14:46:50 +00:00
bors
96eab0655f Auto merge of #11859 - y21:issue11856, r=blyxyas
[`missing_asserts_for_indexing`]: work with bodies instead of blocks separately

Fixes #11856

Before this change, this lint would check blocks independently of each other, which means that it misses `assert!()`s from parent blocks.
```rs
// check_block
assert!(x.len() > 1);

{
  // check_block
  // no assert here
  let _ = x[0] + x[1];
}
```

This PR changes it to work with bodies rather than individual blocks. That means that a function will be checked in one go and we can remember if an `assert!` occurred anywhere.

Eventually it would be nice to have a more control flow-aware analysis, possibly by rewriting it as a MIR lint, but that's more complicated and I wanted this fixed first.

changelog: [`missing_asserts_for_indexing`]: accept `assert!`s from parent blocks
2023-11-24 12:18:11 +00:00
Samuel Moelius
4937fba456
Nit re matches! formatting 2023-11-24 07:10:28 -05:00
Christoph Beberweil
2512341fe4 feat: 7125 shorten lint text 2023-11-24 10:38:45 +01:00
Christoph Beberweil
c58d692e1f fix: 7125 update lint applicability to Unspecified 2023-11-24 10:30:19 +01:00
Christoph Beberweil
447edf92b4 suggest alternatives to iterate an array of ranges
Co-authored-by: ThinkerDreamer <74881094+ThinkerDreamer@users.noreply.github.com>
2023-11-23 23:07:36 +01:00
Guillaume Gomez
6c84b96886 Improve error messages format 2023-11-23 13:32:41 +01:00
Guillaume Gomez
2817c5fc14 Extend result_map_or_into_option lint to handle Result::map_or_else(|_| None, Some) 2023-11-23 10:57:37 +01:00
y21
553857bb2b check on a per-body level instead of blocks independently 2023-11-23 09:31:49 +01:00
bors
c24784ed81 Auto merge of #11757 - matthri:iter-kv-map-msrv-fix, r=Alexendoo
Fix iter_kv_map false positive into_keys and into_values suggestion

fixes: #11752

changelog: [`iter_kv_map`]: fix false positive: Don't suggest `into_keys()` and `into_values()` if the MSRV is to low
2023-11-22 20:39:44 +00:00
bors
a72730e9a1 Auto merge of #11844 - GuillaumeGomez:manual_non_exhaustive-rm-underscore-check, r=flip1995
Remove underscore check for `manual_non_exhaustive` lint

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

As indicated in https://github.com/rust-lang/rust-clippy/pull/10559, the underscore check should be removed.

changelog: remove underscore check for `manual_non_exhaustive` lint

r? `@blyxyas`
2023-11-22 13:37:31 +00:00
Guillaume Gomez
91fc4b3001 Remove underscore check for manual_non_exhaustive lint 2023-11-22 13:42:13 +01:00
bors
a8b0e5ffad Auto merge of #11627 - y21:issue11616, r=giraffate
[`needless_return_with_question_mark`]: don't lint if never type is used for coercion

Fixes #11616

When we have something like
```rs
let _x: String = {
  return Err(())?;
};
```
we shouldn't suggest removing the `return` because the `!`-ness of `return` is used to coerce the enclosing block to some other type. That will lead to a typeck error without a diverging expression like `return`.

changelog: [`needless_return_with_question_mark`]: don't lint if `return`s never typed-ness is used for coercion
2023-11-22 04:49:00 +00:00
Nicholas Nethercote
fa7cd2548c Update itertools to 0.11.
Because the API for `with_position` improved in 0.11 and I want to use
it.
2023-11-22 08:13:21 +11:00
Nilstrieb
43d8d51b6d Allow #[deprecated(since = "TBD")]
"TBD" is allowed by rustdoc, saying that it will be deprecated in a future version.
rustc will also not actually warn on it.
2023-11-21 22:03:00 +01:00
y21
a74fa97fab [needless_return_with_question_mark]: dont lint in case of coercion 2023-11-21 12:02:12 +01:00
Guillaume Gomez
abd9deb9f4 [missing_safety_doc], [unnecessary_safety_doc], [missing_panics_doc], [missing_errors_doc]: Added the [check-private-items] configuration to enable lints on private items.
[#11842](https://github.com/rust-lang/rust-clippy/pull/11842)
2023-11-21 11:42:42 +01:00
J-ZhengLi
3e9a6d142e stop warning never-returning calls
and add more test cases
2023-11-21 16:18:18 +08:00
bors
72c0d80f46 Auto merge of #11801 - y21:split_doc_pass, r=blyxyas
Split `doc.rs` up into a subdirectory

So, first, sorry for the bad diff. 😅

In #11798, `@flip1995`  suggested splitting `doc.rs` up, much like how we have the `methods/`, `matches/`, `types/` subdirectories.
I agree with this, the file is getting bigger as we add more and more doc lints that it makes sense to do this refactoring.

This is purely an internal change that moves things around a bit.
(**EDIT:** depending on the outcome of https://github.com/rust-lang/rust-clippy/pull/11801#issuecomment-1816715615 , this may change the lint group name from `doc_markdoc` to `doc`).

I tried to not change any of the actual logic of the lints and as such some things weren't as easy to move to a separate file. So we still have some `span_lint*` calls in the `doc/mod.rs` file, which I think is fine. This is also the case in `methods/mod.rs`.

Also worth mentioning that the lints missing_errors_doc, missing_panics_doc, missing_safety_doc and unnecessary_safety_doc have a lot of the same logic so it didn't make much sense for each of these to be in their own file. Instead I just put them all in `missing_headers.rs`

I also added a bit of documentation to the involved `check_{attrs,doc}` methods.

changelog: none
2023-11-20 17:22:05 +00:00
ofeeg
34d9e88a47
New lint clippy::join_absolute_paths
* `join_absolute_paths` Address PR review
* Move `clippy::join_absolute_paths` to `clippy::suspicious`
* `join_absolute_paths`: Address PR review

Co-Authored-By: ofeeg <mhanna0000@gmail.com>
2023-11-20 13:28:28 +01:00
y21
56cee3c587 move doc.rs to its own subdirectory 2023-11-20 12:08:07 +01:00
bors
41140e3cb8 Auto merge of #11840 - GuillaumeGomez:improve-maybe_misused_cfg, r=blyxyas
Improve maybe misused cfg

Follow-up of the improvements that were suggested to me in https://github.com/rust-lang/rust-clippy/pull/11821:

 * I unified the output to use the same terms.
 * I updated the code to prevent creating a new symbol.

r? `@blyxyas`

changelog: [`maybe_misued_cfg`]: Output and code improvements
2023-11-19 22:31:11 +00:00
Guillaume Gomez
dfbca7ffa8 Improve maybe_misused_cfg lint output
Small performance improvement when comparing symbols for `maybe_misused_cfg`
Improve suggestion for `maybe_misused_cfg` lint
2023-11-19 22:46:19 +01:00
Esteban Küber
82babe0303 Don't sort span_suggestions, leave that to caller 2023-11-19 17:50:45 +00:00
bors
9c3a365fd2 Auto merge of #11781 - partiallytyped:11710, r=xFrednet
Verify Borrow<T> semantics for types that implement Hash, Borrow<str> and Borrow<[u8]>.

Fixes #11710

The essence of the issue is that types that implement Borrow<T> provide a facet or a representation of the underlying type. Under these semantics `hash(a) == hash(a.borrow())`.

This is a problem when a type implements `Borrow<str>`, `Borrow<[u8]>` and Hash, it is expected that the hash of all three types is identical. The problem is that the hash of [u8] is not the same as that of a String, even when the byte reference ([u8]) is derived from `.as_bytes()`

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

---

 - [x] Explanation of the issue in the code
 - [x] Tests reproducing the issue
 - [x] Lint rule and emission

---

changelog: New lint: [`impl_hash_borrow_with_str_and_bytes`]
[#11781](https://github.com/rust-lang/rust-clippy/pull/11781)
2023-11-19 10:59:34 +00:00
Quinn Sinclair
3c1e0afa58 New Lint [impl_hash_with_borrow_str_and_bytes]
Implements a lint to prevent implementation of Hash, Borrow<str> and
Borrow<[u8]> as it breaks Borrow<T> "semantics". According to the book,
types that implement Borrow<A> and Borrow<B> must ensure equality of
borrow results under Eq,Ord and Hash.

> In particular Eq, Ord and Hash must be equivalent for borrowed and
owned values: x.borrow() == y.borrow() should give the same result as x == y.

In the same way, hash(x) == hash(x as Borrow<[u8]>) != hash(x as Borrow<str>).

changelog: newlint [`impl_hash_with_borrow_str_and_bytes`]
2023-11-19 11:33:01 +01:00
bors
dbd19f9b48 Auto merge of #11691 - sjwang05:lines-filter-map-ok-fix, r=Centri3
Lint `flatten()` under `lines_filter_map_ok`

Fixes #11686

changelog: [`lines_filter_map_ok`]: Also lint calls to `flatten()`
2023-11-19 01:50:24 +00:00
bors
9263f806d8 Auto merge of #11782 - Alexendoo:macro-use-imports-ordering, r=Centri3
Make `macro_use_imports` lint ordering more stable

changelog: none

Fixes [the `macro_use_imports` ordering dependence](https://github.com/rust-lang/rust/pull/117649#issuecomment-1797716088) on the hash of `Span`s
2023-11-19 01:39:06 +00:00
bors
6eb935a578 Auto merge of #11826 - kpreid:typo, r=Alexendoo
Fix typos in recent lint documentation.

Fixes typos and markup errors, and also makes the examples more realistic by hiding the `;`s so as not to visibly be discarding the computed value. Affected lints:

* `redundant_as_str`
* `unnecessary_map_on_constructor`

changelog: none
2023-11-18 19:49:46 +00:00
Kevin Reid
b3f4a9015c Remove space and rephrase map() advice. 2023-11-18 10:53:03 -08:00
y21
4de845e375 [missing_asserts_for_indexing]: accept len equality checks 2023-11-18 14:59:24 +01:00
Lukas Lueg
a2e396badf Don't suggest a.mul_add(b, c) if parameters are not float
clippy::suboptimal_flops used to not check if the second parameter to f32/f64.mul_add() was float. Since the method is
only defined to take `Self` as paremters, the suggestion was wrong.

Fixes #11831
2023-11-18 13:50:18 +01:00
bors
e8e9510219 Auto merge of #11002 - y21:issue9422, r=Jarcho
teach `eager_or_lazy` about panicky arithmetic operations

Fixes #9422
Fixes #9814
Fixes #11793

It's a bit sad that we have to do this because arithmetic operations seemed to me like the prime example where a closure would not be necessary, but this has "side effects" (changes behavior when going from lazy to eager) as some of these panic on overflow/underflow if compiled with `-Coverflow-checks` (which is the default in debug mode).
Given the number of backlinks in the mentioned issues, this seems to be a FP that is worth fixing, probably.

changelog: [`unnecessary_lazy_evaluations`]: don't lint if closure has panicky arithmetic operations
2023-11-17 18:53:15 +00:00
Kevin Reid
bffb664fbf Fix markup in recent lint documentation.
Also make the examples more realistic by hiding the `;`s so as not to
visibly be discarding the computed value.
2023-11-17 10:12:12 -08:00
bors
31e38fee23 Auto merge of #11821 - GuillaumeGomez:misspelled-cfg, r=blyxyas
Extend `maybe_misused_cfg` lint over `cfg(test)`

Fixes #11240.

One thought I had is that we could use the levenshtein distance (of 1) to ensure this is indeed `test` that was targeted. But maybe it's overkill, not sure.

changelog: [`maybe_misused_cfg`]: Extend lint over `cfg(test)`

r? `@blyxyas`
2023-11-17 11:49:20 +00:00
J-ZhengLi
2d9fc6dfc8 implement unoptimized code logic for [infinite_loops] 2023-11-17 18:10:50 +08:00
lcnr
8c6c542443 rename bound region instantiation
- `erase_late_bound_regions` -> `instantiate_bound_regions_with_erased`
- `replace_late_bound_regions_X` -> `instantiate_bound_regions_X`
2023-11-17 09:29:48 +00:00