Commit Graph

7629 Commits

Author SHA1 Message Date
Ralf Jung 77f8c3caea detect consts that reference extern statics 2024-02-10 16:13:48 +01:00
Ralf Jung 9c0623fe8f validation: descend from consts into statics 2024-02-10 16:13:47 +01:00
Ralf Jung 4e77e368eb unstably allow constants to refer to statics and read from immutable statics 2024-02-10 16:12:55 +01:00
Matthias Krüger 55913368c5
Rollup merge of #120870 - Zalathar:allow-min-spec, r=oli-obk
Allow restricted trait impls under `#[allow_internal_unstable(min_specialization)]`

This is a follow-up to #119963 and a companion to #120866, though it can land independently from the latter.

---

We have several compiler crates that only enable `#[feature(min_specialization)]` because it is required by their expansions of `newtype_index!`, in order to implement traits marked with `#[rustc_specialization_trait]`.

This PR allows those traits to be implemented internally by macros with `#[allow_internal_unstable(min_specialization)]`, without needing specialization to be enabled in the enclosing crate.
2024-02-10 13:12:31 +01:00
Matthias Krüger 2dbc9f55f7
Rollup merge of #120859 - nnethercote:fix-120856, r=oli-obk
Loosen an assertion to account for stashed errors.

The meaning of this assertion changed in #120828 when the meaning of `has_errors` changed to exclude stashed errors. Evidently the new meaning is too restrictive.

Fixes #120856.

r? ```@oli-obk```
2024-02-10 13:12:30 +01:00
Matthias Krüger e11e4446da
Rollup merge of #120719 - compiler-errors:no-dyn-atb, r=lcnr
Remove support for `associated_type_bound` nested in `dyn` types

These necessarily desugar to `impl Trait`, which is inconsistent with the `associated_type_bound` feature after #120584.

This PR keeps the `is_in_dyn_type` hack, which kind of makes me sad. Ideally, we'd be validating that no object types have associated type bounds somewhere else. Unfortunately, we can't do this later during astconv (i think?), nor can we do it earlier during ast validation (i think?) because of the feature gating of ATB being a *warning* rather than an *error*. Let me know if you have thoughts about this.

r? lcnr
2024-02-10 13:12:28 +01:00
Matthias Krüger 0b7f0ff230
Rollup merge of #117614 - RalfJung:static-mut-refs, r=davidtwco,oli-obk
static mut: allow mutable reference to arbitrary types, not just slices and arrays

For historical reasons, we allow this:
```rust
static mut ARRAY: &'static mut [isize] = &mut [1];
```
However, we do not allow this:
```rust
static mut INT: &'static mut isize = &mut 1;
```

I think that's terribly inconsistent. I don't care much for `static mut`, but we have to keep it around for backwards compatibility and so we have to keep supporting it properly in the compiler. In recent refactors of how we deal with mutability of data in `static` and `const`, I almost made a fatal mistake since I tested `static mut INT: &'static mut isize = &mut 1` and concluded that we don't allow such `'static` mutable references even inside `static mut`. After all, nobody would expect this to be allowed only for arrays and slices, right?!?? So for the sake of our own sanity, and of whoever else reverse engineers these rules in the future to understand what the Rust compiler accepts or does not accept, I propose that we accept this for all types, not just arrays and slices.
2024-02-10 13:12:28 +01:00
bors 757b8efed4 Auto merge of #120712 - compiler-errors:async-closures-harmonize, r=oli-obk
Harmonize `AsyncFn` implementations, make async closures conditionally impl `Fn*` traits

This PR implements several changes to the built-in and libcore-provided implementations of `Fn*` and `AsyncFn*` to address two problems:
1. async closures do not implement the `Fn*` family traits, leading to breakage: https://crater-reports.s3.amazonaws.com/pr-120361/index.html
2. *references* to async closures do not implement `AsyncFn*`, as a consequence of the existing blanket impls of the shape `AsyncFn for F where F: Fn, F::Output: Future`.

In order to fix (1.), we implement `Fn` traits appropriately for async closures. It turns out that async closures can:
* always implement `FnOnce`, meaning that they're drop-in compatible with `FnOnce`-bound combinators like `Option::map`.
* conditionally implement `Fn`/`FnMut` if they have no captures, which means that existing usages of async closures should *probably* work without breakage (crater checking this: https://github.com/rust-lang/rust/pull/120712#issuecomment-1930587805).

In order to fix (2.), we make all of the built-in callables implement `AsyncFn*` via built-in impls, and instead adjust the blanket impls for `AsyncFn*` provided by libcore to match the blanket impls for `Fn*`.
2024-02-10 07:15:15 +00:00
Zalathar 7b73e4fd44 Allow restricted trait impls in macros with `min_specialization`
Implementing traits marked with `#[rustc_specialization_trait]` normally
requires (min-)specialization to be enabled for the enclosing crate.

