Commit Graph

7416 Commits

Author SHA1 Message Date
bors
591ecb88df Auto merge of #128742 - RalfJung:miri-vtable-uniqueness, r=saethlin
miri: make vtable addresses not globally unique

Miri currently gives vtables a unique global address. That's not actually matching reality though. So this PR enables Miri to generate different addresses for the same type-trait pair.

To avoid generating an unbounded number of `AllocId` (and consuming unbounded amounts of memory), we use the "salt" technique that we also already use for giving constants non-unique addresses: the cache is keyed on a "salt" value n top of the actually relevant key, and Miri picks a random salt (currently in the range `0..16`) each time it needs to choose an `AllocId` for one of these globals -- that means we'll get up to 16 different addresses for each vtable. The salt scheme is integrated into the global allocation deduplication logic in `tcx`, and also used for functions and string literals. (So this also fixes the problem that casting the same function to a fn ptr over and over will consume unbounded memory.)

r? `@saethlin`
Fixes https://github.com/rust-lang/miri/issues/3737
2024-08-13 04:32:34 +00:00
Matthias Krüger
85eb465a10
Rollup merge of #128912 - compiler-errors:do-not-recommend-impl, r=lcnr
Store `do_not_recommend`-ness in impl header

Alternative to #128674

It's less flexible, but also less invasive. Hopefully it's also performant. I'd recommend we think separately about the design for how to gate arbitrary diagnostic attributes moving forward.
2024-08-12 23:10:51 +02:00
Matthias Krüger
4c49418472
Rollup merge of #128712 - compiler-errors:normalize-borrowck, r=lcnr
Normalize struct tail properly for `dyn` ptr-to-ptr casting in new solver

Realized that the new solver didn't handle ptr-to-ptr casting correctly.

r? lcnr

Built on #128694
2024-08-12 23:10:50 +02:00
Guillaume Gomez
7c6dca9050
Rollup merge of #128978 - compiler-errors:assert-matches, r=jieyouxu
Use `assert_matches` around the compiler more

It's a useful assertion, especially since it actually prints out the LHS.
2024-08-12 17:09:19 +02:00
Michael Goulet
f15997ffec Remove struct_tail_no_normalization 2024-08-11 19:40:03 -04:00
Michael Goulet
b5d2079fb9 Rename normalization functions to raw 2024-08-11 19:40:03 -04:00
Michael Goulet
c361c924a0 Use assert_matches around the compiler 2024-08-11 12:25:39 -04:00
bors
04ba50e823 Auto merge of #128927 - GuillaumeGomez:rollup-ei2lr0f, r=GuillaumeGomez
Rollup of 8 pull requests

Successful merges:

 - #128273 (Improve `Ord` violation help)
 - #128807 (run-make: explaing why fmt-write-bloat is ignore-windows)
 - #128903 (rustdoc-json-types `Discriminant`: fix typo)
 - #128905 (gitignore: Add Zed and Helix editors)
 - #128908 (diagnostics: do not warn when a lifetime bound infers itself)
 - #128909 (Fix dump-ice-to-disk for RUSTC_ICE=0 users)
 - #128910 (Differentiate between methods and associated functions in diagnostics)
 - #128923 ([rustdoc] Stop showing impl items for negative impls)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-08-10 15:13:38 +00:00
Guillaume Gomez
50e9fd1a1d
Rollup merge of #128910 - estebank:assoc-fn, r=compiler-errors
Differentiate between methods and associated functions in diagnostics

Accurately refer to assoc fn without receiver as assoc fn instead of methods. Add `AssocItem::descr` method to centralize where we call methods and associated functions.
2024-08-10 16:23:55 +02:00
bors
8291d68d92 Auto merge of #122792 - Nadrieril:stabilize-min-exh-pats2, r=fee1-dead
Stabilize `min_exhaustive_patterns`

## Stabilisation report

