Commit Graph

333516 Commits

Author SHA1 Message Date
Guillaume Gomez
7e294a5206 Fix tests/ui/rust-2018/removing-extern-crate-malformed-cfg.rs test 2026-07-23 12:06:42 +02:00
Guillaume Gomez
219d6bb935 Filter derive impls earlier on 2026-07-23 12:06:42 +02:00
Guillaume Gomez
7f88868ce4 Extend cfg_attr retrieval for all impls, including ones without the automatically_derived attribute 2026-07-23 00:20:33 +02:00
Guillaume Gomez
ed30e03798 Update AttributeKind::CfgAttrTrace variant usage in clippy 2026-07-22 23:50:54 +02:00
Guillaume Gomez
35c57b5638 Add regression test for doc_cfg feature on derive impl blocks 2026-07-22 23:50:54 +02:00
Guillaume Gomez
9d0c58d90f Retrieve cfg_attr information for derived impls for rustdoc doc_cfg feature 2026-07-22 23:50:54 +02:00
Guillaume Gomez
0eb2348e8b Keep cfg predicate in CfgAttrTrace so it can be used by rustdoc 2026-07-22 23:50:54 +02:00
bors
ae3bbe78ec Auto merge of #159728 - JonathanBrouwer:rollup-6YNKbiO, r=JonathanBrouwer
Rollup of 11 pull requests

Successful merges:

 - rust-lang/rust#159712 (Subtree sync for rustc_codegen_cranelift)
 - rust-lang/rust#155697 (Stabilize c-variadic function definitions)
 - rust-lang/rust#159285 (Simplify `apply_effects_in_range`)
 - rust-lang/rust#159596 (unify the AST repr of type const and const RHS)
 - rust-lang/rust#159607 (test: update riscv32e-registers.rs for LLVM 24 MC diagnostic changes)
 - rust-lang/rust#159659 (Move `Limit` out of `rustc_hir`)
 - rust-lang/rust#159707 (fix error when a dangling ref in a ManuallyDrop is used in a pattern)
 - rust-lang/rust#158738 (next_trait_solver: Recover from GCE const exprs)
 - rust-lang/rust#159451 (Remove config cloning in compiletest)
 - rust-lang/rust#159646 (Increase depth for float infer var fallback hack)
 - rust-lang/rust#159705 (bootstrap: Prefer `cfg!(not(test))` when skipping code paths during unit tests)
2026-07-22 16:03:28 +00:00
Jonathan Brouwer
6d43869b7b Rollup merge of #159705 - Zalathar:cfg-test, r=Kobzol
bootstrap: Prefer `cfg!(not(test))` when skipping code paths during unit tests

