Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

experiment: remove value-based reasoning for interior mutability #122789

Closed
wants to merge 2 commits into from

Conversation

RalfJung
Copy link
Member

This also stabilizes const_refs_to_cell as it's just a crater experiment anyway and that reduces the amount of regressions.

@rustbot
Copy link
Collaborator

rustbot commented Mar 20, 2024

r? @wesleywiser

rustbot has assigned @wesleywiser.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Mar 20, 2024
@rustbot
Copy link
Collaborator

rustbot commented Mar 20, 2024

Some changes occurred in exhaustiveness checking

cc @Nadrieril

Some changes occurred to MIR optimizations

cc @rust-lang/wg-mir-opt

@RalfJung RalfJung marked this pull request as draft March 20, 2024 19:12
@RalfJung RalfJung removed the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Mar 20, 2024
@RalfJung
Copy link
Member Author

Sorry for the pings, I forgot to mark this a draft. (Why does github make that so annoying? Just give me a checkbox, instead of remember this decision for the next PR...)

@RalfJung
Copy link
Member Author

@bors try

bors added a commit to rust-lang-ci/rust that referenced this pull request Mar 20, 2024
…<try>

experiment: remove value-based reasoning for interior mutability

This also stabilizes `const_refs_to_cell` as it's just a crater experiment anyway and that reduces the amount of regressions.
@bors
Copy link
Contributor

bors commented Mar 20, 2024

⌛ Trying commit 3660dd9 with merge cb4bf0e...

@@ -2,6 +2,7 @@

#![allow(rustc::untranslatable_diagnostic)]
#![allow(rustc::diagnostic_outside_of_impl)]
#![feature(freeze)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this actually gets merged, please set this only when feature = "rustc". This crate needs to build on stable for rust-analyzer.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it needed just for this?

PatOrWild::Wild => &Wildcard,

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an experiment, it won't get merged. Also the crate can't build on stable any more with this rustc change.

Copy link
Member Author

@RalfJung RalfJung Mar 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it needed just for this?

Yes. That previously got promoted even though other enum variants have interior mutability, which is not entirely a sound thing to do (Cc rust-lang/unsafe-code-guidelines#493).

@rust-log-analyzer
Copy link
Collaborator

The job x86_64-gnu-llvm-17 failed! Check out the build log: (web) (plain)

Click to see the possible cause of the failure (guessed by this bot)
#17 exporting to docker image format
#17 sending tarball 45.8s done
#17 DONE 50.6s
##[endgroup]
Setting extra environment values for docker:  --env ENABLE_GCC_CODEGEN=1 --env GCC_EXEC_PREFIX=/usr/lib/gcc/
[CI_JOB_NAME=x86_64-gnu-llvm-17]
##[group]Clock drift check
  local time: Wed Mar 20 19:14:50 UTC 2024
  network time: Wed, 20 Mar 2024 19:14:50 GMT
  network time: Wed, 20 Mar 2024 19:14:50 GMT
##[endgroup]
sccache: Starting the server...
##[group]Configure the build
configure: processing command line
configure: 
configure: build.configure-args := ['--build=x86_64-unknown-linux-gnu', '--llvm-root=/usr/lib/llvm-17', '--enable-llvm-link-shared', '--set', 'rust.thin-lto-import-instr-limit=10', '--set', 'change-id=99999999', '--enable-verbose-configure', '--enable-sccache', '--disable-manage-submodules', '--enable-locked-deps', '--enable-cargo-native-static', '--set', 'rust.codegen-units-std=1', '--set', 'dist.compression-profile=balanced', '--dist-compression-formats=xz', '--disable-dist-src', '--release-channel=nightly', '--enable-debug-assertions', '--enable-overflow-checks', '--enable-llvm-assertions', '--set', 'rust.verify-llvm-ir', '--set', 'rust.codegen-backends=llvm,cranelift,gcc', '--set', 'llvm.static-libstdcpp', '--enable-new-symbol-mangling']
configure: target.x86_64-unknown-linux-gnu.llvm-config := /usr/lib/llvm-17/bin/llvm-config
configure: llvm.link-shared     := True
configure: rust.thin-lto-import-instr-limit := 10
configure: change-id            := 99999999
---

---- [ui] tests/ui/consts/const-multi-ref.rs stdout ----
diff of stderr:

8    = help: add `#![feature(const_mut_refs)]` to the crate attributes to enable
9    = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
- error[E0658]: cannot borrow here, since the borrowed element may contain interior mutability
-   --> $DIR/const-multi-ref.rs:16:13
-    |
- LL |     let p = &a;
- LL |     let p = &a;
-    |             ^^
-    |
-    = note: see issue #80384 <https://github.com/rust-lang/rust/issues/80384> for more information
-    = help: add `#![feature(const_refs_to_cell)]` to the crate attributes to enable
-    = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
- error: aborting due to 2 previous errors
+ error: aborting due to 1 previous error
22 
23 For more information about this error, try `rustc --explain E0658`.
---
--- stderr -------------------------------
error[E0658]: mutable references are not allowed in constants
##[error]  --> /checkout/tests/ui/consts/const-multi-ref.rs:6:13
   |
LL |     let p = &mut a; //~ ERROR mutable references are not allowed in constants
   |
   = note: see issue #57349 <https://github.com/rust-lang/rust/issues/57349> for more information
   = help: add `#![feature(const_mut_refs)]` to the crate attributes to enable
   = help: add `#![feature(const_mut_refs)]` to the crate attributes to enable
   = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0658`.
------------------------------------------
---
   |
LL |     let x: &'static _ = &X;
   |            ----------    ^ creates a temporary value which is freed while still in use
   |            |
   |            type annotation requires that borrow lasts for `'static`
LL |     let y: &'static _ = &Y;
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/const_let_promote.rs:16:26
##[error]  --> /checkout/tests/ui/consts/const_let_promote.rs:16:26
   |
LL |     let y: &'static _ = &Y;
   |            ----------    ^ creates a temporary value which is freed while still in use
   |            type annotation requires that borrow lasts for `'static`
LL | }
   | - temporary value is freed at the end of this statement

