Commit graph

4837 commits

Author SHA1 Message Date
Lukas Lueg
9ffc5a5c8d Fix more parens for suboptimal_flops suggs 2022-08-29 22:36:11 +02:00
Lukas Lueg
26a6891925 Fix missing parens in suboptimal_flops sugg
Fixes #9391
2022-08-29 13:56:03 +02:00
bors
28ec27b33a Auto merge of #9388 - Jarcho:rustup, r=Jarcho
Rustup

Hopefully this is done right.

changelog: None
2022-08-29 01:51:23 +00:00
Jason Newcomb
3ad398d9b0 Merge branch 'master' into rustup 2022-08-28 06:44:13 -04:00
Lukas Lueg
c542f1fe3f Don't lint literal None from expansion 2022-08-28 12:18:50 +02:00
bors
8d9da4d7c7 Auto merge of #9276 - dswij:9164, r=flip1995
Ignore `match_like_matches_macro` when there is comment

Closes #9164

changelog: [`match_like_matches_macro`] is ignored when there is some comment inside the match block.

Also add `span_contains_comment` util to check if given span contains comments.
2022-08-28 07:08:18 +00:00
bors
2d4d8e16cd Auto merge of #8984 - xanathar:pr/suspicious_to_owned, r=llogiq
Implemented `suspicious_to_owned` lint to check if `to_owned` is called on a `Cow`

changelog: Add lint ``[`suspicious_to_owned`]``

-----------------
Hi,
posting this unsolicited PR as I've been burned by this issue :)
Being unsolicited, feel free to reject it or reassign a different lint level etc.

This lint checks whether `to_owned` is called on `Cow<'_, _>`. This is done because `to_owned` is very similarly named to `into_owned`, but the effect of calling those two methods is completely different (one makes the `Cow::Borrowed` into a `Cow::Owned`, the other just clones the `Cow`). If the cow is then passed to code for which the type is not checked (e.g. generics, closures, etc.) it might slip through and if the cow data is coming from an unsafe context there is the potential for accidentally cause undefined behavior.
Even if not falling into this painful case, there's really no reason to call `to_owned` on a `Cow` other than confusing people reading the code: either `into_owned` or `clone` should be called.

Note that this overlaps perfectly with `implicit_clone` as a warning, but `implicit_clone` is classified pedantic (while the consequences for `Cow` might be of a wider blast radius than just pedantry); given the overlap, I set-up the lint so that if `suspicious_to_owned` triggers `implicit_clone` will not trigger. I'm not 100% sure this is done in the correct way (I tried to copy what other lints were doing) so please provide feedback on it if it isn't.

### Checklist

