From 6649219c3f218408b630d14d03271c9038901000 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 22:29:46 -0700
Subject: [PATCH 01/21] Remove asmjs from library

---
 library/core/src/ffi/mod.rs         |  6 ------
 library/std/build.rs                |  1 -
 library/std/src/os/l4re/raw.rs      |  1 -
 library/std/src/os/linux/raw.rs     |  1 -
 library/std/src/sys/common/alloc.rs |  1 -
 library/std/src/sys/unix/env.rs     | 11 -----------
 6 files changed, 21 deletions(-)

diff --git a/library/core/src/ffi/mod.rs b/library/core/src/ffi/mod.rs
index 6908c824f44b6..7340ad90da509 100644
--- a/library/core/src/ffi/mod.rs
+++ b/library/core/src/ffi/mod.rs
@@ -241,7 +241,6 @@ impl fmt::Debug for c_void {
     ),
     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios", target_os = "tvos")),
     target_family = "wasm",
-    target_arch = "asmjs",
     target_os = "uefi",
     windows,
 ))]
@@ -270,7 +269,6 @@ pub struct VaListImpl<'f> {
     ),
     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios", target_os = "tvos")),
     target_family = "wasm",
-    target_arch = "asmjs",
     target_os = "uefi",
     windows,
 ))]
@@ -395,7 +393,6 @@ pub struct VaList<'a, 'f: 'a> {
             any(target_os = "macos", target_os = "ios", target_os = "tvos")
         ),
         target_family = "wasm",
-        target_arch = "asmjs",
         target_os = "uefi",
         windows,
     ))]
@@ -413,7 +410,6 @@ pub struct VaList<'a, 'f: 'a> {
             not(any(target_os = "macos", target_os = "ios", target_os = "tvos"))
         ),
         not(target_family = "wasm"),
-        not(target_arch = "asmjs"),
         not(target_os = "uefi"),
         not(windows),
     ))]
@@ -431,7 +427,6 @@ pub struct VaList<'a, 'f: 'a> {
     ),
     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios", target_os = "tvos")),
     target_family = "wasm",
-    target_arch = "asmjs",
     target_os = "uefi",
     windows,
 ))]
@@ -461,7 +456,6 @@ impl<'f> VaListImpl<'f> {
         not(any(target_os = "macos", target_os = "ios", target_os = "tvos"))
     ),
     not(target_family = "wasm"),
-    not(target_arch = "asmjs"),
     not(target_os = "uefi"),
     not(windows),
 ))]
