Commit Graph

7531 Commits

Author SHA1 Message Date
Matthias Krüger
2a321e14a5
Rollup merge of #129527 - compiler-errors:lint-nit, r=Nadrieril
Don't use `TyKind` in a lint

Allows us to remove an inherent method from `TyKind` from the type ir crate.
2024-08-31 10:08:53 +02:00
Strophox
7fde02ea53 enable Miri to pass const pointers through FFI
Co-authored-by: Ralf Jung <post@ralfj.de>
2024-08-30 16:05:53 +02:00
Rémy Rakic
e0bb1c7291 make -Z mir-include-spans a dedicated enum
We want to allow setting this on the CLI, override it only in MIR
passes, and disable it altogether in mir-opt tests.

The default value is "only for NLL MIR dumps", which is considered off
for all intents and purposes, except for `rustc_borrowck` when an NLL
MIR dump is requested.
2024-08-30 07:14:19 +00:00
Rémy Rakic
c646b46b52 introduce PrettyPrintMirOptions for cosmetic MIR dump options
initially starting with `-Z mir-include-spans` because we want them in
the NLL mir dump pass
2024-08-30 07:07:28 +00:00
Nicholas Nethercote
938daf6033 Add warn(unreachable_pub) to rustc_middle.
I am surprised the diff is so small for this enormous crate.
2024-08-29 20:13:06 +10:00
Michael Goulet
92004523db Stop using ty::GenericPredicates for non-predicates_of queries 2024-08-29 00:17:40 -04:00
Jubilee
9d5f794312
Rollup merge of #129401 - workingjubilee:partial-initialization-of-stabilization, r=dtolnay,joboet
Partially stabilize `feature(new_uninit)`

Finished comment period: https://github.com/rust-lang/rust/issues/63291#issuecomment-2183022955

The following API has been stabilized from https://github.com/rust-lang/rust/issues/63291

```rust
impl<T> Box<T> { pub fn new_uninit() -> Box<MaybeUninit<T>> {…} }
impl<T> Rc<T> { pub fn new_uninit() -> Rc<MaybeUninit<T>> {…} }
impl<T> Arc<T> { pub fn new_uninit() -> Arc<MaybeUninit<T>> {…} }

impl<T> Box<[T]> { pub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>]> {…} }
impl<T> Rc<[T]> { pub fn new_uninit_slice(len: usize) -> Rc<[MaybeUninit<T>]> {…} }
impl<T> Arc<[T]> { pub fn new_uninit_slice(len: usize) -> Arc<[MaybeUninit<T>]> {…} }

impl<T> Box<MaybeUninit<T>> { pub unsafe fn assume_init(self) -> Box<T> {…} }
impl<T> Box<[MaybeUninit<T>]> { pub unsafe fn assume_init(self) -> Box<[T]> {…} }
impl<T> Rc<MaybeUninit<T>> { pub unsafe fn assume_init(self) -> Rc<T> {…} }
impl<T> Rc<[MaybeUninit<T>]> { pub unsafe fn assume_init(self) -> Rc<[T]> {…} }
impl<T> Arc<MaybeUninit<T>> { pub unsafe fn assume_init(self) -> Arc<T> {…} }
impl<T> Arc<[MaybeUninit<T>]> { pub unsafe fn assume_init(self) -> Arc<[T]> {…} }
```

The remaining API is split between new issues
- `new_zeroed_alloc`: https://github.com/rust-lang/rust/issues/129396
- `box_uninit_write`: https://github.com/rust-lang/rust/issues/129397

All relevant code is thus either stabilized or split out of that issue, so this closes #63291 as, with the FCP concluded, that issue has served its purpose.

try-job: x86_64-rust-for-linux
2024-08-28 19:12:52 -07:00
bors
acb4e8b625 Auto merge of #127537 - veluca93:struct_tf, r=BoxyUwU
Implement a first version of RFC 3525: struct target features

This PR is an attempt at implementing https://github.com/rust-lang/rfcs/pull/3525, behind a feature gate `struct_target_features`.