- \[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`
2022-08-27 17:38:40 +00:00
dswij
b07d72b69e Ignore when there is comment 2022-08-28 00:07:00 +08:00
Marco Mastropaolo
de028e2fb9 Implemented suspicious_to_owned lint to check if to_owned is called on a Cow.
This is done because `to_owned` is very similarly named to `into_owned`, but the
effect of calling those two methods is completely different. This creates
confusion (stemming from the ambiguity of the 'owned' term in the context of
`Cow`s) and might not be what the writer intended.
2022-08-26 17:41:17 -07:00
Lukas Lueg
fe93b8d001 Don't lint needless_return if return has attrs
Fixes #9361
2022-08-26 19:06:07 +02:00
bors
21f103abcc Auto merge of #9379 - royrustdev:multi_assignments, r=llogiq
new lint

This fixes #6576

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

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

---

changelog: add [`multi_assignments`] lint
2022-08-26 12:05:57 +00:00
royrustdev
fb7dffeac9 add multi_assignments lint 2022-08-26 17:05:52 +05:30
Joshua Nelson
345c42a2d6 Stabilize #![feature(label_break_value)]
# Stabilization proposal

The feature was implemented in https://github.com/rust-lang/rust/pull/50045 by est31 and has been in nightly since 2018-05-16 (over 4 years now).
There are [no open issues][issue-label] other than the tracking issue. There is a strong consensus that `break` is the right keyword and we should not use `return`.

There have been several concerns raised about this feature on the tracking issue (other than the one about tests, which has been fixed, and an interaction with try blocks, which has been fixed).
1. nrc's original comment about cost-benefit analysis: https://github.com/rust-lang/rust/issues/48594#issuecomment-422235234
2. joshtriplett's comments about seeing use cases: https://github.com/rust-lang/rust/issues/48594#issuecomment-422281176
3. withoutboats's comments that Rust does not need more control flow constructs: https://github.com/rust-lang/rust/issues/48594#issuecomment-450050630

Many different examples of code that's simpler using this feature have been provided:
- A lexer by rpjohnst which must repeat code without label-break-value: https://github.com/rust-lang/rust/issues/48594#issuecomment-422502014
- A snippet by SergioBenitez which avoids using a new function and adding several new return points to a function: https://github.com/rust-lang/rust/issues/48594#issuecomment-427628251. This particular case would also work if `try` blocks were stabilized (at the cost of making the code harder to optimize).
- Several examples by JohnBSmith: https://github.com/rust-lang/rust/issues/48594#issuecomment-434651395
- Several examples by Centril: https://github.com/rust-lang/rust/issues/48594#issuecomment-440154733
- An example by petrochenkov where this is used in the compiler itself to avoid duplicating error checking code: https://github.com/rust-lang/rust/issues/48594#issuecomment-443557569
- Amanieu recently provided another example related to complex conditions, where try blocks would not have helped: https://github.com/rust-lang/rust/issues/48594#issuecomment-1184213006

Additionally, petrochenkov notes that this is strictly more powerful than labelled loops due to macros which accidentally exit a loop instead of being consumed by the macro matchers: https://github.com/rust-lang/rust/issues/48594#issuecomment-450246249

nrc later resolved their concern, mostly because of the aforementioned macro problems.
joshtriplett suggested that macros could be able to generate IR directly
(https://github.com/rust-lang/rust/issues/48594#issuecomment-451685983) but there are no open RFCs,
and the design space seems rather speculative.

joshtriplett later resolved his concerns, due to a symmetry between this feature and existing labelled break: https://github.com/rust-lang/rust/issues/48594#issuecomment-632960804

withoutboats has regrettably left the language team.

joshtriplett later posted that the lang team would consider starting an FCP given a stabilization report: https://github.com/rust-lang/rust/issues/48594#issuecomment-1111269353

[issue-label]: https://github.com/rust-lang/rust/issues?q=is%3Aissue+is%3Aopen+label%3AF-label_break_value+

 ## Report

+ Feature gate:
    - d695a497bb/src/test/ui/feature-gates/feature-gate-label_break_value.rs
+ Diagnostics:
    - 6b2d3d5f3c/compiler/rustc_parse/src/parser/diagnostics.rs (L2629)
    - f65bf0b2bb/compiler/rustc_resolve/src/diagnostics.rs (L749)
    - f65bf0b2bb/compiler/rustc_resolve/src/diagnostics.rs (L1001)
    - 111df9e6ed/compiler/rustc_passes/src/loops.rs (L254)
    - d695a497bb/compiler/rustc_parse/src/parser/expr.rs (L2079)
    - d695a497bb/compiler/rustc_parse/src/parser/expr.rs (L1569)
+ Tests:
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_continue.rs
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_unlabeled_break.rs
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_illegal_uses.rs
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/lint/unused_labels.rs
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/run-pass/for-loop-while/label_break_value.rs

 ## Interactions with other features

Labels follow the hygiene of local variables.

label-break-value is permitted within `try` blocks:
```rust
let _: Result<(), ()> = try {
    'foo: {
        Err(())?;
        break 'foo;
    }
};
```

label-break-value is disallowed within closures, generators, and async blocks:
```rust
'a: {
    || break 'a
    //~^ ERROR use of unreachable label `'a`
    //~| ERROR `break` inside of a closure
}
```

label-break-value is disallowed on [_BlockExpression_]; it can only occur as a [_LoopExpression_]:
```rust
fn labeled_match() {
    match false 'b: { //~ ERROR block label not supported here
        _ => {}
    }
}

macro_rules! m {
    ($b:block) => {
        'lab: $b; //~ ERROR cannot use a `block` macro fragment here
        unsafe $b; //~ ERROR cannot use a `block` macro fragment here
        |x: u8| -> () $b; //~ ERROR cannot use a `block` macro fragment here
    }
}

fn foo() {
    m!({});
}
```

[_BlockExpression_]: https://doc.rust-lang.org/nightly/reference/expressions/block-expr.html
[_LoopExpression_]: https://doc.rust-lang.org/nightly/reference/expressions/loop-expr.html
2022-08-23 21:14:12 -05:00
Alex Macleod
2cb5318e97 Rename manual_empty_string_creation and move to pedantic 2022-08-23 14:19:46 +00:00
Samuel E. Moelius III
687fcf14c4 Fix to_string_in_format_args false positive 2022-08-21 19:38:09 +00:00
bors
cc637bacfa Auto merge of #9092 - tamaroning:fix-needless-match, r=llogiq
Fix false positives of needless_match

closes: #9084
made needless_match take into account arm in the form of `_ if => ...`

changelog: none
2022-08-21 13:22:21 +00:00
bors
e19a05cbb3 Auto merge of #8992 - kyoto7250:fix_8753, r=flip1995
feat(fix): Do not lint if the target code is inside a loop

close #8753

we consider the following code.

```rust
fn main() {
    let vec = vec![1];
    let w: Vec<usize> = vec.iter().map(|i| i * i).collect();  // <- once.

    for i in 0..2 {
        let _ = w.contains(&i);
    }
}
```

and the clippy will issue the following warning.

```rust
warning: avoid using `collect()` when not needed
 --> src/main.rs:3:51
  |
