Commit Graph

3841 Commits

Author SHA1 Message Date
Matthias Krüger 3051dde87f
Rollup merge of #116975 - ojeda:move-invalid-test, r=Nilstrieb
Move `invalid-llvm-passes` test to `invalid-compile-flags` folder

Nowadays there is an `invalid-compile-flags` folder, thus move this one there.
2023-10-21 13:58:34 +02:00
Matthias Krüger 05e154fdb7
Rollup merge of #106601 - estebank:match-semi, r=cjgillot
Suggest `;` after bare `match` expression E0308

Fix #72634.
2023-10-21 13:58:33 +02:00
Lukas Markeffsky ccc4638d73 fix spans for removing `.await` on `for` expressions 2023-10-21 13:18:00 +02:00
bors 786c94a4eb Auto merge of #116734 - Nadrieril:lint-per-column, r=cjgillot
Lint `non_exhaustive_omitted_patterns` by columns

This is a rework of the `non_exhaustive_omitted_patterns` lint to make it more consistent. The intent of the lint is to help consumers of `non_exhaustive` enums ensure they stay up-to-date with all upstream variants. This rewrite fixes two cases we didn't handle well before:

First, because of details of exhaustiveness checking, the following wouldn't lint `Enum::C` as missing:
```rust
match Some(x) {
    Some(Enum::A) => {}
    Some(Enum::B) => {}
    _ => {}
}
```

Second, because of the fundamental workings of exhaustiveness checking, the following would treat the `true` and `false` cases separately and thus lint about missing variants:
```rust
match (true, x) {
    (true, Enum::A) => {}
    (true, Enum::B) => {}
    (false, Enum::C) => {}
    _ => {}
}
```
Moreover, it would correctly not lint in the case where the pair is flipped, because of asymmetry in how exhaustiveness checking proceeds.

A drawback is that it no longer makes sense to set the lint level per-arm. This will silently break the lint for current users of it (but it's behind a feature gate so that's ok).

The new approach is now independent of the exhaustiveness algorithm; it's a separate pass that looks at patterns column by column. This is another of the motivations for this: I'm glad to move it out of the algorithm, it was akward there.

This PR is almost identical to https://github.com/rust-lang/rust/pull/111651. cc `@eholk` who reviewed it at the time. Compared to then, I'm more confident this is the right approach.
2023-10-21 11:04:19 +00:00
Camille GILLOT 8d535070a2 Do not report errors from move path builder. 2023-10-21 10:29:40 +00:00
Matthias Krüger e9d18f5f78
Rollup merge of #116995 - estebank:issue-69944, r=compiler-errors
Point at assoc fn definition on type param divergence

When the number of type parameters in the associated function of an impl and its trait differ, we now *always* point at the trait one, even if it comes from a foreign crate. When it is local, we point at the specific params, when it is foreign, we point at the whole associated item.

Fix #69944.
2023-10-21 10:08:18 +02:00
Matthias Krüger dd66bc86be
Rollup merge of #116990 - estebank:issue-68445, r=cjgillot
Mention `into_iter` on borrow errors suggestions when appropriate

If we encounter a borrow error on `vec![1, 2, 3].iter()`, suggest `into_iter`.

Fix #68445.
2023-10-21 10:08:18 +02:00
Matthias Krüger c5dd84d493
Rollup merge of #116961 - estebank:issue-60164, r=oli-obk
Typo suggestion to change bindings with leading underscore

When encountering a binding that isn't found but has a typo suggestion for a binding with a leading underscore, suggest changing the binding definition instead of the use place.

Fix #60164.
2023-10-21 10:08:16 +02:00
Matthias Krüger 3fd7175db4
Rollup merge of #116911 - estebank:issue-85378, r=oli-obk
Suggest relaxing implicit `type Assoc: Sized;` bound

Fix #85378.
2023-10-21 10:08:15 +02:00
Esteban Küber 939a224ce3 Point at assoc fn definition on type param divergence
When the number of type parameters in the associated function of an impl
and its trait differ, we now *always* point at the trait one, even if it
comes from a foreign crate. When it is local, we point at the specific
params, when it is foreign, we point at the whole associated item.

Fix #69944.
2023-10-20 22:11:01 +00:00
Oli Scherer 5c1872d7ae Rename `generator` folder 2023-10-20 21:14:02 +00:00
Oli Scherer af93c20c06 Rename lots of files that had `generator` in their name 2023-10-20 21:14:02 +00:00
Oli Scherer 82ffd58bfb Rename `Gen` to `Coro` in tests 2023-10-20 21:14:02 +00:00
Oli Scherer e96ce20b34 s/generator/coroutine/ 2023-10-20 21:14:01 +00:00
Oli Scherer 60956837cf s/Generator/Coroutine/ 2023-10-20 21:10:38 +00:00
Esteban Küber 88bccf454f Mention `into_iter` on borrow errors suggestions when appropriate
If we encounter a borrow error on `vec![1, 2, 3].iter()`, suggest
`into_iter`.

Fix #68445.
2023-10-20 18:50:25 +00:00
Esteban Küber b0d17f35d9 Typo suggestion to change bindings with leading underscore
When encountering a binding that isn't found but has a typo suggestion
for a binding with a leading underscore, suggest changing the binding
definition instead of the use place.

Fix #60164.
2023-10-20 15:58:25 +00:00
bors 274455a9d1 Auto merge of #116965 - estebank:issue-65329, r=cjgillot
Move where doc comment meant as comment check

The new place makes more sense and covers more cases beyond individual statements.

```
error: expected one of `.`, `;`, `?`, `else`, or an operator, found doc comment `//!foo
  --> $DIR/doc-comment-in-stmt.rs:25:22
   |
LL |     let y = x.max(1) //!foo
   |                      ^^^^^^ expected one of `.`, `;`, `?`, `else`, or an operator
   |
help: add a space before `!` to write a regular comment
   |
LL |     let y = x.max(1) // !foo
   |                        +
```

Fix #65329.
2023-10-20 13:02:11 +00:00
Miguel Ojeda 35f03b763e Move `invalid-llvm-passes` test to `invalid-compile-flags` folder
Nowadays there is an `invalid-compile-flags` folder, thus move this
one there.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-10-20 14:59:26 +02:00
Georg Semmler 3d03a8a653
Fix a span for one of the test cases 2023-10-20 13:24:58 +02:00
Ethan Brierley 6c97f13612 Invalid `?` suggestion on mismatched `Ok(T)` 2023-10-20 10:13:19 +01:00
Oli Scherer fd9ef69adf Avoid a `track_errors` by bubbling up most errors from `check_well_formed` 2023-10-20 08:46:27 +00:00
bors 7849162ace Auto merge of #116899 - compiler-errors:closure-sig-infer, r=lcnr
Add a test showing failing closure signature inference in new solver

Been thinking a bit about how to make this test pass... but we don't actually have any good tests exercising this behavior in the suite.

r? lcnr
2023-10-20 05:55:25 +00:00
Esteban Küber 20de5c762d Move where doc comment meant as comment check
The new place makes more sense and covers more cases beyond individual
statements.

```
error: expected one of `.`, `;`, `?`, `else`, or an operator, found doc comment `//!foo
  --> $DIR/doc-comment-in-stmt.rs:25:22
   |
LL |     let y = x.max(1) //!foo
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected one of `.`, `;`, `?`, `else`, or an operator
   |
help: add a space before `!` to write a regular comment
   |
LL |     let y = x.max(1) // !foo
   |                        +
```

Fix #65329.
2023-10-20 02:54:45 +00:00
bors ae466d2d0a Auto merge of #116838 - gurry:116836-dup-macro-invoc-diag, r=petrochenkov
Fix duplicate labels emitted in `render_multispan_macro_backtrace()`

This PR replaces the `Vec` used to store labels with an `FxIndexSet` in order to eliminate duplicates

Fixes #116836
2023-10-20 02:07:05 +00:00
Rémy Rakic 8b76518a28 add non-regression test for issue 116657 2023-10-19 21:11:21 +00:00
bors 94c4e5c411 Auto merge of #115214 - Urgau:rfc-3127-trim-paths, r=compiler-errors
Implement rustc part of RFC 3127 trim-paths