There's obviously a few tasks that ought to be done before this is merged; in no particular order:
- add proper error messages
- add tests
- create a tracking issue for the RFC
- properly serialize/deserialize the new target_features field in `rmeta` (assuming I even understood that correctly :-))

That said, as I am definitely not a `rustc` expert, I'd like to get some early feedback on the overall approach before fixing those things (and perhaps some pointers for `rmeta`...), hence this early PR :-)

Here's an example piece of code that I have been using for testing - with the new code, the calls to intrinsics get correctly inlined:
```rust
#![feature(struct_target_features)]

use std::arch::x86_64::*;

/*
// fails to compile
#[target_feature(enable = "avx")]
struct Invalid(u32);
*/

#[target_feature(enable = "avx")]
struct Avx {}

#[target_feature(enable = "sse")]
struct Sse();

/*
// fails to compile
extern "C" fn bad_fun(_: Avx) {}
*/

/*
// fails to compile
#[inline(always)]
fn inline_fun(_: Avx) {}
*/

trait Simd {
    fn do_something(&self);
}

impl Simd for Avx {
    fn do_something(&self) {
        unsafe {
            println!("{:?}", _mm256_setzero_ps());
        }
    }
}

impl Simd for Sse {
    fn do_something(&self) {
        unsafe {
            println!("{:?}", _mm_setzero_ps());
        }
    }
}

struct WithAvx {
    #[allow(dead_code)]
    avx: Avx,
}

impl Simd for WithAvx {
    fn do_something(&self) {
        unsafe {
            println!("{:?}", _mm256_setzero_ps());
        }
    }
}

#[inline(never)]
fn dosomething<S: Simd>(simd: &S) {
    simd.do_something();
}

fn main() {
    /*
    // fails to compile
    Avx {};
    */

    if is_x86_feature_detected!("avx") {
        let avx = unsafe { Avx {} };
        dosomething(&avx);
        dosomething(&WithAvx { avx });
    }
    if is_x86_feature_detected!("sse") {
        dosomething(&unsafe { Sse {} })
    }
}
```

Tracking:

- https://github.com/rust-lang/rust/issues/129107
2024-08-28 22:54:55 +00:00
Zalathar
46e1b5b6dd coverage: Rename CodeRegion to SourceRegion
LLVM uses the word "code" to refer to a particular kind of coverage mapping.
This unrelated usage of the word is confusing, and makes it harder to introduce
types whose names correspond to the LLVM classification of coverage kinds.
2024-08-28 22:17:42 +10:00
Zalathar
f61f34f4b8 coverage: CodeRegion is never stored in an arena
This might have been left over when coverage regions were stored in individual
MIR statements, instead of a separate table attached to the MIR body.
2024-08-28 22:03:48 +10:00
Luca Versari
7eb4cfeace Implement RFC 3525. 2024-08-28 09:54:23 +02:00
bors
748c54848d Auto merge of #129546 - compiler-errors:no-pred-on, r=fee1-dead
Get rid of `predicates_defined_on`

This is the uncontroversial part of #129532. This simply inlines the `predicates_defined_on` into into `predicates_of`. Nothing should change here logically.
2024-08-28 04:41:43 +00:00
bors
d9a2cc4dae Auto merge of #128506 - compiler-errors:by-move-body, r=cjgillot
Stop storing a special inner body for the coroutine by-move body for async closures

...and instead, just synthesize an item which is treated mostly normally by the MIR pipeline.

This PR does a few things:
* We synthesize a new `DefId` for the by-move body of a closure, which has its `mir_built` fed with the output of the `ByMoveBody` MIR transformation, and some other relevant queries.
* This has the `DefKind::ByMoveBody`, which we use to distinguish it from "real" bodies (that come from HIR) which need to be borrowck'd. Introduce `TyCtxt::is_synthetic_mir` to skip over `mir_borrowck` which is called by `mir_promoted`; borrowck isn't really possible to make work ATM since it heavily relies being called on a body generated from HIR, and is redundant by the construction of the by-move-body.
* Remove the special `PassManager` hacks for handling the inner `by_move_body` stored within the coroutine's mir body. Instead, this body is fed like a regular MIR body, so it's goes through all of the `tcx.*_mir` stages normally (build -> promoted -> ...etc... -> optimized) .
* Remove the `InstanceKind::ByMoveBody` shim, since now we have a "regular" def id, we can just use `InstanceKind::Item`. This also allows us to remove the corresponding hacks from codegen, such as in `fn_sig_for_fn_abi` .

