Commit Graph

105 Commits

Author SHA1 Message Date
Matthias Krüger
20770ac3fc
Rollup merge of #122589 - wutchzone:121547, r=compiler-errors
Fix diagnostics for async block cloning

Closes #121547

r? diagnostics
2024-03-26 21:23:48 +01:00
Daniel Sedlak
0c7f8b0f89 Fix diagnostics for async block cloning 2024-03-23 20:22:51 +01:00
Matthias Krüger
e54bff7109 add test for #104779 opaque types, patterns and subtyping ICE: IndexMap: key not found
Fixes #104779
2024-03-23 12:19:05 +01:00
Matthias Krüger
bdafec33d5 add test for #121807
Fixes #121807
2024-03-21 21:27:37 +01:00
Michael Goulet
ce5f8c93fa Bless test fallout (duplicate diagnostics) 2024-03-20 13:00:34 -04:00
Esteban Küber
cc9631a371 When displaying multispans, ignore empty lines adjacent to ...
```
error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:98:18
    |
6   |       let _ = match true {
    |               ---------- `match` arms have incompatible types
7   |           true => (
    |  _________________-
8   | |             // last line shown in multispan header
...   |
96  | |
97  | |         ),
    | |_________- this is found to be of type `()`
98  |           false => "
    |  __________________^
...   |
119 | |
120 | |         ",
    | |_________^ expected `()`, found `&str`

error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:215:18
    |
122 |       let _ = match true {
    |               ---------- `match` arms have incompatible types
123 |           true => (
    |  _________________-
124 | |
125 | |         1 // last line shown in multispan header
...   |
213 | |
214 | |         ),
    | |_________- this is found to be of type `{integer}`
215 |           false => "
    |  __________________^
216 | |
217 | |
218 | |         1 last line shown in multispan
...   |
237 | |
238 | |         ",
    | |_________^ expected integer, found `&str`
```
2024-03-18 16:25:36 +00:00
Esteban Küber
14473adf42 Detect when move of !Copy value occurs within loop and should likely not be cloned
When encountering a move error on a value within a loop of any kind,
identify if the moved value belongs to a call expression that should not
be cloned and avoid the semantically incorrect suggestion. Also try to
suggest moving the call expression outside of the loop instead.

```
error[E0382]: use of moved value: `vec`
  --> $DIR/recreating-value-in-loop-condition.rs:6:33
   |
LL |     let vec = vec!["one", "two", "three"];
   |         --- move occurs because `vec` has type `Vec<&str>`, which does not implement the `Copy` trait
LL |     while let Some(item) = iter(vec).next() {
   |     ----------------------------^^^--------
   |     |                           |
   |     |                           value moved here, in previous iteration of loop
   |     inside of this loop
   |
note: consider changing this parameter type in function `iter` to borrow instead if owning the value isn't necessary
  --> $DIR/recreating-value-in-loop-condition.rs:1:17
   |
LL | fn iter<T>(vec: Vec<T>) -> impl Iterator<Item = T> {
   |    ----         ^^^^^^ this parameter takes ownership of the value
   |    |
   |    in this function
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~     let mut value = iter(vec);
LL ~     while let Some(item) = value.next() {
   |
```

We use the presence of a `break` in the loop that would be affected by
the moved value as a heuristic for "shouldn't be cloned".

Fix #121466.
2024-03-17 21:32:26 +00:00
Matthias Krüger
9e153ccd45
Rollup merge of #122254 - estebank:issue-48677, r=oli-obk
Detect calls to .clone() on T: !Clone types on borrowck errors

When encountering a lifetime error on a type that *holds* a type that doesn't implement `Clone`, explore the item's body for potential calls to `.clone()` that are only cloning the reference `&T` instead of `T` because `T: !Clone`. If we find this, suggest `T: Clone`.

