2445 Commits

Author SHA1 Message Date
Matthias Krüger
c6de7ca41a
Rollup merge of #142708 - Darksonn:location-len-without-nul, r=Mark-Simulacrum
Do not include NUL-terminator in computed length

This PR contains just the first commit of rust-lang/rust#142579 which changes it so that the string length stored in the `Location` is the length of the `&str` rather than the length of the `&CStr`. Since most users will want the `&str` length, it seems better to optimize for that use-case.

There should be no visible changes in the behavior or API.
2025-06-28 22:05:28 +02:00
bors
b63223c152 Auto merge of #141759 - 1c3t3a:discriminants-query, r=saethlin
Insert checks for enum discriminants when debug assertions are enabled

Similar to the existing null-pointer and alignment checks, this checks for valid enum discriminants on creation of enums through unsafe transmutes. Essentially this sanitizes patterns like the following:
```rust
let val: MyEnum = unsafe { std::mem::transmute<u32, MyEnum>(42) };
```

An extension of this check will be done in a follow-up that explicitly sanitizes for extern enum values that come into Rust from e.g. C/C++.

This check is similar to Miri's capabilities of checking for valid construction of enum values.

This PR is inspired by saethlin@'s PR
https://github.com/rust-lang/rust/pull/104862. Thank you so much for keeping this code up and the detailed comments!

I also pair-programmed large parts of this together with vabr-g@.

r? `@saethlin`
2025-06-28 10:25:00 +00:00
Matthias Krüger
994ed31a96
Rollup merge of #143096 - RalfJung:tag_for_variant, r=compiler-errors
tag_for_variant: properly pass TypingEnv

Hard-coding `fully_monomorphized` here does not seem right...

This came up [on Zulip](https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/.E2.9C.94.20VariantId.3DDiscriminant.20when.20tag.20is.20niche.20encoded.3F/with/526103956).
2025-06-27 22:13:06 +02:00
Matthias Krüger
088f6ab1c5
Rollup merge of #143092 - RalfJung:const-check-lifetime-ext, r=oli-obk
const checks for lifetime-extended temporaries: avoid 'top-level scope' terminology

This error recently got changed in https://github.com/rust-lang/rust/pull/140942 to use the terminology of "top-level scope", but after further discussion in https://github.com/rust-lang/reference/pull/1865 it seems the reference will not be using that terminology after all. So let's also remove it from the compiler again, and let's focus on what actually happens with these temporaries: their lifetime is extended until the end of the program.

r? ``@oli-obk`` ``@traviscross``
2025-06-27 22:13:06 +02:00
Matthias Krüger
2d59c4e0fe
Rollup merge of #143046 - RalfJung:zst-unsafe-cell, r=lcnr,oli-obk
const validation: properly ignore zero-sized UnsafeCell

Fixes https://github.com/rust-lang/rust/issues/142948
r? `@oli-obk`
2025-06-27 22:13:05 +02:00
Matthias Krüger
36c2b011cb
Rollup merge of #139858 - oli-obk:new-const-traits-syntax, r=fee1-dead
New const traits syntax

This PR only affects the AST and doesn't actually change anything semantically.

All occurrences of `~const` outside of libcore have been replaced by `[const]`. Within libcore we have to wait for rustfmt to be bumped in the bootstrap compiler. This will happen "automatically" (when rustfmt is run) during the bootstrap bump, as rustfmt converts `~const` into `[const]`. After this we can remove the `~const` support from the parser

Caveat discovered during impl: there is no legacy bare trait object recovery for `[const] Trait` as that snippet in type position goes down the slice /array parsing code and will error

r? ``@fee1-dead``

cc ``@nikomatsakis`` ``@traviscross`` ``@compiler-errors``
2025-06-27 22:13:00 +02:00
Ralf Jung
5af79242ac tag_for_variant: properly pass TypingEnv 2025-06-27 17:04:33 +02:00
Ralf Jung
d0fa0260ca const checks: avoid 'top-level scope' terminology 2025-06-27 17:03:48 +02:00
Guillaume Gomez
0bbeeffe57
Rollup merge of #143084 - RalfJung:const-eval-recursive-static-write, r=oli-obk
const-eval: error when initializing a static writes to that static

Fixes https://github.com/rust-lang/rust/issues/142404 by also calling the relevant hook for writes, not just reads. To avoid erroring during the actual write of the initial value, we neuter the hook when popping the final stack frame.

Calling the hook during writes requires changing its signature since we cannot pass in the entire interpreter any more.