Notable remarks:
* ~~I know it's kind of weird to be using `DefKind::Closure` here, since it's not a distinct closure but just a new MIR body. I don't believe it really matters, but I could also use a different `DefKind`... maybe one that we could use for synthetic MIR bodies in general?~~ edit: We're doing this now.
2024-08-27 23:30:24 +00:00
Jubilee Young
2535a0f776 compiler: Remove feature(new_uninit) 2024-08-27 10:17:05 -07:00
Michael Goulet
38e62b9841 Use unsafe extern blocks throughout the compiler 2024-08-26 19:51:05 -04:00
Michael Goulet
4609841c07 Stop using a special inner body for the coroutine by-move body for async closures 2024-08-26 18:44:19 -04:00
Matthias Krüger
d6a3aa4fc4
Rollup merge of #129590 - compiler-errors:ref-tykind, r=fmease
Avoid taking reference of &TyKind

It's already a ref anyways. Just a tiny cleanup here.
2024-08-26 01:49:04 +02:00
Michael Goulet
48f43fa0ed Avoid taking reference of &TyKind 2024-08-25 16:02:29 -04:00
Matthias Krüger
7edbd6353b
Rollup merge of #129091 - RalfJung:box_as_ptr, r=Amanieu
add Box::as_ptr and Box::as_mut_ptr methods

Unstably implements https://github.com/rust-lang/libs-team/issues/355. Tracking issue: https://github.com/rust-lang/rust/issues/129090.

r? libs-api
2024-08-25 16:51:03 +02:00
bors
717aec0f8e Auto merge of #129521 - matthiaskrgr:rollup-uigv77m, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #128596 (stabilize const_fn_floating_point_arithmetic)
 - #129199 (make writes_through_immutable_pointer a hard error)
 - #129246 (Retroactively feature gate `ConstArgKind::Path`)
 - #129290 (Pin `cc` to 1.0.105)
 - #129323 (Implement `ptr::fn_addr_eq`)
 - #129500 (remove invalid `TyCompat` relation for effects)
 - #129501 (panicking: improve hint for Miri's RUST_BACKTRACE behavior)
 - #129505 (interpret: ImmTy: tighten sanity checks in offset logic)
 - #129510 (Fix `elided_named_lifetimes` in code)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-08-25 08:12:16 +00:00
Trevor Gross
00308920ae
Rollup merge of #128467 - estebank:unsized-args, r=cjgillot
Detect `*` operator on `!Sized` expression

The suggestion is new:

```
error[E0277]: the size for values of type `str` cannot be known at compilation time
  --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:15:9
   |
LL |     let x = *"";
   |         ^ doesn't have a size known at compile-time
   |
   = help: the trait `Sized` is not implemented for `str`
   = note: all local variables must have a statically known size
   = help: unsized locals are gated as an unstable feature
help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression
   |
LL -     let x = *"";
LL +     let x = "";
   |
```

Fix #128199.
2024-08-24 21:03:30 -05:00
Michael Goulet
dbf06d2170 Get rid of predicates_defined_on 2024-08-24 18:25:41 -04:00
Michael Goulet
42a901acd9 Don't use TyKind in lint 2024-08-24 17:16:39 -04:00
Matthias Krüger
e664ff5d8c
Rollup merge of #129510 - GrigorenkoPV:fix-elided-named-lifetimes, r=cjgillot
Fix `elided_named_lifetimes` in code

https://github.com/rust-lang/rust/pull/129207#issuecomment-2308428671