---
---- [ui] tests/ui/consts/future-incompat-mutable-in-final-value-issue-121610.rs stdout ----

error: test compilation failed although it shouldn't!
status: exit status: 1
command: RUSTC_ICE="0" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/bin/rustc" "/checkout/tests/ui/consts/future-incompat-mutable-in-final-value-issue-121610.rs" "-Zthreads=1" "-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX" "-Ztranslate-remapped-path-to-local-path=no" "-Z" "ignore-directory-in-diagnostics-source-blocks=/cargo" "--sysroot" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2" "--target=x86_64-unknown-linux-gnu" "--error-format" "json" "--json" "future-incompat" "-Ccodegen-units=1" "-Zui-testing" "-Zdeduplicate-diagnostics=no" "-Zwrite-long-types-to-disk=no" "-Cstrip=debuginfo" "--emit" "metadata" "-C" "prefer-dynamic" "--out-dir" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/consts/future-incompat-mutable-in-final-value-issue-121610" "-A" "unused" "-A" "internal_features" "-Crpath" "-Cdebuginfo=0" "-Lnative=/checkout/obj/build/x86_64-unknown-linux-gnu/native/rust-test-helpers" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/consts/future-incompat-mutable-in-final-value-issue-121610/auxiliary"
--- stderr -------------------------------
error[E0492]: constants cannot refer to interior mutable data
##[error]  --> /checkout/tests/ui/consts/future-incompat-mutable-in-final-value-issue-121610.rs:13:29
   |
   |
LL | const UNDEFINED: &JsValue = &JsValue::Undefined;
   |                             ^^^^^^^^^^^^^^^^^^^ this borrow of an interior mutable value may end up in the final value
error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0492`.
------------------------------------------
---
--- stderr -------------------------------
error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/interior-mut-const-via-union.rs:37:26
   |
LL |     let _: &'static _ = &C;
   |            ----------    ^ creates a temporary value which is freed while still in use
   |            type annotation requires that borrow lasts for `'static`
LL | }
   | - temporary value is freed at the end of this statement

---
---- [ui] tests/ui/consts/issue-65348.rs stdout ----

error: test compilation failed although it shouldn't!
status: exit status: 1
command: RUSTC_ICE="0" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/bin/rustc" "/checkout/tests/ui/consts/issue-65348.rs" "-Zthreads=1" "-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX" "-Ztranslate-remapped-path-to-local-path=no" "-Z" "ignore-directory-in-diagnostics-source-blocks=/cargo" "--sysroot" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2" "--target=x86_64-unknown-linux-gnu" "--error-format" "json" "--json" "future-incompat" "-Ccodegen-units=1" "-Zui-testing" "-Zdeduplicate-diagnostics=no" "-Zwrite-long-types-to-disk=no" "-Cstrip=debuginfo" "--emit" "metadata" "-C" "prefer-dynamic" "--out-dir" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/consts/issue-65348" "-A" "unused" "-A" "internal_features" "-Crpath" "-Cdebuginfo=0" "-Lnative=/checkout/obj/build/x86_64-unknown-linux-gnu/native/rust-test-helpers" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/consts/issue-65348/auxiliary"
--- stderr -------------------------------
error[E0515]: cannot return reference to temporary value
##[error]  --> /checkout/tests/ui/consts/issue-65348.rs:13:5
   |
   |
LL |     &Generic::<T>::ARRAY[0]
   |     ^-------------------^^^
   |     |temporary value created here
   |     returns a reference to data owned by the current function

error[E0515]: cannot return reference to temporary value
error[E0515]: cannot return reference to temporary value
##[error]  --> /checkout/tests/ui/consts/issue-65348.rs:17:5
   |
LL |     &Generic::<T>::NEWTYPE_ARRAY.0[0]
   |     ^---------------------------^^^^^
   |     |temporary value created here
   |     returns a reference to data owned by the current function

error[E0515]: cannot return reference to temporary value
error[E0515]: cannot return reference to temporary value
##[error]  --> /checkout/tests/ui/consts/issue-65348.rs:21:5
   |
LL |     &(Generic::<T>::ARRAY_FIELD.0).1[0]
   |     ^^-------------------------^^^^^^^^
   |     | temporary value created here
   |     returns a reference to data owned by the current function

error: aborting due to 3 previous errors
---
--- stderr -------------------------------
error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promoted-storage.rs:19:26
   |
LL |     let _: &'static _ = &C;
   |            ----------    ^ creates a temporary value which is freed while still in use
   |            type annotation requires that borrow lasts for `'static`
LL | }
   | - temporary value is freed at the end of this statement