3 |     let w: Vec<usize> = vec.iter().map(|i| i * i).collect();
  |                                                   ^^^^^^^
...
6 |         let _ = w.contains(&i);
  |                 -------------- the iterator could be used here instead
  |
  = note: `#[warn(clippy::needless_collect)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
help: check if the original Iterator contains an element instead of collecting then checking
  |
3 ~
4 |
5 |     for i in 0..2 {
6 ~         let _ = vec.iter().map(|i| i * i).any(|x| x == i);
```

Rewrite the code as indicated.

```rust
fn main() {
    let vec = vec![1];

    for i in 0..2 {
        let _ = vec.iter().map(|i| i * i).any(|x| x == i);  // <- execute `map` every loop.
    }
}
```

this code is valid in the compiler, but, it is different from the code before the rewrite.
So, we should not lint, If `collect` is outside of a loop.

Thank you in advance.

---

changelog: Do not lint if the target code is inside a loop in `needless_collect`
2022-08-21 09:58:24 +00:00
kyoto7250
5048af7a3a
feat(fix): Do not lint if the target code is inside a loop 2022-08-21 10:47:03 +02:00
Philipp Krones
1f75845a8f
Reduce indentation and add comment about lint name 2022-08-21 10:29:26 +02:00
tamaron
f7a376e4fc Update needless_match.stderr 2022-08-21 17:26:39 +09:00
J-ZhengLi
ffe7125163
and check for Result 2022-08-21 10:24:30 +02:00
J-ZhengLi
5d403c0b85
allow check for match in lint [option_if_let_else]
and add test case for `Result`
2022-08-21 10:24:27 +02:00
Samuel E. Moelius III
6f3d398e13 Add test for #8855 2022-08-20 15:21:32 +00:00
bors
5820addb24 Auto merge of #9269 - nahuakang:collapsible_str_replace, r=flip1995
Lint `collapsible_str_replace`

fixes #6651

```
changelog: [`collapsible_str_replace`]: create new lint `collapsible_str_replace`
```

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

- \[x] Followed [lint naming conventions][lint_naming]
- \[x] Added passing UI tests (including committed `.stderr` file)
- \[x] `cargo test` passes locally
- \[ ] Executed `cargo dev update_lints`
- \[x] Added lint documentation
- \[x] Run `cargo dev fmt`
2022-08-20 13:44:35 +00:00
Nahua Kang
b070b4045f Simplify lint logic and address code review comments 2022-08-20 12:09:09 +02:00
bors
2091142f5d Auto merge of #9258 - Serial-ATA:unused-peekable, r=Alexendoo
Add [`unused_peekable`] lint

changelog: Add [`unused_peekable`] lint
closes: #854
2022-08-19 18:30:13 +00:00
Nahua Kang
fb30b64f63 Adjust test cases; run cargo dev bless 2022-08-19 20:00:20 +02:00
Nahua Kang
c989746ccf Remove checks on char slice; improve lint suggestion 2022-08-19 20:00:20 +02:00
Nahua Kang
a9bd0bd321 Handle repeated str::replace calls with single char kind to str 2022-08-19 20:00:19 +02:00
Nahua Kang
6e86687529 Handle replace calls with char slices 2022-08-19 19:55:28 +02:00
Nahua Kang
89698b9613 Extend and improve initial test cases for collapsible_str_replace 2022-08-19 19:49:16 +02:00
Nahua Kang
a4413f75bf Register new lint collapsible_str_replace to methods 2022-08-19 19:49:15 +02:00
bors
3a54117ffc Auto merge of #8804 - Jarcho:in_recursion, r=Alexendoo
Rework `only_used_in_recursion`

fixes #8782
fixes #8629
fixes #8560
fixes #8556

This is a complete rewrite of the lint. This loses some capabilities of the old implementation. Namely the ability to track through tuple and slice patterns, as well as the ability to trace through assignments.

The two reported bugs are fixed with this. One was caused by using the name of the method rather than resolving to the `DefId` of the called method. The second was cause by using the existence of a cycle in the dependency graph to determine whether the parameter was used in recursion even though there were other ways to create a cycle in the graph.