r? cjgillot
2024-08-24 22:14:15 +02:00
Matthias Krüger
c0bedb9e5e
Rollup merge of #129246 - BoxyUwU:feature_gate_const_arg_path, r=cjgillot
Retroactively feature gate `ConstArgKind::Path`

This puts the lowering introduced by #125915 under a feature gate until we fix the regressions introduced by it. Alternative to whole sale reverting the PR since it didn't seem like a very clean revert and I think this is generally a step in the right direction and don't want to get stuck landing and reverting the PR over and over :)

cc #129137 ``@camelid,`` tests taken from there. beta is branching soon so I think it makes sense to not try and rush that fix through since it wont have much time to bake and if it has issues we can't simply revert it on beta.

Fixes #128016
2024-08-24 22:14:12 +02:00
Pavel Grigorenko
53ce92770d Fix elided_named_lifetimes in code 2024-08-24 19:21:32 +03:00
Matthias Krüger
487b3d92cf
Rollup merge of #129386 - cjgillot:local-resolved-arg, r=compiler-errors
Use a LocalDefId in ResolvedArg.
2024-08-23 06:26:53 +02:00
Matthias Krüger
9d39b59862
Rollup merge of #129395 - fmease:pp-dyn-w-gat, r=compiler-errors
Pretty-print own args of existential projections (dyn-Trait w/ GAT constraints)

Previously we would just drop them. This bug isn't that significant as it can only be triggered by user code that constrains GATs inside trait object types which is currently gated under the interim feature `generic_associated_types_extended` (whose future is questionable) or on stable if the GATs are 'disabled' in dyn-Trait via `where Self: Sized` (in which case the assoc type bindings get ignored anyway (and trigger the warn-by-default lint `unused_associated_type_bounds`)), so yeah.

Affects diagnostic output and output of `std::any::type_name{_of_val}`.
2024-08-22 08:17:23 +02:00
León Orell Valerian Liehr
080c2ca2dc
Pretty-print own args of existential projections 2024-08-22 06:22:36 +02:00
Camille GILLOT
c51f2d24d1 Use a LocalDefId in ResolvedArg. 2024-08-22 01:17:01 +00:00
Matthias Krüger
9fd2832a7e
Rollup merge of #129355 - RalfJung:PlaceMention, r=compiler-errors
fix comment on PlaceMention semantics

It seems this was simply missed in https://github.com/rust-lang/rust/pull/114330.
2024-08-21 18:15:06 +02:00
Matthias Krüger
937a18daf9
Rollup merge of #129344 - compiler-errors:less-option-unit-diagnostics, r=jieyouxu
Use `bool` in favor of `Option<()>` for diagnostics

We originally only supported `Option<()>` for optional notes/labels, but we now support `bool`. Let's use that, since it usually leads to more readable code.

I'm not removing the support from the derive macro, though I guess we could error on it... 🤔
2024-08-21 18:15:05 +02:00
Ralf Jung
9010708d9f fix comment on PlaceMention semantics 2024-08-21 15:52:06 +02:00
Michael Goulet
25ff9b6bcb Use bool in favor of Option<()> for diagnostics 2024-08-21 01:31:11 -04:00
kyoto7250
df568af244 fix link in mir/mod
change url path when rewrite those code
2024-08-21 00:14:04 +09:00
bors
79611d90b6 Auto merge of #122551 - RayMuir:copy_fmt, r=saethlin
Added "copy" to Debug fmt for copy operands

In MIR's debug mode (--emit mir) the printing for Operands is slightly inconsistent.

The RValues - values on the right side of an Assign - are usually printed with their Operand when they are Places.

Example:
_2 = move _3

But for arguments, the operand is omitted.

_2 = _1

I propose a change be made, to display the place with the operand.

_2 = copy _1

Move and copy have different semantics, meaning this difference is important and helpful to the user. It also adds consistency to the pretty printing.

-- EDIT --

 Consider this example Rust program and its MIR output with the **updated pretty printer.**

This was generated with the arguments --emit mir --crate-type lib -Zmir-opt-level=0 (Otherwise, it's optimised away since it's a junk program).