---
-   --> $DIR/promote-not.rs:40:29
+ error[E0080]: it is undefined behavior to use this value
+   --> $DIR/promote-not.rs:38:1
33    |
+ LL | const TEST_INTERIOR_MUT: () = {
+    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at .<deref>.0.value: encountered `UnsafeCell` in read-only memory
+    |
+    = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.
+    = note: the raw bytes of the constant (size: 8, align: 8) {
+            }
+ 
+ note: erroneous constant encountered
+   --> $DIR/promote-not.rs:40:28
+   --> $DIR/promote-not.rs:40:28
+    |
34 LL |     let _val: &'static _ = &(Cell::new(1), 2).1;
-    |               ----------    ^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
-    |               type annotation requires that borrow lasts for `'static`
- LL | };
-    | - temporary value is freed at the end of this statement
+    |                            ^^^^^^^^^^^^^^^^^^^^
---
--- stderr -------------------------------
error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:9:50
   |
LL | static mut TEST1: Option<&mut [i32]> = Some(&mut [1, 2, 3]); //~ ERROR temporary value dropped while borrowed
   |                                        |         |        |
   |                                        |         |        temporary value is freed at the end of this statement
   |                                        |         creates a temporary value which is freed while still in use
   |                                        using this value as a static requires that borrow lasts for `'static`
   |                                        using this value as a static requires that borrow lasts for `'static`

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:12:18
   |
LL |     let x = &mut [1,2,3]; //~ ERROR temporary value dropped while borrowed
   |                  ^^^^^^^ creates a temporary value which is freed while still in use
   |     - using this value as a static requires that borrow lasts for `'static`
LL | };
   | - temporary value is freed at the end of this statement


error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:34:29
   |
LL |     let _x: &'static i32 = &unsafe { U { x: 0 }.x }; //~ ERROR temporary value dropped while borrowed
   |             ------------    ^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |             type annotation requires that borrow lasts for `'static`
LL | };
   | - temporary value is freed at the end of this statement


error[E0080]: it is undefined behavior to use this value
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:38:1
   |
LL | const TEST_INTERIOR_MUT: () = {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at .<deref>.0.value: encountered `UnsafeCell` in read-only memory
   |
   = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.
   = note: the raw bytes of the constant (size: 8, align: 8) {
           }

note: erroneous constant encountered
  --> /checkout/tests/ui/consts/promote-not.rs:40:28
  --> /checkout/tests/ui/consts/promote-not.rs:40:28
   |
LL |     let _val: &'static _ = &(Cell::new(1), 2).1; //~ ERROR temporary value dropped while borrowed

error[E0493]: destructor of `String` cannot be evaluated at compile-time
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:47:14
   |
   |
LL |     let x = &String::new(); //~ ERROR destructor of `String` cannot be evaluated at compile-time
   |              ^^^^^^^^^^^^^ the destructor for this type cannot be evaluated in constants
LL | };
   | - value is dropped here

error[E0716]: temporary value dropped while borrowed
error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:21:32
   |
LL |         let _x: &'static () = &foo(); //~ ERROR temporary value dropped while borrowed
   |                 -----------    ^^^^^ creates a temporary value which is freed while still in use
   |                 type annotation requires that borrow lasts for `'static`
LL |     }
   |     - temporary value is freed at the end of this statement


error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:29:29
   |
LL |     let _x: &'static i32 = &unsafe { U { x: 0 }.x }; //~ ERROR temporary value dropped while borrowed
   |             ------------    ^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |             type annotation requires that borrow lasts for `'static`
LL | }
   | - temporary value is freed at the end of this statement


error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:56:29
   |
LL |     let _val: &'static _ = &(Cell::new(1), 2).0; //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:57:29
   |
LL |     let _val: &'static _ = &(Cell::new(1), 2).1; //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:60:29
   |
LL |     let _val: &'static _ = &(1/0); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:61:29
   |
LL |     let _val: &'static _ = &(1/(1-1)); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:62:29
   |
LL |     let _val: &'static _ = &((1+1)/(1-1)); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:63:29
   |
LL |     let _val: &'static _ = &(i32::MIN/-1); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:64:29
   |
LL |     let _val: &'static _ = &(i32::MIN/(0-1)); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:65:29
   |
LL |     let _val: &'static _ = &(-128i8/-1); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:66:29
   |
LL |     let _val: &'static _ = &(1%0); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:67:29
   |
LL |     let _val: &'static _ = &(1%(1-1)); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:68:29
   |
LL |     let _val: &'static _ = &([1,2,3][4]+1); //~ ERROR temporary value dropped while borrowed
   |               ----------    ^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:72:29
   |
LL |     let _val: &'static _ = &TEST_DROP;
   |               ----------    ^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:74:29
   |
LL |     let _val: &'static _ = &&TEST_DROP;
   |               ----------    ^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:74:30
   |
LL |     let _val: &'static _ = &&TEST_DROP;
   |               ----------     ^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:77:29
   |
LL |     let _val: &'static _ = &(&TEST_DROP,);
   |               ----------    ^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:77:31
   |
LL |     let _val: &'static _ = &(&TEST_DROP,);
   |               ----------      ^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:80:29
   |
LL |     let _val: &'static _ = &[&TEST_DROP; 1];
   |               ----------    ^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`
...
LL | }
   | - temporary value is freed at the end of this statement
   | - temporary value is freed at the end of this statement

error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:80:31
   |
LL |     let _val: &'static _ = &[&TEST_DROP; 1];
   |               |               |
   |               |               creates a temporary value which is freed while still in use
   |               type annotation requires that borrow lasts for `'static`