Implementation wise this switches from using a visitor to walking up the tree from every use of each parameter until it has been determined the parameter is used for something other than recursion. This is likely to perform better as it avoids walking the entire function a second time, and it is unlikely to walk up the HIR tree very much. Some cases would perform worse though.

cc `@buttercrab`

changelog: Scale back `only_used_in_recursion` to fix false positives
changelog: Move `only_used_in_recursion` back to `complexity`
2022-08-19 16:11:48 +00:00
Jason Newcomb
d95b67560c Rework only_used_in_recursion 2022-08-19 11:42:14 -04:00
Alex Macleod
4f049f5a69 Refactor FormatArgsExpn 2022-08-19 15:35:26 +00:00
Jason Newcomb
8acc4d2f1e Move VecResizeToZero into Methods lint pass 2022-08-19 10:54:55 -04:00
Serial
0efafa4a6e Better handle method/function calls 2022-08-19 08:18:34 -04:00
Serial
2666c38acb Add [unused_peekable] lint 2022-08-19 08:05:59 -04:00
bors
868dba9f65 Auto merge of #9295 - Guilherme-Vasconcelos:manual-empty-string-creation, r=dswij
Add `manual_empty_string_creations` lint

Closes #2972

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

changelog: [`manual_empty_string_creations`]: Add lint for empty String not being created with `String::new()`
2022-08-19 11:19:06 +00:00
Lukas Lueg
e87a5a1cc5 Dont lint on match pattern-binding
Fixes #9347

Technically it is possible to have a blank match-pattern that does
nothing, and we fail to lint. But its easier to be safe than sorry here.
2022-08-18 19:30:56 +02:00
bors
c419d0a8b5 Auto merge of #9136 - smoelius:enhance-needless-borrow, r=Jarcho
Enhance `needless_borrow` to consider trait implementations

The proposed enhancement causes `needless_borrow` to suggest removing `&` from `&e` when `&e` is an argument position requiring trait implementations, and `e` implements the required traits. Example:
```
error: the borrowed expression implements the required traits
  --> $DIR/needless_borrow.rs:131:51
   |
LL |     let _ = std::process::Command::new("ls").args(&["-a", "-l"]).status().unwrap();
   |                                                   ^^^^^^^^^^^^^ help: change this to: `["-a", "-l"]`
```

r? `@Jarcho`

changelog: Enhance `needless_borrow` to consider trait implementations
2022-08-18 15:57:37 +00:00
bors
849c1c0465 Auto merge of #9338 - sgued:9331-unwrap-err-used, r=giraffate
unwrap_used and expect_used: trigger on uses of their _err variants

changelog: [`unwrap_used`]: lint uses of `unwrap_err`
changelog: [`expect_used`]: lint uses of `expect_err`

fixes #9331
2022-08-17 23:35:44 +00:00
Sosthène Guédon
ab91d5a540 unwrap_used: Fix error message for unwrap_err when expect_used is allowed 2022-08-17 18:58:17 +02:00
bors
84fb7e0395 Auto merge of #9287 - Jarcho:trans_undefined, r=xFrednet
`transmute_undefined_repr` fix

changelog: Don't lint `transmute_undefined_repr` when the the first field of a `repr(C)` type is compatible with the other type
2022-08-17 13:14:55 +00:00
Samuel E. Moelius III
032f112745 Fix adjacent code 2022-08-16 18:34:51 -04:00
Samuel E. Moelius III
a05cb74d30 Enhance needless_borrow to consider trait implementations 2022-08-16 18:34:51 -04:00
bors
f4f5bb4328 Auto merge of #9327 - Serial-ATA:non_ascii_literal_macro, r=Alexendoo
Fix [`non_ascii_literal`] in tests

changelog: Don't lint [`non_ascii_literal`] when using non-ascii comments in tests
changelog: Don't lint [`non_ascii_literal`] when `allow`ed on tests

closes: #7739
closes: #8263
2022-08-16 20:22:39 +00:00
Serial
bd121eff8a Fix [non_ascii_literal] in tests 2022-08-16 15:53:01 -04:00
Sosthène Guédon
c1e04352bd unwrap_used and expect_used: trigger on uses of their _err variants 2022-08-16 18:31:57 +02:00
bors
86ac6e88a8 Auto merge of #9040 - miam-miam100:unused_named_parameter, r=dswij
Add new lint [`positional_named_format_parameters`]

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

changelog: Add new lint [`positional_named_format_parameters`] to warn when named parameters in format strings are used as positional arguments.
2022-08-16 13:11:27 +00:00