```rust
fn main(foo: i32) {
    let v = 10;

    if v == 20 {
        foo;
    }
    else {
        v;
    }
}
```

```MIR
// WARNING: This output format is intended for human consumers only
// and is subject to change without notice. Knock yourself out.
fn main(_1: i32) -> () {
    debug foo => _1;
    let mut _0: ();
    let _2: i32;
    let mut _3: bool;
    let mut _4: i32;
    let _5: i32;
    let _6: i32;
    scope 1 {
        debug v => _2;
    }

    bb0: {
        StorageLive(_2);
        _2 = const 10_i32;
        StorageLive(_3);
        StorageLive(_4);
        _4 = copy _2;
        _3 = Eq(move _4, const 20_i32);
        switchInt(move _3) -> [0: bb2, otherwise: bb1];
    }

    bb1: {
        StorageDead(_4);
        StorageLive(_5);
        _5 = copy _1;
        StorageDead(_5);
        _0 = const ();
        goto -> bb3;
    }

    bb2: {
        StorageDead(_4);
        StorageLive(_6);
        _6 = copy _2;
        StorageDead(_6);
        _0 = const ();
        goto -> bb3;
    }

    bb3: {
        StorageDead(_3);
        StorageDead(_2);
        return;
    }
}
```

In this example program, we can see that when we move a place, it is preceded by "move". e.g. ``` _3 = Eq(move _4, const 20_i32);```. However, when we copy a place such as ```_5 = _1;```, it is not preceded by the operand in the original printout. I propose to change the print to include the copy ```_5 = copy _1``` as in this example.

Regarding the arguments part. When I originally submitted this PR, I was under the impression this only affected the print for arguments to a function, but actually, it affects anything that uses a copy. This is preferable anyway with regard to consistency. The PR is about making ```copy``` explicit.
2024-08-19 23:10:46 +00:00
Boxy
b8eedfa3d2 Retroactively feature gate ConstArgKind::Path 2024-08-19 01:14:22 +01:00
RayMuir
32185decd6 Added "copy" to Debug fmt for copy operands 2024-08-18 14:05:47 -07:00
Ralf Jung
35709be02d rename AddressOf -> RawBorrow inside the compiler 2024-08-18 19:46:53 +02:00
许杰友 Jieyou Xu (Joe)
130cb9e30c
Rollup merge of #129203 - compiler-errors:extern_crate_data, r=jieyouxu
Use cnum for extern crate data key

Noticed this when fixing #129184. I still have yet to put up a fix for that (mostly because I'm too lazy to minimize a test, that will come soon though).
2024-08-18 14:55:23 +08:00
bors
feeba198f2 Auto merge of #128792 - compiler-errors:foreign-sig, r=spastorino
Use `FnSig` instead of raw `FnDecl` for `ForeignItemKind::Fn`, fix ICE for `Fn` trait error on safe foreign fn

Let's use `hir::FnSig` instead of `hir::FnDecl + hir::Safety` for `ForeignItemKind::Fn`. This consolidates some handling code between normal fns and foreign fns.

Separetly, fix an ICE where we weren't handling `Fn` trait errors for safe foreign fns.

If perf is bad for the first commit, I can rework the ICE fix to not rely on it. But if perf is good, I prefer we fix and clean up things all at once 👍

r? spastorino

Fixes #128764
2024-08-17 19:35:01 +00:00
Michael Goulet
b2dd943d4b Use cnum for extern crate data 2024-08-17 12:50:18 -04:00
Matthias Krüger
ddbbda47eb
Rollup merge of #129168 - BoxyUwU:mismatched_ty_correct_id, r=compiler-errors
Return correct HirId when finding body owner in diagnostics

Fixes #129145
Fixes #128810

r? ```@compiler-errors```

```rust
fn generic<const N: u32>() {}

trait Collate<const A: u32> {
    type Pass;
    fn collate(self) -> Self::Pass;
}

impl<const B: u32> Collate<B> for i32 {
    type Pass = ();
    fn collate(self) -> Self::Pass {
        generic::<{ true }>()
        //~^ ERROR: mismatched types
    }
}
```

