Commit Graph

1637 Commits

Author SHA1 Message Date
bors
3fba278231 Auto merge of #123537 - compiler-errors:shallow, r=lcnr
Simplify shallow resolver to just fold ty/consts

Probably faster than using a whole folder?
2024-04-16 21:59:36 +00:00
Guillaume Gomez
24cdb7ed56
Rollup merge of #123990 - compiler-errors:suggest-closure-ret-deref, r=oli-obk
Make `suggest_deref_closure_return` more idiomatic/easier to understand

The only functional change here really is just making it not use a fresh type variable for upvars. I'll point that out in the code.

The rest of the changes are just stylistic, because reading this code was really confusing me (variable names were vague, ways of accessing types were unidiomatic, order of operations was kind of strange, etc).

This is stacked on #123989.

r? oli-obk since you approved #122213
2024-04-16 15:19:14 +02:00
Guillaume Gomez
9da8f04da3
Rollup merge of #123797 - amandasystems:better-graphviz, r=oli-obk
Better graphviz output for SCCs and NLL constraints

This PR modifies the output for `-Z dump-mir-graphviz=yes`. Specifically, it changes the output of the files `.-------.nll.0.regioncx.all.dot` and `nll.0.regioncx.scc.dot` to be easier to read and contain some information that helped me during debugging. In particular:

- SCC indices are contracted to `SCC(n)` instead of `ConstraintSccIndex(n)` to compress the nodes
- SCC regions are in `{}` rather than `[]` (controversial since they are technically ordered by index, but I figured they're more sets than arrays conceptually since they're equivalence classes).
- For regions in other universes than the root, also show the region universe (as ?8/U1)
- For regions with external names, show the external name in parenthesis
- For the region graph where edges are locations, render the All variant of the enum without the file since it's extremely long and often destroys the rendering
- For region graph edge annotations for single locations, remove the wrapping around the Location variant and just add its contents since this can be unambiguously done

