Commit Graph

6044 Commits

Author SHA1 Message Date
Matthias Krüger
b88d62e222
Rollup merge of #117615 - bjorn3:misc_changes, r=davidtwco
Couple of small changes

These are unrelated to each other, but they are each small enough that opening separate PR's doesn't make sense to me either.

* Remove a place where the parse driver query is stolen.
* Update an outdated doc comment
* Use correct crate name in `-Zprint-vtable-sizes` when using `#![crate_name = "..."]`.
2023-11-06 11:28:19 +01:00
Ralf Jung
b85c6835d0 warn when using an unstable feature with -Ctarget-feature 2023-11-06 09:44:00 +01:00
bors
152a4e90d1 Auto merge of #117585 - dnbln:feat/move-kw-span, r=cjgillot
Add the `Span` of the `move` keyword to the HIR.

This is required to implement a lint like the one described here: https://github.com/rust-lang/rust-clippy/issues/11721
2023-11-06 02:07:34 +00:00
bjorn3
ba82056a14 Use the actual computed crate name for -Zprint-vtable-sizes 2023-11-05 16:29:15 +00:00
bors
992943dbae Auto merge of #117537 - GKFX:offset-of-enum-feature, r=cjgillot
Feature gate enums in offset_of

As requested at https://github.com/rust-lang/rust/issues/106655#issuecomment-1790815262, put enums in offset_of behind their own feature gate.

`@rustbot` label F-offset_of
2023-11-05 13:44:59 +00:00
bors
8acf40bd54 Auto merge of #117469 - cjgillot:filecheck-mir, r=Mark-Simulacrum
Add FileCheck annotations to a few MIR opt tests

const_debuginfo did not specify which passes were running.
const_prop_miscompile is renamed and moved to const_prop directory.
while_storage was broken.
2023-11-05 07:54:12 +00:00
bors
da1e0d1d75 Auto merge of #116218 - tgross35:const-maybe-uninit-zeroed, r=dtolnay
Stabilize `const_maybe_uninit_zeroed` and `const_mem_zeroed`

Make `MaybeUninit::zeroed` and `mem::zeroed` const stable. Newly stable API:

```rust
// core::mem
pub const unsafe fn zeroed<T>() ->;

impl<T> MaybeUninit<T> {
    pub const fn zeroed() -> MaybeUninit<T>;
}
```

This relies on features based around `const_mut_refs`. Per `@RalfJung,` this should be OK since we do not leak any `&mut` to the user.

For this to be possible, intrinsics `assert_zero_valid` and `assert_mem_uninitialized_valid` were made const stable.

Tracking issue: #91850
Zulip discussion: https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/.60const_mut_refs.60.20dependents

r? libs-api
`@rustbot` label -T-libs +T-libs-api +A-const-eval
cc `@RalfJung`  `@oli-obk` `@rust-lang/wg-const-eval`
2023-11-05 05:56:21 +00:00
bors
f64d028196 Auto merge of #117589 - compiler-errors:global-vars-bug, r=jackh726
Make sure that predicates with unmentioned bound vars are still considered global in the old solver

In the old solver, we consider predicates with late-bound vars to not be "global":
9c8a2694fa/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1840-L1844)

The implementation of `has_late_bound_vars` was modified in #115834 so that we'd properly anonymize binders that had late-bound vars but didn't reference them. This fixed an ICE.

However, this also led to a behavioral change in https://github.com/rust-lang/rust/issues/117056#issuecomment-1775014545 for a couple of crates, which now consider `for<'a> GL33: Shader` (note the binder var that is *not* used in the predicate) to not be "global". This forces associated types to not be normalizable due to the old trait solver being dumb.