```
error[E0502]: cannot borrow `*list` as mutable because it is also borrowed as immutable
  --> $DIR/clone-on-ref.rs:7:5
   |
LL |     for v in list.iter() {
   |              ---- immutable borrow occurs here
LL |         cloned_items.push(v.clone())
   |                             ------- this call doesn't do anything, the result is still `&T` because `T` doesn't implement `Clone`
LL |     }
LL |     list.push(T::default());
   |     ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL |
LL |     drop(cloned_items);
   |          ------------ immutable borrow later used here
   |
help: consider further restricting this bound
   |
LL | fn foo<T: Default + Clone>(list: &mut Vec<T>) {
   |                   +++++++
```
```
error[E0505]: cannot move out of `x` because it is borrowed
  --> $DIR/clone-on-ref.rs:23:10
   |
LL | fn qux(x: A) {
   |        - binding `x` declared here
LL |     let a = &x;
   |             -- borrow of `x` occurs here
LL |     let b = a.clone();
   |               ------- this call doesn't do anything, the result is still `&A` because `A` doesn't implement `Clone`
LL |     drop(x);
   |          ^ move out of `x` occurs here
LL |
LL |     println!("{b:?}");
   |               ----- borrow later used here
   |
help: consider annotating `A` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | struct A;
   |
```

Fix #48677.
2024-03-15 21:51:56 +01:00
Esteban Küber
2d3435b4df Detect calls to .clone() on T: !Clone types on borrowck errors
When encountering a lifetime error on a type that *holds* a type that
doesn't implement `Clone`, explore the item's body for potential calls
to `.clone()` that are only cloning the reference `&T` instead of `T`
because `T: !Clone`. If we find this, suggest `T: Clone`.

```
error[E0502]: cannot borrow `*list` as mutable because it is also borrowed as immutable
  --> $DIR/clone-on-ref.rs:7:5
   |
LL |     for v in list.iter() {
   |              ---- immutable borrow occurs here
LL |         cloned_items.push(v.clone())
   |                             ------- this call doesn't do anything, the result is still `&T` because `T` doesn't implement `Clone`
LL |     }
LL |     list.push(T::default());
   |     ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL |
LL |     drop(cloned_items);
   |          ------------ immutable borrow later used here
   |
help: consider further restricting this bound
   |
LL | fn foo<T: Default + Clone>(list: &mut Vec<T>) {
   |                   +++++++
```
```
error[E0505]: cannot move out of `x` because it is borrowed
  --> $DIR/clone-on-ref.rs:23:10
   |
LL | fn qux(x: A) {
   |        - binding `x` declared here
LL |     let a = &x;
   |             -- borrow of `x` occurs here
LL |     let b = a.clone();
   |               ------- this call doesn't do anything, the result is still `&A` because `A` doesn't implement `Clone`
LL |     drop(x);
   |          ^ move out of `x` occurs here
LL |
LL |     println!("{b:?}");
   |               ----- borrow later used here
   |
help: consider annotating `A` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | struct A;
   |
```
2024-03-13 23:05:11 +00:00
Oli Scherer
96d24f2dd1 Revert "Auto merge of #122140 - oli-obk:track_errors13, r=davidtwco"
This reverts commit 65cd843ae0, reversing
changes made to d255c6a57c.
2024-03-11 21:28:16 +00:00
Oli Scherer
55ea94402b Run a single huge par_body_owners instead of many small ones after each other.
This improves parallel rustc parallelism by avoiding the bottleneck after each individual `par_body_owners` (because it needs to wait for queries to finish, so if there is one long running one, a lot of cores will be idle while waiting for the single query).
2024-03-11 08:48:03 +00:00
许杰友 Jieyou Xu (Joe)
64dda8c837
Fix invalid compiletest directives in tests
- Fix invalid directive in `normalize-hidden-types`
- Update legacy directive in `two-phase-reservation-sharing-interference`
2024-03-10 13:13:09 +00:00
Matthias Krüger
80549a8811
Rollup merge of #120646 - clubby789:uninit-destructuring-sugg, r=michaelwoerister
Fix incorrect suggestion for uninitialized binding in pattern