Example output (from the function `foo()` of `tests/ui/error-codes/E0582.rs`) for an SCC graph:
![a graph showing SCCs](https://github.com/rust-lang/rust/assets/102855/0b998338-0379-4829-b99e-d8105c094897)

...and for the constraints:
![a graph showing regions and their constraints](https://github.com/rust-lang/rust/assets/102855/e984c4ca-7aa2-4db2-9878-bf38fe8208d5)

This PR also gives `UniverseIndex`es the `is_root()` method since this is now an operation that happens three times in the borrowck crate.
2024-04-16 15:19:14 +02:00
Michael Goulet
00838b3140 Make suggest_deref_closure_return more idiomatic/easier to understand 2024-04-15 23:04:16 -04:00
León Orell Valerian Liehr
daa2ebc70c
Rollup merge of #123989 - compiler-errors:type-dependent-def-id, r=oli-obk
Just use `type_dependent_def_id` to figure out what the method is for an expr

The calls to `lookup_method_for_diagnostic` are overkill.

r? oli-obk
2024-04-16 01:12:39 +02:00
León Orell Valerian Liehr
9cc26b598a
Rollup merge of #123016 - compiler-errors:no-type-var-origin, r=lcnr
Remove `TypeVariableOriginKind` and `ConstVariableOriginKind`

It's annoying to have to import `TypeVariableOriginKind` just to fill it with `MiscVariable` for almost every use. Every other usage other than `TypeParameterDefinition` wasn't even used -- I can see how it may have been useful once for debugging, but I do quite a lot of typeck debugging and I've never really needed it.

So let's just remove it, and keep around the only useful thing which is the `DefId` of the param for `var_for_def`.

This is based on #123006, which removed the special use of `TypeVariableOriginKind::OpaqueInference`, which I'm pretty sure I was the one that added.

r? lcnr or re-roll to types
2024-04-16 01:12:36 +02:00
Michael Goulet
ecef296a03 Simplify shallow resolver to just fold ty/consts 2024-04-15 18:09:16 -04:00
Michael Goulet
98890be9c4 Rebase fallout 2024-04-15 17:37:56 -04:00
Michael Goulet
05bb3d2683 Just use type_dependent_def_id to figure out what the method is for an expr 2024-04-15 17:14:59 -04:00
Michael Goulet
34bce07e8e Remove TypeVariableOriginKind 2024-04-15 16:51:50 -04:00
Michael Goulet
20a5fb3b4a
Rollup merge of #123924 - compiler-errors:tuple-sugg, r=estebank
Fix various bugs in `ty_kind_suggestion`

Consolidates two implementations of `ty_kind_suggestion`
Fixes some misuse of the empty param-env
Fixes a problem where we suggested `(42)` instead of `(42,)` for tuple suggestions
Suggest a value when `return;`, making it consistent with `break;`
Fixes #123906
2024-04-15 15:18:06 -04:00
许杰友 Jieyou Xu (Joe)
5580ae9795
Rollup merge of #123934 - WaffleLapkin:graph-mini-refactor, r=fmease
`rustc_data_structures::graph` mini refactor

Who doesn't love to breathe dust from the ancient times?
2024-04-15 16:56:18 +01:00
Maybe Waffle
435db9b9bd Use RPITIT for Successors and Predecessors traits
Now with RPITIT instead of GAT!
2024-04-15 13:34:08 +00:00
Maybe Waffle
e8d2221e3b Make depth_first_search into a standalone function
Does not necessarily change much, but we never overwrite it, so I see no reason
for it to be in the `Successors` trait. (+we already have a similar `is_cyclic`)
2024-04-14 16:03:08 +00:00
Maybe Waffle
0d5fc9bf58 Merge {With,Graph}{Successors,Predecessors} into {Successors,Predecessors}
Now with GAT!
2024-04-14 15:48:53 +00:00
Maybe Waffle
398da593a5 Merge WithNumNodes into DirectedGraph 2024-04-14 15:46:40 +00:00
Michael Goulet
d6ac50e547 Consolidate two copies of ty_kind_suggestion 2024-04-14 09:42:53 -04:00
bors
6eaa7fb576 Auto merge of #122603 - estebank:clone-o-rama, r=lcnr
Detect borrow checker errors where `.clone()` would be an appropriate user action

When a value is moved twice, suggest cloning the earlier move:

```
error[E0509]: cannot move out of type `U2`, which implements the `Drop` trait
  --> $DIR/union-move.rs:49:18
   |
LL |         move_out(x.f1_nocopy);
   |                  ^^^^^^^^^^^
   |                  |
   |                  cannot move out of here
   |                  move occurs because `x.f1_nocopy` has type `ManuallyDrop<RefCell<i32>>`, which does not implement the `Copy` trait
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |         move_out(x.f1_nocopy.clone());
   |                             ++++++++
```

When a value is borrowed by an `fn` call, consider if cloning the result of the call would be reasonable, and suggest cloning that, instead of the argument:

```
error[E0505]: cannot move out of `a` because it is borrowed
  --> $DIR/variance-issue-20533.rs:53:14
   |
LL |         let a = AffineU32(1);
   |             - binding `a` declared here
LL |         let x = bat(&a);
   |                     -- borrow of `a` occurs here
LL |         drop(a);
   |              ^ move out of `a` occurs here
LL |         drop(x);
   |              - borrow later used here
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |         let x = bat(&a).clone();
   |                        ++++++++
```

otherwise, suggest cloning the argument:

```
error[E0505]: cannot move out of `a` because it is borrowed
  --> $DIR/variance-issue-20533.rs:59:14
   |
LL |         let a = ClonableAffineU32(1);
   |             - binding `a` declared here
LL |         let x = foo(&a);
   |                     -- borrow of `a` occurs here
LL |         drop(a);
   |              ^ move out of `a` occurs here
LL |         drop(x);
   |              - borrow later used here
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL -         let x = foo(&a);
LL +         let x = foo(a.clone());
   |
```

This suggestion doesn't attempt to square out the types between what's cloned and what the `fn` expects, to allow the user to make a determination on whether to change the `fn` call or `fn` definition themselves.

Special case move errors caused by `FnOnce`:

```
error[E0382]: use of moved value: `blk`
  --> $DIR/once-cant-call-twice-on-heap.rs:8:5
   |
LL | fn foo<F:FnOnce()>(blk: F) {
   |                    --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
LL |     blk();
   |     ----- `blk` moved due to this call
LL |     blk();
   |     ^^^ value used here after move
   |
note: `FnOnce` closures can only be called once
  --> $DIR/once-cant-call-twice-on-heap.rs:6:10
   |
LL | fn foo<F:FnOnce()>(blk: F) {
   |          ^^^^^^^^ `F` is made to be an `FnOnce` closure here
LL |     blk();
   |     ----- this value implements `FnOnce`, which causes it to be moved when called
```

Account for redundant `.clone()` calls in resulting suggestions:

```
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).into_iter() {}
   |                  ++++++++++++++++++++++++++++++    ~
```

We use the presence of `&mut` values in a move error as a proxy for the user caring about side effects, so we don't emit a clone suggestion in that case:

```
error[E0505]: cannot move out of `s` because it is borrowed
  --> $DIR/borrowck-overloaded-index-move-index.rs:53:7
   |
LL |     let mut s = "hello".to_string();
   |         ----- binding `s` declared here
LL |     let rs = &mut s;
   |              ------ borrow of `s` occurs here
...
LL |     f[s] = 10;
   |       ^ move out of `s` occurs here
...
LL |     use_mut(rs);
   |             -- borrow later used here
```

We properly account for `foo += foo;` errors where we *don't* suggest `foo.clone() += foo;`, instead suggesting `foo += foo.clone();`.

---

Each commit can be reviewed in isolation. There are some "cleanup" commits, but kept them separate in order to show *why* specific changes were being made, and their effect on tests' output.

Fix #49693, CC #64167.
2024-04-13 09:07:26 +00:00
Esteban Küber
4c7213c888 review comments
Added comments and reworded messages
2024-04-12 20:57:07 +00:00
Esteban Küber
dea9b5031c Better account for more cases involving closures 2024-04-12 04:46:31 +00:00
Esteban Küber
3cdc6897c5 Fix rebase 2024-04-12 04:45:50 +00:00
Matthias Krüger
6f78bf2322
Rollup merge of #123599 - matthiaskrgr:rm, r=cjgillot
remove some things that do not need to be
2024-04-12 04:38:21 +02:00
Matthias Krüger
ec91d71a38
Rollup merge of #123523 - estebank:issue-123414, r=BoxyUwU
Account for trait/impl difference when suggesting changing argument from ref to mut ref

Do not ICE when encountering a lifetime error involving an argument with an immutable reference of a method that differs from the trait definition.

Fix #123414.
2024-04-11 22:38:54 +02:00
Matthias Krüger
f9ca213510 remove some things that do not need to be 2024-04-11 21:09:52 +02:00
Esteban Küber
d97d2fe744 Mention when the type of the moved value doesn't implement Clone 2024-04-11 16:41:42 +00:00
Esteban Küber
d578ac9e47 Account for move error in the spread operator on struct literals
We attempt to suggest an appropriate clone for move errors on expressions
like `S { ..s }` where a field isn't `Copy`. If we can't suggest, we still don't
emit the incorrect suggestion of `S { ..s }.clone()`.

```
error[E0509]: cannot move out of type `S<K>`, which implements the `Drop` trait
  --> $DIR/borrowck-struct-update-with-dtor.rs:28:19
   |
LL |         let _s2 = S { a: 2, ..s0 };
   |                   ^^^^^^^^^^^^^^^^
   |                   |
   |                   cannot move out of here
   |                   move occurs because `s0.c` has type `K`, which does not implement the `Copy` trait
   |
help: clone the value from the field instead of using the spread operator syntax
   |
LL |         let _s2 = S { a: 2, c: s0.c.clone(), ..s0 };
   |                           +++++++++++++++++
```
```
error[E0509]: cannot move out of type `S<()>`, which implements the `Drop` trait
  --> $DIR/borrowck-struct-update-with-dtor.rs:20:19
   |
LL |         let _s2 = S { a: 2, ..s0 };
   |                   ^^^^^^^^^^^^^^^^
   |                   |
   |                   cannot move out of here
   |                   move occurs because `s0.b` has type `B`, which does not implement the `Copy` trait
   |
note: `B` doesn't implement `Copy` or `Clone`
  --> $DIR/borrowck-struct-update-with-dtor.rs:4:1
   |
LL | struct B;
   | ^^^^^^^^
help: if `B` implemented `Clone`, you could clone the value from the field instead of using the spread operator syntax
   |
LL |         let _s2 = S { a: 2, b: s0.b.clone(), ..s0 };
   |                           +++++++++++++++++
```
2024-04-11 16:41:42 +00:00
Esteban Küber
4ca876b7a4 Better account for FnOnce in move errors
```
error[E0382]: use of moved value: `blk`
  --> $DIR/once-cant-call-twice-on-heap.rs:8:5
   |
LL | fn foo<F:FnOnce()>(blk: F) {
   |                    --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
LL |     blk();
   |     ----- `blk` moved due to this call
LL |     blk();
   |     ^^^ value used here after move
   |
note: `FnOnce` closures can only be called once
  --> $DIR/once-cant-call-twice-on-heap.rs:6:10
   |
LL | fn foo<F:FnOnce()>(blk: F) {
   |          ^^^^^^^^ `F` is made to be an `FnOnce` closure here
LL |     blk();
   |     ----- this value implements `FnOnce`, which causes it to be moved when called
```
2024-04-11 16:41:42 +00:00
Esteban Küber
dfe28debb9 Account for assign binops in clone suggestions
Explicitly look for `expr += other_expr;` and avoid suggesting
`expr.clone() += other_expr;`, instead suggesting `expr += other_expr.clone();`.
2024-04-11 16:41:41 +00:00
Esteban Küber
a1a3abb08f When possible, suggest cloning the result of a call instead of an argument
```
error[E0505]: cannot move out of `a` because it is borrowed
  --> $DIR/variance-issue-20533.rs:28:14
   |
LL |         let a = AffineU32(1);
   |             - binding `a` declared here
LL |         let x = foo(&a);
   |                     -- borrow of `a` occurs here
LL |         drop(a);
   |              ^ move out of `a` occurs here
LL |         drop(x);
   |              - borrow later used here
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |         let x = foo(&a).clone();
   |                        ++++++++
```
2024-04-11 16:41:41 +00:00
Esteban Küber
7f7f6792f1 Do not recomment cloning explicit &mut expressions 2024-04-11 16:41:41 +00:00
Esteban Küber
5a7caa3174 Fix accuracy of T: Clone check in suggestion 2024-04-11 16:41:41 +00:00
Esteban Küber
259348cf7e Remove unnecessary argument from suggest_cloning 2024-04-11 16:41:41 +00:00
Esteban Küber
01b810e052 Silence redundant clone suggestion 2024-04-11 16:41:41 +00:00
Esteban Küber
065454dd1d More move error suggestions to clone
```
error[E0507]: cannot move out of `val`, a captured variable in an `FnMut` closure
  --> $DIR/issue-87456-point-to-closure.rs:10:28
   |
LL |     let val = String::new();
   |         --- captured outer variable
LL |
LL |     take_mut(|| {
   |              -- captured by this `FnMut` closure
LL |
LL |         let _foo: String = val;
   |                            ^^^ move occurs because `val` has type `String`, which does not implement the `Copy` trait
   |
help: consider borrowing here
   |
LL |         let _foo: String = &val;
   |                            +
help: consider cloning the value if the performance cost is acceptable
   |
LL |         let _foo: String = val.clone();
   |                               ++++++++
```
2024-04-11 16:41:41 +00:00
Esteban Küber
10c2fbec24 Suggest .clone() in some move errors
```
error[E0507]: cannot move out of `*x` which is behind a shared reference
  --> $DIR/borrowck-fn-in-const-a.rs:6:16
   |
LL |         return *x
   |                ^^ move occurs because `*x` has type `String`, which does not implement the `Copy` trait
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL -         return *x
LL +         return x.clone()
   |
```
2024-04-11 16:41:41 +00:00
Esteban Küber
bce78102c3 Account for unops when suggesting cloning 2024-04-11 16:41:41 +00:00
Esteban Küber
fa2fc3ab96 Suggest .clone() when moved while borrowed 2024-04-11 16:41:41 +00:00
Esteban Küber
5eb573a343 Account for .clone() when suggesting <T as Clone>::clone 2024-04-11 16:41:40 +00:00
Amanda Stjerna
800c50608c Slightly more readable NLL/constraint graph dumps 2024-04-11 17:14:35 +02:00
Matthias Krüger
93645f481d
Rollup merge of #123704 - estebank:diag-changes, r=compiler-errors
Tweak value suggestions in `borrowck` and `hir_analysis`

Unify the output of `suggest_assign_value` and `ty_kind_suggestion`.

Ideally we'd make these a single function, but doing so would likely require modify the crate dependency tree.
2024-04-11 09:31:50 +02:00
bors
08273780d8 Auto merge of #122213 - estebank:issue-50195, r=oli-obk,estebank
Provide suggestion to dereference closure tail if appropriate

When encoutnering a case like

```rust
use std::collections::HashMap;

fn main() {
    let vs = vec![0, 0, 1, 1, 3, 4, 5, 6, 3, 3, 3];

    let mut counts = HashMap::new();
    for num in vs {
        let count = counts.entry(num).or_insert(0);
        *count += 1;
    }

    let _ = counts.iter().max_by_key(|(_, v)| v);
```
produce the following suggestion
```
error: lifetime may not live long enough
  --> $DIR/return-value-lifetime-error.rs:13:47
   |
LL |     let _ = counts.iter().max_by_key(|(_, v)| v);
   |                                       ------- ^ returning this value requires that `'1` must outlive `'2`
   |                                       |     |
   |                                       |     return type of closure is &'2 &i32
   |                                       has type `&'1 (&i32, &i32)`
   |
help: dereference the return value
   |
LL |     let _ = counts.iter().max_by_key(|(_, v)| **v);
   |                                               ++
```

Fix #50195.
2024-04-11 02:37:35 +00:00
Esteban Küber
1eda0565fa Handle more cases of "values to suggest" given a type
Add handling for `String`, `Box`, `Option` and `Result`.
2024-04-10 23:58:36 +00:00
Esteban Küber
e17388b809 Handle more cases of value suggestions 2024-04-10 20:36:14 +00:00
Oli Scherer
f2465f8f20 Use trait solver to answer questions instead of manually writing a trait solver 2024-04-10 05:22:43 +00:00
Esteban Küber
a983dd8563 Tweak value suggestions in borrowck and hir_analysis
Unify the output of `suggest_assign_value` and `ty_kind_suggestion`.

Ideally we'd make these a single function, but doing so would likely require modify the crate dependency tree.
2024-04-09 23:37:13 +00:00
bors
b234e44944 Auto merge of #122077 - oli-obk:eager_opaque_checks4, r=lcnr
Pass list of defineable opaque types into canonical queries

This eliminates `DefiningAnchor::Bubble` for good and brings the old solver closer to the new one wrt cycles and nested obligations. At that point the difference between `DefiningAnchor::Bind([])` and `DefiningAnchor::Error` was academic. We only used the difference for some sanity checks, which actually had to be worked around in places, so I just removed `DefiningAnchor` entirely and just stored the list of opaques that may be defined.

fixes #108498
fixes https://github.com/rust-lang/rust/issues/116877

* [x] run crater
  - https://github.com/rust-lang/rust/pull/122077#issuecomment-2013293931
2024-04-08 23:01:50 +00:00
Oli Scherer
2f2350e577 Eliminate DefiningAnchor now that is just a single-variant enum 2024-04-08 15:00:27 +00:00
Oli Scherer
b2b5fa825d Eagerly check for accidentally registered region constraints instead of waiting until borrowck is done 2024-04-08 15:00:26 +00:00
Oli Scherer
19bd91d128 Pass list of defineable opaque types into canonical queries 2024-04-08 15:00:26 +00:00
Oli Scherer
84acfe86de Actually create ranged int types in the type system. 2024-04-08 12:02:19 +00:00
Esteban Küber
731c0e59a4 Account for trait/impl difference when suggesting changing argument from ref to mut ref
Do not ICE when encountering a lifetime error involving an argument with
an immutable reference of a method that differs from the trait definition.

Fix #123414.
2024-04-06 16:23:10 +00:00
Esteban Küber
9de6b70bb6 Provide suggestion to dereference closure tail if appropriate
When encoutnering a case like

```rust
//@ run-rustfix
use std::collections::HashMap;

fn main() {
    let vs = vec![0, 0, 1, 1, 3, 4, 5, 6, 3, 3, 3];

    let mut counts = HashMap::new();
    for num in vs {
        let count = counts.entry(num).or_insert(0);
        *count += 1;
    }

    let _ = counts.iter().max_by_key(|(_, v)| v);
```
produce the following suggestion
```
error: lifetime may not live long enough
  --> $DIR/return-value-lifetime-error.rs:13:47
   |
LL |     let _ = counts.iter().max_by_key(|(_, v)| v);
   |                                       ------- ^ returning this value requires that `'1` must outlive `'2`
   |                                       |     |
   |                                       |     return type of closure is &'2 &i32
   |                                       has type `&'1 (&i32, &i32)`
   |
help: dereference the return value
   |
LL |     let _ = counts.iter().max_by_key(|(_, v)| **v);
   |                                               ++
```

Fix #50195.
2024-04-05 19:42:55 +00:00
Matthias Krüger
25b0e84170
Rollup merge of #123419 - petrochenkov:zeroindex, r=compiler-errors
rustc_index: Add a `ZERO` constant to index types

It is commonly used.
2024-04-03 22:11:02 +02:00
Vadim Petrochenkov
b40ea03f8a rustc_index: Add a ZERO constant to index types
It is commonly used.
2024-04-03 19:06:22 +03:00
joboet
989660c3e6
rename expose_addr to expose_provenance 2024-04-03 16:00:38 +02:00
Jacob Pratt
e9ef8e1efa
Rollup merge of #122935 - RalfJung:with-exposed-provenance, r=Amanieu
rename ptr::from_exposed_addr -> ptr::with_exposed_provenance

As discussed on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-opsem/topic/To.20expose.20or.20not.20to.20expose/near/427757066).

The old name, `from_exposed_addr`, makes little sense as it's not the address that is exposed, it's the provenance. (`ptr.expose_addr()` stays unchanged as we haven't found a better option yet. The intended interpretation is "expose the provenance and return the address".)

The new name nicely matches `ptr::without_provenance`.
2024-04-02 20:37:39 -04:00
Michael Goulet
bda301ead8 Stop calling visitors V 2024-03-30 11:13:33 -04:00
Matthias Krüger
8d820c0c47
Rollup merge of #123188 - klensy:clippy-me2, r=Nilstrieb
compiler: fix few unused_peekable and needless_pass_by_ref_mut clippy lints

This fixes few instances of `unused_peekable` and `needless_pass_by_ref_mut`. While i expected to fix more warnings, `needless_pass_by_ref_mut` produced too much for one PR, so i stopped here.

Better reviewed commit by commit, as fixes splitted by chunks.
2024-03-29 15:17:11 +01:00
bors
45796d1c24 Auto merge of #123080 - Jules-Bertholet:mut-ref-mut, r=Nadrieril
Match ergonomics 2024: implement mutable by-reference bindings

Implements the mutable by-reference bindings portion of match ergonomics 2024 (#123076), with the `mut ref`/`mut ref mut` syntax, under feature gate `mut_ref`.

r? `@Nadrieril`

`@rustbot` label A-patterns A-edition-2024
2024-03-29 11:08:11 +00:00
klensy
9a6b3dfc06 and few more
maybe bug here?

warning: this argument is a mutable reference, but not used mutably
    --> compiler\rustc_borrowck\src\diagnostics\conflict_errors.rs:3857:35
     |
3857 |     pub(crate) fn emit(&self, cx: &mut MirBorrowckCtxt<'_, 'tcx>, diag: &mut Diag<'_>) -> String {
     |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&MirBorrowckCtxt<'_, 'tcx>`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
   --> compiler\rustc_borrowck\src\type_check\liveness\trace.rs:601:17
    |
601 |         typeck: &mut TypeChecker<'_, 'tcx>,
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&TypeChecker<'_, 'tcx>`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
2024-03-28 16:57:32 +03:00
bors
551abd65be Auto merge of #116891 - aliemjay:opaque-region-infer-rework-2, r=compiler-errors,oli-obk
rework opaque type region inference

User-facing changes are documented in [this comment](https://github.com/rust-lang/rust/pull/116891#issuecomment-1973774412).

The design document is in [this comment](https://github.com/rust-lang/rust/pull/116891#issuecomment-1836900102).

---

\- Fix Ice in check_unique; ICE -> Error; fixes #122782.
\- Ignore uncaptured lifetime args; ICE -> Pass; fixes #111906, fixes #110623, fixes #109059, fixes #122307
\- Except equal parameters from the uniqueness check; Pass -> Error; fixes #113916.
\- Check RPITs for invalid args; Pass -> Error; fixes #111935; ICE -> Error; fixes #110726.
\- Rework opaque types region inference; Pass -> Error; fixes #113971, fixes #112841.
\- Reject external lifetimes as invalid args; Pass -> Error; fixes #105498.

r? `@ghost`
2024-03-28 09:51:39 +00:00
Ali MJ Al-Nasrawy
7c6876f9a9 simplify check_unique 2024-03-28 06:00:26 +00:00
Ali MJ Al-Nasrawy
6b6ed2ea28 reject external lifetimes as invalid arguments 2024-03-28 06:00:26 +00:00
Ali MJ Al-Nasrawy
f4940e4d22 rework opaque types region inference 2024-03-28 06:00:26 +00:00
Ali MJ Al-Nasrawy
08c8caa524 convert all named regions in opaque types to nll vars
Do it in typeck before entering region inference routines
particularly because we will no longer be able to convert placeholders.
2024-03-28 06:00:26 +00:00
Ali MJ Al-Nasrawy
15c7e59c05 favor placeholders over existentials when choosing SCC representatives
... even when the existential has the least RegionVid.

universal regions (of root universe) > placeholders > existentials

The previous behavior, that chooses the minimal RegionVid index, naturally prefers universal regions over others
because they always have the least RegionVids, but there was no guranteed ordering between placeholders and existentials.
2024-03-28 06:00:26 +00:00
Ali MJ Al-Nasrawy
ce91e46a1e check RPITs for invalid args 2024-03-28 06:00:26 +00:00
Ali MJ Al-Nasrawy
c337825d6d ignore error params 2024-03-28 06:00:25 +00:00
Ali MJ Al-Nasrawy
4ecdf5ff00 except equal parameters from the uniqueness check 2024-03-28 06:00:25 +00:00
xiaoxiangxianzi
3157114f0b chore: fix some comments
Signed-off-by: xiaoxiangxianzi <zhaoyizheng@outlook.com>
2024-03-27 22:32:53 +08:00
Jules Bertholet
e0da13f25f
Implement mut ref/mut ref mut 2024-03-27 09:53:23 -04:00
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
Ali MJ Al-Nasrawy
4e1999d387 ignore uncaptured lifetimes when checking opaques 2024-03-26 09:26:23 +00:00
Ali MJ Al-Nasrawy
92f40b8059 fix ICE in check_unique 2024-03-26 09:26:23 +00:00
Matthias Krüger
9b4ee1be9e
Rollup merge of #122970 - cuviper:use-chunk_by, r=Mark-Simulacrum
Use `chunk_by` when building `ReverseSccGraph`

With stable `chunk_by` in Rust 1.77, this code doesn't need `Itertools::group_by` anymore.
2024-03-25 17:05:33 +01:00
Jubilee
c94d229337
Rollup merge of #122969 - cuviper:borrowck-rposition, r=matthewjasper
Simplify an iterator search in borrowck diag

Rather than `.into_iter().rev().find_position(...)`, this case can
simply call `.iter().rposition(...)`.
2024-03-23 22:59:43 -07:00
Josh Stone
87808e71be Use chunk_by when building ReverseSccGraph 2024-03-23 17:30:12 -07:00
Josh Stone
66f1e14cc3 Simplify an iterator search in borrowck diag
Rather than `.into_iter().rev().find_position(...)`, this case can
simply call `.iter().rposition(...)`.
2024-03-23 17:24:13 -07:00
bors
2f090c30dd Auto merge of #122629 - RalfJung:assert-unsafe-precondition, r=saethlin
refactor check_{lang,library}_ub: use a single intrinsic

This enacts the plan I laid out [here](https://github.com/rust-lang/rust/pull/122282#issuecomment-1996917998): use a single intrinsic, called `ub_checks` (in aniticpation of https://github.com/rust-lang/compiler-team/issues/725), that just exposes the value of `debug_assertions` (consistently implemented in both codegen and the interpreter). Put the language vs library UB logic into the library.

This makes it easier to do something like https://github.com/rust-lang/rust/pull/122282 in the future: that just slightly alters the semantics of `ub_checks` (making it more approximating when crates built with different flags are mixed), but it no longer affects whether these checks can happen in Miri or compile-time.

The first commit just moves things around; I don't think these macros and functions belong into `intrinsics.rs` as they are not intrinsics.

r? `@saethlin`
2024-03-23 21:11:00 +00:00
Daniel Sedlak
2c433d0e9c Fix typos 2024-03-23 20:25:54 +01:00
Daniel Sedlak
0c7f8b0f89 Fix diagnostics for async block cloning 2024-03-23 20:22:51 +01:00
Ralf Jung
6177530420 refactor check_{lang,library}_ub: use a single intrinsic, put policy into library 2024-03-23 18:45:05 +01:00
Matthias Krüger
99e34b4f7a
Rollup merge of #122780 - GuillaumeGomez:rename-hir-local, r=oli-obk
Rename `hir::Local` into `hir::LetStmt`

Follow-up of #122776.

As discussed on [zulip](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Improve.20naming.20of.20.60ExprKind.3A.3ALet.60.3F).

I made this change into a separate PR because I'm less sure about this change as is. For example, we have `visit_local` and `LocalSource` items. Is it fine to keep these two as is (I supposed it is but I prefer to ask) or not? Having `Node::Local(LetStmt)` makes things more explicit but is it going too far?

r? ```@oli-obk```
2024-03-23 15:00:18 +01:00
Ralf Jung
038e7c6c38 rename MIR int2ptr casts to match library name 2024-03-23 13:18:33 +01:00
bors
c308726599 Auto merge of #119552 - krtab:dead_code_priv_mod_pub_field, r=cjgillot,saethlin
Replace visibility test with reachability test in dead code detection

Fixes https://github.com/rust-lang/rust/issues/119545

Also included is a fix for an error now flagged by the lint
2024-03-23 00:37:05 +00:00
bors
0ad5e0d2de Auto merge of #122900 - matthiaskrgr:rollup-nls90mb, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #114009 (compiler: allow transmute of ZST arrays with generics)
 - #122195 (Note that the caller chooses a type for type param)
 - #122651 (Suggest `_` for missing generic arguments in turbofish)
 - #122784 (Add `tag_for_variant` query)
 - #122839 (Split out `PredicatePolarity` from `ImplPolarity`)
 - #122873 (Merge my contributor emails into one using mailmap)
 - #122885 (Adjust better spastorino membership to triagebot's adhoc_groups)
 - #122888 (add a couple more tests)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-22 22:35:11 +00:00
Guillaume Gomez
e0d3439226 Rename hir::Node::Local into hir::Node::LetStmt 2024-03-22 20:48:36 +01:00
Guillaume Gomez
b376f49e30 Rename hir::Local into hir::LetStmt 2024-03-22 20:36:21 +01:00
Michael Goulet
4b87c0b9c9 Split out ImplPolarity and PredicatePolarity 2024-03-22 11:16:56 -04:00
Michael Goulet
7be0dbe772 Make RawPtr take Ty and Mutbl separately 2024-03-22 11:13:29 -04:00
Michael Goulet
ff0c31e6b9 Programmatically convert some of the pat ctors 2024-03-22 11:13:29 -04:00
Matthias Krüger
40c972e335
Rollup merge of #122733 - oli-obk:error_prop, r=compiler-errors
Strip placeholders from hidden types before remapping generic parameter

When remapping generic parameters in the hidden type to the generic parameters of the definition of the opaque, we assume that placeholders cannot exist. Instead of just patching that site, I decided to handle it earlier, directly in `infer_opaque_types`, where we are already doing all the careful lifetime handling.

fixes #122694

the reason that ICE now occurred was that we stopped treating `operation` as being in the defining scope, so the TAIT became part of the hidden type of the `async fn`'s opaque type instead of just bailing out as ambiguos

I think

```rust
use std::future::Future;

mod foo {
    type FutNothing<'a> = impl 'a + Future<Output = ()>;
    //~^ ERROR: unconstrained opaque type
}

async fn operation(_: &mut ()) -> () {
    //~^ ERROR: concrete type differs from previous
    call(operation).await
    //~^ ERROR: concrete type differs from previous
}

async fn call<F>(_f: F)
where
    for<'any> F: FnMut(&'any mut ()) -> foo::FutNothing<'any>,
{
    //~^ ERROR: expected generic lifetime parameter, found `'any`
}
```

would have already had the same ICE before https://github.com/rust-lang/rust/pull/121796
2024-03-21 17:46:49 +01:00
Oli Scherer
6623bdf68b Strip placeholders from hidden types before remapping generic parameter in the hidden type to the generic parameters of the definition of the opaque 2024-03-21 08:17:12 +00:00
bors
47dd709bed Auto merge of #121123 - compiler-errors:item-assumptions, r=oli-obk
Split an item bounds and an item's super predicates

This is the moral equivalent of #107614, but instead for predicates this applies to **item bounds**. This PR splits out the item bounds (i.e. *all* predicates that are assumed to hold for the alias) from the item *super predicates*, which are the subset of item bounds which share the same self type as the alias.

## Why?

Much like #107614, there are places in the compiler where we *only* care about super-predicates, and considering predicates that possibly don't have anything to do with the alias is problematic. This includes things like closure signature inference (which is at its core searching for `Self: Fn(..)` style bounds), but also lints like `#[must_use]`, error reporting for aliases, computing type outlives predicates.

Even in cases where considering all of the `item_bounds` doesn't lead to bugs, unnecessarily considering irrelevant bounds does lead to a regression (#121121) due to doing extra work in the solver.

## Example 1 - Trait Aliases

This is best explored via an example:

```
type TAIT<T> = impl TraitAlias<T>;

trait TraitAlias<T> = A + B where T: C;
```

The item bounds list for `Tait<T>` will include:
* `Tait<T>: A`
* `Tait<T>: B`
* `T: C`

While `item_super_predicates` query will include just the first two predicates.

Side-note: You may wonder why `T: C` is included in the item bounds for `TAIT`? This is because when we elaborate `TraitAlias<T>`, we will also elaborate all the predicates on the trait.

## Example 2 - Associated Type Bounds

```
type TAIT<T> = impl Iterator<Item: A>;
```

The `item_bounds` list for `TAIT<T>` will include:
* `Tait<T>: Iterator`
* `<Tait<T> as Iterator>::Item: A`

But the `item_super_predicates` will just include the first bound, since that's the only bound that is relevant to the *alias* itself.

## So what

This leads to some diagnostics duplication just like #107614, but none of it will be user-facing. We only see it in the UI test suite because we explicitly disable diagnostic deduplication.

Regarding naming, I went with `super_predicates` kind of arbitrarily; this can easily be changed, but I'd consider better names as long as we don't block this PR in perpetuity.
2024-03-21 06:12:24 +00:00
Jacob Pratt
4e792df4ed
Rollup merge of #122749 - aliemjay:region-err, r=compiler-errors
make `type_flags(ReError) & HAS_ERROR`

Self-explanatory. `TypeVisitableExt::references_error(ReError)` incorrectly returned `false`.
2024-03-20 20:29:45 -04:00
Ali MJ Al-Nasrawy
19e0ea4a6d make type_flags(ReError) & HAS_ERROR 2024-03-20 17:29:58 +00:00
Michael Goulet
aa39dbb962 Split item bounds and item super predicates 2024-03-20 13:00:34 -04:00
bors
c86f3ac24f Auto merge of #120717 - compiler-errors:cap-closure-kind, r=oli-obk
For async closures, cap closure kind, get rid of `by_mut_body`

Right now we have three `AsyncFn*` traits, and three corresponding futures that are returned by the `call_*` functions for them. This is fine, but it is a bit excessive, since the future returned by `AsyncFn` and `AsyncFnMut` are identical. Really, the only distinction we need to make with these bodies is "by ref" and "by move".

This PR removes `AsyncFn::CallFuture` and renames `AsyncFnMut::CallMutFuture` to `AsyncFnMut::CallRefFuture`. This simplifies MIR building for async closures, since we don't need to build an extra "by mut" body, but just a "by move" body which is materially different.

We need to do a bit of delicate handling of the ClosureKind for async closures, since we need to "cap" it to `AsyncFnMut` in some cases when we only care about what body we're looking for.

This also fixes a bug where `<{async closure} as Fn>::call` was returning a body that takes the async-closure receiver *by move*.

This also helps align the `AsyncFn` traits to the `LendingFn` traits' eventual designs.
2024-03-20 11:40:45 +00:00
Michael Goulet
05116c5c30 Only split by-ref/by-move futures for async closures 2024-03-19 16:59:23 -04:00
bors
a7e4de13c1 Auto merge of #116935 - oli-obk:different_lifetime_taits_in_same_sig, r=compiler-errors
Prevent opaque types being instantiated twice with different regions within the same function

addresses https://github.com/orgs/rust-lang/projects/22/views/1?pane=issue&itemId=41329537

r? `@compiler-errors`
2024-03-19 19:57:51 +00:00