error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/promote-not.rs:89:26
   |
LL |     let x: &'static _ = &UnionWithCell { f1: 0 };
   |            ----------    ^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |            type annotation requires that borrow lasts for `'static`
   |            type annotation requires that borrow lasts for `'static`
LL |     //~^ ERROR temporary value dropped while borrowed
   | - temporary value is freed at the end of this statement

error: aborting due to 26 previous errors

---

---- [ui] tests/ui/consts/refs-to-cell-in-final.rs stdout ----
diff of stderr:

12 LL | const RAW_SYNC_C: SyncPtr<Cell<i32>> = SyncPtr { x: &Cell::new(42) };
13    |                                                     ^^^^^^^^^^^^^^ this borrow of an interior mutable value may end up in the final value
- warning: encountered mutable pointer in final value of constant
-   --> $DIR/refs-to-cell-in-final.rs:30:1
+ error[E0492]: constants cannot refer to interior mutable data
+   --> $DIR/refs-to-cell-in-final.rs:30:29
+   --> $DIR/refs-to-cell-in-final.rs:30:29
17    |
18 LL | const UNDEFINED: &JsValue = &JsValue::Undefined;
-    | ^^^^^^^^^^^^^^^^^^^^^^^^^
+    |                             ^^^^^^^^^^^^^^^^^^^ this borrow of an interior mutable value may end up in the final value
+ error[E0492]: constants cannot refer to interior mutable data
+   --> $DIR/refs-to-cell-in-final.rs:35:42
20    |
-    = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
-    = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
-    = note: for more information, see issue #122153 <https://github.com/rust-lang/rust/issues/122153>
-    = note: `#[warn(const_eval_mutable_ptr_in_final_value)]` on by default
+ LL | const NONE: &'static Option<Cell<i32>> = &None;
+    |                                          ^^^^^ this borrow of an interior mutable value may end up in the final value
- error: aborting due to 2 previous errors; 1 warning emitted
- 
- For more information about this error, try `rustc --explain E0492`.
- Future incompatibility report: Future breakage diagnostic:
- Future incompatibility report: Future breakage diagnostic:
- warning: encountered mutable pointer in final value of constant
-   --> $DIR/refs-to-cell-in-final.rs:30:1
+ error[E0716]: temporary value dropped while borrowed
+   --> $DIR/refs-to-cell-in-final.rs:38:14
31    |
- LL | const UNDEFINED: &JsValue = &JsValue::Undefined;
-    |
-    = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
-    = note: for more information, see issue #122153 <https://github.com/rust-lang/rust/issues/122153>
-    = note: `#[warn(const_eval_mutable_ptr_in_final_value)]` on by default
-    = note: `#[warn(const_eval_mutable_ptr_in_final_value)]` on by default
+ LL |     let x = &None;
+    |              ^^^^ creates a temporary value which is freed while still in use
+ LL |     x
+    |     - using this value as a constant requires that borrow lasts for `'static`
+ LL | };
+    | - temporary value is freed at the end of this statement
+ error: aborting due to 5 previous errors
+ 
+ Some errors have detailed explanations: E0492, E0716.
+ For more information about an error, try `rustc --explain E0492`.
---
--- stderr -------------------------------
error[E0492]: statics cannot refer to interior mutable data
##[error]  --> /checkout/tests/ui/consts/refs-to-cell-in-final.rs:13:54
   |
LL | static RAW_SYNC_S: SyncPtr<Cell<i32>> = SyncPtr { x: &Cell::new(42) };
   |                                                      ^^^^^^^^^^^^^^ this borrow of an interior mutable value may end up in the final value
   = help: to fix this, the value can be extracted to a separate `static` item and then referenced

error[E0492]: constants cannot refer to interior mutable data
##[error]  --> /checkout/tests/ui/consts/refs-to-cell-in-final.rs:15:53
##[error]  --> /checkout/tests/ui/consts/refs-to-cell-in-final.rs:15:53
   |
LL | const RAW_SYNC_C: SyncPtr<Cell<i32>> = SyncPtr { x: &Cell::new(42) };
   |                                                     ^^^^^^^^^^^^^^ this borrow of an interior mutable value may end up in the final value
error[E0492]: constants cannot refer to interior mutable data
##[error]  --> /checkout/tests/ui/consts/refs-to-cell-in-final.rs:30:29
   |
   |
LL | const UNDEFINED: &JsValue = &JsValue::Undefined;
   |                             ^^^^^^^^^^^^^^^^^^^ this borrow of an interior mutable value may end up in the final value
error[E0492]: constants cannot refer to interior mutable data
Build completed unsuccessfully in 0:14:00
##[error]  --> /checkout/tests/ui/consts/refs-to-cell-in-final.rs:35:42
   |
   |
LL | const NONE: &'static Option<Cell<i32>> = &None;
   |                                          ^^^^^ this borrow of an interior mutable value may end up in the final value
error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/refs-to-cell-in-final.rs:38:14
   |
   |
LL |     let x = &None;
   |              ^^^^ creates a temporary value which is freed while still in use
   |     - using this value as a constant requires that borrow lasts for `'static`
LL | };
   | - temporary value is freed at the end of this statement

---
--- stderr -------------------------------
error[E0716]: temporary value dropped while borrowed
##[error]  --> /checkout/tests/ui/consts/rvalue-static-promotion.rs:17:45
   |