I propose we stabilize the [`min_exhaustive_patterns`](https://github.com/rust-lang/rust/issues/119612) language feature.

With this feature, patterns of empty types are considered unreachable when matched by-value. This allows:
```rust
enum Void {}
fn foo() -> Result<u32, Void>;

fn main() {
  let Ok(x) = foo();
  // also
  match foo() {
    Ok(x) => ...,
  }
}
```

This is a subset of the long-unstable [`exhaustive_patterns`](https://github.com/rust-lang/rust/issues/51085) feature. That feature is blocked because omitting empty patterns is tricky when *not* matched by-value. This PR stabilizes the by-value case, which is not tricky.

The not-by-value cases (behind references, pointers, and unions) stay as they are today, e.g.
```rust
enum Void {}
fn foo() -> Result<u32, &Void>;

fn main() {
  let Ok(x) = foo(); // ERROR: missing `Err(_)`
}
```

The consequence on existing code is some extra "unreachable pattern" warnings. This is fully backwards-compatible.

### Comparison with today's rust

This proposal only affects match checking of empty types (i.e. types with no valid values). Non-empty types behave the same with or without this feature. Note that everything below is phrased in terms of `match` but applies equallly to `if let` and other pattern-matching expressions.

To be precise, a visibly empty type is:
- an enum with no variants;
- the never type `!`;
- a struct with a *visible* field of a visibly empty type (and no #[non_exhaustive] annotation);
- a tuple where one of the types is visibly empty;
- en enum with all variants visibly empty (and no `#[non_exhaustive]` annotation);
- a `[T; N]` with `N != 0` and `T` visibly empty;
- all other types are nonempty.

(An extra change was proposed below: that we ignore #[non_exhaustive] for structs since adding fields cannot turn an empty struct into a non-empty one)

For normal types, exhaustiveness checking requires that we list all variants (or use a wildcard). For empty types it's more subtle: in some cases we require a `_` pattern even though there are no valid values that can match it. This is where the difference lies regarding this feature.

#### Today's rust

Under today's rust, a `_` is required for all empty types, except specifically: if the matched expression is of type `!` (the never type) or `EmptyEnum` (where `EmptyEnum` is an enum with no variants), then the `_` is not required.

```rust
let foo: Result<u32, !> = ...;
match foo {
    Ok(x) => ...,
    Err(_) => ..., // required
}
let foo: Result<u32, &!> = ...;
match foo {
    Ok(x) => ...,
    Err(_) => ..., // required
}
let foo: &! = ...;
match foo {
    _ => ..., // required
}
fn blah(foo: (u32, !)) {
    match foo {
        _ => ..., // required
    }
}
unsafe {
    let ptr: *const ! = ...;
    match *ptr {} // allowed
    let ptr: *const (u32, !) = ...;
    match *ptr {
        (x, _) => { ... } // required
    }
    let ptr: *const Result<u32, !> = ...;
    match *ptr {
        Ok(x) => { ... }
        Err(_) => { ... } // required
    }
}
```

#### After this PR

After this PR, a pattern of an empty type can be omitted if (and only if):
- the match scrutinee expression has type  `!` or `EmptyEnum` (like before);
- *or* the empty type is matched by value (that's the new behavior).

In all other cases, a `_` is required to match on an empty type.

```rust
let foo: Result<u32, !> = ...;
match foo {
    Ok(x) => ..., // `Err` not required
}
let foo: Result<u32, &!> = ...;
match foo {
    Ok(x) => ...,
    Err(_) => ..., // required because `!` is under a dereference
}
let foo: &! = ...;
match foo {
    _ => ..., // required because `!` is under a dereference
}
fn blah(foo: (u32, !)) {
    match foo {} // allowed
}
unsafe {
    let ptr: *const ! = ...;
    match *ptr {} // allowed
    let ptr: *const (u32, !) = ...;
    match *ptr {
        (x, _) => { ... } // required because the matched place is under a (pointer) dereference
    }
    let ptr: *const Result<u32, !> = ...;
    match *ptr {
        Ok(x) => { ... }
        Err(_) => { ... } // required because the matched place is under a (pointer) dereference
    }
}
```

### Documentation

The reference does not say anything specific about exhaustiveness checking, hence there is nothing to update there. The nomicon does, I opened https://github.com/rust-lang/nomicon/pull/445 to reflect the changes.

### Tests

The relevant tests are in `tests/ui/pattern/usefulness/empty-types.rs`.

### Unresolved Questions

None that I know of.

try-job: dist-aarch64-apple
2024-08-10 12:48:29 +00:00
bors
48090b11b5 Auto merge of #128746 - compiler-errors:cache-super-outlives, r=lcnr
Cache supertrait outlives of impl header for soundness check

This caches the results of computing the transitive supertraits of an impl and filtering it to its outlives obligations. This is purely an optimization to improve https://github.com/rust-lang/rust/pull/124336.
2024-08-10 10:22:06 +00:00
Nadrieril
c256de2253 Update std and compiler 2024-08-10 12:07:17 +02:00
bors
7347f8e4e0 Auto merge of #128740 - compiler-errors:generic-preds, r=estebank
Stop unnecessarily taking GenericPredicates by `&self`

This results in overcapturing in edition 2024, and is unnecessary since `GenericPredicates: Copy`.
2024-08-10 07:54:26 +00:00
Michael Goulet
ed7bdbb17b Store do_not_recommend-ness in impl header 2024-08-09 22:02:20 -04:00
Esteban Küber
860c8cdeaf Differentiate between methods and associated functions
Accurately refer to assoc fn without receiver as assoc fn instead of methods.
Add `AssocItem::descr` method to centralize where we call methods and associated functions.
2024-08-10 00:54:16 +00:00
bors
899eb03926 Auto merge of #128703 - compiler-errors:normalizing-tails, r=lcnr
Miscellaneous improvements to struct tail normalization

1. Make checks for foreign tails more accurate by normalizing the struct tail. I didn't write a test for this one.
2. Normalize when computing struct tail for `offset_of` for slice/str. This fixes the new solver only.
3. Normalizing when computing tails for disaligned reference check. This fixes both solvers.

r? lcnr
2024-08-09 11:36:01 +00:00
Michael Goulet
b916431976 Rename struct_tail_erasing_lifetimes to struct_tail_for_codegen 2024-08-08 12:15:16 -04:00
Alex Macleod
9289f5691b Only suggest #[allow] for --warn and --deny lint level flags 2024-08-08 13:09:58 +00:00
Caleb Zulawski
8818c95528 Disallow enabling features without their implied features 2024-08-07 00:45:00 -04:00
Caleb Zulawski
83276f5680 Hide implicit target features from diagnostics when possible 2024-08-07 00:43:52 -04:00
Caleb Zulawski
74653b61a6 Add implied target features to target_feature attribute 2024-08-07 00:41:48 -04:00
Michael Goulet
79228526bf Cache supertrait outlives of impl header for soundness check 2024-08-06 13:33:32 -04:00
Ralf Jung
5cab8ae4a4 miri: make vtable addresses not globally unique 2024-08-06 19:09:31 +02:00
Michael Goulet
cc96efd7e3 Stop unnecessarily taking GenericPredicates by &self 2024-08-06 11:54:45 -04:00
bors
8f63e9f873 Auto merge of #128441 - Bryanskiy:delegation-perf, r=petrochenkov
Delegation: second attempt to improve perf

Possible perf fix for https://github.com/rust-lang/rust/pull/125929

r? `@petrochenkov`
2024-08-03 23:45:22 +00:00
Matthias Krüger
66d243f61b
Rollup merge of #128494 - RalfJung:mir-lazy-lists, r=compiler-errors
MIR required_consts, mentioned_items: ensure we do not forget to fill these lists

Bodies initially get created with empty required_consts and mentioned_items, but at some point those should be filled. Make sure we notice when that is forgotten.
2024-08-02 06:43:44 +02:00
Ralf Jung
6d312d7bd1 MIR required_consts, mentioned_items: ensure we do not forget to fill these lists 2024-08-01 15:49:25 +02:00
Ralf Jung
5d5c97aad7 interpret: simplify pointer arithmetic logic 2024-08-01 14:25:19 +02:00
Ralf Jung
de78cb56b2 on a signed deref check, mention the right pointer in the error 2024-08-01 14:25:19 +02:00
Bryanskiy
9b097b2d44 Delegation: second attempt to improve perf 2024-07-31 18:58:04 +03:00
Zalathar
dd5a8d7714 Use a separate pattern type for rustc_pattern_analysis diagnostics
The pattern-analysis code needs to print patterns, as part of its user-visible
diagnostics. But it never actually tries to print "real" patterns! Instead, it
only ever prints synthetic patterns that it has reconstructed from its own
internal represenations.

We can therefore simultaneously remove two obstacles to changing `thir::Pat`,
by having the pattern-analysis code use its own dedicated type for building
printable patterns, and then making `thir::Pat` not printable at all.
2024-07-31 16:03:27 +10:00
Zalathar
a9ea85e044 Revert "Make thir::Pat not implement fmt::Display directly"
This reverts commit ae0ec731a8.

The original change in #128304 was intended to be a step towards being able to
print `thir::Pat` even after switching to `PatId`.

But because the only patterns that need to be printed are the synthetic ones
created by pattern analysis (for diagnostic purposes only), it makes more sense
to completely separate the printable patterns from the real THIR patterns.
2024-07-31 16:00:52 +10:00
bors
1ddedbaa59 Auto merge of #125929 - Bryanskiy:delegation-generics-3, r=petrochenkov
Delegation: support generics for delegation from free functions

(The PR was split from https://github.com/rust-lang/rust/pull/123958, explainer - https://github.com/Bryanskiy/posts/blob/master/delegation%20in%20generic%20contexts.md)

This PR implements generics inheritance from free functions to free functions and trait methods.

#### free functions to free functions:

```rust
fn to_reuse<T: Clone>(_: T) {}

reuse to_reuse as bar;
// desugaring:
fn bar<T: Clone>(x: T) {
  to_reuse(x)
}
```

Generics, predicates and signature are simply copied. Generic arguments in paths are ignored during generics inheritance:

```rust
fn to_reuse<T: Clone>(_: T) {}

reuse to_reuse::<u8> as bar;
// desugaring:
fn bar<T: Clone>(x: T) {
  to_reuse::<u8>(x) // ERROR: mismatched types
}
```

Due to implementation limitations callee path is lowered without modifications. Therefore, it is a compilation error at the moment.

#### free functions to trait methods:

```rust
trait Trait<'a, A> {
    fn foo<'b, B>(&self, x: A, y: B) {...}
}

reuse Trait::foo;
// desugaring:
fn foo<'a, 'b, This: Trait<'a, A>, A, B>(this: &This, x: A, y: B) {
  Trait::foo(this, x, y)
}
```

The inheritance is similar to the previous case but with some corrections:

- `Self` parameter converted into `T: Trait`
- generic parameters need to be reordered so that lifetimes go first

Arguments are similarly ignored.

---

In the future, we plan to  support generic inheritance for delegating from all contexts to all contexts (from free/trait/impl to free/trait /impl). These cases were considered first as the simplest from the implementation perspective.
2024-07-30 10:39:33 +00:00
Bryanskiy
f2f9aab380 Delegation: support generics for delegation from free functions 2024-07-29 20:04:55 +03:00
Matthias Krüger
d73decdaad
Rollup merge of #128304 - Zalathar:thir-pat-display, r=Nadrieril
Isolate the diagnostic code that expects `thir::Pat` to be printable

Currently, `thir::Pat` implements `fmt::Display` (and `IntoDiagArg`) directly, for use by a few diagnostics.

That makes it tricky to experiment with alternate representations for THIR patterns, because the patterns currently need to be printable on their own. That immediately rules out possibilities like storing subpatterns as a `PatId` index into a central list (instead of the current directly-owned `Box<Pat>`).

This PR therefore takes an incremental step away from that obstacle, by removing `thir::Pat` from diagnostic structs in `rustc_pattern_analysis`, and hiding the pattern-printing process behind a single public `Pat::to_string` method. Doing so makes it easier to identify and update the code that wants to print patterns, and gives a place to pass in additional context in the future if necessary.

---

I'm currently not sure whether switching over to `PatId` is actually desirable or not, but I think this change makes sense on its own merits, by reducing the coupling between `thir::Pat` and the pattern-analysis error types.
2024-07-29 11:42:34 +02:00
Matthias Krüger
eb8114bad7
Rollup merge of #128277 - RalfJung:offset_from_wildcard, r=oli-obk
miri: fix offset_from behavior on wildcard pointers

offset_from wouldn't behave correctly when the "end" pointer was a wildcard pointer (result of an int2ptr cast) just at the end of the allocation. Fix that by expressing the "same allocation" check in terms of two `check_ptr_access_signed` instead of something specific to offset_from, which is both more canonical and works better with wildcard pointers.

The second commit just improves diagnostics: I wanted the "pointer is dangling (has no provenance)" message to say how many bytes of memory it expected to see (since if it were 0 bytes, this would actually be legal, so it's good to tell the user that it's not 0 bytes). And then I was annoying that the error looks so different for when you deref a dangling pointer vs an out-of-bounds pointer so I made them more similar.

Fixes https://github.com/rust-lang/miri/issues/3767
2024-07-29 11:42:34 +02:00
Zalathar
ae0ec731a8 Make thir::Pat not implement fmt::Display directly
This gives a clearer view of the (diagnostic) code that expects to be able to
print THIR patterns, and makes it possible to experiment with requiring some
kind of context (for ID lookup) when printing patterns.
2024-07-29 14:56:50 +10:00
Nicholas Nethercote
84ac80f192 Reformat use declarations.
The previous commit updated `rustfmt.toml` appropriately. This commit is
the outcome of running `x fmt --all` with the new formatting options.
2024-07-29 08:26:52 +10:00
Zalathar
e1fc4a997d Don't store thir::Pat in error structs
In several cases this avoids the need to clone the underlying pattern, and then
print the clone later.
2024-07-28 21:58:44 +10:00
Ralf Jung
f8ebe8d783 improve dangling/oob errors and make them more uniform 2024-07-27 21:12:54 +02:00
bors
2d5a628a1d Auto merge of #128165 - saethlin:optimize-clone-shims, r=compiler-errors
Let InstCombine remove Clone shims inside Clone shims

The Clone shims that we generate tend to recurse into other Clone shims, which gets very silly very quickly. Here's our current state: https://godbolt.org/z/E69YeY8eq

So I've added InstSimplify to the shims optimization passes, and improved `is_trivially_pure_clone_copy` so that it can delete those calls inside the shim. This makes the shim way smaller because most of its size is the required ceremony for unwinding.

This change also completely breaks the UI test added for https://github.com/rust-lang/rust/issues/104870. With this PR, that program ICEs in MIR type checking because `is_trivially_pure_clone_copy` and the trait solver disagree on whether `*mut u8` is `Copy`. And adding the requisite `Copy` impl to make them agree makes the test not generate any diagnostics. Considering that I spent most of my time on this PR fixing `#![no_core]` tests, I would prefer to just delete this one. The maintenance burden of `#![no_core]` is uniquely high because when they break they tend to break in very confusing ways.

try-job: x86_64-mingw
2024-07-26 13:13:04 +00:00
bors
2f26b2a99a Auto merge of #127042 - GrigorenkoPV:derivative, r=compiler-errors
Switch from `derivative` to `derive-where`

This is a part of the effort to get rid of `syn 1.*` in compiler's dependencies: #109302

Derivative has not been maintained in nearly 3 years[^1]. It also depends on `syn 1.*`.

This PR replaces `derivative` with `derive-where`[^2], a not dead alternative, which uses `syn 2.*`.

A couple of `Debug` formats have changed around the skipped fields[^3], but I doubt this is an issue.

[^1]: https://github.com/mcarton/rust-derivative/issues/117
[^2]: https://lib.rs/crates/derive-where
[^3]: See the changes in `tests/ui`
2024-07-25 22:50:58 +00:00
Ben Kimock
a7d57aa7c8 Let InstCombine remove Clone shims inside Clone shims
Co-authored-by: scottmcm <scottmcm@users.noreply.github.com>
2024-07-25 15:14:42 -04:00
Matthias Krüger
2ff33bb1df
Rollup merge of #127717 - gurry:127441-stray-impl-sugg, r=compiler-errors
Fix malformed suggestion for repeated maybe unsized bounds

Fixes #127441

Now when we encounter something like `foo(a : impl ?Sized + ?Sized)`, instead of suggesting removal of both bounds and leaving `foo(a: impl )` behind, we suggest changing the first bound to `Sized` and removing the second bound, resulting in `foo(a: impl Sized)`.

Although the issue was reported for impl trait types, it also occurred with regular param bounds. So if we encounter `foo<T: ?Sized + ?Sized>(a: T)` we now detect that all the bounds are `?Sized` and therefore emit the suggestion to remove the entire predicate `: ?Sized + ?Sized` resulting in `foo<T>(a: T)`.

Lastly, if we encounter a situation where some of the bounds are something other than `?Sized`, then we emit separate removal suggestions for each `?Sized` bound. E.g. if we see `foo(a: impl ?Sized + Bar + ?Sized)` or `foo<T: ?Sized + Bar + ?Sized>(a: T)` we emit suggestions such that the user will be left with `foo(a : impl Bar)` or `foo<T: Bar>(a: T)` respectively.
2024-07-24 22:22:16 +02:00
Oli Scherer
acba6449f8 Do not try to reveal hidden types when trying to prove Freeze in the defining scope 2024-07-24 16:00:48 +00:00
bors
ae7b1c1916 Auto merge of #127442 - saethlin:alloc-decoding-lock, r=oli-obk
Try to fix ICE from re-interning an AllocId with different allocation contents

As far as I can tell, based on my investigation in https://github.com/rust-lang/rust/issues/126741, the racy decoding scheme implemented here was never fully correct, but the arrangement of Allocations that's required to ICE the compiler requires some very specific MIR optimizations to create. As far as I can tell, GVN likes to create the problematic pattern, which is why we're noticing this problem now.

So the solution here is to not do racy decoding. If two threads race to decoding an AllocId, one of them is going to sit on a lock until the other is done.
2024-07-22 05:56:05 +00:00
bors
0f8534e79e Auto merge of #120812 - compiler-errors:impl-sorting, r=lcnr
Remove unnecessary impl sorting in queries and metadata

Removes unnecessary impl sorting because queries already return their keys in HIR definition order: https://github.com/rust-lang/rust/issues/120371#issuecomment-1926422838

r? `@cjgillot` or `@lcnr` -- unless I totally misunderstood what was being asked for here? 😆

fixes #120371
2024-07-21 22:43:47 +00:00
Ben Kimock
107cf981d5 Explain why the new setup can't deadlock 2024-07-21 12:31:25 -04:00
bors
2e6fc42541 Auto merge of #128002 - matthiaskrgr:rollup-21p0cue, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #127463 ( use precompiled rustdoc with CI rustc)
 - #127779 (Add a hook for `should_codegen_locally`)
 - #127843 (unix: document unsafety for std `sig{action,altstack}`)
 - #127873 (kmc-solid: `#![forbid(unsafe_op_in_unsafe_fn)]`)
 - #127917 (match lowering: Split `finalize_or_candidate` into more coherent methods)
 - #127964 (run_make_support: skip rustfmt for lib.rs)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-20 13:26:11 +00:00
Matthias Krüger
9a6f8ccf3a
Rollup merge of #127779 - momvart:should_codegen_hook, r=cjgillot
Add a hook for `should_codegen_locally`

This PR lifts the module-local function `should_codegen_locally` to `TyCtxt` as a hook.
In addition to monomorphization, this function is used for checking the dependency of `compiler_builtins` on other libraries. Moving this function to the hooks also makes overriding it possible for the tools that use the rustc interface.
2024-07-20 13:24:52 +02:00