While doing this I also realized a gap in https://github.com/rust-lang/rust/pull/142575 for zero-sized copies on the read side, so I fixed that and added a test.

r? `@oli-obk`
2025-06-27 15:04:57 +02:00
Guillaume Gomez
8256a75fff
Rollup merge of #143051 - Stypox:tracing-validity, r=RalfJung
Add tracing to `validate_operand`

This PR adds a tracing call to keep track of how much time is spent in `validate_operand` and `const_validate_operand`. Let me know if more fine-grained tracing is needed (e.g. adding tracing to `validate_operand_internal` too, which is just called from those two functions).

I also fixed the rustdoc of `validate_operand` and `const_validate_operand` since it was referencing an older name for the `val` parameter which was renamed in cbdcbf0d6a586792c5e0a0b8965a3179bac56120.

Here is some tracing output when Miri is run on `src/tools/miri/tests/pass/hello.rs`, visualizable in [ui.perfetto.dev](https://ui.perfetto.dev/): [trace-1750932222218210.json](https://github.com/user-attachments/files/20924000/trace-1750932222218210.json)

**Note: obtaining tracing output depends on https://github.com/rust-lang/miri/pull/4406, but this PR is standalone and can be merged without waiting for https://github.com/rust-lang/miri/pull/4406.**

r? `@RalfJung`
2025-06-27 15:04:55 +02:00
Ralf Jung
ed4f01ed2e const-eval: error when initializing a static writes to that static 2025-06-27 14:39:35 +02:00
Stypox
708dc15cf1
Add InterpCx::layout_of with tracing, shadowing LayoutOf 2025-06-27 11:49:22 +02:00
Bastian Kersting
1087042e22 Insert checks for enum discriminants when debug assertions are enabled
Similar to the existing nullpointer and alignment checks, this checks
for valid enum discriminants on creation of enums through unsafe
transmutes. Essentially this sanitizes patterns like the following:
```rust
let val: MyEnum = unsafe { std::mem::transmute<u32, MyEnum>(42) };
```
An extension of this check will be done in a follow-up that explicitly
sanitizes for extern enum values that come into Rust from e.g. C/C++.

This check is similar to Miri's capabilities of checking for valid
construction of enum values.

This PR is inspired by saethlin@'s PR
https://github.com/rust-lang/rust/pull/104862. Thank you so much for
keeping this code up and the detailed comments!

I also pair-programmed large parts of this together with vabr-g@.
2025-06-27 09:37:36 +00:00
Stypox
5e1082899b
Add tracing for instantiate_from_frame_and_normalize_erasing_regions 2025-06-27 11:32:32 +02:00
Stypox
89a636fb12
Add tracing to validate_operand 2025-06-27 10:15:27 +02:00
bors
e61dd437f3 Auto merge of #143074 - compiler-errors:rollup-cv64hdh, r=compiler-errors
Rollup of 18 pull requests

Successful merges:

 - rust-lang/rust#137843 (make RefCell unstably const)
 - rust-lang/rust#140942 (const-eval: allow constants to refer to mutable/external memory, but reject such constants as patterns)
 - rust-lang/rust#142549 (small iter.intersperse.fold() optimization)
 - rust-lang/rust#142637 (Remove some glob imports from the type system)
 - rust-lang/rust#142647 ([perf] Compute hard errors without diagnostics in impl_intersection_has_impossible_obligation)
 - rust-lang/rust#142700 (Remove incorrect comments in `Weak`)
 - rust-lang/rust#142927 (Add note to `find_const_ty_from_env`)
 - rust-lang/rust#142967 (Fix RwLock::try_write documentation for WouldBlock condition)
 - rust-lang/rust#142986 (Port `#[export_name]` to the new attribute parsing infrastructure)
 - rust-lang/rust#143001 (Rename run always )
 - rust-lang/rust#143010 (Update `browser-ui-test` version to `0.20.7`)
 - rust-lang/rust#143015 (Add `sym::macro_pin` diagnostic item for `core::pin::pin!()`)
 - rust-lang/rust#143033 (Expand const-stabilized API links in relnotes)
 - rust-lang/rust#143041 (Remove cache for citool)
 - rust-lang/rust#143056 (Move an ACE test out of the GCI directory)
 - rust-lang/rust#143059 (Fix 1.88 relnotes)
 - rust-lang/rust#143067 (Tracking issue number for `iter_macro`)
 - rust-lang/rust#143073 (Fix some fixmes that were waiting for let chains)

Failed merges:

 - rust-lang/rust#143020 (codegen_fn_attrs: make comment more precise)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-06-27 00:44:20 +00:00
Ralf Jung
bade3fd058 clarify and unify 'transient mutable borrow' errors 2025-06-26 18:11:24 +02:00
Ralf Jung
492526548d const-eval: allow constants to refer to mutable/external memory, but reject such constants as patterns 2025-06-26 18:09:47 +02:00
Matthias Krüger
158340f561
Rollup merge of #141311 - folkertdev:tidy-natural-sort, r=jieyouxu
make `tidy-alphabetical` use a natural sort

The idea here is that these lines should be correctly sorted, even though a naive string comparison would say they are not:

```
foo2
foo10
```

This is the ["natural sort order"](https://en.wikipedia.org/wiki/Natural_sort_order).

There is more discussion in [#t-compiler/help > tidy natural sort](https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/tidy.20natural.20sort/with/519111079)

Unfortunately, no standard sorting tools are smart enough to to this automatically (casting some doubt on whether we should make this change). Here are some sort outputs:

```
> cat foo.txt | sort
foo
foo1
foo10
foo2
mp
mp1e2
np",
np1e2",
> cat foo.txt | sort -n
foo
foo1
foo10
foo2
mp
mp1e2
np",
np1e2",
> cat foo.txt | sort -V
foo
foo1
foo2
foo10
mp
mp1e2
np1e2",
np",
```

Disappointingly, "numeric" sort does not actually have the behavior we want. It only sorts by numeric value if the line starts with a number. The "version" sort looks promising, but does something very unintuitive if you look at the final 4 values. None of the other options seem to have the desired behavior in all cases:

```
  -b, --ignore-leading-blanks  ignore leading blanks
  -d, --dictionary-order      consider only blanks and alphanumeric characters
  -f, --ignore-case           fold lower case to upper case characters
  -g, --general-numeric-sort  compare according to general numerical value
  -i, --ignore-nonprinting    consider only printable characters
  -M, --month-sort            compare (unknown) < 'JAN' < ... < 'DEC'
  -h, --human-numeric-sort    compare human readable numbers (e.g., 2K 1G)
  -n, --numeric-sort          compare according to string numerical value
  -R, --random-sort           shuffle, but group identical keys.  See shuf(1)
      --random-source=FILE    get random bytes from FILE
  -r, --reverse               reverse the result of comparisons
      --sort=WORD             sort according to WORD:
                                general-numeric -g, human-numeric -h, month -M,
                                numeric -n, random -R, version -V
  -V, --version-sort          natural sort of (version) numbers within text
```

r? ```@Noratrieb``` (it sounded like you know this code?)
2025-06-26 15:47:17 +02:00
Oli Scherer
eb7245a864 Change const trait bound syntax from ~const to [const] 2025-06-26 13:46:45 +00:00
Stypox
625f8ee5dc
Fix documentation of validate_operand
The name of the parameter changed from `op` to `val` in cbdcbf0d6a586792c5e0a0b8965a3179bac56120
2025-06-26 11:17:07 +02:00
Ralf Jung
7de39f55dd make size_and_align_of_mplace work on all projectable 2025-06-26 10:28:15 +02:00
Ralf Jung
3790eff4d4 const validation: properly ignore zero-sized UnsafeCell 2025-06-26 10:20:48 +02:00
Folkert de Vries
1dfc8406dc
make tidy-alphabetical use a natural sort 2025-06-25 22:52:38 +02:00
Jana Dönszelmann
63c5a84b74
Rollup merge of #142724 - xizheyin:avoid_overwrite_args, r=oli-obk
Add runtime check to avoid overwrite arg in `Diag`

## Origin PR description
At first, I set up a `debug_assert` check for the arg method to make sure that `args` in `Diag` aren't easily overwritten, and I added the `remove_arg()` method, so that if you do need to overwrite an arg, then you can explicitly call `remove_arg()` to remove it first, then call `arg()` to overwrite it.

For the code before the rust-lang/rust#142015 change, it won't compile because it will report an error
```
arg `instance`already exists.
```

This PR also modifies all diagnostics that fail the check to pass the check. There are two cases of check failure:

1. ~~Between *the parent diagnostic and the subdiagnostic*, or *between the subdiagnostics* have the same field between them. In this case, I renamed the conflicting fields.~~
2. ~~For subdiagnostics stored in `Vec`, the rendering may iteratively write the same arg over and over again. In this case, I changed the auto-generation with `derive(SubDiagnostic)` to manually implementing `SubDiagnostic` and manually rendered it with `eagerly_translate()`, similar to https://github.com/rust-lang/rust/issues/142031#issuecomment-2984812090, and after rendering it I manually deleted useless arg with the newly added `remove_arg` method.~~

## Final Decision

After trying and discussing, we made a final decision.

For `#[derive(Subdiagnostic)]`, This PR made two changes:

1. After the subdiagnostic is rendered, remove all args of this subdiagnostic, which allows for usage like `Vec<Subdiag>`.
2. Store `diag.args` before setting arguments, so that you can restore the contents of the main diagnostic after deleting the arguments after subdiagnostic is rendered, to avoid deleting the main diagnostic's arg when they have the same name args.
2025-06-25 22:14:55 +02:00
xizheyin
d2d17c60bd
Add runtime check to avoid overwrite arg easily in diag and store and restore snapshot when set subdiag arg
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-06-25 21:07:16 +08:00
Jubilee
4f477427b8
Rollup merge of #135731 - frank-king:feature/pin-borrow, r=eholk,traviscross
Implement parsing of pinned borrows

This PR implements part of #130494.

EDIT: It introduces `&pin mut $place` and `&pin const $place` as sugars for `std::pin::pin!($place)` and its shared reference equivalent, except that `$place` will not be moved when borrowing. The borrow check will be in charge of enforcing places cannot be moved or mutably borrowed since being pinned till dropped.

### Implementation steps:
- [x] parse the `&pin mut $place` and `&pin const $place` syntaxes
- [ ] borrowck of `&pin mut|const`
- [ ] support autoref of `&pin mut|const` when needed
2025-06-24 19:45:29 -07:00
Folkert de Vries
a123a36a1f
centralize -Zmin-function-alignment logic 2025-06-22 00:47:10 +02:00
Trevor Gross
5d6ecf584e
Rollup merge of #142575 - oli-obk:sneaky-self-init, r=RalfJung
Ensure copy* intrinsics also perform the static self-init checks

fixes rust-lang/rust#142532

r? `@RalfJung`
2025-06-20 13:36:01 -04:00
Oli Scherer
cfc22cfffb Ensure copy* intrinsics also perform the static self-init checks 2025-06-20 07:30:36 +00:00
Alice Ryhl
f3383e4942 Do not include NUL-terminator in computed length 2025-06-19 07:47:49 +00:00
Camille GILLOT
7fa94af556 Make feature suggestion more consistent. 2025-06-18 16:52:38 +00:00
Frank King
e627f88f88 Implement pinned borrows, part of pin_ergonomics 2025-06-15 10:21:29 +08:00
Jubilee
179bcf6805
Rollup merge of #142405 - oli-obk:type-once, r=RalfJung
Don't hardcode the intrinsic return types twice in the compiler

We already manually check intrinsic types in intrinsicck so we don't need to do it in the interpreter
2025-06-13 20:59:17 -07:00
Ralf Jung
62418f4c56 intrinsics: rename min_align_of to align_of 2025-06-12 17:50:25 +02:00
Oli Scherer
de4e7adc96 Don't hardcode the intrinsic return types twice in the compiler 2025-06-12 09:57:06 +00:00
Stypox
cd04717899
Fix enter_trace_span!() using wrong $crate paths 2025-06-11 12:22:20 +02:00
Ralf Jung
6d1db1144c const_eval: fix some outdated comments 2025-06-10 11:45:38 +02:00
Matthias Krüger
7ab938375d
Rollup merge of #142222 - compiler-errors:ocx-w-no-diag, r=lcnr
Dont make `ObligationCtxt`s with diagnostics unnecessarily

just a nit, shouldn't affect perf b/c `ObligationCtxt::new_with_diagnostics` should only be more expensive in the new trait solver, and I don't expect either of these to encounter errors today anyways.

r? oli-obk
2025-06-09 13:55:34 +02:00
Michael Goulet
d2afab4d60 Dont make ObligationCtxts with diagnostics unnecessarily 2025-06-08 22:40:44 -04:00
bors
334ba81275 Auto merge of #142220 - workingjubilee:rollup-idgfpof, r=workingjubilee
Rollup of 12 pull requests

Successful merges:

 - rust-lang/rust#141803 (Remove rustc's notion of "preferred" alignment AKA `__alignof`)
 - rust-lang/rust#142053 (Add new Tier-3 targets: `loongarch32-unknown-none*`)
 - rust-lang/rust#142089 (Replace all uses of sysroot_candidates with get_or_default_sysroot)
 - rust-lang/rust#142108 (compiler: Add track_caller to AbiMapping::unwrap)
 - rust-lang/rust#142132 (`tests/ui`: A New Order [6/N])
 - rust-lang/rust#142162 (UnsafePinned: update get() docs and signature to allow shared mutation)
 - rust-lang/rust#142171 (`tests/ui`: A New Order [7/N])
 - rust-lang/rust#142179 (store `target.min_global_align` as an `Align`)
 - rust-lang/rust#142183 (Added test for 30904)
 - rust-lang/rust#142194 (Remove all unused feature gates from the compiler)
 - rust-lang/rust#142199 (Do not free disk space in the `mingw-check-tidy` job)
 - rust-lang/rust#142210 (Run `mingw-check-tidy` on auto builds)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-06-09 02:20:44 +00:00
Jubilee Young
2e19658315 Remove rustc's notion of "preferred" alignment AKA __alignof
In PR 90877 T-lang decided not to remove `intrinsics::pref_align_of`.
However, the intrinsic and its supporting code
1.  is a nightly feature, so can be removed at compiler/libs discretion
2.  requires considerable effort in the compiler to support, as it
    necessarily complicates every single site reasoning about alignment
3.  has been justified based on relevance to codegen, but it is only a
    requirement for C++ (not C, not Rust) stack frame layout for AIX,
    in ways Rust would not consider even with increased C++ interop
4.  is only used by rustc to overalign some globals, not correctness
5.  can be adequately replaced by other rules for globals, as it mostly
    affects alignments for a few types under 16 bytes of alignment
6.  has only one clear benefactor: automating C -> Rust translation
    for GNU extensions like `__alignof`
7.  such code was likely intended to be `alignof` or `_Alignof`,
    because the GNU extension is a "false friend" of the C keyword,
    which makes the choice to support such a mapping very questionable
8.  makes it easy to do incorrect codegen in the compiler by its mere
    presence as usual Rust rules of alignment (e.g. `size == align * N`)
    do not hold with preferred alignment

The implementation is clearly damaging the code quality of the compiler.
Thus it is within the compiler team's purview to simply rip it out.
If T-lang wishes to have this intrinsic restored for c2rust's benefit,
it would have to use a radically different implementation that somehow
does not cause internal incorrectness.

Until then, remove the intrinsic and its supporting code, as one tool
and an ill-considered GCC extension cannot justify risking correctness.

Because we touch a fair amount of the compiler to change this at all,
and unfortunately the duplication of AbiAndPrefAlign is deep-rooted,
we keep an "AbiAlign" type which we can wean code off later.
2025-06-08 16:41:46 -07:00
Ralf Jung
17946c22b1 const-eval error: always say in which item the error occurred
also adjust the wording a little so that we don't say "the error occurred here" for two different spans
2025-06-07 13:42:30 +02:00
Guillaume Gomez
3a6f1b0375
Rollup merge of #142103 - scottmcm:fieldidx-in-interp, r=oli-obk
Update `InterpCx::project_field` to take `FieldIdx`

As suggested by Ralf in https://github.com/rust-lang/rust/pull/142005#discussion_r2125839015
2025-06-06 23:53:18 +02:00
Scott McMurray
8bce2255e8 Update InterpCx::project_field to take FieldIdx
As suggested by Ralf in 142005.
2025-06-05 19:15:56 -07:00
Matthias Krüger
c1d1f7a16f
Rollup merge of #142012 - oli-obk:no-optional-spans, r=fee1-dead
Replace some `Option<Span>` with `Span` and use DUMMY_SP instead of None

Turns out many locations actually have a span available that we could use, so I used it
2025-06-06 00:58:44 +02:00
Oli Scherer
fd3da4bebd Replace some Option<Span> with Span and use DUMMY_SP instead of None 2025-06-05 14:14:59 +00:00
Matthias Krüger
0820dd0bc2
Rollup merge of #142015 - oli-obk:wrong-instance, r=RalfJung
Report the actual item that evaluation failed for

instead of id of the last frame in the evaluation stack

r? ``@RalfJung``

fixes rust-lang/rust#142010
2025-06-05 16:02:03 +02:00
bors
c360e219f5 Auto merge of #135054 - cramertj:file-cstr, r=m-ou-se
Add Location::file_with_nul

This is useful for C/C++ APIs which expect the const char* returned from __FILE__ or std::source_location::file_name.

ACP: https://github.com/rust-lang/libs-team/issues/466
Tracking issue: https://github.com/rust-lang/rust/issues/141727
2025-06-05 10:21:20 +00:00
Taylor Cramer
b541f93372 Add Location::file_with_nul
This is useful for C/C++ APIs which expect the const char* returned
from __FILE__ or std::source_location::file_name.
2025-06-04 09:23:05 -07:00