With this change, that permission can also be granted by an
`allow_internal_unstable` attribute on the macro that generates the impl.
2024-02-10 18:14:02 +11:00
Michael Goulet fde695a2d1 Add a helpful suggestion 2024-02-10 03:31:34 +00:00
Michael Goulet 973bbfbd23 No more associated type bounds in dyn trait 2024-02-10 03:23:51 +00:00
Matthias Krüger 8177c0fead
Rollup merge of #120850 - petrochenkov:empimpres, r=cjgillot
ast_lowering: Fix regression in `use ::{}` imports.

Fixes https://github.com/rust-lang/rust/issues/120789
2024-02-10 00:58:39 +01:00
Matthias Krüger 34489b7769
Rollup merge of #120629 - c410-f3r:testsssssss, r=petrochenkov
Move some test files

r? ``@petrochenkov``
2024-02-10 00:58:38 +01:00
Matthias Krüger c06199f863
Rollup merge of #120596 - GuillaumeGomez:jump-to-def-non-local-link, r=notriddle,fmease
[rustdoc] Correctly generate path for non-local items in source code pages

While browsing some crates using the "jump to def" feature, I realized that a lot of items didn't have a link generated. The reason is because we only cache foreign items if they appear in the documented API. This means that for the others, we need to infer them.

r? ``@notriddle``
2024-02-10 00:58:37 +01:00
Matthias Krüger 9ec287dec2
Rollup merge of #120584 - compiler-errors:u, r=lcnr
For a rigid projection, recursively look at the self type's item bounds to fix the `associated_type_bounds` feature

Given a deeply nested rigid projection like `<<<T as Trait1>::Assoc1 as Trait2>::Assoc2 as Trait3>::Assoc3`, this PR adjusts both trait solvers to look at the item bounds for all of `Assoc3`, `Assoc2`, and `Assoc1` in order to satisfy a goal. We do this because the item bounds for projections may contain relevant bounds for *other* nested projections when the `associated_type_bounds` (ATB) feature is enabled. For example:

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

trait Trait1 {
    type Assoc1: Trait2<Assoc2: Foo>;
    // Item bounds for `Assoc1` are:
    // `<Self as Trait1>::Assoc1: Trait2`
    // `<<Self as Trait1>::Assoc1 as Trait2>::Assoc2: Foo`
}

trait Trait2 {
    type Assoc2;
}

trait Foo {}