This PR distinguishes types which *reference* late-bound vars and binders which *have* late-bound vars. The latter is represented with the new type flag `TypeFlags::HAS_BINDER_VARS`, which is used when we only care about knowing whether binders have vars in their bound var list (even if they're not used, like for binder anonymization).

This should fix (after beta backport) the `luminance-gl` and `luminance-webgl` crates in #117056.

r? types
**(priority is kinda high on a review here given beta becomes stable on November 16.)**
2023-11-05 03:58:09 +00:00
bors
f5ca57e153 Auto merge of #117503 - kornelski:hint-try-reserved, r=workingjubilee
Hint optimizer about try-reserved capacity

This is #116568, but limited only to the less-common `try_reserve` functions to reduce bloat in debug binaries from debug info, while still addressing the main use-case #116570
2023-11-05 00:03:41 +00:00
León Orell Valerian Liehr
1dcdf83927
rustdoc: properly elide cross-crate host effect args 2023-11-05 00:56:54 +01:00
bors
4b85902b43 Auto merge of #117590 - matthiaskrgr:rollup-9cqh1q8, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #110340 (Deref docs: expand and remove "smart pointer" qualifier)
 - #116894 (Guarantee that `char` has the same size and alignment as `u32`)
 - #117534 (clarify that the str invariant is a safety, not validity, invariant)
 - #117562 (triagebot no-merges: exclude different case)
 - #117570 (fallback for `construct_generic_bound_failure`)
 - #117583 (Remove `'tcx` lifetime on `PlaceholderConst`)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-11-04 21:15:09 +00:00
Matthias Krüger
a47c137f3a
Rollup merge of #117570 - bvanjoi:fix-117547, r=cjgillot
fallback for `construct_generic_bound_failure`

Fixes #117547

This case regressed at #115882.

In this context, `generic_param_scope` is produced by `RPITVisitor` and not included by `hir_owner`. Therefore, I've added a fallback to address this.
2023-11-04 21:38:29 +01:00
Michael Goulet
32294fc0ed Make sure that predicates with unmentioned bound vars are still considered global in the old solver 2023-11-04 20:36:21 +00:00
Dinu Blanovschi
54ce0346c0 add fn visit_capture_by to MutVisitor and fix pprust-expr-roundtrip.rs 2023-11-04 21:04:54 +01:00
Trevor Gross
5e5f3341e3 Stabilize const_mem_zeroed
Make `core::mem::zeroed` const stable. Newly stable API:

    // core::mem
    pub const unsafe fn zeroed<T>() -> T;

This is stabilized with `const_maybe_uninit_zeroed` since it is a simple
wrapper.

In order to make this possible, intrinsics `assert_zero_valid` was made
const stable under `const_assert_type2`.
`assert_mem_uninitialized_valid` was also made const stable since it is
under the same gate.
2023-11-04 15:27:29 -04:00
bors
a42d94ebb8 Auto merge of #113343 - saethlin:looser-alignment, r=RalfJung
Update the alignment checks to match rust-lang/reference#1387

Previously, we had a special case to not check `Rvalue::AddressOf` in this pass because we weren't quite sure if pointers needed to be aligned in the Place passed to it: https://github.com/rust-lang/rust/pull/112026

Since https://github.com/rust-lang/reference/pull/1387 merged, this PR updates this pass to match. The behavior of the check is nearly unchanged, except we also avoid inserting a check for creating references. Most of the changes in this PR are cleanup and new tests.
2023-11-04 19:17:02 +00:00
Ben Kimock
f9bd7dabcf Check alignment of pointers only when read/written through 2023-11-04 13:01:32 -04:00
bohan
a4768fea35 fallback for construct_generic_bound_failure 2023-11-04 22:15:22 +08:00
Nadrieril
f0e8330879 Suggest to set lint level on whole match 2023-11-04 14:44:00 +01:00
Nadrieril
61d0fc7cf5 Warn when lint level is set on a match arm 2023-11-04 14:44:00 +01:00
Nadrieril
7b19fb88be Add tests 2023-11-04 14:44:00 +01:00
Ralf Jung
281d8cc4ae document ABI compatibility 2023-11-04 11:22:17 +01:00
Takayuki Maeda
9b9ea77641
Rollup merge of #117343 - Nadrieril:cleanup_check_match, r=davidtwco
Cleanup `rustc_mir_build/../check_match.rs`

The file had become pretty unwieldy, with a fair amount of duplication. As a bonus, I discovered that we weren't running some pattern checks in if-let chains.

I recommend looking commit-by-commit. The last commit is a whim, I think it makes more sense that way but I don't hold this opinion strongly.
2023-11-04 12:44:44 +09:00
Rémy Rakic
2dff90dc23 add test for issue 117146 2023-11-04 01:04:12 +00:00
Nicholas Nethercote
5c462a32bd Remove support for compiler plugins.
They've been deprecated for four years.

This commit includes the following changes.
- It eliminates the `rustc_plugin_impl` crate.
- It changes the language used for lints in
  `compiler/rustc_driver_impl/src/lib.rs` and
  `compiler/rustc_lint/src/context.rs`. External lints are now called
  "loaded" lints, rather than "plugins" to avoid confusion with the old
  plugins. This only has a tiny effect on the output of `-W help`.
- E0457 and E0498 are no longer used.
- E0463 is narrowed, now only relating to unfound crates, not plugins.
- The `plugin` feature was moved from "active" to "removed".
- It removes the entire plugins chapter from the unstable book.
- It removes quite a few tests, mostly all of those in
  `tests/ui-fulldeps/plugin/`.

Closes #29597.
2023-11-04 08:50:46 +11:00
Nadrieril
746197c08a Tweak spans for "adt defined here" note 2023-11-03 18:26:16 +01:00
bors
9c20ddd956 Auto merge of #117507 - nnethercote:rustc_span, r=Nilstrieb
`rustc_span` cleanups

Just some things I found while looking over this crate.

r? `@oli-obk`
2023-11-03 14:57:40 +00:00
George Bateman
7c09b99ebb
Feature gate enums in offset_of 2023-11-03 13:16:47 +00:00
Matthias Krüger
6cb627b681
Rollup merge of #117505 - estebank:issue-117501, r=TaKO8Ki
Fix incorrect trait bound restriction suggestion

Suggest

```
error[E0308]: mismatched types
  --> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
   |
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
   |                        -           - expected `B` because of return type
   |                        |
   |                        expected this type parameter
LL |     return a.bar();
   |            ^^^^^^^ expected type parameter `B`, found associated type
   |
   = note: expected type parameter `B`
             found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
   |
LL | pub fn foo<A: MyTrait<T = B>, B>(a: A) -> B {
   |                      +++++++
```

instead of

```
error[E0308]: mismatched types
  --> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
   |
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
   |                        -           - expected `B` because of return type
   |                        |
   |                        expected this type parameter
LL |     return a.bar();
   |            ^^^^^^^ expected type parameter `B`, found associated type
   |
   = note: expected type parameter `B`
             found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
   |
LL | pub fn foo<A: MyTrait + <T = B>, B>(a: A) -> B {
   |                      +++++++++
```

Fix #117501.
2023-11-03 12:44:50 +01:00
Ralf Jung
eaaa03faf7 default Aggregate ABI to Indirect, and make sure it's never used for unsized 2023-11-03 07:14:27 +01:00
Ralf Jung
405e4204d0 move ABI sanity check from LLVM codegen backend to ABI computation logic 2023-11-03 07:14:27 +01:00
bors
1d6f05fd37 Auto merge of #116439 - compiler-errors:on-unimplemented, r=davidtwco
Pretty print `Fn` traits in `rustc_on_unimplemented`

I don't think that users really ever should need to think about `Fn*` traits' tupled args for a simple trait error.

r? diagnostics
2023-11-03 06:08:03 +00:00
Gurinder Singh
4b3ece475d Emit explanatory note for move errors in packed struct derives
Derive expansions for packed structs cause move errors because
they prefer copying over borrowing since borrowing the fields of a
packed struct can result in unaligned access and therefore undefined
behaviour.

This underlying cause of the errors, however, is not apparent
to the user. We add a diagnostic note here to remedy that.
2023-11-03 07:32:10 +05:30
ltdk
8337e86b28 Add insta-stable std:#️⃣:{DefaultHasher, RandomState} exports 2023-11-02 20:35:20 -04:00
bors
2520ca8566 Auto merge of #117131 - compiler-errors:projection-oops, r=lcnr
Add all RPITITs when augmenting param-env with GAT bounds in `check_type_bounds`

When checking that associated type definitions actually satisfy their associated type bounds in `check_type_bounds`, we construct a "`normalize_param_env`" which adds a projection predicate that allows us to assume that we can project the GAT to the definition we're checking. For example, in:

```rust
type Foo {
  type Bar: Display = i32;
}
```

We would add `<Self as Foo>::Bar = i32` as a projection predicate when checking that `i32: Display` holds.

That `normalize_param_env` was, for some reason, only being used to normalize the predicate before it was registered. This is sketchy, because a nested obligation may require the GAT bound to hold, and also the projection cache is broken and doesn't differentiate projection cache keys that differ by param-envs 😿.

This `normalize_param_env` is also not sufficient when we have nested RPITITs and default trait methods, since we need to be able to assume we can normalize both the RPITIT and all of its child RPITITs to sufficiently prove all of its bounds. This is the cause of #117104, which only starts to fail for RPITITs that are nested 3 and above due to the projection-cache bug above.[^1]

## First fix

Use the `normalize_param_env` everywhere in `check_type_bounds`. This is reflected in a test I've constructed that fixes a GAT-only failure.

## Second fix

For RPITITs, install projection predicates for each RPITIT in the same function in `check_type_bounds`. This fixes #117104.

not sure who to request, so...
r? `@lcnr` hehe feel free to reassign :3

[^1]: The projection cache bug specifically occurs because we try normalizing the `assumed_wf_types` with the non-normalization param-env. This causes us to insert a projection cache entry that keeps the outermost RPITIT rigid, and it trivially satisifes all its own bounds. Super sketchy![^2]

[^2]: I haven't actually gone and fixed the projection cache bug because it's only marginally related, but I could, and it should no longer be triggered here.
2023-11-03 00:02:44 +00:00
bors
a2f5f9691b Auto merge of #117134 - lcnr:dropck_outlives-coroutine, r=compiler-errors
dropck_outlives check whether generator witness needs_drop

see https://rust-lang.zulipchat.com/#narrow/stream/326866-t-types.2Fnominated/topic/.23116242.3A.20Code.20no.20longer.20compiles.20after.20-Zdrop-tracking-mir.20.E2.80.A6/near/398311627 for an explanation.

Fixes #116242 (or well, the repro by `@jamuraa` in https://github.com/rust-lang/rust/issues/116242#issuecomment-1739802047). I did not add a regression test as it depends on other crates. We do have 1 test going from fail to pass, showing the intended behavior.

r? types
2023-11-02 22:03:38 +00:00
Michael Goulet
c83f642f12 Pretty print Fn traits in rustc_on_unimplemented 2023-11-02 20:57:05 +00:00
Michael Goulet
dd571e472a Add all RPITITs when augmenting param-env with GAT bounds in check_type_bounds 2023-11-02 20:47:10 +00:00
Michael Goulet
bb74d7e97d Use the normalizing param-env always in check_type_bounds 2023-11-02 20:47:05 +00:00
Esteban Küber
9e7345be1f Fix incorrect trait bound restriction suggestion
Suggest

```
error[E0308]: mismatched types
  --> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
   |
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
   |                        -           - expected `B` because of return type
   |                        |
   |                        expected this type parameter
LL |     return a.bar();
   |            ^^^^^^^ expected type parameter `B`, found associated type
   |
   = note: expected type parameter `B`
             found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
   |
LL | pub fn foo<A: MyTrait<T = B>, B>(a: A) -> B {
   |                      +++++++
```

instead of

```
error[E0308]: mismatched types
  --> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
   |
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
   |                        -           - expected `B` because of return type
   |                        |
   |                        expected this type parameter
LL |     return a.bar();
   |            ^^^^^^^ expected type parameter `B`, found associated type
   |
   = note: expected type parameter `B`
             found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
   |
LL | pub fn foo<A: MyTrait + <T = B>, B>(a: A) -> B {
   |                      +++++++++
```

Fix #117501.
2023-11-02 18:04:41 +00:00
bors
b20f40dba9 Auto merge of #117521 - GuillaumeGomez:impl-on-foreign-order, r=notriddle
Fix order of implementations in the "implementations on foreign types" section

Fixes #117391.

We forgot to run the `sort_by_cached_key` on this section. This fixes it.

r? `@notriddle`
2023-11-02 17:54:29 +00:00
lcnr
dda5e32ab0 review + add tests 2023-11-02 18:16:37 +01:00
Guillaume Gomez
2e4a36bb53 Add GUI test to ensure that implementations on foreign types are in the expected order 2023-11-02 18:02:14 +01:00
lcnr
57253552de dropck_outlives check generator witness needs_drop 2023-11-02 17:20:13 +01:00
Matthias Krüger
666cad9a5f add test for #113375
Fixes #113375
2023-11-02 16:16:56 +01:00
Matthias Krüger
384f7382ba add test for #113381
Fixes #113381

r? fee1-dead
2023-11-02 15:59:54 +01:00
bors
c5afe0a61e Auto merge of #117513 - matthiaskrgr:rollup-jvl6y84, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #117394 (use global cache when computing proof trees)
 - #117495 (Clarify `Unsize` documentation)
 - #117509 (Remove support for alias `-Z symbol-mangling-version`)
 - #117512 (Expand mem::offset_of! docs)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-11-02 14:46:23 +00:00
Matthias Krüger
67b51879e3
Rollup merge of #117509 - Zalathar:zsymbol, r=petrochenkov
Remove support for alias `-Z symbol-mangling-version`

(This is very similar to the removal of `-Z instrument-coverage` in #117111.)

`-C symbol-mangling-version` was stabilized back in rustc 1.59.0 (2022-02-24) via #90128, with the old unstable flag kept around (with a warning) as an alias to ease migration.
2023-11-02 15:31:21 +01:00
Matthias Krüger
9575625835
Rollup merge of #117495 - compiler-errors:unsize-docs, r=lcnr
Clarify `Unsize` documentation

The documentation erroneously says that:

```rust
/// - Types implementing a trait `Trait` also implement `Unsize<dyn Trait>`.
/// - Structs `Foo<..., T, ...>` implement `Unsize<Foo<..., U, ...>>` if all of these conditions
///   are met:
///   - `T: Unsize<U>`.
///   - Only the last field of `Foo` has a type involving `T`.
///   - `Bar<T>: Unsize<Bar<U>>`, where `Bar<T>` stands for the actual type of that last field.
```

Specifically, `T: Unsize<U>` is not required to hold -- only the final field must implement `FinalField<T>: Unsize<FinalField<U>>`. This can be demonstrated by the test I added.

---

Second commit fleshes out the documentation a lot more.
2023-11-02 15:31:21 +01:00
bors
b800c30352 Auto merge of #117466 - compiler-errors:alias-bound, r=aliemjay
Don't check for alias bounds in liveness when aliases have escaping bound vars

I actually have no idea how we *should* be treating aliases with escaping bound vars here... but the simplest behavior is just doing what we used to do before.

r? aliemjay

Fixes #117455
2023-11-02 12:47:14 +00:00
Michael Goulet
4d5d763e05 Don't check for alias bounds in liveness when aliases have escaping bound vars 2023-11-02 10:25:57 +00:00
bors
62270fb4d6 Auto merge of #117204 - nnethercote:rustc_ast_passes, r=compiler-errors
Minor improvements to `rustc_ast_passes`

Some improvements I found while looking at this code.

r? `@compiler-errors`
2023-11-02 10:08:53 +00:00
Nicholas Nethercote
f405ce86c2 Minimize pub usage in source_map.rs.
Most notably, this commit changes the `pub use crate::*;` in that file
to `use crate::*;`. This requires a lot of `use` items in other crates
to be adjusted, because everything defined within `rustc_span::*` was
also available via `rustc_span::source_map::*`, which is bizarre.

The commit also removes `SourceMap::span_to_relative_line_string`, which
is unused.
2023-11-02 19:35:00 +11:00
Zalathar
76103a8f6e Remove support for alias -Z symbol-mangling-version 2023-11-02 18:41:33 +11:00
Zalathar
a9e1e43b56 Add UI tests for values accepted by -C symbol-mangling-version 2023-11-02 18:20:42 +11:00
Nadrieril
c19856929d Always do all the pattern checks 2023-11-02 03:19:19 +01:00
Nadrieril
b60f08a66d Add regression test for pattern checks 2023-11-02 03:19:19 +01:00
Nadrieril
d95f6a9532 Tweak diagnostic for consistency 2023-11-02 03:19:19 +01:00
Kornel
029fbd67ef Hint optimizer about reserved capacity 2023-11-02 00:52:06 +00:00
bors
722b3eeb72 Auto merge of #117498 - matthiaskrgr:rollup-z7mg4ck, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #117298 (Recover from missing param list in function definitions)
 - #117373 (Avoid the path trimming ICE lint in error reporting)
 - #117441 (Do not assert in op_to_const.)
 - #117488 (Update minifier-rs version to 0.3.0)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-11-01 22:37:24 +00:00
Matthias Krüger
4e437be044
Rollup merge of #117441 - cjgillot:diag-noassert, r=oli-obk,RalfJung
Do not assert in op_to_const.

`op_to_const` is used in `try_destructure_mir_constant_for_diagnostics`, which may encounter invalid constants created by optimizations and debugging.

r? ``@oli-obk``

Fixes https://github.com/rust-lang/rust/issues/117368
2023-11-01 21:40:06 +01:00
Matthias Krüger
2b2360abb1
Rollup merge of #117298 - clubby789:fn-missing-params, r=petrochenkov
Recover from missing param list in function definitions

Addresses the other issue mentioned in #108109
2023-11-01 21:40:05 +01:00
bors
75b064d269 Auto merge of #117029 - rmehri01:mir_opt_filecheck_inline_tests, r=cjgillot
Add FileCheck annotations to MIR-opt inlining tests

Part of #116971, adds FileCheck annotations to MIR-opt tests in `tests/mir-opt/inline`.

I left out a few (such as `inline_cycle`) where it mentioned that the particular outcome of inlining isn't important, just that the inliner doesn't get stuck in an infinite loop.

r? cjgillot
2023-11-01 20:37:38 +00:00
Michael Goulet
6af30ec720 Remove a false statement from Unsize docs, add a test 2023-11-01 20:16:11 +00:00
bors
b0a07595b5 Auto merge of #117289 - estebank:issue-72298, r=cjgillot
Account for `ref` and `mut` in the wrong place for pattern ident renaming

If the user writes `S { ref field: name }` instead of `S { field: ref name }`, we suggest the correct code.

Fix #72298.
2023-11-01 18:39:01 +00:00
Camille GILLOT
0f8f77fcc2 Rebase fallout. 2023-11-01 16:55:18 +00:00
Camille GILLOT
a2e151ca4b Make ui into mir-opt test. 2023-11-01 16:49:18 +00:00
Camille GILLOT
c2f49e9edf Do not assert in op_to_const. 2023-11-01 16:49:18 +00:00
clubby789
904aceec7d Give a better diagnostic for missing parens in Fn* bounds 2023-11-01 15:33:46 +00:00
Ryan Mehri
5f75326d74 fix spans for inline_couroutine panic-abort 2023-11-01 07:58:19 -07:00
clubby789
ca1bcb6466 Recover from missing param list in function definitions 2023-11-01 14:48:20 +00:00
bors
146dafa262 Auto merge of #114208 - GKFX:offset_of_enum, r=wesleywiser
Support enum variants in offset_of!

This MR implements support for navigating through enum variants in `offset_of!`, placing the enum variant name in the second argument to `offset_of!`. The RFC placed it in the first argument, but I think it interacts better with nested field access in the second, as you can then write things like

```rust
offset_of!(Type, field.Variant.field)
```

Alternatively, a syntactic distinction could be made between variants and fields (e.g. `field::Variant.field`) but I'm not convinced this would be helpful.

[RFC 3308 # Enum Support](https://rust-lang.github.io/rfcs/3308-offset_of.html#enum-support-offset_ofsomeenumstructvariant-field_on_variant)
Tracking Issue #106655.
2023-11-01 14:17:56 +00:00
Matthias Krüger
260e07b0cb
Rollup merge of #115626 - clarfonthey:unchecked-math, r=thomcc
Clean up unchecked_math, separate out unchecked_shifts

Tracking issue: #85122

Changes:

1. Remove `const_inherent_unchecked_arith` flag and make const-stability flags the same as the method feature flags. Given the number of other unsafe const fns already stabilised, it makes sense to just stabilise these in const context when they're stabilised.
2. Move `unchecked_shl` and `unchecked_shr` into a separate `unchecked_shifts` flag, since the semantics for them are unclear and they'll likely be stabilised separately as a result.
3. Add an `unchecked_neg` method exclusively to signed integers, under the `unchecked_neg` flag. This is because it's a new API and probably needs some time to marinate before it's stabilised, and while it *would* make sense to have a similar version for unsigned integers since `checked_neg` also exists for those there is absolutely no case where that would be a good idea, IMQHO.

The longer-term goal here is to prepare the `unchecked_math` methods for an FCP and stabilisation since they've existed for a while, their semantics are clear, and people seem in favour of stabilising them.
2023-11-01 11:29:41 +01:00
bors
7fc6365570 Auto merge of #116692 - Nadrieril:half-open-ranges, r=cjgillot
Match usize/isize exhaustively with half-open ranges

The long-awaited finale to the saga of [exhaustiveness checking for integers](https://github.com/rust-lang/rust/pull/50912)!

```rust
match 0usize {
    0.. => {} // exhaustive!
}
match 0usize {
    0..usize::MAX => {} // helpful error message!
}
```

Features:
- Half-open ranges behave as expected for `usize`/`isize`;
- Trying to use `0..usize::MAX` will tell you that `usize::MAX..` is missing and explain why. No more unhelpful "`_` is missing";
- Everything else stays the same.

This should unblock https://github.com/rust-lang/rust/issues/37854.

Review-wise:
- I recommend looking commit-by-commit;
- This regresses perf because of the added complexity in `IntRange`; hopefully not too much;
- I measured each `#[inline]`, they all help a bit with the perf regression (tho I don't get why);
- I did not touch MIR building; I expect there's an easy PR there that would skip unnecessary comparisons when the range is half-open.
2023-11-01 03:17:19 +00:00
bors
98f5ebbe2e Auto merge of #113970 - cjgillot:assume-all-the-things, r=nikic
Replace switch to unreachable by assume statements

`UnreachablePropagation` currently keeps some switch terminators alive in order to ensure codegen can infer the inequalities on the discriminants.

This PR proposes to encode those inequalities as `Assume` statements.

This allows to simplify MIR further by removing some useless terminators.
2023-11-01 01:10:31 +00:00
George Bateman
e742f809f6
Update based on wesleywiser review 2023-10-31 23:41:40 +00:00
George Bateman
9d6ce61376
Update MIR tests for offset_of 2023-10-31 23:26:02 +00:00
George Bateman
d995bd61e7
Enums in offset_of: update based on est31, scottmcm & llogiq review 2023-10-31 23:26:02 +00:00
George Bateman
e936416a8d
Support enum variants in offset_of! 2023-10-31 23:25:54 +00:00
bors
09ac6e4b6d Auto merge of #117459 - matthiaskrgr:rollup-t3osb3c, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #113241 (rustdoc: Document lack of object safety on affected traits)
 - #117388 (Turn const_caller_location from a query to a hook)
 - #117417 (Add a stable MIR visitor)
 - #117439 (prepopulate opaque ty storage before using it)
 - #117451 (Add support for pre-unix-epoch file dates on Apple platforms (#108277))

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-31 23:08:56 +00:00
Camille GILLOT
ac4d0965bb FileCheck const_prop_miscompile. 2023-10-31 22:56:02 +00:00
Camille GILLOT
e65ec7d8f1 FileCheck const_debuginfo. 2023-10-31 22:55:59 +00:00
Camille GILLOT
3d454707ab FileCheck while_storage. 2023-10-31 22:55:14 +00:00
Ryan Mehri
2fcb4d92b0 change inline_retag to after.mir 2023-10-31 11:58:20 -07:00
Matthias Krüger
290daf9318
Rollup merge of #117417 - celinval:smir-visitor, r=oli-obk
Add a stable MIR visitor

This change also adds a few utility functions as well and extend most `mir` and `ty` ADTs to implement `PartialEq` and `Eq`.

Fixes https://github.com/rust-lang/project-stable-mir/issues/32

r? `@oli-obk`
2023-10-31 19:03:21 +01:00
Matthias Krüger
51b275bff8
Rollup merge of #113241 - poliorcetics:85138-doc-object-safety, r=GuillaumeGomez
rustdoc: Document lack of object safety on affected traits

Closes #85138

I saw the issue didn't have any recent activity, if there is another MR for it I missed it.

I want the issue to move forward so here is my proposition.

It takes some space just before the "Implementors" section and only if the trait is **not** object
safe since it is the only case where special care must be taken in some cases and this has the
benefit of avoiding generation of HTML in (I hope) the common case.
2023-10-31 19:03:20 +01:00
bors
50be229640 Auto merge of #117450 - oli-obk:rustdoc_verify, r=estebank
Accept less invalid Rust in rustdoc

pulled out of https://github.com/rust-lang/rust/pull/117213 where this change was already approved

This only affects rustdoc, and has up to [20% perf regressions in rustdoc](https://github.com/rust-lang/rust/pull/117213#issuecomment-1785776288). These are unavoidable, as we are simply doing more checks now, but it's part of the longer term plan of making rustdoc more resistant to ICEs by only accepting valid Rust code.
2023-10-31 17:07:35 +00:00
Oli Scherer
4512f211ae Accept less invalid Rust in rustdoc 2023-10-31 13:58:03 +00:00
bors
045f158d7b Auto merge of #117444 - matthiaskrgr:rollup-43s0spc, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #116267 (Some codegen cleanups around SIMD checks)
 - #116712 (When encountering unclosed delimiters during lexing, check for diff markers)
 - #117416 (Also consider TAIT to be uncomputable if the MIR body is tainted)
 - #117421 (coverage: Replace impossible `coverage::Error` with assertions)
 - #117438 (Do not ICE on constant evaluation failure in GVN.)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-31 12:55:06 +00:00
Matthias Krüger
f623530742
Rollup merge of #117438 - cjgillot:deterministic-error, r=oli-obk
Do not ICE on constant evaluation failure in GVN.

Fixes https://github.com/rust-lang/rust/issues/117362
2023-10-31 12:55:10 +01:00
Matthias Krüger
8daa317a4b
Rollup merge of #117416 - compiler-errors:tait-in-bad-body, r=oli-obk
Also consider TAIT to be uncomputable if the MIR body is tainted

Not totally sure if this is the best solution. We could, alternatively, look at the hir typeck results and try to take a type from there instead of just falling back to type error, inferring `u8` instead of `{type error}`. Not certain it really matters, though.

Happy to iterate on this.

Fixes #117413

r? ``@oli-obk`` cc ``@Nadrieril``
2023-10-31 12:55:09 +01:00
Matthias Krüger
7035c3d718
Rollup merge of #116712 - estebank:issue-116252, r=petrochenkov
When encountering unclosed delimiters during lexing, check for diff markers

Fix #116252.
2023-10-31 12:55:09 +01:00
Camille GILLOT
ae2e21114b FileCheck uninhabited_enum_branching. 2023-10-31 11:44:23 +00:00
Camille GILLOT
cb918904fe Only emit != assumptions if the otherwise target is reachable. 2023-10-31 11:44:23 +00:00
Camille GILLOT
096196d5b0 Refactor UninhabitedEnumBranching to mark targets unreachable. 2023-10-31 11:44:23 +00:00
Camille GILLOT
0b13e636f5 Simplify assume of a constant. 2023-10-31 11:44:23 +00:00
Camille GILLOT
c748ac1f11 Replace SwitchInt to unreachable by an assumption. 2023-10-31 11:44:23 +00:00
Camille GILLOT
ed27cb0f49 Reorder passes. 2023-10-31 11:44:23 +00:00
Camille GILLOT
5b7cc9d704 Do not ICE on constant evaluation failure in GVN. 2023-10-31 10:44:28 +00:00
bors
22b27120b9 Auto merge of #117377 - dtolnay:deprecatedsince, r=cjgillot
Store #[deprecated] attribute's `since` value in parsed form

This PR implements the first followup bullet listed in https://github.com/rust-lang/rust/pull/117148#issue-1960240108.

We centralize error handling to the attribute parsing code in `compiler/rustc_attr/src/builtin.rs`, and thereby remove some awkward error codepaths from later phases of compilation that had to make sense of these #\[deprecated\] attributes, namely `compiler/rustc_passes/src/stability.rs` and `compiler/rustc_middle/src/middle/stability.rs`.
2023-10-31 10:42:24 +00:00
David Tolnay
c52367276d
Preserve deprecation attribute even if 'since' version is missing 2023-10-30 15:48:46 -07:00
bors
a395214a3a Auto merge of #116405 - estebank:issue-103155, r=davidtwco
Detect object safety errors when assoc type is missing

When an associated type with GATs isn't specified in a `dyn Trait`, emit an object safety error instead of only complaining about the missing associated type, as it will lead the user down a path of three different errors before letting them know that what they were trying to do is impossible to begin with.

Fix #103155.
2023-10-30 22:47:48 +00:00
Esteban Küber
b8a8ba9c91 Sort errors 2023-10-30 22:19:17 +00:00
Esteban Küber
8c5577283c Add test 2023-10-30 22:12:07 +00:00
Esteban Küber
17a6ae2df3 Detect object safety errors when assoc type is missing
When an associated type with GATs isn't specified in a `dyn Trait`, emit
an object safety error instead of only complaining about the missing
associated type, as it will lead the user down a path of three different
errors before letting them know that what they were trying to do is
impossible to begin with.

Fix #103155.
2023-10-30 22:12:07 +00:00
Nicholas Nethercote
5b391b01ce Test the multispan case in tests.ui/bounds-lifetime.rs. 2023-10-31 08:01:02 +11:00
bors
31bc7e2c47 Auto merge of #117415 - matthiaskrgr:rollup-jr2p1t2, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #116862 (Detect when trait is implemented for type and suggest importing it)
 - #117389 (Some diagnostics improvements of `gen` blocks)
 - #117396 (Don't treat closures/coroutine types as part of the public API)
 - #117398 (Correctly handle nested or-patterns in exhaustiveness)
 - #117403 (Poison check_well_formed if method receivers are invalid to prevent typeck from running on it)
 - #117411 (Improve some diagnostics around `?Trait` bounds)
 - #117414 (Don't normalize to an un-revealed opaque when we hit the recursion limit)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-30 20:50:14 +00:00
Michael Goulet
48491c182b Also consider TAIT to be uncomputable if the MIR body is tainted 2023-10-30 20:16:22 +00:00
Celina G. Val
af7472ecbc Add a stable MIR visitor
Add a few utility functions as well and extend most `mir` and `ty`
ADTs to implement `PartialEq` and `Eq`.
2023-10-30 13:11:14 -07:00
Matthias Krüger
c5aec96440
Rollup merge of #117414 - compiler-errors:tait-forevert, r=oli-obk
Don't normalize to an un-revealed opaque when we hit the recursion limit

Currently, we will normalize `Opaque := Option<&Opaque>` to something like `Option<&Option<&Option<&...Opaque>>>`, hitting a limit and bottoming out in an unnormalized opaque after the recursion limit gets hit.

Unfortunately, during `layout_of`, we'll simply recurse and try again if the type normalizes to something different than the type:
e6e931dda5/compiler/rustc_ty_utils/src/layout.rs (L58-L60)

That means then we'll try to normalize `Option<&Option<&Option<&...Opaque>>>` again, substituting `Opaque` into itself even deeper. Eventually this will get to the point that we're just stack-overflowing on a really deep type before even hitting an opaque again.

To fix this, we just bottom out into `ty::Error` instead of the unrevealed opaque type.

Fixes #117412

r? `@oli-obk`
2023-10-30 21:03:40 +01:00
Matthias Krüger
3e95c6ab03
Rollup merge of #117411 - oli-obk:query_merge_immobile_game, r=compiler-errors,Nilstrieb
Improve some diagnostics around `?Trait` bounds

* uses better spans
* clarifies a message that was only talking about generic params, but applies to `dyn ?Trait` and `impl ?Trait` as well
2023-10-30 21:03:39 +01:00
Matthias Krüger
24c6b6c803
Rollup merge of #117403 - oli-obk:the_gift_that_keeps_on_giving_116849, r=compiler-errors
Poison check_well_formed if method receivers are invalid to prevent typeck from running on it

fixes #117379

Though if some code invokes typeck without having first invoked `check_well_formed` then we'll encounter this ICE again. This can happen in const and const fn bodies if they are evaluated due to other `check_well_formed` checks or similar
2023-10-30 21:03:39 +01:00
Matthias Krüger
342483ccc6
Rollup merge of #117398 - Nadrieril:fix-117378, r=compiler-errors
Correctly handle nested or-patterns in exhaustiveness

I had assumed nested or-patterns were flattened, and they mostly are but not always.

Fixes https://github.com/rust-lang/rust/issues/117378
2023-10-30 21:03:38 +01:00
Matthias Krüger
e648f479d8
Rollup merge of #117396 - oli-obk:privacy_visitor_types, r=compiler-errors
Don't treat closures/coroutine types as part of the public API

Fixes a regression from https://github.com/rust-lang/rust/pull/117076

r? `@compiler-errors`
2023-10-30 21:03:38 +01:00
Matthias Krüger
86259e79e4
Rollup merge of #117389 - oli-obk:gen_fn, r=compiler-errors
Some diagnostics improvements of `gen` blocks

These are leftovers from https://github.com/rust-lang/rust/pull/116447
2023-10-30 21:03:37 +01:00
Michael Goulet
c91f60e22f Don't super-fold types when we hit the recursion limit 2023-10-30 19:24:15 +00:00
Oli Scherer
455cf5a4f6 Improve some diagnostics around ?Trait bounds 2023-10-30 17:47:07 +00:00
Esteban Küber
162443b32e Detect when trait is implemented for type and suggest importing it
Fix #57457.
2023-10-30 17:00:44 +00:00
Guillaume Gomez
9e4ab9f111
Rollup merge of #117395 - gurry:117380-wrong-parent-sugg, r=Nilstrieb
Fix missing leading space in suggestion

For a local pattern with no space between `let` and `(` e.g.:
```rust
  let(_a) = 3;
```
we were previously suggesting this illegal code:
```rust
  let_a = 3;
```
After this change the suggestion will instead be:
```rust
  let _a = 3;
```
Fixes #117380
2023-10-30 17:33:19 +01:00
Guillaume Gomez
02d32d2bc2
Rollup merge of #117390 - chenyukang:yukang-fix-117284-unused-macro, r=estebank
Fix unused variables lint issue for args in macro

Fixes #117284
r? ````@estebank````
2023-10-30 17:33:18 +01:00
Guillaume Gomez
784f04b367
Rollup merge of #117370 - nicholasbishop:bishop-better-c-variadic-errors, r=oli-obk
C-variadic error improvements

A couple improvements for c-variadic errors:

1. Fix the bad-c-variadic error being emitted multiple times. If a function incorrectly contains multiple `...` args, and is also not foreign or `unsafe extern "C"`, only emit the latter error once rather than once per `...`.

2. Explicitly reject `const` C-variadic functions. Trying to use C-variadics in a const function would previously fail with an error like "destructor of `VaListImpl<'_>` cannot be evaluated at compile-time". Add an explicit check for const C-variadics to provide a clearer error: "functions cannot be both `const` and C-variadic". This also addresses one of the concerns in https://github.com/rust-lang/rust/issues/44930: "Ensure that even when this gets stabilized for regular functions, it is still rejected on const fn."
2023-10-30 17:33:17 +01:00
Guillaume Gomez
95de91b5ce
Rollup merge of #117132 - estebank:issue-80194, r=petrochenkov
On object safety error, mention new enum as alternative

When we encounter a `dyn Trait` that isn't object safe, look for its implementors. If there's one, mention using it directly If there are less than 9, mention the possibility of creating a new enum and using that instead.

Fix #80194.
2023-10-30 17:33:15 +01:00
Guillaume Gomez
b9dce53d4a
Rollup merge of #112463 - fmease:rustdoc-elide-x-crate-def-gen-args, r=GuillaumeGomez
rustdoc: elide cross-crate default generic arguments

Elide cross-crate generic arguments if they coincide with their default.
TL;DR: Most notably, no more `Box<…, Global>` in `std`'s docs, just `Box<…>` from now on.
Fixes #80379.

Also helps with #44306. Follow-up to #103885, #107637.

r? ``@ghost``
2023-10-30 17:33:14 +01:00
Oli Scherer
224ddf8fd9 Only run panic tests on targets that can unwind 2023-10-30 16:32:53 +00:00
Oli Scherer
ff3a818554 Poison check_well_formed if method receivers are invalid to prevent typeck from running on it 2023-10-30 16:11:52 +00:00
León Orell Valerian Liehr
58a80c85b9
rustdoc: elide cross-crate default generic arguments 2023-10-30 16:44:52 +01:00
Nicholas Bishop
f91b5ceaf2 Explicitly reject const C-variadic functions
Trying to use C-variadics in a const function would previously fail with
an error like "destructor of `VaListImpl<'_>` cannot be evaluated at
compile-time".

Add an explicit check for const C-variadics to provide a clearer error:
"functions cannot be both `const` and C-variadic".
2023-10-30 10:38:25 -04:00
Nadrieril
d5e836cf0c Correctly handle nested or-patterns in column-wise analyses 2023-10-30 15:31:00 +01:00
Nicholas Bishop
8508e65895 Fix bad-c-variadic error being emitted multiple times
If a function incorrectly contains multiple `...` args, and is also not
foreign or `unsafe extern "C"`, only emit the latter error once.
2023-10-30 10:29:11 -04:00
Oli Scherer
8d03e1394f Don't treat closures/coroutines as part of the public API 2023-10-30 13:46:44 +00:00
Oli Scherer
972ee01b69 Add regression test 2023-10-30 13:38:54 +00:00
yukang
82f34fdd23 Fix #117284, Fix unused variables lint issue for args in macro 2023-10-30 21:35:18 +08:00
Gurinder Singh
a2486dba3b Fix missing leading space in suggestion
For a local pattern with no space between `let` and `(` e.g.:

  let(_a) = 3;

we were previously suggesting this illegal code:

  let_a =3;

After this change the suggestion will instead be:

  let _a =3;

(Note the space after `let`)
2023-10-30 19:04:55 +05:30
Oli Scherer
bc926f7c33 Add a custom panic message for resuming gen blocks after they panicked 2023-10-30 10:23:57 +00:00
Oli Scherer
745c600617 Talk about gen fn in diagnostics about gen fn 2023-10-30 10:13:12 +00:00
León Orell Valerian Liehr
4f4b38c40f
Rollup merge of #117382 - gurry:114529-ice-const-eval, r=oli-obk
Fail typeck for illegal break-with-value

This is fixes the issue wherein typeck was succeeding for break-with-value exprs at illegal locations such as inside `while`, `while let` and `for` loops which eventually caused an ICE during MIR interpretation for const eval.

Now we fail typeck for such code which prevents faulty MIR from being generated and interpreted, thus fixing the ICE.

Fixes #114529
2023-10-30 10:48:20 +01:00
León Orell Valerian Liehr
12eb539bf2
Rollup merge of #117371 - compiler-errors:unique-params, r=oli-obk
Ignore RPIT duplicated lifetimes in `opaque_types_defined_by`

An RPIT's or TAIT's own generics are kinda useless -- so just ignore them. For TAITs, they will always be empty, and for RPITs, they're always duplicated lifetimes.

Fixes #115013.
2023-10-30 10:48:20 +01:00
León Orell Valerian Liehr
5eb76fac7c
Rollup merge of #117205 - weiznich:multiple_notes_for_on_unimplemented, r=compiler-errors
Allows `#[diagnostic::on_unimplemented]` attributes to have multiple

notes

This commit extends the `#[diagnostic::on_unimplemented]` (and `#[rustc_on_unimplemented]`) attributes to allow multiple `note` options. This enables emitting multiple notes for custom error messages. For now I've opted to not change any of the existing usages of `#[rustc_on_unimplemented]` and just updated the relevant compile tests.

r? `@compiler-errors`

I'm happy to adjust any of the existing changed location to emit the old error message if that's desired.
2023-10-30 10:48:18 +01:00
León Orell Valerian Liehr
2915707622
Rollup merge of #117147 - DaniPopes:pphir-fn-variadic, r=compiler-errors
Print variadic argument pattern in HIR pretty printer

Variadic argument name/pattern was ignored during HIR pretty printing.
Could not figure out why it only works on normal functions (`va2`) and not in foreign ones (`va1`).
2023-10-30 10:48:17 +01:00
Gurinder Singh
0c8bdd0bf3 Fail typeck for illegal break-with-value
This is fixes the issue wherein typeck was succeeding for break-with-value
at illegal locations such as inside `while`, `while let` and `for` loops which
eventually caused an ICE during MIR interpetation for const eval.

Now we fail typeck for such code which prevents faulty MIR from being generated
and interpreted, thus fixing the ICE.
2023-10-30 13:03:40 +05:30
David Tolnay
2fe7d17bd9
Store version of deprecated attribute in structured form 2023-10-29 22:42:32 -07:00
David Tolnay
5c7cf83739
Fill in syntactically valid deprecation version in tests 2023-10-29 22:33:51 -07:00
Esteban Küber
50ca5ef07f When encountering unclosed delimiters during parsing, check for diff markers
Fix #116252.
2023-10-30 00:56:46 +00:00
Esteban Küber
b589f47441 Account for ref and mut in the wrong place for pattern ident renaming
If the user writes `S { ref field: name }` instead of
`S { field: ref name }`, we suggest the correct code.

Fix #72298.
2023-10-30 00:15:49 +00:00
Esteban Küber
8c04999226 On object safety error, mention new enum as alternative
When we encounter a `dyn Trait` that isn't object safe, look for its
implementors. If there's one, mention using it directly If there are
less than 9, mention the possibility of creating a new enum and using
that instead.

Account for object unsafe `impl Trait on dyn Trait {}`.  Make a
distinction between public and sealed traits.

Fix #80194.
2023-10-29 23:55:46 +00:00
Alexis (Poliorcetics) Bourget
a119158eb3 tests: object-safety section in traits 2023-10-29 22:57:45 +01:00
Michael Goulet
c5613258bb Ignore RPIT duplicated lifetimes in opaque_types_defined_by 2023-10-29 17:45:05 -04:00
bors
ec2b311914 Auto merge of #116733 - compiler-errors:alias-liveness-but-this-time-sound, r=aliemjay
Consider alias bounds when computing liveness in NLL (but this time sound hopefully)

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

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

Fixes #116794 as well

---

(mostly copied from #116040 and reworked slightly)

# Background

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

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

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

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

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

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

# The Fix

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

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

## Limitation: Multiple choices

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

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

## Limitation: Opaque hidden types

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

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

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

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

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

## Read more

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

[^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
2023-10-29 18:42:02 +00:00
bors
88ae8c9385 Auto merge of #116889 - MU001999:master, r=petrochenkov
Eat close paren if capture_cfg to avoid unbalanced parens

Fixes #116781
2023-10-29 16:46:47 +00:00
bors
83c9732e0c Auto merge of #116270 - cjgillot:gvn-aggregate, r=oli-obk,RalfJung
See through aggregates in GVN

This PR is extracted from https://github.com/rust-lang/rust/pull/111344

The first 2 commit are cleanups to avoid repeated work. I propose to stop removing useless assignments as part of this pass, and let a later `SimplifyLocals` do it. This makes tests easier to read (among others).

The next 3 commits add a constant folding mechanism to the GVN pass, presented in https://github.com/rust-lang/rust/pull/116012. ~This pass is designed to only use global allocations, to avoid any risk of accidental modification of the stored state.~

The following commits implement opportunistic simplifications, in particular:
- projections of aggregates: `MyStruct { x: a }.x` gets replaced by `a`, works with enums too;
- projections of arrays: `[a, b][0]` becomes `a`;
- projections of repeat expressions: `[a; N][x]` becomes `a`;
- transform arrays of equal operands into a repeat rvalue.

Fixes https://github.com/rust-lang/miri/issues/3090

r? `@oli-obk`
2023-10-29 14:50:53 +00:00
Guillaume Gomez
2b98ecd345
Rollup merge of #117082 - fortanix:raoul/fix_closure_inherit_target_feature_sgx, r=Mark-Simulacrum
Fix closure-inherit-target-feature test for SGX platform

PR #116078 adds the `closure-inherit-target-feature.rs` test that checks the generated assembly code for closures. These checks explicitly check the presence of `ret` instructions. This is incompatible with the SGX target as it explicitly rewrites all `ret` instructions to mitigate LVI vulnerabilities of certain processors. This PR simply ignores these tests for the SGX platform.

cc: ```@jethrogb```
2023-10-29 12:35:00 +01:00
Jubilee Young
e9a009fd1a Remove asmjs from tests 2023-10-28 23:11:03 -07:00
bors
2cad938a81 Auto merge of #116447 - oli-obk:gen_fn, r=compiler-errors
Implement `gen` blocks in the 2024 edition

Coroutines tracking issue https://github.com/rust-lang/rust/issues/43122
`gen` block tracking issue https://github.com/rust-lang/rust/issues/117078

This PR implements `gen` blocks that implement `Iterator`. Most of the logic with `async` blocks is shared, and thus I renamed various types that were referring to `async` specifically.

An example usage of `gen` blocks is

```rust
fn foo() -> impl Iterator<Item = i32> {
    gen {
        yield 42;
        for i in 5..18 {
            if i.is_even() { continue }
            yield i * 2;
        }
    }
}
```

The limitations (to be resolved) of the implementation are listed in the tracking issue
2023-10-29 00:03:52 +00:00
bors
7cc36de72d Auto merge of #116240 - dtolnay:constdiscriminant, r=thomcc
Const stabilize mem::discriminant

Tracking issue: #69821.

This PR is a rebase of https://github.com/rust-lang/rust/pull/103893 to resolve conflicts in library/core/src/lib.rs (against #102470 and #110393).
2023-10-28 19:38:15 +00:00
bors
6b78377245 Auto merge of #117123 - Zalathar:bad-counter-ids, r=petrochenkov
coverage: Consistently remove unused counter IDs from expressions/mappings

If some coverage counters were removed by MIR optimizations, we need to take care not to refer to those counter IDs in coverage mappings, and instead replace them with a constant zero value. If we don't, `llvm-cov` might see a too-large counter ID and silently discard the entire function from its coverage reports.

Fixes #117012.
2023-10-28 17:43:07 +00:00
Ralf Jung
70a8e157ab make pointer_structural_match warn-by-default 2023-10-28 17:02:18 +02:00
Ralf Jung
af6c7e0ca1 also lint against fn ptr and raw ptr nested inside the const 2023-10-28 17:02:18 +02:00
Ralf Jung
bec88ad4aa patterns: reject raw pointers that are not just integers 2023-10-28 17:02:18 +02:00
Jubilee
09fd68d9ee
Rollup merge of #117277 - RalfJung:too-big-with-padding, r=oli-obk
fix failure to detect a too-big-type after adding padding

Fixes https://github.com/rust-lang/rust/issues/117265
2023-10-28 01:07:39 -07:00
Jubilee
87a564d271
Rollup merge of #117025 - Urgau:cleanup-improve-check-cfg-impl, r=petrochenkov
Cleanup and improve `--check-cfg` implementation

This PR removes some indentation in the code, as well as preventing some bugs/misusages and fix a nit in the doc.

r? ```@petrochenkov``` (maybe)
2023-10-28 01:07:37 -07:00
Jubilee
9f631d0c23
Rollup merge of #116945 - estebank:sealed-trait-impls, r=petrochenkov
When encountering sealed traits, point types that implement it

```
error[E0277]: the trait bound `S: d::Hidden` is not satisfied
  --> $DIR/sealed-trait-local.rs:53:20
   |
LL | impl c::Sealed for S {}
   |                    ^ the trait `d::Hidden` is not implemented for `S`
   |
note: required by a bound in `c::Sealed`
  --> $DIR/sealed-trait-local.rs:17:23
   |
LL |     pub trait Sealed: self::d::Hidden {
   |                       ^^^^^^^^^^^^^^^ required by this bound in `Sealed`
   = note: `Sealed` is a "sealed trait", because to implement it you also need to implement `c::d::Hidden`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
   = help: the following types implement the trait:
            - c::X
            - c::Y
```

The last `help` is new.
2023-10-28 01:07:37 -07:00
Mu001999
fe00cfef57 restore snapshot when parse_param_general 2023-10-28 08:53:51 +08:00
bors
6f349cdbfa Auto merge of #116471 - notriddle:notriddle/js-trait-alias, r=GuillaumeGomez
rustdoc: use JS to inline target type impl docs into alias

Preview docs:

- https://notriddle.com/rustdoc-html-demo-5/js-trait-alias/std/io/type.Result.html

- https://notriddle.com/rustdoc-html-demo-5/js-trait-alias-compiler/rustc_middle/ty/type.PolyTraitRef.html

This pull request also includes a bug fix for trait alias inlining across crates. This means more documentation is generated, and is why ripgrep runs slower (it's a thin wrapper on top of the `grep` crate, so 5% of its docs are now the Result type).

- Before, built with rustdoc 1.75.0-nightly (aa1a71e9e 2023-10-26), Result type alias method docs are missing: http://notriddle.com/rustdoc-html-demo-5/ripgrep-js-nightly/rg/type.Result.html
- After, built with this branch, all the methods on Result are shown: http://notriddle.com/rustdoc-html-demo-5/ripgrep-js-trait-alias/rg/type.Result.html

*Review note: This is mostly just reverting https://github.com/rust-lang/rust/pull/115201. The last commit has the new work in it.*

Fixes #115718

This is an attempt to balance three problems, each of which would
be violated by a simpler implementation:

- A type alias should show all the `impl` blocks for the target
  type, and vice versa, if they're applicable. If nothing was
  done, and rustdoc continues to match them up in HIR, this
  would not work.

- Copying the target type's docs into its aliases' HTML pages
  directly causes far too much redundant HTML text to be generated
  when a crate has large numbers of methods and large numbers
  of type aliases.

- Using JavaScript exclusively for type alias impl docs would
  be a functional regression, and could make some docs very hard
  to find for non-JS readers.

- Making sure that only applicable docs are show in the
  resulting page requires a type checkers. Do not reimplement
  the type checker in JavaScript.

So, to make it work, rustdoc stashes these type-alias-inlined docs
in a JSONP "database-lite". The file is generated in `write_shared.rs`,
included in a `<script>` tag added in `print_item.rs`, and `main.js`
takes care of patching the additional docs into the DOM.

The format of `trait.impl` and `type.impl` JS files are superficially
similar. Each line, except the JSONP wrapper itself, belongs to a crate,
and they are otherwise separate (rustdoc should be idempotent). The
"meat" of the file is HTML strings, so the frontend code is very simple.
Links are relative to the doc root, though, so the frontend needs to fix
that up, and inlined docs can reuse these files.

However, there are a few differences, caused by the sophisticated
features that type aliases have. Consider this crate graph:

```text
 ---------------------------------
 | crate A: struct Foo<T>        |
 |          type Bar = Foo<i32>  |
 |          impl X for Foo<i8>   |
 |          impl Y for Foo<i32>  |
 ---------------------------------
     |
 ----------------------------------
 | crate B: type Baz = A::Foo<i8> |
 |          type Xyy = A::Foo<i8> |
 |          impl Z for Xyy        |
 ----------------------------------
```

The type.impl/A/struct.Foo.js JS file has a structure kinda like this:

```js
JSONP({
"A": [["impl Y for Foo<i32>", "Y", "A::Bar"]],
"B": [["impl X for Foo<i8>", "X", "B::Baz", "B::Xyy"], ["impl Z for Xyy", "Z", "B::Baz"]],
});
```

When the type.impl file is loaded, only the current crate's docs are
actually used. The main reason to bundle them together is that there's
enough duplication in them for DEFLATE to remove the redundancy.

The contents of a crate are a list of impl blocks, themselves
represented as lists. The first item in the sublist is the HTML block,
the second item is the name of the trait (which goes in the sidebar),
and all others are the names of type aliases that successfully match.

This way:

- There's no need to generate these files for types that have no aliases
  in the current crate. If a dependent crate makes a type alias, it'll
  take care of generating its own docs.
- There's no need to reimplement parts of the type checker in
  JavaScript. The Rust backend does the checking, and includes its
  results in the file.
- Docs defined directly on the type alias are dropped directly in the
  HTML by `render_assoc_items`, and are accessible without JavaScript.
  The JSONP file will not list impl items that are known to be part
  of the main HTML file already.

[JSONP]: https://en.wikipedia.org/wiki/JSONP
2023-10-27 23:08:24 +00:00
Zalathar
230dd5b8c7 coverage: Consistently remove unused counter IDs from expressions/mappings 2023-10-28 09:33:48 +11:00
Zalathar
975b98b816 coverage: Regression test for #17012 (bad counter IDs in mappings) 2023-10-28 09:27:06 +11:00
bors
2f1bd0729b Auto merge of #117294 - matthiaskrgr:rollup-xylsec7, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #116834 (Remove `rustc_symbol_mangling/messages.ftl`.)
 - #117212 (Properly restore snapshot when failing to recover parsing ternary)
 - #117246 (Fix ICE: Restrict param constraint suggestion)
 - #117247 (NVPTX: Allow PassMode::Direct for ptx kernels for now)
 - #117270 (Hide internal methods from documentation)
 - #117281 (std::thread : add SAFETY comment)
 - #117287 (fix miri target information for Test step)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-27 21:11:52 +00:00
bors
59bb9505bc Auto merge of #103208 - cjgillot:match-fake-read, r=oli-obk,RalfJung
Allow partially moved values in match

This PR attempts to unify the behaviour between `let _ = PLACE`, `let _: TY = PLACE;` and `match PLACE { _ => {} }`.
The logical conclusion is that the `match` version should not check for uninitialised places nor check that borrows are still live.

The `match PLACE {}` case is handled by keeping a `FakeRead` in the unreachable fallback case to verify that `PLACE` has a legal value.

Schematically, `match PLACE { arms }` in surface rust becomes in MIR:
```rust
PlaceMention(PLACE)
match PLACE {
  // Decision tree for the explicit arms
  arms,
  // An extra fallback arm
  _ => {
    FakeRead(ForMatchedPlace, PLACE);
    unreachable
  }
}
```

`match *borrow { _ => {} }` continues to check that `*borrow` is live, but does not read the value.
`match *borrow {}` both checks that `*borrow` is live, and fake-reads the value.

Continuation of ~https://github.com/rust-lang/rust/pull/102256~ ~https://github.com/rust-lang/rust/pull/104844~

Fixes https://github.com/rust-lang/rust/issues/99180 https://github.com/rust-lang/rust/issues/53114
2023-10-27 18:51:43 +00:00
clubby789
be0b42fabe Recover from incorrectly ordered/duplicated function keywords 2023-10-27 18:29:43 +00:00
Nadrieril
a4875ae1e2 Match usize/isize exhaustively 2023-10-27 19:56:12 +02:00
Nadrieril
11268b48a1 Add tests 2023-10-27 19:56:12 +02:00
Matthias Krüger
a77f743239
Rollup merge of #117246 - estebank:issue-117209, r=petrochenkov
Fix ICE: Restrict param constraint suggestion

When encountering an associated item with a type param that could be constrained, do not look at the parent item if the type param comes from the associated item.

Fix #117209, fix #89868.
2023-10-27 19:46:08 +02:00
Matthias Krüger
b2295375f8
Rollup merge of #117212 - clubby789:fix-ternary-recover, r=compiler-errors
Properly restore snapshot when failing to recover parsing ternary

If the recovery parsed an expression, then failed to eat a `:`, it would return `false` without restoring the snapshot. Fix this by always restoring the snapshot when returning `false`.

Draft for now because I'd like to try and improve this recovery further.

Fixes #117208
2023-10-27 19:46:07 +02:00
Esteban Küber
6dbad23641 When encountering sealed traits, point types that implement it
```
error[E0277]: the trait bound `S: d::Hidden` is not satisfied
  --> $DIR/sealed-trait-local.rs:53:20
   |
LL | impl c::Sealed for S {}
   |                    ^ the trait `d::Hidden` is not implemented for `S`
   |
note: required by a bound in `c::Sealed`
  --> $DIR/sealed-trait-local.rs:17:23
   |
LL |     pub trait Sealed: self::d::Hidden {
   |                       ^^^^^^^^^^^^^^^ required by this bound in `Sealed`
   = note: `Sealed` is a "sealed trait", because to implement it you also need to implement `c::d::Hidden`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
   = help: the following types implement the trait:
            - c::X
            - c::Y
```

The last `help` is new.
2023-10-27 17:40:52 +00:00
Esteban Küber
231f93524d Detect misparsed binop caused by missing semi
When encountering

```rust
foo()
*bar = baz;
```

We currently emit potentially two errors, one for the return type of
`foo` not being multiplyiable by the type of `bar`, and another for
`foo() * bar` not being assignable.

We now check for this case and suggest adding a semicolon in the right
place.

Fix #80446.
2023-10-27 17:19:32 +00:00
Esteban Küber
7449478c2f Account for type param from other item in note_and_explain
Fix #89868.
2023-10-27 16:24:01 +00:00
Ralf Jung
2ef5897a89 fix failure to detect a too-big-type after adding padding 2023-10-27 18:07:53 +02:00
Oli Scherer
eb66d10cc3 Fuse gen blocks 2023-10-27 15:20:44 +00:00
bors
9d6d5d4894 Auto merge of #116751 - Nadrieril:lint-overlap-per-column, r=davidtwco
Lint overlapping ranges as a separate pass

This reworks the [`overlapping_range_endpoints`](https://doc.rust-lang.org/beta/nightly-rustc/rustc_lint_defs/builtin/static.OVERLAPPING_RANGE_ENDPOINTS.html) lint. My motivations are:

- It was annoying to have this lint entangled with the exhaustiveness algorithm, especially wrt librarification;
- This makes the lint behave consistently.

Here's the consistency story. Take the following matches:
```rust
match (0u8, true) {
    (0..=10, true) => {}
    (10..20, true) => {}
    (10..20, false) => {}
    _ => {}
}
match (true, 0u8) {
    (true, 0..=10) => {}
    (true, 10..20) => {}
    (false, 10..20) => {}
    _ => {}
}
```
There are two semantically consistent options: option 1 we lint all overlaps between the ranges, option 2 we only lint the overlaps that could actually occur (i.e. the ones with `true`). Option 1 is what this PR does. Option 2 is possible but would require the exhaustiveness algorithm to track more things for the sake of the lint. The status quo is that we're inconsistent between the two.

Option 1 generates more false postives, but I prefer it from a maintainer's perspective. I do think the difference is minimal; cases where the difference is observable seem rare.

This PR adds a separate pass, so this will have a perf impact. Let's see how bad, it looked ok locally.
2023-10-27 14:10:42 +00:00
Oli Scherer
bb90c4bf35 Use targetted diagnostic for borrow across yield error 2023-10-27 13:05:49 +00:00
Oli Scherer
6223744078 Prevent generators from being movable 2023-10-27 13:05:49 +00:00
Oli Scherer
4ac25faf9f Handle move generators 2023-10-27 13:05:48 +00:00
Oli Scherer
cece90c65f Feature gate coroutine yield usage 2023-10-27 13:05:48 +00:00
Oli Scherer
2e5b36741b Demonstrate issue with yield checks 2023-10-27 13:05:48 +00:00
Oli Scherer
638d2d6fc1 Feature gate gen blocks, even in 2024 edition 2023-10-27 13:05:48 +00:00
Oli Scherer
c892b28c02 Basic generators work 2023-10-27 13:05:48 +00:00
Oli Scherer
998a816106 Make gen blocks implement the Iterator trait 2023-10-27 13:05:48 +00:00
Oli Scherer
621494382d Add gen blocks to ast and do some broken ast lowering 2023-10-27 13:05:48 +00:00
bors
688892938e Auto merge of #116858 - estebank:issue-22488, r=petrochenkov
Suggest assoc fn `new` when trying to build tuple struct with private fields

Fix #22488.
2023-10-27 12:16:01 +00:00
Georg Semmler
160b1793b2
Allows #[diagnostic::on_unimplemented] attributes to have multiple
notes

This commit extends the `#[diagnostic::on_unimplemented]` (and
`#[rustc_on_unimplemented]`) attributes to allow multiple `note`
options. This enables emitting multiple notes for custom error messages.
For now I've opted to not change any of the existing usages of
`#[rustc_on_unimplemented]` and just updated the relevant compile tests.
2023-10-27 12:42:42 +02:00
bors
95f6a01e8f Auto merge of #117272 - matthiaskrgr:rollup-upg122z, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #114998 (feat(docs): add cargo-pgo to PGO documentation 📝)
 - #116868 (Tweak suggestion span for outer attr and point at item following invalid inner attr)
 - #117240 (Fix documentation typo in std::iter::Iterator::collect_into)
 - #117241 (Stash and cancel cycle errors for auto trait leakage in opaques)
 - #117262 (Create a new ConstantKind variant (ZeroSized) for StableMIR)
 - #117266 (replace transmute by raw pointer cast)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-27 10:19:35 +00:00
Urgau
84a1a689cc Better guard against wrong input with check-cfg any() 2023-10-27 12:02:54 +02:00
Matthias Krüger
5459333ffc
Rollup merge of #117241 - compiler-errors:auto-trait-leak-cycle, r=oli-obk
Stash and cancel cycle errors for auto trait leakage in opaques

We don't need to emit a traditional cycle error when we have a selection error that explains what's going on but in more detail.

We may want to augment this error to actually point out the cycle, now that the cycle error is not being emitted. We could do that by storing the set of opaques that was in the `CyclePlaceholder` that gets returned from `type_of_opaque`.

r? `@oli-obk` cc `@estebank` #117235
2023-10-27 11:48:06 +02:00
Matthias Krüger
a69fb480a4
Rollup merge of #116868 - estebank:suggestion, r=petrochenkov
Tweak suggestion span for outer attr and point at item following invalid inner attr

After:

```
error: `unix_sigpipe` attribute cannot be used at crate level
  --> $DIR/unix_sigpipe-crate.rs:2:1
   |
LL | #![unix_sigpipe = "inherit"]
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
LL |
LL | fn main() {}
   | ------------ the inner attribute doesn't annotate this function
   |
help: perhaps you meant to use an outer attribute
   |
LL - #![unix_sigpipe = "inherit"]
LL + #[unix_sigpipe = "inherit"]
   |
```

Before:

```
error: `unix_sigpipe` attribute cannot be used at crate level
  --> $DIR/unix_sigpipe-crate.rs:2:1
   |
LL | #![unix_sigpipe = "inherit"]
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
help: perhaps you meant to use an outer attribute
   |
LL | #[unix_sigpipe = "inherit"]
   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~
```

CC #89566.
2023-10-27 11:48:05 +02:00
bors
54e57e66ff Auto merge of #116205 - WaffleLapkin:stabilize_pointer_byte_offsets, r=dtolnay
Stabilize `[const_]pointer_byte_offsets`

Closes #96283
Awaiting FCP completion: https://github.com/rust-lang/rust/issues/96283#issuecomment-1735835331

r? libs-api
2023-10-27 08:24:54 +00:00
bors
707d8c3f1b Auto merge of #117260 - okaneco:ascii_branchless, r=thomcc
Refactor some `char`, `u8` ASCII functions to be branchless

Extract conditions in singular `matches!` with or-patterns to individual `matches!` statements which enables branchless code output. The following functions were changed:
- `is_ascii_alphanumeric`
- `is_ascii_hexdigit`
- `is_ascii_punctuation`

Added codegen tests

---

Continued from https://github.com/rust-lang/rust/pull/103024.
Based on the comment from `@scottmcm` https://github.com/rust-lang/rust/pull/103024#pullrequestreview-1248697206.

The unmodified `is_ascii_*` functions didn't seem to benefit from extracting the conditions.

I've never written a codegen test before, but I tried to check that no branches were emitted.
2023-10-27 04:06:40 +00:00
Nadrieril
3fa2e71ce1 Handle ty::Opaque correctly 2023-10-27 05:16:26 +02:00
Nadrieril
d5070e32ea Lint overlapping ranges as a separate pass 2023-10-27 05:16:26 +02:00
bors
31ffe48723 Auto merge of #116035 - lqd:mcp-510-target-specs, r=petrochenkov
Allow target specs to use an LLD flavor, and self-contained linking components

This PR allows:
- target specs to use an LLD linker-flavor: this is needed to switch `x86_64-unknown-linux-gnu` to using LLD, and is currently not possible because the current flavor json serialization fails to roundtrip on the modern linker-flavors. This can e.g. be seen in https://github.com/rust-lang/rust/pull/115622#discussion_r1321312880 which explains where an `Lld::Yes` is ultimately deserialized into an `Lld::No`.
- target specs to declare self-contained linking components: this is needed to switch `x86_64-unknown-linux-gnu` to using `rust-lld`
- adds an end-to-end test of a custom target json simulating `x86_64-unknown-linux-gnu` being switched to using `rust-lld`
- disables codegen backends from participating because they don't support `-Zgcc-ld=lld` which is the basis of mcp510.

r? `@petrochenkov:` if the approach discussed https://github.com/rust-lang/rust/pull/115622#discussion_r1329403467 and on zulip would work for you: basically, see if we can emit only modern linker flavors in the json specs, but accept both old and new flavors while reading them, to fix the roundtrip issue.

The backwards compatible `LinkSelfContainedDefault` variants are still serialized and deserialized in `crt-objects-fallback`, while the spec equivalent of e.g. `-Clink-self-contained=+linker` is serialized into a different json object (with future-proofing to incorporate `crt-objects-fallback`  in the future).

---

I've been test-driving this in https://github.com/rust-lang/rust/pull/113382 to test actually switching `x86_64-unknown-linux-gnu`  to `rust-lld` (and fix what needs to be fixed in CI, bootstrap, etc), and it seems to work fine.
2023-10-27 02:11:36 +00:00
okaneco
465ffc9ca7 Refactor some char, u8 ascii functions to be branchless
Decompose singular `matches!` with or-patterns to individual `matches!`
statements to enable branchless code output. The following functions
were changed:
- `is_ascii_alphanumeric`
- `is_ascii_hexdigit`
- `is_ascii_punctuation`

Add codegen tests

Co-authored-by: George Bateman <george.bateman16@gmail.com>
Co-authored-by: scottmcm <scottmcm@users.noreply.github.com>
2023-10-26 21:48:36 -04:00
bors
aa91057796 Auto merge of #113183 - estebank:redundant-sized-errors, r=davidtwco
Only emit one error per unsized binding, instead of one per usage

Fix #56607.
2023-10-27 00:06:12 +00:00
clubby789
e81a5c65d9 Recover ternary expression as error 2023-10-26 23:04:20 +00:00
Esteban Küber
87dc85d322 Suggest assoc fn new when trying to build tuple struct with private fields
Fix #22488.
2023-10-26 22:21:05 +00:00
Matthias Krüger
a8f7acd8f8
Rollup merge of #117114 - nnethercote:improve-stringify-test, r=petrochenkov
Improve `stringify.rs` test

Best reviewed one commit at a time.

r? `@petrochenkov`
2023-10-26 22:26:11 +02:00
Matthias Krüger
d09c988791
Rollup merge of #117106 - estebank:issue-27300, r=petrochenkov
When expecting closure argument but finding block provide suggestion

Detect if there is a potential typo where the `{` meant to open the closure body was written before the body.

```
error[E0277]: expected a `FnOnce<({integer},)>` closure, found `Option<usize>`
  --> $DIR/ruby_style_closure_successful_parse.rs:3:31
   |
LL |       let p = Some(45).and_then({|x|
   |  ______________________--------_^
   | |                      |
   | |                      required by a bound introduced by this call
LL | |         1 + 1;
LL | |         Some(x * 2)
   | |         ----------- this tail expression is of type `Option<usize>`
LL | |     });
   | |_____^ expected an `FnOnce<({integer},)>` closure, found `Option<usize>`
   |
   = help: the trait `FnOnce<({integer},)>` is not implemented for `Option<usize>`
note: required by a bound in `Option::<T>::and_then`
  --> $SRC_DIR/core/src/option.rs:LL:COL
help: you might have meant to open the closure body instead of placing a closure within a block
   |
LL -     let p = Some(45).and_then({|x|
LL +     let p = Some(45).and_then(|x| {
   |
```

Detect the potential typo where the closure header is missing.

```
error[E0277]: expected a `FnOnce<(&bool,)>` closure, found `bool`
  --> $DIR/block_instead_of_closure_in_arg.rs:3:23
   |
LL |        Some(true).filter({
   |  _________________------_^
   | |                 |
   | |                 required by a bound introduced by this call
LL | |/         if number % 2 == 0 {
LL | ||             number == 0
LL | ||         } else {
LL | ||             number != 0
LL | ||         }
   | ||_________- this tail expression is of type `bool`
LL | |      });
   | |______^ expected an `FnOnce<(&bool,)>` closure, found `bool`
   |
   = help: the trait `for<'a> FnOnce<(&'a bool,)>` is not implemented for `bool`
note: required by a bound in `Option::<T>::filter`
  --> $SRC_DIR/core/src/option.rs:LL:COL
help: you might have meant to create the closure instead of a block
   |
LL |     Some(true).filter(|_| {
   |                       +++
```

Partially address #27300. Fix #104690.
2023-10-26 22:26:11 +02:00
Matthias Krüger
934cbe4637
Rollup merge of #116968 - eopb:116967, r=petrochenkov
Invalid `?` suggestion on mismatched `Ok(T)`

fixes: #116967
2023-10-26 22:26:10 +02:00
Esteban Küber
27919ceba7 Tweak suggestion spans for invalid crate-level inner attribute
CC #89566.
2023-10-26 18:35:09 +00:00
Esteban Küber
3bbc70a5f7 Restrict param constraint suggestion
When encountering an associated item with a type param that could be
constrained, do not look at the parent item if the type param comes from
the associated item.

Fix #117209.
2023-10-26 18:33:03 +00:00
Michael Goulet
1836c1fbbd Stash and cancel cycle errors for auto trait leakage in opaques 2023-10-26 17:58:02 +00:00
bors
8396efecf7 Auto merge of #117228 - matthiaskrgr:rollup-23zzepv, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #116905 (refactor(compiler/resolve): simplify some code)
 - #117095 (Add way to differentiate argument locals from other locals in Stable MIR)
 - #117143 (Avoid unbounded O(n^2) when parsing nested type args)
 - #117194 (Minor improvements to `rustc_incremental`)
 - #117202 (Revert "Remove TaKO8Ki from reviewers")
 - #117207 (The value of `-Cinstrument-coverage=` doesn't need to be `Option`)
 - #117214 (Quietly fail if an error has already occurred)
 - #117221 (Rename type flag `HAS_TY_GENERATOR` to `HAS_TY_COROUTINE`)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-26 17:35:23 +00:00
Matthias Krüger
70a4678a77
Rollup merge of #117214 - oli-obk:error_shenanigans, r=compiler-errors
Quietly fail if an error has already occurred

fixes #117195
2023-10-26 17:45:46 +02:00
Matthias Krüger
7eb05480e9
Rollup merge of #117143 - estebank:issue-117080, r=wesleywiser
Avoid unbounded O(n^2) when parsing nested type args

When encountering code like `f::<f::<f::<f::<f::<f::<f::<f::<...` with unmatched closing angle brackets, add a linear check that avoids the exponential behavior of the parse recovery mechanism.

Fix https://github.com/rust-lang/rust/issues/117080, fix https://github.com/rust-lang/rust/issues/115414.
2023-10-26 17:45:44 +02:00
Matthias Krüger
b66c6e719f
Rollup merge of #117095 - klinvill:smir-fn-arg-count, r=oli-obk
Add way to differentiate argument locals from other locals in Stable MIR

This PR resolves rust-lang/project-stable-mir#47 which request a way to differentiate argument locals in a SMIR `Body` from other locals.

Specifically, this PR exposes the `arg_count` field from the MIR `Body`. However, I'm opening this as a draft PR because I think there are a few outstanding questions on how this information should be exposed and described. Namely:

- Is exposing `arg_count` the best way to surface this information to SMIR users? Would it be better to leave `arg_count` as a private field and add public methods (e.g. `fn arguments(&self) -> Iter<'_, LocalDecls>`) that may use the underlying `arg_count` info from the MIR body, but expose this information to users in a more convenient form? Or is it best to stick close to the current MIR convention?
- If the answer to the above point is to stick with the current MIR convention (`arg_count`), is it reasonable to also commit to sticking to the current MIR convention that the first local is always the return local, while the next `arg_count` locals are always the (in-order) argument locals?
- Should `Body` in SMIR only represent function bodies (as implied by the comment I added)? That seems to be the current case in MIR, but should this restriction always be the case for SMIR?

r? `@celinval`
r? `@oli-obk`
2023-10-26 17:45:43 +02:00
bors
698db856de Auto merge of #117171 - fee1-dead-contrib:deny-explicit-effect-params, r=oli-obk
Deny providing explicit effect params

r? `@oli-obk`

cc https://github.com/rust-lang/rust/issues/110395
2023-10-26 14:50:23 +00:00
bors
6f65201659 Auto merge of #113262 - Nilstrieb:rawr-casting, r=lcnr
Never consider raw pointer casts to be trival

HIR typeck tries to figure out which casts are trivial by doing them as
coercions and seeing whether this works. Since HIR typeck is oblivious
of lifetimes, this doesn't work for pointer casts that only change the
lifetime of the pointee, which are, as borrowck will tell you, not
trivial.

This change makes it so that raw pointer casts are never considered
trivial.

This also incidentally fixes the "trivial cast" lint false positive on
the same code. Unfortunately, "trivial cast" lints are now never emitted
on raw pointer casts, even if they truly are trivial. This could be
fixed by also doing the lint in borrowck for raw pointers specifically.

fixes #113257
2023-10-26 12:54:19 +00:00
Oli Scherer
d572729d59 Quietly fail if an error has already occurred 2023-10-26 11:14:53 +00:00
clubby789
041f0313cf Properly restore snapshot when failing to recover parsing ternary 2023-10-26 11:11:36 +00:00
bors
9ab0749ce3 Auto merge of #112875 - compiler-errors:negative-coherence-rework, r=lcnr
Rework negative coherence to properly consider impls that only partly overlap

This PR implements a modified negative coherence that handles impls that only have partial overlap.

It does this by:
1. taking both impl trait refs, instantiating them with infer vars
2. equating both trait refs
3. taking the equated trait ref (which represents the two impls' intersection), and resolving any vars
4. plugging all remaining infer vars with placeholder types

these placeholder-plugged trait refs can then be used normally with the new trait solver, since we no longer have to worry about the issue with infer vars in param-envs.

We use the **new trait solver** to reason correctly about unnormalized trait refs (due to deferred projection equality), since this avoid having to normalize anything under param-envs with infer vars in them.

This PR then additionally:
* removes the `FnPtr` knowable hack by implementing proper negative `FnPtr` trait bounds for rigid types.

---

An example:

Consider these two partially overlapping impls:

```
impl<T, U> PartialEq<&U> for &T where T: PartialEq<U> {}
impl<F> PartialEq<F> for F where F: FnPtr {}
```

Under the old algorithm, we would take one of these impls and replace it with infer vars, then try unifying it with the other impl under identity substitutions. This is not possible in either direction, since it either sets `T = U`, or tries to equate `F = &?0`.

Under the new algorithm, we try to unify `?0: PartialEq<?0>` with `&?1: PartialEq<&?2>`. This gives us `?0 = &?1 = &?2` and thus `?1 = ?2`. The intersection of these two trait refs therefore looks like: `&?1: PartialEq<&?1>`. After plugging this with placeholders, we get a trait ref that looks like `&!0: PartialEq<&!0>`, with the first impl having substs `?T = ?U = !0` and the second having substs `?F = &!0`[^1].

Then we can take the param-env from the first impl, and try to prove the negated where clause of the second.

We know that `&!0: !FnPtr` never holds, since it's a rigid type that is also not a fn ptr, we successfully detect that these impls may never overlap.

[^1]: For the purposes of this example, I just ignored lifetimes, since it doesn't really matter.
2023-10-26 10:57:21 +00:00
Deadbeef
47efc90366 Deny providing explicit effect params 2023-10-26 08:24:25 +00:00
bors
104ac7bb6a Auto merge of #117148 - dtolnay:sinceversion, r=cjgillot
Store #[stable] attribute's `since` value in structured form

Followup to https://github.com/rust-lang/rust/pull/116773#pullrequestreview-1680913901.

Prior to this PR, if you wrote an improper `since` version in a `stable` attribute, such as `#[stable(feature = "foo", since = "wat.0")]`, rustc would emit a diagnostic saying **_'since' must be a Rust version number, such as "1.31.0"_** and then throw out the whole `stable` attribute as if it weren't there. This strategy had 2 problems, both fixed in this PR:

1. If there was also a `#[deprecated]` attribute on the same item, rustc would want to enforce that the stabilization version is older than the deprecation version. This involved reparsing the `stable` attribute's `since` version, with a diagnostic **_invalid stability version found_** if it failed to parse. Of course this diagnostic was unreachable because an invalid `since` version would have already caused the `stable` attribute to be thrown out. This PR deletes that unreachable diagnostic.

2. By throwing out the `stable` attribute when `since` is invalid, you'd end up with a second diagnostic saying **_function has missing stability attribute_** even though your function is not missing a stability attribute. This PR preserves the `stable` attribute even when `since` cannot be parsed, avoiding the misleading second diagnostic.

Followups I plan to try next:

- Do the same for the `since` value of `#[deprecated]`.

- See whether it makes sense to also preserve `stable` and/or `unstable` attributes when they contain an invalid `feature`. What redundant/misleading diagnostics can this eliminate? What problems arise from not having a usable feature name for some API, in the situation that we're already failing compilation, so not concerned about anything that happens in downstream code?
2023-10-26 06:59:19 +00:00
Oli Scherer
a61cf673cd Reserve gen keyword for gen {} blocks and gen fn in 2024 edition 2023-10-26 06:49:17 +00:00
bors
ccb160d343 Auto merge of #117115 - zetafunction:linking, r=bjorn3
Mark .rmeta files as /SAFESEH on x86 Windows.

Chrome links .rlibs with /WHOLEARCHIVE or -Wl,--whole-archive to prevent the linker from discarding static initializers. This works well, except on Windows x86, where lld complains:

  error: /safeseh: lib.rmeta is not compatible with SEH

The fix is simply to mark the .rmeta as SAFESEH aware. This is trivially true, since the metadata file does not contain any executable code.
2023-10-26 04:04:50 +00:00
bors
6d674af861 Auto merge of #116818 - Nilstrieb:stop-submitting-bug-reports, r=wesleywiser
Stop telling people to submit bugs for internal feature ICEs

This keeps track of usage of internal features, and changes the message to instead tell them that using internal features is not supported.

I thought about several ways to do this but now used the explicit threading of an `Arc<AtomicBool>` through `Session`. This is not exactly incremental-safe, but this is fine, as this is set during macro expansion, which is pre-incremental, and also only affects the output of ICEs, at which point incremental correctness doesn't matter much anyways.

See [MCP 620.](https://github.com/rust-lang/compiler-team/issues/596)

![image](https://github.com/rust-lang/rust/assets/48135649/be661f05-b78a-40a9-b01d-81ad2dbdb690)
2023-10-26 02:08:07 +00:00
Maybe Waffle
fe97fdf782 Remove unused feature from a miri test 2023-10-26 00:46:56 +00:00
Kirby Linvill
bac7d5b52c
Add test for smir locals 2023-10-26 00:22:56 +01:00
Kirby Linvill
4b23bd4734
Update Place and Operand to take slices
The latest locals() method in stable MIR returns slices instead of vecs.
This commit also includes fixes to the existing tests that previously
referenced the private locals field.
2023-10-26 00:21:28 +01:00
Maybe Waffle
e36224118f Stabilize [const_]pointer_byte_offsets 2023-10-25 22:35:12 +00:00
Ryan Mehri
1ec10ec77f address review comments 2023-10-25 15:25:38 -07:00
Ryan Mehri
6ab66c3f37 FileCheck unwrap_unchecked 2023-10-25 15:25:38 -07:00
Ryan Mehri
3faf05b6e7 FileCheck unsized_argument 2023-10-25 15:25:38 -07:00
Ryan Mehri
6e047c07a6 FileCheck unchecked_shifts 2023-10-25 15:25:38 -07:00
Ryan Mehri
5cf65eb16a FileCheck issue_78442 2023-10-25 15:25:38 -07:00
Ryan Mehri
bb695977de FileCheck inline_scopes_parenting 2023-10-25 15:25:38 -07:00
Ryan Mehri
773dc62756 FileCheck inline_as_ref_as_mut 2023-10-25 15:25:38 -07:00
Ryan Mehri
1b9cb5d59b FileCheck inline_trait_method 2023-10-25 15:25:38 -07:00
Ryan Mehri
f7acf17945 FileCheck inline_trait_method_2 2023-10-25 15:25:38 -07:00
Ryan Mehri
25325667f2 FileCheck inline_specialization 2023-10-25 15:25:38 -07:00
Ryan Mehri
21a4c39cb8 FileCheck inline_retag 2023-10-25 15:25:38 -07:00
Ryan Mehri
3202d4e357 FileCheck inline_options 2023-10-25 15:25:38 -07:00
Ryan Mehri
de8255194a FileCheck inline_into_box_place 2023-10-25 15:25:38 -07:00
Ryan Mehri
19c36a96df FileCheck inline_instruction_set 2023-10-25 15:25:38 -07:00
Ryan Mehri
20e7caa737 FileCheck inline_coroutine 2023-10-25 15:25:38 -07:00
Ryan Mehri
d8f33ef93d FileCheck inline_diverging 2023-10-25 15:25:38 -07:00
Ryan Mehri
7ee05d24b5 FileCheck inline_closure 2023-10-25 15:22:01 -07:00
Ryan Mehri
5caee416a5 FileCheck inline_closure_captures 2023-10-25 15:22:01 -07:00
Ryan Mehri
9d61e6a4e4 FileCheck inline_closure_borrows_arg 2023-10-25 15:22:01 -07:00
Ryan Mehri
de56d2d9b2 FileCheck inline_box_fn 2023-10-25 15:22:01 -07:00
Ryan Mehri
22679cd36d FileCheck inline_any_operand 2023-10-25 15:22:01 -07:00
Ryan Mehri
f005d2325a FileCheck exponential_runtime 2023-10-25 15:22:01 -07:00
Ryan Mehri
76faae9cdc FileCheck dyn_trait 2023-10-25 15:22:01 -07:00
Ryan Mehri
9b3f5e1527 FileCheck dont_ice_on_generic_rust_call 2023-10-25 15:22:01 -07:00