diff --git a/library/std/build.rs b/library/std/build.rs
index ad0a82eab8ca1..11ba29766c17e 100644
--- a/library/std/build.rs
+++ b/library/std/build.rs
@@ -25,7 +25,6 @@ fn main() {
         || target.contains("vxworks")
         || target.contains("wasm32")
         || target.contains("wasm64")
-        || target.contains("asmjs")
         || target.contains("espidf")
         || target.contains("solid")
         || target.contains("nintendo-3ds")
diff --git a/library/std/src/os/l4re/raw.rs b/library/std/src/os/l4re/raw.rs
index 12c0293285a5e..8fb6e99ecfa1e 100644
--- a/library/std/src/os/l4re/raw.rs
+++ b/library/std/src/os/l4re/raw.rs
@@ -31,7 +31,6 @@ pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
     target_arch = "powerpc",
     target_arch = "sparc",
     target_arch = "arm",
-    target_arch = "asmjs",
     target_arch = "wasm32"
 ))]
 mod arch {
diff --git a/library/std/src/os/linux/raw.rs b/library/std/src/os/linux/raw.rs
index a568f9b26baa9..c29dd62bc06f0 100644
--- a/library/std/src/os/linux/raw.rs
+++ b/library/std/src/os/linux/raw.rs
@@ -31,7 +31,6 @@ pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
     target_arch = "powerpc",
     target_arch = "sparc",
     target_arch = "arm",
-    target_arch = "asmjs",
     target_arch = "wasm32"
 ))]
 mod arch {
diff --git a/library/std/src/sys/common/alloc.rs b/library/std/src/sys/common/alloc.rs
index d58aa6c27b8cd..b7357460f3931 100644
--- a/library/std/src/sys/common/alloc.rs
+++ b/library/std/src/sys/common/alloc.rs
@@ -14,7 +14,6 @@ use crate::ptr;
     target_arch = "powerpc",
     target_arch = "powerpc64",
     target_arch = "sparc",
-    target_arch = "asmjs",
     target_arch = "wasm32",
     target_arch = "hexagon",
     all(target_arch = "riscv32", not(target_os = "espidf")),
diff --git a/library/std/src/sys/unix/env.rs b/library/std/src/sys/unix/env.rs
index 3bb492fa98bcf..3d4ba509829d3 100644
--- a/library/std/src/sys/unix/env.rs
+++ b/library/std/src/sys/unix/env.rs
@@ -174,17 +174,6 @@ pub mod os {
     pub const EXE_EXTENSION: &str = "elf";
 }
 
-#[cfg(all(target_os = "emscripten", target_arch = "asmjs"))]
-pub mod os {
-    pub const FAMILY: &str = "unix";
-    pub const OS: &str = "emscripten";
-    pub const DLL_PREFIX: &str = "lib";
-    pub const DLL_SUFFIX: &str = ".so";
-    pub const DLL_EXTENSION: &str = "so";
-    pub const EXE_SUFFIX: &str = ".js";
-    pub const EXE_EXTENSION: &str = "js";
-}
-
 #[cfg(all(target_os = "emscripten", target_arch = "wasm32"))]
 pub mod os {
     pub const FAMILY: &str = "unix";

From e9a009fd1a9ce00ee07eeb17bc8e9985815a1296 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:11:03 -0700
Subject: [PATCH 02/21] Remove asmjs from tests

---
 .../stack-protector/stack-protector-target-support.rs        | 5 ++---
 tests/incremental/commandline-args.rs                        | 1 -
 tests/incremental/remapped_paths_cc/main.rs                  | 1 -
 tests/incremental/span_hash_stable/main.rs                   | 1 -
 tests/incremental/spans_in_type_debuginfo.rs                 | 1 -
 tests/incremental/spans_significant_w_debuginfo.rs           | 1 -
 tests/ui/abi/variadic-ffi.rs                                 | 5 -----
 tests/ui/async-await/issue-60709.rs                          | 1 -
 tests/ui/binding/match-arm-statics.rs                        | 1 -
 tests/ui/cfg/conditional-compile-arch.rs                     | 3 ---
 tests/ui/coroutine/issue-58888.rs                            | 1 -
 tests/ui/coroutine/size-moved-locals.rs                      | 1 -
 tests/ui/extern/extern-const.fixed                           | 1 -
 tests/ui/extern/extern-const.rs                              | 1 -
 tests/ui/extern/extern-const.stderr                          | 2 +-
 tests/ui/issues/issue-18804/main.rs                          | 1 -
 tests/ui/issues/issue-23477.rs                               | 1 -
 tests/ui/issues/issue-24687-embed-debuginfo/main.rs          | 1 -
 tests/ui/issues/issue-24945-repeat-dash-opts.rs              | 1 -
 tests/ui/issues/issue-26484.rs                               | 1 -
 tests/ui/issues/issue-33096.rs                               | 1 -
 tests/ui/issues/issue-34569.rs                               | 1 -
 tests/ui/issues/issue-36856.rs                               | 1 -
 tests/ui/issues/issue-42210.rs                               | 1 -
 tests/ui/issues/issue-45731.rs                               | 1 -
 tests/ui/issues/issue-58463.rs                               | 1 -
 tests/ui/lto/debuginfo-lto.rs                                | 1 -
 tests/ui/parser/issues/issue-48508.rs                        | 1 -
 tests/ui/sepcomp/sepcomp-lib-lto.rs                          | 1 -
 tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs | 1 -
 30 files changed, 3 insertions(+), 38 deletions(-)

diff --git a/tests/assembly/stack-protector/stack-protector-target-support.rs b/tests/assembly/stack-protector/stack-protector-target-support.rs
index e5cbace80b1e2..c6528ac7c8d16 100644
--- a/tests/assembly/stack-protector/stack-protector-target-support.rs
+++ b/tests/assembly/stack-protector/stack-protector-target-support.rs
@@ -2,7 +2,7 @@
 // targets, with the exception of nvptx64-nvidia-cuda
 //
 // revisions: r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23
-// revisions: r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 r35 r36 r37 r38 r39 r40 r41 r42 r43 r44
+// revisions: r24 r25 r26 r27 r28 r29 r30 r31 r32 r33     r35 r36 r37 r38 r39 r40 r41 r42 r43 r44
 // revisions: r45 r46 r47 r48 r49 r50 r51 r52 r53 r54 r55 r56 r57 r58 r59 r60 r61 r62 r63 r64 r65
 // revisions: r66 r67 r68 r69 r70 r71 r72 r73 r74 r75 r76 r77 r78 r79 r80 r81 r82 r83 r84
 // assembly-output: emit-asm
@@ -72,8 +72,7 @@
 // [r32] needs-llvm-components: arm
 // [r33] compile-flags: --target armv7-unknown-linux-musleabihf
 // [r33] needs-llvm-components: arm
-// [r34] compile-flags: --target asmjs-unknown-emscripten
-// [r34] needs-llvm-components: webassembly
+
 // [r35] compile-flags: --target i586-pc-windows-msvc
 // [r35] needs-llvm-components: x86
 // [r36] compile-flags: --target i586-unknown-linux-gnu
diff --git a/tests/incremental/commandline-args.rs b/tests/incremental/commandline-args.rs
index 35b7183db7fac..e17e6feae0745 100644
--- a/tests/incremental/commandline-args.rs
+++ b/tests/incremental/commandline-args.rs
@@ -1,7 +1,6 @@
 // Test that changing a tracked commandline argument invalidates
 // the cache while changing an untracked one doesn't.
 
-// ignore-asmjs wasm2js does not support source maps yet
 // revisions:rpass1 rpass2 rpass3 rpass4
 // compile-flags: -Z query-dep-graph
 
diff --git a/tests/incremental/remapped_paths_cc/main.rs b/tests/incremental/remapped_paths_cc/main.rs
index b01f02444eae8..12411a928799f 100644
--- a/tests/incremental/remapped_paths_cc/main.rs
+++ b/tests/incremental/remapped_paths_cc/main.rs
@@ -2,7 +2,6 @@
 // compile-flags: -Z query-dep-graph -g
 // aux-build:extern_crate.rs
 
-// ignore-asmjs wasm2js does not support source maps yet
 // This test case makes sure that we detect if paths emitted into debuginfo
 // are changed, even when the change happens in an external crate.
 
diff --git a/tests/incremental/span_hash_stable/main.rs b/tests/incremental/span_hash_stable/main.rs
index 367416430f86b..f1d7de1455938 100644
--- a/tests/incremental/span_hash_stable/main.rs
+++ b/tests/incremental/span_hash_stable/main.rs
@@ -3,7 +3,6 @@
 // the spans and this test makes sure that we handle them correctly by hashing
 // file:line:column instead of raw byte offset.
 
-// ignore-asmjs wasm2js does not support source maps yet
 // revisions:rpass1 rpass2
 // compile-flags: -g -Z query-dep-graph
 
diff --git a/tests/incremental/spans_in_type_debuginfo.rs b/tests/incremental/spans_in_type_debuginfo.rs
index f5cae15a4bc7c..8ed469db6e633 100644
--- a/tests/incremental/spans_in_type_debuginfo.rs
+++ b/tests/incremental/spans_in_type_debuginfo.rs
@@ -1,7 +1,6 @@
 // Test that moving a type definition within a source file does not affect
 // re-compilation.
 
-// ignore-asmjs wasm2js does not support source maps yet
 // revisions:rpass1 rpass2
 // compile-flags: -Z query-dep-graph -g
 
diff --git a/tests/incremental/spans_significant_w_debuginfo.rs b/tests/incremental/spans_significant_w_debuginfo.rs
index 38ab28461911b..a036d3e69fe4a 100644
--- a/tests/incremental/spans_significant_w_debuginfo.rs
+++ b/tests/incremental/spans_significant_w_debuginfo.rs
@@ -3,7 +3,6 @@
 
 // revisions:rpass1 rpass2
 
-// ignore-asmjs wasm2js does not support source maps yet
 // compile-flags: -g -Z query-dep-graph
 
 #![feature(rustc_attrs)]
diff --git a/tests/ui/abi/variadic-ffi.rs b/tests/ui/abi/variadic-ffi.rs
index a952ea0779329..1862177005f93 100644
--- a/tests/ui/abi/variadic-ffi.rs
+++ b/tests/ui/abi/variadic-ffi.rs
@@ -8,11 +8,6 @@ use std::ffi::VaList;
 extern "C" {
     fn rust_interesting_average(_: u64, ...) -> f64;
 
-    // FIXME: we need to disable this lint for `VaList`,
-    // since it contains a `MaybeUninit<i32>` on the asmjs target,
-    // and this type isn't FFI-safe. This is OK for now,
-    // since the type is layout-compatible with `i32`.
-    #[cfg_attr(target_arch = "asmjs", allow(improper_ctypes))]
     fn rust_valist_interesting_average(_: u64, _: VaList) -> f64;
 }
 
diff --git a/tests/ui/async-await/issue-60709.rs b/tests/ui/async-await/issue-60709.rs
index 2cda40e9e11ba..c206f01b98f78 100644
--- a/tests/ui/async-await/issue-60709.rs
+++ b/tests/ui/async-await/issue-60709.rs
@@ -3,7 +3,6 @@
 // compile-flags: -Copt-level=z -Cdebuginfo=2 --edition=2018
 
 // run-pass
-// ignore-asmjs wasm2js does not support source maps yet
 
 use std::future::Future;
 use std::task::Poll;
diff --git a/tests/ui/binding/match-arm-statics.rs b/tests/ui/binding/match-arm-statics.rs
index e6d17def1477e..5f7e357eeb2a9 100644
--- a/tests/ui/binding/match-arm-statics.rs
+++ b/tests/ui/binding/match-arm-statics.rs
@@ -1,7 +1,6 @@
 // run-pass
 #![allow(dead_code)]
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 #[derive(PartialEq, Eq)]
 struct NewBool(bool);
diff --git a/tests/ui/cfg/conditional-compile-arch.rs b/tests/ui/cfg/conditional-compile-arch.rs
index e59e06f801b78..c6ecf4807364d 100644
--- a/tests/ui/cfg/conditional-compile-arch.rs
+++ b/tests/ui/cfg/conditional-compile-arch.rs
@@ -28,9 +28,6 @@ pub fn main() { }
 #[cfg(target_arch = "s390x")]
 pub fn main() { }
 
-#[cfg(target_arch = "asmjs")]
-pub fn main() { }
-
 #[cfg(target_arch = "wasm32")]
 pub fn main() { }
 
diff --git a/tests/ui/coroutine/issue-58888.rs b/tests/ui/coroutine/issue-58888.rs
index af8e60ce460cd..9c699c7bb8292 100644
--- a/tests/ui/coroutine/issue-58888.rs
+++ b/tests/ui/coroutine/issue-58888.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 #![feature(coroutines, coroutine_trait)]
 
diff --git a/tests/ui/coroutine/size-moved-locals.rs b/tests/ui/coroutine/size-moved-locals.rs
index cfbbb9c1b318f..10f988cc06665 100644
--- a/tests/ui/coroutine/size-moved-locals.rs
+++ b/tests/ui/coroutine/size-moved-locals.rs
@@ -11,7 +11,6 @@
 
 // edition:2018
 // ignore-wasm32 issue #62807
-// ignore-asmjs issue #62807
 // needs-unwind Size of Closures change on panic=abort
 
 #![feature(coroutines, coroutine_trait)]
diff --git a/tests/ui/extern/extern-const.fixed b/tests/ui/extern/extern-const.fixed
index 9d96b4f63fb6c..248efc93d008a 100644
--- a/tests/ui/extern/extern-const.fixed
+++ b/tests/ui/extern/extern-const.fixed
@@ -6,7 +6,6 @@
 
 // run-rustfix
 // ignore-wasm32-bare no external library to link to.
-// ignore-asmjs wasm2js does not support source maps yet
 // compile-flags: -g
 #![feature(rustc_private)]
 extern crate libc;
diff --git a/tests/ui/extern/extern-const.rs b/tests/ui/extern/extern-const.rs
index 7cef5b3497b5a..d3b3bef6dae6f 100644
--- a/tests/ui/extern/extern-const.rs
+++ b/tests/ui/extern/extern-const.rs
@@ -6,7 +6,6 @@
 
 // run-rustfix
 // ignore-wasm32-bare no external library to link to.
-// ignore-asmjs wasm2js does not support source maps yet
 // compile-flags: -g
 #![feature(rustc_private)]
 extern crate libc;
diff --git a/tests/ui/extern/extern-const.stderr b/tests/ui/extern/extern-const.stderr
index 7f67adbdb19c7..a296751994ea2 100644
--- a/tests/ui/extern/extern-const.stderr
+++ b/tests/ui/extern/extern-const.stderr
@@ -1,5 +1,5 @@
 error: extern items cannot be `const`
-  --> $DIR/extern-const.rs:16:11
+  --> $DIR/extern-const.rs:15:11
    |
 LL |     const rust_dbg_static_mut: libc::c_int;
    |     ------^^^^^^^^^^^^^^^^^^^
diff --git a/tests/ui/issues/issue-18804/main.rs b/tests/ui/issues/issue-18804/main.rs
index c36048ea54503..47c3f13d23cad 100644
--- a/tests/ui/issues/issue-18804/main.rs
+++ b/tests/ui/issues/issue-18804/main.rs
@@ -2,7 +2,6 @@
 // Test for issue #18804, #[linkage] does not propagate through generic
 // functions. Failure results in a linker error.
 
-// ignore-asmjs no weak symbol support
 // ignore-emscripten no weak symbol support
 // ignore-windows no extern_weak linkage
 // ignore-macos no extern_weak linkage
diff --git a/tests/ui/issues/issue-23477.rs b/tests/ui/issues/issue-23477.rs
index 988ebe03ccf66..1ce05ba390d76 100644
--- a/tests/ui/issues/issue-23477.rs
+++ b/tests/ui/issues/issue-23477.rs
@@ -1,5 +1,4 @@
 // build-pass
-// ignore-asmjs wasm2js does not support source maps yet
 // compile-flags: -g
 
 pub struct Dst {
diff --git a/tests/ui/issues/issue-24687-embed-debuginfo/main.rs b/tests/ui/issues/issue-24687-embed-debuginfo/main.rs
index f08bcdfe6d16c..773792c7a3f1f 100644
--- a/tests/ui/issues/issue-24687-embed-debuginfo/main.rs
+++ b/tests/ui/issues/issue-24687-embed-debuginfo/main.rs
@@ -1,7 +1,6 @@
 // run-pass
 // aux-build:issue-24687-lib.rs
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 extern crate issue_24687_lib as d;
 
diff --git a/tests/ui/issues/issue-24945-repeat-dash-opts.rs b/tests/ui/issues/issue-24945-repeat-dash-opts.rs
index 0f92fc2f7f31a..cf3834952c6a6 100644
--- a/tests/ui/issues/issue-24945-repeat-dash-opts.rs
+++ b/tests/ui/issues/issue-24945-repeat-dash-opts.rs
@@ -3,7 +3,6 @@
 // as options to the compiler.
 
 // compile-flags:-g -g -O -O
-// ignore-asmjs wasm2js does not support source maps yet
 
 fn main() {
     assert_eq!(1, 1);
diff --git a/tests/ui/issues/issue-26484.rs b/tests/ui/issues/issue-26484.rs
index 2a8750d3e431f..3b40b3dd8f075 100644
--- a/tests/ui/issues/issue-26484.rs
+++ b/tests/ui/issues/issue-26484.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 fn helper<F: FnOnce(usize) -> bool>(_f: F) {
     print!("");
diff --git a/tests/ui/issues/issue-33096.rs b/tests/ui/issues/issue-33096.rs
index 2501e1430b3d1..f0b472e2fe821 100644
--- a/tests/ui/issues/issue-33096.rs
+++ b/tests/ui/issues/issue-33096.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 use std::ops::Deref;
 
diff --git a/tests/ui/issues/issue-34569.rs b/tests/ui/issues/issue-34569.rs
index 88dcdd4113807..1f68560509e8c 100644
--- a/tests/ui/issues/issue-34569.rs
+++ b/tests/ui/issues/issue-34569.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 // In this test we just want to make sure that the code below does not lead to
 // a debuginfo verification assertion during compilation. This was caused by the
diff --git a/tests/ui/issues/issue-36856.rs b/tests/ui/issues/issue-36856.rs
index 5657ba69f9449..f2dfaf3dd367e 100644
--- a/tests/ui/issues/issue-36856.rs
+++ b/tests/ui/issues/issue-36856.rs
@@ -2,7 +2,6 @@
 // Regression test for #36856.
 
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 fn g() -> bool {
     false
diff --git a/tests/ui/issues/issue-42210.rs b/tests/ui/issues/issue-42210.rs
index 01a5d563639b5..318e3099f98ba 100644
--- a/tests/ui/issues/issue-42210.rs
+++ b/tests/ui/issues/issue-42210.rs
@@ -2,7 +2,6 @@
 // Regression test for #42210.
 
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 trait Foo {
     fn foo() { }
diff --git a/tests/ui/issues/issue-45731.rs b/tests/ui/issues/issue-45731.rs
index 5c5ac59873a3a..d20c07276a8c5 100644
--- a/tests/ui/issues/issue-45731.rs
+++ b/tests/ui/issues/issue-45731.rs
@@ -1,7 +1,6 @@
 // run-pass
 #![allow(unused_variables)]
 // compile-flags:--test -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 #[cfg(target_os = "macos")]
 #[test]
diff --git a/tests/ui/issues/issue-58463.rs b/tests/ui/issues/issue-58463.rs
index af93f76221d4e..9573c9b703aa3 100644
--- a/tests/ui/issues/issue-58463.rs
+++ b/tests/ui/issues/issue-58463.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags:-C debuginfo=2
-// ignore-asmjs wasm2js does not support source maps yet
 
 fn foo() -> impl Copy {
     foo
diff --git a/tests/ui/lto/debuginfo-lto.rs b/tests/ui/lto/debuginfo-lto.rs
index 43f75b0344be7..e4beee9e737ba 100644
--- a/tests/ui/lto/debuginfo-lto.rs
+++ b/tests/ui/lto/debuginfo-lto.rs
@@ -7,7 +7,6 @@
 // aux-build:debuginfo-lto-aux.rs
 // compile-flags: -C lto -g
 // no-prefer-dynamic
-// ignore-asmjs wasm2js does not support source maps yet
 
 extern crate debuginfo_lto_aux;
 
diff --git a/tests/ui/parser/issues/issue-48508.rs b/tests/ui/parser/issues/issue-48508.rs
index 1e7db9df814b4..b66e09620f4eb 100644
--- a/tests/ui/parser/issues/issue-48508.rs
+++ b/tests/ui/parser/issues/issue-48508.rs
@@ -7,7 +7,6 @@
 // issue-48508-aux.rs
 
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 #![allow(uncommon_codepoints)]
 
diff --git a/tests/ui/sepcomp/sepcomp-lib-lto.rs b/tests/ui/sepcomp/sepcomp-lib-lto.rs
index 51a572899f819..164ae79c254fa 100644
--- a/tests/ui/sepcomp/sepcomp-lib-lto.rs
+++ b/tests/ui/sepcomp/sepcomp-lib-lto.rs
@@ -4,7 +4,6 @@
 
 // aux-build:sepcomp_lib.rs
 // compile-flags: -C lto -g
-// ignore-asmjs wasm2js does not support source maps yet
 // no-prefer-dynamic
 
 extern crate sepcomp_lib;
diff --git a/tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs b/tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs
index 4b7016def9d60..94bb44d2cf50c 100644
--- a/tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs
+++ b/tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs
@@ -10,7 +10,6 @@
 // This is a regression test for issue #17021.
 //
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 use std::ptr;
 

From c88fc2ec6a1a8dfcb97d64e359c05c53ae93ab3f Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:13:23 -0700
Subject: [PATCH 03/21] Remove asmjs from CI

---
 .../host-x86_64/disabled/asmjs/Dockerfile     | 43 -------------------
 .../host-x86_64/dist-various-1/Dockerfile     |  3 +-
 2 files changed, 1 insertion(+), 45 deletions(-)
 delete mode 100644 src/ci/docker/host-x86_64/disabled/asmjs/Dockerfile

diff --git a/src/ci/docker/host-x86_64/disabled/asmjs/Dockerfile b/src/ci/docker/host-x86_64/disabled/asmjs/Dockerfile
deleted file mode 100644
index 07dcb9ea928f8..0000000000000
--- a/src/ci/docker/host-x86_64/disabled/asmjs/Dockerfile
+++ /dev/null
@@ -1,43 +0,0 @@
-FROM ubuntu:16.04
-
-RUN apt-get update && apt-get install -y --no-install-recommends \
-  g++ \
-  make \
-  ninja-build \
-  file \
-  curl \
-  ca-certificates \
-  python3 \
-  git \
-  cmake \
-  sudo \
-  gdb \
-  xz-utils \
-  bzip2
-
-COPY scripts/emscripten.sh /scripts/
-RUN bash /scripts/emscripten.sh
-
-COPY scripts/sccache.sh /scripts/
-RUN sh /scripts/sccache.sh
-
-ENV PATH=$PATH:/emsdk-portable
-ENV PATH=$PATH:/emsdk-portable/upstream/emscripten/
-ENV PATH=$PATH:/emsdk-portable/node/12.9.1_64bit/bin/
-ENV BINARYEN_ROOT=/emsdk-portable/upstream/
-
-ENV TARGETS=asmjs-unknown-emscripten
-
-# Use -O1 optimizations in the link step to reduce time spent optimizing JS.
-ENV EMCC_CFLAGS=-O1
-
-# Emscripten installation is user-specific
-ENV NO_CHANGE_USER=1
-
-ENV SCRIPT python3 ../x.py --stage 2 test --host='' --target $TARGETS
-
-# This is almost identical to the wasm32-unknown-emscripten target, so
-# running with assertions again is not useful
-ENV NO_DEBUG_ASSERTIONS=1
-ENV NO_LLVM_ASSERTIONS=1
-ENV NO_OVERFLOW_CHECKS=1
diff --git a/src/ci/docker/host-x86_64/dist-various-1/Dockerfile b/src/ci/docker/host-x86_64/dist-various-1/Dockerfile
index 3372baed999ac..341e2de223aa5 100644
--- a/src/ci/docker/host-x86_64/dist-various-1/Dockerfile
+++ b/src/ci/docker/host-x86_64/dist-various-1/Dockerfile
@@ -75,8 +75,7 @@ ENV RUN_MAKE_TARGETS=$RUN_MAKE_TARGETS,thumbv7m-none-eabi
 ENV RUN_MAKE_TARGETS=$RUN_MAKE_TARGETS,thumbv7em-none-eabi
 ENV RUN_MAKE_TARGETS=$RUN_MAKE_TARGETS,thumbv7em-none-eabihf
 
-ENV TARGETS=asmjs-unknown-emscripten
-ENV TARGETS=$TARGETS,wasm32-unknown-emscripten
+ENV TARGETS=wasm32-unknown-emscripten
 ENV TARGETS=$TARGETS,arm-unknown-linux-musleabi
 ENV TARGETS=$TARGETS,arm-unknown-linux-musleabihf
 ENV TARGETS=$TARGETS,armv5te-unknown-linux-gnueabi

From e8a027433b205af1d0815d17dbf4bde0f48fa592 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:15:30 -0700
Subject: [PATCH 04/21] Remove asmjs from miri

---
 src/tools/miri/src/shims/foreign_items.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs
index 2d5df3037452f..329a30a9faf3b 100644
--- a/src/tools/miri/src/shims/foreign_items.rs
+++ b/src/tools/miri/src/shims/foreign_items.rs
@@ -345,7 +345,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
         // List taken from `library/std/src/sys/common/alloc.rs`.
         // This list should be kept in sync with the one from libstd.
         let min_align = match this.tcx.sess.target.arch.as_ref() {
-            "x86" | "arm" | "mips" | "mips32r6" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
+            "x86" | "arm" | "mips" | "mips32r6" | "powerpc" | "powerpc64" | "wasm32" => 8,
             "x86_64" | "aarch64" | "mips64" | "mips64r6" | "s390x" | "sparc64" | "loongarch64" =>
                 16,
             arch => bug!("unsupported target architecture for malloc: `{}`", arch),

From ca4d6d15ff0ef8002aaaaf12938775e215ff6aa8 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:17:39 -0700
Subject: [PATCH 05/21] Remove asmjs from tools

---
 src/librustdoc/clean/cfg.rs               | 1 -
 src/tools/build-manifest/src/main.rs      | 1 -
 src/tools/compiletest/src/common.rs       | 3 ---
 src/tools/compiletest/src/header/cfg.rs   | 8 +-------
 src/tools/compiletest/src/header/tests.rs | 5 -----
 5 files changed, 1 insertion(+), 17 deletions(-)

diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs
index ab5aec12fe7cb..a5fa9980ce072 100644
--- a/src/librustdoc/clean/cfg.rs
+++ b/src/librustdoc/clean/cfg.rs
@@ -516,7 +516,6 @@ impl<'a> fmt::Display for Display<'a> {
                     (sym::target_arch, Some(arch)) => match arch.as_str() {
                         "aarch64" => "AArch64",
                         "arm" => "ARM",
-                        "asmjs" => "JavaScript",
                         "loongarch64" => "LoongArch LA64",
                         "m68k" => "M68k",
                         "csky" => "CSKY",
diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs
index 2c795ebb21487..88f940c7678ac 100644
--- a/src/tools/build-manifest/src/main.rs
+++ b/src/tools/build-manifest/src/main.rs
@@ -82,7 +82,6 @@ static TARGETS: &[&str] = &[
     "armv7r-none-eabi",
     "armv7r-none-eabihf",
     "armv7s-apple-ios",
-    "asmjs-unknown-emscripten",
     "bpfeb-unknown-none",
     "bpfel-unknown-none",
     "i386-apple-ios",
diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index 0e1bf0c6c2dce..11e51ef6e4ba3 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -396,9 +396,6 @@ impl Config {
 
     pub fn matches_arch(&self, arch: &str) -> bool {
         self.target_cfg().arch == arch ||
-        // Shorthand for convenience. The arch for
-        // asmjs-unknown-emscripten is actually wasm32.
-        (arch == "asmjs" && self.target.starts_with("asmjs")) ||
         // Matching all the thumb variants as one can be convenient.
         // (thumbv6m, thumbv7em, thumbv7m, etc.)
         (arch == "thumb" && self.target.starts_with("thumb"))
diff --git a/src/tools/compiletest/src/header/cfg.rs b/src/tools/compiletest/src/header/cfg.rs
index 77c2866b366a6..3a1b9dff3a6b5 100644
--- a/src/tools/compiletest/src/header/cfg.rs
+++ b/src/tools/compiletest/src/header/cfg.rs
@@ -146,19 +146,13 @@ pub(super) fn parse_cfg_name_directive<'a>(
     }
 
     // `wasm32-bare` is an alias to refer to just wasm32-unknown-unknown
-    // (in contrast to `wasm32` which also matches non-bare targets like
-    // asmjs-unknown-emscripten).
+    // (in contrast to `wasm32` which also matches non-bare targets)
     condition! {
         name: "wasm32-bare",
         condition: config.target == "wasm32-unknown-unknown",
         message: "when the target is WASM"
     }
 
-    condition! {
-        name: "asmjs",
-        condition: config.target.starts_with("asmjs"),
-        message: "when the architecture is asm.js",
-    }
     condition! {
         name: "thumb",
         condition: config.target.starts_with("thumb"),
diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs
index 2fd80b52ceeee..ab600f179137e 100644
--- a/src/tools/compiletest/src/header/tests.rs
+++ b/src/tools/compiletest/src/header/tests.rs
@@ -396,8 +396,6 @@ fn ignore_arch() {
         ("x86_64-unknown-linux-gnu", "x86_64"),
         ("i686-unknown-linux-gnu", "x86"),
         ("nvptx64-nvidia-cuda", "nvptx64"),
-        ("asmjs-unknown-emscripten", "wasm32"),
-        ("asmjs-unknown-emscripten", "asmjs"),
         ("thumbv7m-none-eabi", "thumb"),
     ];
     for (target, arch) in archs {
@@ -490,9 +488,6 @@ fn wasm_special() {
         ("wasm32-unknown-unknown", "wasm32", true),
         ("wasm32-unknown-unknown", "wasm32-bare", true),
         ("wasm32-unknown-unknown", "wasm64", false),
-        ("asmjs-unknown-emscripten", "emscripten", true),
-        ("asmjs-unknown-emscripten", "wasm32", true),
-        ("asmjs-unknown-emscripten", "wasm32-bare", false),
         ("wasm32-unknown-emscripten", "emscripten", true),
         ("wasm32-unknown-emscripten", "wasm32", true),
         ("wasm32-unknown-emscripten", "wasm32-bare", false),

From 0c1a452304a832428c629e083d61d58e4a077018 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:20:14 -0700
Subject: [PATCH 06/21] Remove asmjs from bootstrap

---
 src/bootstrap/src/lib.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs
index 8dd1a698dfa8e..c65954ed2545f 100644
--- a/src/bootstrap/src/lib.rs
+++ b/src/bootstrap/src/lib.rs
@@ -97,7 +97,7 @@ const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
     /* Extra values not defined in the built-in targets yet, but used in std */
     (Some(Mode::Std), "target_env", Some(&["libnx"])),
     // (Some(Mode::Std), "target_os", Some(&[])),
-    (Some(Mode::Std), "target_arch", Some(&["asmjs", "spirv", "nvptx", "xtensa"])),
+    (Some(Mode::Std), "target_arch", Some(&["spirv", "nvptx", "xtensa"])),
     /* Extra names used by dependencies */
     // FIXME: Used by serde_json, but we should not be triggering on external dependencies.
     (Some(Mode::Rustc), "no_btreemap_remove_entry", None),

From 208f378ef18aa1d8d9482caa7fa5ab8ab190d2f3 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:20:55 -0700
Subject: [PATCH 07/21] Remove asmjs from compiler

---
 compiler/rustc_codegen_llvm/src/back/write.rs              | 6 +-----
 compiler/rustc_codegen_ssa/src/back/link.rs                | 6 +++---
 compiler/rustc_target/src/abi/call/mod.rs                  | 1 -
 compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs | 7 -------
 compiler/rustc_target/src/spec/mod.rs                      | 5 -----
 5 files changed, 4 insertions(+), 21 deletions(-)
 delete mode 100644 compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs

diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs
index 9d5204034def0..8d335ff17183c 100644
--- a/compiler/rustc_codegen_llvm/src/back/write.rs
+++ b/compiler/rustc_codegen_llvm/src/back/write.rs
@@ -990,11 +990,7 @@ unsafe fn embed_bitcode(
     // reason (see issue #90326 for historical background).
     let is_aix = target_is_aix(cgcx);
     let is_apple = target_is_apple(cgcx);
-    if is_apple
-        || is_aix
-        || cgcx.opts.target_triple.triple().starts_with("wasm")
-        || cgcx.opts.target_triple.triple().starts_with("asmjs")
-    {
+    if is_apple || is_aix || cgcx.opts.target_triple.triple().starts_with("wasm") {
         // We don't need custom section flags, create LLVM globals.
         let llconst = common::bytes_in_context(llcx, bitcode);
         let llglobal = llvm::LLVMAddGlobal(
diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs
index bcbb75d959976..61f36cb912d29 100644
--- a/compiler/rustc_codegen_ssa/src/back/link.rs
+++ b/compiler/rustc_codegen_ssa/src/back/link.rs
@@ -2251,9 +2251,9 @@ fn linker_with_args<'a>(
     // ------------ Late order-dependent options ------------
 
     // Doesn't really make sense.
-    // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
-    // introduce a target spec option for order-independent linker options, migrate built-in specs
-    // to it and remove the option.
+    // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
+    // Introduce a target spec option for order-independent linker options, migrate built-in specs
+    // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
     add_post_link_args(cmd, sess, flavor);
 
     Ok(cmd.take_cmd())
diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs
index 5efd171b9dd76..1aa24f6b84a8d 100644
--- a/compiler/rustc_target/src/abi/call/mod.rs
+++ b/compiler/rustc_target/src/abi/call/mod.rs
@@ -836,7 +836,6 @@ impl<'a, Ty> FnAbi<'a, Ty> {
                     wasm::compute_c_abi_info(cx, self)
                 }
             }
-            "asmjs" => wasm::compute_c_abi_info(cx, self),
             "bpf" => bpf::compute_abi_info(self),
             arch => {
                 return Err(AdjustForForeignAbiError::Unsupported {
diff --git a/compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs b/compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs
deleted file mode 100644
index f492c3451a418..0000000000000
--- a/compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-use super::{wasm32_unknown_emscripten, LinkerFlavor, Target};
-
-pub fn target() -> Target {
-    let mut target = wasm32_unknown_emscripten::target();
-    target.add_post_link_args(LinkerFlavor::EmCc, &["-sWASM=0", "--memory-init-file", "0"]);
-    target
-}
diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs
index 31f538d8b612c..915b5aa288f76 100644
--- a/compiler/rustc_target/src/spec/mod.rs
+++ b/compiler/rustc_target/src/spec/mod.rs
@@ -1641,7 +1641,6 @@ supported_targets! {
     ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
     ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
 
-    ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
     ("wasm32-unknown-unknown", wasm32_unknown_unknown),
     ("wasm32-wasi", wasm32_wasi),
@@ -2276,10 +2275,6 @@ impl TargetOptions {
         add_link_args(&mut self.pre_link_args, flavor, args);
     }
 
-    fn add_post_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
-        add_link_args(&mut self.post_link_args, flavor, args);
-    }
-
     fn update_from_cli(&mut self) {
         self.linker_flavor = LinkerFlavor::from_cli_json(
             self.linker_flavor_json,

From dbb250046d20da4eaa0320b3ecb52befce3dd419 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:12:19 -0700
Subject: [PATCH 08/21] Officially remove asmjs platform support

---
 src/doc/rustc/src/platform-support.md | 1 -
 1 file changed, 1 deletion(-)

diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md
index ae514ff38fa0a..2a8e6a8124fd6 100644
--- a/src/doc/rustc/src/platform-support.md
+++ b/src/doc/rustc/src/platform-support.md
@@ -148,7 +148,6 @@ target | std | notes
 `armv7a-none-eabi` | * | Bare ARMv7-A
 `armv7r-none-eabi` | * | Bare ARMv7-R
 `armv7r-none-eabihf` | * | Bare ARMv7-R, hardfloat
-`asmjs-unknown-emscripten` | ✓ | asm.js via Emscripten
 `i586-pc-windows-msvc` | * | 32-bit Windows w/o SSE [^x86_32-floats-x87]
 `i586-unknown-linux-gnu` | ✓ | 32-bit Linux w/o SSE (kernel 3.2, glibc 2.17) [^x86_32-floats-x87]
 `i586-unknown-linux-musl` | ✓ | 32-bit Linux w/o SSE, MUSL [^x86_32-floats-x87]

From e6779d98eef749832c5626c94c3391aa057a941b Mon Sep 17 00:00:00 2001
From: DaniPopes <57450786+DaniPopes@users.noreply.github.com>
Date: Fri, 3 Nov 2023 17:11:39 +0100
Subject: [PATCH 09/21] library: use `copied` instead of manual `map`

---
 library/core/src/array/mod.rs            | 2 +-
 library/core/src/iter/adapters/copied.rs | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs
index ebd4a8c05fe30..4c48b199f0f27 100644
--- a/library/core/src/array/mod.rs
+++ b/library/core/src/array/mod.rs
@@ -206,7 +206,7 @@ where
 
     #[inline]
     fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
-        <&Self>::try_from(slice).map(|r| *r)
+        <&Self>::try_from(slice).copied()
     }
 }
 
diff --git a/library/core/src/iter/adapters/copied.rs b/library/core/src/iter/adapters/copied.rs
index 8f6b2904eae42..7a2c9d839b7e4 100644
--- a/library/core/src/iter/adapters/copied.rs
+++ b/library/core/src/iter/adapters/copied.rs
@@ -193,7 +193,7 @@ where
     T: Copy,
 {
     default fn spec_next_chunk(&mut self) -> Result<[T; N], array::IntoIter<T, N>> {
-        array::iter_next_chunk(&mut self.map(|e| *e))
+        array::iter_next_chunk(&mut self.copied())
     }
 }
 

From 27364309a52fb7bc2df365cb26b4d6227aaa0e15 Mon Sep 17 00:00:00 2001
From: DaniPopes <57450786+DaniPopes@users.noreply.github.com>
Date: Fri, 3 Nov 2023 17:18:19 +0100
Subject: [PATCH 10/21] compiler: use `copied` instead of manual `map`

---
 compiler/rustc_ast_lowering/src/expr.rs               | 3 +--
 compiler/rustc_ast_lowering/src/lib.rs                | 4 ++--
 compiler/rustc_infer/src/infer/error_reporting/mod.rs | 2 +-
 compiler/rustc_lint/src/context.rs                    | 2 +-
 compiler/rustc_middle/src/mir/pretty.rs               | 2 +-
 compiler/rustc_ty_utils/src/assoc.rs                  | 4 ++--
 6 files changed, 8 insertions(+), 9 deletions(-)

diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs
index 93805710cb544..88e44e10a13f7 100644
--- a/compiler/rustc_ast_lowering/src/expr.rs
+++ b/compiler/rustc_ast_lowering/src/expr.rs
@@ -41,8 +41,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
                     }
                     // Merge attributes into the inner expression.
                     if !e.attrs.is_empty() {
-                        let old_attrs =
-                            self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
+                        let old_attrs = self.attrs.get(&ex.hir_id.local_id).copied().unwrap_or(&[]);
                         self.attrs.insert(
                             ex.hir_id.local_id,
                             &*self.arena.alloc_from_iter(
diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index bc656585d4783..69ccf739af3c7 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -505,7 +505,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
     /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
     /// resolver (if any).
     fn orig_opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
-        self.resolver.node_id_to_def_id.get(&node).map(|local_def_id| *local_def_id)
+        self.resolver.node_id_to_def_id.get(&node).copied()
     }
 
     /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
@@ -548,7 +548,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
         self.generics_def_id_map
             .iter()
             .rev()
-            .find_map(|map| map.get(&local_def_id).map(|local_def_id| *local_def_id))
+            .find_map(|map| map.get(&local_def_id).copied())
             .unwrap_or(local_def_id)
     }
 
diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs
index e4be435fded30..5fd846d0845e8 100644
--- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs
+++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs
@@ -860,7 +860,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
                         self.suggest_boxing_for_return_impl_trait(
                             err,
                             ret_sp,
-                            prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
+                            prior_arms.iter().chain(std::iter::once(&arm_span)).copied(),
                         );
                     }
                 }
diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs
index 5b7ba03d9adfc..1df1deca65cf0 100644
--- a/compiler/rustc_lint/src/context.rs
+++ b/compiler/rustc_lint/src/context.rs
@@ -715,7 +715,7 @@ pub trait LintContext: Sized {
                     db.note("see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information");
                 },
                 BuiltinLintDiagnostics::UnexpectedCfgName((name, name_span), value) => {
-                    let possibilities: Vec<Symbol> = sess.parse_sess.check_config.expecteds.keys().map(|s| *s).collect();
+                    let possibilities: Vec<Symbol> = sess.parse_sess.check_config.expecteds.keys().copied().collect();
 
                     // Suggest the most probable if we found one
                     if let Some(best_match) = find_best_match_for_name(&possibilities, name, None) {
diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs
index debd85dad2e02..2136752e63913 100644
--- a/compiler/rustc_middle/src/mir/pretty.rs
+++ b/compiler/rustc_middle/src/mir/pretty.rs
@@ -1337,7 +1337,7 @@ pub fn write_allocations<'tcx>(
     fn alloc_ids_from_alloc(
         alloc: ConstAllocation<'_>,
     ) -> impl DoubleEndedIterator<Item = AllocId> + '_ {
-        alloc.inner().provenance().ptrs().values().map(|id| *id)
+        alloc.inner().provenance().ptrs().values().copied()
     }
 
     fn alloc_ids_from_const_val(val: ConstValue<'_>) -> impl Iterator<Item = AllocId> + '_ {
diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs
index 3e140793b5a5a..ffeeae668587e 100644
--- a/compiler/rustc_ty_utils/src/assoc.rs
+++ b/compiler/rustc_ty_utils/src/assoc.rs
@@ -43,7 +43,7 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] {
                                     trait_fn_def_id,
                                 )
                             })
-                            .map(|def_id| *def_id),
+                            .copied(),
                     ),
             )
         }
@@ -69,7 +69,7 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] {
                                     impl_fn_def_id,
                                 )
                             })
-                            .map(|def_id| *def_id)
+                            .copied()
                     })),
             )
         }

From 890ce26213c1cdc12ae269a91a62e3502a3165cc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Esteban=20K=C3=BCber?= <esteban@kuber.com.ar>
Date: Thu, 16 Nov 2023 06:07:33 +0000
Subject: [PATCH 11/21] When using existing fn as module, don't claim it
 doesn't exist

Tweak wording of module not found in resolve, when the name exists but
belongs to a non-`mod` item.

Fix #81232.
---
 compiler/rustc_resolve/src/diagnostics.rs        | 14 +++++++++++++-
 tests/ui/suggestions/crate-or-module-typo.rs     |  2 +-
 tests/ui/suggestions/crate-or-module-typo.stderr |  4 ++--
 3 files changed, 16 insertions(+), 4 deletions(-)

diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs
index 93db6cfc4635d..28e6fe9b4b739 100644
--- a/compiler/rustc_resolve/src/diagnostics.rs
+++ b/compiler/rustc_resolve/src/diagnostics.rs
@@ -2028,7 +2028,19 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
                     },
                 )
             });
-            (format!("use of undeclared crate or module `{ident}`"), suggestion)
+            if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
+                ident,
+                ScopeSet::All(ValueNS),
+                parent_scope,
+                None,
+                false,
+                ignore_binding,
+            ) {
+                let descr = binding.res().descr();
+                (format!("{descr} `{ident}` is not a crate or module"), suggestion)
+            } else {
+                (format!("use of undeclared crate or module `{ident}`"), suggestion)
+            }
         }
     }
 
diff --git a/tests/ui/suggestions/crate-or-module-typo.rs b/tests/ui/suggestions/crate-or-module-typo.rs
index 2471b11c61efd..b12ad495e9fd5 100644
--- a/tests/ui/suggestions/crate-or-module-typo.rs
+++ b/tests/ui/suggestions/crate-or-module-typo.rs
@@ -3,7 +3,7 @@
 use st::cell::Cell; //~ ERROR failed to resolve: use of undeclared crate or module `st`
 
 mod bar {
-    pub fn bar() { bar::baz(); } //~ ERROR failed to resolve: use of undeclared crate or module `bar`
+    pub fn bar() { bar::baz(); } //~ ERROR failed to resolve: function `bar` is not a crate or module
 
     fn baz() {}
 }
diff --git a/tests/ui/suggestions/crate-or-module-typo.stderr b/tests/ui/suggestions/crate-or-module-typo.stderr
index 9ece31e76f005..457d779064682 100644
--- a/tests/ui/suggestions/crate-or-module-typo.stderr
+++ b/tests/ui/suggestions/crate-or-module-typo.stderr
@@ -42,11 +42,11 @@ LL -     bar: st::cell::Cell<bool>
 LL +     bar: cell::Cell<bool>
    |
 
-error[E0433]: failed to resolve: use of undeclared crate or module `bar`
+error[E0433]: failed to resolve: function `bar` is not a crate or module
   --> $DIR/crate-or-module-typo.rs:6:20
    |
 LL |     pub fn bar() { bar::baz(); }
-   |                    ^^^ use of undeclared crate or module `bar`
+   |                    ^^^ function `bar` is not a crate or module
 
 error: aborting due to 4 previous errors
 

From ae62ebedfb0bc8b4528564d17af1195d6d593914 Mon Sep 17 00:00:00 2001
From: Michael Goulet <michael@errs.io>
Date: Thu, 16 Nov 2023 22:20:50 +0000
Subject: [PATCH 12/21] Don't require intercrate mode for negative coherence

---
 .../rustc_trait_selection/src/traits/coherence.rs    |  6 +++++-
 .../coherence-negative-outlives-lifetimes.rs         |  2 +-
 ...outlives-lifetimes.with_negative_coherence.stderr | 11 -----------
 tests/ui/coherence/coherence-overlap-with-regions.rs |  8 +-------
 .../coherence/coherence-overlap-with-regions.stderr  | 11 -----------
 .../negative-coherence-considering-regions.rs        |  2 +-
 ...ve-coherence-considering-regions.static_lt.stderr | 12 ------------
 7 files changed, 8 insertions(+), 44 deletions(-)
 delete mode 100644 tests/ui/coherence/coherence-negative-outlives-lifetimes.with_negative_coherence.stderr
 delete mode 100644 tests/ui/coherence/coherence-overlap-with-regions.stderr
 delete mode 100644 tests/ui/coherence/negative-coherence-considering-regions.static_lt.stderr

diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs
index 7ca33ae41c0ce..0274c004f839f 100644
--- a/compiler/rustc_trait_selection/src/traits/coherence.rs
+++ b/compiler/rustc_trait_selection/src/traits/coherence.rs
@@ -397,7 +397,11 @@ fn impl_intersection_has_negative_obligation(
 ) -> bool {
     debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
 
-    let ref infcx = tcx.infer_ctxt().intercrate(true).with_next_trait_solver(true).build();
+    // N.B. We don't need to use intercrate mode here because we're trying to prove
+    // the *existence* of a negative goal, not the non-existence of a positive goal.
+    // Without this, we over-eagerly register coherence ambiguity candidates when
+    // impl candidates do exist.
+    let ref infcx = tcx.infer_ctxt().with_next_trait_solver(true).build();
     let universe = infcx.universe();
 
     let impl1_header = fresh_impl_header(infcx, impl1_def_id);
diff --git a/tests/ui/coherence/coherence-negative-outlives-lifetimes.rs b/tests/ui/coherence/coherence-negative-outlives-lifetimes.rs
index 0e16d12a18114..3acf0d8d39ab9 100644
--- a/tests/ui/coherence/coherence-negative-outlives-lifetimes.rs
+++ b/tests/ui/coherence/coherence-negative-outlives-lifetimes.rs
@@ -1,5 +1,5 @@
 // revisions: stock with_negative_coherence
-//[with_negative_coherence] known-bug: unknown
+//[with_negative_coherence] check-pass
 
 #![feature(negative_impls)]
 #![cfg_attr(with_negative_coherence, feature(with_negative_coherence))]
diff --git a/tests/ui/coherence/coherence-negative-outlives-lifetimes.with_negative_coherence.stderr b/tests/ui/coherence/coherence-negative-outlives-lifetimes.with_negative_coherence.stderr
deleted file mode 100644
index 097cc4e0fe3e6..0000000000000
--- a/tests/ui/coherence/coherence-negative-outlives-lifetimes.with_negative_coherence.stderr
+++ /dev/null
@@ -1,11 +0,0 @@
-error[E0119]: conflicting implementations of trait `MyTrait<'_>` for type `&_`
-  --> $DIR/coherence-negative-outlives-lifetimes.rs:14:1
-   |
-LL | impl<'a, T: MyPredicate<'a>> MyTrait<'a> for T {}
-   | ---------------------------------------------- first implementation here
-LL | impl<'a, T> MyTrait<'a> for &'a T {}
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `&_`
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0119`.
diff --git a/tests/ui/coherence/coherence-overlap-with-regions.rs b/tests/ui/coherence/coherence-overlap-with-regions.rs
index 9945c8e6cfd7b..32f01f4180103 100644
--- a/tests/ui/coherence/coherence-overlap-with-regions.rs
+++ b/tests/ui/coherence/coherence-overlap-with-regions.rs
@@ -1,10 +1,4 @@
-// known-bug: unknown
-
-// This fails because we currently perform negative coherence in coherence mode.
-// This means that when looking for a negative predicate, we also assemble a
-// coherence-unknowable predicate. Since confirming the negative impl has region
-// obligations, we don't prefer the impl over the unknowable predicate
-// unconditionally and instead flounder.
+// check-pass
 
 #![feature(negative_impls)]
 #![feature(rustc_attrs)]
diff --git a/tests/ui/coherence/coherence-overlap-with-regions.stderr b/tests/ui/coherence/coherence-overlap-with-regions.stderr
deleted file mode 100644
index fd25f0978bad2..0000000000000
--- a/tests/ui/coherence/coherence-overlap-with-regions.stderr
+++ /dev/null
@@ -1,11 +0,0 @@
-error[E0119]: conflicting implementations of trait `Bar` for type `&_`
-  --> $DIR/coherence-overlap-with-regions.rs:20:1
-   |
-LL | impl<T: Foo> Bar for T {}
-   | ---------------------- first implementation here
-LL | impl<T> Bar for &T where T: 'static {}
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `&_`
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0119`.
diff --git a/tests/ui/coherence/negative-coherence-considering-regions.rs b/tests/ui/coherence/negative-coherence-considering-regions.rs
index 597a597262846..e7dab91073dcf 100644
--- a/tests/ui/coherence/negative-coherence-considering-regions.rs
+++ b/tests/ui/coherence/negative-coherence-considering-regions.rs
@@ -1,5 +1,5 @@
 // revisions: any_lt static_lt
-//[static_lt] known-bug: unknown
+//[static_lt] check-pass
 
 // This fails because we currently perform negative coherence in coherence mode.
 // This means that when looking for a negative predicate, we also assemble a
diff --git a/tests/ui/coherence/negative-coherence-considering-regions.static_lt.stderr b/tests/ui/coherence/negative-coherence-considering-regions.static_lt.stderr
deleted file mode 100644
index 87e7be2aa44a9..0000000000000
--- a/tests/ui/coherence/negative-coherence-considering-regions.static_lt.stderr
+++ /dev/null
@@ -1,12 +0,0 @@
-error[E0119]: conflicting implementations of trait `Bar` for type `&'static _`
-  --> $DIR/negative-coherence-considering-regions.rs:26:1
-   |
-LL | impl<T> Bar for T where T: Foo {}
-   | ------------------------------ first implementation here
-...
-LL | impl<T> Bar for &'static T {}
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `&'static _`
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0119`.

From d688b86c3df18c76de65966d5355e19a7df5deb4 Mon Sep 17 00:00:00 2001
From: Michael Goulet <michael@errs.io>
Date: Thu, 16 Nov 2023 22:50:59 +0000
Subject: [PATCH 13/21] Ignore but do not assume region obligations from
 unifying headers in negative coherence

---
 .../src/traits/coherence.rs                   | 12 ++++-----
 ...constraints-on-unification.explicit.stderr | 19 ++++++++++++++
 ...older-region-constraints-on-unification.rs | 25 +++++++++++++++++++
 3 files changed, 50 insertions(+), 6 deletions(-)
 create mode 100644 tests/ui/coherence/negative-coherence-placeholder-region-constraints-on-unification.explicit.stderr
 create mode 100644 tests/ui/coherence/negative-coherence-placeholder-region-constraints-on-unification.rs

diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs
index 7ca33ae41c0ce..faded18582f70 100644
--- a/compiler/rustc_trait_selection/src/traits/coherence.rs
+++ b/compiler/rustc_trait_selection/src/traits/coherence.rs
@@ -542,14 +542,14 @@ fn try_prove_negated_where_clause<'tcx>(
     };
 
     // FIXME(with_negative_coherence): the infcx has region contraints from equating
-    // the impl headers as requirements. Given that the only region constraints we
-    // get are involving inference regions in the root, it shouldn't matter, but
-    // still sus.
+    // the impl headers as requirements.
     //
-    // We probably should just throw away the region obligations registered up until
-    // now, or ideally use them as assumptions when proving the region obligations
-    // that we get from proving the negative predicate below.
+    // We ideally should use these region constraints as assumptions when proving
+    // the region obligations that we get from proving the negative predicate below.
     let ref infcx = root_infcx.fork();
+    let _ = infcx.take_registered_region_obligations();
+    let _ = infcx.take_and_reset_region_constraints();
+
     let ocx = ObligationCtxt::new(infcx);
 
     ocx.register_obligation(Obligation::new(
diff --git a/tests/ui/coherence/negative-coherence-placeholder-region-constraints-on-unification.explicit.stderr b/tests/ui/coherence/negative-coherence-placeholder-region-constraints-on-unification.explicit.stderr
new file mode 100644
index 0000000000000..34f3904443c31
--- /dev/null
+++ b/tests/ui/coherence/negative-coherence-placeholder-region-constraints-on-unification.explicit.stderr
@@ -0,0 +1,19 @@
+error: conflicting implementations of trait `FnMarker` for type `fn(&_)`
+  --> $DIR/negative-coherence-placeholder-region-constraints-on-unification.rs:21:1
+   |
+LL | impl<T: ?Sized + Marker> FnMarker for fn(T) {}
+   | ------------------------------------------- first implementation here
+LL | impl<T: ?Sized> FnMarker for fn(&T) {}
+   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `fn(&_)`
+   |
+   = 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 #56105 <https://github.com/rust-lang/rust/issues/56105>
+   = note: this behavior recently changed as a result of a bug fix; see rust-lang/rust#56105 for details
+note: the lint level is defined here
+  --> $DIR/negative-coherence-placeholder-region-constraints-on-unification.rs:4:11
+   |
+LL | #![forbid(coherence_leak_check)]
+   |           ^^^^^^^^^^^^^^^^^^^^
+
+error: aborting due to previous error
+
diff --git a/tests/ui/coherence/negative-coherence-placeholder-region-constraints-on-unification.rs b/tests/ui/coherence/negative-coherence-placeholder-region-constraints-on-unification.rs
new file mode 100644
index 0000000000000..26d9d84d8f0c9
--- /dev/null
+++ b/tests/ui/coherence/negative-coherence-placeholder-region-constraints-on-unification.rs
@@ -0,0 +1,25 @@
+// revisions: explicit implicit
+//[implicit] check-pass
+
+#![forbid(coherence_leak_check)]
+#![feature(negative_impls, with_negative_coherence)]
+
+pub trait Marker {}
+
+#[cfg(implicit)]
+impl<T: ?Sized> !Marker for &T {}
+
+#[cfg(explicit)]
+impl<'a, T: ?Sized + 'a> !Marker for &'a T {}
+
+trait FnMarker {}
+
+// Unifying these two impls below results in a `T: '!0` obligation
+// that we shouldn't need to care about. Ideally, we'd treat that
+// as an assumption when proving `&'!0 T: Marker`...
+impl<T: ?Sized + Marker> FnMarker for fn(T) {}
+impl<T: ?Sized> FnMarker for fn(&T) {}
+//[explicit]~^ ERROR conflicting implementations of trait `FnMarker` for type `fn(&_)`
+//[explicit]~| WARN this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+
+fn main() {}

From ae179a04b64d56fa4d648fccf3db661301550797 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Wed, 8 Nov 2023 12:37:26 +0300
Subject: [PATCH 14/21] emit basic smir

---
 compiler/rustc_driver_impl/Cargo.toml         |   1 +
 compiler/rustc_driver_impl/src/pretty.rs      |   6 +
 compiler/rustc_session/src/config.rs          |  10 +-
 compiler/rustc_smir/src/rustc_internal/mod.rs |   7 +
 .../rustc_smir/src/rustc_internal/pretty.rs   | 133 ++++++++++++++++++
 compiler/rustc_smir/src/rustc_smir/mod.rs     |   6 +-
 compiler/stable_mir/src/mir/body.rs           |   2 +
 7 files changed, 160 insertions(+), 5 deletions(-)
 create mode 100644 compiler/rustc_smir/src/rustc_internal/pretty.rs

diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml
index da7c2440faad4..e9b5a32842204 100644
--- a/compiler/rustc_driver_impl/Cargo.toml
+++ b/compiler/rustc_driver_impl/Cargo.toml
@@ -44,6 +44,7 @@ rustc_query_system = { path = "../rustc_query_system" }
 rustc_resolve = { path = "../rustc_resolve" }
 rustc_session = { path = "../rustc_session" }
 rustc_span = { path = "../rustc_span" }
+rustc_smir ={ path = "../rustc_smir" }
 rustc_symbol_mangling = { path = "../rustc_symbol_mangling" }
 rustc_target = { path = "../rustc_target" }
 rustc_trait_selection = { path = "../rustc_trait_selection" }
diff --git a/compiler/rustc_driver_impl/src/pretty.rs b/compiler/rustc_driver_impl/src/pretty.rs
index cc533b9941ab4..84f8941ff662d 100644
--- a/compiler/rustc_driver_impl/src/pretty.rs
+++ b/compiler/rustc_driver_impl/src/pretty.rs
@@ -9,6 +9,7 @@ use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};
 use rustc_middle::ty::{self, TyCtxt};
 use rustc_session::config::{OutFileName, PpHirMode, PpMode, PpSourceMode};
 use rustc_session::Session;
+use rustc_smir::rustc_internal::pretty::write_smir_pretty;
 use rustc_span::symbol::Ident;
 use rustc_span::FileName;
 
@@ -325,6 +326,11 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
             write_mir_graphviz(ex.tcx(), None, &mut out).unwrap();
             String::from_utf8(out).unwrap()
         }
+        Smir => {
+            let mut out = Vec::new();
+            write_smir_pretty(ex.tcx(), &mut out).unwrap();
+            String::from_utf8(out).unwrap()
+        }
         ThirTree => {
             let tcx = ex.tcx();
             let mut out = String::new();
diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs
index add40b83d21d3..54335645e43e2 100644
--- a/compiler/rustc_session/src/config.rs
+++ b/compiler/rustc_session/src/config.rs
@@ -2926,6 +2926,7 @@ fn parse_pretty(handler: &EarlyErrorHandler, unstable_opts: &UnstableOptions) ->
         "thir-tree" => ThirTree,
         "thir-flat" => ThirFlat,
         "mir" => Mir,
+        "smir" => Smir,
         "mir-cfg" => MirCFG,
         name => handler.early_error(format!(
             "argument to `unpretty` must be one of `normal`, `identified`, \
@@ -3106,6 +3107,8 @@ pub enum PpMode {
     Mir,
     /// `-Zunpretty=mir-cfg`
     MirCFG,
+    /// `-Zunpretty=smir`
+    Smir,
 }
 
 impl PpMode {
@@ -3122,7 +3125,8 @@ impl PpMode {
             | ThirTree
             | ThirFlat
             | Mir
-            | MirCFG => true,
+            | MirCFG
+            | Smir => true,
         }
     }
     pub fn needs_hir(&self) -> bool {
@@ -3130,13 +3134,13 @@ impl PpMode {
         match *self {
             Source(_) | AstTree | AstTreeExpanded => false,
 
-            Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG => true,
+            Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG | Smir => true,
         }
     }
 
     pub fn needs_analysis(&self) -> bool {
         use PpMode::*;
-        matches!(*self, Hir(PpHirMode::Typed) | Mir | MirCFG | ThirTree | ThirFlat)
+        matches!(*self, Hir(PpHirMode::Typed) | Mir | Smir | MirCFG | ThirTree | ThirFlat)
     }
 }
 
diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs
index c82f948f195e6..7957c3ce61703 100644
--- a/compiler/rustc_smir/src/rustc_internal/mod.rs
+++ b/compiler/rustc_smir/src/rustc_internal/mod.rs
@@ -21,6 +21,7 @@ use std::hash::Hash;
 use std::ops::Index;
 
 mod internal;
+pub mod pretty;
 
 pub fn stable<'tcx, S: Stable<'tcx>>(item: S) -> S::T {
     with_tables(|tables| item.stable(tables))
@@ -299,4 +300,10 @@ impl<K: PartialEq + Hash + Eq, V: Copy + Debug + PartialEq + IndexedVal> Index<V
 pub trait RustcInternal<'tcx> {
     type T;
     fn internal(&self, tables: &mut Tables<'tcx>) -> Self::T;
+
+    /// Use this when you want to convert to a rustc counterpart in user-code.
+    /// Do not use this within the smir crates themselves.
+    fn internal_via_tls(&self) -> Self::T {
+        with_tables(|tables| self.internal(tables))
+    }
 }
diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
new file mode 100644
index 0000000000000..e9af5081353ee
--- /dev/null
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -0,0 +1,133 @@
+use std::io;
+
+use rustc_middle::ty::TyCtxt;
+use stable_mir::{
+    ty::{RigidTy, TyKind},
+    CrateItem, mir::Mutability,
+};
+
+
+use super::{run, RustcInternal};
+
+pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> { 
+    run(tcx, || {
+        let items = stable_mir::all_local_items();
+        items.iter().for_each(|item| {
+            // Because we can't return a Result from a closure, we have to unwrap here.
+            writeln!(w, "{}", function_name(*item,tcx)).unwrap();
+            writeln!(w, "{}", function_body(*item,tcx)).unwrap();
+        })
+    });
+    Ok(())
+}
+
+pub fn function_name(item: CrateItem,tcx: TyCtxt<'_>) -> String {
+    let mut name = String::new();
+    let body  = item.body();
+    name.push_str("fn ");
+    name.push_str(item.name().as_str());
+    if body.arg_locals().is_empty() {
+        name.push_str("()");
+    }else{
+        name.push_str("(");
+    }
+    body.arg_locals().iter().for_each(|local| {
+        name.push_str(format!("_{}: ",local.local).as_str());
+        name.push_str(&pretty_ty(local.ty.kind(), tcx));
+    });
+    if !body.arg_locals().is_empty() {
+        name.push_str(")");
+    }
+    let return_local = body.ret_local();
+    name.push_str(" -> ");
+    name.push_str(&pretty_ty(return_local.ty.kind(), tcx));
+    name.push_str(" {");
+    name
+}
+
+pub fn function_body(item: CrateItem,_tcx: TyCtxt<'_>) -> String {
+    let mut body_str = String::new();
+    let body  = item.body();
+    body.inner_locals().iter().for_each(|local| {
+        body_str.push_str("    ");
+        body_str.push_str(format!("let {}",ret_mutability(&local.mutability)).as_str());
+        body_str.push_str(format!("_{}: ",local.local).as_str());
+        body_str.push_str(format!("{}",pretty_ty(local.ty.kind(), _tcx)).as_str());
+        body_str.push_str(";\n");
+
+    });
+    body_str.push_str("}");
+    body_str
+
+}
+
+pub fn ret_mutability(mutability: &Mutability) -> String {
+    match mutability {
+        Mutability::Not => "".to_string(),
+        Mutability::Mut => "mut ".to_string(),
+    }
+}
+
+pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
+    let mut pretty = String::new();
+    pretty.push_str("");
+    match ty {
+        TyKind::RigidTy(rigid_ty) => match rigid_ty {
+            RigidTy::Bool => "bool".to_string(),
+            RigidTy::Char => "char".to_string(),
+            RigidTy::Int(i) => match i {
+                stable_mir::ty::IntTy::Isize => "isize".to_string(),
+                stable_mir::ty::IntTy::I8 => "i8".to_string(),
+                stable_mir::ty::IntTy::I16 => "i16".to_string(),
+                stable_mir::ty::IntTy::I32 => "i32".to_string(),
+                stable_mir::ty::IntTy::I64 => "i64".to_string(),
+                stable_mir::ty::IntTy::I128 => "i128".to_string(),
+            },
+            RigidTy::Uint(u) => match u {
+                stable_mir::ty::UintTy::Usize => "usize".to_string(),
+                stable_mir::ty::UintTy::U8 => "u8".to_string(),
+                stable_mir::ty::UintTy::U16 => "u16".to_string(),
+                stable_mir::ty::UintTy::U32 => "u32".to_string(),
+                stable_mir::ty::UintTy::U64 => "u64".to_string(),
+                stable_mir::ty::UintTy::U128 => "u128".to_string(),
+            },
+            RigidTy::Float(f) => match f {
+                stable_mir::ty::FloatTy::F32 => "f32".to_string(),
+                stable_mir::ty::FloatTy::F64 => "f64".to_string(),
+            },
+            RigidTy::Adt(def, _) => format!("{:#?}", tcx.type_of(def.0.internal_via_tls()).instantiate_identity()),
+            RigidTy::Foreign(_) => format!("{:#?}", rigid_ty),
+            RigidTy::Str => "str".to_string(),
+            RigidTy::Array(_ty, len) => {
+                format!("[{};{:#?}]", 1,len.internal_via_tls())},
+            RigidTy::Slice(ty) => pretty_ty(ty.kind(),tcx),
+            RigidTy::RawPtr(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(),tcx),
+            RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
+            RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Coroutine(_, _, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Dynamic(_, _, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Never => "!".to_string(),
+            RigidTy::Tuple(tuple) => {
+                if tuple.is_empty(){
+                    "()".to_string()
+                }else {
+                    let mut tuple_str = String::new();
+                    tuple_str.push_str("(");
+                    tuple.iter().enumerate().for_each(|(i,ty)| {
+                        tuple_str.push_str(&pretty_ty(ty.kind(),tcx));
+                        if i != tuple.len() - 1 {
+                            tuple_str.push_str(", ");
+                        }
+                    });
+                    tuple_str.push_str(")");
+                    tuple_str
+                }
+            },
+        },
+        TyKind::Alias(_, _) => format!("{:#?}", ty),
+        TyKind::Param(_) => format!("{:#?}", ty),
+        TyKind::Bound(_, _) => format!("{:#?}", ty),
+    }
+}
diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs
index 3df09cef1c7dc..69b0c0bb80d55 100644
--- a/compiler/rustc_smir/src/rustc_smir/mod.rs
+++ b/compiler/rustc_smir/src/rustc_smir/mod.rs
@@ -400,10 +400,12 @@ impl<'tcx> Stable<'tcx> for mir::Body<'tcx> {
                 })
                 .collect(),
             self.local_decls
-                .iter()
-                .map(|decl| stable_mir::mir::LocalDecl {
+                .iter_enumerated()
+                .map(|(local, decl)| stable_mir::mir::LocalDecl {
                     ty: decl.ty.stable(tables),
                     span: decl.source_info.span.stable(tables),
+                    local: local.as_usize(),
+                    mutability: decl.mutability.stable(tables),
                 })
                 .collect(),
             self.arg_count,
diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs
index 351e7bb69c3f7..2981d6a8bb5c6 100644
--- a/compiler/stable_mir/src/mir/body.rs
+++ b/compiler/stable_mir/src/mir/body.rs
@@ -64,6 +64,8 @@ type LocalDecls = Vec<LocalDecl>;
 pub struct LocalDecl {
     pub ty: Ty,
     pub span: Span,
+    pub local: Local,
+    pub mutability: Mutability,
 }
 
 #[derive(Clone, Debug)]

From 0f0e9baf199d022c6a93bb36353358a101c4b4f5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Wed, 8 Nov 2023 15:25:48 +0300
Subject: [PATCH 15/21] cover statements

---
 .../rustc_smir/src/rustc_internal/pretty.rs   | 181 +++++++++++++++---
 1 file changed, 155 insertions(+), 26 deletions(-)

diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index e9af5081353ee..ea0ccfe3e4eba 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -2,37 +2,43 @@ use std::io;
 
 use rustc_middle::ty::TyCtxt;
 use stable_mir::{
+    mir::{Mutability, Operand, Rvalue, StatementKind},
     ty::{RigidTy, TyKind},
-    CrateItem, mir::Mutability,
+    CrateItem,
 };
 
-
 use super::{run, RustcInternal};
 
-pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> { 
+pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
     run(tcx, || {
         let items = stable_mir::all_local_items();
         items.iter().for_each(|item| {
             // Because we can't return a Result from a closure, we have to unwrap here.
-            writeln!(w, "{}", function_name(*item,tcx)).unwrap();
-            writeln!(w, "{}", function_body(*item,tcx)).unwrap();
+            writeln!(w, "{}", function_name(*item, tcx)).unwrap();
+            writeln!(w, "{}", function_body(*item, tcx)).unwrap();
+            writeln!(w, "------------------").unwrap();
+            item.body().blocks.iter().for_each(|block| {
+                block.statements.iter().for_each(|statement| {
+                    writeln!(w, "{}", pretty_statement(&statement.kind, tcx)).unwrap();
+                });
+            })
         })
     });
     Ok(())
 }
 
-pub fn function_name(item: CrateItem,tcx: TyCtxt<'_>) -> String {
+pub fn function_name(item: CrateItem, tcx: TyCtxt<'_>) -> String {
     let mut name = String::new();
-    let body  = item.body();
+    let body = item.body();
     name.push_str("fn ");
     name.push_str(item.name().as_str());
     if body.arg_locals().is_empty() {
         name.push_str("()");
-    }else{
+    } else {
         name.push_str("(");
     }
     body.arg_locals().iter().for_each(|local| {
-        name.push_str(format!("_{}: ",local.local).as_str());
+        name.push_str(format!("_{}: ", local.local).as_str());
         name.push_str(&pretty_ty(local.ty.kind(), tcx));
     });
     if !body.arg_locals().is_empty() {
@@ -45,20 +51,18 @@ pub fn function_name(item: CrateItem,tcx: TyCtxt<'_>) -> String {
     name
 }
 
-pub fn function_body(item: CrateItem,_tcx: TyCtxt<'_>) -> String {
+pub fn function_body(item: CrateItem, _tcx: TyCtxt<'_>) -> String {
     let mut body_str = String::new();
-    let body  = item.body();
+    let body = item.body();
     body.inner_locals().iter().for_each(|local| {
         body_str.push_str("    ");
-        body_str.push_str(format!("let {}",ret_mutability(&local.mutability)).as_str());
-        body_str.push_str(format!("_{}: ",local.local).as_str());
-        body_str.push_str(format!("{}",pretty_ty(local.ty.kind(), _tcx)).as_str());
+        body_str.push_str(format!("let {}", ret_mutability(&local.mutability)).as_str());
+        body_str.push_str(format!("_{}: ", local.local).as_str());
+        body_str.push_str(format!("{}", pretty_ty(local.ty.kind(), _tcx)).as_str());
         body_str.push_str(";\n");
-
     });
     body_str.push_str("}");
     body_str
-
 }
 
 pub fn ret_mutability(mutability: &Mutability) -> String {
@@ -68,7 +72,129 @@ pub fn ret_mutability(mutability: &Mutability) -> String {
     }
 }
 
-pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
+pub fn pretty_statement(statement: &StatementKind, tcx: TyCtxt<'_>) -> String {
+    let mut pretty = String::new();
+    match statement {
+        StatementKind::Assign(place, rval) => {
+            pretty.push_str(format!("_{} = ", place.local).as_str());
+            pretty.push_str(&pretty_rvalue(rval, tcx))
+        }
+        StatementKind::FakeRead(_, _) => todo!(),
+        StatementKind::SetDiscriminant { .. } => todo!(),
+        StatementKind::Deinit(_) => todo!(),
+        StatementKind::StorageLive(_) => todo!(),
+        StatementKind::StorageDead(_) => todo!(),
+        StatementKind::Retag(_, _) => todo!(),
+        StatementKind::PlaceMention(_) => todo!(),
+        StatementKind::AscribeUserType { .. } => todo!(),
+        StatementKind::Coverage(_) => todo!(),
+        StatementKind::Intrinsic(_) => todo!(),
+        StatementKind::ConstEvalCounter => (),
+        StatementKind::Nop => (),
+    }
+    pretty
+}
+
+pub fn pretty_operand(operand: &Operand, _tcx: TyCtxt<'_>) -> String {
+    let mut pretty = String::new();
+    match operand {
+        Operand::Copy(copy) => {
+            pretty.push_str("");
+            pretty.push_str(format!("{}", copy.local).as_str());
+        }
+        Operand::Move(mv) => {
+            pretty.push_str("move");
+            pretty.push_str(format!("{}", mv.local).as_str());
+        }
+        Operand::Constant(cnst) => {
+            pretty.push_str("const ");
+            pretty.push_str(cnst.literal.internal_via_tls().to_string().as_str());
+        }
+    }
+    pretty
+}
+
+pub fn pretty_rvalue(rval: &Rvalue, tcx: TyCtxt<'_>) -> String {
+    let mut pretty = String::new();
+    match rval {
+        Rvalue::AddressOf(muta, addr) => {
+            pretty.push_str("address_of");
+            pretty.push_str(&ret_mutability(&muta));
+            pretty.push_str(format!("{}", addr.local).as_str());
+        }
+        Rvalue::Aggregate(aggregatekind, operands) => {
+            pretty.push_str(format!("{:#?}", aggregatekind).as_str());
+            pretty.push_str("(");
+            operands.iter().enumerate().for_each(|(i, op)| {
+                pretty.push_str(&pretty_operand(op, tcx));
+                if i != operands.len() - 1 {
+                    pretty.push_str(", ");
+                }
+            });
+            pretty.push_str(")");
+        }
+        Rvalue::BinaryOp(bin, op, op2) => {
+            pretty.push_str(&pretty_operand(op, tcx));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", bin).as_str());
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_operand(op2, tcx));
+        }
+        Rvalue::Cast(_, op, ty) => {
+            pretty.push_str(&pretty_operand(op, tcx));
+            pretty.push_str(" as ");
+            pretty.push_str(&pretty_ty(ty.kind(), tcx));
+        }
+        Rvalue::CheckedBinaryOp(bin, op1, op2) => {
+            pretty.push_str(&pretty_operand(op1, tcx));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", bin).as_str());
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_operand(op2, tcx));
+        }
+        Rvalue::CopyForDeref(deref) => {
+            pretty.push_str("CopyForDeref");
+            pretty.push_str(format!("{}", deref.local).as_str());
+        }
+        Rvalue::Discriminant(place) => {
+            pretty.push_str("discriminant");
+            pretty.push_str(format!("{}", place.local).as_str());
+        }
+        Rvalue::Len(len) => {
+            pretty.push_str("len");
+            pretty.push_str(format!("{}", len.local).as_str());
+        }
+        Rvalue::Ref(_, borrowkind, place) => {
+            pretty.push_str("ref");
+            pretty.push_str(format!("{:#?}", borrowkind).as_str());
+            pretty.push_str(format!("{}", place.local).as_str());
+        }
+        Rvalue::Repeat(op, cnst) => {
+            pretty.push_str(&pretty_operand(op, tcx));
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_ty(cnst.ty().kind(), tcx));
+        }
+        Rvalue::ShallowInitBox(_, _) => todo!(),
+        Rvalue::ThreadLocalRef(item) => {
+            pretty.push_str("thread_local_ref");
+            pretty.push_str(format!("{:#?}", item).as_str());
+        }
+        Rvalue::NullaryOp(nul, ty) => {
+            pretty.push_str(format!("{:#?}", nul).as_str());
+            pretty.push_str(&&pretty_ty(ty.kind(), tcx));
+            pretty.push_str(" ");
+        }
+        Rvalue::UnaryOp(un, op) => {
+            pretty.push_str(&pretty_operand(op, tcx));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", un).as_str());
+        }
+        Rvalue::Use(op) => pretty.push_str(&pretty_operand(op, tcx)),
+    }
+    pretty
+}
+
+pub fn pretty_ty(ty: TyKind, tcx: TyCtxt<'_>) -> String {
     let mut pretty = String::new();
     pretty.push_str("");
     match ty {
@@ -95,14 +221,17 @@ pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
                 stable_mir::ty::FloatTy::F32 => "f32".to_string(),
                 stable_mir::ty::FloatTy::F64 => "f64".to_string(),
             },
-            RigidTy::Adt(def, _) => format!("{:#?}", tcx.type_of(def.0.internal_via_tls()).instantiate_identity()),
+            RigidTy::Adt(def, _) => {
+                format!("{:#?}", tcx.type_of(def.0.internal_via_tls()).instantiate_identity())
+            }
             RigidTy::Foreign(_) => format!("{:#?}", rigid_ty),
             RigidTy::Str => "str".to_string(),
             RigidTy::Array(_ty, len) => {
-                format!("[{};{:#?}]", 1,len.internal_via_tls())},
-            RigidTy::Slice(ty) => pretty_ty(ty.kind(),tcx),
+                format!("[{};{:#?}]", 1, len.internal_via_tls())
+            }
+            RigidTy::Slice(ty) => pretty_ty(ty.kind(), tcx),
             RigidTy::RawPtr(_, _) => format!("{:#?}", rigid_ty),
-            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(),tcx),
+            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(), tcx),
             RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
             RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
             RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
@@ -110,13 +239,13 @@ pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
             RigidTy::Dynamic(_, _, _) => format!("{:#?}", rigid_ty),
             RigidTy::Never => "!".to_string(),
             RigidTy::Tuple(tuple) => {
-                if tuple.is_empty(){
+                if tuple.is_empty() {
                     "()".to_string()
-                }else {
+                } else {
                     let mut tuple_str = String::new();
                     tuple_str.push_str("(");
-                    tuple.iter().enumerate().for_each(|(i,ty)| {
-                        tuple_str.push_str(&pretty_ty(ty.kind(),tcx));
+                    tuple.iter().enumerate().for_each(|(i, ty)| {
+                        tuple_str.push_str(&pretty_ty(ty.kind(), tcx));
                         if i != tuple.len() - 1 {
                             tuple_str.push_str(", ");
                         }
@@ -124,7 +253,7 @@ pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
                     tuple_str.push_str(")");
                     tuple_str
                 }
-            },
+            }
         },
         TyKind::Alias(_, _) => format!("{:#?}", ty),
         TyKind::Param(_) => format!("{:#?}", ty),

From ebd9c145f600245ec66d0ddf4c0129874c10ecb8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Thu, 9 Nov 2023 12:11:41 +0300
Subject: [PATCH 16/21] better formatting for statements

---
 Cargo.lock                                    |  1 +
 compiler/rustc_driver_impl/Cargo.toml         |  2 +-
 compiler/rustc_smir/src/rustc_internal/mod.rs |  6 --
 .../rustc_smir/src/rustc_internal/pretty.rs   | 63 ++++++++++++++-----
 compiler/stable_mir/src/mir/visit.rs          |  2 +-
 5 files changed, 49 insertions(+), 25 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 92bac995bc615..9fe70870140d8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3815,6 +3815,7 @@ dependencies = [
  "rustc_query_system",
  "rustc_resolve",
  "rustc_session",
+ "rustc_smir",
  "rustc_span",
  "rustc_symbol_mangling",
  "rustc_target",
diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml
index e9b5a32842204..545ff32e598ae 100644
--- a/compiler/rustc_driver_impl/Cargo.toml
+++ b/compiler/rustc_driver_impl/Cargo.toml
@@ -43,8 +43,8 @@ rustc_privacy = { path = "../rustc_privacy" }
 rustc_query_system = { path = "../rustc_query_system" }
 rustc_resolve = { path = "../rustc_resolve" }
 rustc_session = { path = "../rustc_session" }
-rustc_span = { path = "../rustc_span" }
 rustc_smir ={ path = "../rustc_smir" }
+rustc_span = { path = "../rustc_span" }
 rustc_symbol_mangling = { path = "../rustc_symbol_mangling" }
 rustc_target = { path = "../rustc_target" }
 rustc_trait_selection = { path = "../rustc_trait_selection" }
diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs
index 7957c3ce61703..fa75fd3076ce0 100644
--- a/compiler/rustc_smir/src/rustc_internal/mod.rs
+++ b/compiler/rustc_smir/src/rustc_internal/mod.rs
@@ -300,10 +300,4 @@ impl<K: PartialEq + Hash + Eq, V: Copy + Debug + PartialEq + IndexedVal> Index<V
 pub trait RustcInternal<'tcx> {
     type T;
     fn internal(&self, tables: &mut Tables<'tcx>) -> Self::T;
-
-    /// Use this when you want to convert to a rustc counterpart in user-code.
-    /// Do not use this within the smir crates themselves.
-    fn internal_via_tls(&self) -> Self::T {
-        with_tables(|tables| self.internal(tables))
-    }
 }
diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index ea0ccfe3e4eba..45917630cf3e9 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -7,20 +7,23 @@ use stable_mir::{
     CrateItem,
 };
 
-use super::{run, RustcInternal};
+use super::{internal, run};
 
 pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
+    writeln!(w, "// WARNING: This is highly experimental output it's intended for stable-mir developers only.").unwrap();
+    writeln!(w, "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir.").unwrap();
     run(tcx, || {
         let items = stable_mir::all_local_items();
         items.iter().for_each(|item| {
             // Because we can't return a Result from a closure, we have to unwrap here.
             writeln!(w, "{}", function_name(*item, tcx)).unwrap();
             writeln!(w, "{}", function_body(*item, tcx)).unwrap();
-            writeln!(w, "------------------").unwrap();
-            item.body().blocks.iter().for_each(|block| {
+            item.body().blocks.iter().enumerate().for_each(|(index, block)| {
+                writeln!(w, "    bb{}: {{", index).unwrap();
                 block.statements.iter().for_each(|statement| {
                     writeln!(w, "{}", pretty_statement(&statement.kind, tcx)).unwrap();
                 });
+                writeln!(w, "    }}").unwrap();
             })
         })
     });
@@ -76,8 +79,8 @@ pub fn pretty_statement(statement: &StatementKind, tcx: TyCtxt<'_>) -> String {
     let mut pretty = String::new();
     match statement {
         StatementKind::Assign(place, rval) => {
-            pretty.push_str(format!("_{} = ", place.local).as_str());
-            pretty.push_str(&pretty_rvalue(rval, tcx))
+            pretty.push_str(format!("        _{} = ", place.local).as_str());
+            pretty.push_str(format!("{}", &pretty_rvalue(rval, tcx)).as_str());
         }
         StatementKind::FakeRead(_, _) => todo!(),
         StatementKind::SetDiscriminant { .. } => todo!(),
@@ -103,12 +106,12 @@ pub fn pretty_operand(operand: &Operand, _tcx: TyCtxt<'_>) -> String {
             pretty.push_str(format!("{}", copy.local).as_str());
         }
         Operand::Move(mv) => {
-            pretty.push_str("move");
-            pretty.push_str(format!("{}", mv.local).as_str());
+            pretty.push_str("move ");
+            pretty.push_str(format!("_{}", mv.local).as_str());
         }
         Operand::Constant(cnst) => {
             pretty.push_str("const ");
-            pretty.push_str(cnst.literal.internal_via_tls().to_string().as_str());
+            pretty.push_str(internal(&cnst.literal).to_string().as_str());
         }
     }
     pretty
@@ -118,9 +121,9 @@ pub fn pretty_rvalue(rval: &Rvalue, tcx: TyCtxt<'_>) -> String {
     let mut pretty = String::new();
     match rval {
         Rvalue::AddressOf(muta, addr) => {
-            pretty.push_str("address_of");
+            pretty.push_str("&raw ");
             pretty.push_str(&ret_mutability(&muta));
-            pretty.push_str(format!("{}", addr.local).as_str());
+            pretty.push_str(format!("(*_{})", addr.local).as_str());
         }
         Rvalue::Aggregate(aggregatekind, operands) => {
             pretty.push_str(format!("{:#?}", aggregatekind).as_str());
@@ -222,21 +225,45 @@ pub fn pretty_ty(ty: TyKind, tcx: TyCtxt<'_>) -> String {
                 stable_mir::ty::FloatTy::F64 => "f64".to_string(),
             },
             RigidTy::Adt(def, _) => {
-                format!("{:#?}", tcx.type_of(def.0.internal_via_tls()).instantiate_identity())
+                format!("{}", tcx.type_of(internal(&def.0)).instantiate_identity())
             }
             RigidTy::Foreign(_) => format!("{:#?}", rigid_ty),
             RigidTy::Str => "str".to_string(),
-            RigidTy::Array(_ty, len) => {
-                format!("[{};{:#?}]", 1, len.internal_via_tls())
+            RigidTy::Array(ty, len) => {
+                format!(
+                    "[{}; {}]",
+                    pretty_ty(ty.kind(), tcx),
+                    internal(&len).try_to_scalar().unwrap()
+                )
+            }
+            RigidTy::Slice(ty) => {
+                format!("[{}]", pretty_ty(ty.kind(), tcx))
+            }
+            RigidTy::RawPtr(ty, mutability) => {
+                pretty.push_str("*");
+                match mutability {
+                    Mutability::Not => pretty.push_str("const "),
+                    Mutability::Mut => pretty.push_str("mut "),
+                }
+                pretty.push_str(&pretty_ty(ty.kind(), tcx));
+                pretty
             }
-            RigidTy::Slice(ty) => pretty_ty(ty.kind(), tcx),
-            RigidTy::RawPtr(_, _) => format!("{:#?}", rigid_ty),
             RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(), tcx),
             RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
             RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
             RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
             RigidTy::Coroutine(_, _, _) => format!("{:#?}", rigid_ty),
-            RigidTy::Dynamic(_, _, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Dynamic(data, region, repr) => {
+                // FIXME: Fix binder printing, it looks ugly now
+                pretty.push_str("(");
+                match repr {
+                    stable_mir::ty::DynKind::Dyn => pretty.push_str("dyn "),
+                    stable_mir::ty::DynKind::DynStar => pretty.push_str("dyn* "),
+                }
+                pretty.push_str(format!("{:#?}", data).as_str());
+                pretty.push_str(format!(" +  {:#?} )", region).as_str());
+                pretty
+            }
             RigidTy::Never => "!".to_string(),
             RigidTy::Tuple(tuple) => {
                 if tuple.is_empty() {
@@ -256,7 +283,9 @@ pub fn pretty_ty(ty: TyKind, tcx: TyCtxt<'_>) -> String {
             }
         },
         TyKind::Alias(_, _) => format!("{:#?}", ty),
-        TyKind::Param(_) => format!("{:#?}", ty),
+        TyKind::Param(param_ty) => {
+            format!("{:#?}", param_ty.name)
+        }
         TyKind::Bound(_, _) => format!("{:#?}", ty),
     }
 }
diff --git a/compiler/stable_mir/src/mir/visit.rs b/compiler/stable_mir/src/mir/visit.rs
index d6304d3ea398d..40bedd67352f7 100644
--- a/compiler/stable_mir/src/mir/visit.rs
+++ b/compiler/stable_mir/src/mir/visit.rs
@@ -157,7 +157,7 @@ pub trait MirVisitor {
 
     fn super_local_decl(&mut self, local: Local, decl: &LocalDecl) {
         let _ = local;
-        let LocalDecl { ty, span } = decl;
+        let LocalDecl { ty, span, .. } = decl;
         self.visit_ty(ty, Location(*span));
     }
 

From c821603484e1f0eb2d314a5e4ca842f38ac6dfab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Tue, 14 Nov 2023 13:06:58 +0300
Subject: [PATCH 17/21] remove unwrap

---
 .../rustc_smir/src/rustc_internal/pretty.rs   | 25 +++++++++++--------
 1 file changed, 15 insertions(+), 10 deletions(-)

diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index 45917630cf3e9..67995b1811046 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -12,20 +12,25 @@ use super::{internal, run};
 pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
     writeln!(w, "// WARNING: This is highly experimental output it's intended for stable-mir developers only.").unwrap();
     writeln!(w, "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir.").unwrap();
+
     run(tcx, || {
         let items = stable_mir::all_local_items();
-        items.iter().for_each(|item| {
+        let _ = items.iter().map(|item| -> io::Result<()> {
             // Because we can't return a Result from a closure, we have to unwrap here.
-            writeln!(w, "{}", function_name(*item, tcx)).unwrap();
-            writeln!(w, "{}", function_body(*item, tcx)).unwrap();
-            item.body().blocks.iter().enumerate().for_each(|(index, block)| {
-                writeln!(w, "    bb{}: {{", index).unwrap();
-                block.statements.iter().for_each(|statement| {
-                    writeln!(w, "{}", pretty_statement(&statement.kind, tcx)).unwrap();
-                });
+            writeln!(w, "{}", function_name(*item, tcx))?;
+            writeln!(w, "{}", function_body(*item, tcx))?;
+            let _ = item.body().blocks.iter().enumerate().map(|(index, block)| -> io::Result<()> {
+                writeln!(w, "    bb{}: {{", index)?;
+                let _ = block.statements.iter().map(|statement| -> io::Result<()> {
+                    writeln!(w, "{}", pretty_statement(&statement.kind, tcx))?;
+                    Ok(())
+                }).collect::<Vec<_>>();
                 writeln!(w, "    }}").unwrap();
-            })
-        })
+                Ok(())
+            }).collect::<Vec<_>>();
+            Ok(())
+        }).collect::<Vec<_>>();
+        
     });
     Ok(())
 }

From 3883645a9b228cf5b91f8766692ff57455ad6123 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Tue, 14 Nov 2023 16:21:55 +0300
Subject: [PATCH 18/21] change smir to StableMir

---
 compiler/rustc_driver_impl/src/pretty.rs      |  2 +-
 compiler/rustc_session/src/config.rs          | 14 +++----
 .../rustc_smir/src/rustc_internal/pretty.rs   | 42 ++++++++++++-------
 3 files changed, 35 insertions(+), 23 deletions(-)

diff --git a/compiler/rustc_driver_impl/src/pretty.rs b/compiler/rustc_driver_impl/src/pretty.rs
index 84f8941ff662d..7cd63bc6422c3 100644
--- a/compiler/rustc_driver_impl/src/pretty.rs
+++ b/compiler/rustc_driver_impl/src/pretty.rs
@@ -326,7 +326,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
             write_mir_graphviz(ex.tcx(), None, &mut out).unwrap();
             String::from_utf8(out).unwrap()
         }
-        Smir => {
+        StableMir => {
             let mut out = Vec::new();
             write_smir_pretty(ex.tcx(), &mut out).unwrap();
             String::from_utf8(out).unwrap()
diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs
index 54335645e43e2..d4f9122e7e384 100644
--- a/compiler/rustc_session/src/config.rs
+++ b/compiler/rustc_session/src/config.rs
@@ -2926,13 +2926,13 @@ fn parse_pretty(handler: &EarlyErrorHandler, unstable_opts: &UnstableOptions) ->
         "thir-tree" => ThirTree,
         "thir-flat" => ThirFlat,
         "mir" => Mir,
-        "smir" => Smir,
+        "stable-mir" => StableMir,
         "mir-cfg" => MirCFG,
         name => handler.early_error(format!(
             "argument to `unpretty` must be one of `normal`, `identified`, \
                             `expanded`, `expanded,identified`, `expanded,hygiene`, \
                             `ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \
-                            `hir,typed`, `hir-tree`, `thir-tree`, `thir-flat`, `mir` or \
+                            `hir,typed`, `hir-tree`, `thir-tree`, `thir-flat`, `mir`, `stable-mir`, or \
                             `mir-cfg`; got {name}"
         )),
     };
@@ -3107,8 +3107,8 @@ pub enum PpMode {
     Mir,
     /// `-Zunpretty=mir-cfg`
     MirCFG,
-    /// `-Zunpretty=smir`
-    Smir,
+    /// `-Zunpretty=stable-mir`
+    StableMir,
 }
 
 impl PpMode {
@@ -3126,7 +3126,7 @@ impl PpMode {
             | ThirFlat
             | Mir
             | MirCFG
-            | Smir => true,
+            | StableMir => true,
         }
     }
     pub fn needs_hir(&self) -> bool {
@@ -3134,13 +3134,13 @@ impl PpMode {
         match *self {
             Source(_) | AstTree | AstTreeExpanded => false,
 
-            Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG | Smir => true,
+            Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG | StableMir => true,
         }
     }
 
     pub fn needs_analysis(&self) -> bool {
         use PpMode::*;
-        matches!(*self, Hir(PpHirMode::Typed) | Mir | Smir | MirCFG | ThirTree | ThirFlat)
+        matches!(*self, Hir(PpHirMode::Typed) | Mir | StableMir | MirCFG | ThirTree | ThirFlat)
     }
 }
 
diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index 67995b1811046..1c2662fe85f20 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -15,22 +15,34 @@ pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::
 
     run(tcx, || {
         let items = stable_mir::all_local_items();
-        let _ = items.iter().map(|item| -> io::Result<()> {
-            // Because we can't return a Result from a closure, we have to unwrap here.
-            writeln!(w, "{}", function_name(*item, tcx))?;
-            writeln!(w, "{}", function_body(*item, tcx))?;
-            let _ = item.body().blocks.iter().enumerate().map(|(index, block)| -> io::Result<()> {
-                writeln!(w, "    bb{}: {{", index)?;
-                let _ = block.statements.iter().map(|statement| -> io::Result<()> {
-                    writeln!(w, "{}", pretty_statement(&statement.kind, tcx))?;
-                    Ok(())
-                }).collect::<Vec<_>>();
-                writeln!(w, "    }}").unwrap();
+        let _ = items
+            .iter()
+            .map(|item| -> io::Result<()> {
+                // Because we can't return a Result from a closure, we have to unwrap here.
+                writeln!(w, "{}", function_name(*item, tcx))?;
+                writeln!(w, "{}", function_body(*item, tcx))?;
+                let _ = item
+                    .body()
+                    .blocks
+                    .iter()
+                    .enumerate()
+                    .map(|(index, block)| -> io::Result<()> {
+                        writeln!(w, "    bb{}: {{", index)?;
+                        let _ = block
+                            .statements
+                            .iter()
+                            .map(|statement| -> io::Result<()> {
+                                writeln!(w, "{}", pretty_statement(&statement.kind, tcx))?;
+                                Ok(())
+                            })
+                            .collect::<Vec<_>>();
+                        writeln!(w, "    }}").unwrap();
+                        Ok(())
+                    })
+                    .collect::<Vec<_>>();
                 Ok(())
-            }).collect::<Vec<_>>();
-            Ok(())
-        }).collect::<Vec<_>>();
-        
+            })
+            .collect::<Vec<_>>();
     });
     Ok(())
 }

From 71c990470a958b14b78f9627d4aba2b1d6c79144 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Wed, 15 Nov 2023 10:12:17 +0300
Subject: [PATCH 19/21] move pretty into stable_mir

---
 .../rustc_smir/src/rustc_internal/pretty.rs   | 310 +-----------------
 compiler/rustc_smir/src/rustc_smir/mod.rs     |   5 +-
 compiler/stable_mir/src/lib.rs                |   9 +-
 compiler/stable_mir/src/mir.rs                |   1 +
 compiler/stable_mir/src/mir/body.rs           |  27 +-
 compiler/stable_mir/src/mir/pretty.rs         | 261 +++++++++++++++
 6 files changed, 308 insertions(+), 305 deletions(-)
 create mode 100644 compiler/stable_mir/src/mir/pretty.rs

diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index 1c2662fe85f20..19baf490a5d29 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -1,308 +1,20 @@
 use std::io;
 
+use super::run;
 use rustc_middle::ty::TyCtxt;
-use stable_mir::{
-    mir::{Mutability, Operand, Rvalue, StatementKind},
-    ty::{RigidTy, TyKind},
-    CrateItem,
-};
-
-use super::{internal, run};
-
-pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
-    writeln!(w, "// WARNING: This is highly experimental output it's intended for stable-mir developers only.").unwrap();
-    writeln!(w, "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir.").unwrap();
 
+pub fn write_smir_pretty<'tcx, W: io::Write>(tcx: TyCtxt<'tcx>, w: &mut W) -> io::Result<()> {
+    writeln!(
+        w,
+        "// WARNING: This is highly experimental output it's intended for stable-mir developers only."
+    )?;
+    writeln!(
+        w,
+        "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir."
+    )?;
     run(tcx, || {
         let items = stable_mir::all_local_items();
-        let _ = items
-            .iter()
-            .map(|item| -> io::Result<()> {
-                // Because we can't return a Result from a closure, we have to unwrap here.
-                writeln!(w, "{}", function_name(*item, tcx))?;
-                writeln!(w, "{}", function_body(*item, tcx))?;
-                let _ = item
-                    .body()
-                    .blocks
-                    .iter()
-                    .enumerate()
-                    .map(|(index, block)| -> io::Result<()> {
-                        writeln!(w, "    bb{}: {{", index)?;
-                        let _ = block
-                            .statements
-                            .iter()
-                            .map(|statement| -> io::Result<()> {
-                                writeln!(w, "{}", pretty_statement(&statement.kind, tcx))?;
-                                Ok(())
-                            })
-                            .collect::<Vec<_>>();
-                        writeln!(w, "    }}").unwrap();
-                        Ok(())
-                    })
-                    .collect::<Vec<_>>();
-                Ok(())
-            })
-            .collect::<Vec<_>>();
+        let _ = items.iter().map(|item| -> io::Result<()> { item.dump(w) }).collect::<Vec<_>>();
     });
     Ok(())
 }
-
-pub fn function_name(item: CrateItem, tcx: TyCtxt<'_>) -> String {
-    let mut name = String::new();
-    let body = item.body();
-    name.push_str("fn ");
-    name.push_str(item.name().as_str());
-    if body.arg_locals().is_empty() {
-        name.push_str("()");
-    } else {
-        name.push_str("(");
-    }
-    body.arg_locals().iter().for_each(|local| {
-        name.push_str(format!("_{}: ", local.local).as_str());
-        name.push_str(&pretty_ty(local.ty.kind(), tcx));
-    });
-    if !body.arg_locals().is_empty() {
-        name.push_str(")");
-    }
-    let return_local = body.ret_local();
-    name.push_str(" -> ");
-    name.push_str(&pretty_ty(return_local.ty.kind(), tcx));
-    name.push_str(" {");
-    name
-}
-
-pub fn function_body(item: CrateItem, _tcx: TyCtxt<'_>) -> String {
-    let mut body_str = String::new();
-    let body = item.body();
-    body.inner_locals().iter().for_each(|local| {
-        body_str.push_str("    ");
-        body_str.push_str(format!("let {}", ret_mutability(&local.mutability)).as_str());
-        body_str.push_str(format!("_{}: ", local.local).as_str());
-        body_str.push_str(format!("{}", pretty_ty(local.ty.kind(), _tcx)).as_str());
-        body_str.push_str(";\n");
-    });
-    body_str.push_str("}");
-    body_str
-}
-
-pub fn ret_mutability(mutability: &Mutability) -> String {
-    match mutability {
-        Mutability::Not => "".to_string(),
-        Mutability::Mut => "mut ".to_string(),
-    }
-}
-
-pub fn pretty_statement(statement: &StatementKind, tcx: TyCtxt<'_>) -> String {
-    let mut pretty = String::new();
-    match statement {
-        StatementKind::Assign(place, rval) => {
-            pretty.push_str(format!("        _{} = ", place.local).as_str());
-            pretty.push_str(format!("{}", &pretty_rvalue(rval, tcx)).as_str());
-        }
-        StatementKind::FakeRead(_, _) => todo!(),
-        StatementKind::SetDiscriminant { .. } => todo!(),
-        StatementKind::Deinit(_) => todo!(),
-        StatementKind::StorageLive(_) => todo!(),
-        StatementKind::StorageDead(_) => todo!(),
-        StatementKind::Retag(_, _) => todo!(),
-        StatementKind::PlaceMention(_) => todo!(),
-        StatementKind::AscribeUserType { .. } => todo!(),
-        StatementKind::Coverage(_) => todo!(),
-        StatementKind::Intrinsic(_) => todo!(),
-        StatementKind::ConstEvalCounter => (),
-        StatementKind::Nop => (),
-    }
-    pretty
-}
-
-pub fn pretty_operand(operand: &Operand, _tcx: TyCtxt<'_>) -> String {
-    let mut pretty = String::new();
-    match operand {
-        Operand::Copy(copy) => {
-            pretty.push_str("");
-            pretty.push_str(format!("{}", copy.local).as_str());
-        }
-        Operand::Move(mv) => {
-            pretty.push_str("move ");
-            pretty.push_str(format!("_{}", mv.local).as_str());
-        }
-        Operand::Constant(cnst) => {
-            pretty.push_str("const ");
-            pretty.push_str(internal(&cnst.literal).to_string().as_str());
-        }
-    }
-    pretty
-}
-
-pub fn pretty_rvalue(rval: &Rvalue, tcx: TyCtxt<'_>) -> String {
-    let mut pretty = String::new();
-    match rval {
-        Rvalue::AddressOf(muta, addr) => {
-            pretty.push_str("&raw ");
-            pretty.push_str(&ret_mutability(&muta));
-            pretty.push_str(format!("(*_{})", addr.local).as_str());
-        }
-        Rvalue::Aggregate(aggregatekind, operands) => {
-            pretty.push_str(format!("{:#?}", aggregatekind).as_str());
-            pretty.push_str("(");
-            operands.iter().enumerate().for_each(|(i, op)| {
-                pretty.push_str(&pretty_operand(op, tcx));
-                if i != operands.len() - 1 {
-                    pretty.push_str(", ");
-                }
-            });
-            pretty.push_str(")");
-        }
-        Rvalue::BinaryOp(bin, op, op2) => {
-            pretty.push_str(&pretty_operand(op, tcx));
-            pretty.push_str(" ");
-            pretty.push_str(format!("{:#?}", bin).as_str());
-            pretty.push_str(" ");
-            pretty.push_str(&pretty_operand(op2, tcx));
-        }
-        Rvalue::Cast(_, op, ty) => {
-            pretty.push_str(&pretty_operand(op, tcx));
-            pretty.push_str(" as ");
-            pretty.push_str(&pretty_ty(ty.kind(), tcx));
-        }
-        Rvalue::CheckedBinaryOp(bin, op1, op2) => {
-            pretty.push_str(&pretty_operand(op1, tcx));
-            pretty.push_str(" ");
-            pretty.push_str(format!("{:#?}", bin).as_str());
-            pretty.push_str(" ");
-            pretty.push_str(&pretty_operand(op2, tcx));
-        }
-        Rvalue::CopyForDeref(deref) => {
-            pretty.push_str("CopyForDeref");
-            pretty.push_str(format!("{}", deref.local).as_str());
-        }
-        Rvalue::Discriminant(place) => {
-            pretty.push_str("discriminant");
-            pretty.push_str(format!("{}", place.local).as_str());
-        }
-        Rvalue::Len(len) => {
-            pretty.push_str("len");
-            pretty.push_str(format!("{}", len.local).as_str());
-        }
-        Rvalue::Ref(_, borrowkind, place) => {
-            pretty.push_str("ref");
-            pretty.push_str(format!("{:#?}", borrowkind).as_str());
-            pretty.push_str(format!("{}", place.local).as_str());
-        }
-        Rvalue::Repeat(op, cnst) => {
-            pretty.push_str(&pretty_operand(op, tcx));
-            pretty.push_str(" ");
-            pretty.push_str(&pretty_ty(cnst.ty().kind(), tcx));
-        }
-        Rvalue::ShallowInitBox(_, _) => todo!(),
-        Rvalue::ThreadLocalRef(item) => {
-            pretty.push_str("thread_local_ref");
-            pretty.push_str(format!("{:#?}", item).as_str());
-        }
-        Rvalue::NullaryOp(nul, ty) => {
-            pretty.push_str(format!("{:#?}", nul).as_str());
-            pretty.push_str(&&pretty_ty(ty.kind(), tcx));
-            pretty.push_str(" ");
-        }
-        Rvalue::UnaryOp(un, op) => {
-            pretty.push_str(&pretty_operand(op, tcx));
-            pretty.push_str(" ");
-            pretty.push_str(format!("{:#?}", un).as_str());
-        }
-        Rvalue::Use(op) => pretty.push_str(&pretty_operand(op, tcx)),
-    }
-    pretty
-}
-
-pub fn pretty_ty(ty: TyKind, tcx: TyCtxt<'_>) -> String {
-    let mut pretty = String::new();
-    pretty.push_str("");
-    match ty {
-        TyKind::RigidTy(rigid_ty) => match rigid_ty {
-            RigidTy::Bool => "bool".to_string(),
-            RigidTy::Char => "char".to_string(),
-            RigidTy::Int(i) => match i {
-                stable_mir::ty::IntTy::Isize => "isize".to_string(),
-                stable_mir::ty::IntTy::I8 => "i8".to_string(),
-                stable_mir::ty::IntTy::I16 => "i16".to_string(),
-                stable_mir::ty::IntTy::I32 => "i32".to_string(),
-                stable_mir::ty::IntTy::I64 => "i64".to_string(),
-                stable_mir::ty::IntTy::I128 => "i128".to_string(),
-            },
-            RigidTy::Uint(u) => match u {
-                stable_mir::ty::UintTy::Usize => "usize".to_string(),
-                stable_mir::ty::UintTy::U8 => "u8".to_string(),
-                stable_mir::ty::UintTy::U16 => "u16".to_string(),
-                stable_mir::ty::UintTy::U32 => "u32".to_string(),
-                stable_mir::ty::UintTy::U64 => "u64".to_string(),
-                stable_mir::ty::UintTy::U128 => "u128".to_string(),
-            },
-            RigidTy::Float(f) => match f {
-                stable_mir::ty::FloatTy::F32 => "f32".to_string(),
-                stable_mir::ty::FloatTy::F64 => "f64".to_string(),
-            },
-            RigidTy::Adt(def, _) => {
-                format!("{}", tcx.type_of(internal(&def.0)).instantiate_identity())
-            }
-            RigidTy::Foreign(_) => format!("{:#?}", rigid_ty),
-            RigidTy::Str => "str".to_string(),
-            RigidTy::Array(ty, len) => {
-                format!(
-                    "[{}; {}]",
-                    pretty_ty(ty.kind(), tcx),
-                    internal(&len).try_to_scalar().unwrap()
-                )
-            }
-            RigidTy::Slice(ty) => {
-                format!("[{}]", pretty_ty(ty.kind(), tcx))
-            }
-            RigidTy::RawPtr(ty, mutability) => {
-                pretty.push_str("*");
-                match mutability {
-                    Mutability::Not => pretty.push_str("const "),
-                    Mutability::Mut => pretty.push_str("mut "),
-                }
-                pretty.push_str(&pretty_ty(ty.kind(), tcx));
-                pretty
-            }
-            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(), tcx),
-            RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
-            RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
-            RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
-            RigidTy::Coroutine(_, _, _) => format!("{:#?}", rigid_ty),
-            RigidTy::Dynamic(data, region, repr) => {
-                // FIXME: Fix binder printing, it looks ugly now
-                pretty.push_str("(");
-                match repr {
-                    stable_mir::ty::DynKind::Dyn => pretty.push_str("dyn "),
-                    stable_mir::ty::DynKind::DynStar => pretty.push_str("dyn* "),
-                }
-                pretty.push_str(format!("{:#?}", data).as_str());
-                pretty.push_str(format!(" +  {:#?} )", region).as_str());
-                pretty
-            }
-            RigidTy::Never => "!".to_string(),
-            RigidTy::Tuple(tuple) => {
-                if tuple.is_empty() {
-                    "()".to_string()
-                } else {
-                    let mut tuple_str = String::new();
-                    tuple_str.push_str("(");
-                    tuple.iter().enumerate().for_each(|(i, ty)| {
-                        tuple_str.push_str(&pretty_ty(ty.kind(), tcx));
-                        if i != tuple.len() - 1 {
-                            tuple_str.push_str(", ");
-                        }
-                    });
-                    tuple_str.push_str(")");
-                    tuple_str
-                }
-            }
-        },
-        TyKind::Alias(_, _) => format!("{:#?}", ty),
-        TyKind::Param(param_ty) => {
-            format!("{:#?}", param_ty.name)
-        }
-        TyKind::Bound(_, _) => format!("{:#?}", ty),
-    }
-}
diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs
index 69b0c0bb80d55..69e556ff3ec5a 100644
--- a/compiler/rustc_smir/src/rustc_smir/mod.rs
+++ b/compiler/rustc_smir/src/rustc_smir/mod.rs
@@ -400,11 +400,10 @@ impl<'tcx> Stable<'tcx> for mir::Body<'tcx> {
                 })
                 .collect(),
             self.local_decls
-                .iter_enumerated()
-                .map(|(local, decl)| stable_mir::mir::LocalDecl {
+                .iter()
+                .map(|decl| stable_mir::mir::LocalDecl {
                     ty: decl.ty.stable(tables),
                     span: decl.source_info.span.stable(tables),
-                    local: local.as_usize(),
                     mutability: decl.mutability.stable(tables),
                 })
                 .collect(),
diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs
index 0262fb536e785..dca43a2c090d7 100644
--- a/compiler/stable_mir/src/lib.rs
+++ b/compiler/stable_mir/src/lib.rs
@@ -19,9 +19,9 @@
 
 use crate::mir::mono::InstanceDef;
 use crate::mir::Body;
-use std::cell::Cell;
 use std::fmt;
 use std::fmt::Debug;
+use std::{cell::Cell, io};
 
 use self::ty::{
     GenericPredicates, Generics, ImplDef, ImplTrait, IndexedVal, LineInfo, Span, TraitDecl,
@@ -37,6 +37,8 @@ pub mod ty;
 pub mod visitor;
 
 use crate::ty::{AdtDef, AdtKind, ClosureDef, ClosureKind};
+use crate::mir::pretty::function_name;
+use crate::mir::Mutability;
 pub use error::*;
 use mir::mono::Instance;
 use ty::{FnDef, GenericArgs};
@@ -137,6 +139,11 @@ impl CrateItem {
     pub fn ty(&self) -> Ty {
         with(|cx| cx.def_ty(self.0))
     }
+    
+    pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
+        writeln!(w, "{}", function_name(*self))?;
+        self.body().dump(w)
+    }
 }
 
 /// Return the function where execution starts if the current
diff --git a/compiler/stable_mir/src/mir.rs b/compiler/stable_mir/src/mir.rs
index 2e1714b49c184..2cbe6eb4ad117 100644
--- a/compiler/stable_mir/src/mir.rs
+++ b/compiler/stable_mir/src/mir.rs
@@ -1,5 +1,6 @@
 mod body;
 pub mod mono;
+pub mod pretty;
 pub mod visit;
 
 pub use body::*;
diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs
index 2981d6a8bb5c6..b1ba8b97418e7 100644
--- a/compiler/stable_mir/src/mir/body.rs
+++ b/compiler/stable_mir/src/mir/body.rs
@@ -1,7 +1,8 @@
+use crate::mir::pretty::{function_body, pretty_statement};
 use crate::ty::{AdtDef, ClosureDef, Const, CoroutineDef, GenericArgs, Movability, Region, Ty};
 use crate::Opaque;
 use crate::Span;
-
+use std::io;
 /// The SMIR representation of a single function.
 #[derive(Clone, Debug)]
 pub struct Body {
@@ -56,6 +57,29 @@ impl Body {
     pub fn locals(&self) -> &[LocalDecl] {
         &self.locals
     }
+
+    pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
+        writeln!(w, "{}", function_body(self))?;
+        let _ = self
+            .blocks
+            .iter()
+            .enumerate()
+            .map(|(index, block)| -> io::Result<()> {
+                writeln!(w, "    bb{}: {{", index)?;
+                let _ = block
+                    .statements
+                    .iter()
+                    .map(|statement| -> io::Result<()> {
+                        writeln!(w, "{}", pretty_statement(&statement.kind))?;
+                        Ok(())
+                    })
+                    .collect::<Vec<_>>();
+                writeln!(w, "    }}").unwrap();
+                Ok(())
+            })
+            .collect::<Vec<_>>();
+        Ok(())
+    }
 }
 
 type LocalDecls = Vec<LocalDecl>;
@@ -64,7 +88,6 @@ type LocalDecls = Vec<LocalDecl>;
 pub struct LocalDecl {
     pub ty: Ty,
     pub span: Span,
-    pub local: Local,
     pub mutability: Mutability,
 }
 
diff --git a/compiler/stable_mir/src/mir/pretty.rs b/compiler/stable_mir/src/mir/pretty.rs
new file mode 100644
index 0000000000000..2bdcabb1bf522
--- /dev/null
+++ b/compiler/stable_mir/src/mir/pretty.rs
@@ -0,0 +1,261 @@
+use crate::mir::{Operand, Rvalue, StatementKind};
+use crate::ty::{DynKind, FloatTy, IntTy, RigidTy, TyKind, UintTy};
+use crate::{Body, CrateItem, Mutability};
+
+pub fn function_name(item: CrateItem) -> String {
+    let mut pretty_name = String::new();
+    let body = item.body();
+    pretty_name.push_str("fn ");
+    pretty_name.push_str(item.name().as_str());
+    if body.arg_locals().is_empty() {
+        pretty_name.push_str("()");
+    } else {
+        pretty_name.push_str("(");
+    }
+    body.arg_locals().iter().enumerate().for_each(|(index, local)| {
+        pretty_name.push_str(format!("_{}: ", index).as_str());
+        pretty_name.push_str(&pretty_ty(local.ty.kind()));
+    });
+    if !body.arg_locals().is_empty() {
+        pretty_name.push_str(")");
+    }
+    let return_local = body.ret_local();
+    pretty_name.push_str(" -> ");
+    pretty_name.push_str(&pretty_ty(return_local.ty.kind()));
+    pretty_name.push_str(" {");
+    pretty_name
+}
+
+pub fn function_body(body: &Body) -> String {
+    let mut pretty_body = String::new();
+    body.inner_locals().iter().enumerate().for_each(|(index, local)| {
+        pretty_body.push_str("    ");
+        pretty_body.push_str(format!("let {}", ret_mutability(&local.mutability)).as_str());
+        pretty_body.push_str(format!("_{}: ", index).as_str());
+        pretty_body.push_str(format!("{}", pretty_ty(local.ty.kind())).as_str());
+        pretty_body.push_str(";\n");
+    });
+    pretty_body.push_str("}");
+    pretty_body
+}
+
+pub fn ret_mutability(mutability: &Mutability) -> String {
+    match mutability {
+        Mutability::Not => "".to_string(),
+        Mutability::Mut => "mut ".to_string(),
+    }
+}
+
+pub fn pretty_statement(statement: &StatementKind) -> String {
+    let mut pretty = String::new();
+    match statement {
+        StatementKind::Assign(place, rval) => {
+            pretty.push_str(format!("        _{} = ", place.local).as_str());
+            pretty.push_str(format!("{}", &pretty_rvalue(rval)).as_str());
+        }
+        StatementKind::FakeRead(_, _) => todo!(),
+        StatementKind::SetDiscriminant { .. } => todo!(),
+        StatementKind::Deinit(_) => todo!(),
+        StatementKind::StorageLive(_) => todo!(),
+        StatementKind::StorageDead(_) => todo!(),
+        StatementKind::Retag(_, _) => todo!(),
+        StatementKind::PlaceMention(_) => todo!(),
+        StatementKind::AscribeUserType { .. } => todo!(),
+        StatementKind::Coverage(_) => todo!(),
+        StatementKind::Intrinsic(_) => todo!(),
+        StatementKind::ConstEvalCounter => (),
+        StatementKind::Nop => (),
+    }
+    pretty
+}
+
+pub fn pretty_operand(operand: &Operand) -> String {
+    let mut pretty = String::new();
+    match operand {
+        Operand::Copy(copy) => {
+            pretty.push_str("");
+            pretty.push_str(format!("{}", copy.local).as_str());
+        }
+        Operand::Move(mv) => {
+            pretty.push_str("move ");
+            pretty.push_str(format!("_{}", mv.local).as_str());
+        }
+        Operand::Constant(_) => {
+            // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
+            pretty.push_str("const ");
+            //pretty.push_str(internal(&cnst.literal).to_string().as_str());
+        }
+    }
+    pretty
+}
+
+pub fn pretty_rvalue(rval: &Rvalue) -> String {
+    let mut pretty = String::new();
+    match rval {
+        Rvalue::AddressOf(muta, addr) => {
+            pretty.push_str("&raw ");
+            pretty.push_str(&ret_mutability(&muta));
+            pretty.push_str(format!("(*_{})", addr.local).as_str());
+        }
+        Rvalue::Aggregate(aggregatekind, operands) => {
+            pretty.push_str(format!("{:#?}", aggregatekind).as_str());
+            pretty.push_str("(");
+            operands.iter().enumerate().for_each(|(i, op)| {
+                pretty.push_str(&pretty_operand(op));
+                if i != operands.len() - 1 {
+                    pretty.push_str(", ");
+                }
+            });
+            pretty.push_str(")");
+        }
+        Rvalue::BinaryOp(bin, op, op2) => {
+            pretty.push_str(&pretty_operand(op));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", bin).as_str());
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_operand(op2));
+        }
+        Rvalue::Cast(_, op, ty) => {
+            pretty.push_str(&pretty_operand(op));
+            pretty.push_str(" as ");
+            pretty.push_str(&pretty_ty(ty.kind()));
+        }
+        Rvalue::CheckedBinaryOp(bin, op1, op2) => {
+            pretty.push_str(&pretty_operand(op1));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", bin).as_str());
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_operand(op2));
+        }
+        Rvalue::CopyForDeref(deref) => {
+            pretty.push_str("CopyForDeref");
+            pretty.push_str(format!("{}", deref.local).as_str());
+        }
+        Rvalue::Discriminant(place) => {
+            pretty.push_str("discriminant");
+            pretty.push_str(format!("{}", place.local).as_str());
+        }
+        Rvalue::Len(len) => {
+            pretty.push_str("len");
+            pretty.push_str(format!("{}", len.local).as_str());
+        }
+        Rvalue::Ref(_, borrowkind, place) => {
+            pretty.push_str("ref");
+            pretty.push_str(format!("{:#?}", borrowkind).as_str());
+            pretty.push_str(format!("{}", place.local).as_str());
+        }
+        Rvalue::Repeat(op, cnst) => {
+            pretty.push_str(&pretty_operand(op));
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_ty(cnst.ty().kind()));
+        }
+        Rvalue::ShallowInitBox(_, _) => todo!(),
+        Rvalue::ThreadLocalRef(item) => {
+            pretty.push_str("thread_local_ref");
+            pretty.push_str(format!("{:#?}", item).as_str());
+        }
+        Rvalue::NullaryOp(nul, ty) => {
+            pretty.push_str(format!("{:#?}", nul).as_str());
+            pretty.push_str(&&pretty_ty(ty.kind()));
+            pretty.push_str(" ");
+        }
+        Rvalue::UnaryOp(un, op) => {
+            pretty.push_str(&pretty_operand(op));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", un).as_str());
+        }
+        Rvalue::Use(op) => pretty.push_str(&pretty_operand(op)),
+    }
+    pretty
+}
+
+pub fn pretty_ty(ty: TyKind) -> String {
+    let mut pretty = String::new();
+    pretty.push_str("");
+    match ty {
+        TyKind::RigidTy(rigid_ty) => match rigid_ty {
+            RigidTy::Bool => "bool".to_string(),
+            RigidTy::Char => "char".to_string(),
+            RigidTy::Int(i) => match i {
+                IntTy::Isize => "isize".to_string(),
+                IntTy::I8 => "i8".to_string(),
+                IntTy::I16 => "i16".to_string(),
+                IntTy::I32 => "i32".to_string(),
+                IntTy::I64 => "i64".to_string(),
+                IntTy::I128 => "i128".to_string(),
+            },
+            RigidTy::Uint(u) => match u {
+                UintTy::Usize => "usize".to_string(),
+                UintTy::U8 => "u8".to_string(),
+                UintTy::U16 => "u16".to_string(),
+                UintTy::U32 => "u32".to_string(),
+                UintTy::U64 => "u64".to_string(),
+                UintTy::U128 => "u128".to_string(),
+            },
+            RigidTy::Float(f) => match f {
+                FloatTy::F32 => "f32".to_string(),
+                FloatTy::F64 => "f64".to_string(),
+            },
+            RigidTy::Adt(_, _) => {
+                // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
+                format!("{rigid_ty:#?}")
+            }
+            RigidTy::Str => "str".to_string(),
+            RigidTy::Array(ty, len) => {
+                // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
+                format!("[{}; {:#?}]", pretty_ty(ty.kind()), len)
+            }
+            RigidTy::Slice(ty) => {
+                format!("[{}]", pretty_ty(ty.kind()))
+            }
+            RigidTy::RawPtr(ty, mutability) => {
+                pretty.push_str("*");
+                match mutability {
+                    Mutability::Not => pretty.push_str("const "),
+                    Mutability::Mut => pretty.push_str("mut "),
+                }
+                pretty.push_str(&pretty_ty(ty.kind()));
+                pretty
+            }
+            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind()),
+            RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
+            RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Coroutine(_, _, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Dynamic(data, region, repr) => {
+                // FIXME: Fix binder printing, it looks ugly now
+                pretty.push_str("(");
+                match repr {
+                    DynKind::Dyn => pretty.push_str("dyn "),
+                    DynKind::DynStar => pretty.push_str("dyn* "),
+                }
+                pretty.push_str(format!("{:#?}", data).as_str());
+                pretty.push_str(format!(" +  {:#?} )", region).as_str());
+                pretty
+            }
+            RigidTy::Never => "!".to_string(),
+            RigidTy::Tuple(tuple) => {
+                if tuple.is_empty() {
+                    "()".to_string()
+                } else {
+                    let mut tuple_str = String::new();
+                    tuple_str.push_str("(");
+                    tuple.iter().enumerate().for_each(|(i, ty)| {
+                        tuple_str.push_str(&pretty_ty(ty.kind()));
+                        if i != tuple.len() - 1 {
+                            tuple_str.push_str(", ");
+                        }
+                    });
+                    tuple_str.push_str(")");
+                    tuple_str
+                }
+            }
+            _ => format!("{:#?}", rigid_ty),
+        },
+        TyKind::Alias(_, _) => format!("{:#?}", ty),
+        TyKind::Param(param_ty) => {
+            format!("{:#?}", param_ty.name)
+        }
+        TyKind::Bound(_, _) => format!("{:#?}", ty),
+    }
+}

From 3b0e1d23b7fff6b57a634f529ee19d0d173a95f7 Mon Sep 17 00:00:00 2001
From: lcnr <rust@lcnr.de>
Date: Fri, 17 Nov 2023 11:03:40 +0000
Subject: [PATCH 20/21] only free lifetimes may get erased

---
 library/core/src/mem/mod.rs | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs
index b810318fe7d3d..bf10ada0176c2 100644
--- a/library/core/src/mem/mod.rs
+++ b/library/core/src/mem/mod.rs
@@ -1132,10 +1132,12 @@ impl<T> fmt::Debug for Discriminant<T> {
 ///
 /// [Reference]: ../../reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations
 ///
-/// The value of a [`Discriminant<T>`] is independent of any *lifetimes* in `T`. As such, reading
-/// or writing a `Discriminant<Foo<'a>>` as a `Discriminant<Foo<'b>>` (whether via [`transmute`] or
-/// otherwise) is always sound. Note that this is **not** true for other kinds of generic
-/// parameters; `Discriminant<Foo<A>>` and `Discriminant<Foo<B>>` might be incompatible.
+/// The value of a [`Discriminant<T>`] is independent of any *free lifetimes* in `T`. As such,
+/// reading or writing a `Discriminant<Foo<'a>>` as a `Discriminant<Foo<'b>>` (whether via
+/// [`transmute`] or otherwise) is always sound. Note that this is **not** true for other kinds
+/// of generic parameters and for higher-ranked lifetimes; `Discriminant<Foo<A>>` and
+/// `Discriminant<Foo<B>>` as well as `Discriminant<Bar<dyn for<'a> Trait<'a>>>` and
+/// `Discriminant<Bar<dyn Trait<'static>>>` may be incompatible.
 ///
 /// # Examples
 ///

From 92657f163ac3c30af2652c8c7ba5ee7edb14ba01 Mon Sep 17 00:00:00 2001
From: ouz-a <ouz.agz@gmail.com>
Date: Fri, 17 Nov 2023 14:03:54 +0300
Subject: [PATCH 21/21] use new apis and add new function

---
 compiler/rustc_smir/src/rustc_internal/pretty.rs |  2 +-
 compiler/rustc_smir/src/rustc_smir/mod.rs        |  6 +++++-
 compiler/stable_mir/src/lib.rs                   |  9 ++++++---
 compiler/stable_mir/src/mir/body.rs              |  5 ++---
 compiler/stable_mir/src/mir/pretty.rs            | 15 ++++++---------
 5 files changed, 20 insertions(+), 17 deletions(-)

diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index 19baf490a5d29..3ef2d28ea4734 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -12,7 +12,7 @@ pub fn write_smir_pretty<'tcx, W: io::Write>(tcx: TyCtxt<'tcx>, w: &mut W) -> io
         w,
         "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir."
     )?;
-    run(tcx, || {
+    let _ = run(tcx, || {
         let items = stable_mir::all_local_items();
         let _ = items.iter().map(|item| -> io::Result<()> { item.dump(w) }).collect::<Vec<_>>();
     });
diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs
index 69e556ff3ec5a..89dbf40c7b4d0 100644
--- a/compiler/rustc_smir/src/rustc_smir/mod.rs
+++ b/compiler/rustc_smir/src/rustc_smir/mod.rs
@@ -7,7 +7,7 @@
 //!
 //! For now, we are developing everything inside `rustc`, thus, we keep this module private.
 
-use crate::rustc_internal::{IndexMap, RustcInternal};
+use crate::rustc_internal::{internal, IndexMap, RustcInternal};
 use crate::rustc_smir::stable_mir::ty::{BoundRegion, Region};
 use rustc_hir as hir;
 use rustc_hir::def::DefKind;
@@ -105,6 +105,10 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
         tables.tcx.type_of(item.internal(&mut *tables)).instantiate_identity().stable(&mut *tables)
     }
 
+    fn const_literal(&self, cnst: &stable_mir::ty::Const) -> String {
+        internal(cnst).to_string()
+    }
+
     fn span_of_an_item(&self, def_id: stable_mir::DefId) -> Span {
         let mut tables = self.0.borrow_mut();
         tables.tcx.def_span(tables[def_id]).stable(&mut *tables)
diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs
index dca43a2c090d7..79102dcce3585 100644
--- a/compiler/stable_mir/src/lib.rs
+++ b/compiler/stable_mir/src/lib.rs
@@ -36,12 +36,12 @@ pub mod mir;
 pub mod ty;
 pub mod visitor;
 
-use crate::ty::{AdtDef, AdtKind, ClosureDef, ClosureKind};
 use crate::mir::pretty::function_name;
 use crate::mir::Mutability;
+use crate::ty::{AdtDef, AdtKind, ClosureDef, ClosureKind};
 pub use error::*;
 use mir::mono::Instance;
-use ty::{FnDef, GenericArgs};
+use ty::{Const, FnDef, GenericArgs};
 
 /// Use String for now but we should replace it.
 pub type Symbol = String;
@@ -139,7 +139,7 @@ impl CrateItem {
     pub fn ty(&self) -> Ty {
         with(|cx| cx.def_ty(self.0))
     }
-    
+
     pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
         writeln!(w, "{}", function_name(*self))?;
         self.body().dump(w)
@@ -230,6 +230,9 @@ pub trait Context {
     /// Returns the type of given crate item.
     fn def_ty(&self, item: DefId) -> Ty;
 
+    /// Returns literal value of a const as a string.
+    fn const_literal(&self, cnst: &Const) -> String;
+
     /// `Span` of an item
     fn span_of_an_item(&self, def_id: DefId) -> Span;
 
diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs
index b1ba8b97418e7..fa58a7ffe1554 100644
--- a/compiler/stable_mir/src/mir/body.rs
+++ b/compiler/stable_mir/src/mir/body.rs
@@ -60,8 +60,7 @@ impl Body {
 
     pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
         writeln!(w, "{}", function_body(self))?;
-        let _ = self
-            .blocks
+        self.blocks
             .iter()
             .enumerate()
             .map(|(index, block)| -> io::Result<()> {
@@ -77,7 +76,7 @@ impl Body {
                 writeln!(w, "    }}").unwrap();
                 Ok(())
             })
-            .collect::<Vec<_>>();
+            .collect::<Result<Vec<_>, _>>()?;
         Ok(())
     }
 }
diff --git a/compiler/stable_mir/src/mir/pretty.rs b/compiler/stable_mir/src/mir/pretty.rs
index 2bdcabb1bf522..e52c3360ce425 100644
--- a/compiler/stable_mir/src/mir/pretty.rs
+++ b/compiler/stable_mir/src/mir/pretty.rs
@@ -1,6 +1,6 @@
 use crate::mir::{Operand, Rvalue, StatementKind};
 use crate::ty::{DynKind, FloatTy, IntTy, RigidTy, TyKind, UintTy};
-use crate::{Body, CrateItem, Mutability};
+use crate::{with, Body, CrateItem, Mutability};
 
 pub fn function_name(item: CrateItem) -> String {
     let mut pretty_name = String::new();
@@ -80,10 +80,9 @@ pub fn pretty_operand(operand: &Operand) -> String {
             pretty.push_str("move ");
             pretty.push_str(format!("_{}", mv.local).as_str());
         }
-        Operand::Constant(_) => {
-            // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
+        Operand::Constant(cnst) => {
             pretty.push_str("const ");
-            //pretty.push_str(internal(&cnst.literal).to_string().as_str());
+            pretty.push_str(with(|cx| cx.const_literal(&cnst.literal)).as_str());
         }
     }
     pretty
@@ -196,14 +195,12 @@ pub fn pretty_ty(ty: TyKind) -> String {
                 FloatTy::F32 => "f32".to_string(),
                 FloatTy::F64 => "f64".to_string(),
             },
-            RigidTy::Adt(_, _) => {
-                // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
-                format!("{rigid_ty:#?}")
+            RigidTy::Adt(def, _) => {
+                format!("{:#?}", with(|cx| cx.def_ty(def.0)))
             }
             RigidTy::Str => "str".to_string(),
             RigidTy::Array(ty, len) => {
-                // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
-                format!("[{}; {:#?}]", pretty_ty(ty.kind()), len)
+                format!("[{}; {}]", pretty_ty(ty.kind()), with(|cx| cx.const_literal(&len)))
             }
             RigidTy::Slice(ty) => {
                 format!("[{}]", pretty_ty(ty.kind()))