Fixes #120634
2024-03-01 17:51:28 +01:00
Obei Sideg
408eeae59d Improve wording of static_mut_ref
Rename `static_mut_ref` lint to `static_mut_refs`.
2024-02-18 06:01:40 +03:00
许杰友 Jieyou Xu (Joe)
ec2cc761bc
[AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
Guillaume Gomez
e5a743c4c2
Rollup merge of #121020 - oli-obk:diagnostics_ice, r=davidtwco
Avoid an ICE in diagnostics

fixes #121004

just a slice usage in diagnostics code. Sadly we can't yet bubble the `ErrorGuaranteed` from wf check to borrowck for these cases, as that causes cycle errors iirc
2024-02-16 17:08:12 +01:00
许杰友 Jieyou Xu (Joe)
ee88f3435a
Fix two UI tests with incorrect directive / invalid revision 2024-02-14 09:13:53 +00:00
Oli Scherer
d3a89cd214 Avoid an ICE in diagnostics 2024-02-13 10:44:54 +00:00
clubby789
75da582987 Fix incorrect suggestion for uninitialize binding in destructuring pattern 2024-02-06 23:12:23 +00:00
Ali MJ Al-Nasrawy
a3fe3bbb2c borrowck: wf-check fn item args 2024-01-16 09:25:28 +01:00
Matthias Krüger
73256c68b8
Rollup merge of #119818 - oli-obk:even_more_follow_up_errors3, r=compiler-errors
Silence some follow-up errors [3/x]

this is one piece of the requested cleanups from https://github.com/rust-lang/rust/pull/117449

Keep error types around, even in obligations.

These help silence follow-up errors, as we now figure out that some types (most notably inference variables) are equal to an error type.

But it also allows figuring out more types in the presence of errors, possibly causing more errors.
2024-01-15 08:44:46 +01:00
Michael Goulet
04a6fd241b Make InferCtxtExt::could_impl_trait less messed up 2024-01-13 22:00:34 +00:00
Oli Scherer
fb44c848c3 Keep error types around, even in obligations.
These help silence follow up errors
2024-01-11 09:52:25 +00:00
bors
94807670a6 Auto merge of #117449 - oli-obk:query_merge_immobile_game, r=matthewjasper
Avoid silencing relevant follow-up errors

r? `@matthewjasper`

This PR only adds new errors to tests that are already failing and fixes one ICE.

Several tests were changed to not emit new errors. I believe all of them were faulty tests, and not explicitly testing for the code that had new errors.
2024-01-09 22:50:49 +00:00
Oli Scherer
0978f6e010 Avoid silencing relevant follow-up errors 2024-01-09 21:08:16 +00:00
Obei Sideg
a8aa6878f6 Update test for E0796 and static_mut_ref lint 2024-01-07 17:29:25 +03:00
jyn
eb53721a34 recurse into refs when comparing tys for diagnostics 2023-12-07 23:00:46 -05:00
Esteban Küber
cc80106cb5 Provide more suggestions for cloning immutable bindings
When encountering multiple mutable borrows, suggest cloning and adding
derive annotations as needed.

```
error[E0596]: cannot borrow `sm.x` as mutable, as it is behind a `&` reference
  --> $DIR/accidentally-cloning-ref-borrow-error.rs:32:9
   |
LL |     foo(&mut sm.x);
   |         ^^^^^^^^^ `sm` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |
help: `Str` doesn't implement `Clone`, so this call clones the reference `&Str`
  --> $DIR/accidentally-cloning-ref-borrow-error.rs:31:21
   |
LL |     let mut sm = sr.clone();
   |                     ^^^^^^^
help: consider annotating `Str` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | struct Str {
   |
help: consider specifying this binding's type
   |
LL |     let mut sm: &mut Str = sr.clone();
   |               ++++++++++
```

```
error[E0596]: cannot borrow `*inner` as mutable, as it is behind a `&` reference
  --> $DIR/issue-91206.rs:14:5
   |
LL |     inner.clear();
   |     ^^^^^ `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |
help: you can `clone` the `Vec<usize>` value and consume it, but this might not be your desired behavior
  --> $DIR/issue-91206.rs:11:17
   |
LL |     let inner = client.get_inner_ref();
   |                 ^^^^^^^^^^^^^^^^^^^^^^
help: consider specifying this binding's type
   |
LL |     let inner: &mut Vec<usize> = client.get_inner_ref();
   |              +++++++++++++++++
```
2023-12-04 21:54:34 +00:00
Esteban Küber
1c69c6ab08 Mark more tests as run-rustfix 2023-12-04 21:54:32 +00:00
Esteban Küber
98cfed7b97 Suggest cloning and point out obligation errors on move error
When encountering a move error, look for implementations of `Clone` for
the moved type. If there is one, check if all its obligations are met.
If they are, we suggest cloning without caveats. If they aren't, we
suggest cloning while mentioning the unmet obligations, potentially
suggesting `#[derive(Clone)]` when appropriate.

```
error[E0507]: cannot move out of a shared reference
  --> $DIR/suggest-clone-when-some-obligation-is-unmet.rs:20:28
   |
LL |     let mut copy: Vec<U> = map.clone().into_values().collect();
   |                            ^^^^^^^^^^^ ------------- value moved due to this method call
   |                            |
   |                            move occurs because value has type `HashMap<T, U, Hash128_1>`, which does not implement the `Copy` trait
   |
note: `HashMap::<K, V, S>::into_values` takes ownership of the receiver `self`, which moves value
  --> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL
help: you could `clone` the value and consume it, if the `Hash128_1: Clone` trait bound could be satisfied
   |
LL |     let mut copy: Vec<U> = <HashMap<T, U, Hash128_1> as Clone>::clone(&map.clone()).into_values().collect();
   |                            ++++++++++++++++++++++++++++++++++++++++++++           +
help: consider annotating `Hash128_1` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | pub struct Hash128_1;
   |
```

Fix #109429.
2023-12-04 21:54:32 +00:00
Esteban Küber
03c88aaf21 Tweak .clone() suggestion to work in more cases
When going through auto-deref, the `<T as Clone>` impl sometimes needs
to be specified for rustc to actually clone the value and not the
reference.

```
error[E0507]: cannot move out of dereference of `S`
  --> $DIR/needs-clone-through-deref.rs:15:18
   |
LL |         for _ in self.clone().into_iter() {}
   |                  ^^^^^^^^^^^^ ----------- value moved due to this method call
   |                  |
   |                  move occurs because value has type `Vec<usize>`, which does not implement the `Copy` trait
   |
note: `into_iter` takes ownership of the receiver `self`, which moves value
  --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL
help: you can `clone` the value and consume it, but this might not be your desired behavior
   |
LL |         for _ in <Vec<usize> as Clone>::clone(&self.clone()).into_iter() {}
   |                  ++++++++++++++++++++++++++++++            +
```

CC #109429.
2023-12-04 21:54:32 +00:00
Josh Stone
b8cdd4338d Fix a typo in a format_args! note 2023-11-28 17:12:20 -08:00
Nilstrieb
41e8d152dc Show number in error message even for one error
Co-authored-by: Adrian <adrian.iosdev@gmail.com>
2023-11-24 19:15:52 +01:00
Nilstrieb
4bb3ae39b7
Rollup merge of #118035 - ouz-a:november_ice2, r=compiler-errors
Fix early param lifetimes in generic_const_exprs

In cases like below, we never actually be able to capture region name for two reasons, first `'static` becomes anonymous lifetime and second we never capture region if it doesn't have a name so this results in ICE.
```
struct DataWrapper<'static> {
    data: &'a [u8; Self::SIZE],
}

impl DataWrapper<'a> {
```

Fixes https://github.com/rust-lang/rust/issues/118021
2023-11-21 14:36:14 +01:00
ouz-a
f68c6c9528 Fix early param lifetimes in generic_const_exprs 2023-11-20 23:13:36 +03:00
Nilstrieb
e5c330ac48 Note about object lifetime defaults in does not live long enough error
This is a aspect of Rust that frequently trips up people who are not
aware of it yet. This diagnostic attempts to explain what's happening
and why the lifetime constraint, that was never mentioned in the source,
arose.
2023-11-12 13:51:16 +01:00
Michael Goulet
4d5d763e05 Don't check for alias bounds in liveness when aliases have escaping bound vars 2023-11-02 10:25:57 +00:00
bors
ec2b311914 Auto merge of #116733 - compiler-errors:alias-liveness-but-this-time-sound, r=aliemjay
Consider alias bounds when computing liveness in NLL (but this time sound hopefully)

This is a revival of #116040, except removing the changes to opaque lifetime captures check to make sure that we're not triggering any unsoundness due to the lack of general existential regions and the currently-existing `ReErased` hack we use instead.

r? `@aliemjay` -- I appreciate you pointing out the unsoundenss in the previous iteration of this PR, and I'd like to hear that you're happy with this iteration of this PR before this goes back into FCP :>

Fixes #116794 as well

---

(mostly copied from #116040 and reworked slightly)

# Background

Right now, liveness analysis in NLL is a bit simplistic. It simply walks through all of the regions of a type and marks them as being live at points. This is problematic in the case of aliases, since it requires that we mark **all** of the regions in their args[^1] as live, leading to bugs like #42940.

In reality, we may be able to deduce that fewer regions are allowed to be present in the projected type (or "hidden type" for opaques) via item bounds or where clauses, and therefore ideally, we should be able to soundly require fewer regions to be live in the alias.

For example:
```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn capture<'o>(_: &'o mut ()) -> impl Sized + Captures<'o> + 'static {}

fn test_two_mut(mut x: ()) {
    let _f1 = capture(&mut x);
    let _f2 = capture(&mut x);
    //~^ ERROR cannot borrow `x` as mutable more than once at a time
}
```

In the example above, we should be able to deduce from the `'static` bound on `capture`'s opaque that even though `'o` is a captured region, it *can never* show up in the opaque's hidden type, and can soundly be ignored for liveness purposes.

# The Fix

We apply a simple version of RFC 1214's `OutlivesProjectionEnv` and `OutlivesProjectionTraitDef` rules to NLL's `make_all_regions_live` computation.

Specifically, when we encounter an alias type, we:
1. Look for a unique outlives bound in the param-env or item bounds for that alias. If there is more than one unique region, bail, unless any of the outlives bound's regions is `'static`, and in that case, prefer `'static`. If we find such a unique region, we can mark that outlives region as live and skip walking through the args of the opaque.
2. Otherwise, walk through the alias's args recursively, as we do today.

## Limitation: Multiple choices

This approach has some limitations. Firstly, since liveness doesn't use the same type-test logic as outlives bounds do, we can't really try several options when we're faced with a choice.

If we encounter two unique outlives regions in the param-env or bounds, we simply fall back to walking the opaque via its args. I expect this to be mostly mitigated by the special treatment of `'static`, and can be fixed in a forwards-compatible by a more sophisticated analysis in the future.

## Limitation: Opaque hidden types

Secondly, we do not employ any of these rules when considering whether the regions captured by a hidden type are valid. That causes this code (cc #42940) to fail:

```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn a() -> impl Sized + 'static {
    b(&vec![])
}

fn b<'o>(_: &'o Vec<i32>) -> impl Sized + Captures<'o> + 'static {}
```

We need to have existential regions to avoid [unsoundness](https://github.com/rust-lang/rust/pull/116040#issuecomment-1751628189) when an opaque captures a region which is not represented in its own substs but which outlives a region that does.

## Read more

Context: https://github.com/rust-lang/rust/pull/115822#issuecomment-1731153952 (for the liveness case)
More context: https://github.com/rust-lang/rust/issues/42940#issuecomment-455198309 (for the opaque capture case, which this does not fix)

[^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
2023-10-29 18:42:02 +00:00
Camille GILLOT
ec28dc7aa7 Use PlaceMention for match scrutinees. 2023-10-24 15:30:17 +00:00
Oli Scherer
e96ce20b34 s/generator/coroutine/ 2023-10-20 21:14:01 +00:00
Michael Goulet
f0e385d6b7 Flesh out tests more 2023-10-17 01:26:46 +00:00
Michael Goulet
371d8a8215 Consider static specially 2023-10-14 15:35:01 +01:00
Michael Goulet
e425d85518 Consider param-env candidates, too 2023-10-14 15:35:01 +01:00
Michael Goulet
184d5ef107 Consider alias bounds when considering lliveness for alias types in NLL 2023-10-14 15:35:01 +01:00
Alex Macleod
5453a9f34d Add a note to duplicate diagnostics 2023-10-05 01:04:41 +00:00
Camille GILLOT
211d2ed07b Bless tests. 2023-09-23 13:47:30 +00:00
bors
959b2c703d Auto merge of #115696 - RalfJung:closure-ty-print, r=oli-obk
adjust how closure/generator types are printed

I saw `&[closure@$DIR/issue-20862.rs:2:5]` and I thought it is a slice type, because that's usually what `&[_]` is... it took me a while to realize that this is just a confusing printer and actually there's no slice. Let's use something that cannot be mistaken for a regular type.
2023-09-22 15:19:38 +00:00
Ralf Jung
c4ec12f4b7 adjust how closure/generator types and rvalues are printed 2023-09-21 22:20:58 +02:00
Eduardo Sánchez Muñoz
c599761140 rustc_hir_analysis: add a helper to check function the signature mismatches
This function is now used to check `#[panic_handler]`, `start` lang item, `main`, `#[start]` and intrinsic functions.

The diagnosis produced are now closer to the ones produced by trait/impl method signature mismatch.
2023-09-19 18:15:23 +02:00
Ralf Jung
9ac8b363e3 don't point at const usage site for resolution-time errors
also share the code that emits the actual error
2023-09-14 22:34:05 +02:00