Commit graph

2674 commits

Author SHA1 Message Date
bors
8188f6c808 Auto merge of #149709 - Urgau:overhaul-filenames, r=davidtwco
Overhaul filename handling for cross-compiler consistency

This PR overhauls the way we handle filenames in the compiler and `rmeta` in order to achieve achieve cross-compiler consistency (ie. having the same path no matter if the filename was created in the current compiler session or is coming from `rmeta`).

This is required as some parts of the compiler rely on consistent paths for the soundness of generated code (see rust-lang/rust#148328).

In order to achieved consistency multiple steps are being taken by this PR:
 - by making `RealFileName` immutable
 - by only having `SourceMap::to_real_filename` create `RealFileName`
   - currently `RealFileName` can be created from any `Path` and are remapped afterwards, which creates consistency issue
 - by also making `RealFileName` holds it's working directory, embeddable name and the remapped scopes
   - this removes the need for a `Session`, to know the current(!) scopes and cwd, which is invalid as they may not be equal to the scopes used when creating the filename

In order for `SourceMap::to_real_filename` to know which scopes to apply `FilePathMapping` now takes the current remapping scopes to apply, which makes `FileNameDisplayPreference` and company useless and are removed.

This PR is split-up in multiple commits (unfortunately not atomic), but should help review the changes.

Unblocks https://github.com/rust-lang/rust/pull/147611
Fixes https://github.com/rust-lang/rust/issues/148328
2025-12-13 14:32:09 +00:00
Esteban Küber
a49c175380 #![deny(clippy::manual_let_else)] in some rustc modules 2025-12-12 17:53:19 +00:00
Urgau
8cbfb26383 Overhaul filename handling for cross-compiler consistency
This commit refactors `SourceMap` and most importantly `RealFileName` to
make it self-contained in order to achieve cross-compiler consistency.

This is achieved:
 - by making `RealFileName` immutable
 - by only having `SourceMap::to_real_filename` create `RealFileName`
 - by also making `RealFileName` holds it's working directory,
   it's embeddable name and the remapped scopes
 - by making most `FileName` and `RealFileName` methods take a scope as
   an argument

In order for `SourceMap::to_real_filename` to know which scopes to apply
`FilePathMapping` now takes the current remapping scopes to apply, which
makes `FileNameDisplayPreference` and company useless and are removed.

The scopes type `RemapPathScopeComponents` was moved from
`rustc_session::config` to `rustc_span`.

The previous system for scoping the local/remapped filenames
`RemapFileNameExt::for_scope` is no longer useful as it's replaced by
methods on `FileName` and `RealFileName`.
2025-12-12 07:33:09 +01:00
Jacob Pratt
e5f552a02b
Rollup merge of #149592 - oli-obk:no_is_const_default_method_fn, r=fee1-dead
`is_const_default_method` is completely handled by the `constness` query

After  rust-lang/rust#149444 this function became obsolete

r? `@fee1-dead`
2025-12-05 23:26:37 -05:00
Matthias Krüger
a43b30c113
Rollup merge of #149671 - RalfJung:interpret-float-min-max, r=mati865
interpret: test SNaN handling of float min/max and update comments

Also see https://github.com/rust-lang/rust/pull/149563.

I also renamed these enum variants so they are not almost identical.
2025-12-05 16:17:13 +01:00
bors
97b131c900 Auto merge of #148602 - BoxyUwU:coercion_cleanup_uncontroversial, r=lcnr
misc coercion cleanups and handle safety correctly

r? lcnr

### "remove normalize call"

Fixes rust-lang/rust#132765

If the normalization fails we would sometimes get a `TypeError` containing inference variables created inside of the probe used by coercion. These would then get leaked out causing ICEs in diagnostics logic

### "leak check and lub for closure<->closure coerce-lubs of same defids"

Fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/233
```rust
fn peculiar() -> impl Fn(u8) -> u8 {
    return |x| x + 1
}
```
the `|x| x + 1` expr has a type of `Closure(?31t)` which we wind up inferring the RPIT to. The `CoerceMany` `ret_coercion` for the whole `peculiar` typeck has an expected type of `RPIT` (unnormalized). When we type check the `return |x| x + 1` expr we go from the never type to `Closure(?31t)` which then participates in the `ret_coercion` giving us a `coerce-lub(RPIT, Closure(?31t))`.

Normalizing `RPIT` gives us some `Closure(?50t)` where `?31t` and `?50t` have been unified with `?31t` as the root var. `resolve_vars_if_possible` doesn't resolve infer vars to their roots so these wind up with different structural identities so the fast path doesn't apply and we fall back to coercing to a `fn` ptr. cc rust-lang/rust#147193 which also fixes this

New solver probably just gets more inference variables here because canonicalization + generally different approach to normalization of opaques. Idk :3

### FCP worthy stuffy

there are some other FCP worthy things but they're in my FCP comment which also contains some analysis of the breaking nature of the previously listed changes in this PR: https://github.com/rust-lang/rust/pull/148602#issuecomment-3503497467
2025-12-05 11:46:41 +00:00
Ralf Jung
f040a1a915 interpret: test SNaN handling of float min/max and update comments 2025-12-05 08:53:42 +01:00
Boxy Uwu
76bd21ad66 account for safe target features in fndef<->closure and fndef<->fndef coerce-lubs 2025-12-03 14:55:41 +00:00
Oli Scherer
0ab78c1523 is_const_default_method is completely handled by the constness query 2025-12-03 12:38:24 +00:00
lcnr
02d84c8d23 generic normalization errors to TooGeneric 2025-12-01 13:00:22 +01:00
Matthias Krüger
9507d5c149
Rollup merge of #149444 - fee1-dead-contrib:push-lurmmylquwsq, r=oli-obk
collapse `constness` query `match` logic

We already have the HIR node data, so no need for asking `def_kind` again.

r? oli-obk
2025-11-30 12:03:23 +01:00
Deadbeef
cf91330b6b collapse constness query match logic
We already have the HIR node data, so no need for asking `def_kind` again.
2025-11-29 20:00:40 -05:00
Matthias Krüger
8e4c70f02b
Rollup merge of #148746 - RalfJung:mutable-ref-in-const, r=davidtwco
const validation: remove check for mutable refs in final value of const

This check rejects code that is not necessarily UB, e.g. a mutable ref to a `static mut` that is very carefully used correctly. That led to us having to describe it in the Reference, which uncovered just how ad-hoc this check is (https://github.com/rust-lang/reference/issues/2074).

Even without this check, we still reject things like
```rust
const C: &mut i32 = &mut 0;
```
This is rejected by const checking -- the part of the frontend that looks at the source code and says whether it is allowed in const context. In the Reference, this restriction is explained [here](https://doc.rust-lang.org/nightly/reference/const_eval.html#r-const-eval.const-expr.borrows).

So, the check during validation is just a safety net. And it is already a safety net with gaping holes since we only check `&mut T`, not `&UnsafeCell<T>`, due to the fact that we promote some immutable values that have `!Freeze` type so `&!Freeze` actually can occur in the final value of a const.

So... it may be time for me to acknowledge that the "mutable ref in final value of const" check is a cure that's worth than the disease. Nobody asked for that check, I just added it because I was worried about soundness issues when we allow mutable references in constants. Originally it was much stricter, but I had to slowly relax it to its current form to prevent t from firing on code we intend to allow. In the end there are only 3 tests left that trigger this error, and they are all just constants containing references to mutable statics -- not the safest code in the world, but also not so bad that we have to spend a lot of time devising a core language limitation and associated Reference wording to prevent it from ever happening.

So... `@rust-lang/wg-const-eval` `@rust-lang/lang`  I propose that we allow code like this
```rust
static mut S: i32 = 3;
const C2: &'static mut i32 = unsafe { &mut * &raw mut S };
```
`@theemathas` would be great if you could try to poke a hole into this. ;)
2025-11-29 20:54:05 +01:00
Stuart Cook
df6f24cc51
Rollup merge of #149239 - RalfJung:float-intrinsics, r=tgross35
clarify float min/max behavios for NaNs and signed zeros

The first comment is internal, it only documents the intrinsics to more clearly say what they do.
This makes the currently implemented semantics more explicit, so one does not have to go look for the publicly exposed version of the operation to figure out what exactly should happen.

The second commit adds a NaN test to the doc comment for `min`/`max`, which matches what we already have for `minimum`/`maximum`.
2025-11-27 12:36:52 +11:00
Ralf Jung
8b87b25c80 intrinsics: clarify float min/max behavios for NaNs and signed zeros 2025-11-24 08:21:19 +01:00
bors
e9acbd99d3 Auto merge of #147827 - saethlin:maybeuninit-codegen2, r=scottmcm
Fix MaybeUninit codegen using GVN

This is an alternative to https://github.com/rust-lang/rust/pull/142837, based on https://github.com/rust-lang/rust/pull/146355#discussion_r2421651968.

The general approach I took here is to aggressively propagate anything that is entirely uninitialized. GVN generally takes the approach of only synthesizing small types, but we need to generate large consts to fix the codegen issue.

I also added a special case to MIR dumps for this where now an entirely uninit const is printed as `const <uninit>`, because otherwise we end up with extremely verbose dumps of the new consts.

After GVN though, we still end up with a lot of MIR that looks like this:
```
StorageLive(_1);
_1 = const <uninit>;
_2 = &raw mut _1;
```
Which will break tests/codegen-llvm/maybeuninit-rvo.rs with the naive lowering. I think the ideal fix here is to somehow omit these `_1 = const <uninit>` assignments that come directly after a StorageLive, but I'm not sure how to do that. For now at least, ignoring such assignments (even if they don't come right after a StorageLive) in codegen seems to work.

Note that since GVN is based on synthesizing a `ConstValue`  which has a defined layout, this scenario still gets deoptimized by LLVM.
```rust
#![feature(rustc_attrs)]
#![crate_type = "lib"]
use std::mem::MaybeUninit;

#[unsafe(no_mangle)]
pub fn oof() -> [[MaybeUninit<u8>; 8]; 8] {
    #[rustc_no_mir_inline]
    pub fn inner<T: Copy>() -> [[MaybeUninit<T>; 8]; 8] {
        [[MaybeUninit::uninit(); 8]; 8]
    }

    inner()
}
```
This case can be handled correctly if enough inlining has happened, or it could be handled by post-mono GVN. Synthesizing `UnevaluatedConst` or some other special kind of const seems dubious.
2025-11-23 17:09:07 +00:00
Ben Kimock
1a4852c5fe Fix MaybeUninit codegen using GVN 2025-11-23 08:23:49 -05:00
bors
6159a44067 Auto merge of #148434 - oli-obk:inherent-const-impl, r=fee1-dead
Inherent const impl

Some constifications are annoying because we need to repeat `T: Trait` bounds from an impl block on the individual constified `const fn`s as `T: [const] Trait`. We've brainstormed solutions before, and one would be to have separate `const impl` blocks or sth. However the final syntax will look, I decided to just impl this syntax and either have sth nice on nightly to work with or at least move the discussion along.

Also interacts with the discussion around `impl const Trait for Type` vs `const impl Trait for Type`, as we may want to use the latter to keep inherent and trait impls in sync (unless we come up with even another scheme).

* [ ] rustdoc + tests
* [ ] macro stability /regression tests

r? `@fee1-dead`

cc `@traviscross` `@rust-lang/project-const-traits`
2025-11-19 02:23:56 +00:00
Oli Scherer
ababa26251 Collect const_conditions for inherent impls 2025-11-18 16:00:18 +00:00
Oli Scherer
939afab37e Treat inherent methods in const impl blocks as const 2025-11-18 16:00:18 +00:00
Camille Gillot
63a7712552 Simplify implementation. 2025-11-18 00:10:03 +00:00
Camille Gillot
12e91cf814 Honor allow_internal_unstable for const intrinsics. 2025-11-18 00:10:03 +00:00
Camille Gillot
72444372ae Replace OffsetOf by an actual sum. 2025-11-18 00:10:03 +00:00
bors
89fe96197d Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts

That lets us remove this gnarly implementation from Miri and const-eval.

However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2025-11-17 04:36:16 +00:00
Ralf Jung
324e47ba2b when writing a scalar pair, always reset the entire destination range 2025-11-15 10:09:43 +01:00
Ralf Jung
907fd85e16 const-eval: fix and re-enable pointer fragment support 2025-11-15 10:09:42 +01:00
Matthias Krüger
e5a69bb215
Rollup merge of #148683 - fmease:rm-const_trait-attr, r=fee1-dead
Remove `#[const_trait]`

Remove `#[const_trait]` since we now have `const trait`. Update all structured diagnostics that still suggested the attribute.

r? ```@rust-lang/project-const-traits```
2025-11-09 17:37:05 +01:00
Ralf Jung
3d7c9bdbb7 const validation: remove check for mutable refs in final value of const 2025-11-09 14:32:01 +01:00
bors
20f1c045c4 Auto merge of #148721 - Zalathar:rollup-398va3y, r=Zalathar
Rollup of 22 pull requests

Successful merges:

 - rust-lang/rust#128666 (Add `overflow_checks` intrinsic)
 - rust-lang/rust#146305 (Add correct suggestion for multi-references for self type in method)
 - rust-lang/rust#147179 ([DebugInfo] Fix container types failing to find template args)
 - rust-lang/rust#147743 (Show packed field alignment in mir_transform_unaligned_packed_ref)
 - rust-lang/rust#148079 (Rename `downcast_[ref|mut]_unchecked` -> `downcast_unchecked_[ref|mut]`)
 - rust-lang/rust#148084 (Optimize path components iteration on platforms that don't have prefixes)
 - rust-lang/rust#148126 (Fix rust stdlib build failing for VxWorks)
 - rust-lang/rust#148204 (Modify contributor email entries in .mailmap)
 - rust-lang/rust#148279 (rustc_builtin_macros: rename bench parameter to avoid collisions with user-defined function names)
 - rust-lang/rust#148333 (constify result unwrap unchecked)
 - rust-lang/rust#148539 (Add Allocator proxy impls for Box, Rc, and Arc)
 - rust-lang/rust#148601 (`invalid_atomic_ordering`: also lint `update` & `try_update`)
 - rust-lang/rust#148612 (Add note for identifier with attempted hygiene violation)
 - rust-lang/rust#148613 (Switch hexagon targets to rust-lld)
 - rust-lang/rust#148619 (Enable std locking functions on AIX)
 - rust-lang/rust#148644 ([bootstrap] Make `--open` option work with `doc src/tools/error_index_generator`)
 - rust-lang/rust#148649 (don't completely reset `HeadUsages`)
 - rust-lang/rust#148673 (Remove a remnant of `dyn*` from the parser)
 - rust-lang/rust#148675 (Remove eslint-js from npm dependencies)
 - rust-lang/rust#148680 (Recover `[T: N]` as `[T; N]`)
 - rust-lang/rust#148688 (Remove unused argument `features` from `eval_config_entry`)
 - rust-lang/rust#148711 (Use the current lint note id when parsing `cfg!()`)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-11-09 08:27:35 +00:00
Stuart Cook
068e784890
Rollup merge of #147743 - 21aslade:packed-diagnostic, r=RalfJung
Show packed field alignment in mir_transform_unaligned_packed_ref

Fixes rust-lang/rust#147528

I left the expected padding for the field out of the error message so the message would be the same on all platforms. It also isn't always possible to know the expected alignment, so this makes the message simpler.
2025-11-09 13:22:25 +11:00
Stuart Cook
d3475140ee
Rollup merge of #128666 - pitaj:intrinsic-overflow_checks, r=BoxyUwU
Add `overflow_checks` intrinsic

This adds an intrinsic which allows code in a pre-built library to inherit the overflow checks option from a crate depending on it. This enables code in the standard library to explicitly change behavior based on whether `overflow_checks` are enabled, regardless of the setting used when standard library was compiled.

This is very similar to the `ub_checks` intrinsic, and refactors the two to use a common mechanism.

The primary use case for this is to allow the new `RangeFrom` iterator to yield the maximum element before overflowing, as requested [here](https://github.com/rust-lang/rust/issues/125687#issuecomment-2151118208). This PR includes a working `IterRangeFrom` implementation based on this new intrinsic that exhibits the desired behavior.

[Prior discussion on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Ability.20to.20select.20code.20based.20on.20.60overflow_checks.60.3F)
2025-11-09 13:22:23 +11:00
bors
acda5e9f9a Auto merge of #148692 - matthiaskrgr:rollup-hryk71f, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#145656 (Stabilize s390x `vector` target feature and `is_s390x_feature_detected!` macro)
 - rust-lang/rust#147024 (std_detect: Support run-time detection on OpenBSD using elf_aux_info)
 - rust-lang/rust#147534 (Implement SIMD funnel shifts in const-eval/Miri)
 - rust-lang/rust#147540 (Stabilise `as_array` in `[_]` and `*const [_]`; stabilise `as_mut_array` in `[_]` and `*mut [_]`.)
 - rust-lang/rust#147686 (update isolate_highest_one for NonZero<T>)
 - rust-lang/rust#148230 (rustdoc: Properly highlight shebang, frontmatter & weak keywords in source code pages and code blocks)
 - rust-lang/rust#148555 (Fix rust-by-example spanish translation)
 - rust-lang/rust#148556 (Fix suggestion for returning async closures)
 - rust-lang/rust#148585 ([rustdoc] Replace `print` methods with functions to improve code readability)
 - rust-lang/rust#148600 (re-use `self.get_all_attrs` result for pass indirectly attribute)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-11-09 01:40:19 +00:00
bors
72b21e1a64 Auto merge of #139558 - camelid:mgca-const-items, r=oli-obk,BoxyUwU
mgca: Add ConstArg representation for const items

tracking issue: rust-lang/rust#132980
fixes rust-lang/rust#131046
fixes rust-lang/rust#134641

As part of implementing `min_generic_const_args`, we need to distinguish const items that can be used in the type system, such as in associated const equality projections, from const items containing arbitrary const code, which must be kept out of the type system. Specifically, all "type consts" must be either concrete (no generics) or generic with a trivial expression like `N` or a path to another type const item.

To syntactically distinguish these cases, we require, for now at least, that users annotate all type consts with the `#[type_const]` attribute. Then, we validate that the const's right-hand side is indeed eligible to be a type const and represent it differently in the HIR.

We accomplish this representation using a new `ConstItemRhs` enum in the HIR, and a similar but simpler enum in the AST. When `#[type_const]` is **not** applied to a const (e.g. on stable), we represent const item right-hand sides (rhs's) as HIR bodies, like before. However, when the attribute is applied, we instead lower to a `hir::ConstArg`. This syntactically distinguishes between trivial const args (paths) and arbitrary expressions, which are represented using `AnonConst`s. Then in `generics_of`, we can take advantage of the existing machinery to bar the `AnonConst` rhs's from using parent generics.
2025-11-08 22:31:33 +00:00
Boxy Uwu
a7626dc996 Fix const qualifs under mgca 2025-11-08 13:50:48 -05:00
Peter Jaszkowiak
cc8b95cc54 add overflow_checks intrinsic 2025-11-08 10:57:35 -07:00
Matthias Krüger
0f786bd8fb
Rollup merge of #147534 - sayantn:simd-funnel-shifts, r=RalfJung
Implement SIMD funnel shifts in const-eval/Miri

Split off from rust-lang/rust#147520 with just this change for easier review

r? ```@RalfJung```
2025-11-08 15:42:21 +01:00
León Orell Valerian Liehr
c262920059
Remove #[const_trait] 2025-11-08 07:37:15 +01:00
21aslade
566a86b02f show packed alignment in mir_transform_unaligned_packed_ref 2025-11-07 13:57:37 -07:00
sayantn
a7aedeb5c8
implement SIMD funnel shifts in const-eval 2025-11-07 16:09:50 +05:30
Ralf Jung
bc809befe2 use funnel shift as fallback impl for rotating shifts 2025-11-06 08:02:10 +01:00
bjorn3
973c7527b4 Unify the configuration of the compiler docs
Previously it was rather inconsistent which crates got the rust logo and
which didn't and setting html_root_url was forgotten in many cases.
2025-11-05 11:25:27 +00:00
sayantn
ffe6cf6e16
Add implementation of the alignment parameter in Miri 2025-11-04 03:02:38 +05:30
Guillaume Gomez
c8625a5543
Rollup merge of #147520 - sayantn:simd-const-eval, r=RalfJung
Port the remaining SIMD intrinsics to const-eval

successor to rust-lang/rust#146568, this refactors some implementations and ports the implementation of `simd_fma` and `simd_relaxed_fma`to `rustc_const_eval`

Also adds some remaining f16/f128 support in these intrinsics

r? `@RalfJung`
2025-11-03 17:20:32 +01:00
sayantn
4d70bf4c5a
Add some missing f16-f128 support in intrinsics 2025-11-03 12:22:51 +05:30
sayantn
ebf2e10238
Refactor float rounding intrinsics a bit 2025-11-03 12:22:50 +05:30
sayantn
d335ea91b5
Refactor implementation of float minmax intrinsics 2025-11-03 12:22:42 +05:30
Esteban Küber
74b7592ce9 fix rebase 2025-11-02 20:17:06 +00:00
Esteban Küber
a2c3913007 review comments 2025-11-02 20:12:26 +00:00
Esteban Küber
bf45da7e51 Account for #![feature(const_trait_impl)] state 2025-11-02 20:12:26 +00:00
Esteban Küber
9bc814cc8d Point at the enclosing const context
```
error[E0015]: cannot call non-const associated function `Foo::{constant#0}::Foo::<17>::value` in constants
  --> $DIR/nested-type.rs:15:5
   |
LL |   struct Foo<const N: [u8; {
   |  __________________________-
LL | |     struct Foo<const N: usize>;
LL | |
LL | |     impl<const N: usize> Foo<N> {
...  |
LL | |     Foo::<17>::value()
   | |     ^^^^^^^^^^^^^^^^^^
LL | |
LL | | }]>;
   | |_- calls in constants are limited to constant functions, tuple structs and tuple variants
```
2025-11-02 20:12:26 +00:00