fn hello<T: Trait1>(x: <<T as Trait1>::Assoc1 as Trait2>::Assoc2) {
    fn is_foo(_: impl Foo) {}
    is_foo(x);
    // Currently fails with:
    // ERROR the trait bound `<<Self as Trait1>::Assoc1 as Trait2>::Assoc2: Foo` is not satisfied
}
```

This has been a long-standing place of brokenness for ATBs, and is also part of the reason why ATBs currently desugar so differently in various positions (i.e. sometimes desugaring to param-env bounds, sometimes desugaring to RPITs, etc). For example, in RPIT and TAIT position, `impl Foo<Bar: Baz>` currently desugars to `impl Foo<Bar = impl Baz>` because we do not currently take advantage of these nested item bounds if we desugared them into a single set of item bounds on the opaque. This is obviously both strange and unnecessary if we just take advantage of these bounds as we should.

## Approach

This PR repeatedly peels off each projection of a given goal's self type and tries to match its item bounds against a goal, repeating with the self type of the projection. This is pretty straightforward to implement in the new solver, only requiring us to loop on the self type of a rigid projection to discover inner rigid projections, and we also need to introduce an extra probe so we can normalize them.

In the old solver, we can do essentially the same thing, however we rely on the fact that projections *should* be normalized already. This is obviously not always the case -- however, in the case that they are not fully normalized, such as a projection which has both infer vars and, we bail out with ambiguity if we hit an infer var for the self type.

## Caveats

⚠️ In the old solver, this has the side-effect of actually stalling some higher-ranked trait goals of the form `for<'a> <?0 as Tr<'a>>: Tr2`. Because we stall them, they no longer are eagerly treated as error -- this cause some existing `known-bug` tests to go from fail -> pass.

I'm pretty unconvinced that this is a problem since we make code that we expect to pass in the *new* solver also pass in the *old* solver, though this obviously doesn't solve the *full* problem.

## And then also...

We also adjust the desugaring of ATB to always desugar to a regular associated bound, rather than sometimes to an impl Trait **except** for when the ATB is present in a `dyn Trait`. We need to lower `dyn Trait<Assoc: Bar>` to `dyn Trait<Assoc = impl Bar>` because object types need all of their associated types specified.

I would also be in favor of splitting out the ATB feature and/or removing support for object types in order to stabilize just the set of positions for which the ATB feature is consistent (i.e. always elaborates to a bound).
2024-02-10 00:58:36 +01:00
Nicholas Nethercote bb60ded24b Loosen an assertion to account for stashed errors.
The meaning of this assertion changed in #120828 when the meaning of
`has_errors` changed to exclude stashed errors. Evidently the new
meaning is too restrictive.

Fixes #120856.
2024-02-10 09:14:59 +11:00
Caio 69a5264a52 Move some tests 2024-02-09 15:43:08 -03:00
Matthias Krüger aa0b0b65b3
Rollup merge of #120844 - compiler-errors:async-di, r=oli-obk
Build DebugInfo for async closures

The test is pretty bare, because I don't really know how to write debuginfo tests. I'd like to land this first, and then flesh it out correctly one it's no longer ICEing on master (which breaks people's ability to test using async closures).

r? oli-obk cc `@rust-lang/wg-debugging` (if any of y'all want to help me write a more fleshed out async closures test)
2024-02-09 19:21:19 +01:00
Matthias Krüger 251584581f
Rollup merge of #120836 - lcnr:param-env-hide-impl, r=BoxyUwU
hide impls if trait bound is proven from env

AVERT YOUR EYES `@compiler-errors`

fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/76 and https://github.com/rust-lang/trait-system-refactor-initiative/issues/12#issuecomment-1865234925

this is kinda ugly and I hate it, but I wasn't able to think of a cleaner approach for now. I am also unsure whether we have to refine this filtering later on, so by making the change pretty minimal it should be easier to improve going forward.

r? `@BoxyUwU`
2024-02-09 19:21:19 +01:00
Matthias Krüger d9a957b32a
Rollup merge of #120822 - gurry:120756-terse-non-prim-cast-diag, r=petrochenkov
Emit more specific diagnostics when enums fail to cast with `as`

Fixes #120756

Changes this diagnostic reported in the issue:
```
error[E0605]: non-primitive cast: `Bad` as `u32`
  --> src/main.rs:18:10
   |
18 |     dbg!(bad as u32);
   |          ^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
```

to this:
```
error[E0605]: non-primitive cast: `Bad` as `u32`
  --> src/main.rs:18:10
   |
18 |     dbg!(bad as u32);
   |          ^^^^^^^^^^ an `as` expression can be used to convert enum types to numeric types only if the enum type is unit-only or field-less
   |
   = note: see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information
