fix(lint): check const context
close: https://github.com/rust-lang/rust-clippy/issues/8898
This PR fixes a bug in checked_conversions.
Thank you in advance.
changelog: check const context in checked_conversions.
Remove migrate borrowck mode
Closes#58781Closes#43234
# Stabilization proposal
This PR proposes the stabilization of `#![feature(nll)]` and the removal of `-Z borrowck`. Current borrow checking behavior of item bodies is currently done by first infering regions *lexically* and reporting any errors during HIR type checking. If there *are* any errors, then MIR borrowck (NLL) never occurs. If there *aren't* any errors, then MIR borrowck happens and any errors there would be reported. This PR removes the lexical region check of item bodies entirely and only uses MIR borrowck. Because MIR borrowck could never *not* be run for a compiled program, this should not break any programs. It does, however, change diagnostics significantly and allows a slightly larger set of programs to compile.
Tracking issue: #43234
RFC: https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md
Version: 1.63 (2022-06-30 => beta, 2022-08-11 => stable).
## Motivation
Over time, the Rust borrow checker has become "smarter" and thus allowed more programs to compile. There have been three different implementations: AST borrowck, MIR borrowck, and polonius (well, in progress). Additionally, there is the "lexical region resolver", which (roughly) solves the constraints generated through HIR typeck. It is not a full borrow checker, but does emit some errors.
The AST borrowck was the original implementation of the borrow checker and was part of the initially stabilized Rust 1.0. In mid 2017, work began to implement the current MIR borrow checker and that effort ompleted by the end of 2017, for the most part. During 2018, efforts were made to migrate away from the AST borrow checker to the MIR borrow checker - eventually culminating into "migrate" mode - where HIR typeck with lexical region resolving following by MIR borrow checking - being active by default in the 2018 edition.
In early 2019, migrate mode was turned on by default in the 2015 edition as well, but with MIR borrowck errors emitted as warnings. By late 2019, these warnings were upgraded to full errors. This was followed by the complete removal of the AST borrow checker.
In the period since, various errors emitted by the MIR borrow checker have been improved to the point that they are mostly the same or better than those emitted by the lexical region resolver.
While there do remain some degradations in errors (tracked under the [NLL-diagnostics tag](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3ANLL-diagnostics), those are sufficiently small and rare enough that increased flexibility of MIR borrow check-only is now a worthwhile tradeoff.
## What is stabilized
As said previously, this does not fundamentally change the landscape of accepted programs. However, there are a [few](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3ANLL-fixed-by-NLL) cases where programs can compile under `feature(nll)`, but not otherwise.
There are two notable patterns that are "fixed" by this stabilization. First, the `scoped_threads` feature, which is a continutation of a pre-1.0 API, can sometimes emit a [weird lifetime error](https://github.com/rust-lang/rust/issues/95527) without NLL. Second, actually seen in the standard library. In the `Extend` impl for `HashMap`, there is an implied bound of `K: 'a` that is available with NLL on but not without - this is utilized in the impl.
As mentioned before, there are a large number of diagnostic differences. Most of them are better, but some are worse. None are serious or happen often enough to need to block this PR. The biggest change is the loss of error code for a number of lifetime errors in favor of more general "lifetime may not live long enough" error. While this may *seem* bad, the former error codes were just attempts to somewhat-arbitrarily bin together lifetime errors of the same type; however, on paper, they end up being roughly the same with roughly the same kinds of solutions.
## What isn't stabilized
This PR does not completely remove the lexical region resolver. In the future, it may be possible to remove that (while still keeping HIR typeck) or to remove it together with HIR typeck.
## Tests
Many test outputs get updated by this PR. However, there are number of tests specifically geared towards NLL under `src/test/ui/nll`
## History
* On 2017-07-14, [tracking issue opened](https://github.com/rust-lang/rust/issues/43234)
* On 2017-07-20, [initial empty MIR pass added](https://github.com/rust-lang/rust/pull/43271)
* On 2017-08-29, [RFC opened](https://github.com/rust-lang/rfcs/pull/2094)
* On 2017-11-16, [Integrate MIR type-checker with NLL](https://github.com/rust-lang/rust/pull/45825)
* On 2017-12-20, [NLL feature complete](https://github.com/rust-lang/rust/pull/46862)
* On 2018-07-07, [Don't run AST borrowck on mir mode](https://github.com/rust-lang/rust/pull/52083)
* On 2018-07-27, [Add migrate mode](https://github.com/rust-lang/rust/pull/52681)
* On 2019-04-22, [Enable migrate mode on 2015 edition](https://github.com/rust-lang/rust/pull/59114)
* On 2019-08-26, [Don't downgrade errors on 2015 edition](https://github.com/rust-lang/rust/pull/64221)
* On 2019-08-27, [Remove AST borrowck](https://github.com/rust-lang/rust/pull/64790)
* Don't lint on `.cloned().flatten()` when `T::Item` doesn't implement `IntoIterator`
* Reduce verbosity of lint message
* Narrow down the scope of the replacement range
improve [`for_loops_over_fallibles`] to detect the usage of iter, iter_mut and into_iterator
fix#6762
detects code like
```rust
for _ in option.iter() {
//..
}
```
changelog: Improve [`for_loops_over_fallibles`] to detect `for _ in option.iter() {}` or using `iter_mut()` or `into_iterator()`.
fix(manual_find_map and manual_filter_map): check clone method
close#8920
Added conditional branching when the clone method is used.
Thank you in advance.
---
changelog: check `clone()` and other variant preserving methods in [`manual_find_map`] and [`manual_filter_map`]
When setting suggestion for significant_drop_in_scrutinee, add suggestion for MoveAndClone for non-ref
When trying to set the current suggestion, if the type of the expression
is not a reference and it is not trivially pure clone copy, we should still
trigger and emit a lint message. Since this fix may require cloning an
expensive-to-clone type, do not attempt to offer a suggested fix.
This change means that matches generated from TryDesugar and AwaitDesugar
would normally trigger a lint, but they are out of scope for this lint,
so we will explicitly ignore matches with sources of TryDesugar or
AwaitDesugar.
changelog: Update for ``[`significant_drop_in_scrutinee`]`` to correctly
emit lint messages for cases where the type is not a reference *and*
not trivially pure clone copy.
changelog: [`significant_drop_in_scrutinee`]: No longer lint on Try `?`
and `await` desugared expressions.
remove `large_enum_variant` suggestion for `Copy` types
Replaces the (erroneous) suggestion on `large_enum_variant` for `Copy` types by a note. This fixes#8894.
---
changelog: none
Set correct `ParamEnv` for `derive_partial_eq_without_eq`
fixes#8867
changelog: Handle differing predicates applied by `#[derive(PartialEq)]` and `#[derive(Eq)]` in `derive_partial_eq_without_eq`
new lint: `borrow_deref_ref`
changelog: ``[`borrow_deref_ref`]``
Related pr: #6837#7577
`@Jarcho` Could you please give a review?
`cargo lintcheck` gives no false negative (but tested crates are out-of-date).
TODO:
1. Not sure the name. `deref_on_immutable_ref` or some others?
Fix `manual_range_contains` false negative with chains of `&&` and `||`
Fixes#8745
Since the precedence for `&&` is the same as itself the HIR for a chain of `&&` ends up with a right skewed tree like:
```
&&
/ \
&& c2
/ \
... c1
```
So only the leftmost `&&` was actually "fully" checked, the top level was just `c2` and `&&` so the `manual_range_contains` lint won't apply. This change makes it also check `c2` with `c1`.
There's a bit of a hacky solution in the [second commit](257f09776a) to check if the number of open/closing parens in the snippet match. This is to prevent a case like `((x % 2 == 0) || (x < 0)) || (x >= 10)` from offering a suggestion like `((x % 2 == 0) || !(0..10).contains(&x)` which now won't compile.
Any suggestions for that paren hack welcome, kinda new to working on this so not too sure about possible solutions :) it's weird because I don't know how else to check for parens in HIR considering they're removed when lowering AST.
changelog: Fix [`manual_range_contains`] false negative with chains of `&&` and `||`
Don't lint `useless_transmute` on types with erased regions
fixes#6356fixes#3340fixes#2906
This should get a proper fix at some point, but this at least gets the lint running on some types.
cc #5343
changelog: Don't lint `useless_transmute` on types with erased regions
`cast_abs_to_unsigned`: do not remove cast if it's required
Fixes#8873
If `iX` is not cast to `uX` then keep the cast rather than removing it
changelog: [`cast_abs_to_unsigned`]: do not remove cast if it's required
needless_late_init: fix ICE when all branches return the never type
Fixes#8911
When the assignment is done in a match guard or the if condition and all of the branches return the never type `assignment_suggestions` would return an empty `Vec` which caused the ICE. It now returns `None` in that scenario
Also moves some tests to the top of the file
changelog: ICE Fixes: [`needless_late_init`] #8911
Fix `[use_self]` false negative with on struct and tuple struct patterns
fixes#8845
changelog: Triggered the warning for ``[`use_self`]`` on `TupleStruct` and `Struct` patterns, whereas currently it's only triggered for `Path` patterns
add doc_link_with_quotes lint
I'm not sure about wording, it seems OK to me but happy to change if other people have better ideas
closes#8383
---
changelog: add [`doc_link_with_quotes`] lint
Check `.fixed` paths' existence in `run_ui`
This PR adds a test to check that there exists a `.fixed` file for every `.stderr` file in `tests/ui` that mentions a `MachineApplicable` lint. The test leverages `compiletest-rs`'s `rustfix_coverage` option.
I tried to add `.fixed` files where they appeared to be missing. However, 38 exceptional `.rs` files remain. Several of those include comments indicating that they are exceptions, though not all do. Apologies, as I have not tried to associate the 38 files with GH issues. (I think that would be a lot of work, and I worry about linking the wrong issue.)
changelog: none
Fix `empty_line_after_outer_attribute` false positive
This PR fixes a false positive in `empty_line_after_outer_attribute`.
Here is a minimal example that trigger the FP:
```rust
#[derive(clap::Parser)]
#[clap(after_help = "This ia a help message.
You're welcome.
")]
pub struct Args;
```
changelog: PF: [`empty_line_after_outer_attribute`]: No longer lints empty lines in inner string values.
Introduce `allow-dbg-in-tests` config value
related to: Issue #8758, PR https://github.com/rust-lang/rust-clippy/pull/8838
changelog: Introduced `allow-dbg-in-tests` config value. [dbg_macro] does not allow `dbg!` in test code by default.
When trying to set the current suggestion, if the type of the expression
is not a reference and it is not trivially pure clone copy, we should still
trigger and emit a lint message. Since this fix may require cloning an
expensive-to-clone type, do not attempt to offer a suggested fix.
This change means that matches generated from TryDesugar and AwaitDesugar
would normally trigger a lint, but they are out of scope for this lint,
so we will explicitly ignore matches with sources of TryDesugar or
AwaitDesugar.
changelog: Update for [`significant_drop_in_scrutinee`] to correctly
emit lint messages for cases where the type is not a reference and
not trivially pure clone copy.
`get_last_with_len`: lint `VecDeque` and any deref to slice
changelog: [`get_last_with_len`]: lint `VecDeque` and any deref to slice
Previously only `Vec`s were linted, this will now catch any usages on slices, arrays, etc. It also suggests `.back()` for `VecDeque`s
Also moves the lint into `methods/`
Add some testcases for recent rustfix update
changelog: none
This adds a testcase for a bugfix that has been fixed by https://github.com/rust-lang/rustfix/tree/v0.6.1
`rustfix` is pulled in by `compiletest_rs`. So to test that the correct rustfix version is used, I added one (and a half) testcase.
I tried to add a testcase for #8734 as well, but interesting enough the rustfix is wrong:
```diff
fn issue8734() {
let _ = [0u8, 1, 2, 3]
.into_iter()
- .and_then(|n| match n {
+ .flat_map(|n| match n {
+ 1 => [n
+ .saturating_add(1)
1 => [n
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)],
n => [n],
});
}
```
this needs some investigation and then this testcase needs to be enabled by commenting it out
closes#8878
related to #8734
`identity_op`: add parenthesis to suggestions where required
changelog: [`identity_op`]: add parenthesis to suggestions where required
Follow up to #8730, wraps the cases we can't lint as-is in parenthesis rather than ignoring them
Catches a couple new FPs with mixed operator precedences and `as` casts
```rust
// such as
0 + { a } * 2;
0 + a as usize;
```
The suggestions are now applied using `span_lint_and_sugg` rather than appearing in just the message and have a `run-rustfix` test
[dbg_macro] tolerates use of `dbg!` in items which have `#[cfg(test)]` attribute
fix: #8758
changelog: [dbg_macro] tolerates use of `dbg!` in items with `#[cfg(test)]` attribute
add suggestions to rc_clone_in_vec_init
A followup to https://github.com/rust-lang/rust-clippy/pull/8769
I also switch the order of the 2 suggestions, since the loop initialization one is probably the common case.
`@xFrednet` I'm not letting you guys rest for a minute 😅
changelog: add suggestions to [`rc_clone_in_vec_init`]
`undocumented_unsafe_blocks` does not trigger on unsafe trait impls
Closes#8505
changelog: This lint checks unsafe impls NOT from macro expansions and checks ones in macro declarations.
~~`unsafe impl`s from macro invocations don't trigger the lint for now.~~
~~This lint checks unsafe impls from/not from macro expansions~~
Don't lint `vec_init_then_push` when further extended
fixes#7071
This will still lint when a larger number of pushes are done (four currently). The exact number could be debated, but this is more readable then a sequence of pushes so it shouldn't be too large.
changelog: Don't lint `vec_init_then_push` when further extended.
changelog: Remove `mut` binding from `vec_init_then_push` when possible.
Fix redundant_allocation warning for Rc<Box<str>>
changelog: [`redundant_allocation`] Fixes#8604
Fixes false positives where a fat pointer with `str` type was made thin by another allocation, but that thinning allocation was marked as redundant