LL |     let _: &'static Option<Cell<String>> = &NONE_CELL_STRING;
   |            -----------------------------    ^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
   |            type annotation requires that borrow lasts for `'static`
   |            type annotation requires that borrow lasts for `'static`
LL |     let _: &'static Option<Box<()>> = &Foo::FOO;
   | - temporary value is freed at the end of this statement

error: aborting due to 1 previous error

---
- error: aborting due to 2 previous errors
+ error[E0492]: constants cannot refer to interior mutable data
+   --> $DIR/E0492.rs:7:44
+    |
+ LL | const NONE: &'static Option<AtomicUsize> = &None;
+    |                                            ^^^^^ this borrow of an interior mutable value may end up in the final value
+ error: aborting due to 3 previous errors
16 
17 For more information about this error, try `rustc --explain E0492`.
18 
---
To only update this specific test, also pass `--test-args error-codes/E0492.rs`

error: 1 errors occurred comparing output.
status: exit status: 1
command: RUSTC_ICE="0" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/bin/rustc" "/checkout/tests/ui/error-codes/E0492.rs" "-Zthreads=1" "-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX" "-Ztranslate-remapped-path-to-local-path=no" "-Z" "ignore-directory-in-diagnostics-source-blocks=/cargo" "--sysroot" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2" "--target=x86_64-unknown-linux-gnu" "--error-format" "json" "--json" "future-incompat" "-Ccodegen-units=1" "-Zui-testing" "-Zdeduplicate-diagnostics=no" "-Zwrite-long-types-to-disk=no" "-Cstrip=debuginfo" "--emit" "metadata" "-C" "prefer-dynamic" "--out-dir" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/error-codes/E0492" "-A" "unused" "-A" "internal_features" "-Crpath" "-Cdebuginfo=0" "-Lnative=/checkout/obj/build/x86_64-unknown-linux-gnu/native/rust-test-helpers" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/error-codes/E0492/auxiliary"
--- stderr -------------------------------
error[E0492]: constants cannot refer to interior mutable data
##[error]  --> /checkout/tests/ui/error-codes/E0492.rs:4:33
   |
   |
LL | const B: &'static AtomicUsize = &A; //~ ERROR E0492
   |                                 ^^ this borrow of an interior mutable value may end up in the final value
error[E0492]: statics cannot refer to interior mutable data
##[error]  --> /checkout/tests/ui/error-codes/E0492.rs:5:34
   |
   |
LL | static C: &'static AtomicUsize = &A; //~ ERROR E0492
   |                                  ^^ this borrow of an interior mutable value may end up in the final value
   = help: to fix this, the value can be extracted to a separate `static` item and then referenced

error[E0492]: constants cannot refer to interior mutable data
##[error]  --> /checkout/tests/ui/error-codes/E0492.rs:7:44
##[error]  --> /checkout/tests/ui/error-codes/E0492.rs:7:44
   |
LL | const NONE: &'static Option<AtomicUsize> = &None;
   |                                            ^^^^^ this borrow of an interior mutable value may end up in the final value