```

This change is only for enums. The diagnostic remains unchanged for all other cases.
2024-02-09 19:21:18 +01:00
Matthias Krüger 99bafad6c2
Rollup merge of #120354 - lukas-code:metadata-normalize, r=lcnr
improve normalization of `Pointee::Metadata`

This PR makes it so that `<Wrapper<Tail> as Pointee>::Metadata` is normalized to `<Tail as Pointee>::Metadata` if we don't know `Wrapper<Tail>: Sized`. With that, the trait solver can prove projection predicates like `<Wrapper<Tail> as Pointee>::Metadata == <Tail as Pointee>::Metadata`, which makes it possible to use the metadata APIs to cast between the tail and the wrapper:

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

use std::ptr::{self, Pointee};

fn cast_same_meta<T: ?Sized, U: ?Sized>(ptr: *const T) -> *const U
where
    T: Pointee<Metadata = <U as Pointee>::Metadata>,
{
    let (thin, meta) = ptr.to_raw_parts();
    ptr::from_raw_parts(thin, meta)
}

struct Wrapper<T: ?Sized>(T);

fn cast_to_wrapper<T: ?Sized>(ptr: *const T) -> *const Wrapper<T> {
    cast_same_meta(ptr)
}
```

Previously, this failed to compile:

```
error[E0271]: type mismatch resolving `<Wrapper<T> as Pointee>::Metadata == <T as Pointee>::Metadata`
  --> src/lib.rs:16:5
   |
15 | fn cast_to_wrapper<T: ?Sized>(ptr: *const T) -> *const Wrapper<T> {
   |                    - found this type parameter
16 |     cast_same_meta(ptr)
   |     ^^^^^^^^^^^^^^ expected `Wrapper<T>`, found type parameter `T`
   |
   = note: expected associated type `<Wrapper<T> as Pointee>::Metadata`
              found associated type `<T as Pointee>::Metadata`
   = note: an associated type was expected, but a different one was found
```