- [Zulip thread: Reducing conditional compilation in bootstrap?](https://rust-lang.zulipchat.com/#narrow/channel/326414-t-infra.2Fbootstrap/topic/Reducing.20conditional.20compilation.20in.20bootstrap.3F/with/611882645)
---

Bootstrap contains a few code paths that need to be stubbed out when running bootstrap's unit tests, so that they don't download files or cause other problems. (That's unfortunate, but fixing it is outside the scope of this PR.)

Currently those code paths are skipped using `#[cfg(test)]` and `#[cfg(not(test))]`, which does achieve the desired effect, but has a few downsides. The stubbed-out code triggers dead-code and unused-import warnings, and makes IDE navigation harder when rust-analyzer treats `cfg(test)` as true when analyzing the code.

If we switch to using `cfg!(test)` and `cfg!(not(test))` to “dynamically” skip the relevant code paths, it still gets skipped, but the skipped code is still considered live for the purpose of dead-code warnings and IDE analysis.
2026-07-22 18:02:25 +02:00
Jonathan Brouwer
0159af3305 Rollup merge of #159646 - adwinwhite:fix-f16-hack, r=lcnr
Increase depth for float infer var fallback hack

Fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/280

With this, the fallback hack works again in `bevy-shaders@0.1.0` and `bevy-multi@0.1.0`.

Also added perf optimizations to the proof tree visitor.

r? @ShoyuVanilla
cc @lcnr
2026-07-22 18:02:24 +02:00
Jonathan Brouwer
f95ce5b0f6 Rollup merge of #159451 - Kobzol:compiletest-debuginfo, r=Zalathar,jieyouxu
Remove config cloning in compiletest

This PR is a continuation of https://github.com/rust-lang/rust/pull/159177. It removes the previous cloning of the compiletest config, and replaces it with a concept of a test *variant*, which is a generalization of a test revision. The variant contains an optional revision and an optional debugger for which will the given test be executed.

CC @zalathar

Best reviewed commit-by-commit.

r? @jieyouxu
2026-07-22 18:02:23 +02:00
Jonathan Brouwer
ac24945706 Rollup merge of #158738 - Dnreikronos:next_trait_solver/gce_expr_recovery, r=BoxyUwU
next_trait_solver: Recover from GCE const exprs

fixes rust-lang/rust#158428

the next solver already rejects `generic_const_exprs` with `-Znext-solver=globally`, but we can still walk into `ConstKind::Expr` while compiling after that error and crash anyway.

imo this should stay as a recovery fix, not a gce implementation. ambiguity still lgtm to me here: idk that we want to say the expr is solved when the feature combo is already invalid, we just need to not ice after the real error.

long-term, proper `ConstKind::Expr` support would be a much bigger thing. the next solver would need to type-check, normalize, compare, and evaluate or prove these exprs structurally, including nested binops, unops, casts, calls, and the result type for `ConstArgHasType`. that's out of scope for this pr.

this teaches both const evaluatable and const arg has type paths to recover on `ConstKind::Expr`, then adds the union repro as a ui test.
2026-07-22 18:02:22 +02:00
Jonathan Brouwer
9111027471 Rollup merge of #159707 - RalfJung:dangling-ref-in-pattern, r=WaffleLapkin
fix error when a dangling ref in a ManuallyDrop is used in a pattern

Fixes https://github.com/rust-lang/rust/issues/159701
Cc @rust-lang/wg-const-eval
2026-07-22 18:02:22 +02:00
Jonathan Brouwer
92190394b9 Rollup merge of #159659 - mejrs:limit, r=petrochenkov
Move `Limit` out of `rustc_hir`

It feels rather out of place in `rustc_hir`, so this PR moves it to `rustc_data_structures`. Part of hopefully moving attributes from `rustc_hir` to their own crate.

~~This also lets `rustc_type_ir` use it~~ actually rustc_type_ir needs to compile on stable and `rustc_data_structures` uses like 30 features 😢
2026-07-22 18:02:21 +02:00
Jonathan Brouwer
fa3a58ef49 Rollup merge of #159607 - durin42:llvm-23-riscv32e-error-msg, r=nikic
test: update riscv32e-registers.rs for LLVM 24 MC diagnostic changes

LLVM 24 updates (in llvm/llvm-project@bff9c544bd) the diagnostic string for the RISC-V GPR register class in MC. As a result, invalid register operand references (such as x16..=x31 on riscv32e targets) now emit "register must be a GPR" instead of "invalid operand for instruction".

To keep the test passing on both LLVM <=23 and LLVM >=24, split the target revisions into versioned pairs (e.g. riscv32e_llvm23 and riscv32e_llvm24) gated by `max-llvm-major-version: 23` and `min-llvm-version: 24`, respectively, with corresponding stderr references. This is admittedly a bit aggressive - I'm also fine if we want to just set a max-llvm-major-version and ignore it or preemptively bump it for 24 and set the min version instead of this complexity.
2026-07-22 18:02:20 +02:00
Jonathan Brouwer
2118316ebc Rollup merge of #159596 - khyperia:type-const-rhs-expr, r=BoxyUwU
unify the AST repr of type const and const RHS

related to min_generic_const_args, tracking issue here: https://github.com/rust-lang/rust/issues/132980

Previously, we were parsing/lowering the RHS of type consts differently than regular consts. We no longer need to do so, yippee! This deletes the anon const from the RHS of type consts. This removes the fake defid for the rhs of type consts, FYI.

r? @BoxyUwU
2026-07-22 18:02:19 +02:00
Jonathan Brouwer
a6627d2974 Rollup merge of #159285 - nnethercote:simplify-apply_effects_in_range, r=cjgillot
Simplify `apply_effects_in_range`

Details in individual commits.

r? @cjgillot
2026-07-22 18:02:19 +02:00
Jonathan Brouwer
df662e186a Rollup merge of #155697 - folkertdev:stabilize-c-variadic, r=tgross35,traviscross
Stabilize c-variadic function definitions

tracking issue: Fixes https://github.com/rust-lang/rust/issues/44930
reference PR: https://github.com/rust-lang/reference/pull/2177

There are some minor things still in flight, but I think we're far enough along now.

# Stabilization report
## Summary

In C, functions can use a variable argument list `...` to accept an arbitrary number of untyped arguments. Rust is already able to call such functions (e.g. `libc::printf`), the `c_variadic` feature adds the ability to define them.

A rust c-variadic function looks like this:

```rust
/// SAFETY: must be called with (at least) 2 i32 arguments.
unsafe extern "C" fn sum(mut args: ...) -> i32 {
    let a = args.next_arg::<i32>();
    let b = args.next_arg::<i32>();
    a + b
}

fn foo() -> i32 {
    unsafe { sum(0i32, 2i32) }
}
```

This function accepts a variable arguments list `args: ...`, from which it is able to read arguments using the `next_arg` method.

The main goal of defining c-variadic functions in rust is interaction with C code. Therefore it is a design goal that the rust types map directly to their C counterparts on all targets. Additionally, we disallow interaction between c-variadic functions and certain rust features that don't make much sense in an FFI context (e.g. `extern "Rust" fn` or `async fn`).

## How variadics work in C

The authoritative source for how variadics (also known as "variable arguments") work in C is the C specification. In this document we'll use [section 7.16 of the final draft of the C23 standard](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf#page=302).

> A function may be called with a variable number of arguments of varying types if its parameter type list ends with an ellipsis

Earlier versions of C furthermore required that the `...` argument is not the first argument of the parameter type list (so at least one other argument was required). Starting in C23 this requirement has been lifted.

### C API surface

- `va_list`:  an opaque type that stores the information needed to read variadic arguments, or copy the list of variadic arguments. Typically values of this type get the name `ap`.
- `va_start`: a `va_list` must be initialized with the `va_start` macro before it can be used.
- `va_copy`:  the `va_copy` macro copies a `va_list`. The copy starts at the position in the argument list of the original (so **not** at the first variadic argument to the function), and both can be moved forward independently. This means the same argument can be read multiple times.
- `va_arg`: reads the next argument from the `va_ist`.
- `va_end`: deinitializes a `va_list`.

### Important notes

#### Not calling `va_end` is UB

Section 7.16.1

 > Each invocation of the `va_start` and `va_copy` macros shall be matched by a corresponding invocation of the `va_end` macro in the same function.

Section 7.16.1.3:

> The `va_end` macro facilitates a normal return from the function whose variable argument list was referred to by the expansion of the `va_start` macro, or the function containing the expansion of the `va_copy` macro, that initialized the `va_list` ap. The `va_end` macro may modify ap so that it is no longer usable (without being reinitialized by the `va_start` or `va_copy` macro). If there is no corresponding invocation of the `va_start` or `va_copy` macro, or if the `va_end` macro is not invoked before the return, the behavior is undefined.

We believe that this behavior is this strict because some early C implementations chose to implement `va_list` like so [(source)](https://softwarepreservation.computerhistory.org/c_plus_plus/cfront/release_3.0.3/source/incl-master/proto-headers/stdarg.sol):

```rust
#define         va_start(ap, parmN)     {\
        va_buf  _va;\
        _vastart(ap = (va_list)_va, (char *)&parmN + sizeof parmN)
#define         va_end(ap)      }
#define         va_arg(ap, mode)        *((mode *)_vaarg(ap, sizeof (mode)))
```

To our knowledge no remotely-modern implementation actually implements `va_end` as anything but a no-op.
#### A `va_list` may be moved

Section 7.16

> The object  `ap` may be passed as an argument to another function; if that function invokes the `va_arg` macro with parameter `ap`, the representation of `ap` in the calling function is indeterminate and shall be passed to the `va_end` macro prior to any further reference to `ap`.

and

> A pointer to a `va_list` can be created and passed to another function, in which case the original function can make further use of the original list after the other function returns

So `va_list` can be moved into another function, but `va_end` must still run in the frame that initialized (with `va_start` or `va_copy`) the `va_list` .

#### Representation of `va_list`

The representation of `va_list` is platform-specific.  There are three flavors that are used by current rust targets:

- `va_list` is an opaque pointer
- `va_list` is a struct
- `va_list` is a single-element array, containing a struct

The opaque pointer approach is the simplest to implement: the pointer just points to an array of arguments on the caller's stack.

The struct and single-element array variants are more complex, but potentially more efficient because the additional state makes it possible to pass c-variadic arguments via registers.

#### array-to-pointer decay

If the `va_list` is of the single-element array flavor, it is subject to array-to-pointer decay: in C, arrays are passed not by-value, but as pointers. Hence, from an FFI perspective, these two functions are equivalent.

```c
#include <stdarg.h>

extern int foo(va_list va) {
    return va_arg(va, int);
}

extern int bar(va_list *va) {
    return va_arg(*va, int);
}
```

Indeed, they generate the same assembly, see https://godbolt.org/z/n8c4aq5hM.

#### other calling conventions

Both `clang` and `gcc` refuse to compile a function that uses variadic arguments and a non-default calling convention. See also https://github.com/rust-lang/rust/issues/141618, in particular https://github.com/rust-lang/rust/issues/141618#issuecomment-2911802411.

The LLVM intrinsics (`va_start`, `va_arg`, etc.) always expand based on the default C ABI on the current platform, not the ABI of the function they are used in. While rust only supports defining C-variadic functions with the `extern "C"` ABI that is fine, but relaxing that restriction would require either changing LLVM to take the calling convention of the current function into account, or implementing `va_start` ourselves for all platforms.

### `va_arg` and argument promotion

With some exceptions, the return type of a `va_arg` call must match the type of the supplied argument:

Section 7.16.1

> If type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined

These default argument promotions are specified in section 6.5.3.3:

>  The arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type. The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter, if present. The integer promotions are performed on each trailing argument, and trailing arguments that have type float are promoted to double. These are called the default argument promotions. No other conversions are performed implicitly

There are a couple of additional conversions that are allowed, such as casting signed to/from unsigned integers.

A concrete example of what is  not allowed is to use `va_arg` to read (signed or unsigned) `char` or `short`, or `float` arguments. Reading such types is UB.  See also https://github.com/rust-lang/rust/issues/61275#issuecomment-2193942535.

## How c-variadics work in rust

### Rust API surface

The rust API has similar capabilities to C but uses rust names and concepts.

```rust
pub struct VaList<'f> {
    /* ... */
    _marker: PhantomCovariantLifetime<'f>,
}
```

The `VaList` struct has a lifetime parameter that ensures that the `VaList` cannot outlive the function that created it. Semantically `VaList` contains mutable references (to the caller's and/or callee's stack), so the lifetime is covariant.

The `#[rustc_pass_indirectly_in_non_rustic_abis]` attribute is applied to the definition if `va_list` is a single-element array on the target platform. This attribute simulates the array-to-pointer decay that the C `va_list` type is subject to on that target.

A goal of `c_variadic` is to be able to write portable code that uses c-variadics. When `va_list` is a pointer or struct FFI compatibility with a rust `VaList` is straightforward, the attribute to pass indirectly is needed to also make the types FFI compatible on targets where array-to-pointer decay kicks in.

The `#[rustc_pass_indirectly_in_non_rustic_abis]` attribute works as desired because `VaList` is a by-move type: in rust this is enforced by the type system, in C the specification requires it. Mutations to the passed object are not observable in the caller (because the value is semantically moved and hence inaccessible).

The `VaList::next_arg` method can be used to read the next argument.

```rust
pub unsafe trait VaArgSafe: Copy + Sealed {}

impl<'f> VaList<'f> {
    pub unsafe fn next_arg<T: VaArgSafe>(&mut self) -> T { /* ... */ }
}
```

The implementation is equivalent to C `va_arg`, though for all targets that we propose to stabilize here the `va_arg` logic is implemented in `rustc` itself, and does not rely on LLVM (more information on that below).

The return type is constrained by `VaArgSafe` so that only valid argument types can be read. In particular this mechanism prevents subtle issues around implicit numeric promotion in C. Reading an argument is unsafe because reading more arguments than were supplied is UB. Implementors of `VaArgSafe` must implement `Copy` because the `VaList` can be cloned and hence the same variable argument can be read twice, which is only safe if the type is `Copy`.

The `VaArgSafe` trait is guaranteed to be implemented for:

- `c_int`, `c_long` and `c_longlong`
- `c_uint`, `c_ulong` and `c_ulonglong`
- `c_double`
- `*const T` and `*mut T`

Implementations for other types are not guaranteed to be portable, so portable programs should not rely on e.g. `usize` or `f64` implementing this trait directly.

C argument types are considered to have the rust type that corresponds to `core::ffi::*`, so a C `int` is mapped to `c_int` and so on. We don't consider the C `_BitInt` or `_Float32` types here, rather we (on most platforms) map `f64` to `double` etc. `_BitInt(32)` and `int` are distinct types. `_BitInt` is furthermore special because it does not participate in integer promotion.

Calling `VaList::next_arg` to read an argument of type `T` is only safe if all of the following conditions are satisfied:

- There is another c-variadic argument to read.
- The actual type of the argument `U` is compatible with `T` (as defined below).
- If `U` and `T` are both integer types, then the value passed by the caller must be
representable in both types.

Types `T` and `U` are compatible when:

- `T` and `U` are the same type (up to free lifetimes).
- `T` and `U` are integer types of the same size.
- `T` and `U` are both pointers, and their target types are compatible.
- `T` is a pointer to `c_void` and `U` is a pointer to `i8` or `u8`, or vice versa.

```rust
// SAFETY: the caller must supply an argument that is compatible with `u64`,
// optionally followed by other arguments that are ignored.
unsafe extern "C" fn variadic(mut ap: ...) -> u64 {
    unsafe { ap.next_arg::<u64>() }
}

// The type is incompatible, Miri will report UB.
unsafe { variadic(1u32) }

// The value is not representable by u64, Miri will report UB.
unsafe { variadic(-1i64) }

// This is fine.
unsafe { variadic(42i64) }
```

And an example of when equality up to free lifetimes is relevant.

```rust
const unsafe extern "C" fn read_as<T: core::ffi::VaArgSafe>(mut ap: ...) -> T {
    ap.next_arg::<T>()
}

unsafe fn read_cast_lifetime() {
    // Allowed
    const { read_as::<*const &'static i32>(std::ptr::dangling::<&i32>()) };

    // Not allowed
    const { read_as::<*const fn(&'static ())>(std::ptr::dangling::<for<'a> fn(&'a ())>()) };
    //~^ ERROR va_arg type mismatch: requested `*const fn(&())` is incompatible with next argument of type `*const for<'a> fn(&'a ())`
}
```

The `VaList` type implements `Clone` and `Drop`:

```rust
impl<'f> Clone for VaList<'f> { /* ... */ }

impl<'f> Drop for VaList<'f> {
    fn drop(&mut self) {
        /* no-op */
    }
}
```

The `Clone` implementation can be used to duplicate a `VaList`. The copy has the same position as the original, but both can be incremented independently. While all current targets could also implement `Copy` for `VaList`, a future target might not, so for now `Copy` is not implemented. LLVM now guarantee that `memcpy` may be used to duplicate a `VaList` when the operation is equivalent to `memcpy` on the platform, which is true for all current LLVM targets.

The `Drop` implementation is a no-op, it does call a function named `va_end`, but that itself is a no-op that exists only for Miri to detect UB. In C,`va_end` must run in the frame where the `va_list` was initialized. Because `VaList` can be moved (like the C `va_list`), the frame in which a `VaList` is dropped may not be the frame in which it was initialized. LLVM now guarantees that `va_end` may be omitted when `va_end` is a no-op, which is the case for all current LLVM targets.

The `VaList` type is available on all targets, even on targets that don't actually support c-variadic definitions. On such targets, it is impossible to get a valid `VaList` value, because attempting to define a c-variadic function (using the `...` argument) will throw an error.

### Syntax

 In rust, a C-variadic function looks like this:

```rust
unsafe extern "C" fn foo(a: i32, b: i32, args: ...) {
    /* body */
}
```

The special `args: ...` argument stands in for an arbitrary number of arguments that the caller may pass.  The `...` argument must be the last argument in the parameter list of a function. Like in C23 and later, `...` may be the only argument. The `...` syntax is already stable in foreign functions, `c_variadic` additionally allows it in function definitions.

In function definitions, the `...` argument must have a pattern. The argument can be ignored by using `_: ...`. In foreign function declarations the pattern can be omitted.

A function definition with a `...` argument must be an `unsafe` function. Passing an incorrect number of arguments, or arguments of the wrong type, is UB, and hence every call site has to satisfy the safety conditions. A special case is a function that ignores its `VaList` entirely using `_: ...`: we may  decide to allow such functions to be safe. At the time of writing we see insufficient benefits relative to the additional complexity that this entails.

A function with the `...` argument must be an `extern "C"` or `extern "C-unwind"` function. In the future we want to extend the set of accepted ABIs to include all ABIs for which we allow calling a c-variadic function (including e.g. `sysv64` and `win64`).

The `...` argument can occur in definitions of functions, inherent methods, and trait methods. When any method on a trait uses a c-variadic argument, the trait is no longer dyn-compatible. The technical reason is that there is no sound way to generate a `ReifyShim` that passes on the c-variadic arguments.

### Desugaring

In a function like this:

```rust
unsafe extern "C" fn foo(args: ...) {
    // ...
}
```

The `args: ...` is internally desugared into a call to LLVM's `va_start` that initializes `args` as a `VaList`. The `VaList` gets the lifetime of a local variable on `foo`'s stack, so that the `VaList` cannot outlive the function that created it.

The desugaring will fail with an error when the current target does not support c-variadic definitions. Currently this is the case for `spriv` and `bpf`:

```
error: the `bpfel` target does not support c-variadic functions
  --> $DIR/not-supported.rs:23:31
   |
LL | unsafe extern "C" fn variadic(_: ...) {}
   |                               ^^^^^^
```

### A note on LLVM `va_arg`

The LLVM `va_arg` intrinsic is known to silently miscompile. A [comment in the implementation](72c8f98f74/clang/lib/CodeGen/ABIInfoImpl.cpp (L406-L411)) notes:

> This default implementation defers to the llvm backend's va_arg instruction. It can handle only passing arguments directly (typically only handled in the backend for primitive types), or aggregates passed indirectly by pointer (NOTE: if the "byval" flag has ABI impact in the callee, this implementation cannot work.)
>
> Only a few cases are covered here at the moment -- those needed by the default abi.

Hence, like `clang`, `rustc` implements `va_arg` for the vast majority of targets (specifically including all tier-1 targets) in [`va_arg.rs`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_codegen_llvm/src/va_arg.rs). Note that the match on the architecture is exhaustive, however the behavior on targets where we've not validated the correctness of the implementation is an unresolved question (see below).

## Future extensions

### C-variadics  and `const fn`

Support for c-variadic `const fn` (and by extension, support in Miri) is implemented in
https://github.com/rust-lang/rust/pull/150601 and gated by `const_c_variadic`. Practical usage requires `const_destruct` too because `VaList` has a custom `Drop` implementation.

```rust
#![feature(c_variadic, const_c_variadic, const_destruct)]

const unsafe extern "C" fn variadic(mut ap: ...) -> i32 {
    ap.next_arg()
}
```

### Naked variadic functions

Currently only `C` and `C-unwind` are valid ABIs for all c-variadic function definitions. With naked functions it is possible to define e.g. a `win64` c-variadic function in a program where `sysv64` is the default. This feature is tracked as [`c_variadic_naked_functions`](https://github.com/rust-lang/rust/issues/148767).

```rust
#![feature(c_variadic, c_variadic_naked_functions)]

#[unsafe(naked)]
unsafe extern "win64" fn variadic_win64(_: u32, _: ...) -> u32 {
    core::arch::naked_asm!(
        r#"
        push    rax
        mov     qword ptr [rsp + 40], r9
        mov     qword ptr [rsp + 24], rdx
        mov     qword ptr [rsp + 32], r8
        lea     rax, [rsp + 40]
        mov     qword ptr [rsp], rax
        lea     eax, [rdx + rcx]
        add     eax, r8d
        pop     rcx
        ret
    "#,
    )
}
```

### C-variadics  and coroutines

An `async fn` or any other type of coroutine cannot be c-variadic. We see no reason to support this.
### Defining safe C-variadic functions

In `extern` blocks, it is valid to mark C-variadic functions as safe, under the assumption that the function completely ignores the variable arguments list:

```rust
unsafe extern "C" {
    safe fn foo(...);
}
```

Normally, C-variadic function definitions must be unsafe, because calling the function with unexpected (in type or number) elements is UB. We could relax this constraint on C-variadic functions that ignore their C variable argument list, e.g.:

```rust
// NOTE: not unsafe
extern "C" fn(x: i32, _: ...) -> i32 {
    x
}
```

At the moment we don't have a good reason to add this behavior. It is completely backwards compatible, so if a need arises in the future we can revisit this.

### Accepting more `va_arg` return types

Discussed in https://github.com/rust-lang/rust/issues/44930#issuecomment-4289951633.

We only want to implement `VaArgSafe` for types that have a clear counterpart in C. That rules out types like `Option<NonNull>` or `NonZeroI32`. We might add `MaybeUninit<c_int>` and so on in the future if a use case comes up: this would map to a C `union`.

The only planned extension right now is support for `i128` and `u128` where they can be mapped to (unsigned) `__int128`. However `rustc` currently does not know on what targets this type is available, and hence we leave it out of the stabilization for now.

Adding 128-bit support is in progress in https://github.com/rust-lang/rust/pull/155429.

### C-variadic support on untested targets

Because c-variadic is a platform-specific feature, and extremely unsafe, we're apprehensive about stabilizing it for targets where that implementation has not actually been validated. The [`#[c_variadic_experimental_arch]`](https://github.com/rust-lang/rust/issues/155973) feature gates such targets. The current list of targets which are kept unstable by this PR is:

- `riscv32e-unknown-none-elf` because its ABI may change in the future
- `sparc` because compilers for it are no longer distributed
- `avr`, `m68k` and `msp430` because they are hard to validate
- targets categorized as `Other`, e.g. through a custom `target.json`

### Multiple C-variadic ABIs in the same program

https://github.com/rust-lang/rust/issues/141618

Both `clang` and `gcc` reject using `...` in functions with a non-default ABI for the target. That makes the layout of `VaList` and expansion of `va_start`, `va_arg` etc. unambiguous. For now we impose a similar restriction for the rust implementation. This restriction could be lifted in the future, but this would requite that `VaList` somehow "stores" its ABI.

One approach is to add a type parameter to `VaList` that default's to the platform's default ABI. Each c-variadic argument would then desugar to use the ABI of the c-variadic function that creates it.
## History

[RFC 2137](https://github.com/rust-lang/rfcs/pull/2137) proposes to "support defining C-compatible variadic functions in rust" in 2017, and it is still the core of the implementation today. The text lays out a basic rust API and highlights potential issues (e.g. some solution is needed to match C's array-to-pointer decay), but does not always provide concrete solutions.

In 2019 https://github.com/rust-lang/rust/pull/59625 introduces a wrapper type to simulate array-to-pointer decay. With this API the C semantics can be matched, but doing so correctly takes a great deal of care. The `VaList` type also has two lifetime arguments in this version, which is inelegant.

Then, little seems to have happened for 6 years, until the recent burst of activity that resulted in the current proposal.

- [#t-compiler > c_variadic API and ABI](https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/c_variadic.20API.20and.20ABI/with/527115587)
- https://github.com/rust-lang/rust/issues/141524

**implementation history**

The list of PRs is long, but they have all been labled with [`F-c_variadic`](https://github.com/rust-lang/rust/pulls?q=is%3Apr+label%3AF-c_variadic+).

## Unresolved Questions

### `VaArgSafe` and function pointers

https://github.com/rust-lang/rust/issues/153646

Currently `VaArgSafe` is not implemented for function pointers, and doing so would be tricky. There is the practical issue of not being able to be generic over the number of arguments, but there are also some complex constraints on the signature, see https://www.gnu.org/software/c-intro-and-ref/manual/html_node/Compatible-Types.html.

### Thanks

Many people have worked on this feature over the years, and many more have provided input. I'd like to credit here the people that have been especially involved in this push for stabilization:  @workingjubilee, @RalfJung, @beetrees, @JoshTriplett and @tgross35.

r? @tgross35
2026-07-22 18:02:18 +02:00
Jonathan Brouwer
83b50379bc Rollup merge of #159712 - bjorn3:sync_cg_clif-2026-07-22, r=bjorn3
Subtree sync for rustc_codegen_cranelift

The main highlights this time are a Cranelift update and support a couple of new arm64 vendor intrinsics

r? @ghost

@rustbot label +A-codegen +A-cranelift +T-compiler +subtree-sync
2026-07-22 18:02:17 +02:00
Ralf Jung
c22fbbe582 fix error when a dangling ref in a ManuallyDrop is used in a pattern 2026-07-22 15:26:51 +02:00
bjorn3
39c2db0934 Merge commit 'cb89537d435ec9cc9c812cd47c6130bd96aa0050' into sync_cg_clif-2026-07-22 2026-07-22 13:06:34 +02:00
bjorn3
cb89537d43 Fix rustc test suite 2026-07-22 12:19:33 +02:00
bjorn3
6da84ff814 Rustup to rustc 1.99.0-nightly (0e29c21d9 2026-07-21) 2026-07-22 12:00:24 +02:00
bors
c188565812 Auto merge of #159623 - camelid:good-impls, r=notriddle,GuillaumeGomez
rustdoc: Only build extern trait impls if needed



or, finally remove the `BadImplStripper`!

Building inlined impls is expensive, and most of them end up being
unneeded and stripped later in this function. So we should filter them
ahead of time. This requires inlining external auto traits when we
construct auto impls, since this no longer happens as a side effect.

We inline external impls when they are
* for generics (i.e., blanket impls)
* for primitive types (probably this should be handled below really)
* for a type (inlined) in the current crate
* of a trait (inlined) in the current crate
* of `Deref`
These rules are based on the existing filtering rules that are applied
after building the inlined impls.

After doing the filtering ahead of time, we can remove the downstream
filtering. Thus, we can finally remove `BadImplStripper` and unused
deref-following logic. It appears that all this `Deref` logic was pointless
in the first place since following derefs already happens elsewhere in
rustdoc, where it is actually needed.
2026-07-22 09:55:03 +00:00
Folkert de Vries
d7ea382797 Stabilize c_variadic 2026-07-22 11:42:09 +02:00
bjorn3
e1fa066a0c Sync from rust 0e29c21d93 2026-07-22 10:53:53 +02:00
Zalathar
480c37dbd3 Prefer cfg!(not(test)) when skipping downloads
Assertions have been added to some code paths that were previously not built
during `cfg(test)`, to make sure they aren't accidentally executed.
2026-07-22 18:23:43 +10:00
Augie Fackler
2f5a71d441 LLVM 24 updates (in llvm/llvm-project@bff9c544bd) the diagnostic string for the RISC-V GPR register class in MC. As a result, invalid register operand references (such as x16..=x31 on riscv32e targets) now emit "register must be a GPR" instead of "invalid operand for instruction".
To keep the test passing on both LLVM <=23 and LLVM >=24, split the target revisions into versioned pairs (e.g. riscv32e_llvm23 and riscv32e_llvm24) gated by `max-llvm-major-version: 23` and `min-llvm-version: 24`, respectively, with corresponding stderr references. This is admittedly a bit aggressive - I'm also fine if we want to just set a max-llvm-major-version and ignore it or preemptively bump it for 24 and set the min version instead of this complexity.
2026-07-22 08:08:40 +00:00
khyperia
e895ed8c90 unify the AST repr of type const and const RHS 2026-07-22 09:22:45 +02:00
Zalathar
3559c7ddaf Prefer cfg!(not(test)) when skipping code paths during unit tests 2026-07-22 17:13:31 +10:00
bors
b803f36e07 Auto merge of #159609 - nikic:opt-escape, r=folkertdev
Optimize escape_string_symbol()

Going through escape_default() + to_string(), which involves going through formatting machinery and a flat_map of a complex iterator, ends up being quite slow. Directly pushing to a string, even with a naive implementation, is significantly faster.

This shows up in the include-blob benchmark, which mostly exercises this one function.
2026-07-22 06:22:21 +00:00
Adwin White
490b3445bd increase depth for float fallback hack visitor 2026-07-22 11:39:29 +08:00
bors
1af98b7cdf Auto merge of #159697 - jhpratt:rollup-4WBEz7c, r=jhpratt
Rollup of 13 pull requests

Successful merges:

 - rust-lang/rust#159582 (Sync from portable simd 2026 07 20)
 - rust-lang/rust#158890 (Fix splat v0 mangling)
 - rust-lang/rust#159614 (debuginfo generation for unsafe binders)
 - rust-lang/rust#159647 (Remove `early_exit` closures)
 - rust-lang/rust#159656 (define a `Simd` type in `minicore`)
 - rust-lang/rust#156474 (Add paths for linked associated items)
 - rust-lang/rust#159211 (Fix debuginfo argument when invoking LLBC linker)
 - rust-lang/rust#159527 (Bring runtime symbols statics on par with foreign functions)
 - rust-lang/rust#159625 (Refactor is_opsem_inhabited)
 - rust-lang/rust#159629 (Add more splat rust-call regression tests)
 - rust-lang/rust#159652 (Remove `cfg(not(no_global_oom_handling))` from the `Drop` impl of `UniqueArcUninit`)
 - rust-lang/rust#159657 (Remove the blanket `#![cfg_attr(test, allow(unused))]` from bootstrap )
 - rust-lang/rust#159663 (Add layout cycle hang regression test)
2026-07-22 03:09:22 +00:00
Jacob Pratt
b3e54027ea Rollup merge of #159663 - chenyukang:yukang-fix-153205-layout-cycle-hang-test, r=lqd
Add layout cycle hang regression test

Fixes rust-lang/rust#153205

The issue was already fixed https://github.com/rust-lang/rust/issues/153205#issuecomment-5032590821
2026-07-21 20:59:30 -04:00
Jacob Pratt
513078635e Rollup merge of #159657 - Zalathar:allow-unused, r=jieyouxu
Remove the blanket `#![cfg_attr(test, allow(unused))]` from bootstrap

- Originally added by https://github.com/rust-lang/rust/pull/138704
---

This blanket allow was hiding several unused imports and items in test-only code. It has been replaced with a number of narrower ensures.

We can also drop the `pretty_assertions` dev-dependency, which turns out to have been unused.
2026-07-21 20:59:29 -04:00
Jacob Pratt
0bb7d378d8 Rollup merge of #159652 - maxdexh:bugfix/unique-arc-uninit-drop-oom, r=Darksonn
Remove `cfg(not(no_global_oom_handling))` from the `Drop` impl of `UniqueArcUninit`

Fixes rust-lang/rust#159651
2026-07-21 20:59:28 -04:00
Jacob Pratt
676e5eb65e Rollup merge of #159629 - teor2345:splat-closure-test, r=JohnTitor
Add more splat rust-call regression tests

Tracking issue: rust-lang/rust#153629

This PR provides more test coverage for splat, rust-call, and closure rejection (bugs rust-lang/rust#158800 and rust-lang/rust#158605), after the fixes in PRs rust-lang/rust#158645 and rust-lang/rust#158850.

This PR only contains tests.

@rustbot +F-splat +T-compiler +C-bug
2026-07-21 20:59:27 -04:00
Jacob Pratt
ca0d2f7b5c Rollup merge of #159625 - camsteffen:opsem-inhabited-refactor, r=RalfJung
Refactor is_opsem_inhabited

Refactor of rust-lang/rust#156977

Introduce a struct to generally simplify the recursion.

r? WaffleLapkin
cc @RalfJung
2026-07-21 20:59:26 -04:00
Jacob Pratt
ae89c41a79 Rollup merge of #159527 - Urgau:runtime-symbols-static-cleanup, r=GuillaumeGomez
Bring runtime symbols statics on par with foreign functions

This PR cleanups the `static` items path when checking the runtime symbols, and brings it on par with the foreign functions check.

It also fixes a bug where static only reported the invalid lint and never the suspicious lint.

Best reviewed commit by commit.
2026-07-21 20:59:25 -04:00
Jacob Pratt
1268eaa357 Rollup merge of #159211 - kulst:llbc-fix-debuginfo, r=nnethercote
Fix debuginfo argument when invoking LLBC linker

Previously LLBC's Linker implementation unconditionally added `--debug` to the linker invocation. This just became visible when 062ecd6 made LLBC no longer strip debug information unconditionally.

It is also common to use `cargo build --release` together with `-Zbuild-std=core` when targeting NVPTX. In this case the release profile will prevent all crates from embedding debug information in the first place. This additionally made the bug less visible.

This PR adds the proper logic to LLBC's linker implementation to only invoke LLBC with `--debug` when debug-information should not be stripped.

I did not add a regression test yet, since this would require to actually invoke the linker in `assembly-llvm`. As soon as https://github.com/rust-lang/rust/pull/157512 is merged and we have `assembly-output: linker-asm` available, I want to follow up on that.

cc: @kjetilkjeka
@rustbot label +O-NVPTX
2026-07-21 20:59:24 -04:00
Jacob Pratt
38d03cc980 Rollup merge of #156474 - qaijuang:rustdoc-json-link-paths, r=aDotInTheVoid,GuillaumeGomez
Add paths for linked associated items

rustdoc-json emits intra-doc links to associated items using the associated item's id. For external associated items, that id is not present in `index`, and it was also missing from `paths`.

This PR backfills missing `paths` summaries for intra-doc link targets from the resolved page item and cached parent paths. Local targets are only added when already present in `index`, preserving jsondoclint's local-path invariant.

Fixes rust-lang/rust#152511
2026-07-21 20:59:23 -04:00
Jacob Pratt
dd38657962 Rollup merge of #159656 - folkertdev:minicore-simd, r=jieyouxu
define a `Simd` type in `minicore`

Saves a lot of repetition.

r? jieyouxu
2026-07-21 20:59:21 -04:00
Jacob Pratt
4bfd047ad8 Rollup merge of #159647 - nnethercote:rm-early_exit-closures, r=bjorn3
Remove `early_exit` closures

Details in individual commits.

r? @bjorn3
2026-07-21 20:59:20 -04:00
Jacob Pratt
aaa7d87dc1 Rollup merge of #159614 - amirHdev:fix-unsafe-binder-debuginfo, r=JohnTitor
debuginfo generation for unsafe binders

debug-info generation removed an unsafe binder which allowed bound regions to escape into layout and trait queries while constructing the inner debug info type
instantiate those bound regions with erased regions before constructing the inner debug info node

Fix rust-lang/rust#159576
2026-07-21 20:59:19 -04:00
Jacob Pratt
4609c871f2 Rollup merge of #158890 - teor2345:splat-mangling-clash, r=wesleywiser
Fix splat v0 mangling

Tracking issue: rust-lang/rust#153629

Typecheck considers a splatted and non-splatted function as distinct types, so mangling has to include splatting. If it doesn't, we get symbol clashes. See the ticket and the tests in this PR for details.

Demangling PR: https://github.com/rust-lang/rustc-demangle/pull/90
Demangling in rust-lang/rust PR: https://github.com/rust-lang/rust/pull/159202

@rustbot label +C-bug +F-splat +T-compiler +A-name-mangling

Fixes rust-lang/rust#158644

This PR was based on rust-lang/rust#159202, so we waited for that PR to merge first, then rebased this one.
2026-07-21 20:59:18 -04:00
Jacob Pratt
1b34ade47d Rollup merge of #159582 - folkertdev:sync-from-portable-simd-2026-07-20, r=oli-obk
Sync from portable simd 2026 07 20

r? @ghost

feel free to `r+` once green
2026-07-21 20:59:16 -04:00
bors
b9ee8d8bcb Auto merge of #159658 - jieyouxu:rustfmt-subtree-update, r=ytmimi
rustfmt subtree update

## Summary

Part of https://github.com/rust-lang/rustfmt/issues/6965.
Closes https://github.com/rust-lang/rustfmt/issues/6965.

Corresponding subtree pushes:

- https://github.com/rust-lang/rustfmt/pull/6966
- https://github.com/rust-lang/rustfmt/pull/6939

Merge conflicts were trivial (just the CI workflows and leftover pattern rewrite helper function).

## Additional context

- [#t-rustfmt > Sync to rust-lang/rust](https://rust-lang.zulipchat.com/#narrow/channel/357797-t-rustfmt/topic/Sync.20to.20rust-lang.2Frust/with/611624237)

r? @ytmimi
2026-07-21 23:11:51 +00:00
bors
0e29c21d93 Auto merge of #154989 - Jamesbarford:chore/move-region-to-ir, r=lcnr
Move Region from rustc_middle to rustc_type_ir



## General notes
Probably best reviewed commit by commit. I've tried where to make the changes as isolated as possible.
- For the `pub struct Region` if we use `Interned<...>` in the definition then we'd need to add a lifetime to the `Interner` trait. As such I opted for a type `InternedRegionKind` which is `Interned<'tcx, RegionKind<'tcx>>` in the implementation. To allow calling the `kind()` method I implemented `inherent::IntoKind` for `Interned<'tcx, T>`.
- All methods from the `Region` trait in `inherent` have been moved to `compiler/rustc_type_ir/src/sty/mod.rs`.
- Had to implement `Lift` manually for `Interned<RegionKind>` (`I::InternedRegionKind`) which is a no-op.
- I'm not sure the implementation of `kind()` is correct or even should be implemented for `Interned<...>`?
- Add a small abstraction needed for decode to still re-intern `Region` and moved this along with other `encode/decode` implementations into a `serialize` file.
```
error[E0210]: type parameter `E` must be used as the type parameter for some local type (e.g., `MyStruct<E>`)
   --> compiler/rustc_middle/src/ty/codec.rs:162:12
    |
162 | impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Region<'tcx> {
    |            ^ type parameter `E` must be used as the type parameter for some local type
    |
    = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
    = note: only traits defined in the current crate can be implemented for a type parameter

error[E0210]: type parameter `D` must be used as the type parameter for some local type (e.g., `MyStruct<D>`)
   --> compiler/rustc_middle/src/ty/codec.rs:301:12
    |
301 | impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> {
    |            ^ type parameter `D` must be used as the type parameter for some local type
    |
    = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
    = note: only traits defined in the current crate can be implemented for a type parameter
```

## `compiler/rustc_middle/src/ty/region.rs`
Generally anything that needed to access fields on `TyCtxt` have been made methods on the interner.
- `interner.lifetimes.anon_re_bounds.get(debruijn.as_usize())` for getting an interned lifetime, is now a trait method on `Interner`; `fn get_anon_re_bounds_lifetime(...)`
- `fn intern_region(...)` now a trait method on `Interner`
- `interner.lifetimes.anon_re_canonical_bounds.get(debruijn.as_usize())` required
   for `fn new_canonical_bound(...)`. Is now `fn get_anon_re_canonical_bounds_lifetime(...)`
- `interner.lifetimes.re_static` has become `fn get_re_static_lifetime()` for method `fn new_static((..)`

r? @lcnr
2026-07-21 18:42:37 +00:00
Noah Lev
afaa98372c rustdoc: Keep external impls of notable traits
The code predating this PR was actually incorrect since it did not keep
these impls. However, removing the redundant deref-following logic had
the side effect of breaking a GUI test for the notable traits tooltip.
It seems like previously an unrelated type with a deref impl to
`Vec<u8>` ended up causing the impl of `Write` for it to be kept.

In fact, this change required some snapshot tests to be updated because
it fixed a latent bug where the notable trait tooltip would not appear
for many external traits (if they didn't happen to get pulled in like
`Write for Vec<u8>` did).
2026-07-21 18:16:01 +00:00
Cameron Steffen
7f2417bcc2 Refactor is_opsem_inhabited 2026-07-21 12:31:40 -05:00