error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0492`.
------------------------------------------
------------------------------------------


---- [ui] tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs stdout ----
diff of stderr:

23    = help: the trait `~const PartialEq<&u8>` is not implemented for `&u8`
24    = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
25 
- error[E0391]: cycle detected when computing type of opaque `test::{opaque#0}`
-   --> $DIR/ice-112822-expected-type-for-param.rs:3:20
-    |
- LL | const fn test() -> impl ~const Fn() {
-    |
-    |
- note: ...which requires borrow-checking `test`...
-   --> $DIR/ice-112822-expected-type-for-param.rs:3:1
-    |
- LL | const fn test() -> impl ~const Fn() {
-    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- note: ...which requires promoting constants in MIR for `test`...
-   --> $DIR/ice-112822-expected-type-for-param.rs:3:1
-    |
- LL | const fn test() -> impl ~const Fn() {
-    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- note: ...which requires const checking `test`...
-   --> $DIR/ice-112822-expected-type-for-param.rs:3:1
-    |
- LL | const fn test() -> impl ~const Fn() {
-    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-    = note: ...which requires computing whether `test::{opaque#0}` is freeze...
-    = note: ...which requires evaluating trait selection obligation `test::{opaque#0}: core::marker::Freeze`...
-    = note: ...which again requires computing type of opaque `test::{opaque#0}`, completing the cycle
- note: cycle used when computing type of `test::{opaque#0}`
-   --> $DIR/ice-112822-expected-type-for-param.rs:3:20
-    |
- LL | const fn test() -> impl ~const Fn() {
-    |                    ^^^^^^^^^^^^^^^^
-    = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information
56 
- error: aborting due to 4 previous errors
- 
- Some errors have detailed explanations: E0277, E0391, E0658.
---

The actual stderr differed from the expected stderr.
Actual stderr saved to /checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param/ice-112822-expected-type-for-param.stderr
To update references, rerun the tests and pass the `--bless` flag
To only update this specific test, also pass `--test-args rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs`
error: 1 errors occurred comparing output.
status: exit status: 1
command: RUSTC_ICE="0" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/bin/rustc" "/checkout/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs" "-Zthreads=1" "-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX" "-Ztranslate-remapped-path-to-local-path=no" "-Z" "ignore-directory-in-diagnostics-source-blocks=/cargo" "--sysroot" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2" "--target=x86_64-unknown-linux-gnu" "--error-format" "json" "--json" "future-incompat" "-Ccodegen-units=1" "-Zui-testing" "-Zdeduplicate-diagnostics=no" "-Zwrite-long-types-to-disk=no" "-Cstrip=debuginfo" "--emit" "metadata" "-C" "prefer-dynamic" "--out-dir" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param" "-A" "unused" "-A" "internal_features" "-Crpath" "-Cdebuginfo=0" "-Lnative=/checkout/obj/build/x86_64-unknown-linux-gnu/native/rust-test-helpers" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param/auxiliary"
stdout: none
stdout: none
--- stderr -------------------------------
error[E0658]: const closures are experimental
##[error]  --> /checkout/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs:5:5
   |
LL |     const move || { //~ ERROR const closures are experimental
   |
   = note: see issue #106003 <https://github.com/rust-lang/rust/issues/106003> for more information
   = help: add `#![feature(const_closures)]` to the crate attributes to enable
   = help: add `#![feature(const_closures)]` to the crate attributes to enable
   = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date

error: `~const` can only be applied to `#[const_trait]` traits
   |
   |
LL | const fn test() -> impl ~const Fn() { //~ ERROR `~const` can only be applied to `#[const_trait]` traits


error[E0277]: can't compare `&u8` with `&u8`
   |
   |
LL |                 assert_eq!(first, &b'f');
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `&u8 == &u8`
   |
   = help: the trait `~const PartialEq<&u8>` is not implemented for `&u8`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 3 previous errors

Some errors have detailed explanations: E0277, E0658.
For more information about an error, try `rustc --explain E0277`.
For more information about an error, try `rustc --explain E0277`.
------------------------------------------


---- [ui] tests/ui/unsafe/ranged_ints3_const.rs stdout ----
diff of stderr:

6    |
7    = note: references to fields of layout constrained fields lose the constraints. Coupled with interior mutability, the field can be changed to invalid values
- error[E0658]: cannot borrow here, since the borrowed element may contain interior mutability
-   --> $DIR/ranged_ints3_const.rs:12:13
-    |
-    |
- LL |     let y = &x.0;
-    |
-    = note: see issue #80384 <https://github.com/rust-lang/rust/issues/80384> for more information
-    = help: add `#![feature(const_refs_to_cell)]` to the crate attributes to enable
-    = help: add `#![feature(const_refs_to_cell)]` to the crate attributes to enable
-    = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
18 
- error[E0658]: cannot borrow here, since the borrowed element may contain interior mutability
-   --> $DIR/ranged_ints3_const.rs:19:22
-    |
-    |
- LL |     let y = unsafe { &x.0 };
-    |
-    = note: see issue #80384 <https://github.com/rust-lang/rust/issues/80384> for more information
-    = help: add `#![feature(const_refs_to_cell)]` to the crate attributes to enable
-    = help: add `#![feature(const_refs_to_cell)]` to the crate attributes to enable
-    = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
- error: aborting due to 3 previous errors
- 
- Some errors have detailed explanations: E0133, E0658.
- For more information about an error, try `rustc --explain E0133`.
---
--- stderr -------------------------------
error[E0133]: borrow of layout constrained field with interior mutability is unsafe and requires unsafe function or block
##[error]  --> /checkout/tests/ui/unsafe/ranged_ints3_const.rs:12:13
   |
LL |     let y = &x.0; //~ ERROR the borrowed element may contain interior mutability
   |             ^^^^ borrow of layout constrained field with interior mutability
   |
   = note: references to fields of layout constrained fields lose the constraints. Coupled with interior mutability, the field can be changed to invalid values
error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0133`.
------------------------------------------

@bors
Copy link
Contributor

bors commented Mar 20, 2024

☀️ Try build successful - checks-actions
Build commit: cb4bf0e (cb4bf0ee9ea9dac86332c9e48c07269c7edc21dc)

@RalfJung
Copy link
Member Author

@craterbot check

@craterbot
Copy link
Collaborator

👌 Experiment pr-122789 created and queued.
🤖 Automatically detected try build cb4bf0e
🔍 You can check out the queue and this experiment's details.

ℹ️ Crater is a tool to run experiments across parts of the Rust ecosystem. Learn more

@craterbot craterbot added the S-waiting-on-crater Status: Waiting on a crater run to be completed. label Mar 20, 2024
@craterbot
Copy link
Collaborator

🚧 Experiment pr-122789 is now running

ℹ️ Crater is a tool to run experiments across parts of the Rust ecosystem. Learn more

@craterbot
Copy link
Collaborator

🎉 Experiment pr-122789 is completed!
📊 3823 regressed and 3 fixed (429092 total)
📰 Open the full report.

⚠️ If you notice any spurious failure please add them to the blacklist!
ℹ️ Crater is a tool to run experiments across parts of the Rust ecosystem. Learn more

@craterbot craterbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-crater Status: Waiting on a crater run to be completed. labels Mar 31, 2024
@RalfJung
Copy link
Member Author

Well I think that answers the question. ;)

Noratrieb added a commit to Noratrieb/rust that referenced this pull request Jun 4, 2024
…ference-self, r=BoxyUwU

Item bounds can reference self projections and still be object safe

### Background

Currently, we have some interesting rules about where `Self` is allowed to be mentioned in objects. Specifically, we allow mentioning `Self` behind associated types (e.g. `fn foo(&self) -> Self::Assoc`) only if that `Self` type comes from the trait we're defining or its supertraits:

```
trait Foo {
  fn good() -> Self::Assoc; // GOOD :)

  fn bad() -> <Self as OtherTrait>::Assoc; // BAD!
}
```

And more specifically, these `Self::Assoc` projections are *only* allowed to show up in:
  * (A1) Method signatures
  * (A2) Where clauses on traits, GATs and methods

But `Self::Assoc` projections are **not** allowed to show up in:
  * (B1) Supertrait bounds (specifically: all *super-predicates*, which includes the projections that come from elaboration, and not just the traits themselves).
  * (B2) Item bounds of associated types

The reason for (B1) is interesting: specifically, it arises from the fact that we currently eagerly elaborate all projection predicates into the object, so if we had the following code:

```
trait Sub<Assoc = Self::SuperAssoc> {}
trait Super {
    type SuperAssoc;
}
```

Then given `dyn Sub<SuperAssoc = i32>` we would need to have a type that is substituted into itself an infinite number of times[^1], like `dyn Sub<SuperAssoc = i32, Assoc = <dyn Sub<SuperAssoc = i32, Assoc = <dyn Sub<SuperAssoc = i32, Assoc = <... as Super>::SuperAssoc> as Super>::SuperAssoc> as Super>::SuperAssoc>`, i.e. the fixed-point of: `type T = dyn Sub<SuperAssoc = i32, Assoc = <T as Super>::SuperAssoc>`.

Similarly for (B2), we restrict mentioning `Self::Assoc` in associated type item bounds, which is the cause for rust-lang#122798. However, there is **no reason** for us to do so, since item bounds never show up structurally in the `dyn Trait` object type.

#### What?

This PR relaxes the check for item bounds so that `Self` may be mentioned behind associated types in the same cases that they currently work for method signatures (A1) and where clauses (A2).

#### Why?

Fixes rust-lang#122798. Removes a subtle and confusing inconsistency for the code mentioned in that issue.

This is sound because we only assemble alias bounds for rigid projections, and all projections coming from an object self type are not rigid, since all associated types should be specified by the type.

This is also desirable because we can do this via supertraits already. In rust-lang#122789, it is noted that an item bound of `Eq` already works, just not `PartialEq` because of the default item bound. This is weird and should be fixed.

#### Future work

We could make the check for `Self` in super-predicates more sophisticated as well, only erroring if `Self` shows up in a projection super-predicate.

[^1]: This could be fixed by some sort of structural replacement or eager normalization, but I don't think it's necessary currently.
Noratrieb added a commit to Noratrieb/rust that referenced this pull request Jun 4, 2024
…ference-self, r=BoxyUwU

Item bounds can reference self projections and still be object safe

### Background

Currently, we have some interesting rules about where `Self` is allowed to be mentioned in objects. Specifically, we allow mentioning `Self` behind associated types (e.g. `fn foo(&self) -> Self::Assoc`) only if that `Self` type comes from the trait we're defining or its supertraits:

```
trait Foo {
  fn good() -> Self::Assoc; // GOOD :)

  fn bad() -> <Self as OtherTrait>::Assoc; // BAD!
}
```

And more specifically, these `Self::Assoc` projections are *only* allowed to show up in:
  * (A1) Method signatures
  * (A2) Where clauses on traits, GATs and methods

But `Self::Assoc` projections are **not** allowed to show up in:
  * (B1) Supertrait bounds (specifically: all *super-predicates*, which includes the projections that come from elaboration, and not just the traits themselves).
  * (B2) Item bounds of associated types

The reason for (B1) is interesting: specifically, it arises from the fact that we currently eagerly elaborate all projection predicates into the object, so if we had the following code:

```
trait Sub<Assoc = Self::SuperAssoc> {}
trait Super {
    type SuperAssoc;
}
```

Then given `dyn Sub<SuperAssoc = i32>` we would need to have a type that is substituted into itself an infinite number of times[^1], like `dyn Sub<SuperAssoc = i32, Assoc = <dyn Sub<SuperAssoc = i32, Assoc = <dyn Sub<SuperAssoc = i32, Assoc = <... as Super>::SuperAssoc> as Super>::SuperAssoc> as Super>::SuperAssoc>`, i.e. the fixed-point of: `type T = dyn Sub<SuperAssoc = i32, Assoc = <T as Super>::SuperAssoc>`.

Similarly for (B2), we restrict mentioning `Self::Assoc` in associated type item bounds, which is the cause for rust-lang#122798. However, there is **no reason** for us to do so, since item bounds never show up structurally in the `dyn Trait` object type.

#### What?

This PR relaxes the check for item bounds so that `Self` may be mentioned behind associated types in the same cases that they currently work for method signatures (A1) and where clauses (A2).

#### Why?

Fixes rust-lang#122798. Removes a subtle and confusing inconsistency for the code mentioned in that issue.

This is sound because we only assemble alias bounds for rigid projections, and all projections coming from an object self type are not rigid, since all associated types should be specified by the type.

This is also desirable because we can do this via supertraits already. In rust-lang#122789, it is noted that an item bound of `Eq` already works, just not `PartialEq` because of the default item bound. This is weird and should be fixed.

#### Future work

We could make the check for `Self` in super-predicates more sophisticated as well, only erroring if `Self` shows up in a projection super-predicate.

[^1]: This could be fixed by some sort of structural replacement or eager normalization, but I don't think it's necessary currently.
@fee1-dead
Copy link
Member

fee1-dead commented Aug 17, 2024

A lot of the regressions come from the headers crate, by sampling some of it. It seems to be a widely depended-upon crate, but the alternative solution is icky.

bors added a commit to rust-lang-ci/rust that referenced this pull request Sep 14, 2024
…dead

const-eval interning: accept interior mutable pointers in final value

…but keep rejecting mutable references

This fixes rust-lang#121610 by no longer firing the lint when there is a pointer with interior mutability in the final value of the constant. On stable, such pointers can be created with code like:
```rust
pub enum JsValue {
    Undefined,
    Object(Cell<bool>),
}
impl Drop for JsValue {
    fn drop(&mut self) {}
}
// This does *not* get promoted since `JsValue` has a destructor.
// However, the outer scope rule applies, still giving this 'static lifetime.
const UNDEFINED: &JsValue = &JsValue::Undefined;
```
It's not great to accept such values since people *might* think that it is legal to mutate them with unsafe code. (This is related to how "infectious" `UnsafeCell` is, which is a [wide open question](rust-lang/unsafe-code-guidelines#236).) However, we [explicitly document](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) that things created by `const` are immutable. Furthermore, we also accept the following even more questionable code without any lint today:
```rust
let x: &'static Option<Cell<i32>> = &None;
```
This is even more questionable since it does *not* involve a `const`, and yet still puts the data into immutable memory. We could view this as promotion [potentially introducing UB](rust-lang/unsafe-code-guidelines#493). However, we've accepted this since ~forever and it's [too late to reject this now](rust-lang#122789); the pattern is just too useful.

So basically, if you think that `UnsafeCell` should be tracked fully precisely, then you should want the lint we currently emit to be removed, which this PR does. If you think `UnsafeCell` should "infect" surrounding `enum`s, the big problem is really rust-lang/unsafe-code-guidelines#493 which does not trigger the lint -- the cases the lint triggers on are actually the "harmless" ones as there is an explicit surrounding `const` explaining why things end up being immutable.

What all this goes to show is that the hard error added in rust-lang#118324 (later turned into the future-compat lint that I am now suggesting we remove) was based on some wrong assumptions, at least insofar as it concerns shared references. Furthermore, that lint does not help at all for the most problematic case here where the potential UB is completely implicit. (In fact, the lint is actively in the way of [my preferred long-term strategy](rust-lang/unsafe-code-guidelines#493 (comment)) for dealing with this UB.) So I think we should go back to square one and remove that error/lint for shared references. For mutable references, it does seem to work as intended, so we can keep it. Here it serves as a safety net in case the static checks that try to contain mutable references to the inside of a const initializer are not working as intended; I therefore made the check ICE to encourage users to tell us if that safety net is triggered.

Closes rust-lang#122153 by removing the lint.

Cc `@rust-lang/opsem` `@rust-lang/lang`
github-actions bot pushed a commit to rust-lang/miri that referenced this pull request Sep 16, 2024
const-eval interning: accept interior mutable pointers in final value

…but keep rejecting mutable references

This fixes rust-lang/rust#121610 by no longer firing the lint when there is a pointer with interior mutability in the final value of the constant. On stable, such pointers can be created with code like:
```rust
pub enum JsValue {
    Undefined,
    Object(Cell<bool>),
}
impl Drop for JsValue {
    fn drop(&mut self) {}
}
// This does *not* get promoted since `JsValue` has a destructor.
// However, the outer scope rule applies, still giving this 'static lifetime.
const UNDEFINED: &JsValue = &JsValue::Undefined;
```
It's not great to accept such values since people *might* think that it is legal to mutate them with unsafe code. (This is related to how "infectious" `UnsafeCell` is, which is a [wide open question](rust-lang/unsafe-code-guidelines#236).) However, we [explicitly document](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) that things created by `const` are immutable. Furthermore, we also accept the following even more questionable code without any lint today:
```rust
let x: &'static Option<Cell<i32>> = &None;
```
This is even more questionable since it does *not* involve a `const`, and yet still puts the data into immutable memory. We could view this as promotion [potentially introducing UB](rust-lang/unsafe-code-guidelines#493). However, we've accepted this since ~forever and it's [too late to reject this now](rust-lang/rust#122789); the pattern is just too useful.

So basically, if you think that `UnsafeCell` should be tracked fully precisely, then you should want the lint we currently emit to be removed, which this PR does. If you think `UnsafeCell` should "infect" surrounding `enum`s, the big problem is really rust-lang/unsafe-code-guidelines#493 which does not trigger the lint -- the cases the lint triggers on are actually the "harmless" ones as there is an explicit surrounding `const` explaining why things end up being immutable.

What all this goes to show is that the hard error added in rust-lang/rust#118324 (later turned into the future-compat lint that I am now suggesting we remove) was based on some wrong assumptions, at least insofar as it concerns shared references. Furthermore, that lint does not help at all for the most problematic case here where the potential UB is completely implicit. (In fact, the lint is actively in the way of [my preferred long-term strategy](rust-lang/unsafe-code-guidelines#493 (comment)) for dealing with this UB.) So I think we should go back to square one and remove that error/lint for shared references. For mutable references, it does seem to work as intended, so we can keep it. Here it serves as a safety net in case the static checks that try to contain mutable references to the inside of a const initializer are not working as intended; I therefore made the check ICE to encourage users to tell us if that safety net is triggered.

Closes rust-lang/rust#122153 by removing the lint.

Cc `@rust-lang/opsem` `@rust-lang/lang`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants