about summary refs log tree commit diff
path: root/compiler/rustc_const_eval/src/const_eval
AgeCommit message (Collapse)AuthorLines
2025-09-16Add span for struct tail recursion limit errorTawan Muadmuenwai-0/+2
2025-08-26Rollup merge of #144885 - zachs18:ptr_guaranteed_cmp_more, r=RalfJungStuart Cook-15/+103
Implement some more checks in `ptr_guaranteed_cmp`. * Pointers with different residues modulo their allocations' least common alignment are never equal. * Pointers to the same static allocation are equal if and only if they have the same offset. * Pointers to different non-zero-sized static allocations are unequal if both point within their allocation, and not on opposite ends. Tracking issue for `const_raw_ptr_comparison`: <https://github.com/rust-lang/rust/issues/53020> This should not affect `is_null`, the only usage of this intrinsic on stable. Closes https://github.com/rust-lang/rust/issues/144584
2025-08-23Implement some more checks for `ptr_guaranteed_cmp` in consteval:Zachary S-15/+103
Pointers with different residues modulo their least common allocation alignment are never equal. Pointers to the same static allocation are equal if and only if they have the same offset. Strictly in-bounds (in-bounds and not one-past-the-end) pointers to different static allocations are always unequal. A pointer cannot be equal to an integer if `ptr-int` cannot be null. Also adds more tests for `ptr_guaranteed_cmp`. Co-authored-by: Ralf Jung <post@ralfj.de>
2025-08-17Auto merge of #144081 - RalfJung:const-ptr-fragments, r=oli-obkbors-0/+7
const-eval: full support for pointer fragments This fixes https://github.com/rust-lang/const-eval/issues/72 and makes `swap_nonoverlapping` fully work in const-eval by enhancing per-byte provenance tracking with tracking of *which* of the bytes of the pointer this one is. Later, if we see all the same bytes in the exact same order, we can treat it like a whole pointer again without ever risking a leak of the data bytes (that encode the offset into the allocation). This lifts the limitation that was discussed quite a bit in https://github.com/rust-lang/rust/pull/137280. For a concrete piece of code that used to fail and now works properly consider this example doing a byte-for-byte memcpy in const without using intrinsics: ```rust use std::{mem::{self, MaybeUninit}, ptr}; type Byte = MaybeUninit<u8>; const unsafe fn memcpy(dst: *mut Byte, src: *const Byte, n: usize) { let mut i = 0; while i < n { *dst.add(i) = *src.add(i); i += 1; } } const _MEMCPY: () = unsafe { let ptr = &42; let mut ptr2 = ptr::null::<i32>(); // Copy from ptr to ptr2. memcpy(&mut ptr2 as *mut _ as *mut _, &ptr as *const _ as *const _, mem::size_of::<&i32>()); assert!(*ptr2 == 42); }; ``` What makes this code tricky is that pointers are "opaque blobs" in const-eval, we cannot just let people look at the individual bytes since *we don't know what those bytes look like* -- that depends on the absolute address the pointed-to object will be placed at. The code above "breaks apart" a pointer into individual bytes, and then puts them back together in the same order elsewhere. This PR implements the logic to properly track how those individual bytes relate to the original pointer, and to recognize when they are in the right order again. We still reject constants where the final value contains a not-fully-put-together pointer: I have no idea how one could construct an LLVM global where one byte is defined as "the 3rd byte of a pointer to that other global over there" -- and even if LLVM supports this somehow, we can leave implementing that to a future PR. It seems unlikely to me anyone would even want this, but who knows.^^ This also changes the behavior of Miri, by tracking the order of bytes with provenance and only considering a pointer to have valid provenance if all bytes are in the original order again. This is related to https://github.com/rust-lang/unsafe-code-guidelines/issues/558. It means one cannot implement XOR linked lists with strict provenance any more, which is however only of theoretical interest. Practically I am curious if anyone will show up with any code that Miri now complains about - that would be interesting data. Cc `@rust-lang/opsem`
2025-08-12Revert "Partially outline code inside the panic! macro".Mara Bos-1/+1
Without any tests/benchmarks that show some improvement, it's hard to know whether the change had any positive effect at all. (And if it did, whether that effect is still achieved today.)
2025-07-30const-eval: full support for pointer fragmentsRalf Jung-0/+7
2025-07-23Remove useless lifetime parameter.Camille GILLOT-6/+6
2025-07-23Give an AllocId to ConstValue::Slice.Camille GILLOT-2/+1
2025-07-20fix handling of base address for TypeId allocationsRalf Jung-13/+5
2025-07-18Show the memory of uninit readsOli Scherer-7/+22
2025-07-17parse `const trait Trait`Deadbeef-2/+2
2025-07-16simplfy memory kind handling during interningRalf Jung-3/+0
2025-07-16const heap: fix ICE on forgotten make_globalRalf Jung-3/+8
2025-07-16Comment more code and make tests clearerDeadbeef-1/+5
Co-Authored-By: Ralf Jung <post@ralfj.de>
2025-07-16format pointer later instead of eagerly converting to stringDeadbeef-6/+6
2025-07-16add `const_make_global`; err for `const_allocate` ptrs if didn't callDeadbeef-8/+45
Co-Authored-By: Ralf Jung <post@ralfj.de> Co-Authored-By: Oli Scherer <github333195615777966@oli-obk.de>
2025-07-07Rollup merge of #143584 - fee1-dead-contrib:push-skswvrwsrmll, r=RalfJungMatthias Krüger-3/+3
make `Machine::load_mir` infallible it doesn't need to return an `InterpResult`.
2025-07-07make `Machine::load_mir` infallibleDeadbeef-3/+3
it doesn't need to return an `InterpResult`.
2025-07-06interpret: rename StackPopCleanupRalf Jung-2/+2
2025-07-05Stop using Key trait randomlyMichael Goulet-3/+2
2025-07-02miri: improve errors for type validity assertion failuresRalf Jung-3/+41
2025-06-30Rollup merge of #143140 - RalfJung:ptr-into-parts, r=oli-obkMatthias Krüger-6/+7
give Pointer::into_parts a more scary name and offer a safer alternative `into_parts` is a bit too innocent of a name for a somewhat subtle operation. r? `@oli-obk`
2025-06-30Remove the nullary intrinsic const eval logic and treat them like other ↵Oli Scherer-29/+1
intrinsics
2025-06-29give Pointer::into_parts a more scary name and offer a safer alternativeRalf Jung-6/+7
2025-06-28Auto merge of #141759 - 1c3t3a:discriminants-query, r=saethlinbors-0/+1
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-27Rollup merge of #143096 - RalfJung:tag_for_variant, r=compiler-errorsMatthias Krüger-9/+4
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-27tag_for_variant: properly pass TypingEnvRalf Jung-9/+4
2025-06-27Rollup merge of #143084 - RalfJung:const-eval-recursive-static-write, r=oli-obkGuillaume Gomez-7/+15
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-27const-eval: error when initializing a static writes to that staticRalf Jung-7/+15
2025-06-27Add InterpCx::layout_of with tracing, shadowing LayoutOfStypox-3/+2
2025-06-27Insert checks for enum discriminants when debug assertions are enabledBastian Kersting-0/+1
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-26const-eval: allow constants to refer to mutable/external memory, but reject ↵Ralf Jung-35/+10
such constants as patterns
2025-06-07const-eval error: always say in which item the error occurredRalf Jung-15/+3
also adjust the wording a little so that we don't say "the error occurred here" for two different spans
2025-06-06Rollup merge of #142103 - scottmcm:fieldidx-in-interp, r=oli-obkGuillaume Gomez-5/+5
Update `InterpCx::project_field` to take `FieldIdx` As suggested by Ralf in https://github.com/rust-lang/rust/pull/142005#discussion_r2125839015
2025-06-05Update `InterpCx::project_field` to take `FieldIdx`Scott McMurray-5/+5
As suggested by Ralf in 142005.
2025-06-06Rollup merge of #142012 - oli-obk:no-optional-spans, r=fee1-deadMatthias Krüger-1/+1
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-05Replace some `Option<Span>` with `Span` and use DUMMY_SP instead of NoneOli Scherer-1/+1
2025-06-04Report the actual item that evaluation failed forOli Scherer-2/+3
2025-06-02Use the informative error as the main const eval error messageOli Scherer-19/+35
2025-05-27Rollup merge of #141513 - nia-e:allocbytes-extend, r=RalfJung许杰友 Jieyou Xu (Joe)-0/+8
interpret: add allocation parameters to `AllocBytes` Necessary for a better implementation of [rust-lang/miri#4343](https://github.com/rust-lang/miri/pull/4343). Also included here is the code from that PR, adapted to this new interface for the sake of example and so that CI can run on them; the Miri changes can be reverted and merged separately, though. r? `@RalfJung`
2025-05-26extend allocbytes with associated typeNia Espera-0/+8
2025-05-22interpret: do not force_allocate all return placesRalf Jung-7/+12
2025-04-28AsyncDrop implementation using shim codegen of ↵Andrew Zhogin-0/+1
async_drop_in_place::{closure}, scoped async drop added.
2025-04-03Make LevelAndSource a structOli Scherer-1/+1
2025-04-02Move methods from `Map` to `TyCtxt`, part 5.Nicholas Nethercote-1/+1
This eliminates all methods on `Map`. Actually removing `Map` will occur in a follow-up PR.
2025-03-20interpret memory access hooks: also pass through the Pointer used for the accessRalf Jung-1/+2
2025-02-28Shorten span of panic failures in const contextEsteban Küber-5/+16
Previously, we included a redundant prefix on the panic message and a postfix of the location of the panic. The prefix didn't carry any additional information beyond "something failed", and the location of the panic is redundant with the diagnostic's span, which gets printed out even if its code is not shown. ``` error[E0080]: evaluation of constant value failed --> $DIR/assert-type-intrinsics.rs:11:9 | LL | MaybeUninit::<!>::uninit().assume_init(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: aborted execution: attempted to instantiate uninhabited type `!` ``` ``` error[E0080]: evaluation of `Fail::<i32>::C` failed --> $DIR/collect-in-dead-closure.rs:9:19 | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic | = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) ``` ``` error[E0080]: evaluation of constant value failed --> $DIR/uninhabited.rs:41:9 | LL | assert!(false); | ^^^^^^^^^^^^^^ evaluation panicked: assertion failed: false | = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) ``` --- When the primary span for a const error is the same as the first frame in the const error report, skip it. ``` error[E0080]: evaluation of constant value failed --> $DIR/issue-88434-removal-index-should-be-less.rs:3:24 | LL | const _CONST: &[u8] = &f(&[], |_| {}); | ^^^^^^^^^^^^^^ evaluation panicked: explicit panic | note: inside `f::<{closure@$DIR/issue-88434-removal-index-should-be-less.rs:3:31: 3:34}>` --> $DIR/issue-88434-removal-index-should-be-less.rs:10:5 | LL | panic!() | ^^^^^^^^ the failure occurred here = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) ``` instead of ``` error[E0080]: evaluation of constant value failed --> $DIR/issue-88434-removal-index-should-be-less.rs:10:5 | LL | panic!() | ^^^^^^^^ explicit panic | note: inside `f::<{closure@$DIR/issue-88434-removal-index-should-be-less.rs:3:31: 3:34}>` --> $DIR/issue-88434-removal-index-should-be-less.rs:10:5 | LL | panic!() | ^^^^^^^^ note: inside `_CONST` --> $DIR/issue-88434-removal-index-should-be-less.rs:3:24 | LL | const _CONST: &[u8] = &f(&[], |_| {}); | ^^^^^^^^^^^^^^ = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) ``` --- Revert order of constant evaluation errors Point at the code the user wrote first and std functions last. ``` error[E0080]: evaluation of constant value failed --> $DIR/const-errs-dont-conflict-103369.rs:5:25 | LL | impl ConstGenericTrait<{my_fn(1)}> for () {} | ^^^^^^^^ evaluation panicked: Some error occurred | note: called from `my_fn` --> $DIR/const-errs-dont-conflict-103369.rs:10:5 | LL | panic!("Some error occurred"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) ``` instead of ``` error[E0080]: evaluation of constant value failed --> $DIR/const-errs-dont-conflict-103369.rs:10:5 | LL | panic!("Some error occurred"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Some error occurred | note: called from `<() as ConstGenericTrait<{my_fn(1)}>>::{constant#0}` --> $DIR/const-errs-dont-conflict-103369.rs:5:25 | LL | impl ConstGenericTrait<{my_fn(1)}> for () {} | ^^^^^^^^ = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) ```
2025-02-25Teach structured errors to display short `Ty`Esteban Küber-4/+4
Make it so that every structured error annotated with `#[derive(Diagnostic)]` that has a field of type `Ty<'_>`, the printing of that value into a `String` will look at the thread-local storage `TyCtxt` in order to shorten to a length appropriate with the terminal width. When this happen, the resulting error will have a note with the file where the full type name was written to. ``` error[E0618]: expected function, found `((..., ..., ..., ...), ..., ..., ...)`` --> long.rs:7:5 | 6 | fn foo(x: D) { //~ `x` has type `(... | - `x` has type `((..., ..., ..., ...), ..., ..., ...)` 7 | x(); //~ ERROR expected function, found `(... | ^-- | | | call expression requires function | = note: the full name for the type has been written to 'long.long-type-14182675702747116984.txt' = note: consider using `--verbose` to print the full type name to the console ```
2025-02-22Fix binding mode problemsMichael Goulet-6/+4
2025-02-13simplify valtree branches constructionLukas Markeffsky-15/+12