When type checking the `{ true }` anon const we would error with a type mismatch. This then results in diagnostics code attempting to check whether its due to a type mismatch with the return type. That logic was implemented by walking up the hir until we reached the body owner, except instead of using the `enclosing_body_owner` function it special cased various hir nodes incorrectly resulting in us walking out of the anon const and stopping at `fn collate` instead.

This then resulted in diagnostics logic inside of the anon consts `ParamEnv` attempting to do trait solving involving the `<i32 as Collate<B>>::Pass` type which ICEs because it is in the wrong environment.

I have rewritten this function to just walk up until it hits the `enclosing_body_owner` and made some other changes since I found this pretty hard to read/understand. Hopefully it's easier to understand now, it also makes it more obvious that this is not implemented in a very principled way and is definitely missing cases :)
2024-08-17 18:18:19 +02:00
Matthias Krüger
9c910ae7ee
Rollup merge of #129167 - cuviper:either-once-empty, r=Nadrieril
mir/pretty: use `Option` instead of `Either<Once, Empty>`

`Either` is wasteful for a one-or-none iterator, especially since `Once`
is already an `option::IntoIter` internally. We don't really need any of
the iterator mechanisms in this case, just a single conditional insert.
2024-08-17 18:18:18 +02:00
Boxy
ed6315b3fe Rewrite get_fn_id_for_return_block 2024-08-16 20:53:13 +01:00
Josh Stone
29017e45a1 mir/pretty: use Option instead of Either<Once, Empty>
`Either` is wasteful for a one-or-none iterator, especially since `Once`
is already an `option::IntoIter` internally. We don't really need any of
the iterator mechanisms in this case, just a single conditional insert.
2024-08-16 12:42:02 -07:00
Michael Goulet
833af65f38 Use FnSig instead of raw FnDecl for ForeignItemKind::Fn 2024-08-16 14:10:06 -04:00
Matthias Krüger
f04d25fa91
Rollup merge of #129042 - Jaic1:fix-116308, r=BoxyUwU
Special-case alias ty during the delayed bug emission in `try_from_lit`

This PR tries to fix #116308.

A delayed bug in `try_from_lit` will not be emitted so that the compiler will not ICE when it sees the pair `(ast::LitKind::Int, ty::TyKind::Alias)` in `lit_to_const` (called from `try_from_lit`).