(Yes, you can already do this with `as` casts. But using functions is so much  *safer* , because you can't change the metadata on accident.)

---

This PR essentially changes the built-in impls of `Pointee` from this:

```rust
// before

impl Pointee for u8 {
    type Metadata = ();
}

impl Pointee for [u8] {
    type Metadata = usize;
}

// ...

impl Pointee for Wrapper<u8> {
    type Metadata = ();
}

impl Pointee for Wrapper<[u8]> {
    type Metadata = usize;
}

// ...

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T: ?Sized> Pointee for Wrapper<T>
where
    Wrapper<T>: Sized
{
    type Metadata = ();
}

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T /*: Sized */> Pointee for T {
    type Metadata = ();
}
```

to this:

```rust
// after

impl Pointee for u8 {
    type Metadata = ();
}

impl Pointee for [u8] {
    type Metadata = usize;
}

// ...

impl<T: ?Sized> Pointee for Wrapper<T> {
    // in the old solver this will instead project to the "deep" tail directly,
    // e.g. `Wrapper<Wrapper<T>>::Metadata = T::Metadata`
    type Metadata = <T as Pointee>::Metadata;
}

// ...

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T /*: Sized */> Pointee for T {
    type Metadata = ();
}
```
2024-02-09 19:21:16 +01:00
Vadim Petrochenkov 8b6b9c5efc ast_lowering: Fix regression in `use ::{}` imports. 2024-02-09 20:17:48 +03:00
Michael Goulet 34ed554d81 Build DebugInfo for coroutine-closure 2024-02-09 16:01:29 +00:00
bors e28fae52d9 Auto merge of #120843 - matthiaskrgr:rollup-med37z5, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #113671 (Make privacy visitor use types more (instead of HIR))
 - #120308 (core/time: avoid divisions in Duration::new)
 - #120693 (Invert diagnostic lints.)
 - #120704 (A drive-by rewrite of `give_region_a_name()`)
 - #120809 (Use `transmute_unchecked` in `NonZero::new`.)
 - #120817 (Fix more `ty::Error` ICEs in MIR passes)
 - #120828 (Fix `ErrorGuaranteed` unsoundness with stash/steal.)
 - #120831 (Startup objects disappearing from sysroot)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-09 15:34:48 +00:00
Matthias Krüger 116efb5bb1
Rollup merge of #120817 - compiler-errors:more-mir-errors, r=oli-obk
Fix more `ty::Error` ICEs in MIR passes

Fixes #120791 - Add a check for `ty::Error` in the `ByMove` coroutine pass
Fixes #120816 - Add a check for `ty::Error` in the MIR validator

Also a drive-by fix for a FIXME I had asked oli to add

r? oli-obk
2024-02-09 14:41:51 +01:00
Matthias Krüger f41d0d90c2
Rollup merge of #113671 - oli-obk:normalize_weak_tys, r=petrochenkov
Make privacy visitor use types more (instead of HIR)

r? ``@petrochenkov``

This is a prerequisite to normalizing projections, as otherwise we have too many invalid bound vars (hir_ty_to_ty is creating types that have bound vars, but no binder).

The commits are still chaotic, I'm gonna clean them up, but I just wanted to let you know about the general direction and wondering if we could land this before adding normalization, as normalization is where behavioral changes happen, and I'd like to keep that part as minimal as possible.

[context can be found on zulip](https://rust-lang.zulipchat.com/#narrow/stream/315482-t-compiler.2Fetc.2Fopaque-types/topic/weak.20type.20aliases.20and.20privacy)
2024-02-09 14:41:48 +01:00
bors 8fb67fb37f Auto merge of #120594 - saethlin:delayed-debug-asserts, r=oli-obk
Toggle assert_unsafe_precondition in codegen instead of expansion

The goal of this PR is to make some of the unsafe precondition checks in the standard library available in debug builds. Some UI tests are included to verify that it does that.

The diff is large, but most of it is blessing mir-opt tests and I've also split up this PR so it can be reviewed commit-by-commit.

This PR:
1. Adds a new intrinsic, `debug_assertions` which is lowered to a new MIR NullOp, and only to a constant after monomorphization
2. Rewrites `assume_unsafe_precondition` to check the new intrinsic, and be monomorphic.
3. Skips codegen of the `assume` intrinsic in unoptimized builds, because that was silly before but with these checks it's *very* silly
4. The checks with the most overhead are `ptr::read`/`ptr::write` and `NonNull::new_unchecked`. I've simply added `#[cfg(debug_assertions)]` to the checks for `ptr::read`/`ptr::write` because I was unable to come up with any (good) ideas for decreasing their impact. But for `NonNull::new_unchecked` I found that the majority of callers can use a different function, often a safe one.

Yes, this PR slows down the compile time of some programs. But in our benchmark suite it's never more than 1% icount, and the average icount change in debug-full programs is 0.22%. I think that is acceptable for such an improvement in developer experience.

https://github.com/rust-lang/rust/issues/120539#issuecomment-1922687101
2024-02-09 13:33:38 +00:00
Guillaume Gomez 14e0dab96b Unify item relative path computation in one function 2024-02-09 14:16:37 +01:00
lcnr 5051637979 hide impls if trait bound is proven from env 2024-02-09 12:41:39 +01:00
Guillaume Gomez f3c24833c5 Add regression test for non local items link generation 2024-02-09 11:29:40 +01:00
Gurinder Singh 6e37f955e5 Emit more specific diagnostics when enums fail to cast with `as` 2024-02-09 09:19:44 +05:30
Ben Kimock 611c3cb561 Bless/fix tests 2024-02-08 19:56:30 -05:00
Ben Kimock 9e1b2d909b Add new ui tests 2024-02-08 19:56:30 -05:00
Michael Goulet e32c1ddc52 Don't ice in validation when error body is created 2024-02-09 00:40:43 +00:00
Michael Goulet 698a3c7ade Don't ICE in ByMoveBody when coroutine is tainted 2024-02-09 00:36:30 +00:00
Michael Goulet 7a63d3f16a Add tests for untested capabilities 2024-02-09 00:13:52 +00:00
Michael Goulet 22d582a38d For a rigid projection, recursively look at the self type's item bounds 2024-02-09 00:13:51 +00:00
Matthias Krüger ed528515d0
Rollup merge of #120801 - oli-obk:drop_recursion_ice, r=Nilstrieb
Avoid ICE in drop recursion check in case of invalid drop impls

fixes #120787
2024-02-08 20:35:01 +01:00
Matthias Krüger 949e55299d
Rollup merge of #120775 - Nadrieril:more-min_exh_pats, r=compiler-errors
Make `min_exhaustive_patterns` match `exhaustive_patterns` better

Split off from https://github.com/rust-lang/rust/pull/120742.

There remained two edge cases where `min_exhaustive_patterns` wasn't behaving like `exhaustive_patterns`. This fixes them, and tests the feature in a bunch more cases. I essentially went through all uses of `exhaustive_patterns` to see which ones would be interesting to compare between the two features.

r? `@compiler-errors`
2024-02-08 20:34:59 +01:00
Michael Goulet 540be28f6c sort suggestions for object diagnostic 2024-02-08 18:56:52 +00:00
Oli Scherer ad511ef92e Avoid ICE in drop recursion check in case of invalid drop impls 2024-02-08 17:33:04 +00:00
Michael Goulet 9322882ade Add a couple more tests 2024-02-08 15:46:07 +00:00
Michael Goulet 3bb384aad6 Prefer AsyncFn* over Fn* for coroutine-closures 2024-02-08 15:46:00 +00:00
Oli Scherer d80d7ea1e3 Add some tests for associated type normalization edge cases 2024-02-08 12:28:35 +00:00
bors 1280928a99 Auto merge of #120767 - matthiaskrgr:rollup-0k8ib1c, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #119592 (resolve: Unload speculatively resolved crates before freezing cstore)
 - #120103 (Make it so that async-fn-in-trait is compatible with a concrete future in implementation)
 - #120206 (hir: Make sure all `HirId`s have corresponding HIR `Node`s)
 - #120214 (match lowering: consistently lower bindings deepest-first)
 - #120688 (GVN: also turn moves into copies with projections)
 - #120702 (docs: also check the inline stmt during redundant link check)
 - #120727 (exhaustiveness: Prefer "`0..MAX` not covered" to "`_` not covered")
 - #120734 (Add `SubdiagnosticMessageOp` as a trait alias.)
 - #120739 (improve pretty printing for associated items in trait objects)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-08 12:14:19 +00:00
Nadrieril 4733b1bba5 Test `min_exhaustive_patterns` in more cases 2024-02-08 11:48:38 +01:00
Oli Scherer eab2adb660 Continue to borrowck even if there were previous errors 2024-02-08 08:10:43 +00:00
Matthias Krüger a059dd88bf
Rollup merge of #120739 - lukas-code:pp-dyn-assoc, r=compiler-errors
improve pretty printing for associated items in trait objects

* Don't print a binder in front of associated items, because it's not valid syntax.
  * e.g. print `dyn for<'a> Trait<'a, Assoc = &'a u8>` instead of `dyn for<'a> Trait<'a, for<'a> Assoc = &'a u8>`.
* Don't print associated items that are implied by a supertrait bound.
  * e.g. if we have `trait Sub: Super<Assoc = u8> {}`, then just print `dyn Sub` instead of `dyn Sub<Assoc = u8>`.

I've added the test in the first commit, so you can see the diff of the compiler output in the second commit.
2024-02-08 09:06:36 +01:00
Matthias Krüger 87e1e05aa1
Rollup merge of #120734 - nnethercote:SubdiagnosticMessageOp, r=compiler-errors
Add `SubdiagnosticMessageOp` as a trait alias.

It avoids a lot of repetition.

r? matthewjasper
2024-02-08 09:06:36 +01:00
Matthias Krüger 5157190008
Rollup merge of #120727 - Nadrieril:tweak-int-reporting, r=compiler-errors
exhaustiveness: Prefer "`0..MAX` not covered" to "`_` not covered"

There was an exception when reporting integer ranges as missing, it's been there for as long as I can remember. This PR removes it. I think it's nicer to report "`0..MAX` not covered" than "`_` not covered". This also makes it consistent with enums, where we report individual enum variants in this case (as showcased in the rest of the `empty-match.rs` test).

r? ``@estebank``
2024-02-08 09:06:35 +01:00