This PR implements (or at least tries to) [RFC 3127 trim-paths](https://github.com/rust-lang/rust/issues/111540), the rustc part. That is `-Zremap-path-scope` with all of it's components/scopes.

`@rustbot` label: +F-trim-paths
2023-10-19 19:09:29 +00:00
Georg Semmler 9017b974ee
Improve the warning messages for the `#[diagnostic::on_unimplemented]`
This commit improves warnings emitted for malformed on unimplemented
attributes by:

* Improving the span of the warnings
* Adding a label message to them
* Separating the messages for missing and unexpected options
* Adding a help message that says which options are supported
2023-10-19 15:00:47 +02:00
León Orell Valerian Liehr 64ed233fc1
Rollup merge of #116908 - estebank:issue-78206, r=compiler-errors
Tweak wording of type errors involving type params

Fix #78206.
2023-10-19 04:34:47 +02:00
León Orell Valerian Liehr 2eb6e5f740
Rollup merge of #116829 - fmease:rust-aint-c, r=compiler-errors
Make `#[repr(Rust)]` incompatible with other (non-modifier) representation hints like `C` and `simd`

Read more about this change here: https://github.com/rust-lang/rust/pull/116829#issuecomment-1768618240.

Fixes [after backport] #116825.
2023-10-19 04:34:46 +02:00
León Orell Valerian Liehr 2dd1c8f693
Rollup merge of #116663 - compiler-errors:resolve-regions, r=lcnr
Don't ICE when encountering unresolved regions in `fully_resolve`

We can encounter unresolved regions due to unconstrained impl lifetime arguments because `collect_return_position_impl_trait_in_trait_tys` runs before WF actually checks that the impl is well-formed.

Fixes #116525
2023-10-19 04:34:45 +02:00
Gurinder Singh 0091166b57 Fix duplicate labels emitted in `render_multispan_macro_backtrace()`
Using hash set instead of vec to weed out duplicates
2023-10-19 08:03:40 +05:30
Esteban Küber e8d4fb8aaa Suggest relaxing implicit `type Assoc: Sized;` bound
Fix #85378.
2023-10-19 00:07:16 +00:00
Esteban Küber bd8b46800d Tweak wording of type errors involving type params
Fix #78206.
2023-10-18 23:53:18 +00:00
Michael Goulet ea73f10867 Don't ICE when encountering unresolved regions in fully_resolve 2023-10-18 20:39:29 +00:00
Michael Goulet 611766dcee Add a test showing failing closure signature inference in new solver 2023-10-18 18:59:02 +00:00
Michael Goulet 973d589582 Bump COINDUCTIVE_OVERLAP_IN_COHERENCE 2023-10-18 18:54:11 +00:00
León Orell Valerian Liehr d0b99e3efe
Make `#[repr(Rust)]` and `#[repr(C)]` incompatible with one another 2023-10-18 17:25:23 +02:00
Ali MJ Al-Nasrawy 8489bce7f5
Rollup merge of #116879 - aliemjay:revert-opaque-bubble, r=oli-obk
revert #114586

Reverts #114586.

cc #116877 (not closing until this gets a beta backport)
fixes #116684
fixes https://github.com/rust-lang/rust/pull/114586#issuecomment-1751967321

r? `@oli-obk` or `@lcnr`
2023-10-18 14:24:52 +03:00
Ali MJ Al-Nasrawy d69cdb2ceb
Rollup merge of #116865 - estebank:issue-46969, r=compiler-errors
Suggest constraining assoc types in more cases

Fix #46969.

```
error[E0308]: mismatched types
  --> $DIR/suggest-contraining-assoc-type-because-of-assoc-const.rs:12:21
   |
LL |     const N: C::M = 4u8;
   |                     ^^^ expected associated type, found `u8`
   |
   = note: expected associated type `<C as O>::M`
                         found type `u8`
help: consider constraining the associated type `<C as O>::M` to `u8`
   |
LL | impl<C: O<M = u8>> U<C> for u16 {
   |          ++++++++

```
2023-10-18 14:24:51 +03:00
Ali MJ Al-Nasrawy a536d58607
Rollup merge of #116856 - oli-obk:no_effects, r=compiler-errors
Disable effects in libcore again

r? `@fee1-dead`

This was accidentally allowed by https://github.com/rust-lang/rust/pull/114776 without feature gates
2023-10-18 14:24:51 +03:00
Ali MJ Al-Nasrawy 0653d7eebf
Rollup merge of #116812 - rmehri01:missing_copy_implementations_non_exhaustive, r=petrochenkov
Disable missing_copy_implementations lint on non_exhaustive types

Fixes #116766
2023-10-18 14:24:50 +03:00
Ali MJ Al-Nasrawy a1e274f172 revert rust-lang/rust#114586 2023-10-18 06:19:04 +00:00
bors b9832e72c9 Auto merge of #116713 - estebank:issue-116703, r=compiler-errors
Properly account for self ty in method disambiguation suggestion

Fix #116703.
2023-10-18 05:51:40 +00:00
Ben Kimock 33b0e4be06 Automatically enable cross-crate inlining for small functions 2023-10-17 19:53:51 -04:00
Esteban Küber dee86bff40 Suggest constraining assoc types in more cases
Fix #46969.
2023-10-17 23:50:13 +00:00
bors 09df6108c8 Auto merge of #116767 - cjgillot:alloc-normalize, r=oli-obk
Normalize alloc-id in tests.

AllocIds are globally numbered in a rustc invocation. This makes them very sensitive to changes unrelated to what is being tested. This commit normalizes them by renumbering, in order of appearance in the output.

The renumbering allows to keep the identity, that a simple `allocN` wouldn't. This is useful when we have memory dumps.

cc `@saethlin`
r? `@oli-obk`
2023-10-17 20:46:53 +00:00
Oli Scherer bcdd3d7739 Disable effects in libcore again 2023-10-17 17:55:49 +00:00
Esteban Küber 890e92feed Unify suggestion wording 2023-10-17 17:33:55 +00:00
Esteban Küber 6cf01fcf1e review comments + more tests 2023-10-17 17:33:08 +00:00
Esteban Küber 5cc9216ff3 Properly account for self ty in method disambiguation suggestion
Fix #116703.
2023-10-17 17:33:08 +00:00
Matthias Krüger a5aa52c23a
Rollup merge of #116717 - estebank:issue-9082, r=oli-obk
Special case iterator chain checks for suggestion

When encountering method call chains of `Iterator`, check for trailing `;` in the body of closures passed into `Iterator::map`, as well as calls to `<T as Clone>::clone` when `T` is a type param and `T: !Clone`.

Fix #9082.
2023-10-17 19:07:22 +02:00
Matthias Krüger ce407429dd
Rollup merge of #111072 - Urgau:check-cfg-new-syntax, r=petrochenkov
Add new simpler and more explicit syntax for check-cfg

<details>
<summary>
Old proposition (before the MCP)
</summary>

This PR adds a new simpler and more explicit syntax for check-cfg. It consist of two new form:
 - `exhaustive(names, values)`
 - `configure(name, "value1", "value2", ... "valueN")`

The preview forms `names(...)` and `values(...)` have implicit meaning that are not strait-forward. In particular `values(foo)`&`values(bar)` and `names(foo, bar)` are not equivalent which has created [some confusions](https://github.com/rust-lang/rust/pull/98080).

Also the `names()` and `values()` form are not clear either and again created some confusions where peoples believed that `values()`&`values(foo)` could be reduced to just `values(foo)`.

To fix that the two new forms are made to be explicit and simpler. See the table of correspondence:
  - `names()` -> `exhaustive(names)`
  - `values()` -> `exhaustive(values)`
  - `names(foo)` -> `exhaustive(names)`&`configure(foo)`
  - `values(foo)` -> `configure(foo)`
  - `values(feat, "foo", "bar")` -> `configure(feat, "foo", "bar")`
  - `values(foo)`&`values(bar)` -> `configure(foo, bar)`
  - `names()`&`values()`&`values(my_cfg)` -> `exhaustive(names, values)`&`configure(my_cfg)`

Another benefits of the new syntax is that it allow for further options (like conditional checking for --cfg, currently always on) without syntax change.

The two previous forms are deprecated and will be removed once cargo and beta rustc have the necessary support.

</details>

This PR is the first part of the implementation of [MCP636 - Simplify and improve explicitness of the check-cfg syntax](https://github.com/rust-lang/compiler-team/issues/636).

## New `cfg` form

It introduces the new [`cfg` form](https://github.com/rust-lang/compiler-team/issues/636) and deprecate the other two:
```
rustc --check-cfg 'cfg(name1, ..., nameN, values("value1", "value2", ... "valueN"))'
```

## Default built-in names and values

It also changes the default for the built-in names and values checking.

 - Built-in values checking would always be activated as long as a `--check-cfg` argument is present
 - Built-in names checking would always be activated as long as a `--check-cfg` argument is present **unless** if any `cfg(any())` arg is passed

~~**Note: depends on https://github.com/rust-lang/rust/pull/111068 but is reviewable (last two commits)!**~~

Resolve https://github.com/rust-lang/compiler-team/issues/636

r? `@petrochenkov`
2023-10-17 19:07:21 +02:00
Ryan Mehri a8e7e79101 disable missing_copy_implementations lint on non_exhaustive types
use is_variant_list_non_exhaustive/is_field_list_non_exhaustive

remove unused tcx

inline non_exhaustive def/variant check
2023-10-17 08:33:37 -07:00
bors 616e37919c Auto merge of #116756 - fee1-dead-contrib:dupe-those-bounds, r=oli-obk
Duplicate `~const` bounds with a non-const one in effects desugaring

This should unblock #116058.

r? `@oli-obk`
2023-10-17 12:16:54 +00:00
Urgau 297827fb86 [RFC 3127 - Trim Paths]: Add test for -Zremap-path-scope=diagnostics 2023-10-17 10:11:31 +02:00
Urgau 60e24462b6 [RFC 3127 - Trim Paths]: Add test for -Zremap-path-scope=macro 2023-10-17 10:11:31 +02:00
Michael Goulet f0e385d6b7 Flesh out tests more 2023-10-17 01:26:46 +00:00
Guillaume Gomez d0ade3f1ba
Rollup merge of #116800 - compiler-errors:rpitit-gat-outlives, r=jackh726
Fix implied outlives check for GAT in RPITIT

We enforce certain `Self: 'lt` bounds for GATs to save space for more sophisticated implied bounds, but those currently operate on the HIR. Code was easily reworked to operate on def-ids so that we can properly let these suggestions propagate through synthetic associated types like RPITITs and AFITs.

r? `@jackh726` or `@aliemjay`

Fixes #116789
2023-10-16 23:58:04 +02:00
Camille GILLOT 1f90d857d7 Stop trying to preserve pretty-printing. 2023-10-16 19:15:28 +00:00
Camille GILLOT 0eb958a89b Rebless. 2023-10-16 18:36:47 +00:00
clubby789 43a08bd299 Add test for 113326 2023-10-16 18:23:12 +00:00
Matthias Krüger b0572f1a12
Rollup merge of #116802 - compiler-errors:anchor-opaque-wf, r=oli-obk
Remove `DefiningAnchor::Bubble` from opaque wf check

Set the defining anchor to `DefiningAnchor::Bind(parent_def_id)` where `parent_def_id` is the first parent def-id that isn't an opaque.

This "fixes" some of the nested-return-type wf tests. If we *do* want these to be hard-errors for TAITs, we should probably make those error separately from this check (i.e. via some check like the code in the `OPAQUE_HIDDEN_INFERRED_BOUND` lint). The fact that some of these tests fail but not all of them seems kinda coincidental.

r? oli-obk
2023-10-16 19:10:51 +02:00
Matthias Krüger 14663e09b7
Rollup merge of #116257 - estebank:issue-101351, r=b-naber
Suggest trait bounds for used associated type on type param

Fix #101351.

When an associated type on a type parameter is used, and the type parameter isn't constrained by the correct trait, suggest the appropriate trait bound:

```
error[E0220]: associated type `Associated` not found for `T`
 --> file.rs:6:15
  |
6 |     field: T::Associated,
  |               ^^^^^^^^^^ there is a similarly named associated type `Associated` in the trait `Foo`
  |
help: consider restricting type parameter `T`
  |
5 | struct Generic<T: Foo> {
  |                 +++++
  ```

When an associated type on a type parameter has a typo, suggest fixing
it:

```
error[E0220]: associated type `Baa` not found for `T`
  --> $DIR/issue-55673.rs:9:8
   |
LL |     T::Baa: std::fmt::Debug,
   |        ^^^ there is a similarly named associated type `Bar` in the trait `Foo`
   |
help: change the associated type name to use `Bar` from `Foo`
   |
LL |     T::Bar: std::fmt::Debug,
   |        ~~~
```
2023-10-16 19:10:49 +02:00
Camille GILLOT 02424e4bc5 Normalize alloc-id in tests. 2023-10-16 16:29:35 +00:00
Matthew Jasper 5cc83fd4a5 Fix inline const pattern unsafety checking in THIR
THIR unsafety checking was getting a cycle of
function unsafety checking
-> building THIR for the function
-> evaluating pattern inline constants in the function
-> building MIR for the inline constant
-> checking unsafety of functions (so that THIR can be stolen)
This is fixed by not stealing THIR when generating MIR but instead when
unsafety checking.
This leaves an issue with pattern inline constants not being unsafety
checked because they are evaluated away when generating THIR.
To fix that we now represent inline constants in THIR patterns and
visit them in THIR unsafety checking.
2023-10-16 15:57:59 +00:00
Michael Goulet 743e6d1601 Remove `DefiningAnchor::Bubble` from opaque wf check 2023-10-16 15:50:31 +00:00
Michael Goulet 17ec3cd5bf Fix outlives suggestion for GAT in RPITIT 2023-10-16 15:42:26 +00:00
bors e7bdc5f9f8 Auto merge of #114330 - RalfJung:dagling-ptr-deref, r=oli-obk
don't UB on dangling ptr deref, instead check inbounds on projections

This implements https://github.com/rust-lang/reference/pull/1387 in Miri. See that PR for what the change is about.

Detecting dangling references in `let x = &...;` is now done by validity checking only, so some tests need to have validity checking enabled. There is no longer inherently a "nodangle" check in evaluating the expression `&*ptr` (aside from the aliasing model).

r? `@oli-obk`

Based on:
- https://github.com/rust-lang/reference/pull/1387
- https://github.com/rust-lang/rust/pull/115524
2023-10-16 12:40:16 +00:00
Ralf Jung 1ac153f60b add oversized-ref test back 2023-10-16 13:52:19 +02:00
Matthias Krüger 1de910fc0d
Rollup merge of #115196 - chenyukang:yukang-fix-86094, r=estebank
Suggest adding `return` if the for semi which can coerce to the fn return type

Fixes #86094
r? `@estebank`
2023-10-16 06:26:20 +02:00
Matthias Krüger 51be0df011
Rollup merge of #116522 - bvanjoi:fix-115599, r=oli-obk
use `PatKind::Error` when an ADT const value has violation

Fixes #115599

Since the [to_pat](https://github.com/rust-lang/rust/pull/111913/files#diff-6d8d99538aca600d633270051580c7a9e40b35824ea2863d9dda2c85a733b5d9R126-R155) behavior has been changed in the #111913 update, the kind of `inlined_const_ast_pat` has transformed from `PatKind::Leaf { pattern: Pat { kind: Wild, ..} } ` to `PatKind::Constant`. This caused a scenario where there are no matched candidates, leading to a testing of the candidates. This process ultimately attempts to test the string const, triggering the `bug!` invocation finally.

r? ``@oli-obk``
2023-10-15 21:29:07 +02:00
Ralf Jung e24835c6e0 more precise error for 'based on misaligned pointer' case 2023-10-15 18:13:33 +02:00
Ralf Jung f3f9b795bd place evaluation: require the original pointer to be aligned if an access happens 2023-10-15 18:13:31 +02:00
Ralf Jung ea9a24e32e avoid re-checking the offset while iterating an array/slice 2023-10-15 18:12:46 +02:00
Ralf Jung b1ebf002c3 don't UB on dangling ptr deref, instead check inbounds on projections 2023-10-15 18:12:46 +02:00
yukang 25d38c48c3 Suggest adding `return` if the type of unused semi return value can coerce to the fn return type 2023-10-15 22:57:03 +08:00
bors a48396984a Auto merge of #116688 - compiler-errors:rustfmt-up, r=WaffleLapkin,Nilstrieb
Format all the let-chains in compiler crates

Since rust-lang/rustfmt#5910 has landed, soon we will have support for formatting let-chains (as soon as rustfmt syncs and beta gets bumped).

This PR applies the changes [from master rustfmt to rust-lang/rust eagerly](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/out.20formatting.20of.20prs/near/374997516), so that the next beta bump does not have to deal with a 200+ file diff and can remain concerned with other things like `cfg(bootstrap)` -- #113637 was a pain to land, for example, because of let-else.

I will also add this commit to the ignore list after it has landed.

The commands that were run -- I'm not great at bash-foo, but this applies rustfmt to every compiler crate, and then reverts the two crates that should probably be formatted out-of-tree.
```
~/rustfmt $ ls -1d ~/rust/compiler/* | xargs -I@ cargo run --bin rustfmt -- `@/src/lib.rs` --config-path ~/rust --edition=2021 # format all of the compiler crates
~/rust $ git checkout HEAD -- compiler/rustc_codegen_{gcc,cranelift} # revert changes to cg-gcc and cg-clif
```

cc `@rust-lang/rustfmt`
r? `@WaffleLapkin` or `@Nilstrieb` who said they may be able to review this purely mechanical PR :>

cc `@Mark-Simulacrum` and `@petrochenkov,` who had some thoughts on the order of operations with big formatting changes in https://github.com/rust-lang/rust/pull/95262#issue-1178993801. I think the situation has changed since then, given that let-chains support exists on master rustfmt now, and I'm fairly confident that this formatting PR should land even if *bootstrap* rustfmt doesn't yet format let-chains in order to lessen the burden of the next beta bump.
2023-10-15 13:23:55 +00:00
bohan 223674a824 use `PatKind::error` when an ADT const value has violation 2023-10-15 19:20:06 +08:00
Deadbeef f0f89d6d43 Duplicate `~const` bounds with a non-const one in effects desugaring 2023-10-15 08:59:38 +00:00
Guillaume Gomez 03cbf50c34
Rollup merge of #116576 - eduardosm:const-eval-wasm-target-features, r=RalfJung
const-eval: allow calling functions with targat features disabled at compile time in WASM

This is not unsafe on WASM, see https://github.com/rust-lang/rust/pull/84988

r? `@RalfJung`

Fixes https://github.com/rust-lang/rust/issues/116516
2023-10-14 22:35:05 +02:00
Eduardo Sánchez Muñoz f9b1af6587 const-eval: allow calling functions with targat features disabled at compile time in WASM
This is not unsafe on WASM, see https://github.com/rust-lang/rust/pull/84988
2023-10-14 20:15:05 +02:00
Nadrieril ca869e3334 Lint `non_exhaustive_omitted_patterns` per column 2023-10-14 19:39:18 +02:00
Nadrieril 2d45df3caa Add and prepare tests 2023-10-14 19:39:18 +02:00
Matthias Krüger 77b578f72b
Rollup merge of #116730 - compiler-errors:unsoundness-tests-rpit, r=aliemjay
Add some unsoundness tests for opaques capturing hidden regions not in substs

Commit tests from https://github.com/rust-lang/rust/pull/116040#issuecomment-1751610237 and https://github.com/rust-lang/rust/pull/59402#issuecomment-476003242 so that we make sure not to regress them the next time that we relax the opaque capture rules :^)
2023-10-14 19:22:18 +02:00
Matthias Krüger 7d1b24f4bc
Rollup merge of #116715 - Nadrieril:patkind-error, r=oli-obk
Prevent more spurious unreachable pattern lints

Continues the work of https://github.com/rust-lang/rust/pull/115937 by introducing `PatKind::Error`, to be used instead of `PatKind::Wild` when an error was raised during pattern lowering. Most of match checking lints are skipped when a `PatKind::Error` is encountered. This avoids confusing extra warnings when a pattern is malformed. Now `PatKind::Wild` should indicate an actual wildcard pattern.

r? `@oli-obk`
2023-10-14 19:22:17 +02:00
bors 0233608c67 Auto merge of #116727 - matthiaskrgr:rollup-3qqdrny, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #116630 (Add ability to get lines/filename for Span in smir)
 - #116644 (remove outdated bootstrap FIXME)
 - #116695 (Fix a comment)
 - #116696 (Misc improvements)
 - #116704 (Fix AFIT lint message to mention pitfall)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-14 15:07:25 +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
Michael Goulet 3a0799d6d0 Add some unsoundness tests for opaques capturing hidden regions not in substs 2023-10-14 13:26:30 +00:00
Matthias Krüger 45bcef3cd5
Rollup merge of #116689 - lcnr:auto-trait-hidden-ty-leak, r=compiler-errors
explicitly handle auto trait leakage in coherence

does not impact behavior but may avoid weird bugs in the future, cc https://github.com/rust-lang/trait-system-refactor-initiative/issues/65

r? ``@compiler-errors``
2023-10-14 13:48:20 +02:00
Nadrieril 89f75ff4d0 Skip most of check_match checks in the presence of `PatKind::Error` 2023-10-14 13:38:04 +02:00
Nadrieril aab3b9327e Propagate pattern errors via a new `PatKind::Error` variant
Instead of via `Const::new_error`
2023-10-14 13:38:02 +02:00
Matthias Krüger 24116aebe0
Rollup merge of #116704 - compiler-errors:afit-lint-plus, r=tmandry
Fix AFIT lint message to mention pitfall

Addresses https://github.com/rust-lang/rust/pull/116184#issuecomment-1745194387 by adding a short note. Not sure exactly of the wording -- I don't think this should be a blocker for the stabilization PR since we can iterate on this lint's messaging in the next few weeks in the worst case.

r? `@tmandry` cc `@traviscross` `@jonhoo`
2023-10-14 13:36:29 +02:00
bors 139f63a6eb Auto merge of #116015 - EvanMerlock:master, r=oli-obk
const_eval: allow function pointer signatures containing &mut T in const contexts

potentially fixes #114994

We utilize a `TypeVisitor` here in order to more easily handle control flow.
- In the event the typekind the Visitor sees is a function pointer, we skip over it
- However, otherwise we do one of two things:
   - If we find a mutable reference, check it, then continue visiting types
   - If we find any other type, continue visiting types

This means we will check if the function pointer _itself_ is mutable, but not if any of the types _within_ are.
2023-10-14 09:18:28 +00:00
bors 481d45abec Auto merge of #115822 - compiler-errors:stabilize-rpitit, r=jackh726
Stabilize `async fn` and return-position `impl Trait` in trait

# Stabilization report

This report proposes the stabilization of `#![feature(return_position_impl_trait_in_trait)]` ([RPITIT][RFC 3425]) and `#![feature(async_fn_in_trait)]` ([AFIT][RFC 3185]). These are both long awaited features that increase the expressiveness of the Rust language and trait system.

Closes #91611

[RFC 3185]: https://rust-lang.github.io/rfcs/3185-static-async-fn-in-trait.html
[RFC 3425]: https://rust-lang.github.io/rfcs/3425-return-position-impl-trait-in-traits.html

## Updates from thread

The thread has covered two major concerns:

* [Given that we don't have RTN, what should we stabilize?](https://github.com/rust-lang/rust/pull/115822#issuecomment-1731149475) -- proposed resolution is [adding a lint](https://github.com/rust-lang/rust/pull/115822#issuecomment-1728354622) and [careful messaging](https://github.com/rust-lang/rust/pull/115822#issuecomment-1731136169)
* [Interaction between outlives bounds and capture semantics](https://github.com/rust-lang/rust/pull/115822#issuecomment-1731153952) -- This is fixable in a forwards-compatible way via #116040, and also eventually via ATPIT.

## Stabilization Summary

This stabilization allows the following examples to work.

### Example of return-position `impl Trait` in trait definition

```rust
trait Bar {
    fn bar(self) -> impl Send;
}
```

This declares a trait method that returns *some* type that implements `Send`.  It's similar to writing the following using an associated type, except that the associated type is anonymous.

```rust
trait Bar {
    type _0: Send;
    fn bar(self) -> Self::_0;
}
```

### Example of return-position `impl Trait` in trait implementation

```rust
impl Bar for () {
    fn bar(self) -> impl Send {}
}
```

This defines a method implementation that returns an opaque type, just like [RPIT][RFC 1522] does, except that all in-scope lifetimes are captured in the opaque type (as is already true for `async fn` and as is expected to be true for RPIT in Rust Edition 2024), as described below.

[RFC 1522]: https://rust-lang.github.io/rfcs/1522-conservative-impl-trait.html

### Example of `async fn` in trait

```rust
trait Bar {
    async fn bar(self);
}

impl Bar for () {
    async fn bar(self) {}
}
```

This declares a trait method that returns *some* [`Future`](https://doc.rust-lang.org/core/future/trait.Future.html) and a corresponding method implementation.  This is equivalent to writing the following using RPITIT.

```rust
use core::future::Future;

trait Bar {
    fn bar(self) -> impl Future<Output = ()>;
}

impl Bar for () {
    fn bar(self) -> impl Future<Output = ()> { async {} }
}
```

The desirability of this desugaring being available is part of why RPITIT and AFIT are being proposed for stabilization at the same time.

## Motivation

Long ago, Rust added [RPIT][RFC 1522] and [`async`/`await`][RFC 2394].  These are major features that are widely used in the ecosystem.  However, until now, these feature could not be used in *traits* and trait implementations.  This left traits as a kind of second-class citizen of the language.  This stabilization fixes that.

[RFC 2394]: https://rust-lang.github.io/rfcs/2394-async_await.html

### `async fn` in trait

Async/await allows users to write asynchronous code much easier than they could before. However, it doesn't play nice with other core language features that make Rust the great language it is, like traits. Support for `async fn` in traits has been long anticipated and was not added before due to limitations in the compiler that have now been lifted.

`async fn` in traits will unblock a lot of work in the ecosystem and the standard library. It is not currently possible to write a trait that is implemented using `async fn`. The workarounds that exist are undesirable because they require allocation and dynamic dispatch, and any trait that uses them will become obsolete once native `async fn` in trait is stabilized.

We also have ample evidence that there is demand for this feature from the [`async-trait` crate][async-trait], which emulates the feature using dynamic dispatch. The async-trait crate is currently the #5 async crate on crates.io ranked by recent downloads, receiving over 78M all-time downloads. According to a [recent analysis][async-trait-analysis], 4% of all crates use the `#[async_trait]` macro it provides, representing 7% of all function and method signatures in trait definitions on crates.io. We think this is a *lower bound* on demand for the feature, because users are unlikely to use `#[async_trait]` on public traits on crates.io for the reasons already given.

[async-trait]: https://crates.io/crates/async-trait
[async-trait-analysis]: https://rust-lang.zulipchat.com/#narrow/stream/315482-t-compiler.2Fetc.2Fopaque-types/topic/RPIT.20capture.20rules.20.28capturing.20everything.29/near/389496292

### Return-position `impl Trait` in trait

`async fn` always desugars to a function that returns `impl Future`.

```rust!
async fn foo() -> i32 { 100 }

// Equivalent to:
fn foo() -> impl Future<Output = i32> { async { 100 } }
```

All `async fn`s today can be rewritten this way. This is useful because it allows adding behavior that runs at the time of the function call, before the first `.await` on the returned future.

In the spirit of supporting the same set of features on `async fn` in traits that we do outside of traits, it makes sense to stabilize this as well. As described by the [RPITIT RFC][rpitit-rfc], this includes the ability to mix and match the equivalent forms in traits and their corresponding impls:

```rust!
trait Foo {
    async fn foo(self) -> i32;
}

// Can be implemented as:
impl Foo for MyType {
    fn foo(self) -> impl Future<Output = i32> {
        async { 100 }
    }
}
```

Return-position `impl Trait` in trait is useful for cases beyond async, just as regular RPIT is. As a simple example, the RFC showed an alternative way of writing the `IntoIterator` trait with one fewer associated type.

```rust!
trait NewIntoIterator {
    type Item;
    fn new_into_iter(self) -> impl Iterator<Item = Self::Item>;
}

impl<T> NewIntoIterator for Vec<T> {
    type Item = T;
    fn new_into_iter(self) -> impl Iterator<Item = T> {
        self.into_iter()
    }
}
```

[rpitit-rfc]: https://rust-lang.github.io/rfcs/3425-return-position-impl-trait-in-traits.html

## Major design decisions

This section describes the major design decisions that were reached after the RFC was accepted:

- EDIT: Lint against async fn in trait definitions

    - Until the [send bound problem](https://smallcultfollowing.com/babysteps/blog/2023/02/01/async-trait-send-bounds-part-1-intro/) is resolved, the use of `async fn` in trait definitions could lead to a bad experience for people using work-stealing executors (by far the most popular choice). However, there are significant use cases for which the current support is all that is needed (single-threaded executors, such as those used in embedded use cases, as well as thread-per-core setups). We are prioritizing serving users well over protecting people from misuse, and therefore, we opt to stabilize the full range of functionality; however, to help steer people correctly, we are will issue a warning on the use of `async fn` in trait definitions that advises users about the limitations. (See [this summary comment](https://github.com/rust-lang/rust/pull/115822#issuecomment-1731149475) for the details of the concern, and [this comment](https://github.com/rust-lang/rust/pull/115822#issuecomment-1728354622) for more details about the reasoning that led to this conclusion.)

- Capture rules:

    - The RFC's initial capture rules for lifetimes in impls/traits were found to be imprecisely precise and to introduce various inconsistencies. After much discussion, the decision was reached to make `-> impl Trait` in traits/impls capture *all* in-scope parameters, including both lifetimes and types. This is a departure from the behavior of RPITs in other contexts; an RFC is currently being authored to change the behavior of RPITs in other contexts in a future edition.

    - Major discussion links:

        - [Lang team design meeting from 2023-07-26](https://hackmd.io/sFaSIMJOQcuwCdnUvCxtuQ?view)

- Refinement:

    - The [refinement RFC] initially proposed that impl signatures that are more specific than their trait are not allowed unless the `#[refine]` attribute was included, but left it as an open question how to implement this. The stabilized proposal is that it is not a hard error to omit `#[refine]`, but there is a lint which fires if the impl's return type is more precise than the trait. This greatly simplified the desugaring and implementation while still achieving the original goal of ensuring that users do not accidentally commit to a more specific return type than they intended.

    - Major discussion links:

        - [Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/.60.23.5Brefine.5D.60.20as.20a.20lint)

[refinement RFC]: https://rust-lang.github.io/rfcs/3245-refined-impls.html

## What is stabilized

### Async functions in traits and trait implementations

* `async fn` are now supported in traits and trait implementations.
* Associated functions in traits that are `async` may have default bodies.

### Return-position impl trait in traits and trait implementations

* Return-position `impl Trait`s are now supported in traits and trait implementations.
    * Return-position `impl Trait` in implementations are treated like regular return-position `impl Trait`s, and therefore behave according to the same inference rules for hidden type inference and well-formedness.
* Associated functions in traits that name return-position `impl Trait`s may have default bodies.
* Implementations may provide either concrete types or `impl Trait` for each corresponding `impl Trait` in the trait method signature.

For a detailed exploration of the technical implementation of return-position `impl Trait` in traits, see [the dev guide](https://rustc-dev-guide.rust-lang.org/return-position-impl-trait-in-trait.html).

### Mixing `async fn` in trait and return-position `impl Trait` in trait

A trait function declaration that is `async fn ..() -> T` may be satisfied by an implementation function that returns `impl Future<Output = T>`, or vice versa.

```rust
trait Async {
    async fn hello();
}

impl Async for () {
    fn hello() -> impl Future<Output = ()> {
        async {}
    }
}

trait RPIT {
    fn hello() -> impl Future<Output = String>;
}

impl RPIT for () {
    async fn hello() -> String {
        "hello".to_string()
    }
}
```

### Return-position `impl Trait` in traits and trait implementations capture all in-scope lifetimes

Described above in "major design decisions".

### Return-position `impl Trait` in traits are "always revealing"

When a trait uses `-> impl Trait` in return position, it logically desugars to an associated type that represents the return (the actual implementation in the compiler is different, as described below). The value of this associated type is determined by the actual return type written in the impl; if the impl also uses `-> impl Trait` as the return type, then the value of the associated type is an opaque type scoped to the impl method (similar to what you would get when calling an inherent function returning `-> impl Trait`). As with any associated type, the value of this special associated type can be revealed by the compiler if the compiler can figure out what impl is being used.

For example, given this trait:

```rust
trait AsDebug {
    fn as_debug(&self) -> impl Debug;
}
```

A function working with the trait generically is only able to see that the return value is `Debug`:

```rust
fn foo<T: AsDebug>(t: &T) {
    let u = t.as_debug();
    println!("{}", u); // ERROR: `u` is not known to implement `Display`
}
```

But if a function calls `as_debug` on a known type (say, `u32`), it may be able to resolve the return type more specifically, if that implementation specifies a concrete type as well:

```rust
impl AsDebug for u32 {
    fn as_debug(&self) -> u32 {
        *self
    }
}

fn foo(t: &u32) {
    let u: u32 = t.as_debug(); // OK!
    println!("{}",  t.as_debug()); // ALSO OK (since `u32: Display`).
}
```

The return type used in the impl therefore represents a **semver binding** promise from the impl author that the return type of `<u32 as AsDebug>::as_debug` will not change. This could come as a surprise to users, who might expect that they are free to change the return type to any other type that implements `Debug`. To address this, we include a [`refining_impl_trait` lint](https://github.com/rust-lang/rust/pull/115582) that warns if the impl uses a specific type -- the `impl AsDebug for u32` above, for example, would toggle the lint.

The lint message explains what is going on and encourages users to `allow` the lint to indicate that they meant to refine the return type:

```rust
impl AsDebug for u32 {
    #[allow(refining_impl_trait)]
    fn as_debug(&self) -> u32 {
        *self
    }
}
```

[RFC #3245](https://github.com/rust-lang/rfcs/pull/3245) proposed a new attribute, `#[refine]`, that could also be used to "opt-in" to refinements like this (and which would then silence the lint). That RFC is not currently implemented -- the `#[refine]` attribute is also expected to reveal other details from the signature and has not yet been fully implemented.

### Return-position `impl Trait` and `async fn` in traits are opted-out of object safety checks when the parent function has `Self: Sized`

```rust
trait IsObjectSafe {
    fn rpit() -> impl Sized where Self: Sized;
    async fn afit() where Self: Sized;
}
```

Traits that mention return-position `impl Trait` or `async fn` in trait when the associated function includes a `Self: Sized` bound will remain object safe. That is because the associated function that defines them will be opted-out of the vtable of the trait, and the associated types will be unnameable from any trait object.

This can alternatively be seen as a consequence of https://github.com/rust-lang/rust/pull/112319#issue-1742251747 and the desugaring of return-position `impl Trait` in traits to associated types which inherit the where-clauses of the associated function that defines them.

## What isn't stabilized (aka, potential future work)

### Dynamic dispatch

As stabilized, traits containing RPITIT and AFIT are **not dyn compatible**. This means that you cannot create `dyn Trait` objects from them and can only use static dispatch. The reason for this limitation is that dynamic dispatch support for RPITIT and AFIT is more complex than static dispatch, as described on the [async fundamentals page](https://rust-lang.github.io/async-fundamentals-initiative/evaluation/challenges/dyn_traits.html). The primary challenge to using `dyn Trait` in today's Rust is that **`dyn Trait` today must list the values of all associated types**. This means you would have to write `dyn for<'s> Trait<Foo<'s> = XXX>` where `XXX` is the future type defined by the impl, such as `F_A`. This is not only verbose (or impossible), it also uniquely ties the `dyn Trait` to a particular impl, defeating the whole point of `dyn Trait`.

The precise design for handling dynamic dispatch is not yet determined. Top candidates include:

- [callee site selection][], in which we permit unsized return values so that the return type for an `-> impl Foo` method be can be `dyn Foo`, but then users must specify the type of wide pointer at the call-site in some fashion.

- [`dyn*`][], where we create a built-in encapsulation of a "wide pointer" and map the associated type corresponding to an RPITIT to the corresponding `dyn*` type (`dyn*` itself is not exposed to users as a type in this proposal, though that could be a future extension).

[callee site selection]: https://smallcultfollowing.com/babysteps/blog/2022/09/21/dyn-async-traits-part-9-callee-site-selection/

[`dyn*`]: https://smallcultfollowing.com/babysteps/blog/2022/03/29/dyn-can-we-make-dyn-sized/

### Where-clause bounds on return-position `impl Trait` in traits or async futures (RTN/ART)

One limitation of async fn in traits and RPITIT as stabilized is that there is no way for users to write code that adds additional bounds beyond those listed in the `-> impl Trait`. The most common example is wanting to write a generic function that requires that the future returned from an `async fn` be `Send`:

```rust
trait Greet {
    async fn greet(&self);
}

fn greet_in_parallel<G: Greet>(g: &G) {
    runtime::spawn(async move {
        g.greet().await; //~ ERROR: future returned by `greet` may not be `Send`
    })
}
```

Currently, since the associated types added for the return type are anonymous, there is no where-clause that could be added to make this code compile.

There have been various proposals for how to address this problem (e.g., [return type notation][rtn] or having an annotation to give a name to the associated type), but we leave the selection of one of those mechanisms to future work.

[rtn]: https://smallcultfollowing.com/babysteps/blog/2023/02/13/return-type-notation-send-bounds-part-2/

In the meantime, there are workarounds that one can use to address this problem, listed below.

#### Require all futures to be `Send`

For many users, the trait may only ever be used with `Send` futures, in which case one can write an explicit `impl Future + Send`:

```rust
trait Greet {
    fn greet(&self) -> impl Future<Output = ()> + Send;
}
```

The nice thing about this is that it is still compatible with using `async fn` in the trait impl. In the async working group case studies, we found that this could work for the [builder provider API](https://rust-lang.github.io/async-fundamentals-initiative/evaluation/case-studies/builder-provider-api.html). This is also the default approach used by the `#[async_trait]` crate which, as we have noted, has seen widespread adoption.

#### Avoid generics

This problem only applies when the `Self` type is generic. If the `Self` type is known, then the precise return type from an `async fn` is revealed, and the `Send` bound can be inferred thanks to auto-trait leakage. Even in cases where generics may appear to be required, it is sometimes possible to rewrite the code to avoid them. The [socket handler refactor](https://rust-lang.github.io/async-fundamentals-initiative/evaluation/case-studies/socket-handler.html) case study provides one such example.

### Unify capture behavior for `-> impl Trait` in inherent methods and traits

As stabilized, the capture behavior for `-> impl Trait` in a trait (whether as part of an async fn or a RPITIT) captures all types and lifetimes, whereas the existing behavior for inherent methods only captures types and lifetimes that are explicitly referenced. Capturing all lifetimes in traits was necessary to avoid various surprising inconsistencies; the expressed intent of the lang team is to extend that behavior so that we also capture all lifetimes in inherent methods, which would create more consistency and also address a common source of user confusion, but that will have to happen over the 2024 edition. The RFC is in progress. Should we opt not to accept that RFC, we can bring the capture behavior for `-> impl Trait` into alignment in other ways as part of the 2024 edition.

### `impl_trait_projections`

Orthgonal to `async_fn_in_trait` and `return_position_impl_trait_in_trait`, since it can be triggered on stable code. This will be stabilized separately in [#115659](https://github.com/rust-lang/rust/pull/115659).

<details>
If we try to write this code without `impl_trait_projections`, we will get an error:

```rust
#![feature(async_fn_in_trait)]

trait Foo {
    type Error;
    async fn foo(&mut self) -> Result<(), Self::Error>;
}

impl<T: Foo> Foo for &mut T {
    type Error = T::Error;
    async fn foo(&mut self) -> Result<(), Self::Error> {
        T::foo(self).await
    }
}
```

The error relates to the use of `Self` in a trait impl when the self type has a lifetime. It can be worked around by rewriting the impl not to use `Self`:

```rust
#![feature(async_fn_in_trait)]

trait Foo {
    type Error;
    async fn foo(&mut self) -> Result<(), Self::Error>;
}

impl<T: Foo> Foo for &mut T {
    type Error = T::Error;
    async fn foo(&mut self) -> Result<(), <&mut T as Foo>::Error> {
        T::foo(self).await
    }
}
```
</details>

## Tests

Tests are generally organized between return-position `impl Trait` and `async fn` in trait, when the distinction matters.
* RPITIT: https://github.com/rust-lang/rust/tree/master/tests/ui/impl-trait/in-trait
* AFIT: https://github.com/rust-lang/rust/tree/master/tests/ui/async-await/in-trait

## Remaining bugs and open issues

* #112047: Indirection introduced by `async fn` and return-position `impl Trait` in traits may hide cycles in opaque types, causing overflow errors that can only be discovered by monomorphization.
* #111105 - `async fn` in trait is susceptible to issues with checking auto traits on futures' generators, like regular `async`. This is a manifestation of #110338.
    * This was deemed not blocking because fixing it is forwards-compatible, and regular `async` is subject to the same issues.
* #104689: `async fn` and return-position `impl Trait` in trait requires the late-bound lifetimes in a trait and impl function signature to be equal.
    * This can be relaxed in the future with a smarter lexical region resolution algorithm.
* #102527: Nesting return-position `impl Trait` in trait deeply may result in slow compile times.
    * This has only been reported once, and can be fixed in the future.
* #108362: Inference between return types and generics of a function may have difficulties when there's an `.await`.
    * This isn't related to AFIT (https://github.com/rust-lang/rust/issues/108362#issuecomment-1717927918) -- using traits does mean that there's possibly easier ways to hit it.
* #112626: Because `async fn` and return-position `impl Trait` in traits lower to associated types, users may encounter strange behaviors when implementing circularly dependent traits.
    * This is not specific to RPITIT, and is a limitation of associated types: https://github.com/rust-lang/rust/issues/112626#issuecomment-1603405105
* **(Nightly)** #108309: `async fn` and return-position `impl Trait` in trait do not support specialization. This was deemed not blocking, since it can be fixed in the future (e.g. #108321) and specialization is a nightly feature.

#### (Nightly) Return type notation bugs

RTN is not being stabilized here, but there are some interesting outstanding bugs. None of them are blockers for AFIT/RPITIT, but I'm noting them for completeness.

<details>

* #109924 is a bug that occurs when a higher-ranked trait bound has both inference variables and associated types. This is pre-existing -- RTN just gives you a more convenient way of producing them. This should be fixed by the new trait solver.
* #109924 is a manifestation of a more general issue with `async` and auto-trait bounds: #110338. RTN does not cause this issue, just allows us to put `Send` bounds on the anonymous futures that we have in traits.
* #112569 is a bug similar to associated type bounds, where nested bounds are not implied correctly.

</details>

## Alternatives

### Do nothing

We could choose not to stabilize these features. Users that can use the `#[async_trait]` macro would continue to do so. Library maintainers would continue to avoid async functions in traits, potentially blocking the stable release of many useful crates.

### Stabilize `impl Trait` in associated type instead

AFIT and RPITIT solve the problem of returning unnameable types from trait methods. It is also possible to solve this by using another unstable feature, `impl Trait` in an associated type. Users would need to define an associated type in both the trait and trait impl:

```rust!
trait Foo {
    type Fut<'a>: Future<Output = i32> where Self: 'a;
    fn foo(&self) -> Self::Fut<'_>;
}

impl Foo for MyType {
    type Fut<'a> where Self: 'a = impl Future<Output = i32>;
    fn foo(&self) -> Self::Fut<'_> {
        async { 42 }
    }
}
```

This also has the advantage of allowing generic code to bound the associated type. However, it is substantially less ergonomic than either `async fn` or `-> impl Future`, and users still expect to be able to use those features in traits. **Even if this feature were stable, we would still want to stabilize AFIT and RPITIT.**

That said, we can have both. `impl Trait` in associated types is desireable because it can be used in existing traits with explicit associated types, among other reasons. We *should* stabilize this feature once it is ready, but that's outside the scope of this proposal.

### Use the old capture semantics for RPITIT

We could choose to make the capture rules for RPITIT consistent with the existing rules for RPIT. However, there was strong consensus in a recent [lang team meeting](https://hackmd.io/sFaSIMJOQcuwCdnUvCxtuQ?view) that we should *change* these rules, and furthermore that new features should adopt the new rules.

This is consistent with the tenet in RFC 3085 of favoring ["Uniform behavior across editions"](https://rust-lang.github.io/rfcs/3085-edition-2021.html#uniform-behavior-across-editions) when possible. It greatly reduces the complexity of the feature by not requiring us to answer, or implement, the design questions that arise out of the interaction between the current capture rules and traits. This reduction in complexity – and eventual technical debt – is exactly in line with the motivation listed in the aforementioned RFC.

### Make refinement a hard error

Refinement (`refining_impl_trait`) is only a concern for library authors, and therefore doesn't really warrant making into a deny-by-default warning or an error.

Additionally, refinement is currently checked via a lint that compares bounds in the `impl Trait`s in the trait and impl syntactically. This is good enough for a warning that can be opted-out, but not if this were a hard error, which would ideally be implemented using fully semantic, implicational logic. This was implemented (#111931), but also is an unnecessary burden on the type system for little pay-off.

## History

- Dec 7, 2021: [RFC #3185: Static async fn in traits](https://rust-lang.github.io/rfcs/3185-static-async-fn-in-trait.html) merged
- Sep 9, 2022: [Initial implementation](https://github.com/rust-lang/rust/pull/101224) of AFIT and RPITIT landed
- Jun 13, 2023: [RFC #3425: Return position `impl Trait` in traits](https://rust-lang.github.io/rfcs/3425-return-position-impl-trait-in-traits.html) merged

<!--These will render pretty when pasted into github-->
Non-exhaustive list of PRs that are particularly relevant to the implementation:

- #101224
- #103491
- #104592
- #108141
- #108319
- #108672
- #112988
- #113182 (later made redundant by #114489)
- #113215
- #114489
- #115467
- #115582

Doc co-authored by `@nikomatsakis,` `@tmandry,` `@traviscross.` Thanks also to `@spastorino,` `@cjgillot` (for changes to opaque captures!), `@oli-obk` for many reviews, and many other contributors and issue-filers. Apologies if I left your name off 😺
2023-10-14 07:29:08 +00:00
Esteban Küber 6d23ee8430 Special case iterator chain checks for suggestion
When encountering method call chains of `Iterator`, check for trailing
`;` in the body of closures passed into `Iterator::map`, as well as
calls to `<T as Clone>::clone` when `T` is a type param and `T: !Clone`.

Fix #9082.
2023-10-14 04:11:54 +00:00
bors 75a5dd05bc Auto merge of #115524 - RalfJung:misalign, r=wesleywiser
const-eval: make misalignment a hard error

It's been a future-incompat error (showing up in cargo's reports) since https://github.com/rust-lang/rust/pull/104616, Rust 1.68, released in March.  That should be long enough.

The question for the lang team is simply -- should we move ahead with this, making const-eval alignment failures a hard error? (It turns out some of them accidentally already were hard errors since #104616. But not all so this is still a breaking change. Crater found no regression.)
2023-10-14 00:57:09 +00:00
Michael Goulet 3f2574e8ba Test that RPITITs have RPIT scope and not impl-wide scope 2023-10-13 21:01:36 +00:00
Michael Goulet 59315b8a63 Stabilize AFIT and RPITIT 2023-10-13 21:01:36 +00:00
bors 09eff44889 Auto merge of #116645 - estebank:issue-116608, r=oli-obk
Detect ruby-style closure in parser

When parsing a closure without a body that is surrounded by a block, suggest moving the opening brace after the closure head.

Fix #116608.
2023-10-13 19:26:27 +00:00
Esteban Küber 20c622e456 Tweak wording 2023-10-13 19:18:46 +00:00
Esteban Küber 781e86477c Suggest trait bounds for used associated type on type param
Fix #101351.

When an associated type on a type parameter is used, and the type
parameter isn't constrained by the correct trait, suggest the
appropriate trait bound:

```
error[E0220]: associated type `Associated` not found for `T`
 --> file.rs:6:15
  |
6 |     field: T::Associated,
  |               ^^^^^^^^^^ there is a similarly named associated type `Associated` in the trait `Foo`
  |
help: consider restricting type parameter `T`
  |
5 | struct Generic<T: Foo> {
  |                 +++++
  ```

When an associated type on a type parameter has a typo, suggest fixing
it:

```
error[E0220]: associated type `Baa` not found for `T`
  --> $DIR/issue-55673.rs:9:8
   |
LL |     T::Baa: std::fmt::Debug,
   |        ^^^ there is a similarly named associated type `Bar` in the trait `Foo`
   |
help: change the associated type name to use `Bar` from `Foo`
   |
LL |     T::Bar: std::fmt::Debug,
   |        ~~~
```
2023-10-13 19:13:56 +00:00
Michael Goulet 362b75badf Fix AFIT lint message to mention pitfall 2023-10-13 19:13:18 +00:00
Urgau fc78d78988 MCP636: Adapt check-cfg tests to the new syntax 2023-10-13 13:51:03 +02:00
bors 34bc5716b5 Auto merge of #116676 - estebank:issue-116658, r=compiler-errors
On type error involving closure, avoid ICE

When we encounter a type error involving a closure, we try to typeck prior closure invocations to see if they influenced the current expected type. When trying to do so, ensure that the closure was defined in our current scope.

Fix #116658.
2023-10-13 10:29:55 +00:00
lcnr 1bc6ae4401 explicitly handle auto trait leakage in coherence 2023-10-13 09:42:51 +00:00
Michael Goulet e805151fd4 Bless tests and new warnings due to formatting changes 2023-10-13 09:31:36 +00:00
bors a4a10bdf29 Auto merge of #116666 - Urgau:check-cfg-pre-mcp636, r=petrochenkov
Improve check-cfg diagnostics

This PR tries to improve some of the diagnostics of check-cfg.

The main changes is the unexpected name or value being added to the main diagnostic:
```diff
- warning: unexpected `cfg` condition name
+ warning: unexpected `cfg` condition name: `widnows`
```

It also cherry-pick the better sensible logic for when we print the list of expected values when we have a matching value for a very similar name.

Address https://github.com/rust-lang/rust/pull/111072#discussion_r1356818100

r? `@petrochenkov`
2023-10-13 08:37:27 +00:00
Esteban Küber e7618756c0 On type error involving closure, avoid ICE
When we encounter a type error involving a closure, we try to typeck
prior closure invocations to see if they influenced the current expected
type. When trying to do so, ensure that the closure was defined in our
current scope.

Fix #116658.
2023-10-12 23:29:02 +00:00
Esteban Küber 6b2c6c7fd3 Detect ruby-style closure in parser
When parsing a closure without a body that is surrounded by a block,
suggest moving the opening brace after the closure head.

Fix #116608.
2023-10-12 21:50:18 +00:00
bors e20cb77021 Auto merge of #116391 - Nadrieril:constructorset, r=cjgillot
exhaustiveness: Rework constructor splitting

`SplitWildcard` was pretty opaque. I replaced it with a more legible abstraction: `ConstructorSet` represents the set of constructors for patterns of a given type. This clarifies responsibilities: `ConstructorSet` handles one clear task, and diagnostic-related shenanigans can be done separately.

I'm quite excited, I had has this in mind for years but could never quite introduce it. This opens up possibilities, including type-specific optimisations (like using a `FxHashSet` to collect enum variants, which had been [hackily attempted some years ago](https://github.com/rust-lang/rust/pull/76918)), my one-pass rewrite (https://github.com/rust-lang/rust/pull/116042), and future librarification.
2023-10-12 21:33:31 +00:00
Urgau 001a65c4b0 check-cfg: only print the list of expected names once 2023-10-12 18:39:35 +02:00
Urgau dcfc484b09 check-cfg: mention the unexpected name and value in the primary message 2023-10-12 18:39:04 +02:00
Urgau 72815dc08f check-cfg: adjust expected names and values when useful 2023-10-12 18:39:04 +02:00
Matthias Krüger 5f90bee663
Rollup merge of #116642 - weiznich:diagnostic_on_unimplemented_improvements, r=compiler-errors
Handle several `#[diagnostic::on_unimplemented]` attributes correctly

This PR fixes an issues where rustc would ignore subsequent `#[diagnostic::on_unimplemented]` attributes. The [corresponding RFC](https://rust-lang.github.io/rfcs/3368-diagnostic-attribute-namespace.html) specifies that the first matching instance of each option is used. Invalid attributes are linted and otherwise ignored.
2023-10-12 18:36:44 +02:00
bors 19149d1ea9 Auto merge of #116649 - nnethercote:improve-print_tts-precursors, r=petrochenkov
Token cleanups

Some precursors to #114571 that are worth merging even if the main part of #114571 doesn't get merged.

r? `@petrochenkov`
2023-10-12 13:10:14 +00:00
bors 3d575a2f2e Auto merge of #113487 - estebank:sugg-113174, r=oli-obk
Use structured suggestion for #113174

When encountering a for loop that is rejected by the borrow checker because it is being advanced within its body, provide a structured suggestion for `while let Some(pat) = iter.next()`.
2023-10-12 02:34:07 +00:00
Nicholas Nethercote 129fe9a998 Add a comment to `tests/ui/proc-macro/issue-75930-derive-cfg.rs`.
Explaining something in the output that surprised me.
2023-10-12 08:46:15 +11:00
Georg Semmler 232aaeba7c
Handle several `#[diagnostic::on_unimplemented]` attributes correctly
This PR fixes an issues where rustc would ignore subsequent
`#[diagnostic::on_unimplemented]` attributes. The [corresponding
RFC](https://rust-lang.github.io/rfcs/3368-diagnostic-attribute-namespace.html)
specifies that the first matching instance of each option is used.
Invalid attributes are linted and otherwise ignored.
2023-10-11 22:01:59 +02:00
Esteban Küber a53f280bfc Suggest `;` after bare `match` expression E0308
Fix #72634.
2023-10-11 18:51:56 +00:00
Esteban Küber 9d2eb66e1a Use structured suggestion for #113174
When encountering a for loop that is rejected by the borrow checker
because it is being advanced within its body, provide a structured
suggestion for `while let Some(pat) = iter.next()`.
2023-10-11 18:26:44 +00:00
Matthias Krüger 3712ea82f3
Rollup merge of #116436 - compiler-errors:structurally-normalize-for-closure, r=lcnr
Structurally normalize for closure

Fixes some signature deduction problems in the new trait solver (and in the case of async, an ICE).

r? lcnr
2023-10-11 20:08:21 +02:00
Matthias Krüger 8ddc0df1f1
Rollup merge of #116219 - compiler-errors:relate-alias-ty-with-variance, r=lcnr
Relate alias ty with variance

In the new solver, turns out that the subst-relate branch of the alias-relate predicate was relating args invariantly even for opaques, which have variance 💀.

This change is a bit more invasive, but I'd rather not special-case it [here](aeaa5c30e5/compiler/rustc_trait_selection/src/solve/alias_relate.rs (L171-L190)) and then have it break elsewhere. I'm doing a perf run to see if the extra call to `def_kind` is that expensive, if it is, I'll reconsider.

r? ``@lcnr``
2023-10-11 20:08:20 +02:00
bors 3c23df4935 Auto merge of #115937 - oli-obk:spurious_unreachable_pattern, r=Nadrieril
Prevent spurious `unreachable pattern` lints

But it means we'll get more `non-exhaustive` patterns

fixes https://github.com/rust-lang/rust/issues/78057

r? `@Nadrieril` `@RalfJung`
2023-10-11 14:49:49 +00:00
Oli Scherer e83467c3b8 Avoid emitting the non_exhaustive error if other errors already occurred 2023-10-11 12:49:57 +00:00
Oli Scherer d1fd11f3f9 Prevent spurious `unreachable pattern` lints
Means you'll get more `non-exhaustive` patterns
2023-10-11 12:49:57 +00:00
bors 5aa23be6b6 Auto merge of #116014 - lqd:mcp510-2-electric-boogaloo, r=petrochenkov
Implement `-Clink-self-contained=-linker` opt out

This implements the `-Clink-self-contained` opt out necessary to switch to lld by changing rustc's defaults instead of cargo's.

Components that are enabled and disabled on the CLI are recorded, for the purpose of being merged with the ones which the target spec will declare (I'll open another PR for that tomorrow, for easier review).

For MCP510, we now check whether using the self-contained linker is disabled on the CLI. Right now it would only be sensible to with `-Zgcc-ld=lld` (and I'll add some checks that we don't both enable and disable a component on the CLI in a future PR), but the goal is to simplify adding the check of the target's enabled components here in the follow-up PRs.

r? `@petrochenkov`
2023-10-11 12:11:39 +00:00
bors 71704c4f84 Auto merge of #116623 - Nadrieril:validate-range-endpoints, r=oli-obk
Fix overflow checking in range patterns

When a range pattern contains an overflowing literal, if we're not careful we might not notice the overflow and use the wrapped value. This makes for confusing error messages because linting against overflowing literals is only done in a later pass. So when a range is invalid we check for overflows to provide a better error.

This check didn't use to handle negative types; this PR fixes that. First commit adds tests, second cleans up without changing behavior, third does the fix.

EDIT: while I was at it, I fixed a small annoyance about the span of the overflow lint on negated literals.

Fixes https://github.com/rust-lang/rust/issues/94239
2023-10-11 10:07:19 +00:00
bors 6d05c430d2 Auto merge of #115948 - notriddle:notriddle/logo-lockup, r=fmease
rustdoc: show crate name beside smaller logo

*Blocked on https://github.com/rust-lang/cargo/pull/12800*

## Summary

In this PR, the crate name and version are always shown in the sidebar, even in subpages, and the lateral navigation is always shown in the sidebar, even in modules.

Clicking the crate name does the same thing clicking the logo always did: take you to the crate root (the crate's home page, at least within Rustdoc).

The Rust logo is also no longer shown by default for non-Rust docs.

### Screenshots

<details><summary>Before</summary>

| | Macro | Module |
|--|-------|--------|
| In crate | ![image](https://github.com/rust-lang/rust/assets/1593513/d5db0a46-2bb6-44a2-a3aa-2d915ecb8595) |![image](https://github.com/rust-lang/rust/assets/1593513/61f8c1ee-c298-4e2c-b791-18ecb79ab83b)
| In module[^1] | ![image](https://github.com/rust-lang/rust/assets/1593513/73abca59-0b69-4650-a1e2-7278ca34795c) | ![image](https://github.com/rust-lang/rust/assets/1593513/0baf02c2-2ec7-4674-80e5-a6a74a973376)

[^1]: This PR also includes a bug fix for derive macros not showing up in the lateral navigation part of the sidebar

</details>

#### Whole sidebar screenshots

| | Macro | Module |
|--|-------|--------|
| In crate | ![image](https://github.com/rust-lang/rust/assets/1593513/75d1bd07-41f7-4f11-ba24-fd5476e0586a) | ![image](https://github.com/rust-lang/rust/assets/1593513/52960259-2b65-4131-b380-01826f0a0eb7)
| In module | ![image](https://github.com/rust-lang/rust/assets/1593513/06e57928-8cb0-41bd-b152-be16cc53e5ec) | ![image](https://github.com/rust-lang/rust/assets/1593513/37291c69-2a07-4467-a382-d9b029084a47)

#### Different logo configurations

|         | Short crate name | Long crate name |
|---------|------------------|-----------------|
| Root    | ![short-root]    | ![long-root]
| Subpage | ![short-subpage] | ![long-subpage]

[short-root]: https://github.com/rust-lang/rust/assets/1593513/9e2b4fa8-f581-4106-b562-1e0372c13f79
[short-subpage]: https://github.com/rust-lang/rust/assets/1593513/8331cdb8-fa13-4671-a1e2-dcc1cdca7451
[long-root]: https://github.com/rust-lang/rust/assets/1593513/7d377fec-0f1d-4343-9f82-0e35a8f58056
[long-subpage]: https://github.com/rust-lang/rust/assets/1593513/3b3094a4-63c9-477c-8c15-b6075837df30

##### Without a logo

![image](https://github.com/rust-lang/rust/assets/1593513/66672b79-6c59-4be8-a527-25ef6f0b04ab)

### Preview pages

https://notriddle.com/rustdoc-html-demo-5/sidebar-layout-rocket/rocket/index.html

https://notriddle.com/rustdoc-html-demo-5/sidebar-layout-rocket/rocket_sync_db_pools/index.html

https://notriddle.com/rustdoc-html-demo-5/sidebar-layout-rust-compiler/index.html

https://notriddle.com/rustdoc-html-demo-5/sidebar-layout-rust/std/index.html

https://notriddle.com/rustdoc-html-demo-5/sidebar-layout-rocket/tokio/index.html

## Motivation

This improves visual information density (the construct with the logo and crate name is *shorter* than the logo on its own, because it's not square) and navigation clarity (we can now see what clicking the Rust logo does, specifically).

Compare this with the layout at [Phoenix's Hexdocs] (which is what this proposal is closely based on), the old proposal on [Internals Discourse] (which always says "Rust standard library" in the sidebar, but doesn't do the side-by-side layout).

[Phoenix's Hexdocs]: https://hexdocs.pm/phoenix/1.7.7/overview.html
[Internals Discourse]: https://internals.rust-lang.org/t/poc-of-a-new-design-for-the-generated-rustdoc/11018

## Guide-level explanation

This PR cleans up some of the sidebar navigation.

It makes the logo in the desktop sidebar a bit smaller, and puts the crate name and version next to it (either beside it, or below it, depending on if there's space), making it clearer what clicking on it does: click the crate name to open the crate's home page. It also removes the Rust logo from non-official-Rust crates, again to make the navigation and supply chain clearer (since the crate name has been added, the logo is no longer necessary for navigation).

It adds a bit more clarifying information for lateral navigation. On items that don't add their own sidebar items, it just shows its siblings directly below the crate name and logo, but for other items, it shows "In crate alloc" instead of just "In alloc". It also shows the lateral navigation tools on module pages, making modules consistent with every other item.

## Drawbacks

While this actually takes up less screen real estate than the old layout on desktop, it takes up more HTML. It's also a bit more visually complex.

## Rationale and alternatives

I could do what the Internals POC did and keep the vertically stacked layout all the time, instead of doing a horizontal stack where possible. It would take up more screen real estate, though.

## Prior art

This design is lifted almost verbatim from Hexdocs. It seems to work for them. [`opentelemetry_process_propagator`], for example, has a long application name.

[`opentelemetry_process_propagator`]: https://hexdocs.pm/opentelemetry_process_propagator/OpentelemetryProcessPropagator.html

## Unresolved questions

Maybe we should encourage crate authors to include their own logo more often? It certainly helps give people a better sense of "place." This seems to be blocked on coming up with an API to do it without requiring them to host the file somewhere.

## Future possibilities

Beyond this, plenty of other changes could be made to improve the layout, like

* Fix things so that clicking an item in the sidebar doesn't cause it to scroll back to the top.
  * The [Internals demo](https://utherii.github.io/new.html) does this right: clicking an item in the sidebar changes the content area, but the sidebar itself does not change. This is nice, because clicking is cheap and I can skim the opening few paragraphs while browsing.
  * The layout of the docs sidebar causes trouble to implement this, because it's different on different pages, but at least fix this on the file browser.
* Come up with a less cluttered way to do disclosure. There's a lot of `[-]` on the page.
  * We don't lack ideas to fix this one. We have *too many*.
* Do a better job of separating local navigation (vec::Vec links to vec::IntoIter) and the table of contents (vec::Vec links to vec::Vec::new).
  * A possibility: add a Back arrow next to the "In [module]" header?
    ![image](https://github.com/rust-lang/rust/assets/1593513/e969faf7-7722-457a-b8c6-8d962e9e1e23)
* Give readers more control of how much rustdoc shows them, and giving doc authors more control of how much it generates. Basically, https://github.com/rust-lang/rust/pull/115660 is great, let's do it too.

But those are mostly orthogonal, not future possibilities unlocked by this change.
2023-10-11 06:28:36 +00:00
Nadrieril dcdddb7a60 Fix span of overflow lint for negated literals 2023-10-11 04:55:55 +02:00
Nadrieril 1baf8bf54d Fix range overflow checking 2023-10-11 04:55:55 +02:00
Nadrieril c5e17021cc Add tests 2023-10-11 04:54:49 +02:00
Ali MJ Al-Nasrawy a7042a94a3
Rollup merge of #116530 - aliemjay:ice-on-ambiguity, r=compiler-errors
delay a bug when encountering an ambiguity in MIR typeck

We shouldn't have any trait selection ambiguities in MIR typeck.

See https://github.com/rust-lang/rust/pull/114586#issuecomment-1751967321

r? `@oli-obk` `@compiler-errors` `@lcnr`
2023-10-11 03:53:17 +03:00
Guillaume Gomez bbaf6bd136
Rollup merge of #116444 - RalfJung:broken-unused-const, r=oli-obk
add test for const-eval error in dead code during monomorphization
2023-10-10 18:44:45 +02:00
Guillaume Gomez 0e5e04b89a
Rollup merge of #116250 - estebank:closure-arg-inference-span, r=petrochenkov
On type error of closure call argument, point at earlier calls that affected inference

Mitigate part of  https://github.com/rust-lang/rust/issues/71209.

When we encounter a type error on a specific argument of a closure call argument, where the closure's definition doesn't have a type specified, look for other calls of the closure to try and find the specific call that cased that argument to be inferred of the expected type.

```
error[E0308]: mismatched types
  --> $DIR/unboxed-closures-type-mismatch.rs:30:18
   |
LL |         identity(1u16);
   |         -------- ^^^^ expected `u8`, found `u16`
   |         |
   |         arguments to this function are incorrect
   |
note: expected because the closure was earlier called with an argument of type `u8`
  --> $DIR/unboxed-closures-type-mismatch.rs:29:18
   |
LL |         identity(1u8);
   |         -------- ^^^ expected because this argument is of type `u8`
   |         |
   |         in this closure call
note: closure parameter defined here
  --> $DIR/unboxed-closures-type-mismatch.rs:28:25
   |
LL |         let identity = |x| x;
   |                         ^
help: change the type of the numeric literal from `u16` to `u8`
   |
LL |         identity(1u8);
   |                   ~~
```
2023-10-10 18:44:44 +02:00
bors 091bb74e7e Auto merge of #116548 - nnethercote:assert-long-condition, r=matthewjasper
Improve handling of assertion failures with very long conditions

It's not perfectly clear what the best behaviour is here, but I think this is an improvement.

r? `@matthewjasper`
cc `@m-ou-se`
2023-10-10 08:02:20 +00:00
bors 84d44dd1d8 Auto merge of #116366 - estebank:issue-103982, r=oli-obk
Suggest labeling block if `break` is in bare block

Fix #103982.
2023-10-10 06:04:08 +00:00
Esteban Küber 2f79681fb9 Only emit one error per unsized binding, instead of one per usage
Fix #56607.
2023-10-09 23:00:15 +00:00
Esteban Küber 3d86b8acda Add test for #56607 2023-10-09 22:51:16 +00:00
Esteban Küber d23dc2093c Account for macros 2023-10-09 22:48:10 +00:00
Nicholas Nethercote 7528fdc4c4 Don't `escape_debug` the condition of `assert!`.
The assertion in `assert-long-condition.rs` used to be fail like this, all on
one line:
```
thread 'main' panicked at 'assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18\n                                + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0', tests/ui/macros/assert-long-condition.rs:7:5
```
The `\n` and subsequent indent is because the condition is pretty-printed, and
the pretty-printer inserts a newline. Printing the newline in this way is
arguably reasonable given that the message appears within single quotes, which
is very similar to a string literal.

However, after the assertion printing improvements that were released in 1.73,
the assertion now fails like this:
```
thread 'main' panicked at tests/ui/macros/assert-long-condition.rs:7:5:
assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18\n                                + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0
```
Now that there are no single quotes around the pretty-printed condition, the
`\n` is quite strange.

This commit gets rid of the `\n`, by removing the `escape_debug` done on the
pretty-printed message. This results in the following:
```
thread 'main' panicked at tests/ui/macros/assert-long-condition.rs:7:5:
assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18
                                + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0
```
The overly-large indent is still strange, but that's a separate pretty-printing issue.

This change helps with #108341.
2023-10-10 09:08:11 +11:00
Nicholas Nethercote 15c1a6b9e0 Add a ui test with an assertion that has a really long condition.
The `\n` in the output is a little surprising. The next commit will deal
with it.
2023-10-10 09:05:58 +11:00
bors 59edd67056 Auto merge of #116497 - compiler-errors:impl-span, r=cjgillot
Extend `impl`'s `def_span` to include its where clauses

Typically, we highlight the def-span of an impl in a diagnostic due to either:
1. coherence error
2. trait evaluation cycle
3. invalid implementation of built-in trait

I find that an impl's where clauses are very often required to understanding why these errors come about, which is unfortunate since where clauses may be located on different lines and don't show up in the error. This PR expands the def-span of impls to include these where clauses.

r? cjgillot since you've touched this code a while back to make some spans shorter, but you can also reassign to wg-diagnostics or compiler if you're busy or have no strong opinions.
2023-10-09 21:03:41 +00:00
Esteban Küber c30d57bb77 fix 2023-10-09 19:24:05 +00:00
Esteban Küber 5c17b8be61 Move some tests around 2023-10-09 19:24:05 +00:00
Esteban Küber daac011459 Suggest labeling block if `break` is in bare block
Fix #103982.
2023-10-09 19:24:05 +00:00
Matthias Krüger 27a5146e7c
Rollup merge of #116561 - ouz-a:testfor_115517, r=compiler-errors
Add a test for fixed ICE

Addresses https://github.com/rust-lang/rust/issues/115517#issuecomment-1730164116

Closes #115517

r? ``@compiler-errors``
2023-10-09 16:26:03 +02:00
Matthias Krüger 374c885f4a
Rollup merge of #116537 - gurry:116473-ice-sugg-overlap, r=compiler-errors
Fix suggestion span involving wrongly placed generic arg on variant

Fixes #116473

The span computation was wrong. It went from the end of the variant to the end of the (wrongly placed) args. However, the variant lived in a different expansion and this resulted in a nonsensical span that overlaps with another and thereby leads to the ICE.

In the fix I've changed span computation to not be based on the location of the variant, but purely on the location of the args. I simply extend the start of the args span 2 positions to the left and that includes the `::` and that's all we need apparently.

This approach produces a correct span regardless of which macro/expansion the args reside in and where the variant is.
2023-10-09 16:26:01 +02:00
Matthias Krüger 389747c41d
Rollup merge of #115882 - aliemjay:diag-name-region-1, r=compiler-errors
improve the suggestion of `generic_bound_failure`

- Fixes #115375
- suggest the bound in the correct scope: trait or impl header vs assoc item. See `tests/ui/suggestions/lifetimes/type-param-bound-scope.rs`
- don't suggest a lifetime name that conflicts with the other late-bound regions of the function:
```rust
type Inv<'a> = *mut &'a ();
fn check_bound<'a, T: 'a>(_: T, _: Inv<'a>) {}
fn test<'a, T>(_: &'a str, t: T, lt: Inv<'_>) { // suggests a new name `'a`
    check_bound(t, lt); //~ ERROR
}
```
2023-10-09 16:26:00 +02:00
Michael Goulet 592163fb71 Extend impl's def_span to include where clauses 2023-10-09 11:47:02 +00:00
Oğuz Ağcayazı 2e000ebaa5 add test 2023-10-09 13:57:26 +03:00
bors 093b9d5b29 Auto merge of #116533 - cjgillot:skip-trivial-mir, r=oli-obk
Do not run optimizations on trivial MIR.

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

The bug was introduced in https://github.com/rust-lang/rust/pull/110728, which put the check too early in the query chain.

cc `@oli-obk` `@ouz-a`
2023-10-09 06:00:23 +00:00
Michael Howell c6e6ecb1af rustdoc: remove rust logo from non-Rust crates 2023-10-08 20:17:53 -07:00
Gurinder Singh 23a3b9e449 Fix suggestion span involving wrongly placed generic arg on enum variants
When the variant and the (wrongly placed) args are at separate
source locations such as being in different macos or one in a macro and
the other somwhere outside of it, the arg spans we computed spanned
the entire distance between such locations and were hence invalid.
.
2023-10-09 08:04:00 +05:30
Rémy Rakic d634cc5a55 add test for `-Clink-self-contained` consistency 2023-10-08 21:57:39 +00:00
Ralf Jung 5e1b0cbe5d add test for const-eval error in dead code during monomorphization 2023-10-08 17:43:46 +02:00
Camille GILLOT 005ec2e51c Do not run optimizations on trivial MIR. 2023-10-08 12:09:06 +00:00
Ali MJ Al-Nasrawy a8830631b9 remove trailing dots 2023-10-08 10:06:17 +00:00
Ali MJ Al-Nasrawy 996ffcb718 always show and explain sub region 2023-10-08 09:59:51 +00:00
Ali MJ Al-Nasrawy 5be0b2283a improve the suggestion of generic_bound_failure 2023-10-08 09:56:57 +00:00
Ali MJ Al-Nasrawy 710c073acb delay a bug when encountering an ambiguity in MIR typeck 2023-10-08 09:14:12 +00:00
Vadim Petrochenkov 7ecb09d05c linker: Remove unstable legacy CLI linker flavors 2023-10-07 21:57:53 +03:00
bors 48e24629e9 Auto merge of #115583 - RalfJung:packed-unsized, r=lcnr
fix detecting references to packed unsized fields

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

This is a breaking change, but permitted as a soundness fix.
2023-10-07 10:57:18 +00:00
Jubilee 5268120d4a
Rollup merge of #116458 - bjorn3:fix_global_asm_test, r=workingjubilee
Properly export function defined in test which uses global_asm!()

Currently the test passes with the LLVM backend as the codegen unit partitioning logic happens to place both the global_asm!() and the function which calls the function defined by the global_asm!() in the same CGU. With the Cranelift backend it breaks however as it will place all assembly in separate codegen units to be passed to an external linker.
2023-10-06 16:37:47 -07:00
Jubilee 0d68e416a5
Rollup merge of #116400 - estebank:issue-78585, r=WaffleLapkin
Detect missing `=>` after match guard during parsing

```
error: expected one of `,`, `:`, or `}`, found `.`
  --> $DIR/missing-fat-arrow.rs:25:14
   |
LL |         Some(a) if a.value == b {
   |                               - while parsing this struct
LL |             a.value = 1;
   |             -^ expected one of `,`, `:`, or `}`
   |             |
   |             while parsing this struct field
   |
help: try naming a field
   |
LL |             a: a.value = 1;
   |             ++
help: you might have meant to start a match arm after the match guard
   |
LL |         Some(a) if a.value == b => {
   |                                 ++
```

Fix #78585.
2023-10-06 16:37:47 -07:00
bors 94bc9c737e Auto merge of #114811 - estebank:impl-ambiguity, r=wesleywiser
Show more information when multiple `impl`s apply

- When there are `impl`s without type params, show only those (to avoid showing overly generic `impl`s).
```
error[E0283]: type annotations needed
  --> $DIR/multiple-impl-apply.rs:34:9
   |
LL |     let y = x.into();
   |         ^     ---- type must be known at this point
   |
note: multiple `impl`s satisfying `_: From<Baz>` found
  --> $DIR/multiple-impl-apply.rs:14:1
   |
LL | impl From<Baz> for Bar {
   | ^^^^^^^^^^^^^^^^^^^^^^
...
LL | impl From<Baz> for Foo {
   | ^^^^^^^^^^^^^^^^^^^^^^
   = note: required for `Baz` to implement `Into<_>`
help: consider giving `y` an explicit type
   |
LL |     let y: /* Type */ = x.into();
   |          ++++++++++++
```

- Lower the importance of `T: Sized`, `T: WellFormed` and coercion errors, to prioritize more relevant errors. The pre-existing deduplication logic deals with hiding redundant errors better that way, and we show errors with more metadata that is useful to the user.

- Show `<SelfTy as Trait>::assoc_fn` suggestion in more cases.
```
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
  --> $DIR/cross-return-site-inference.rs:38:16
   |
LL |     return Err(From::from("foo"));
   |                ^^^^^^^^^^ cannot call associated function of trait
   |
help: use a fully-qualified path to a specific available implementation
   |
LL |     return Err(</* self type */ as From>::from("foo"));
   |                +++++++++++++++++++     +
```

Fix #88284.
2023-10-06 18:44:32 +00:00
Esteban Küber 4483ac2206 Fix windows test that has different stderr output 2023-10-06 15:51:04 +00:00
Guillaume Gomez 9e28a9349c
Rollup merge of #116329 - RalfJung:swap-comments, r=scottmcm
update some comments around swap()

Based on ``@eddyb's`` comment [here](https://github.com/rust-lang/unsafe-code-guidelines/issues/461#issuecomment-1742156410).

And then I noticed the wrong capitalization for Miri and fixed it in some other places as well.
2023-10-06 13:18:35 +02:00
bjorn3 ecf271cfb6 Use pushsection/popsection 2023-10-06 11:02:11 +00:00
Matthias Krüger 7d7004d3e6
Rollup merge of #116421 - Urgau:inter-mut-invalid_ref_casting, r=oli-obk
Clarify `invalid_reference_casting` lint around interior mutable types

This is PR intends to clarify the `invalid_reference_casting` lint around interior mutable types by adding a note for them saying that they should go through `UnsafeCell::get`.

So for this code:
```rust
let cell = &std::cell::UnsafeCell::new(0);
let _num = &mut *(cell as *const _ as *mut i32);
```

the following note will be added to the lint output:

```diff
 error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused,  consider instead using an `UnsafeCell`
   --> $DIR/reference_casting.rs:68:16
    |
 LL |     let _num = &mut *(cell as *const _ as *mut i32);
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
+   = note: even for types with interior mutability, the only legal way to obtain a mutable pointer from a shared reference is through `UnsafeCell::get`
```

Suggestion are welcome around the note contents.

Fixes https://github.com/rust-lang/rust/issues/116410
cc `@RalfJung`
2023-10-06 06:23:48 +02:00
bjorn3 9facf0bf72 Properly export function defined in test which uses global_asm!()
Currently the test passes with the LLVM backend as the codegen unit
partitioning logic happens to place both the global_asm!() and the
function which calls the function defined by the global_asm!() in the
same CGU. With the Cranelift backend it breaks however as it will place
all assembly in separate codegen units to be passed to an external
linker.
2023-10-05 19:42:25 +00:00
bors cae0791da4 Auto merge of #116417 - ouz-a:trait_type_detective, r=compiler-errors
Remove is global hack

In attempt to fix https://github.com/rust-lang/rust/issues/114057 we found several issues with how compiler computes layouts, this change removes `is_global` from `and` to stop impl from being shadowed.

In depth conversation can be read here https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/Getting.20different.20types.20from.20almost.20same.20inputs

This is a fix candidate opened for performance run.

r? `@lcnr`
2023-10-05 19:42:05 +00:00
Oğuz Ağcayazı e30d27be00 remove is global hack 2023-10-05 21:38:12 +03:00
Matthias Krüger c1c5ab717e
Rollup merge of #116428 - Alexendoo:note-duplicate-diagnostics, r=compiler-errors,estebank
Add a note to duplicate diagnostics

Helps explain why there may be a difference between manual testing and the test suite output and highlights them as something to potentially look into

For existing duplicate diagnostics I just blessed them other than a few files that had other `NOTE` annotations in
2023-10-05 19:24:35 +02:00
ouz-a 3088c4b046 move subtyper change reveal_all 2023-10-05 18:56:30 +03:00
francorbacho c8ee7db6ea Only give autofix suggestion when no named args are present 2023-10-05 16:11:31 +02:00
francorbacho 38b0182832 Add suggestion test 2023-10-05 16:11:31 +02:00
francorbacho 905bace904 Highlight redundant arguments instead of the whole format string 2023-10-05 16:11:31 +02:00
francorbacho fcdd5c0b2d Plurals in format redundant arguments suggestion 2023-10-05 16:11:31 +02:00
francorbacho 04fc051a34 Use diagnostic impls and add suggestions in redundant format!() args 2023-10-05 16:09:57 +02:00
francorbacho 93df9e6d7d Suggest removing redundant arguments in format!() 2023-10-05 16:05:42 +02:00
Jubilee d7b02c3d40
Rollup merge of #116431 - estebank:issue-80476, r=compiler-errors
Tweak wording of E0562

Fix #80476.
2023-10-05 00:56:30 -07:00
Jubilee a9a389cf44
Rollup merge of #116429 - fmease:clean-up-struct-field-suggs, r=compiler-errors
Diagnostics: Be more careful when suggesting struct fields

Consolidate the various places which filter out struct fields that shouldn't be suggested into a single function.

Previously, each of those code paths had slightly different and incomplete metrics for no good reason. Now, there's only a single 'complete' metric (namely `is_field_suggestable`) which also filters out hygienic fields that come from different syntax contexts.

Fixes #116334.
2023-10-05 00:56:30 -07:00
Jubilee cfce3a919d
Rollup merge of #116296 - compiler-errors:default-return, r=estebank
More accurately point to where default return type should go

When getting the "default return type" span, instead of pointing to the low span of the next token, point to the high span of the previous token. This:

1. Makes forming return type suggestions more uniform, since we expect them all in the same place.
2. Arguably makes labels easier to understand, since we're pointing to where the implicit `-> ()` would've gone, rather than the starting brace or the semicolon.

r? ```@estebank```
2023-10-05 00:56:29 -07:00
Jubilee ea3454eabb
Rollup merge of #116223 - catandcoder:master, r=cjgillot
Fix misuses of a vs an

Fixes the misuse of "a" vs "an", according to English grammatical
expectations and using https://www.a-or-an.com/
2023-10-05 00:56:29 -07:00
bors 5236c8e1fa Auto merge of #116273 - compiler-errors:refine2, r=tmandry
Only trigger `refining_impl_trait` lint on reachable traits

Public but unreachable traits don't matter 😸

r? `@tmandry`
2023-10-05 03:00:30 +00:00
bors b781645332 Auto merge of #116184 - compiler-errors:afit-lint, r=tmandry
Add `async_fn_in_trait` lint

cc https://github.com/rust-lang/rust/pull/115822#issuecomment-1731168465

Mostly unsure what the messaging should be. Feedback required.

r? `@tmandry`
2023-10-05 01:14:25 +00:00
Alex Macleod 5453a9f34d Add a note to duplicate diagnostics 2023-10-05 01:04:41 +00:00
Michael Goulet dfbb1bfc89 Also closures 2023-10-05 00:05:45 +00:00
Michael Goulet 966f27977a Structurally normalize async fn return type in deduce_future_output_from_obligations 2023-10-05 00:05:20 +00:00
Nadrieril c1b29b338d Fix handling slices of empty types 2023-10-05 00:58:14 +02:00
Michael Goulet 137b6d0b01 Point to where missing return type should go 2023-10-04 21:09:54 +00:00
bors 2bbb619893 Auto merge of #114417 - chinedufn:fix-expect-unused-in-impl-block-rust-issue-114416, r=cjgillot
Fix multiple `expect` attribs in impl block

Closes #114416
2023-10-04 20:44:38 +00:00
Urgau e46236cceb Clarify `invalid_reference_casting` lint around interior mutable types 2023-10-04 22:06:16 +02:00
Esteban Küber 041e54bd92 Tweak wording of E0562
Fix #80476.
2023-10-04 19:51:43 +00:00
León Orell Valerian Liehr 867cc41b5b
clean up struct field suggestions 2023-10-04 21:36:04 +02:00
Esteban Küber 8d92c996ca Fix test on WASM target by making ambiguity pruning more agressive 2023-10-04 18:58:06 +00:00
bors f306362fb9 Auto merge of #116413 - nnethercote:rm-E0551, r=compiler-errors
Remove E0551

Because it's the same as E0539.

Fixes #51489.

r? `@Nilstrieb`
2023-10-04 16:51:42 +00:00
bors 65519f5fc0 Auto merge of #116360 - compiler-errors:async-span, r=oli-obk
Point to full `async fn` for future

Semi-follow-up to https://github.com/rust-lang/rust/pull/116296#discussion_r1342007575

cc `@asquared31415`
2023-10-04 09:55:02 +00:00
Nicholas Nethercote 0ece171c2f Remove E0551.
Because it's the same as E0539.

Fixes #51489.
2023-10-04 18:12:20 +11:00
Michael Goulet 5087bb1046 Relate AliasTy considering variance 2023-10-04 04:22:04 +00:00
Matthias Krüger 4ed2291624
Rollup merge of #116393 - compiler-errors:auto-bad, r=WaffleLapkin
Emit feature gate *warning* for `auto` traits pre-expansion

Auto traits were introduced before we were more careful about not stabilizing new syntax pre-expansion.

This is a more conservative step in the general direction we want to go in https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Removal.20of.20.60auto.20trait.60.20syntax.

Fixes #116121
2023-10-04 05:02:07 +02:00
Esteban Küber 7313c10774 Show suggestion for `<SelfTy as Trait>::assoc_fn` in more cases and fmt code 2023-10-04 02:04:14 +00:00
Esteban Küber 91b9ffeab0 Reorder fullfillment errors to keep more interesting ones first
In `report_fullfillment_errors` push back `T: Sized`, `T: WellFormed`
and coercion errors to the end of the list. The pre-existing
deduplication logic eliminates redundant errors better that way, keeping
the resulting output with fewer errors than before, while also having
more detail.
2023-10-04 02:04:14 +00:00
Esteban Küber 2817ece19c Show more information when multiple `impl` apply 2023-10-04 02:04:13 +00:00
Esteban Küber 8fd345dd4b review comments 2023-10-04 01:35:07 +00:00
cui fliter f44d116e1f Fix misuses of a vs an
Signed-off-by: cui fliter <imcusg@gmail.com>
2023-10-04 08:01:11 +08:00
Esteban Küber 18ec4e9bcd Move some tests around 2023-10-03 21:31:27 +00:00
Esteban Küber 745c1ea438 Detect missing `=>` after match guard during parsing
```
error: expected one of `,`, `:`, or `}`, found `.`
  --> $DIR/missing-fat-arrow.rs:25:14
   |
LL |         Some(a) if a.value == b {
   |                               - while parsing this struct
LL |             a.value = 1;
   |             -^ expected one of `,`, `:`, or `}`
   |             |
   |             while parsing this struct field
   |
help: try naming a field
   |
LL |             a: a.value = 1;
   |             ++
help: you might have meant to start a match arm after the match guard
   |
LL |         Some(a) if a.value == b => {
   |                                 ++
```

Fix #78585.
2023-10-03 21:21:02 +00:00
Michael Goulet 7815641be0 Gate against auto traits pre-expansion 2023-10-03 19:12:00 +00:00
Matthias Krüger 9143370868
Rollup merge of #116379 - fmease:opaq-hid-inf-bnds-non-lt-bndrs, r=compiler-errors
non_lifetime_binders: fix ICE in lint opaque-hidden-inferred-bound

Opaque types like `impl for<T> Trait<T>` would previously lead to an ICE.

r? `@compiler-errors`
2023-10-03 16:24:17 +02:00
Matthias Krüger 535cd8d511
Rollup merge of #114654 - estebank:suggest-pin-macro, r=davidtwco
Suggest `pin!()` instead of `Pin::new()` when appropriate

When encountering a type that needs to be pinned but that is `!Unpin`, suggest using the `pin!()` macro.

Fix #57994.
2023-10-03 16:24:15 +02:00
León Orell Valerian Liehr 3f0a327fbb
non_lifetime_binders: fix ICE in lint opaque-hidden-inferred-bound 2023-10-03 13:59:59 +02:00
Matthias Krüger fa1cbac1ea
Rollup merge of #116210 - Raekye:master, r=fee1-dead
Ensure that `~const` trait bounds on associated functions are in const traits or impls

Zulip discussion: https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/How.20to.2Fshould.20I.20try.20to.20pinpoint.20ICEs.20related.20to.20effects.3F
2023-10-03 12:24:11 +02:00
Matthias Krüger 634e5c9ba2
Rollup merge of #116158 - compiler-errors:unconstrained-type-var-sugg, r=wesleywiser
Don't suggest nonsense suggestions for unconstrained type vars in `note_source_of_type_mismatch_constraint`

The way we do type inference for suggestions in `note_source_of_type_mismatch_constraint` is a bit strange. We compute the "ideal" method signature, which takes the receiver that we *want* and uses it to compute the types of the arguments that would have given us that receiver via type inference, and use *that* to suggest how to change an argument to make sure our receiver type is inferred correctly.

The problem is that sometimes we have totally unconstrained arguments (well, they're constrained by things outside of the type checker per se, like associated types), and therefore type suggestions are happy to coerce anything to that unconstrained argument. This leads to bogus suggestions, like #116155. This is partly due to above, and partly due to the fact that `emit_type_mismatch_suggestions` doesn't double check that its suggestions are actually compatible with the program other than trying to satisfy the type mismatch.

This adds a hack to make sure that at least the types are fully constrained, but I guess I could also rip out this logic altogether. There would be some sad diagnostics regressions though, such as `tests/ui/type/type-check/point-at-inference-4.rs`.

Fixes #116155
2023-10-03 08:58:48 +02:00
Michael Goulet 2934fe07b7 Point to full async fn for future 2023-10-03 02:25:32 +00:00
Michael Goulet c373d206cd Address review nits 2023-10-03 00:51:13 +00:00
Michael Goulet 90dfa24415 Only reachable traits 2023-10-03 00:37:18 +00:00
Travis Cross afea0b4eab Fill in prose to describe the `async_fn_in_trait` lint
We're stabilizing `async fn` in trait (AFIT), but we have some
reservations about how people might use this in the definitions of
publicly-visible traits, so we're going to lint about that.

This is a bit of an odd lint for `rustc`.  We normally don't lint just
to have people confirm that they understand how Rust works.  But in
this one exceptional case, this seems like the right thing to do as
compared to the other plausible alternatives.

In this commit, we describe the nature of this odd lint.
2023-10-03 00:37:18 +00:00
Michael Goulet 28d58f6524 Bless tests 2023-10-03 00:37:18 +00:00
Michael Goulet ec79720c1e Add async_fn_in_trait lint 2023-10-03 00:37:18 +00:00
Michael Goulet 07851679cd Point out the actual mismatch error 2023-10-02 23:14:29 +00:00
Michael Goulet 8be12f4ed7 For a single impl candidate, try to unify it with error trait ref 2023-10-02 23:14:29 +00:00
Michael Goulet ac5aa8c1a4 Don't suggest nonsense suggestions for unconstrained type vars in note_source_of_type_mismatch_constraint 2023-10-02 21:13:46 +00:00
Tyler Mandry af77806bee
Rollup merge of #114454 - Nilstrieb:no-evil-sorting, r=cjgillot
Replace `HashMap` with `IndexMap` in pattern binding resolve

fixes https://github.com/rust-lang/rust/pull/114332#discussion_r1284189179
2023-10-02 16:09:42 -04:00
Nilstrieb 6ca07235a6 Replace `HashMap` with `IndexMap` in pattern binding resolve
It will be iterated over, so we should avoid using `HashMap`.
2023-10-02 19:12:42 +02:00
Chinedu Francis Nwafili 67379c4006
Address misc feedback 2023-10-02 08:59:31 -04:00
Ralf Jung bfc0f23acb MIRI -> Miri 2023-10-02 08:35:08 +02:00
bors e0d7ed1f45 Auto merge of #116281 - Nadrieril:eager-const-eval, r=cjgillot
Cleanup number handling in match exhaustiveness

Doing a little bit of cleanup; handling number constants was somewhat messy. In particular, this:

- evals float consts once instead of repetitively
- reduces `Constructor` from 88 bytes to 56 (`mir::Const` is big!)

The `fast_try_eval_bits` function was mostly constructed from inlining existing code but I don't fully understand it; I don't follow how consts work and are evaluated very well.
2023-10-01 22:01:44 +00:00
bors 16b7b39fdd Auto merge of #116228 - bvanjoi:fix-116164, r=cjgillot
resolve: skip underscore character during candidate lookup

Fixes #116164

In use statement, an underscore is merely a placeholder symbol and does not bind to any name. Therefore, it can be safely ignored.
2023-10-01 16:41:03 +00:00
Raekye 884af362f2 Validate `~const` trait bounds on associated fns.
Previously, any associated function could have `~const` trait bounds on
generic parameters, which could lead to ICEs when these bounds were used
on associated functions of non-`#[const_trait] trait` or
non-`impl const` blocks.

Includes changes as per @fee1-dead's comments in #116210.
2023-09-30 19:00:45 -04:00
Nadrieril fac50e8fb3 Evaluate float consts eagerly 2023-10-01 00:00:37 +02:00
bors 9136560d32 Auto merge of #115933 - oli-obk:simd_shuffle_const, r=workingjubilee
Prototype using const generic for simd_shuffle IDX array

cc https://github.com/rust-lang/rust/issues/85229

r? `@workingjubilee` on the design

TLDR: there is now a `fn simd_shuffle_generic<T, U, const IDX: &'static [u32]>(x: T, y: T) -> U;` intrinsic that allows replacing

```rust
simd_shuffle(a, b, const { stuff })
```

with

```rust
simd_shuffle_generic::<_, _, {&stuff}>(a, b)
```

which makes the compiler implementations much simpler, if we manage to at some point eliminate `simd_shuffle`.

There are some issues with this today though (can't do math without bubbling it up in the generic arguments). With this change, we can start porting the simple cases and get better data on the others.
2023-09-30 04:05:26 +00:00
Matthias Krüger 3ee2c526df
Rollup merge of #116263 - ferrocene:pa-more-bare-metal-fixes, r=oli-obk
More fixes for running the test suite on a bare metal target

This PR adds more fixes needed to run the test suite on bare metal targets (in this case, without unwinding and with static relocations). There is no CI job exercising tests without unwinds, but I can confirm this worked in Ferrocene's CI.
2023-09-29 22:27:52 +02:00
Matthias Krüger 77e9dcd3c8
Rollup merge of #116030 - RalfJung:abi-compat-test, r=wesleywiser
run abi/compatibility test against a whole bunch of targets
2023-09-29 22:27:50 +02:00
Matthias Krüger 4a886462c9
Rollup merge of #112123 - bvanjoi:fix-98562, r=compiler-errors
fix(suggestion): insert projection to associated types

Fixes #98562

This PR has fixed some help suggestions for unsupported syntax, such as `fn f<T>(_:T) where T: IntoIterator, std::iter::IntoIterator::Item = () {}` to `fn f<T: IntoIterator<Item = ()>>(_T) {}`.
2023-09-29 22:27:49 +02:00
Michael Goulet 06d9602d33 Only trigger refine lint on reachable traits 2023-09-29 18:36:41 +00:00
bors 56ada88e7e Auto merge of #113301 - Be-ing:stabilize_bundle_whole-archive, r=petrochenkov
stabilize combining +bundle and +whole-archive link modifiers

Per discussion on https://github.com/rust-lang/rust/issues/108081 combining +bundle and +whole-archive already works and can be stabilized independently of other aspects of the packed_bundled_libs feature. There is no risk of regression because this was not previously allowed.

r? `@petrochenkov`
2023-09-29 15:51:48 +00:00
apekros e71ee500d1 Add test for rust-lang#114912 2023-09-29 22:39:02 +10:00
Pietro Albini 3853774df8
mark relevant tests as requiring unwinding 2023-09-29 14:24:40 +02:00
bors c5450191f3 Auto merge of #115759 - oli-obk:open_drop_from_non-ADT, r=lcnr
Reveal opaque types before drop elaboration

fixes https://github.com/rust-lang/rust/issues/113594

r? `@cjgillot`

cc `@JakobDegen`

This pass was introduced in https://github.com/rust-lang/rust/pull/110714

I moved it before drop elaboration (which only cares about the hidden types of things, not the opaque TAIT or RPIT type) and set it to run unconditionally (instead of depending on the optimization level and whether the inliner is active)
2023-09-29 11:59:51 +00:00
Pietro Albini 90f317b2de
add needs-relocation-model-pic to compiletest 2023-09-29 13:10:26 +02:00
bohan b83dfb5c5a fix(suggestion): insert projection to associated types 2023-09-29 18:51:59 +08:00
Matthias Krüger 95262e4602
Rollup merge of #116253 - asquared31415:adt_const_params_feature, r=compiler-errors
Make `adt_const_params` feature suggestion consistent with other features and improve when it is emitted

Makes the suggestion to add `adt_const_params` formatted like every other feature gate (notably this makes it such that the playground recognizes it). Additionally improves the situations in which that help is emitted so that it's only emitted when the type would be valid or the type *could* be valid (using a slightly incorrect heuristic that favors suggesting the feature over not) instead of, for example, implying that adding the feature would allow the use of `String`.

Also adds the "the only supported types are integers, `bool` and `char`" note to the errors on fn and raw pointers.

r? `@compiler-errors`
2023-09-29 10:11:15 +02:00
Matthias Krüger e814f1e3c0
Rollup merge of #116201 - Jarcho:noop_fix, r=fee1-dead
Fix `noop_method_call` detection

This needs to be merged before #116198 can compile. The error occurs before the compiler is built so this needs to be a separate PR.
2023-09-29 10:11:12 +02:00
bors c1f86f0bc8 Auto merge of #116089 - estebank:issue-115992-2, r=compiler-errors
When suggesting `self.x` for `S { x }`, use `S { x: self.x }`

Fix #115992.

r? `@compiler-errors`

Follow up to #116086.
2023-09-29 05:45:18 +00:00
bors 60bb5192d1 Auto merge of #115843 - lcnr:bb-provisional-cache, r=compiler-errors
new solver: remove provisional cache

The provisional cache is a performance optimization if there are large, interleaving cycles. Such cycles generally do not exist. It is incredibly complex and unsound in all trait solvers which have one: the old solver, chalk, and the new solver ([link](https://github.com/rust-lang/rust/blob/master/tests/ui/traits/new-solver/cycles/inductive-not-on-stack.rs)).

Given the assumption that it is not perf-critical and also incredibly complex, remove it from the new solver, only checking whether a goal is on the stack. While writing this, I uncovered two additional soundness bugs, see the inline comments for them.

r? `@compiler-errors`
2023-09-29 02:09:40 +00:00
bors 958c2b87d8 Auto merge of #115821 - obeis:hir-analysis-migrate-diagnostics-5, r=compiler-errors
Migrate `rustc_hir_analysis` to session diagnostic [Part 5]

Finishing `coherence/builtin.rs` file
2023-09-29 00:24:57 +00:00