This PR is related to an unstable feature `adt_const_params` (#95174).

r? ``@BoxyUwU``
2024-08-16 19:58:58 +02:00
Jubilee
c6bde8d2e0
Rollup merge of #129110 - nnethercote:Ty-kind-ret-ty-comment, r=jieyouxu
Add a comment explaining the return type of `Ty::kind`.

At least we'll get a useful comment out of #126069 :)

r? ````@lcnr````
2024-08-15 18:44:18 -07:00
Jaic1
cd2b0309cc Special-case alias ty in try_from_lit 2024-08-16 08:37:19 +08:00
Matthias Krüger
f3df807207
Rollup merge of #129106 - compiler-errors:unused-type-ops, r=jieyouxu
Remove redundant type ops: `Eq`/`Subtype`

r? lcnr or anyone really
2024-08-15 19:32:37 +02:00
Nicholas Nethercote
99aad72af5 Add a comment explaining the return type of Ty::kind. 2024-08-15 09:46:21 +10:00
Michael Goulet
f264e5d011 Remove redundant type ops 2024-08-14 14:18:17 -04:00
许杰友 Jieyou Xu (Joe)
59ad2aec49
Rollup merge of #128828 - lcnr:search-graph-11, r=compiler-errors
`-Znext-solver` caching

This PR has two major changes while also fixing multiple issues found via fuzzing.

The main optimization is the ability to not discard provisional cache entries when popping the highest cycle head the entry depends on. This fixes the hang in Fuchsia with `-Znext-solver=coherence`.

It also bails if the result of a fixpoint iteration is ambiguous, even without reaching a fixpoint. This is necessary to avoid exponential blowup if a coinductive cycle results in ambiguity, e.g. due to unknowable candidates in coherence.

Updating stack entries pretty much exclusively happens lazily now, so `fn check_invariants` ended up being mostly useless and I've removed it. See https://gist.github.com/lcnr/8de338fdb2685581e17727bbfab0622a for the invariants we would be able to assert with it.

For a general overview, see the in-process update of the relevant rustc-dev-guide chapter: https://hackmd.io/1ALkSjKlSCyQG-dVb_PUHw

r? ```@compiler-errors```
2024-08-14 21:43:07 +08:00
Ralf Jung
58dcd1c2e6 use the new Box methods in the interpreter 2024-08-14 14:32:17 +02:00
bors
9859bf27fd Auto merge of #129076 - matthiaskrgr:rollup-rg8mi2x, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #128410 (Migrate `remap-path-prefix-dwarf` `run-make` test to rmake)
 - #128759 (alloc: add ToString specialization for `&&str`)
 - #128873 (Add windows-targets crate to std's sysroot)
 - #129001 (chore(lib): Enhance documentation for core::fmt::Formatter's write_fm…)
 - #129061 (Use `is_lang_item` more)
 - #129062 (Remove a no-longer-true assert)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-08-14 04:17:13 +00:00
Matthias Krüger
cd6852b9ea
Rollup merge of #129061 - compiler-errors:lang-item, r=Urgau
Use `is_lang_item` more

Few places that I missed since introducing `TyCtxt::is_lang_item`.
2024-08-14 05:05:52 +02:00
bors
e9c965df7b Auto merge of #128812 - nnethercote:shrink-TyKind-FnPtr, r=compiler-errors
Shrink `TyKind::FnPtr`.

By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and `FnHeader`, which can be packed more efficiently. This reduces the size of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms. This reduces peak memory usage by a few percent on some benchmarks. It also reduces cache misses and page faults similarly, though this doesn't translate to clear cycles or wall-time improvements on CI.

r? `@compiler-errors`
2024-08-14 00:56:53 +00:00
Michael Goulet
bac19686a5 Use is_lang_item more 2024-08-13 16:44:53 -04:00
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
lcnr
7b86c98068 do not use the global solver cache for proof trees
doing so requires overwriting global cache entries and
generally adds significant complexity to the solver. This is
also only ever done for root goals, so it feels easier to wrap
the `evaluate_canonical_goal` in an ordinary query if
necessary.
2024-08-12 10:33:04 +02:00
Nicholas Nethercote
bbd1c3ab73 Streamline some inputs/output traversals. 2024-08-12 16:03:18 +10:00
Nicholas Nethercote
f4a3ed0243 Avoid a FnPtr deconstruct-and-recreate. 2024-08-12 15:37:28 +10: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
Nicholas Nethercote
c4717cc9d1 Shrink TyKind::FnPtr.
By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and
`FnHeader`, which can be packed more efficiently. This reduces the size
of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms.
This reduces peak memory usage by a few percent on some benchmarks. It
also reduces cache misses and page faults similarly, though this doesn't
translate to clear cycles or wall-time improvements on CI.
2024-08-09 14:33:25 +10:00
Nicholas Nethercote
8640998869 Split split_inputs_and_output in two.
I think it's a little clearer and nicer that way.
2024-08-09 14:21:32 +10:00
Esteban Küber
f6767f7a68 Detect * operator on !Sized expression
```
error[E0277]: the size for values of type `str` cannot be known at compilation time
  --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:15:9
   |
LL |     let x = *"";
   |         ^ doesn't have a size known at compile-time
   |
   = help: the trait `Sized` is not implemented for `str`
   = note: all local variables must have a statically known size
   = help: unsized locals are gated as an unstable feature
help: references are always `Sized`, even if they point to unsized data; consider not dereferencing the expression
   |
LL -     let x = *"";
LL +     let x = "";
   |
```
2024-08-08 17:35:40 +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